一、搭建简单的CNN做序列标注代码

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt TIME_STEPS = 15# backpropagation through time 的time_steps
BATCH_SIZE = 1#50
INPUT_SIZE = 1 # x数据输入size
LR = 0.05 # learning rate
num_tags = 2
# 定义一个生成数据的 get_batch function:
def get_batch():
xs = np.array([[[[2], [3], [4], [5], [5], [5], [1], [5], [3], [2], [5], [5], [5], [3], [5]]]])
res = np.array([[0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1]])
ys = np.zeros([1,TIME_STEPS,2])
for i in range(TIME_STEPS):
if(res[0,i] == 0):
ys[0,i,0] = 1
ys[0,i,1] = 0
else:
ys[0,i,0] = 0
ys[0,i,1] = 1 return [xs, res,ys] # 定义 CNN 的主体结构
class CNN(object):
def __init__(self, n_steps, input_size, num_tags, batch_size):
self.n_steps = n_steps
self.input_size = input_size
self.num_tags = num_tags
self.batch_size = batch_size
#卷积神将网络的输入:[batch, in_height, in_width, in_channels],在自然语言处理中height为1
self.xs = tf.placeholder(tf.float32, [self.batch_size,1, self.n_steps, self.input_size], name='xs')
#做序列标注,第二维对应好输入的n_steps,相当于每个时刻的输入都有一个输出
self.ys = tf.placeholder(tf.int32, [self.batch_size, self.n_steps,self.num_tags], name='ys')# self.featureNum = 10#提取10个特征 #[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数]
W_conv1 = self.weight_variable([1,3,1,self.featureNum])#提取10个特征
#对应10个卷积核输出
b_conv1 = self.bias_varibale([self.featureNum]) #卷积操作
layer_conv1 = tf.nn.conv2d(self.xs, W_conv1,strides=[1, 1, 1, 1],padding="SAME",) + b_conv1
#激励层
layer_conv1 = tf.nn.relu(layer_conv1)
#最大值池化 本处去除池化层为了后续计算简便
#layer_pool1 = tf.nn.max_pool(layer_conv1,
# [1, 1, 3, 1],[1,1,1,1],padding='VALID')
layer_pool1 = layer_conv1 # 全连接层 映射到self.n_steps x self.num_tags
layer_pool1 = tf.reshape(layer_pool1,[self.n_steps,self.featureNum])
W_fc1 = self.weight_variable([self.featureNum,self.num_tags])
b_fc1 = self.bias_varibale([self.num_tags])
h_fc1 = tf.matmul(layer_pool1, W_fc1) + b_fc1
#激励层
h_fc1 = tf.nn.relu(h_fc1)
#softmax 归一化
self.y_conv = tf.nn.softmax(h_fc1)
self.label = tf.reshape(self.ys,[self.n_steps,2])
self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.label, logits=self.y_conv))
#梯度下降
self.train_op = tf.train.AdamOptimizer(LR).minimize(self.cost)
self.pred = tf.argmax(self.y_conv,axis = 1) def weight_variable(self,shape):
initial=tf.truncated_normal(shape, mean=0.0, stddev=0.1)
return tf.Variable(initial)
def bias_varibale(self,shape):
initial=tf.constant(0,1,shape=shape)
return tf.Variable(initial) # 训练CNN
if __name__ == '__main__': # 搭建 CNN 模型
model = CNN(TIME_STEPS, INPUT_SIZE, num_tags, BATCH_SIZE)
sess = tf.Session()
sess.run(tf.global_variables_initializer()) # matplotlib可视化
plt.ion() # 设置连续 plot
plt.show()
# 训练多次
for i in range(150):
xs, res,ys = get_batch() # 提取 batch data
# 初始化 data
feed_dict = {
model.xs: xs,
model.ys: ys,
}
# 训练
_, cost,pred = sess.run(
[model.train_op, model.cost, model.pred],
feed_dict=feed_dict) # plotting x = xs.reshape(-1,1)
r = res.reshape(-1, 1)
p = pred.reshape(-1, 1) x = range(len(x)) plt.clf()
plt.plot(x, r, 'r', x, p, 'b--')
plt.ylim((-1.2, 1.2))
plt.draw()
plt.pause(0.3) # 每 0.3 s 刷新一次 # 打印 cost 结果
if i % 20 == 0:
print('cost: ', round(cost, 4))

  得到结果:

二、CNN主要知识点

  待整理。

