2016-09-06 12 views

उत्तर

22

माध्य और भिन्नता प्राप्त करने के लिए बस tf.nn.moments का उपयोग करें।

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

के लिए अधिक पर tf.nn.moments पैरामीटर देखने docs

+0

मैं इस C++ एपीआई कैसे प्राप्त कर सकते हैं? –

+0

मुझे केवल सी ++ एपीआई में अर्थ के लिए प्रलेखन दिखाई देता है: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/mean मुझे लगता है कि आपको स्वयं को भिन्नता की गणना करनी होगी। योग [(x- u)^2] आप पाइथन स्रोत कोड के माध्यम से खोदने में सक्षम हो सकते हैं कि वे बैक एंड को कैसे कॉल करते हैं यह देखने के लिए कि भिन्नता को और अधिक कुशलतापूर्वक गणना कैसे करें। – Steven

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 –

संबंधित मुद्दे