Python TensorFlow中np.std()的等价物是什么?
只需寻找TensorFlow中np.std()的等价物即可计算张量的标准偏差。要获得均值和方差,只需使用Python TensorFlow中np.std()的等价物是什么?,python,tensorflow,Python,Tensorflow,只需寻找TensorFlow中np.std()的等价物即可计算张量的标准偏差。要获得均值和方差,只需使用tf.nn.moments mean, var = tf.nn.moments(x, axes=[1]) 有关tf.nn.moments参数的更多信息,请参见,您也可以在以下改编自Keras的代码中使用reduce_std: #coding=utf-8 import numpy as np import tensorflow as tf def reduce_var(x, axis=Non
tf.nn.moments
mean, var = tf.nn.moments(x, axes=[1])
有关
tf.nn.moments
参数的更多信息,请参见,您也可以在以下改编自Keras的代码中使用reduce_std
:
#coding=utf-8
import numpy as np
import tensorflow as tf
def reduce_var(x, axis=None, keepdims=False):
"""Variance of a tensor, alongside the specified axis.
# Arguments
x: A tensor or variable.
axis: An integer, the axis to compute the variance.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`,
the reduced dimension is retained with length 1.
# Returns
A tensor with the variance of elements of `x`.
"""
m = tf.reduce_mean(x, axis=axis, keep_dims=True)
devs_squared = tf.square(x - m)
return tf.reduce_mean(devs_squared, axis=axis, keep_dims=keepdims)
def reduce_std(x, axis=None, keepdims=False):
"""Standard deviation of a tensor, alongside the specified axis.
# Arguments
x: A tensor or variable.
axis: An integer, the axis to compute the standard deviation.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`,
the reduced dimension is retained with length 1.
# Returns
A tensor with the standard deviation of elements of `x`.
"""
return tf.sqrt(reduce_var(x, axis=axis, keepdims=keepdims))
if __name__ == '__main__':
x_np = np.arange(10).reshape(2, 5).astype(np.float32)
x_tf = tf.constant(x_np)
with tf.Session() as sess:
print(sess.run(reduce_std(x_tf, keepdims=True)))
print(sess.run(reduce_std(x_tf, axis=0, keepdims=True)))
print(sess.run(reduce_std(x_tf, axis=1, keepdims=True)))
print(np.std(x_np, keepdims=True))
print(np.std(x_np, axis=0, keepdims=True))
print(np.std(x_np, axis=1, keepdims=True))
如何在C++ API中实现这一点?我只看到C++中的均值的文档:我想你必须自己计算变量。sum[(x-u)^2]您可能可以深入了解python源代码,了解它们如何调用后端,以了解如何更有效地计算方差。注意:这计算的是均值和“方差”,而不是“标准差”。我使用的是tf1.4,tf.nn。出于某些原因,矩量不能给出正确的结果。。。我尝试了你的版本,第一次就成功了:)+1如果我想将其用作丢失函数,是否需要将keepdims设置为True?