【问题标题】:Unexpected result when using TensorFlow matmul, dtype=tf.float32使用 TensorFlow matmul 时出现意外结果,dtype=tf.float32
【发布时间】:2021-09-28 01:32:39
【问题描述】:

使用张量流 2.3.0,python 3.8.11。

代码如下:

a = tf.constant([2, 2, 3, 3], shape=[2, 2], dtype=tf.float32)
print('-------------------')
print(a)

a2 = tf.matmul(a,a)
print('-------------------')
print(a2)

输出如下(在不同的运行中得到其他错误结果):

-------------------
tf.Tensor(
[[2. 2.]
 [3. 3.]], shape=(2, 2), dtype=float32)
-------------------
tf.Tensor(
[[10. 10.]
 [ 0.  0.]], shape=(2, 2), dtype=float32)

但是如果设置dtype为int32或float64,得到正确的结果,float64结果如下:

-------------------
tf.Tensor(
[[2. 2.]
 [3. 3.]], shape=(2, 2), dtype=float64)
-------------------
tf.Tensor(
[[10. 10.]
 [15. 15.]], shape=(2, 2), dtype=float64)

这是一个错误吗?

【问题讨论】:

    标签: python-3.x tensorflow


    【解决方案1】:

    tf.matmulTensorflow 2.6.0 配合良好。

    import tensorflow as tf
    a = tf.constant([2, 2, 3, 3], shape=[2, 2], dtype=tf.float32)
    print('-------------------')
    print(a)
    
    a2 = tf.matmul(a,a)
    print('-------------------')
    print(a2)
    

    输出

    -------------------
    tf.Tensor(
    [[2. 2.]
     [3. 3.]], shape=(2, 2), dtype=float32)
    -------------------
    tf.Tensor(
    [[10. 10.]
     [15. 15.]], shape=(2, 2), dtype=float32)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 2017-10-04
      • 2020-10-20
      • 1970-01-01
      • 2017-07-29
      • 2018-07-18
      • 2015-05-30
      相关资源
      最近更新 更多