Tob*_*tor 5 python resize neural-network tensorflow
为了训练神经网络,我修改了在 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
Run Code Online (Sandbox Code Playgroud)
现在,我尝试使用此代码训练神经网络,训练样本大小为 105.000(图像文件包含 37 种可能性中的 8 个字符、AZ、0-9 和空格)。我使用了一个相对较小的批量大小(32,我认为这已经太小了)来提高效率,但仍然花费了很长时间来训练第一个 epoch 的四分之一(我每个 epoch 有 826 步,花了 90 分钟199步...steps_per_epoch = num_train_samples // batch_size)。
数据生成器中包含以下功能:
def shuffle_data(data):
data=random.shuffle(data)
return data
Run Code Online (Sandbox Code Playgroud)
我不认为我们可以使这个函数更有效或从生成器中排除它。
def preprocessing(img, new_height, new_width):
img = cv2.resize(img,(new_height, new_width))
img = img/255
return img
Run Code Online (Sandbox Code Playgroud)
为了预处理/调整数据大小,我使用此代码将图像设置为唯一大小,例如 (224, 224, 3)。我认为,生成器的这一部分花费的时间最多,但我看不出有可能将它从生成器中排除(因为如果我们在批次外调整图像大小,我的内存会已满)。
#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
Run Code Online (Sandbox Code Playgroud)
我认为,在这部分中,可能有一种方法可以提高效率。我正在考虑从生成器中排除这段代码,并在生成器之外生成数组 y_train,这样生成器就不必每次都对标签进行热编码。
你怎么认为?或者我应该采取完全不同的方法?
我发现你的问题非常有趣,因为你只提供了线索。这是我的调查。
使用您的代码片段,我在 YouTube 上找到了GitHub 存储库和 3 部分视频教程,主要关注在 Python 中使用生成器函数的好处。数据基于此 kaggle(我建议检查该问题的不同内核,以将您已经尝试过的方法与其他 CNN 网络进行比较,并查看正在使用的 API)。
您不需要从头开始编写数据生成器,虽然这并不难,但发明轮子的效率并不高。
tf.data.Dataset.然而,为了解决 Kaggle 的任务,该模型只需要感知单个图像,因此该模型是一个简单的深度 CNN。但据我了解,您将 8 个随机字符(类别)组合到一张图像中以一次识别多个类别。对于该任务,您需要 R-CNN 或 YOLO 作为模型。我最近刚刚为自己打开了YOLO v4,并且可以让它非常快速地完成特定任务。
关于您的设计和代码的一般建议。
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |