我更改了数据类型,但无法解决该错误。
我尝试了“一键编码”,但是它也不起作用。
我不知道怎么了:(
seed = 0
np.random.seed(seed)
tf.set_random_seed(seed)
df = pd.read_csv('HW01_dataset_tae.txt', sep=',' ,header=None, names = ["Native", "Instructor", "Course", "Semester", "Class Size", "Evaluation"])
dataset = df.values # dataframe to int64
X = dataset[:,0:5] # attribute
Y_Eva = dataset[:,5] # class
e = LabelEncoder()
e.fit(Y_Eva)
Y = e.transform(Y_Eva)
K = 10
kFold = StratifiedKFold(n_splits=K, shuffle=True, random_state=seed)
accuracy = []
for train_index, test_index in kFold.split(X,Y):
model = Sequential()
model.add(Dense(16, input_dim=5, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='mean_squared_error',
optimizer='adam',
metrics=['accuracy'])
model.fit(X[train_index], Y[train_index], epochs=100, batch_size=2)
错误;检查目标时出错:预期density_2的形状为(3,),但数组的形状为(1,)
在这里检测到; model.fit(X [train_index],Y [train_index],epochs = 100,batch_size = 2)。
我会做什么?
答案 0 :(得分:1)
我解决了这个问题。
使用此代码,
model.fit(X[train_index], Y[train_index], epochs=100, batch_size=2)
“ Y [train_index]”中的行数必须为3,因为类是3。
由于每个Y [train_index]只有一行,因此出现了错误。
因此,我使用了“一键编码”并更改了这样的代码。
e = LabelEncoder()
e.fit(Y_Eva)
Y = e.transform(Y_Eva)
Y_encoded = np_utils.to_categorical(Y) # changed code
K = 10
kFold = StratifiedKFold(n_splits=K, shuffle=True, random_state=seed)
accuracy = []
for train_index, test_index in kFold.split(X,Y):
model = Sequential()
model.add(Dense(32, input_dim=5, activation='relu'))
model.add(Dense(16, activation='relu'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(X[train_index], Y_encoded[train_index], epochs=100, batch_size=2) # changed code
最后,我能够运行代码。
答案 1 :(得分:0)
TensorFlow在致密层上做了一些文档处理,如果您不说input_dim说input_shape,则可以指定首选形状。
https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense
model = Sequential()
model.add(Dense(16, input_shape=(5,))) # Then your data has to be of shape (batch x 5)
然后添加另一个密集层时,实际上不必提供input_sahpe
model.add(Dense(10))