使用tensorflow训练mnist数字数据集时的密集形状错误

时间:2018-08-28 17:33:57

标签: tensorflow python-3.6

我正在尝试训练mnist的整个数据集。我将基于此代码tutorial。以下是我的代码

import tensorflow as tf
mnist = tf.keras.datasets.mnist
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28,1)
x_test = x_test.reshape(x_test.shape[0], 28, 28,1)

mean_px = x_train.mean().astype(np.float32)
std_px = x_train.std().astype(np.float32)

def standardize(x): 
    return (x-mean_px)/std_px

y_train= tf.keras.utils.to_categorical(y_train)
num_classes = y_train.shape[1]
seed = 43
np.random.seed(seed)

model= tf.keras.models.Sequential()
model.add(tf.keras.layers.Lambda(standardize,input_shape=(28,28,1)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(10, activation='softmax'))
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.001),
 loss='categorical_crossentropy',
 metrics=['accuracy'])
gen =  tf.keras.preprocessing.image.ImageDataGenerator()
batches = gen.flow(x_train, y_train, batch_size=64)
val_batches=gen.flow(x_test, y_test, batch_size=64)

history=model.fit_generator(generator=batches, steps_per_epoch=batches.n, epochs=3,validation_data=val_batches, validation_steps=val_batches.n)

但是,我收到一条错误消息,说ValueError: Error when checking target: expected dense to have shape (10,) but got array with shape (1,)

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

我认为您忘记了将y_test转换为一键向量。

   y_test= tf.keras.utils.to_categorical(y_test)

一旦成功,那就成功了。

  

损耗:0.2412-acc:0.9353-val_loss:0.3187-val_acc:0.9222