如何计算TensorFlow中张量的加权和?

时间:2018-02-07 08:50:44

标签: python tensorflow

我想计算张量的每一行的加权和,权重是元素,另一个乘数是列号。示例吹:

input:
[[0.2 0.5 0.3],
 [0.4 0.1 0.5]]

output:
[0.2*0+0.5*1+0.3*2, 0.4*0+0.1*1+0.5*2] = [1.1, 1.1]

我该怎么做?

2 个答案:

答案 0 :(得分:3)

这是内在产品的定义。使用numpy.dot

data=[[0.2, 0.5, 0.3], [0.4, 0.1, 0.5]]
np.dot(data,range(len(data)+1))
array([ 1.1,  1.1])

答案 1 :(得分:1)

以下代码应该有效:

import tensorflow as tf
import numpy as np


a = np.array([[0.2, 0.5, 0.3], [0.4, 0.1, 0.5]])

x = tf.placeholder(tf.float64, [2, 3])

# weighted_sum_op = tf.reduce_sum(x * np.arange(0, a.shape[1]), 1,)

# or if you want to have the range in the TensorFlow graph:
weighted_sum_op = tf.reduce_sum(x * tf.range(0., tf.cast(tf.shape(x)[1], tf.float64)), 1, )

# You ccould also make use of tf.py_func
# weighted_sum_op = tf.py_func(lambda y: np.dot(y, np.arange(0, y.shape[1])), [x], tf.float64)

with tf.Session() as sess:
    print(sess.run(weighted_sum_op, {x: a}))