ValueError:检查目标时出错:预期density_3的形状为(1,),但数组的形状为(11,)

时间:2019-09-14 20:56:46

标签: machine-learning keras

我正在尝试与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 )

1 个答案:

答案 0 :(得分:0)

似乎input_shape的设置不正确。

来自docs

  

输入形状

     

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],))

...