A-A+

cannot compute Pack as input #1(zero-based) was expected to be a float tensor but is a double tensor [Op:Pack] name: stack

2020年04月19日 16:06 学习笔记 暂无评论 共1809字 (阅读5,324 views次)

【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】

今天在学习TensorFlow2.0的时候,运行脚本报错,似乎是数据类型的问题。先看看代码吧,代码如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# coding: UTF-8
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
 
plt.rcParams['font.sans-serif'] = ['SimHei']
 
x1 = tf.constant(np.array(
    [137.97, 104.50, 100.00, 124.32, 79.20, 99.00, 124.00, 114.00, 106.69, 138.05, 53.75, 46.91, 68.00, 63.02, 81.26,
     86.21]))
x2 = tf.constant(np.array([3, 2, 2, 3, 1, 2, 3, 2, 2, 3, 1, 1, 1, 1, 2, 2]))
 
y = tf.constant(np.array(
    [145.00, 110.00, 93.00, 116.00, 65.32, 104.00, 118.00, 91.00, 62.00, 133.00, 51.00, 45.00, 78.50, 69.65, 75.69,
     95.30]))
x0 = tf.ones(len(x1))
X = tf.stack((x0, x1, x2), axis=1)   #注意在这里报错了
Y = tf.reshape(y, shape=[-1, 1])
 
Xt = tf.transpose(X)
print(Xt)

报错信息如下:

tensorflow.python.framework.errors_impl.InvalidArgumentError: cannot compute Pack as input #1(zero-based) was expected to be a float tensor but is a double tensor [Op:Pack] name: stack

通过报错信息发现,似乎是类型的问题。我们看一下类型。

<x0.dtype: 'float32'> <x1.dtype: 'float64'> <x2.dtype: 'int32'>

既然已经提示报错点,那么我们看一下tf.stack函数。

  Args:
    values: A list of `Tensor` objects with the same shape and type.
    axis: An `int`. The axis to stack along. Defaults to the first dimension.
      Negative values wrap around, so the valid range is `[-(R+1), R+1)`.
    name: A name for this operation (optional).

  Returns:
    output: A stacked `Tensor` with the same type as `values`.

很明显了吧,所以,我们要把所有的数据类型统一即可。那么正确的代码应该是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# coding: UTF-8
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
 
plt.rcParams['font.sans-serif'] = ['SimHei']
 
x1 = tf.constant(np.array(
    [137.97, 104.50, 100.00, 124.32, 79.20, 99.00, 124.00, 114.00, 106.69, 138.05, 53.75, 46.91, 68.00, 63.02, 81.26,
     86.21]), dtype=tf.float32)
x2 = tf.constant(np.array([3, 2, 2, 3, 1, 2, 3, 2, 2, 3, 1, 1, 1, 1, 2, 2]), dtype=tf.float32)
 
y = tf.constant(np.array(
    [145.00, 110.00, 93.00, 116.00, 65.32, 104.00, 118.00, 91.00, 62.00, 133.00, 51.00, 45.00, 78.50, 69.65, 75.69,
     95.30]), dtype=tf.float32)
x0 = tf.ones(len(x1))
 
X = tf.stack((x0, x1, x2), axis=1)
Y = tf.reshape(y, shape=[-1, 1])
 
Xt = tf.transpose(X)
print(Xt)

布施恩德可便相知重

微信扫一扫打赏

支付宝扫一扫打赏

×
标签:

给我留言