我目前正在尝试测试我在jupyter笔记本上训练的一个模型,但我不断收到错误,并且我不确定如何组织代码以使模型预测输出。这是我训练模型的代码。
model = Sequential()
model.add(Dense(400, input_dim=features,activation='tanh'))
model.add(Dense(150, activation='tanh'))
model.add(Dense(80, activation='tanh'))
model.add(Dense(40, activation='tanh'))
model.add(Dense(5, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.save_weights("testSave.hdf5")
history = model.fit(X, Y, validation_split=0.33,epochs=15)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()代码可以正常工作,并且编译良好。下面是尝试创建新记录并在上面训练的模型上测试它的代码。
model2 = Sequential()
model2.add(Dense(400, input_dim=features, activation='tanh'))
model2.add(Dense(150, activation='tanh'))
model2.add(Dense(80, activation='tanh'))
model2.add(Dense(40, activation='tanh'))
model2.add(Dense(5, activation='softmax'))
model2.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model2.load_weights("testSave.hdf5")
newData = random.rand(features) # Creates a new array of 87 instances (amount of features I have)
reshaped_to_2d = np.reshape(newData, (-1, 2)) # Attempting to reshape to 2D array as this is what an error is telling me to do. This doesnt work
scaler = preprocessing.Normalizer().fit(reshaped_to_2d)
newDataN = scaler.transform(reshaped_to_2d)
result = model2.predict_classes((newDataN), axis=1)
for item in result:
print("Predicted Value: ", item[0])这个模型在这一行抛出了一个错误reshaped_to_2d = np.reshape(newData, (-1, 2)),说它不能将一个由87个实例组成的数组转换成一个由2个实例组成的数组。这可能是一个非常微不足道的问题,但我很难理解它,并且在网上找不到帮助。任何帮助都很好,谢谢。
返回的错误如下图所示。

这是我用来创建模型的代码,所以它可以在87列* 100000行上训练。
seed = 34
random.seed(seed)
features = 87
classes = 5
n = 100000
errors = 0.4
# Truncate
redundant = int(features/4)
# Classification dataset
X, y = make_classification(n_samples=n, n_classes=classes, n_features=features, \
random_state = 1,n_informative =20, flip_y=errors, \
n_redundant=redundant)
# reshape y to 2D array, it needs to be to append
y = reshape(y, (-1, 1))
scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))
rescaledX = scaler.fit_transform(X)
Xy = concatenate((rescaledX,y),axis=1)
savetxt("myCAData.csv", Xy, delimiter=",")
data = read_csv("myCAData.csv")
print(Xy[:5])
Y = np_utils.to_categorical(y)发布于 2020-04-13 02:31:03
当您使用np.reshape()时提供的新形状是无效的,因为您生成的数据长度为87,这是一个奇数,并且您想要将其拆分为相同长度的两列时,这是不可能的,因为87 /2不是整数。当在长度元组中使用参数为-1的np.reshape时,输入向量的长度必须除以第二个数字。
您已经说过,输入特征向量的长度是87,所以当您想要将输入到模型的newData拆分为2D向量时,我不明白您的意思。你能解释一下背后的逻辑吗?这样我就可以帮助你解决这个维度的问题了。
https://stackoverflow.com/questions/61121215
复制相似问题