无法在Tensorflow中运行tf.math.reduce\u std和tf.math.reduce\u方差?(错误:输入必须是实的或复杂的)

2024-03-29 10:45:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我对计算充满随机变量的张量的标准差和方差有一个问题。它抛出一条与输入错误相关的消息

下面是我的代码片段,如下所示

# Create a tensor with 50 random values between 0 and 100
E = tf.constant(np.random.randint(low=0, high=100, size=50))
print(E)

# Calculate the standard deviation and variance
print(tf.math.reduce_std(E))
print(tf.math.reduce_variance(E))

这是控制台上显示的错误消息

Traceback (most recent call last):
  File "C:\Users\Noyan\PycharmProjects\1_Fundementals_of_Tensorflow\001_introduction_to_tensors.py", line 515, in <module>
    print(tf.math.reduce_std(E))
  File "C:\Users\User\PycharmProjects\1_Fundementals_of_Tensorflow\venv\lib\site-packages\tensorflow\python\util\dispatch.py", line 206, in wrapper
    return target(*args, **kwargs)
  File "C:\Users\User\PycharmProjects\1_Fundementals_of_Tensorflow\venv\lib\site-packages\tensorflow\python\ops\math_ops.py", line 2558, in reduce_std
    variance = reduce_variance(input_tensor, axis=axis, keepdims=keepdims)
  File "C:\Users\User\PycharmProjects\1_Fundementals_of_Tensorflow\venv\lib\site-packages\tensorflow\python\util\dispatch.py", line 206, in wrapper
    return target(*args, **kwargs)
  File "C:\Users\User\PycharmProjects\1_Fundementals_of_Tensorflow\venv\lib\site-packages\tensorflow\python\ops\math_ops.py", line 2499, in reduce_variance
    raise TypeError("Input must be either real or complex")
TypeError: Input must be either real or complex

我怎样才能修好它


Tags: ofinpyreducetftensorflowlinemath
2条回答

对于tf.math.reduce_stdtf.math.reduce_variance输入张量必须是实数或复数类型。因此,只需将数据转换为float,然后再传递给以下函数:

E = tf.constant(np.random.randint(low=0, high=100, size=50))
print(E)

# Add this line
E = tf.cast(E, dtype=tf.float32) # Convert to float 32

print(tf.math.reduce_std(E))
print(tf.math.reduce_variance(E))

要找到张量的方差,我们需要访问tensorflow_probability

import tensorflow_probability as tfp

tfp.stats.variance(E)

如果您使用下面的代码,请在传递到这些函数之前将数据转换为float,如下所示

tf.math.reduce_variance(tf.cast(E, dtype=tf.float32))  

要找到标准偏差,请在传递到这些函数之前将数据转换为float

tfp.stats.stddev(tf.cast(E, dtype=tf.float32))

tf.math.reduce_std(tf.cast(E, dtype=tf.float32))

相关问题 更多 >