层序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 6,但接收的输入形状为 (None, 1)

时间:2021-07-03 14:07:46

标签: python numpy tensorflow machine-learning keras

我目前正在使用 Keras 用 Python 编写机器学习回归程序。

我收到不兼容的输入形状错误...请帮忙!

这是我的代码

import numpy as np
import pandas as pd
from keras import layers
from keras import models
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split


data = pd.read_csv('path/to/csv', sep=',')
y = data.points

X = data.copy(deep=True)
X.drop(columns=['points'], inplace=True)

X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = models.Sequential()

model.add(layers.Dense(64, activation='relu', name='dense_1', input_shape=(6,)))
model.add(layers.Dense(64, activation='relu', name='dense_2'))
model.add(layers.Dense(1, name='output'))

model.compile(optimizer='adam', loss='mse', metrics=['mae'])

results = model.evaluate(X_test, Y_test) 
print("Results: ", results)

arr = np.array([0.04, 0.01, 0.35, 0, 0, 0.001])
prediction = model.predict(arr.reshape(-1, 1))
print(prediction)

这是一个数据集示例:

dataset sample

points 列是要预测的列。

predict 行中,我收到此错误

 ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 6 but received input with shape (None, 1)

1 个答案:

答案 0 :(得分:0)

模型将第一个维度作为批次,其他维度基于您的输入模型。因此,如果您的模型输入是 (6,),并且您想预测一个样本,则应该传递形状为 (1,6) 的数据。

所以,像这样改变你的预测线:

prediction = model.predict(arr.reshape((1,-1)))