python - 如何使用keras定义模型架构?

标签 python machine-learning neural-network keras

我想创建如下图所示的神经网络模型

enter image description here

我的 x_train 变量具有 (20204,2) 维度,y_train 具有 (20204,) 维度

我正在使用 keras 顺序模型,但是当我运行下面的代码时

model=Sequential()
model.add(Dense(output_dim = 2, init = 'uniform', activation = 'relu', input_dim=20204))
model.add(Dense(output_dim = 3,init = 'uniform',activation = 'softmax'))
model.compile(loss = 'sparse_categorical_crossentropy',optimizer = 'adam',metrics = ['accuracy'])
model.fit(x_train,y_train,batch_size=12,epochs=14)
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=12)
print(loss_and_metrics)

我收到一条错误消息

ValueError: Error when checking input: expected dense_26_input to have shape (20204,) but got array with shape (2,)

如何解决这个问题?

最佳答案

当您说您的输入的形状为 (20204, 2) 时,您的意思是您有 20204 个训练示例,每个示例有 2 尺寸。

您需要告诉您的输入预期为 2 尺寸,并且不是20204。发生错误的原因是您的模型期望接收 20204 个特征(即参数 input_dim=20204),但实际接收到 2 个特征。

要解决此问题,只需更改我上面提到的参数即可:

model=Sequential()
model.add(Dense(output_dim=2, init='uniform', activation='relu', input_dim=2))
model.add(Dense(output_dim=3, init='uniform', activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=12, epochs=14)
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=12)
print(loss_and_metrics)
<小时/>

编辑:

正如 @today 和 @desertnaut 正确指出的那样,你的图显示隐藏层有 4 个神经元,而不是像上面的代码产生的 2 个神经元。

要更改此设置,您需要将隐藏层中的参数 output_dim=2 替换为 output_dim=4:

model.add(Dense(output_dim=4, init='uniform', activation='relu', input_dim=2))

关于python - 如何使用keras定义模型架构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52058487/

相关文章:

python - Keras 没有使用 100% cpu

python - 实例化一个新对象更好,还是简单地更新新数据的属性更好?

python - django自定义函数用于过滤查询

python - 具有变化的先验概率的文本数据集的多类 NaiveBayes 分类

pandas - 为什么会出现“name 'pd ' is not Defined”错误?

python - 如何获得 catboost 可视化以显示类别

c# - C# 中的强化学习

python - Tensorflow中的 block 激活函数实现

python - django 模板问题(访问列表)

python - 如何在 openpyxl 条件格式中使用占位符?