python - Keras 中的输入和输出维度错误

标签 python machine-learning keras

我目前正在研究二元分类的客户流失管理问题。

我在拟合模型时遇到错误。输入/输出中似乎有一些东西导致了我无法捕捉到的问题。

这是代码(df 包含我从中创建向量的数据框):

#Delete unimportant columns.
del df['RowNumber']
del df['CustomerId']
del df['Surname']

然后,我必须转换两个分类变量:

#Converting and creating dummy variables for categorical variables
df["Gender"] = df["Gender"].astype('category')
df["Geography"] = df["Geography"].astype('category')
df['Gender'] = pd.get_dummies(df['Gender'])
df['Geography'] = pd.get_dummies(df['Geography'])

y = df.iloc[:, -1] #Label variable
X = df.iloc[:, :10] #Features

将数据集分为测试和训练:

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

接下来,我将缩放变量:

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train) 
X_test = sc.transform(X_test)
print(X_train.shape) #(8000, 10)
print(X_test.shape) #(2000, 10)
print(y_train.shape)#(8000,)
print(y_test.shape)#(2000,)

建立网络:

model = models.Sequential()
model.add(layers.Dense(32, activation='relu', input_shape=(8000,)))
model.add(layers.Dense(1, activation='sigmoid'))
# Compiling Neural Network
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
#Fitting our model
model.fit(X_train, y_train, batch_size = 10, epochs = 10)

# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)

# Creating the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

我收到的具体错误代码是:

ValueError:检查输入时出错:预期dense_47_input 的形状为(None, 8),但得到的数组形状为(8000, 10)

任何解决这个问题的帮助都会很棒!

编辑:model.compile之前的模型摘要: enter image description here

Edit2:编译后的模型摘要: enter image description here

最佳答案

我认为你需要纠正这个问题:

model.add(layers.Dense(32, activation='relu', input_shape=(10,)))

10 是您使用的功能数量。 Keras 将自动获取批处理/数据集中的行数。

编辑说明:

from keras import models
from keras import layers

model = models.Sequential()
model.add(layers.Dense(32, input_shape=(10,)))
model.add(layers.Dense(1))

这里,创建的第一层仅接受维度为 10 的 2D 张量(第零维度,批量维度,未指定,因此任何值都将被接受)。

因此,该层只能连接到需要 32 维向量作为输入的上游。使用 Keras 时,您不必担心兼容性,因为添加到模型中的层是动态构建的,以匹配传入层的形状。

第二层没有接收输入形状参数,而是自动将其输入形状推断为前一层的输出形状。

解码模型中的参数值:

假设这是我的模型:

from keras import models
from keras import layers

model = models.Sequential()
model.add(layers.Dense(32, input_shape=(2,)))
model.add(layers.Dense(1))
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
print model.summary()

这是模型摘要:

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_1 (Dense)              (None, 32)                96
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 33
=================================================================
Total params: 129
Trainable params: 129
Non-trainable params: 0
_________________________________________________________________

对于密集层,我们需要计算:

output = dot(W, input) + b

output = relu(dot(W, input) + b) #relu here is the activation function

在此表达式中,W 和 b 是张量,是层的属性。它们被称为层的“权重”或“可训练参数”(分别是内核和偏差属性)。这些权重包含网络从训练数据中学到的信息。

对于第 1 层(参数=96)= Hidden_​​units * Dimension_of_input_data +bias_value

96 = 32 (Hidden Units) * 2 (Data Dimension) + 32 (Bias Value Same as Hidden Units)

对于第 2 层(参数 = 33)= 隐藏单元 * 数据维度 + 偏差值

33 = 1 (Hidden Units) * 32 (Data Dimension) + 1 (Bias Value Same as Hidden Units)

Total Params = 96+33 = 129

希望这有帮助:)

解释来源:Keras Documentation

关于python - Keras 中的输入和输出维度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507546/

相关文章:

python - 如何计算 PIL 逊相关矩阵并仅保留有效值?

machine-learning - Cloud ML 高效地从 Google Storage 读取大量图像

machine-learning - 自动化谣言识别过程

python - TF Hub微调错误: ValueError: Failed to find data adapter that can handle input

deep-learning - 如何在 Keras 中使用 return_sequences 选项和 TimeDistributed 层?

python - 在python中执行基于特定时间间隔的任务

python - 如何使用 groupby 减去列中的值

numpy - 为什么 MinMaxScaler 会向图像添加线条?

python - Keras 中 TimeDistributed 层的作用是什么?

python - 在python中按索引切片嵌套列表