为了训练神经网络,我修改了在 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 和空格)。我使用了相对较小的批次大小(32,我认为这已经太小了)来提高效率,但是训练第一个时期的四分之一却花了很长时间(我每个时期有 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 Labels
from numpy import argmax
# define input string
我认为,在这一部分中,可能有一种方法可以提高效率。我正在考虑从生成器中排除此代码并在生成器外部生成数组 y_train,这样生成器就不必每次都对标签进行热编码。
你怎么看?还是我应该采用完全不同的方法?
LEATH
相关分类