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 = f.readlines()
    with open(output_seg_file, 'w') as f:
        for line in lines:

            label, content = line.strip('\n').split('\t')
            word_iter = jieba.cut(content)
            word_content = ''
            for word in word_iter:
                word = word.strip(' ')
                if word != '':
                    word_content  += word + ' '
            out_line = '%s\t%s\n'%(label, word_content.strip(' ')) # 將最後一個空格刪除
            f.write(out_line)

# 對 三個 文件 進行分詞
#generate_seg_file(train_file, seg_train_file)
#generate_seg_file(val_file, seg_val_file)
#generate_seg_file(test_file, seg_test_file)

def generate_vocab_file(input_seg_file, output_vocab_file):
    '''
    :param input_seg_file: 已經分詞的文件
    :param output_vocab_file: 輸出的詞表
    :return:
    '''
    with open(input_seg_file, 'r') as f:
        lines = f.readlines()
    word_dict = {}  # 統計 詞頻 信息,因爲 我們只需要 關注的 是詞頻
    for line in lines:
        label, content = line.strip('\n').split('\t')
        for word in content.split(' '):
            word_dict.setdefault(word, 0) # 如果 沒有這個 詞語,就把給詞語的默認值設爲 0
            word_dict[word] += 1

    # dict.item() 將字典轉化爲列表
    # 詳情參考:http://www.runoob.com/python/att-dictionary-items.html
    sorted_word_dict = sorted(word_dict.items(), key=lambda d:d[1], reverse=True)
    # 現在sorted_word_dict的格式爲: [(word, frequency).....(word, frequency)]
    with open(output_vocab_file, 'w') as f:
        f.write('<UNK>\t1000000\n') # 因爲不是所有詞彙都有的,對於一些沒有的詞彙,就用 unk 來代替
        for item in sorted_word_dict:
            f.write('%s\t%d\n'%(item[0], item[1]))

#generate_vocab_file(seg_train_file, vocab_file) # 從訓練集中 統計 詞表


def generate_category_dict(input_file, category_file):
    with open(input_file, 'r') as f:
        lines = f.readlines()
    category_dict = {}
    for line in lines:
        label, content = line.strip('\n').split('\t')
        category_dict.setdefault(label, 0)
        category_dict[label] += 1

    category_number = len(category_dict)
    with open(category_file, 'w') as f:
        for category in category_dict:
            line = '%s\n' % category # 現在才知道,原來遍歷字典,原來默認查出的是key
            print('%s\t%d' % (category, category_dict[category]))
            f.write(line)



generate_category_dict(train_file, category_file)

數據預處理完畢,接下來進行模型的訓練和測試,請參考: Tensorflow使用LSTM實現中文文本分類(二)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章