预期与keras中的test_set不同的维度

时间:2019-04-22 17:01:45

标签: keras

我曾尝试制作一个像“ mnist”之类的简单项目,但我发现有关错配的错误

我尝试使用与https://github.com/amir-saniyan/HodaDatasetReader不同的数据集 并试图跟随我之前为“ mnist”而失望 但是发生了这个错误!

Traceback (most recent call last): File "train..py", line 51, in <module> score = network.evaluate(x_test, y_test) File "/usr/local/lib/python3.6/dist-packages/keras/engine/training.py", line 1102, in evaluate batch_size=batch_size) File "/usr/local/lib/python3.6/dist-packages/keras/engine/training.py", line 789, in _standardize_user_data exception_prefix='target') File "/usr/local/lib/python3.6/dist-packages/keras/engine/training_utils.py", line 128, in standardize_input_data 'with shape ' + str(data_shape)) ValueError: Error when checking target: expected dense_2 to have 2 dimensions, but got array with shape (20000, 10, 2)

并且此行中发生了错误:

score = network.evaluate(x_test, y_test)"

我定义数据集的方式:

import numpy as np
import matplotlib.pyplot as plt
from HodaDatasetReader.HodaDatasetReader import read_hoda_cdb, read_hoda_dataset
plt.rcParams['figure.figsize'] = (7,9) # Make the figures a bit bigger
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.utils import np_utils, to_categorical

加载训练数据

nb_classes = 10
x_train, y_train = read_hoda_dataset(dataset_path='HodaDatasetReader/DigitDB/Train 60000.cdb',
                                images_height=32,
                                images_width=32,
                                one_hot=False,
                                reshape=True)
x_test, y_test = read_hoda_dataset(dataset_path='HodaDatasetReader/DigitDB/Test 20000.cdb',
                              images_height=32,
                              images_width=32,
                              one_hot=True,
                              reshape=False)

x_train = x_train.reshape((60000, 32 * 32))
x_train = x_train.astype('float32') / 255
x_test = x_test.reshape((20000, 32 * 32))
x_test = x_test.astype('float32') / 255

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

模型

network = Sequential()
network.add(Dense(512, activation='relu', input_shape=(32 * 32,)))
network.add(Dense(10, activation='softmax'))

和预测

network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
network.fit(x_train, y_train, epochs=1, batch_size=1000)
score = network.evaluate(x_test, y_test)###error was here :(

2 个答案:

答案 0 :(得分:1)

您对y_test有疑问。您可以使用以下代码更改代码,因为x_train, y_trainx_test, y_test之间的初始化存在差异。

x_test, y_test = read_hoda_dataset(dataset_path='HodaDatasetReader/DigitDB/Test 20000.cdb',
                              images_height=32,
                              images_width=32,
                              one_hot=False,
                              reshape=True)

答案 1 :(得分:0)

正如我发现的那样,我们不需要更改y-test形式,因此只需删除这部分代码即可: “ y_test = to_categorical(y_test)” 而且有效!!