我有一個形狀的張量[x, y]
並且我想用行標準差減去平均值和除數(即我想對每個行)。 TensorFlow中最有效的方法是什麼?TensorFlow中的有效方法是通過每行的標準偏差減去平均值和除數
當然我可以通過行循環如下:
new_tensor = [i - tf.reduce_mean(i) for i in old_tensor]
...減去平均值,然後做一些類似找到它的標準差和分裂的東西,但這是最好的辦法在TensorFlow中做?
我有一個形狀的張量[x, y]
並且我想用行標準差減去平均值和除數(即我想對每個行)。 TensorFlow中最有效的方法是什麼?TensorFlow中的有效方法是通過每行的標準偏差減去平均值和除數
當然我可以通過行循環如下:
new_tensor = [i - tf.reduce_mean(i) for i in old_tensor]
...減去平均值,然後做一些類似找到它的標準差和分裂的東西,但這是最好的辦法在TensorFlow中做?
The TensorFlow tf.sub()
and tf.div()
運營商支持廣播,所以你不需要遍歷每一行。讓我們考慮的均值,並保留標準差作爲一個練習:
old_tensor = ... # shape = (x, y)
mean = tf.reduce_mean(old_tensor, 1, keep_dims=True) # shape = (x, 1)
stdev = ... # shape = (x,)
stdev = tf.expand_dims(stdev, 1) # shape = (x, 1)
new_tensor = old_tensor - mean # shape = (x, y)
new_tensor = old_tensor/stdev # shape = (x, y)
的減法和除法運算符隱含廣播形狀(x, 1)
沿列維度的張量相匹配的其他參數的形狀,(x, y)
。有關廣播如何工作的詳細信息,請參閱NumPy documentation on the topic(TensorFlow實現NumPy廣播語義)。沿軸1(Y你的情況)
mean, var = tf.nn.moments(old_tensor, [1], keep_dims=True)
new_tensor = tf.div(tf.subtract(old_tensor, mean), tf.sqrt(var))