首页 > 解决方案 > Tensorflow - 拆分,操作,然后求和 2D 数据点

问题描述

我正在使用 tensorflow 解决一个问题,我想将相同的张量运算应用于 2d 数据集中的所有 1d 数据,然后将这些操作的结果加在一起。

例如,假设我有一个数据点:

x0 = [[1, 0, 1, 1],
      [0, 1, 1, 0],
      [1, 2, 0, 1],
      [0, 2, 2, 0]]

和张量运算(函数可能是更准确的术语)f(x)

我想做类似的事情

y = sum([f(x) for x in x0]

我在 TF 中正确表达这一点有点困难。我认为我得到的最接近的是下面。

x = tf.placeholder(tf.float32, [None, 10, 10])

x_sub = tf.placeholder(tf.float32, [None, 10])

W1 = weight_variable([10, 10])
b1= bias_variable([10])

l1 = tf.nn.relu(tf.matmul(x_sub, W1) + b1)

Wf = weight_variable([10, 1])
bf = bias_variable([1])

y_sub = tf.matmul(l1, Wf) + bf

y = ? # I would like to split/unstack x here, apply y_sub to each
      # tensor resulting from the split (shaped [None, 10]) and then
      # add the results together

y_ = tf.placeholder(tf.float32, [None, 1]) 

cross_entropy = tf.reduce_mean(tf.losses.mean_squared_error(y_, y))

任何帮助深表感谢!

标签: pythontensorflow

解决方案


如果我正确理解您的问题,您似乎想要执行批量矩阵乘法和加法(乘法,分别加法,x堆叠在第一个维度上的一批元素,W1然后Wf,分别与b1then bf)。

这可以通过一些手动或自动广播直接完成:

x = tf.placeholder(tf.float32, [None, 10, 10])
x_shape = tf.shape(x)

W1 = weight_variable([10, 10])
b1 = bias_variable([10])

# We broadcast W1 into a tensor of shape (None, 10, 10), for performed batched matmul:
W1_exp = tf.tile(tf.expand_dims(W1, 0), (x_shape[0], 1, 1))
l = tf.nn.relu(tf.matmul(x, W1_exp) + b1)
# note: broadcasting is straightforward and covered for the addition with b1

Wf = weight_variable([10, 1])
bf = bias_variable([1])

# Similarly, we broadcast Wf beforehand:
Wf_exp = tf.tile(tf.expand_dims(Wf, 0), (x_shape[0], 1, 1))
y = tf.matmul(l, Wf_exp) + bf

# Summing over the dimension #1:
y = tf.reduce_sum(y, axis=1)

推荐阅读