第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

基于內(nèi)部值的 Numpy 數(shù)組操作

基于內(nèi)部值的 Numpy 數(shù)組操作

胡說(shuō)叔叔 2021-11-30 19:22:43
我正在嘗試完成一項(xiàng)奇怪的任務(wù)。我需要在不使用 sklearn 的情況下完成以下操作,最好使用 numpy:給定一個(gè)數(shù)據(jù)集,將數(shù)據(jù)分成 5 個(gè)相等的“折疊”或分區(qū)在每個(gè)分區(qū)內(nèi),將數(shù)據(jù)拆分為“訓(xùn)練”和“測(cè)試”集,拆分比例為 80/20這里有一個(gè)問(wèn)題:你的數(shù)據(jù)集被標(biāo)記為類(lèi)。以一個(gè)有 100 個(gè)實(shí)例的數(shù)據(jù)集為例,A 類(lèi)有 33 個(gè)樣本,B 類(lèi)有 67 個(gè)樣本。我應(yīng)該創(chuàng)建 5 個(gè) 20 個(gè)數(shù)據(jù)實(shí)例的折疊,其中在每個(gè)折疊中,A 類(lèi)有 6 或 7 (1/3) 個(gè)值,B 類(lèi)有其余的我的問(wèn)題是: 我不知道如何為每個(gè)折疊正確返回測(cè)試和訓(xùn)練集,盡管能夠適當(dāng)?shù)胤指钏?,而且,更重要的是,我不知道如何合并每個(gè)類(lèi)的元素?cái)?shù)量的正確劃分.我當(dāng)前的代碼在這里。有人評(píng)論我被卡住的地方:import numpydef csv_to_array(file):    # Open the file, and load it in delimiting on the ',' for a comma separated value file    data = open(file, 'r')    data = numpy.loadtxt(data, delimiter=',')    # Loop through the data in the array    for index in range(len(data)):        # Utilize a try catch to try and convert to float, if it can't convert to float, converts to 0        try:            data[index] = [float(x) for x in data[index]]        except Exception:            data[index] = 0        except ValueError:            data[index] = 0    # Return the now type-formatted data    return datadef five_cross_fold_validation(dataset):    # print("DATASET", dataset)    numpy.random.shuffle(dataset)    num_rows = dataset.shape[0]    split_mark = int(num_rows / 5)    folds = []    temp1 = dataset[:split_mark]    # print("TEMP1", temp1)    temp2 = dataset[split_mark:split_mark*2]    # print("TEMP2", temp2)    temp3 = dataset[split_mark*2:split_mark*3]    # print("TEMP3", temp3)    temp4 = dataset[split_mark*3:split_mark*4]    # print("TEMP4", temp4)    temp5 = dataset[split_mark*4:]    # print("TEMP5", temp5)    folds.append(temp1)    folds.append(temp2)    folds.append(temp3)    folds.append(temp4)    folds.append(temp5)    # folds = numpy.asarray(folds)    for fold in folds:        # fold = numpy.asarray(fold)        num_rows = fold.shape[0]        split_mark = int(num_rows * .8)        fold_training = fold[split_mark:]        fold_testing = fold[:split_mark]
查看完整描述

1 回答

?
互換的青春

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊

編輯我替換np.random.shuffle(A)為A = np.random.permutation(A),唯一的區(qū)別是它不會(huì)改變輸入數(shù)組。這在這段代碼中沒(méi)有任何區(qū)別,但通常更安全。


這個(gè)想法是通過(guò)使用隨機(jī)采樣輸入numpy.random.permutation。一旦行被打亂,我們只需要遍歷所有可能的測(cè)試集(所需大小的滑動(dòng)窗口,這里是輸入大小的 20%)。相應(yīng)的訓(xùn)練集僅由所有剩余元素組成。


這將保留所有子集上的原始類(lèi)分布,即使我們因?yàn)槲覀兇騺y了輸入而按順序選擇了它們。


以下代碼迭代測(cè)試/訓(xùn)練集組合:


import numpy as np


def csv_to_array(file):

  with open(file, 'r') as f:

    data = np.loadtxt(f, delimiter=',')

  return data


def classes_distribution(A):

  """Print the class distributions of array A."""

  nb_classes = np.unique(A[:,-1]).shape[0]

  total_size = A.shape[0]

  for i in range(nb_classes):

    class_size = sum(row[-1] == i for row in A)

    class_p = class_size/total_size

    print(f"\t P(class_{i}) = {class_p:.3f}")


def random_samples(A, test_set_p=0.2):

  """Split the input array A in two uniformly chosen 

  random sets: test/training.

  Repeat this until all rows have been yielded once at least 

  once as a test set."""

  A = np.random.permutation(A)

  sample_size = int(test_set_p*A.shape[0])

  for start in range(0, A.shape[0], sample_size):

    end = start + sample_size

    yield {

      "test": A[start:end,], 

      "train": np.append(A[:start,], A[end:,], 0)

    }


def main():

  ecoli = csv_to_array('ecoli.csv')

  print("Input set shape: ", ecoli.shape)

  print("Input set class distribution:")

  classes_distribution(ecoli)

  print("Training sets class distributions:")

  for iteration in random_samples(ecoli):

    test_set = iteration["test"]

    training_set = iteration["train"]

    classes_distribution(training_set)

    print("---")

    # ... Do what ever with these two sets


main()

它產(chǎn)生以下形式的輸出:


Input set shape:  (169, 8)

Input set class distribution:

     P(class_0) = 0.308

     P(class_1) = 0.213

     P(class_2) = 0.207

     P(class_3) = 0.118

     P(class_4) = 0.154

Training sets class distributions:

     P(class_0) = 0.316

     P(class_1) = 0.206

     P(class_2) = 0.199

     P(class_3) = 0.118

     P(class_4) = 0.162

...


查看完整回答
反對(duì) 回復(fù) 2021-11-30
  • 1 回答
  • 0 關(guān)注
  • 173 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)