ValueError:检查输入时出错:预期density_18_input具有形状(784,)但具有形状(1,)的数组

时间:2019-03-22 01:37:24

标签: python tensorflow machine-learning google-colaboratory tf.keras

我正在用tf.data测试tf.keras,因此可以进行小批量优化。我正在使用MNIST数据集,并且正在Google Colab中运行代码。但是,当我尝试训练网络时,总是会遇到此错误: ValueError: Error when checking input: expected dense_18_input to have shape (784,) but got array with shape (1,)。这是我的代码:

import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import pandas as pd

!git clone https://github.com/DanorRon/my_repo
%cd my_repo
!ls

batch_size = 100
epochs = 10
alpha = 0.01
lambda_ = 0.01
h1 = 50

train = pd.read_csv('/content/sample_data/my_repo/mnist_train.csv.zip')
test = pd.read_csv('/content/sample_data/my_repo/mnist_test.csv.zip')

x_train = train.loc[:, '1x1':'28x28']
y_train = train.loc[:, 'label']

x_test = test.loc[:, '1x1':'28x28']
y_test = test.loc[:, 'label']

Train = tf.data.Dataset.from_tensor_slices((x_train, y_train))
Train.batch(batch_size).repeat(10).shuffle(1000)

model = tf.keras.Sequential()
model.add(layers.Dense(784, input_shape=(784,)))
model.add(layers.Dense(h1, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)))
model.add(layers.Dense(10, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2(0.01)))

model.compile(optimizer=tf.train.AdamOptimizer(alpha),
             loss = 'categorical_crossentropy',
             metrics = ['accuracy'])

model.fit(Train, epochs=epochs, steps_per_epoch=600)

我不知道问题是什么。我认为我的尺寸是正确的,并且看不到任何其他问题。我该如何解决这个问题?

编辑:我已经看了很多/测试过的东西来找到答案,但是找不到任何有效的方法。我完全不知道问题可能是什么。

1 个答案:

答案 0 :(得分:0)

我想也许您应该从x_train中分离y_trainTrain,然后将model.fit改写为model.fit(x_train, y_train, epochs=epochs, steps_per_epoch=600)