Tensorflow Keras Python3期望输出形状(1),但得到形状(3)

Tensorflow Keras Python3期望输出形状(1),但得到形状(3),python,tensorflow,keras,Python,Tensorflow,Keras,我是tensorflow和构建神经网络的新手 我正在尝试用tf.keras api制作一个神经网络,它将接受一个输入,并给出3个输出。这是我的密码: import os import tensorflow as tf from tensorflow import keras import numpy as np train_times = np.array([[1],[2],[3],[4],[5],[6],[7],[8]]) train_sensors = np.array([[0.1,0.1

我是tensorflow和构建神经网络的新手

我正在尝试用tf.keras api制作一个神经网络,它将接受一个输入,并给出3个输出。这是我的密码:

import os
import tensorflow as tf
from tensorflow import keras
import numpy as np

train_times = np.array([[1],[2],[3],[4],[5],[6],[7],[8]])
train_sensors = np.array([[0.1,0.15,0.2],[0.25,0.3,0.35],[0.4,0.45,0.5],[0.55,0.6,0.65],[0.7,0.75,0.8],[0.85,0.9,0.95],[0.05,0.33,0.56],[0.8,0.35,0.9]])
test_times = np.array([[1],[2],[3],[4],[5],[6],[7],[8]])
test_sensors = np.array([[0.1,0.15,0.2],[0.25,0.3,0.35],[0.4,0.45,0.5],[0.55,0.6,0.65],[0.7,0.75,0.8],[0.85,0.9,0.95],[0.05,0.33,0.56],[0.8,0.35,0.9]])
print(train_sensors[0].shape)
def create_model():
    model = tf.keras.models.Sequential([
    keras.layers.Dense(5, activation=tf.nn.relu, input_shape=(1,), name="Input"),
    keras.layers.Dense(10,activation=tf.nn.relu, name="Middle"),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(3, activation=tf.nn.softmax, name="Out")
    ])
    model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.sparse_categorical_crossentropy,
                  metrics=['accuracy'])
    return model


model = create_model()
model.summary()

checkpoint_path = "sensor_predict.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,save_weights_only=True,verbose=1)
model.fit(x=train_times, y=train_sensors,epochs = 10,validation_data = (test_sensors, test_times), callbacks = [cp_callback])
我已经指定最后一层应该有三个输出,但每次运行时都会出现以下错误:

ValueError: Error when checking target: expected Out to have shape (1,) but got array with shape (3,)
我不明白为什么它似乎认为我需要网络的单一输出

注意:我使用的数据集不是我实际使用的数据集。我只是想得到一个函数网络,然后我会在以后生成数据。

你的损失函数(tf.keras.loss.sparse\u category\u crossentropy)期望训练向量是一个热编码的。例如,将其更改为tf.keras.loss.mse,我认为它会起作用


有关定义,请参见。

验证数据=(测试传感器,测试次数)
可能顺序错误?我已经切换了好几次。到目前为止没有发生任何事情…非常感谢!我真不敢相信我没听懂。