2016-09-06 77 views

Trả lời

22

Để lấy giá trị trung bình và phương sai chỉ cần sử dụng tf.nn.moments.

mean, var = tf.nn.moments(x, axes=[1]) 

Để biết thêm về tf.nn.moments params thấy docs

+0

Làm thế nào tôi có thể đạt được trong C++ API này? –

+0

Tôi chỉ thấy tài liệu về giá trị trung bình trong API C++: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/mean Tôi nghĩ bạn sẽ phải tự tính toán phương sai. sum [(x- u)^2] Bạn có thể khai thác mã nguồn python để biết cách chúng gọi kết thúc sau để xem cách tính toán phương sai hiệu quả hơn. – Steven

3

Bạn cũng có thể sử dụng reduce_std trong đoạn mã sau chuyển thể từ Keras:

#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

Tôi đang sử dụng tf1.4, tf.nn.moments không cung cấp cho tôi một kết quả chính xác vì một số lý do ... Tôi đã thử phiên bản của bạn và nó hoạt động trong lần thử đầu tiên :) +1 –

Các vấn đề liên quan