python - 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))
任何帮助深表感谢!
解决方案
如果我正确理解您的问题,您似乎想要执行批量矩阵乘法和加法(乘法,分别加法,x
堆叠在第一个维度上的一批元素,W1
然后Wf
,分别与b1
then 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)
推荐阅读
- go - 语法错误:函数体之外的非声明语句,但所有内容都有声明
- php - 从 PHP 中的回调函数中跳出循环
- python - 以下等式在 python x=4**3**5**7 中如何工作。有人可以解释一下它的执行顺序吗?
- css - 带有css的响应式lightroom风格网格?
- vb.net - 第二次显示后未调用表单显示
- python - 我在梯度下降中遇到问题,它给我的 thetas 没有
- android - 如何平滑离散数据点以使其看起来连续?
- redis - Redis位图split key分割策略
- html - 部署 react/express 应用程序后出现内容安全策略错误
- php - 是否可以在 PHP 中放置两个表单并保存两个 cookie 值?