基于Tensorflow一维卷积用法详解
作者:星夜孤帆 发布时间:2022-12-31 20:04:18
标签: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的shape
以下是input_shape=(1,10,1), w = (3,1,3)时,conv1的shape
补充知识: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'只在输入的末尾填充0
tf.layters.conv1d:
函数形式:tf.layters.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) #池化后进行拼接
来源:https://blog.csdn.net/qq_38826019/article/details/80661260


猜你喜欢
- 问题一个已经有内容的 textarea 元素,在执行该元素的 .focus() 方法后,不同的浏览器有不同表现。我们的预期是能够出现在内容后
- <script>function getJsFile(url, callBack){
- 这是个“懒人”用的办法,你没有时间更新主页,却又不能让三个月前的更新还标着"new",那么用这个js可以帮你的大忙!这个
- 1.format() 基本用法python2.6 开始,新增了一种格式化字符串的函数str.format(),它增强了字符串格式化的功能基本
- 目录1、requests项目单元测试状况2、简单工具类如何测试2.1 test_help 实现分析2.2 test_hooks 实现分析2.
- 1. 数据抽取的概念2. 数据的分类3. JSON数据概述及解析3.1 JSON数据格式3.2 解析库jsonjson模块是Python内置
- 上传问题可以说是网络编程中经常遇到的,也是一个很重要的问题,我们不仅要实现上传文件,图片等基本功能,还有考虑到上传程序的安全性,本文介绍了一
- python一直被病垢运行速度太慢,但是实际上python的执行效率并不慢,慢的是python用的解释器Cpython运行效率太差。“一行代
- 最近开发微信公众号内嵌H5页面,使用vue搭建的项目,由于业务需求,需要实现微信自定义分享功能,所以项目中集成微信JS-SDK。微信JS-S
- np.zeros()和np.ones()函数由于小阿奇在写代码的时候会碰到一些不清楚的函数和使用方法,所以我决定把自己碰到的问题和解决办法写
- 用了这么多年的CSS,现在才明白CSS的真正匹配原理,不知道你是否也跟我一样?看1个简单的CSS:DIV#divBox p span.red
- Mac 安装Mysql有许多开发的小伙伴,使用的是mac,那么在mac上如何安装Mysql呢?这篇文章就给大家说说。1、首先,登陆Mysql
- 前言 绝大多数的Oracle数据库性能问题都是由于数据库设计不合理造成的,只有少部分问题根植于Database Buffer、Share P
- 1、线程池模块引入from concurrent.futures import ThreadPoolExecutor2、使用线程池一个简单的
- 本文实例讲述了Python Excel表格创建乘法表。分享给大家供大家参考,具体如下:题目如下:创建程序multiplicationTabl
- 本文主要列出来python图形开发GUI库pyqt5的窗体,控件属性与方法如果你想看看python图形开发GUI库pyqt5的基础使用方法可
- 昨天晚上群里有朋友采集网页时发现file_get_contents 获得的网页保存到本地为乱码,响应的header 里 Content-En
- Python内建的filter()函数用于过滤序列。和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,fil
- csv是Comma-Separated Values的缩写,是用文本文件形式储存的表格数据,比如如下的表格就可以存储为csv文件,文件内容是
- 本文实例讲述了Python贪心算法。分享给大家供大家参考,具体如下:1. 找零钱问题:假设只有 1 分、 2 分、五分、 1 角、二角、 五