Tensorflow深度學(xué)習(xí)使用CNN分類(lèi)英文文本
Github源碼地址
本文同時(shí)也是學(xué)習(xí)唐宇迪老師深度學(xué)習(xí)課程的一些理解與記錄。
文中代碼是實(shí)現(xiàn)在TensorFlow下使用卷積神經(jīng)網(wǎng)絡(luò)(CNN)做英文文本的分類(lèi)任務(wù)(本次是垃圾郵件的二分類(lèi)任務(wù)),當(dāng)然垃圾郵件分類(lèi)是一種應(yīng)用環(huán)境,模型方法也可以推廣到其它應(yīng)用場(chǎng)景,如電商商品好評(píng)差評(píng)分類(lèi)、正負(fù)面新聞等。

源碼與數(shù)據(jù)
源碼
- data_helpers.py
- train.py
- text_cnn.py
- eval.py(Save the evaluations to a csv, in case the user wants to inspect,analyze, or otherwise use the classifications generated by the neural net)
數(shù)據(jù)
- rt-polarity.neg
- rt-polarity.pos


train.py 源碼及分析
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from text_cnn import TextCNN
from tensorflow.contrib import learn
# Parameters
# ==================================================
# Data loading params
# 語(yǔ)料文件路徑定義
tf.flags.DEFINE_float("dev_sample_percentage", .1, "Percentage of the training data to use for validation")
tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-polarity.pos", "Data source for the positive data.")
tf.flags.DEFINE_string("negative_data_file", "./data/rt-polaritydata/rt-polarity.neg", "Data source for the negative data.")
# Model Hyperparameters
# 定義網(wǎng)絡(luò)超參數(shù)
tf.flags.DEFINE_integer("embedding_dim", 128, "Dimensionality of character embedding (default: 128)")
tf.flags.DEFINE_string("filter_sizes", "3,4,5", "Comma-separated filter sizes (default: '3,4,5')")
tf.flags.DEFINE_integer("num_filters", 128, "Number of filters per filter size (default: 128)")
tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)")
tf.flags.DEFINE_float("l2_reg_lambda", 0.0, "L2 regularization lambda (default: 0.0)")
# Training parameters
# 訓(xùn)練參數(shù)
tf.flags.DEFINE_integer("batch_size", 32, "Batch Size (default: 32)")
tf.flags.DEFINE_integer("num_epochs", 200, "Number of training epochs (default: 200)") # 總訓(xùn)練次數(shù)
tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)") # 每訓(xùn)練100次測(cè)試一下
tf.flags.DEFINE_integer("checkpoint_every", 100, "Save model after this many steps (default: 100)") # 保存一次模型
tf.flags.DEFINE_integer("num_checkpoints", 5, "Number of checkpoints to store (default: 5)")
# Misc Parameters
tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") # 加上一個(gè)布爾類(lèi)型的參數(shù),要不要自動(dòng)分配
tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") # 加上一個(gè)布爾類(lèi)型的參數(shù),要不要打印日志
# 打印一下相關(guān)初始參數(shù)
FLAGS = tf.flags.FLAGS
FLAGS._parse_flags()
print("\nParameters:")
for attr, value in sorted(FLAGS.__flags.items()):
print("{}={}".format(attr.upper(), value))
print("")
# Data Preparation
# ==================================================
# Load data
print("Loading data...")
x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)
# Build vocabulary
max_document_length = max([len(x.split(" ")) for x in x_text]) # 計(jì)算最長(zhǎng)郵件
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length) # tensorflow提供的工具,將數(shù)據(jù)填充為最大長(zhǎng)度,默認(rèn)0填充
x = np.array(list(vocab_processor.fit_transform(x_text)))
# Randomly shuffle data
# 數(shù)據(jù)洗牌
np.random.seed(10)
# np.arange生成隨機(jī)序列
shuffle_indices = np.random.permutation(np.arange(len(y)))
x_shuffled = x[shuffle_indices]
y_shuffled = y[shuffle_indices]
# 將數(shù)據(jù)按訓(xùn)練train和測(cè)試dev分塊
# Split train/test set
# TODO: This is very crude, should use cross-validation
dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y)))
x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]
y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]
print("Vocabulary Size: {:d}".format(len(vocab_processor.vocabulary_)))
print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev))) # 打印切分的比例
# Training
# ==================================================
with tf.Graph().as_default():
session_conf = tf.ConfigProto(
allow_soft_placement=FLAGS.allow_soft_placement,
log_device_placement=FLAGS.log_device_placement)
sess = tf.Session(config=session_conf)
with sess.as_default():
# 卷積池化網(wǎng)絡(luò)導(dǎo)入
cnn = TextCNN(
sequence_length=x_train.shape[1],
num_classes=y_train.shape[1], # 分幾類(lèi)
vocab_size=len(vocab_processor.vocabulary_),
embedding_size=FLAGS.embedding_dim,
filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), # 上面定義的filter_sizes拿過(guò)來(lái),"3,4,5"按","分割
num_filters=FLAGS.num_filters, # 一共有幾個(gè)filter
l2_reg_lambda=FLAGS.l2_reg_lambda) # l2正則化項(xiàng)
# Define Training procedure
global_step = tf.Variable(0, name="global_step", trainable=False)
optimizer = tf.train.AdamOptimizer(1e-3) # 定義優(yōu)化器
grads_and_vars = optimizer.compute_gradients(cnn.loss)
train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)
# Keep track of gradient values and sparsity (optional)
grad_summaries = []
for g, v in grads_and_vars:
if g is not None:
grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g)
sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g))
grad_summaries.append(grad_hist_summary)
grad_summaries.append(sparsity_summary)
grad_summaries_merged = tf.summary.merge(grad_summaries)
# Output directory for models and summaries
timestamp = str(int(time.time()))
out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp))
print("Writing to {}\n".format(out_dir))
# Summaries for loss and accuracy
# 損失函數(shù)和準(zhǔn)確率的參數(shù)保存
loss_summary = tf.summary.scalar("loss", cnn.loss)
acc_summary = tf.summary.scalar("accuracy", cnn.accuracy)
# Train Summaries
# 訓(xùn)練數(shù)據(jù)保存
train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged])
train_summary_dir = os.path.join(out_dir, "summaries", "train")
train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)
# Dev summaries
# 測(cè)試數(shù)據(jù)保存
dev_summary_op = tf.summary.merge([loss_summary, acc_summary])
dev_summary_dir = os.path.join(out_dir, "summaries", "dev")
dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)
# Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it
checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints"))
checkpoint_prefix = os.path.join(checkpoint_dir, "model")
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints) # 前面定義好參數(shù)num_checkpoints
# Write vocabulary
vocab_processor.save(os.path.join(out_dir, "vocab"))
# Initialize all variables
sess.run(tf.global_variables_initializer()) # 初始化所有變量
# 定義訓(xùn)練函數(shù)
def train_step(x_batch, y_batch):
"""
A single training step
"""
feed_dict = {
cnn.input_x: x_batch,
cnn.input_y: y_batch,
cnn.dropout_keep_prob: FLAGS.dropout_keep_prob # 參數(shù)在前面有定義
}
_, step, summaries, loss, accuracy = sess.run(
[train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy], feed_dict)
time_str = datetime.datetime.now().isoformat() # 取當(dāng)前時(shí)間,python的函數(shù)
print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
train_summary_writer.add_summary(summaries, step)
# 定義測(cè)試函數(shù)
def dev_step(x_batch, y_batch, writer=None):
"""
Evaluates model on a dev set
"""
feed_dict = {
cnn.input_x: x_batch,
cnn.input_y: y_batch,
cnn.dropout_keep_prob: 1.0 # 神經(jīng)元全部保留
}
step, summaries, loss, accuracy = sess.run(
[global_step, dev_summary_op, cnn.loss, cnn.accuracy], feed_dict)
time_str = datetime.datetime.now().isoformat()
print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
if writer:
writer.add_summary(summaries, step)
# Generate batches
batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)
# Training loop. For each batch...
# 訓(xùn)練部分
for batch in batches:
x_batch, y_batch = zip(*batch) # 按batch把數(shù)據(jù)拿進(jìn)來(lái)
train_step(x_batch, y_batch)
current_step = tf.train.global_step(sess, global_step) # 將Session和global_step值傳進(jìn)來(lái)
if current_step % FLAGS.evaluate_every == 0: # 每FLAGS.evaluate_every次每100執(zhí)行一次測(cè)試
print("\nEvaluation:")
dev_step(x_dev, y_dev, writer=dev_summary_writer)
print("")
if current_step % FLAGS.checkpoint_every == 0: # 每checkpoint_every次執(zhí)行一次保存模型
path = saver.save(sess, './', global_step=current_step) # 定義模型保存路徑
print("Saved model checkpoint to {}\n".format(path))
data_helpers.py 源碼及分析
import numpy as np
import re
import itertools
from collections import Counter
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
# 清理數(shù)據(jù)替換掉無(wú)詞義的符號(hào)
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s", string)
string = re.sub(r"\'ve", " \'ve", string)
string = re.sub(r"n\'t", " n\'t", string)
string = re.sub(r"\'re", " \'re", string)
string = re.sub(r"\'d", " \'d", string)
string = re.sub(r"\'ll", " \'ll", string)
string = re.sub(r",", " , ", string)
string = re.sub(r"!", " ! ", string)
string = re.sub(r"\(", " \( ", string)
string = re.sub(r"\)", " \) ", string)
string = re.sub(r"\?", " \? ", string)
string = re.sub(r"\s{2,}", " ", string)
return string.strip().lower()
def load_data_and_labels(positive_data_file, negative_data_file):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
# Load data from files
positive = open(positive_data_file, "rb").read().decode('utf-8')
negative = open(negative_data_file, "rb").read().decode('utf-8')
# 按回車(chē)分割樣本
positive_examples = positive.split('\n')[:-1]
negative_examples = negative.split('\n')[:-1]
# 去空格
positive_examples = [s.strip() for s in positive_examples]
negative_examples = [s.strip() for s in negative_examples]
#positive_examples = list(open(positive_data_file, "rb").read().decode('utf-8'))
#positive_examples = [s.strip() for s in positive_examples]
#negative_examples = list(open(negative_data_file, "rb").read().decode('utf-8'))
#negative_examples = [s.strip() for s in negative_examples]
# Split by words
x_text = positive_examples + negative_examples
x_text = [clean_str(sent) for sent in x_text] # 字符過(guò)濾,實(shí)現(xiàn)函數(shù)見(jiàn)clean_str()
# Generate labels
positive_labels = [[0, 1] for _ in positive_examples]
negative_labels = [[1, 0] for _ in negative_examples]
y = np.concatenate([positive_labels, negative_labels], 0) # 將兩種label連在一起
return [x_text, y]
# 創(chuàng)建batch迭代模塊
def batch_iter(data, batch_size, num_epochs, shuffle=True): # shuffle=True洗牌
"""
Generates a batch iterator for a dataset.
"""
# 每次只輸出shuffled_data[start_index:end_index]這么多
data = np.array(data)
data_size = len(data)
num_batches_per_epoch = int((len(data)-1)/batch_size) + 1 # 每一個(gè)epoch有多少個(gè)batch_size
for epoch in range(num_epochs):
# Shuffle the data at each epoch
if shuffle:
shuffle_indices = np.random.permutation(np.arange(data_size)) # 洗牌
shuffled_data = data[shuffle_indices]
else:
shuffled_data = data
for batch_num in range(num_batches_per_epoch):
start_index = batch_num * batch_size # 當(dāng)前batch的索引開(kāi)始
end_index = min((batch_num + 1) * batch_size, data_size) # 判斷下一個(gè)batch是不是超過(guò)最后一個(gè)數(shù)據(jù)了
yield shuffled_data[start_index:end_index]
text_cnn.py 源碼及分析
import tensorflow as tf
import numpy as np
# 定義CNN網(wǎng)絡(luò)實(shí)現(xiàn)的類(lèi)
class TextCNN(object):
"""
A CNN for text classification.
Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
"""
def __init__(self, sequence_length, num_classes, vocab_size,
embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0): # 把train.py中TextCNN里定義的參數(shù)傳進(jìn)來(lái)
# Placeholders for input, output and dropout
self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x") # input_x輸入語(yǔ)料,待訓(xùn)練的內(nèi)容,維度是sequence_length,"N個(gè)詞構(gòu)成的N維向量"
self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y") # input_y輸入語(yǔ)料,待訓(xùn)練的內(nèi)容標(biāo)簽,維度是num_classes,"正面 || 負(fù)面"
self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob") # dropout_keep_prob dropout參數(shù),防止過(guò)擬合,訓(xùn)練時(shí)用
# Keeping track of l2 regularization loss (optional)
l2_loss = tf.constant(0.0) # 先不用,寫(xiě)0
# Embedding layer
# 指定運(yùn)算結(jié)構(gòu)的運(yùn)行位置在cpu非gpu,因?yàn)?embedding"無(wú)法運(yùn)行在gpu
# 通過(guò)tf.name_scope指定"embedding"
with tf.device('/cpu:0'), tf.name_scope("embedding"): # 指定cpu
self.W = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0), name="W") # 定義W并初始化
self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1) # 加一個(gè)維度,轉(zhuǎn)換為4維的格式
# Create a convolution + maxpool layer for each filter size
pooled_outputs = []
# filter_sizes卷積核尺寸,枚舉后遍歷
for i, filter_size in enumerate(filter_sizes):
with tf.name_scope("conv-maxpool-%s" % filter_size):
# Convolution Layer
filter_shape = [filter_size, embedding_size, 1, num_filters] # 4個(gè)參數(shù)分別為filter_size高h(yuǎn),embedding_size寬w,channel為1,filter個(gè)數(shù)
W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W") # W進(jìn)行高斯初始化
b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b") # b給初始化為一個(gè)常量
conv = tf.nn.conv2d(
self.embedded_chars_expanded,
W,
strides=[1, 1, 1, 1],
padding="VALID", # 這里不需要padding
name="conv")
# Apply nonlinearity 激活函數(shù)
# 可以理解為,正面或者負(fù)面評(píng)價(jià)有一些標(biāo)志詞匯,這些詞匯概率被增強(qiáng),即一旦出現(xiàn)這些詞匯,傾向性分類(lèi)進(jìn)正或負(fù)面評(píng)價(jià),
# 該激勵(lì)函數(shù)可加快學(xué)習(xí)進(jìn)度,增加稀疏性,因?yàn)樽尨_定的事情更確定,噪聲的影響就降到了最低。
h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
# Maxpooling over the outputs
# 池化
pooled = tf.nn.max_pool(
h,
ksize=[1, sequence_length - filter_size + 1, 1, 1], # (h-filter+2padding)/strides+1=h-f+1
strides=[1, 1, 1, 1],
padding='VALID', # 這里不需要padding
name="pool")
pooled_outputs.append(pooled)
# Combine all the pooled features
num_filters_total = num_filters * len(filter_sizes)
self.h_pool = tf.concat(3, pooled_outputs)
self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total]) # 扁平化數(shù)據(jù),跟全連接層相連
# Add dropout
# drop層,防止過(guò)擬合,參數(shù)為dropout_keep_prob
# 過(guò)擬合的本質(zhì)是采樣失真,噪聲權(quán)重影響了判斷,如果采樣足夠多,足夠充分,噪聲的影響可以被量化到趨近事實(shí),也就無(wú)從過(guò)擬合。
# 即數(shù)據(jù)越大,drop和正則化就越不需要。
with tf.name_scope("dropout"):
self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)
# Final (unnormalized) scores and predictions
# 輸出層
with tf.name_scope("output"):
W = tf.get_variable(
"W",
shape=[num_filters_total, num_classes], #前面連扁平化后的池化操作
initializer=tf.contrib.layers.xavier_initializer()) # 定義初始化方式
b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
# 損失函數(shù)導(dǎo)入
l2_loss += tf.nn.l2_loss(W)
l2_loss += tf.nn.l2_loss(b)
# xw+b
self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores") # 得分函數(shù)
self.predictions = tf.argmax(self.scores, 1, name="predictions") # 預(yù)測(cè)結(jié)果
# CalculateMean cross-entropy loss
with tf.name_scope("loss"):
# loss,交叉熵?fù)p失函數(shù)
losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)
self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss
# Accuracy
with tf.name_scope("accuracy"):
# 準(zhǔn)確率,求和計(jì)算算數(shù)平均值
correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")

以上就是Tensorflow深度學(xué)習(xí)CNN實(shí)現(xiàn)英文文本分類(lèi)的詳細(xì)內(nèi)容,更多關(guān)于Tensorflow實(shí)現(xiàn)CNN分類(lèi)英文文本的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信