一、数据读取
import pandas as pd
train_df=pd.read_csv('D:/AIproject/NLP_news_paper_classific/data/train_set.csv/train_set.csv',sep='\t',nrows=100)
train_df.head()
二、数据分析
数据分析的目的:
(1)获得赛题数据中新闻文本的长度
(2)获得赛题数据类别分类的分布
(3)获得赛题数据字符的分布
1、句子长度分析
观察前5行数据可知每行句子中的字符用空格隔开,可通过统计单词个数来计算每个句子长度。
%pylab inline
train_df['text_len'] = train_df['text'].apply(lambda x: len(x.split(' ')))
print(train_df['text_len'].describe())
绘制句子长度直方图
plt.hist(train_df['text_len'], bins=200)
plt.xlabel('Text char count')
plt.title("Histogram of char count")
2、类别分布
train_df['label'].value_counts().plot(kind='bar')
plt.title('News class count')
plt.xlabel("category")
在数据集中标签的对应的关系如下:{‘科技’: 0, ‘股票’: 1, ‘体育’: 2, ‘娱乐’: 3, ‘时政’: 4, ‘社会’: 5, ‘教育’: 6, ‘财经’: 7, ‘家居’: 8, ‘游戏’: 9, ‘房产’: 10, ‘时尚’: 11, ‘彩票’: 12, ‘星座’: 13}
可知类别分布不均匀!
3、字符分布统计
统计每个字符出现的次数,首先可以将训练集中所有的句子进行拼接进而划分为字符,并统计每个字符的个数。
from collections import Counter
all_lines = ' '.join(list(train_df['text']))
word_count = Counter(all_lines.split(" "))
word_count = sorted(word_count.items(), key=lambda d:d[1], reverse = True)
print(len(word_count))
print(word_count[0])
print(word_count[-1])
总共包含2405个字符,编号3750的字符出现次数最多,编号5034的字符出现字数最少。
可以根据字在每个句子的出现情况,反推出标点符号。下面统计了不同字符在句子中出现的次数,其中字符3750,字符900和字符648在20w新闻的覆盖率接近99%,很有可能是标点符号。
train_df['text_unique'] = train_df['text'].apply(lambda x: ' '.join(list(set(x.split(' ')))))
all_lines = ' '.join(list(train_df['text_unique']))
word_count = Counter(all_lines.split(" "))
word_count = sorted(word_count.items(), key=lambda d:int(d[1]), reverse = True)
print(word_count[0])
print(word_count[1])
print(word_count[2])
数据分析结论
通过上述分析我们可以得出以下结论:
(1)赛题中每个新闻包含的字符个数平均为872个,还有一些新闻字符较长;
(2)赛题中新闻类别分布不均匀,科技类新闻样本量接近35%,星座类新闻样本量不到1%;
(1)赛题总共包括2405个不同字符;
通过数据分析,我们还可以得出以下结论:
(1)每个新闻平均字符个数较多,可能需要截断;
(2)由于类别不均衡,会严重影响模型的精度;
三、作业
1、假设字符3750,字符900和字符648是句子的标点符号,请分析赛题每篇新闻平均由多少个句子构成?
import re ##split一次指定多个分隔符使用re模块
train_df['sentence_num'] = train_df['text'].apply(lambda x: len(re.split('3750|900|648', x)))
train_df['sentence_num'].describe()
2、统计每类新闻中出现次数对多的字符
from collections import Counter
sort_max_words={}
for i in set(train_df['label'].values):
all_i_lines = ' '.join(list(train_df[train_df['label']==i]['text']))
word_count = Counter(all_i_lines.split(' '))
word_count = sorted(word_count.items(),key=lambda d:d[1],reverse=True)
sort_max_words[i]=word_count[0]
sort_max_words