利用tensorflow进行单词分类

使用tensorflow进行单词划分类别,依赖于sklearn自带的已经标注好的数据集(有监督学习)

https://www.oschina.net/translate/big-picture-machine-learning?lang=chs&page=1# 参考教程
https://github.com/pursedream/tensorflow_1 完整代码

导入相关包

from collections import Counter
import numpy as np
from sklearn.datasets import fetch_20newsgroups
import tensorflow as tf
import pandas as pd

获取训练数据和测试数据

# 导入sklearn集合中的数据集,有监督学习,即里面的数据已经分好了类别
# 具体参见http://scikit-learn.org/stable/datasets/twenty_newsgroups.html
categories = ["comp.graphics","sci.space","rec.sport.baseball"]
train_set = fetch_20newsgroups(subset='train',categories=categories)
test_set = fetch_20newsgroups(subset='test', categories=categories)
# print('total texts in train:',len(train_set.data))
# print('total texts in test:',len(test_set.data))
# 建立数据集单词字典,最终形式是text_index['the'] = 数量
vocab = Counter()
for data in train_set.data:
    for word in data.split(' '):
        vocab[word.lower()] += 1
for test_data in test_set.data:
    for word in test_data.split(' '):
        vocab[word] += 1
print(len(vocab))
total_words = len(vocab)
def get_index(vocab):
    # 先声明word是字典,否则word[element]报错
    word={}
    for i, element in enumerate(vocab):
        word[element.lower()] = i
    return word
text_index = get_index(vocab)
print("the is %s" % text_index['the'])

神经网络的参数设定

# 每层神经元数,包括输入神经元,隐藏神经元,输出神经元"comp.graphics","sci.space","rec.sport.baseball"
n_hidden1 = 100
n_hiddent2 = 100
n_input_number = total_words
n_class = 3
# 在神经网络的术语里,一次 epoch = 一个向前传递(得到输出的值)和一个所有训练示例的向后传递(更新权重)。
training_epochs = 10
learning_rate = 0.01
# 批数量训练数据和测试数据
batch_size = 150
display_step = 1
# shape的None元素对应于大小可变的维度
# 在测试模型时,我们将用更大的批处理来提供字典,这就是为什么需要定义一个可变的批处理维度。
input_tensor = tf.placeholder(tf.float32, [None, n_input_number], name='input')
output_tensor = tf.placeholder(tf.float32, [None, n_class], name='output')

建立模型

# 神经元计算
def out_prediction(input_tensor, weights, biases):
    # 定义乘法运算矩阵乘法
    # relu是激活函数
    layer_1_multiplication = tf.matmul(input_tensor,weights['h1'])
    layer_1_addition = tf.add(layer_1_multiplication, biases['b1'])
    layer_1_activation = tf.nn.relu(layer_1_addition)

    layer_2_multiplication = tf.matmul(layer_1_activation, weights['h2'])
    layer_2_addition = tf.add(layer_2_multiplication, biases['b2'])
    layer_2_activation = tf.nn.relu(layer_2_addition)

    out_layer_multiplication = tf.matmul(layer_2_activation, weights['out'])
    out_layer_addition = out_layer_multiplication + biases['out']

    return out_layer_addition
# shape参数含义;[]表示一个数,[3]表示长为3的向量,
# [2,3]表示矩阵或者张量(tensor)同一个线性变换在不同的基下的表示
# https://www.zhihu.com/question/20695804
# 利用正态分布启动权值和偏差值
weights = {
    'h1':tf.Variable(tf.random_normal([n_input_number, n_hidden1])),
    'h2':tf.Variable(tf.random_normal([n_hidden1, n_hiddent2])),
    'out':tf.Variable(tf.random_normal([n_hiddent2, n_class]))
}
biases = {
    'b1':tf.Variable(tf.random_normal([n_hidden1])),
    'b2':tf.Variable(tf.random_normal([n_hiddent2])),
    'out':tf.Variable(tf.random_normal([n_class]))
}
prediction = out_prediction(input_tensor, weights, biases)

由于是分类问题,使用交叉熵误差权值更新

prediction = out_prediction(input_tensor, weights, biases)
# 由于分类问题,所以使用交叉熵误差进行优化,不断更新权值和output_tensor
cross_loss = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=output_tensor)
loss = tf.reduce_mean(cross_loss)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
# 数据初始化
init = tf.global_variables_initializer()

批处理函数

def get_batch(df, i, batch_size):
    batches = []
    results = []
    texts = df.data[i * batch_size:i * batch_size + batch_size]
    categories = df.target[i * batch_size:i * batch_size + batch_size]
