基于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
0
投稿
猜你喜欢
- 前言加密技术在数据安全存储,数据传输中发挥着重要作用,能够保护用户隐私数据安全,防止信息窃取。RSA是一种非对称加密技术,在软件、网页中已得
- 本文实例讲述了python获取一组汉字拼音首字母的方法。分享给大家供大家参考。具体实现方法如下:#!/usr/bin/env python
- 前言format语法格式:str.format()str是指字符串实例对象,常用格式为‘ ’.for
- 一、为什么要安装虚拟环境 情景一、项目A需要某个库的1.0版本,项目B需要这个库的2.0版本。如果没有安装虚拟环境
- python下os模块强大的重命名方法renames详解 在python中有很多强大的模块,其中我们经常要使用的就是OS模块,OS
- 众所周知,在设计爬虫时,最麻烦的一步就是对网页元素进行分析,目前流行的网页元素获取的工具有BeautifulSoup,lxml等
- cupy我觉得可以理解为cuda for numpy,安装方式pip install cupy,假设import numpy as npim
- 工作中遇到一个问题,两个字符串匹配,要求:每个字符串中最多含有一个*,?可以无限多个*代表一个任意长度的字符串,而?则代表一个字符要求可以提
- 这两个字符串真实长度和取固定长度的字符串函数是在 photo.163.com 的js文件里看到的。 作者&nb
- 本次系统环境os: Deepin(Linux)Python: 3.7lib: PyYAML=5.3.1 | selenium=3.141.0
- 最近学到了一个有趣的装饰器写法,就记录一下。装饰器是一个返回函数的函数。写一个装饰器,除了最常见的在函数中定义函数以外,Python还允许使
- ASP里两种常用的生成文件的方式是:利用ADODB.Stream生成文件和利用Scripting.FileSystemObject(fso)
- Eloquent: 关联模型简介数据库中的表经常性的关联其它的表。比如,一个博客文章可以有很多的评论,或者一个订单会关联一个用户。Eloqu
- 本文实例讲述了python使用pil生成缩略图的方法。分享给大家供大家参考。具体分析如下:这段代码实现python通过pil生成缩略图的功能
- 一、私有化上篇说过封装,既将我们不想让别人看到代码的内容,但是又需要用到的内容,通过类内部调用来实现调用。说到这里却不得不提一下上篇的:cl
- 一、弹窗事件是什么?弹窗事件就是在我们执行某操作的时候,弹出信息框给出提示。或收集数据的时候,弹出窗口收集信息,不想收集可以取消隐藏。二、简
- 假如某个电脑生产商,它的数据库中保存着整机和配件的产品信息。用来保存整机产品信息的表叫做pc;用来保存配件供货信息的表叫做parts。在pc
- 1 Git简介Git 是目前世界上最先进的分布式版本控制系统(没有之一)作用: 源代码管理为什么要进行源代码管理?
- 这篇博客将介绍如何使用Python,OpenCV对图像进行平移转换。平移是图像沿x轴和y轴的移动。使用平移,可以将图像上下左右移动,以及上述
- 本文实例讲述了Python基于回溯法子集树模板解决0-1背包问题。分享给大家供大家参考,具体如下:问题给定N个物品和一个背包。物品i的重量是