如何讓數據生成器更有效率?
為了訓練神經網絡,我修改了在 YouTube 上找到的一段代碼。它看起來如下:def data_generator(samples, batch_size, shuffle_data = True, resize=224): num_samples = len(samples) while True: random.shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samples = samples[offset: offset + batch_size] X_train = [] y_train = [] for batch_sample in batch_samples: img_name = batch_sample[0] label = batch_sample[1] img = cv2.imread(os.path.join(root_dir, img_name)) #img, label = preprocessing(img, label, new_height=224, new_width=224, num_classes=37) img = preprocessing(img, new_height=224, new_width=224) label = my_onehot_encoded(label) X_train.append(img) y_train.append(label) X_train = np.array(X_train) y_train = np.array(y_train) yield X_train, y_train現在,我嘗試使用此代碼訓練神經網絡,訓練樣本大小為 105.000(圖像文件包含 37 種可能性中的 8 個字符、AZ、0-9 和空格)。我使用了相對較小的批次大?。?2,我認為這已經太小了)來提高效率,但是訓練第一個時期的四分之一卻花了很長時間(我每個時期有 826 步,花了 90 分鐘199 步... steps_per_epoch = num_train_samples // batch_size)。數據生成器中包含以下功能:def shuffle_data(data): data=random.shuffle(data) return data我不認為我們可以使這個函數更有效或將它從生成器中排除。def preprocessing(img, new_height, new_width): img = cv2.resize(img,(new_height, new_width)) img = img/255 return img為了預處理/調整數據大小,我使用此代碼將圖像設置為唯一大小,例如 (224, 224, 3)。我認為,生成器的這一部分花費的時間最多,但我看不到將其從生成器中排除的可能性(因為如果我們在批次之外調整圖像的大小,我的內存將滿)。#One Hot Encoding of the Labelsfrom numpy import argmax# define input string我認為,在這一部分中,可能有一種方法可以提高效率。我正在考慮從生成器中排除此代碼并在生成器外部生成數組 y_train,這樣生成器就不必每次都對標簽進行熱編碼。你怎么看?還是我應該采用完全不同的方法?
查看完整描述