CNN做序列标注问题(tensorflow)的更多相关文章

  1. DL4NLP —— 序列标注:BiLSTM-CRF模型做基于字的中文命名实体识别

    三个月之前 NLP 课程结课,我们做的是命名实体识别的实验.在MSRA的简体中文NER语料(我是从这里下载的,非官方出品,可能不是SIGHAN 2006 Bakeoff-3评测所使用的原版语料)上训练 ...

  2. 用CRF++开源工具做文本序列标注教程

    本文只介绍如何快速的使用CRF++做序列标注,对其中的原理和训练测试参数不做介绍. 官网地址:CRF++: Yet Another CRF toolkit 主要完成如下功能: 输入 -> &qu ...

  3. 序列标注(HMM/CRF)

    目录 简介 隐马尔可夫模型(HMM) 条件随机场(CRF) 马尔可夫随机场 条件随机场 条件随机场的特征函数 CRF与HMM的对比 维特比算法(Viterbi) 简介 序列标注(Sequence Ta ...

  4. BiLSTM:序列标注任务的标杆

    Bidirectional LSTM-CRF Models for Sequence Tagging. Zhiheng Huang. 2015 在2015年,本文第一个提出使用BiLSTM-CRF来做 ...

  5. TensorFlow (RNN)深度学习 双向LSTM(BiLSTM)+CRF 实现 sequence labeling 序列标注问题 源码下载

    http://blog.csdn.net/scotfield_msn/article/details/60339415 在TensorFlow (RNN)深度学习下 双向LSTM(BiLSTM)+CR ...

  6. 转:TensorFlow入门(六) 双端 LSTM 实现序列标注(分词)

    http://blog.csdn.net/Jerr__y/article/details/70471066 欢迎转载,但请务必注明原文出处及作者信息. @author: huangyongye @cr ...

  7. TensorFlow教程——Bi-LSTM+CRF进行序列标注(代码浅析)

    https://blog.csdn.net/guolindonggld/article/details/79044574 Bi-LSTM 使用TensorFlow构建Bi-LSTM时经常是下面的代码: ...

  8. 序列标注(BiLSTM-CRF/Lattice LSTM)

    前言 在三大特征提取器中,我们已经接触了LSTM/CNN/Transormer三种特征提取器,这一节我们将介绍如何使用BiLSTM实现序列标注中的命名实体识别任务,以及Lattice-LSTM的模型原 ...

  9. Bi-LSTM+CRF在文本序列标注中的应用

    传统 CRF 中的输入 X 向量一般是 word 的 one-hot 形式,前面提到这种形式的输入损失了很多词语的语义信息.有了词嵌入方法之后,词向量形式的词表征一般效果比 one-hot 表示的特征 ...

随机推荐

  1. 在Spring(4.3.22)中集成Hibernate(5.4.0)

    (1)pom中添加相关依赖 <dependency> <groupId>org.hibernate</groupId> <artifactId>hibe ...

  2. 单页应用 WebApp SPA 骨架 框架 路由 页面切换 转场

    这里收录三个同类产品,找到他们花了我不少时间呢. 张鑫旭写的mobilebone自述:mobile移动端,PC桌面端页面无刷新过场JS骨架,简单.专注!http://www.zhangxinxu.co ...

  3. python 语言特性

    动态强类型: 动态类型语言:在运行期进行类型检查的语言,也就是在编写代码的时候可以不指定变量的数据类型,比如Python和Ruby 静态类型语言:它的数据类型是在编译期进行检查的,也就是说变量在使用前 ...

  4. centos6环境创建局域网http方式的yum源

    环境: yum服务器:centos 6.3 :192.168.8.20 yum源客户端:centos6.5 使用的主要rpm包来自centos6.5光盘 yum源服务器端配置: 1. 首先需要检查一下 ...

  5. 解决报错error the @annotation pointcut expression is only supported at Java 5

    eclipse搭建环境后报错 error the @annotation pointcut expression is only supported at Java 5 错误意思大致是:注释切入点表达 ...

  6. MyEclipse中如何配置默认jsp为UTF-8格式

  7. Linux多台机器配置ssh免登录

    .安装ssh. sudo apt-get install ssh. 安装完成后会在~目录(当前用户主目录,即这里的/home/xuhui)下产生一个隐藏文件夹.ssh(ls -a 可以查看隐藏文件). ...

  8. Java中日期格式化SimpleDateFormat类包含时区的处理方法

    1.前言 需要把格式为“2017-02-23T08:04:02+01:00”转化成”23-02-2017-T15:04:02“格式(中国时区为+08:00所以是15点),通过网上查找答案,发现没有我需 ...

  9. SpringMVC(4.2):Controller接口控制器详解(2)

    原文出处: 张开涛 4.5.ServletForwardingController 将接收到的请求转发到一个命名的servlet,具体示例如下: package cn.javass.chapter4. ...

  10. cf 1041C双指针

    比赛的时候想着用单调队列做... 打完发现其实就是个双指针 /* 构造双指针解决即可 */ #include<iostream> #include<cstring> #incl ...