【问题标题】:Keras: ValueError: Error when checking target: expected dense to have shape (10,) but got array with shape (400,)Keras:ValueError:检查目标时出错:预期密集具有形状(10,)但得到形状为(400,)的数组
【发布时间】:2020-01-02 21:14:19
【问题描述】:

尝试在 Keras 和 Tensorflow 后端训练我的模型时遇到问题。

import numpy as np
from sklearn.utils import shuffle

# Load Data
df = np.loadtxt("features.txt", delimiter=',') 
print('Features shape:', df.shape)

labels = np.loadtxt("labels.txt", delimiter=',') 
print('Labels shape', labels.shape)

# Replace 10 by 0
labels = np.where(labels == 10, 0, labels) 

# Randomize the data 
data_shuffled, labels_shuffled = shuffle(df, labels, random_state=42)

from keras.models import Sequential
from keras.layers import Dense

# split into input (X) and output (y) variables
X = data_shuffled[:4000]
y = data_shuffled[4000:]

print(X.shape, y.shape)

# define the keras model
model = Sequential()
model.add(Dense(12, input_dim=400, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(10, activation='sigmoid'))
# compile the keras model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit the keras model on the dataset
model.fit(X, y, epochs=1000, batch_size=100, verbose=0)
# make class predictions with the model
predictions = model.predict_classes(X)
# summarize the first 5 cases
for i in range(5):
    print('%s => %d (expected %d)' % (X[i].tolist(), predictions[i], y[i]))

# evaluate the keras model
accuracy = model.evaluate(X, y)
print('Accuracy: %.2f' % (accuracy*100))

特征形状:(5000, 400) 标签形状 (5000,)

我在调用 model.fit() 的那一行遇到了错误。

我尝试修复此错误的方法: 我尝试使用以下代码重塑 X 和 y numpy 数组: X.reshape(400, -1) y.reshape(400, -1)

但这无济于事。

【问题讨论】:

    标签: python keras


    【解决方案1】:

    我认为这行是错误的:y = data_shuffled[4000:]

    应该是:y = labels_shuffled[:4000]

    那么你需要one-hot-encode:

    from sklearn.preprocessing import OneHotEncoder
    onehotencoder = OneHotEncoder()
    y = onehotencoder.fit_transform(y.reshape(-1,1)).toarray()
    

    【讨论】:

    • 现在我得到这个错误:ValueError: Error when checks target: expected dense to have shape (10,) but got array with shape (1,)
    • 啊,那是因为你已经设置了网络,假设标签是one-hot-encoded。我会更新答案。让我知道它是否修复它。
    • 顺便说一句,我假设标签是互斥的?就像你不能同时成为 10 个班级中的一个以上的成员一样?
    • 感谢您的回答。是的,标签是互斥的。但是,当我执行您更新的代码时,我收到以下错误: ValueError: Expected 2D array, got 1D array instead: array=[3. 5. 5. ... 7. 9. 1.]。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1) 。 X的形状是(4000, 400),y的形状是(4000,)
    • 我已经更新了答案。只需要重塑标签,如:y.reshape(-1,1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多