python - 神经网络模型

标签 python machine-learning keras neural-network deep-learning

我有 6 列和 100 行的样本数据(所有值都是整数)。输入数据分为 20 个类别。这是我尝试构建的模型:

model = Sequential()
model.add(Dense(50,input_shape=X.shape[1:],activation='relu'))

model.add(Dense(20,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', 
              metrics=['accuracy'])
model.summary()
model.fit(X, Y, epochs=1000, verbose=0)
predictions=model.predict(test_data)

但是,我得到一个错误:

Error when checking target: expected dense_2 to have shape (20,) but got array with shape (1,)

我有两个问题:

  1. 我做错了什么?
  2. 你能给我一个合适的架构吗?

最佳答案

您需要使用 to_categorical ( docs ) 将 Y 转换为二进制类矩阵。

import sklearn.datasets
X,Y = sklearn.datasets.make_classification(n_samples=100, n_features=6, n_redundant=0,n_informative=6, n_classes=20)

import numpy as np
from keras import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
from keras import backend as K
K.clear_session()

model = Sequential()
model.add(Dense(50,input_dim=X.shape[1],activation='softmax'))
model.add(Dense(20,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', 
              metrics=['accuracy'])
model.summary()
model.fit(X, to_categorical(Y), epochs=1000, verbose=1) # <---

您也可以使用 sklearn也为此。

关于python - 神经网络模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54248280/

相关文章:

python - 从 L1 正则化逻辑回归中恢复命名特征

python - 无法记录使用 Keras 构建但使用 Tensorflow 估计器训练的模型的损失

tensorflow - Keras reshape : total size of the new array must be unchanged

python - Tkinter 颜色名称到颜色对象

python - 测试是否存在 IPython

python - 如何抓取公共(public)画面仪表板?

python - 这个 cudaGetDevice() 失败可能是什么问题。状态 : cudaGetErrorString symbol not found

python - pandas DataFrame 爆炸列内容

machine-learning - 如何使用 numpy 数组从单词映射中检索单词? [Tensorflow RNN] 文本分类

python - 在 Keras 中对句子的词向量进行平均 - 预训练词嵌入