首页 > 解决方案 > ValueError:检查目标时出错:预期dense_3的形状为(1,)但得到的数组形状为(11,)

问题描述

我正在尝试使用 Keras 训练我的模型,并且正在学习 udemy 的在线课程。现在一切正常,但是当我尝试将 ANN 拟合到训练集时,它会出现以下错误。一切正常,但是当我执行最后一行时,它给出了错误。如果没有此错误,它应该可以正常工作,还是有任何其他方法可以将 ANN 拟合到训练集?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values

from sklearn.preprocessing import OneHotEncoder, LabelEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])

onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]

from sklearn.model_selection import train_test_split
X_train , y_train , X_test, y_test = train_test_split(X,y, test_size = 0.2 , random_state = 0)


#convert X_test into a 'numpy' array to acoid valur error for 1D array 
X_test = np.reshape(y, (-1,1))

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.fit_transform(X_test)


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

#initializing the ANN
classifier = Sequential()

#adding the input layer and the first hidden layer
classifier.add(Dense(units =6, kernel_initializer = 'uniform' , activation = 'relu', input_dim =11 ))

#adding the second layer
classifier.add(Dense(units = 6 , kernel_initializer = 'uniform' , activation = 'relu'))

#adding the output layer
classifier.add(Dense(units = 1 , kernel_initializer = 'uniform' , activation = 'sigmoid'))

#compiling the ANN
classifier.compile(optimizer = 'adam' , loss = 'binary_crossentropy', metrics = ['accuracy'])
# 'optimizer' is the algorithm that u wanna use for the wights adjustments

#fitting the ann to the trainging set 
classifier.fit(X_train , y_train , batch_size =10 , epochs = 100 )

标签: machine-learningkeras

解决方案


似乎input_shape没有正确设置。

来自文档

输入形状

具有形状的 nD 张量:(batch_size, ..., input_dim)。最常见的情况是具有形状 (batch_size, input_dim) 的 2D 输入。

在你的情况下input_shape=(X_train.shape[1],)

尝试这个:

#initializing the ANN
classifier = Sequential()

#adding the input layer and the first hidden layer
classifier.add(Dense(units=6,
                     kernel_initializer='uniform',
                     activation='relu',
                     input_shape=(X_train.shape[1],))

...

推荐阅读