+-

下面我想把笔记本中的图片存储到名为X_data的变量中,使用的函数是 glob 然后分成训练集和测试集,再测试模型。
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import glob
X_data = []
files = glob.glob ("*.png")
for myFile in files:
image = cv2.imread(myFile)
X_data.append(image)
print('X_data shape:', np.array(X_data).shape)
import numpy
numpy.random.shuffle(X_data)
training, test = X_data[:80,:], X_data[80:,:]
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
model.summary()
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(training, labels_train, epochs=10,
validation_data=(test, labels_test))
但我得到的是
ValueError: Failed to find data adapter that can handle input: <class 'numpy.ndarray'>, (<class 'list'> containing values of types {"<class 'int'>"})
有什么想法吗?
0
投票
投票
我在你的代码中看到几个问题。
两者train 和
test 是
Lists,不
Numpy Arrays 同样的情况可能发生在
Labels 该部分代码不共享)。
该部分代码。
X_data = [] files = glob.glob ("*.png") for myFile in files: image = cv2.imread(myFile) X_data.append(image)
返回一个 List of Strings而不是 Numpy Array 的Floats和代码。
training = training.astype(float) 和 test = test.astype(float) 不会解决这个问题。
['cat.373.jpg', 'cat.843.jpg', 'cat.970.jpg', 'cat.797.jpg', 'cat.786.jpg',
'cat.1.jpg', 'cat.172.jpg', 'cat.660.jpg'...........]
您是否有任何具体的原因想要使用该函数。glob.glob 访问 Images 因为有更好的方法来实现。
其中一个最有效和最优化的方法是使用 Keras ImageDataGenerator 和 ImageDataGenerator.flow_from_directory.
例如,如果你的 Image Data Directory 有文件夹,每个文件夹对应每个类,如下截图所示。
代码来展示如何使用 ImageDataGenerator,以及每行代码的详细解释在下面提到。
train_datagen = ImageDataGenerator(rescale=1./255, # Normalizes every pixel value
validation_split=0.2) # Setting Validation Data as 20% of Total Data
train_generator = train_datagen.flow_from_directory(
Image_data_dir, # Traverses through all the Sub Folders (Category) inside this dir
target_size=(img_height, img_width), # Sets the Image Size
batch_size=batch_size, # Generates batches of `batch_size`
class_mode='categorical', # Will Consider Labels as Categorical
shuffle = True, # Shuffles the Data
subset='training') # Considers 80% as training data
# Since we don't have separate directory for Validation Data and since we want the Total Data to be Partitioned, we should use "train_datagen"
validation_generator = train_datagen.flow_from_directory(
Image_data_dir, # Should use the Same Dir as Training for Splitting
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle = True, # Shuffles the Data
subset='validation') # Considers 20% as Validation data
# Then you can train the model using the code mentioned below
model.fit(
train_generator,
steps_per_epoch = train_generator.samples // batch_size,
validation_data = validation_generator,
validation_steps = validation_generator.samples // batch_size,
epochs = nb_epochs)
希望这能解决你的问题。如果你仍然面临任何错误,请分享完整的代码和错误跟踪。
祝你学习愉快