本文使用的是和鲸社区现有数据集,代码也在和鲸社区公开,fork之后可以直接运行。
本文中所用的数据集清华NLP组提供的THUCNews新闻文本分类数据集的一个子集(原始的数据集大约74万篇文档,训练起来需要花较长的时间)。 本次训练使用了其中的体育, 财经, 房产, 家居, 教育, 科技, 时尚, 时政, 游戏, 娱乐10个分类,每个分类6500条,总共65000条新闻数据。项目在和鲸社区的平台上跑的,数据集直接引用了和鲸的数据集,每个分类6500条,总共65000条新闻数据。
数据集划分如下: cnews.train.txt: 训练集(50000条) cnews.val.txt: 验证集(5000条) cnews.test.txt: 测试集(10000条)
本文使用了较为传统的tfidf算法实现文本的向量化,并使用sklearn中的经典分类算法对文本数据进行分类。
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import metrics
from sklearn.preprocessing import LabelEncoder
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from pprint import pprint
from time import time
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from data_loader.cnews_loader import *
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
预处理
# 设置数据读取、模型、结果保存路径
base_dir = '/home/kesci/input/new3021'
train_dir = os.path.join(base_dir, 'cnews.train.txt')
test_dir = os.path.join(base_dir, 'cnews.test.txt')
val_dir = os.path.join(base_dir, 'cnews.val.txt')
vocab_dir = os.path.join(base_dir, 'cnews.vocab.txt')
save_dir = 'checkpoints/textcnn'
save_path = os.path.join(save_dir, 'best_validation')
读取数据使用了data_loader.cnews_loader中的read_file读取数据。
train_contents, train_labels = read_file(train_dir)
test_contents, test_labels = read_file(test_dir)
val_counts = Counter(train_labels)
val_counts
Counter({'体育': 5000,
'娱乐': 5000,
'家居': 5000,
'房产': 5000,
'教育': 5000,
'时尚': 5000,
'时政': 5000,
'游戏': 5000,
'科技': 5000,
'财经': 5000})
移除特殊字符
import re
#去除文本中的表情字符(只保留中英文和数字)
def clear_character(sentence):
pattern1= '\[.*?\]'
pattern2 = re.compile('[^\u4e00-\u9fa5^a-z^A-Z^0-9]')
line1=re.sub(pattern1,'',sentence)
line2=re.sub(pattern2,'',line1)
new_sentence=''.join(line2.split()) #去除空白
return new_sentence
train_text=list(map(lambda s: clear_character(s), train_contents))
test_text=list(map(lambda s: clear_character(s), test_contents))
分词
使用了jieba分词。
import jieba
train_seg_text=list(map(lambda s: jieba.lcut(s), train_text))
test_seg_text=list(map(lambda s: jieba.lcut(s), test_text))
去除停用词
# 读取停用词
stop_words_path = "/home/kesci/work/data_loader/百度停用词列表.txt"
def get_stop_words():
file = open(stop_words_path, 'rb').read().decode('gbk').split('\r\n')
return set(file)
stopwords = get_stop_words()
# 去掉文本中的停用词
def drop_stopwords(line, stopwords):
line_clean = []
for word in line:
if word in stopwords:
continue
line_clean.append(word)
return line_clean
train_st_text=list(map(lambda s: drop_stopwords(s,stopwords), train_seg_text))
test_st_text=list(map(lambda s: drop_stopwords(s,stopwords), test_seg_text))
标签映射
le = LabelE
535



被折叠的 条评论
为什么被折叠?



