【问题标题】:TensorFlow official documentation tutorial error ''numpy.ndarray' object has no attribute 'get_shape'TensorFlow 官方文档教程报错 ''numpy.ndarray' object has no attribute 'get_shape'
【发布时间】:2020-04-27 16:06:08
【问题描述】:

我试图在 TensorFlow 教程 here 上运行确切的代码。

当我排队时:

predictions = model(x_train[:1]).numpy()

我得到错误:

'numpy.ndarray' 对象没有属性'get_shape'

我看到here有人有类似的问题,所以我把这行改为:

predictions = model(tf.convert_to_tensor(x_train[:1])).numpy()

我得到了错误:

输入 'b' of 'MatMul' Op 的 float32 类型与参数 'a' 的 float64 类型不匹配

有人能告诉我教程中应该包含的正确代码吗?还是我这边的问题?

奇怪的是,如果我在提供的 colab 笔记本中运行代码,它就会运行,但如果我下载 jupyter 笔记本在本地运行,就会出现错误。所以我想知道我是否有不同/错误版本的 TensorFlow?

我的包裹:

tensorflow                1.13.1            
tensorflow-base           1.13.1            
tensorflow-estimator      1.13.0                       
python                    3.7.6                 

【问题讨论】:

  • 你安装numpy包了吗?
  • 我做到了,numpy(1.15.4 版)和 numpy-base(1.15.4 版)

标签: python tensorflow numpy-ndarray attributeerror


【解决方案1】:

您所参考的教程在 Tensorflow 2.x 中(默认为 Eager 模式)。在 Eager 模式下,您可以使用 .numpy() 方法访问张量以获取张量的 numpy 值。

在您的本地,您拥有 TensorFlow 1.13.1,它以图形模式运行模型。您可以通过运行会话并评估张量来访问graph tensor(非急切张量)的 numpy 值。 Here 是一个关于 TF1.x 的教程,其中包含 mnist 数据。总体而言,在 TF1.x 中,您需要创建图表、创建占位符、然后运行 ​​Session、将数据提供给占位符、训练模型,然后进行预测。

其他替代方法是通过运行“pip3 install tensorflow==2.1` 来安装 Tensorflow 2.x。安装后,您可以毫无问题地运行示例。

【讨论】:

    【解决方案2】:

    您第一个问题的原因是您的model() 接受tensor 类型参数而不是numpy。而model(x) 称为x.get_shape()
    x.get_shape() 中,x 必须是tensor。因此,您需要将numpy 转换为tensor。您可以使用tf.convert_to_tensor(x)tf.constant(x)


    第二条错误消息是Input 'b' of 'MatMul' Op has type float32 that does not match type float64 of argument 'a'。该消息意味着在a x b a 类型是float64 和b 类型是float32。它们是不同的类型变量,因此不能相乘。您可以尝试使用tf.cast(a,tf.float32) 更改a 的类型或更改b。但是在您的代码中,您应该使用x_train[:1].dtype 来检查x_train[:1] 的类型。如果是 float32,您可以尝试使用 x_train[:1].astype(np.float64) 对其进行转换,反之亦然。或使用tf.constant(x_train[:1],dtype=tf.float64)

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 2022-12-19
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      • 2022-12-01
      • 1970-01-01
      • 2022-12-03
      相关资源
      最近更新 更多