【问题标题】:Keras input dimension errorKeras输入尺寸错误
【发布时间】:2017-11-09 02:10:20
【问题描述】:

我是 keras 的新手。我遇到了一些输入尺寸问题,你能告诉我我应该如何解决这个错误。真的很感谢你。

这是数据集有 15 列的代码。预测变量来自列索引 [2:14],第 14 列有四个分类标签。

# load dataset
dataframe = pandas.read_csv("tesp_attack.csv",header=None)
dataframe = dataframe.values
predictors = dataframe[:,2:14].astype(int)
response = dataframe[:,14]

n_cols=predictors.shape[1]
print(n_cols)

encoder = LabelEncoder()
encoder.fit(response)
encoded_response = encoder.transform(response)
dummy_response = np_utils.to_categorical(encoded_response)

model = Sequential()
model.add(Dense(50,activation='relu',input_shape=(n_cols,)))
model.add(Dense(50,activation='relu'))
model.add(Dense(12,activation='softmax'))
model.compile(optimizer='adam',loss='categorical_crossentropy', metrics = ['accuracy'])
model.fit(predictors,dummy_response)

这是错误——

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-209-442bc37e349e> in <module>()
----> 1 model.fit(predictors,dummy_response)

~\Anaconda3\lib\site-packages\keras\models.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, **kwargs)
    865                               class_weight=class_weight,
    866                               sample_weight=sample_weight,
--> 867                               initial_epoch=initial_epoch)
    868 
    869     def evaluate(self, x, y, batch_size=32, verbose=1,

~\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
   1520             class_weight=class_weight,
   1521             check_batch_axis=False,
-> 1522             batch_size=batch_size)
   1523         # Prepare validation data.
   1524         do_validation = False

~\Anaconda3\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_batch_axis, batch_size)
   1380                                     output_shapes,
   1381                                     check_batch_axis=False,
-> 1382                                     exception_prefix='target')
   1383         sample_weights = _standardize_sample_weights(sample_weight,
   1384                                                      self._feed_output_names)

~\Anaconda3\lib\site-packages\keras\engine\training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    142                             ' to have shape ' + str(shapes[i]) +
    143                             ' but got array with shape ' +
--> 144                             str(array.shape))
    145     return arrays
    146 

ValueError: Error when checking target: expected dense_34 to have shape (None, 12) but got array with shape (28802, 4)

【问题讨论】:

  • 请在代码块中插入您的代码和错误
  • 请再看看@0TTT0
  • 你的目标有 4 种可能性。您在网络中的哪个位置添加了它。为什么你最后一个 Dense() 的输出形状是 12?
  • @VivekKumar 。好的,我将输出层中的节点数更改为 4 以及任何修改???
  • 没有。试试看,看看你是否还有更多错误。应用前请理解代码。

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


【解决方案1】:

正如 Vivek Kumar 在 cmets 中已经暗示的那样,在 softmax 分类中,最终密集层中的节点数应等于类数;仔细查看错误消息,您会发现它抱怨正是因为该层接收形状 ( , 4) 输入,而它期望形状 ( , 12) 一个(因为您已经这样编码了)。

您应该将最终的密集层(更好的是,将类的数量定义为参数)更改为:

num_classes = 4
# or programatically (requires import numpy as np):
num_classes = np.unique(response).size

[...]
model.add(Dense(num_classes, activation='softmax'))  # final layer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2018-03-06
    • 2017-08-30
    • 1970-01-01
    • 2018-09-01
    • 2019-05-25
    相关资源
    最近更新 更多