machine-learning - 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 )
解决方案
似乎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],))
...
推荐阅读
- python - 将 2 级 multiidex 系列重新组合为数据框,以便二级索引成为名称?
- android - 从免安装应用升级到完整应用的最佳实践
- python-3.x - Python3中的CSV文件比较算法
- python - 从另一个文件调用函数以在模板中使用
- php - 表单中的数据不会传递到 MySQL 数据库
- c# - 将模型中的属性值从控制器传递到视图 - 显示不正确的数据
- python - python调试器在命令行失败时执行完全相同的代码片段
- r - 如何在R中按条件划分数据集
- intellij-idea - 如何在我的 Mac WebStorm 中将 Blisk 配置为默认浏览器?
- azure-cosmosdb - CosmosDB API for Mongo 对待多键唯一索引的方式与 MongoDB 不同