无法在 Tensorflow 中运行 tf.math.reduce_std 和 tf.math.reduce_variance?(错误:输入必须是实数或复数)

2 python tensorflow

我在计算填充随机变量的张量的标准差和方差时遇到问题。它抛出一条与输入错误相关的消息。

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

# 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))
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

我该如何修复它?

Kav*_*veh 11

对于tf.math.reduce_std输入tf.math.reduce_variance张量必须是实数或复数类型。因此,只需将数据转换为浮点数,然后再传递给这些函数,如下所示:

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))
Run Code Online (Sandbox Code Playgroud)