tf.conv1d是实现一维卷积,tf.conv2d是实现二维卷积。
当tf.conv2d的输入第二个或第三个维度为1时就等同于一维卷积了,详细见以下代码。
import tensorflow as tf
import numpy as npinput = tf.constant([[[1], [7], [3], [2], [5], [6], [1]], [[11], [17], [13], [12], [15], [16], [11]]], dtype=tf.float32)kernel = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)# Use tf.nn.conv1d
input_con1 = tf.reshape(input, [2, 7, 1])
kernel1 = tf.reshape(kernel, [3, 1, 2])
con1 = tf.nn.conv1d(input_con1, kernel1, 2, 'VALID')# Use tf.nn.conv2d
input_con2 = tf.reshape(input, [2, 1, 7, 1])
kernel2 = tf.reshape(kernel, [1, 3, 1, 2])
con2 = tf.nn.conv2d(input_con2, kernel2, [1, 1, 2, 1], 'VALID')with tf.Session() as sess:print('Out put of conv1d\n', sess.run(con1))print('Out put of conv2d\n', sess.run(con2))
输出结果:
Out put of conv1d[[[14. 21.][15. 17.][13. 19.]][[54. 71.][55. 67.][53. 69.]]]
Out put of conv2d[[[[14. 21.][15. 17.][13. 19.]]][[[54. 71.][55. 67.][53. 69.]]]]