计算TensorFlow中每个张量行的均值

时间:2018-07-29 11:29:24

标签: python tensorflow

我是张量流的新手,我想从张量计算每一行的均值。 Tensorflow具有tf.reduce_mean操作来执行此操作。问题在于,当一行具有nan值时,该行的均值也为nan。除此之外,我想自己实现这一点,以便更好地理解张量流的哲学。那么我该如何手动实现呢?我写的代码:

import tensorflow as tf
import numpy as np

ratings = np.array([[7, 6, 7, 4, 5, 4], [6, 7, np.NaN, 4, 3, 4], [np.NaN, 3, 3, 1, 1, np.NaN],
                   [1, 2, 2, 3, 3, 4], [1, np.NaN, 1, 2, 3, 3]], dtype = np.float16)

tRatings = tf.convert_to_tensor(ratings, dtype = np.float16)

means = tf.get_variable("means", shape=(5), dtype=tf.float16)


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    mean = tf.reduce_mean(tRatings, axis=1)
    print(sess.run(mean))

1 个答案:

答案 0 :(得分:1)

import tensorflow as tf
import numpy as np
ratings = np.array([[7, 6, 7, 4, 5, 4], [6, 7, np.NaN, 4, 3, 4], [np.NaN, 3, 3, 1, 1, np.NaN],
                       [1, 2, 2, 3, 3, 4], [1, np.NaN, 1, 2, 3, 3]], dtype = np.float16)

tRatings = tf.convert_to_tensor(ratings, dtype = np.float16)
means = tf.get_variable("means", shape=(5), dtype=tf.float16)
with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  #mean = tf.reduce_mean(tRatings, axis=1)
  tRatings_wonan=tf.where(tf.is_nan(tRatings), tf.zeros_like(tRatings), tRatings)
  sum = tf.reduce_sum(tRatings_wonan,axis=1)
  count_nans = tf.reduce_sum(tf.cast(tf.is_nan(tRatings), tf.float16),axis=1)
  mean = tf.div(sum,tf.subtract(tf.cast(tf.shape(tRatings)[1], tf.float16),count_nans))
  print(sess.run(mean))