Python 如何使数据生成器更高效?
为了训练神经网络,我修改了在YouTube上找到的一段代码。情况如下:Python 如何使数据生成器更高效?,python,tensorflow,neural-network,resize,Python,Tensorflow,Neural Network,Resize,为了训练神经网络,我修改了在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_sam
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个字符,a-Z,0-9和空格)。
我使用了一个相对较小的批量大小(32,我认为这已经太小)来提高效率,但是训练第一个历元的四分之一却花费了很长时间(我每个历元有826个步骤,199个步骤花费了90分钟…steps\u per\u epoch=num\u train\u samples//batch\u 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
对于预处理/调整数据大小,我使用此代码将图像设置为唯一大小,例如(2242243)。我认为,生成器的这一部分花费的时间最多,但我不认为有可能将其从生成器中排除(因为如果我们在批处理之外调整图像的大小,我的内存将是满的)
我认为,在这一部分中,可以有一种方法来提高效率。我正在考虑从生成器中排除此代码,并在生成器外部生成数组y_序列,这样生成器就不必每次对标签进行一次热编码
你觉得怎么样?或者我应该采取完全不同的方法吗?我发现你的问题非常有趣,因为你只提供线索。这是我的调查 使用您的代码片段,我在YouTube上找到了一个包含3部分的视频教程,主要介绍如何在Python中使用生成器函数。 这些数据是基于(我建议检查这个问题的不同内核,以比较您已经尝试过的方法与另一个CNN网络,并查看正在使用的API) 您不需要从头开始编写数据生成器,尽管这并不困难,但发明轮子并没有什么生产力
- 凯拉斯有这门课
- 此外,这里还有一个更通用的示例
- Tensorflow提供了他们的
tf.data.Dataset
- 确保库使用GPU。这节省了很多时间。(尽管我在CPU上以非常快的速度从存储库中重复了flowers实验——大约10分钟,但结果预测并不比随机猜测好多少。因此,完整的训练需要大量CPU时间。)
- 比较不同版本以找到瓶颈。尝试一个包含48个图像(每个类1个)的数据集,增加每个类的图像数,然后进行比较。减小图像大小、更改模型结构等
- 在小型人工数据上测试全新模型,以证明想法或使用迭代过程,从可以转换为任务的项目开始(?)
#One Hot Encoding of the Labels
from numpy import argmax
# define input string
def my_onehot_encoded(label):
# define universe of possible input values
characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ '
# define a mapping of chars to integers
char_to_int = dict((c, i) for i, c in enumerate(characters))
int_to_char = dict((i, c) for i, c in enumerate(characters))
# integer encode input data
integer_encoded = [char_to_int[char] for char in label]
# one hot encode
onehot_encoded = list()
for value in integer_encoded:
character = [0 for _ in range(len(characters))]
character[value] = 1
onehot_encoded.append(character)
return onehot_encoded