这是来自Coursera的一个问题。除了训练部分之外,所有输出都如预期。我尝试了不同的层,但结果都是一样的。可能是我的数据集处理上有些错误?
我找不到问题所在,有人能帮忙吗?谢谢
import csvimport numpy as npimport tensorflow as tffrom tensorflow.keras.preprocessing.image import ImageDataGeneratorfrom os import getcwddef get_data(filename): # You will need to write code that will read the file passed # into this function. The first line contains the column headers # so you should ignore it # Each successive line contians 785 comma separated values between 0 and 255 # The first value is the label # The rest are the pixel values for that picture # The function will return 2 np.array types. One with all the labels # One with all the images # # Tips: # If you read a full line (as 'row') then row[0] has the label # and row[1:785] has the 784 pixel values # Take a look at np.array_split to turn the 784 pixels into 28x28 # You are reading in strings, but need the values to be floats # Check out np.array().astype for a conversion with open(filename) as training_file: # Your code starts here reader = csv.reader(training_file) next(reader,None) images = [] labels = [] for i in reader: labels.append(i[0]) imageData = i[1:785] images.append(np.array_split(imageData,28)) # Your code ends here labels = np.array(labels).astype('float') images = np.array(images).astype('float') return images, labelspath_sign_mnist_train = f"{getcwd()}/../tmp2/sign_mnist_train.csv"path_sign_mnist_test = f"{getcwd()}/../tmp2/sign_mnist_test.csv"training_images, training_labels = get_data(path_sign_mnist_train)testing_images, testing_labels = get_data(path_sign_mnist_test)# Keep theseprint(training_images.shape)print(training_labels.shape)print(testing_images.shape)print(testing_labels.shape)# In this section you will have to add another dimension to the data# So, for example, if your array is (10000, 28, 28)# You will need to make it (10000, 28, 28, 1)training_images = np.expand_dims(training_images,axis=-1)# Your Code Heretesting_images = np.expand_dims(testing_images,axis=-1)# Your Code Here# Create an ImageDataGenerator and do Image Augmentationtrain_datagen = ImageDataGenerator(rescale = 1./255., rotation_range = 40, width_shift_range = 0.2, height_shift_range = 0.2, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, fill_mode = 'nearest' )validation_datagen = ImageDataGenerator(rescale = 1./255.) # Keep Theseprint(training_images.shape)print(testing_images.shape) # Their output should be:# (27455, 28, 28, 1)# (7172, 28, 28, 1)# Define the model# Use no more than 2 Conv2D and 2 MaxPooling2Dfrom tensorflow.keras.optimizers import RMSpropmodel = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(32, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(26, activation='softmax')])# Compile Model. model.compile(loss = 'sparse_categorical_crossentropy', optimizer = RMSprop(lr=0.01), metrics = ['accuracy'])# Train the Modeltrain_generator = train_datagen.flow(training_images,training_labels, batch_size = 10 ) validation_generator = validation_datagen.flow( testing_images, testing_labels, batch_size = 10 )history = model.fit_generator(train_generator, epochs=5, steps_per_epoch=len(training_images) / 32, validation_data=validation_generator )model.evaluate(testing_images, testing_labels,verbose=0)
模型的输出如下所示:
Epoch 1/5858/857 [==============================] - 78s 91ms/step - loss: 15.4250 - accuracy: 0.0422 - val_loss: 15.5210 - val_accuracy: 0.0371Epoch 2/5858/857 [==============================] - 75s 88ms/step - loss: 15.4719 - accuracy: 0.0401 - val_loss: 15.5210 - val_accuracy: 0.0371Epoch 3/5858/857 [==============================] - 77s 89ms/step - loss: 15.4230 - accuracy: 0.0431 - val_loss: 15.5210 - val_accuracy: 0.0371Epoch 4/5858/857 [==============================] - 76s 89ms/step - loss: 15.4268 - accuracy: 0.0429 - val_loss: 15.5120 - val_accuracy: 0.0371Epoch 5/5858/857 [==============================] - 75s 88ms/step - loss: 15.4287 - accuracy: 0.0428 - val_loss: 15.5120 - val_accuracy: 0.0371
批量大小设置得很低,因为Coursera的Jupyter笔记本将其限制为10。
回答:
你的代码是正确的。我怀疑这可能与优化器有关。尝试使用Adam代替RMSProp,并将Adam的学习率设置为0.001,这是默认的学习率。除此之外,你的笔记本正确地提取了标签和数据,制定了数据生成器,网络看起来也是正确的。