我是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)
答案 0 :(得分:1)
正如Vivek Kumar在评论中已经暗示的那样,在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