python - 如何在 keras 中训练顺序模型,给出一个列表作为输出和输入?

我对 Keras 和一般的机器学习还很陌生,但这就是我想要的。我有一个输入列表(每个输入节点 1 个值)和一个目标列表(每个输出节点 1 个值)。

    input_list = [1, 0, 1, 0, 1, 0] # maybe longer

    wanted_output_list = [1, 0, 0, 0] # also maybe longer

现在我想将这些作为输入来训练我的神经网络:

    # create model
    model = Sequential()

    # get number of columns in training data
    n_cols = 6

    # add model layers
    model.add(Dense(6, activation='relu', input_shape= (n_cols,)))
    model.add(Dense(2, activation='relu'))
    model.add(Dense(2, activation='relu'))
    model.add(Dense(3))

    # compile the model
    model.compile(optimizer='adam', loss='mean_squared_error')

    # train model
    model.fit(input_list, wanted_output_list, validation_split=0.2, epochs=30)

但是我得到这个错误:

    ValueError: Error when checking input: dense_1_input to have shape (6,) but got with shape (1,)

谁能告诉我为什么以及如何解决这个问题?

最佳答案

在定义模型时,您指定了一个接受具有 6 个特征的输入并输出具有 3 个分量的向量的模型。但是,您的训练数据形状不正确(顺便说一句,您的标签也没有)。您应该按照定义模型的方式塑造数据。在这种情况下,这意味着您的训练数据的每个样本都是一个包含 6 个分量的向量,每个标签都是一个包含 3 个分量的向量。

Keras 在训练具有多个输入的模型时需要一个 numpy 数组 列表(或二维数组),请参阅 documentation .

x : Input data. It could be:

  • A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs).

因此,根据您的模型定义,您可以按以下方式调整训练数据:

import numpy as np
# your data, in this case 2 datapoints
X = np.array([[1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1]])
# the corresponding labels
y = np.array([[1, 0, 0], [0, 1, 0]]) 

然后通过调用 fit 训练您的模型。

model.fit(x, y, epochs=30)

https://stackoverflow.com/questions/58204710/

相关文章:

java - 创建名为“kafkaListenerContainerFactory”的 bean 时

wordpress - 您无权查看此页面 : JWT Authentication for WP R

visual-studio-code - Prettier 在 React Code 中不工作并在状

javascript - 使用 React Hook 应用多个 Context 的好方法

flutter - 如何使用我的整个应用程序在 TabBarView 中创建可滚动的内容?

apache-spark - 在 Spark 2.4.0 中使用 spark.sql 的 Hive

selenium - 登录网站时如何使用 puppeteer/selenium 重用保存的凭据/密码

react-native - null 不是对象(评估 'StripeModule.init' )

reactjs - Jest 性能问题

node.js - nodemailer 不发送邮件,给出 250 ok