TensorFlow一维卷积(Conv1D)用法详解与代码示例

Evan
Evan
发布时间:2026-10-13| 5人浏览过
原创

本文详细解析TensorFlow中一维卷积的实现方法,涵盖tf.nn.conv1d与tf.layers.conv1d两个核心函数的参数设置、步长计算及填充策略。通过具体代码示例,展示如何处理语言序列数据,并介绍利用二维卷积模拟一维卷积及多种池化操作的技巧,适用于自然语言处理中的特征提取任务。

TensorFlow一维卷积基础示例

以下内容将直接通过代码示例进行说明,以便更直观地理解一维卷积的具体应用。


import tensorflow as tf
import numpy as np
input = tf.constant(1,shape=(64,10,1),dtype=tf.float32,name='input')#shape=(batch,in_width,in_channels)
w = tf.constant(3,shape=(3,1,32),dtype=tf.float32,name='w')#shape=(filter_width,in_channels,out_channels)
conv1 = tf.nn.conv1d(input,w,2,'VALID') #2为步长
print(conv1.shape)#宽度计算(width-kernel_size+1)/strides ,(10-3+1)/2=4 (64,4,32)
conv2 = tf.nn.conv1d(input,w,2,'SAME') #步长为2
print(conv2.shape)#宽度计算width/strides 10/2=5 (64,5,32)
conv3 = tf.nn.conv1d(input,w,1,'SAME') #步长为1
print(conv3.shape) # (64,10,32)
with tf.Session() as sess:
 print(sess.run(conv1))
 print(sess.run(conv2))
 print(sess.run(conv3))

当输入形状input_shape设定为(1,10,1),且卷积核权重w设定为(3,1,1)时,conv1层的输出形状如下所示。

当输入形状input_shape设定为(1,10,1),且卷积核权重w设定为(3,1,3)时,conv1层的输出形状如下所示。

语言序列处理与核心函数详解

补充说明:在TensorFlow中使用一维卷积conv1d处理语言序列的具体案例。

使用tf.nn.conv1d函数。

该函数的定义形式为:tf.nn.conv1d(value, filters, stride, padding, use_cudnn_on_gpu=None, data_format=None, name=None)。

具体的程序实现示例如下。


import tensorflow as tf
import numpy as np
sess = tf.InteractiveSession()
 
# --------------- tf.nn.conv1d -------------------
inputs=tf.ones((64,10,3)) # [batch, n_sqs, embedsize]
w=tf.constant(1,tf.float32,(5,3,32)) # [w_high, embedsize, n_filers]
conv1 = tf.nn.conv1d(inputs,w,stride=2 ,padding='SAME') # conv1=[batch, round(n_sqs/stride), n_filers],stride是步长。
 
tf.global_variables_initializer().run()
out = sess.run(conv1)
print(out)

需要注意的是,在一维卷积中,当设置padding='SAME'时,系统仅在输入数据的末尾进行零填充。

使用tf.layers.conv1d函数。

该函数的定义形式为:tf.layers.conv1d(inputs, filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, activation=None, use_bias=True,...)。

具体的程序实现示例如下。


import tensorflow as tf
import numpy as np
sess = tf.InteractiveSession()
 
# --------------- tf.layters.conv1d -------------------
inputs=tf.ones((64,10,3)) # [batch, n_sqs, embedsize]
num_filters=32
kernel_size =5
conv2 = tf.layers.conv1d(inputs, num_filters, kernel_size,strides=2, padding='valid',name='conv2') # shape = (batchsize, round(n_sqs/strides),num_filters)
tf.global_variables_initializer().run()
out = sess.run(conv2)
print(out)

二维卷积模拟与池化操作技巧

此外,还可以通过二维卷积来实现一维卷积的功能。


import tensorflow as tf
sess = tf.InteractiveSession()
def conv2d(x, W):
 return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
def max_pool_1x2(x):
 return tf.nn.avg_pool(x, ksize=[1,1,2,1], strides=[1,1,2,1], padding='SAME')
'''
ksize = [x, pool_height, pool_width, x]
strides = [x, pool_height, pool_width, x]
'''
 
x = tf.Variable([[1,2,3,4]], dtype=tf.float32)
x = tf.reshape(x, [1,1,4,1]) #这一步必不可少,否则会报错说维度不一致;
'''
[batch, in_height, in_width, in_channels] = [1,1,4,1]
'''
 
W_conv1 = tf.Variable([1,1,1],dtype=tf.float32) # 权重值
W_conv1 = tf.reshape(W_conv1, [1,3,1,1]) # 这一步同样必不可少
'''
[filter_height, filter_width, in_channels, out_channels]
'''
h_conv1 = conv2d(x, W_conv1) # 结果:[4,8,12,11]
h_pool1 = max_pool_1x2(h_conv1)
tf.global_variables_initializer().run()
print(sess.run(h_conv1)) # 结果array([6,11.5])x

这里介绍两种常见的池化操作方式。


# 1:stride max pooling
convs = tf.expand_dims(conv, axis=-1) # shape=[?,596,256,1]
smp = tf.nn.max_pool(value=convs, ksize=[1, 3, self.config.num_filters, 1], strides=[1, 3, 1, 1],
     padding='SAME') # shape=[?,299,256,1]
smp = tf.squeeze(smp, -1) # shape=[?,299,256]
smp = tf.reshape(smp, shape=(-1, 199 * self.config.num_filters))
 
# 2: global max pooling layer
gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp')

演示不同卷积核尺寸下的卷积操作效果。


kernel_sizes = [3,4,5] # 分别用窗口大小为3/4/5的卷积核
with tf.name_scope("mul_cnn"):
 pooled_outputs = []
 for kernel_size in kernel_sizes:
  # CNN layer
  conv = tf.layers.conv1d(embedding_inputs, self.config.num_filters, kernel_size, name='conv-%s' % kernel_size)
  # global max pooling layer
  gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp')
  pooled_outputs.append(gmp)
 self.h_pool = tf.concat(pooled_outputs, 1) #池化后进行拼接

以上关于TensorFlow一维卷积用法的详解内容分享完毕,希望能为读者提供有价值的参考,欢迎继续支持本站获取更多技术资讯。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。