【发布时间】:2021-07-25 10:05:53
【问题描述】:
我一直在研究用于图像分类的 CNN,但我一直遇到同样的错误,我的数据正在加载到数据帧中,我无法将其转换为张量以将其输入 CNN。如您所见,我使用此代码将图片加载到数据框中:
for i in range(len(merged)):
full_path = merged.iloc[i]['Image Path Rel']
filename = full_path[-22:-1] + 'G'
try:
img = img_to_array(load_img('D:/Serengeti_Data/Compressed/Compressed/' + filename, target_size=(32,32,3)))
except:
img = np.zeros((32,32,3), dtype=np.float32)
images = images.append({'Capture Id' : merged.iloc[i]['Capture Id'],'Image' : img}, ignore_index = True)
else:
images = images.append({'Capture Id' : merged.iloc[i]['Capture Id'],'Image' : img}, ignore_index = True)
然后,一旦我使用 load_img() 和 img_to_array() 加载了图像,我就进行了整形以获得所需的 (32,32,3) 形状。还通过将 Image 列除以 255 来标准化值。
然后我这样做是为了尝试将它变成张量:
train_tf = tf.data.Dataset.from_tensor_slices(images['Image'])
# Also tried this, but didn't got the same results:
# train_tf = tf.convert_to_tensor(train_df['Image'])
但不断收到错误:
ValueError: 无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)
我也尝试跳过它并尝试立即适应我们的模型,但得到了完全相同的错误:
trying_df = pd.DataFrame(images['Image'])
target_df = pd.DataFrame(targets)
animal_model = models.Sequential()
animal_model.add(layers.Conv2D(30, kernel_size = (3,3), padding = 'valid', activation = 'relu', input_shape =(32,32,3)))
animal_model.add(layers.MaxPooling2D(pool_size=(1,1)))
animal_model.add(layers.Conv2D(60,kernel_size=(1,1),activation = 'relu'))
animal_model.add(layers.Flatten())
animal_model.add(layers.Dense(100, activation = 'relu'))
animal_model.add(layers.Dense(10, activation = 'softmax'))
## compiler to model
animal_model.compile(loss = 'categorical_crossentropy', metrics = ['accuracy'], optimizer ='adam')
## training the model
animal_model.fit(trying_df,target_df, batch_size = 128, epochs = 15)
animal_model.summary()
TensorFlow 版本:2.4.1
Numpy 版本:1.19.5
熊猫版本:1.0.1
【问题讨论】:
-
阵列/图像很可能在形状上有所不同。
标签: python pandas numpy tensorflow keras