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