# 构建矩阵索引
    for text in texts:
        layer = np.zeros(total_words, dtype=float)
        for word in text.split(' '):
            layer[text_index[word.lower()]] += 1

        batches.append(layer)

    for category in categories:
        y = np.zeros((3), dtype=float)
        if category == 0:
            y[0] = 1
        elif category == 1:
            y[1] = 1
        else:
            y[2] = 1
        results.append(y)

    return np.array(batches), np.array(results)

在Session环境中训练模型

with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(len(train_set.data)/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x,batch_y = get_batch(train_set,i,batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            # op(source op),当运行该函数,启动默认图,即运行out_prediction,并不断更新权值和分类结果
            # tf.Session.run(fetches, feed_dict=None, options=None, run_metadata=None)
            # feed_dict 参数是我们为每步运行所输入的数据。为了传递这个数据,我们需要定义tf.placeholders(提供给 feed_dict)
            c,_ = sess.run([loss,optimizer], feed_dict={input_tensor: batch_x,output_tensor:batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "loss=", \
                "{:.9f}".format(avg_cost))
    print("Optimization Finished!")

利用测试数据进行模型评价

 # Test model
    correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(output_tensor, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    total_test_data = len(train_set.target)
    batch_x_test, batch_y_test = get_batch(test_set,0,total_test_data)
    print("Accuracy:", accuracy.eval({input_tensor: batch_x_test, output_tensor: batch_y_test}))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 文本分类 #### 数据预处理 要求训练集和测试集分开存储,对于中文的数据必须先分词,对分词后的词用空格符分开,并且将标签连接到每条数据的尾部,标签和句子用分隔符\分开。具体的如下: * 今天 的 天气 真好\积极 #### 文件结构介绍 * config文件:配置各种模型的配置参数 * data:存放训练集和测试集 * ckpt_model:存放checkpoint模型文件 * data_helpers:提供数据处理的方法 * pb_model:存放pb模型文件 * outputs:存放vocab,word_to_index, label_to_index, 处理后的数据 * models:存放模型代码 * trainers:存放训练代码 * predictors:存放预测代码 #### 训练模型 * python train.py --config_path="config/textcnn_config.json" #### 预测模型 * 预测代码都在predictors/predict.py中,初始化Predictor对象,调用predict方法即可。 #### 模型的配置参数详述 ##### textcnn:基于textcnn的文本分类 * model_name:模型名称 * epochs:全样本迭代次数 * checkpoint_every:迭代多少步保存一次模型文件 * eval_every:迭代多少步验证一次模型 * learning_rate:学习速率 * optimization:优化算法 * embedding_size:embedding层大小 * num_filters:卷积核的数量 * filter_sizes:卷积核的尺寸 * batch_size:批样本大小 * sequence_length:序列长度 * vocab_size:词汇表大小 * num_classes:样本的类别数,二分类时置为1,多分类时置为实际类别数 * keep_prob:保留神经元的比例 * l2_reg_lambda:L2正则化的系数,主要对全连接层的参数正则化 * max_grad_norm:梯度阶段临界值 * train_data:训练数据的存储路径 * eval_data:验证数据的存储路径 * stop_word:停用词表的存储路径 * output_path:输出路径,用来存储vocab,处理后的训练数据,验证数据 * word_vectors_path:词向量的路径 * ckpt_model_path:checkpoint 模型的存储路径 * pb_model_path:pb 模型的存储路径 ##### bilstm:基于bilstm的文本分类 * model_name:模型名称 * epochs:全样本迭代次数 * checkpoint_every:迭代多少步保存一次模型文件 * eval_every:迭代多少步验证一次模型 * learning_rate:学习速率 * optimization:优化算法 * embedding_size:embedding层大小 * hidden_sizes:lstm的隐层大小,列表对象,支持多层lstm,只要在列表中添加相应的层对应的隐层大小 * batch_size:批样本大小 * sequence_length:序列长度 * vocab_size:词汇表大小 * num_classes:样本的类别数,二分类时置为1,多分类时置为实际类别数 * keep_prob:保留神经元的比例 * l2_reg_lambda:L2正则化的系数,主要对全连接层的参数正则化 * max_grad_norm:梯度阶段临界值 * train_data:训练数据的存储路径 * eval_data:验证数据的存储路径 * stop_word:停用词表的存储路径 * output_path:输出路径,用来存储vocab,处理后的训练数据,验证数据 * word_vectors_path:词向量的路径 * ckpt_model_path:checkpoint 模型的存储路径 * pb_model_path:pb 模型的存储路径 ##### bilstm atten:基于bilstm + attention 的文本分类 * model_name:模型名称 * epochs:全样本迭代次数 * checkpoint_every:迭代多少步保存一次模型文件 * eval_every:迭代多少步验证一次模型 * learning_rate:学习速率 * optimization:优化算法 * embedding_size:embedding层大小 * hidd

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值