2018.08.22收获与总结

今天处理了一下THUC的新闻数据集,具体代码在下面。

收获

sklearn里的shuffle可以将数据打乱,我在之前处理南开数据集的时候忽视了这一点。同样,pandas中的sample()也是同样的作用,numpy库中的方法不推荐,会导致内存溢出。

总结

离开实验室的时候跑了TextCNN的模型,结果到家看了一下结果,从第九个epoch开始准确率都为1(一共15个epochs)。一开始我纳闷为啥准确率这么高,因为在复旦数据集上也就0.86左右的准确率。后来看了一下下面的代码。最后两行是我生成训练集和测试集的方法,仔细看知道了测试集就是训练集的一个子集!怪不得准确率这么高,因为已经告诉你label了啊!明天重新生成一下训练集和测试集。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import codecs
import re
import io
import pandas as pd
from sklearn.utils import shuffle

def load_data_to_mini(dirname, targetname, per_class_max_docs=1000):
"""
处理清华大学语料库,将类别和文档处理成1个txt
dirname:原始路径
targetname:保存路径
per_class_max_docs:每类文档保留的文档数量
"""
# f_train = io.open(targetname, 'w', encoding='utf-8')
labels = []
contents = []
ids = []
if not os.path.isdir(dirname):
print('path error')
for category in os.listdir(dirname): # 分类目录
count = 0
cat_dir = os.path.join(dirname, category)
if not os.path.isdir(cat_dir):
continue
files = os.listdir(cat_dir)

for cur_file in files: #具体文件
count += 1
if count > per_class_max_docs:
break
filename = os.path.join(cat_dir, cur_file)
with io.open(filename, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read().replace('\n', '').replace('\t', '').replace('\u3000', '')
# content = is_ustr(content)
# line_content = category + '\t' + content + '\t' _ str(count) + '\n'
# f_train.write(category + '\t' + content + '\t' + str(count) + '\n')
labels.append(label_dict[category])
contents.append(content.replace('\n', ''))
ids.append(str(count))
print('Finished:', category)
# train_len=int(len(ids)*0.8)
# train_df = pd.DataFrame({'label': labels[:train_len], 'content': contents[:train_len], 'id': ids[:train_len]})
val_df = pd.DataFrame({'label': labels[:], 'content': contents[:], 'id': ids[:]})
# train_df.to_csv("/home/zkq/data/small_train.csv", index=False, sep='\t')
val_df = shuffle(val_df) #打乱每行顺序
val_df.to_csv(targetname , index=False, sep='\t')
print('Finished Tran')
# f_train.close()



if __name__ == '__main__':
label_dict = {'星座': '0', '股票': '1', '房产': '2', '时尚': '3', '体育': '4' , '社会':'5','家居':'6','游戏':'7','彩票':'8','科技':'9','教育':'10','时政':'11','娱乐':'12','财经':'13'}
# category = ['星座', '股票', '房产', '时尚', '体育', '社会', '家居', '游戏', '彩票', '科技', '教育', '时政', '娱乐', '财经']
#合并为一个文件
# corpus = load_data_to_mini('/home/zkq/data/THUCNews', '/home/zkq/data/thuc_train.csv', 1000)
corpus = load_data_to_mini('/home/zkq/data/THUCNews', '/home/zkq/data/thuc_val.csv', 200)