python - Tensorflow - 具有多个通道的 2D 卷积
问题描述
我正在以这种方式定义我的输入和我的内核
import numpy as np
k = np.array([[
[1, 0, 1],
[2, 1, 0],
[0, 0, 1]
],[
[1, 0, 1],
[2, 1, 0],
[0, 0, 1]
]
], dtype=np.float32)
i = np.array([
[4, 3, 1, 0],
[2, 1, 0, 1],
[1, 2, 4, 1],
[3, 1, 0, 2]
], dtype=np.float32)
并将两者卷积使用
import tensorflow as tf
kernel = tf.reshape(k, [3, 3, 1, 2], name='kernel')
image = tf.reshape(i, [1, 4, 4, 1], name='image')
res = tf.squeeze(tf.nn.conv2d(image, kernel, [1, 1, 1, 1], "VALID"))
with tf.Session() as sess:
print sess.run(res)
产生的结果
[[[11. 12.]
[ 8. 6.]]
[[11. 11.]
[ 8. 8.]]]
我想要做的是用一个“子过滤器”执行一个卷积
[
[1, 0, 1],
[2, 1, 0],
[0, 0, 1]
]
超过当时的输入。用笔和纸自己做,我得到
[[[14. 6.]
[ 6. 12.]]
[[14. 6.]
[ 6. 12.]]]
“重塑参数”的所有其他排列都会产生错误,我在 TF 文档中找不到我做错了什么。有谁知道我做错了什么?
解决方案
您只需要tf.transpose
在计算之前和之后使用:
import numpy as np
import tensorflow as tf
k = np.array([[
[1, 0, 1],
[2, 1, 0],
[0, 0, 1]
],[
[1, 0, 1],
[2, 1, 0],
[0, 0, 1]
]
], dtype=np.float32)
i = np.array([
[4, 3, 1, 0],
[2, 1, 0, 1],
[1, 2, 4, 1],
[3, 1, 0, 2]
], dtype=np.float32)
with tf.Graph().as_default(), tf.Session() as sess:
kernel = tf.expand_dims(tf.transpose(k, (1, 2, 0)), 2, name='kernel')
image = tf.reshape(i, [1, 4, 4, 1], name='image')
res = tf.squeeze(tf.nn.conv2d(image, kernel, [1, 1, 1, 1], "VALID"))
res = tf.transpose(res, (2, 0, 1))
print sess.run(res)
输出:
[[[ 14. 6.]
[ 6. 12.]]
[[ 14. 6.]
[ 6. 12.]]]
推荐阅读
- javascript - 删除标签后如何完全停止脚本
- java - Elasticsearch:如何调用must长度与数组不同的Java High Level REST Client
- python - 在 python 中加密与我的 HTTP 代理的连接
- postgresql - 将 Postgresql 11.5 安装到 AIX 7.1 时出错
- javascript - XOR 字符串:JS 与 PHP
- node.js - QueryFailedError:当我尝试使用 typeorm 在 postgres 中插入 json 数组时出现格式错误的数组文字
- java - 尝试在 Chrome 选项上设置功能时,它没有列出 .setCapability 方法
- python-3.x - 在 eval() 中未定义名称“self”
- c++ - boost::icl::interval 和 boost::numeric::interval 是否有可用的适配层?
- php - “在将此参数添加到参数时,无法猜测如何从参数“person_id”的请求信息中获取 Doctrine 实例