Keras Debug:ValueError: Error when checking target: expected dense_3 to have shape (None, 10) but got array with shape (42000, 1)


 

初学tensorflow的东西时总是会遇到些奇奇怪怪的错误= =。

错误1:ValueError: Error when checking target: expected dense_3 to have shape (None, 10) but got array with shape (42000, 1)

问题代码:

import numpy as np
import pandas as pd import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt train = pd.read_csv('./input/train.csv') test = pd.read_csv('./input/test.csv') train_images=train.iloc[:,1:] test_images=test train_labels = train.loc[:,['label']] model = tf.keras.models.Sequential([ # tf.keras.layers.Flatten(), tf.keras.layers.Dense(128,activation='relu',input_shape=(784,)), tf.keras.layers.Dense(64,activation='relu'), tf.keras.layers.Dense(10,activation=tf.nn.softmax), ]) #model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy']) model.compile(optimizer='adam',loss=keras.losses.mean_squared_error,metrics=['accuracy']) train_images_array = train_images.as_matrix() train_labels_array = train_labels.as_matrix() model.fit(train_images_array,train_labels_array,epochs=1)

就是kaggle中的CV入门MNIST问题的一个小demo。完全对照TFkeras教程(https://tensorflow.google.cn/tutorials/)写的呀?哪来的问题?

错误信息看的晕头转向,于是查API。问题出在model.fit,就先查tf.keras.Model的fit方法。

输入数据不匹配?没啥毛病呀?一脸懵逼,然后又看回信息,发现问题在要求的是(None,10),而给的是(42100,1),不禁联想到MSE,是不是不适合作为多分类问题的loss,所以问题可能出在compile环节?

改用sparse_categorical_crossentropy即可解决问题。

然后又遇到问题,问题代码:

import numpy as np
import pandas as pd import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt train = pd.read_csv('./input/train.csv') test = pd.read_csv('./input/test.csv') train_images=train.iloc[:,1:] test_images=test train_labels = train.loc[:,['label']] model = tf.keras.models.Sequential([ # tf.keras.layers.Flatten(), tf.keras.layers.Dense(128,activation='relu',input_shape=(784,)), tf.keras.layers.Dense(64,activation='relu'), tf.keras.layers.Dense(10,activation=tf.nn.softmax), ]) model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy']) model.fit(train_images,train_labels,epochs=1)

错误信息 KeyError: '[32679 25818 26494 40410 18964 17697 14090 34050 22019 16643 8492 24508\n 5189 10441 22318 15988 20704 8399 19606 18305 13980 25901 2868 17264\n 39208 33707 36080 27508 6712 33266 8809 28003] not in index'

然后我查了下,其中最小的2868是在train_images里的啊。然后在查看keras.Model的fit方法参数时,发现:

问题可能出在我把DataFrame传进去了,而之前我也犯过类似的错误(对DataFrame进行切片操作),故加入代码,

train_images_array = train_images.as_matrix()
train_labels_array = train_labels.as_matrix() model.fit(train_images_array,train_labels_array,epochs=1)

即可解决问题。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM