Skip to main content
 首页 » 编程设计

python之Tensorflow之拆分、操作,然后对 2D 数据点求和

2024年09月07日36pander-it

我正在使用 tensorflow 解决一个问题,我想对二维数据集中的所有一维数据应用相同的张量运算,然后将这些运算的结果相加。

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

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)) 

非常感谢任何帮助!

请您参考如下方法:

如果我对你的问题的理解正确,那么你似乎想要执行批量矩阵乘法和加法(乘法,resp。加法,x 中堆叠在第一维上的元素批处理,W1 然后是 Wf,分别是 b1 然后是 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)