【问题标题】:Unable to understand format of test data while evaluating training model评估训练模型时无法理解测试数据的格式
【发布时间】:2019-09-20 12:25:47
【问题描述】:

我正在训练一个回归模型,该模型近似于方程的权重: Y = R+B+G 为此,我提供了 R、B 和 G 和 Y 的预定值作为训练数据。

    R    = np.array([-4, -10,  -2,  8, 5, 22,  3],  dtype=float)
    B    = np.array([4, -10,  0,  0, 15, 5,  1],  dtype=float)
    G    = np.array([0, 10,  5,  8, 1, 2,  38],  dtype=float)

    Y    = np.array([0, -10, 3, 16, 21, 29, 42],  dtype=float)

训练批次由 1x3 数组组成,对应于 R、B 和 G 的第 I 个值。

    RBG = np.array([R,B,G]).transpose()
    print(RBG)

    [[ -4.   4.   0.]
    [-10. -10.  10.]
    [ -2.   0.   5.]
    [  8.   0.   8.]
    [  5.  15.   1.]
    [ 22.   5.   2.]
    [  3.   1.  38.]]

我使用的神经网络有 3 个输入,1 个密集层(隐藏层)有 2 个神经元,输出层(输出)有一个神经元。

    hidden = tf.keras.layers.Dense(units=2, input_shape=[3])
    output = tf.keras.layers.Dense(units=1)

此外,我训练了模型

    model = tf.keras.Sequential([hidden, output])
    model.compile(loss='mean_squared_error', 
    optimizer=tf.keras.optimizers.Adam(0.1))
    history = model.fit(RBG,Y, epochs=500, verbose=False)
    print("Finished training the model")

loss vs epoch plot 正常,先递减,然后持平。

但是当我测试模型时,使用 R、B 和 G 的随机值作为

    print(model.predict([[1],[1],[1]]))

期望输出为 1+1+1 = 3,但得到值错误:

    ValueError: Error when checking input: expected dense_2_input to have shape (3,) but got array with shape (1,)

知道我可能在哪里出错了吗?

令人惊讶的是,它响应的唯一输入是训练数据本身。即,

    print(model.predict(RBG))

    [[ 2.1606684e-07]
    [-3.0000000e+01]
    [-3.2782555e-07]
    [ 2.4000002e+01]
    [ 4.4999996e+01]
    [ 2.9000000e+01]
    [ 4.2000000e+01]]

【问题讨论】:

    标签: python-3.x tensorflow linear-regression


    【解决方案1】:

    正如错误所说,问题出在您输入的形状上。你需要转置[[1],[1],[1]]这个输入,然后你就会得到模型所期望的形状。

    所以npq = np.array([[1],[1],[1]]).transpose() 现在将其提供给model.predict(npq)

    【讨论】:

    • 它就像魔术一样!但是你能告诉我这背后的原因吗?开始使用 NumPy 后,我一直在经历这些奇怪的错误。
    • 每个模型都有层,每个层都需要特定形状或维度的输入。这些错误在使用数组或张量时很常见。因此,在输入任何输入之前,请始终确保输入的形状、尺寸等与输入接收器的预期匹配。一种简单的方法是预先打印它们。
    • 但是 np.array([[1],[1],[1]]) 确实给出了错误中要求的尺寸 (3, )。我不明白转置它的原因。
    • this (3,) 表示行数为 3,意味着 3 个样本只有 'R' 的值,但它要求每个样本有 3 列,其中所有列分别代表 R、G、B 值.如果您计算上面打印的 RGB 形状,您将得到 (7,3),即 7 个​​样本,每个样本具有 RGB 值(3 列),现在当您想预测一个样本时,您的最终输入形状必须为 (1,3)。
    • yes bc np.array([1,1,1]) 具有形状 (3,) 并且需要 (1,3)。
    猜你喜欢
    • 2022-07-05
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2019-05-25
    • 1970-01-01
    • 2023-01-10
    • 2018-02-19
    相关资源
    最近更新 更多