Tensorflow使用LSTM实现中文文本分类(1)

前言

使用Tensorflow,利用LSTM进行中文文本的分类。
数据集格式如下:
‘’’
体育 马晓旭意外受伤让国奥警惕 无奈大雨格外青睐殷家军记者傅亚雨沈阳报道 来到沈阳,国奥队依然没有摆脱雨水的困扰。…
‘’’
可以看出 label:体育,接着是一个 tab,最后跟随一段文字。
目标:传入模型一段文字,预测出这段文字所属类别。

数据集下载

中文文本分类数据集下载:https://download.csdn.net/download/missyougoon/11221027

文本预处理

  1. 中文分词
  2. 词语转化为 id ,embeding
    例如: 词语A 转化为 id(5)
    同时,将 label 转化 id
  3. 统计词频

代码演示

# -*- coding:utf-8 -*-

import sys
import os
import jieba

# 输入文件
train_file = './news_data/cnews.train.txt'
val_file = './news_data/cnews.val.txt'
test_file = './news_data/cnews.test.txt'

# 分词结果
seg_train_file = './news_data/cnews.train.seg.txt'
seg_val_file = './news_data/cnews.val.seg.txt'
seg_test_file = './news_data/cnews.test.seg.txt'


# 词语 和 label到id 的 映射
vocab_file = './news_data/cnews.vocab.txt'
category_file = './news_data/cnews.category.txt'

#print(label)


def generate_seg_file(input_file, output_seg_file):
    '''
    生成分词之后的文本数据
    :param input_file: 待分词的输入文件
    :param output_seg_file:  已经分词完毕的文本
    :return:
    '''
    with open(input_file, 'r') as f:
        lines &
  • 3
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
以下是一段使用TensorFlow 2.0实现LSTM文本分类代码,使用GloVe进行词嵌入的示例: ```python import tensorflow as tf import numpy as np # 加载GloVe词向量 glove_file = 'glove.6B.100d.txt' embedding_index = {} with open(glove_file, encoding='utf-8') as f: for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embedding_index[word] = coefs # 构建词向量矩阵 embedding_dim = 100 max_words = 10000 embedding_matrix = np.zeros((max_words, embedding_dim)) for word, i in tokenizer.word_index.items(): if i < max_words: embedding_vector = embedding_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector # 构建模型 model = tf.keras.Sequential([ tf.keras.layers.Embedding(max_words, embedding_dim, input_length=maxlen), tf.keras.layers.LSTM(32), tf.keras.layers.Dense(1, activation='sigmoid') ]) # 编译模型 model.layers[0].set_weights([embedding_matrix]) model.layers[0].trainable = False model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) # 训练模型 history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_val, y_val)) ``` 其中,`glove.6B.100d.txt`是GloVe预训练的100维词向量文件,可以从GloVe官网下载。`max_words`是词汇表的大小,`maxlen`是输入序列的最大长度。在构建词向量矩阵时,只使用了词汇表中前`max_words`个词的词向量,其余词的词向量均为0。在构建模型时,首先使用`Embedding`层加载词向量矩阵,然后使用`LSTM`层进行序列建模,最后使用`Dense`层输出二分类结果。在编译模型时,将词向量矩阵的权重设置为不可训练,以避免过拟合。在训练模型时,使用`fit`方法进行训练,其中`x_train`和`y_train`是训练集的输入和输出,`x_val`和`y_val`是验证集的输入和输出。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值