【问题标题】:model.predict in tensorflow is not workingtensorflow 中的 model.predict 不起作用
【发布时间】:2020-05-04 03:45:28
【问题描述】:

我正在编写此代码来预测最终答案,但我没有得到它。

这是我的代码 将张量流导入为 tf 将 numpy 导入为 np 从张量流导入keras

model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs = np.array([-1.0,  0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))

我收到如下错误: enter image description here

【问题讨论】:

  • 请使用三个反引号格式化代码并将所有代码直接添加到问题中(无图像)。

标签: python tensorflow keras


【解决方案1】:

我认为您提到input_shape 的第一层有一个错字。当您有一个维度时,逗号(,)是必要的。在引擎盖下,模型将添加批次维度。但是,如果您的 input_shape 中有两个或多个维度,则最后不需要逗号 ,。所以更改以下行

model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=(1,))]) 

这是您更新后的适用于我的完整代码。

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

model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=(1,))]) 
model.compile(optimizer='sgd', loss='mean_squared_error')

xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) 
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)

model.fit(xs, ys, epochs=50)

print(model.predict([10.0]))

【讨论】:

    【解决方案2】:

    输入形状应该是 (1,) 而不是 [1]。

    model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=(1,))])
    

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 2021-04-10
      • 2020-10-30
      • 2020-09-06
      • 2020-09-26
      • 2018-11-23
      相关资源
      最近更新 更多