只需在TensorFlow中查找等效的np.std()即可计算张量的标准偏差。TensorFlow中np.std()的等价物是什么?
14
A
回答
22
3
您还可以在改编自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))
+0
我使用tf1.4,由于某种原因tf.nn.moments不给我一个正确的结果...我试过你的版本,它在第一次尝试:) +1 –
相关问题
- 1. 什么是numpy.random.multivariate_normal的Tensorflow等价物?
- 2. TensorFlow上一个简单的SGD的CNTK等价物是什么?
- 3. 什么是VC7中的strtok_s等价物?
- 4. 什么是Silverlight中的OnRender等价物?
- 5. C#中TreeBidiMap的等价物是什么?
- 6. 什么是C#中的vbNullChar等价物?
- 7. MySQL中'go'的等价物是什么?
- 8. Bash中%%〜nxD的等价物是什么?
- 9. C#中memset的等价物是什么?
- 10. Monotouch中的CGPDFDocumentGetCatalog等价物是什么?
- 11. C#中bigint的等价物是什么?
- 12. 什么是android中的dataWithContentsOfURL等价物?
- 13. jquery中Ajax.updater的等价物是什么?
- 14. url中的“ - ”等价物是什么?
- 15. 什么是Ruby中的“sys.stdout.write()”等价物?
- 16. wxWidgets中UpdateWindow()的等价物是什么?
- 17. JQuery中innerHTML的等价物是什么?
- 18. Bindingsource中EOF的等价物是什么?
- 19. RDFlib中rdf:ID的等价物是什么?
- 20. python中'gem'的等价物是什么?
- 21. gcc中的#pragma等价物是什么?
- 22. Python中imadjust的等价物是什么?
- 23. python中print_r()的等价物是什么?
- 24. 什么是Python的os.walk的等价物?
- 25. 什么是PHP的preg_quote的等价物?
- 26. MessageFormat的Pattern.quote()的等价物是什么?
- 27. 什么是Win32_OperatingSystem的64位等价物?
- 28. java.time.Duration的Android等价物是什么?
- 29. 什么是“hasOwnProperty()”接口的等价物?
- 30. 什么是JQuery .load()的YUI等价物?
我怎样才能做到这在C++ API? –
我只看到在C++ API中的平均值的文档:https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/mean我想你必须自己计算方差。 sum [(x-u)^ 2]您可能可以通过python源代码了解他们如何调用后端以了解如何更有效地计算方差。 – Steven