cnn-crf命名实体识别代码
时间: 2023-07-28 08:06:53 浏览: 135
基于门控CNN-CRF的中文命名实体识别
5星 · 资源好评率100%
以下是一个使用CNN-CRF模型进行命名实体识别的代码示例:
```python
import tensorflow as tf
import numpy as np
class CNN_CRF(object):
def __init__(self, sequence_length, num_classes, vocab_size, embedding_size, filter_sizes, num_filters, hidden_dim, l2_reg_lambda=0.0):
self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x")
self.input_y = tf.placeholder(tf.int32, [None, sequence_length], name="input_y")
self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")
self.sequence_length = sequence_length
l2_loss = tf.constant(0.0)
with tf.name_scope("embedding"):
self.W = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0), name="W")
self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)
pooled_outputs = []
for i, filter_size in enumerate(filter_sizes):
with tf.name_scope("conv-maxpool-%s" % filter_size):
filter_shape = [filter_size, embedding_size, 1, num_filters]
W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
conv = tf.nn.conv2d(
self.embedded_chars_expanded,
W,
strides=[1, 1, 1, 1],
padding="VALID",
name="conv")
h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
pooled = tf.nn.max_pool(
h,
ksize=[1, sequence_length - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
pooled_outputs.append(pooled)
num_filters_total = num_filters * len(filter_sizes)
h_pool = tf.concat(pooled_outputs, 3)
self.h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])
with tf.name_scope("dropout"):
self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)
with tf.name_scope("output"):
W = tf.get_variable(
"W",
shape=[num_filters_total, hidden_dim],
initializer=tf.contrib.layers.xavier_initializer())
b = tf.Variable(tf.constant(0.1, shape=[hidden_dim]), name="b")
self.hidden_output = tf.nn.xw_plus_b(self.h_drop, W, b, name="hidden_output")
self.hidden_output_expanded = tf.expand_dims(self.hidden_output, -1)
with tf.name_scope("crf"):
self.transition_params = tf.Variable(tf.random_uniform([num_classes, num_classes], -0.1, 0.1), name="transition_params")
self.log_likelihood, self.transition_params = tf.contrib.crf.crf_log_likelihood(
self.hidden_output,
self.input_y,
self.sequence_length,
self.transition_params)
self.loss = tf.reduce_mean(-self.log_likelihood)
with tf.name_scope("accuracy"):
self.prediction = tf.argmax(self.hidden_output, 1, name="prediction")
correct_predictions = tf.equal(self.prediction, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
self.params = [param for param in tf.trainable_variables() if 'embedding' not in param.name]
l2_reg_lambda = tf.constant(l2_reg_lambda)
l2_loss += tf.nn.l2_loss(W)
l2_loss += tf.nn.l2_loss(b)
self.loss += l2_reg_lambda * l2_loss
```
这里使用的是TensorFlow框架,模型结构包括了卷积神经网络和条件随机场。其中,卷积神经网络用于提取输入句子中的特征,而条件随机场则用于对提取到的特征进行标注,得到最终的命名实体识别结果。
阅读全文