Task1&Task2 数据读取与数据分析
赛题数据是文本数据,每个新闻是不定长的,使用csv格式进行存储。因此可以直接用Pandas
完成数据读取的操作。
import pandas as pd
train_df = pd.read_csv(r'train_set.csv', sep='\t')
pd.read_csv
常用参数:
- 读取的文件路径,这里需要根据改成你本地的路径,可以使用相对路径或绝对路径;
- 分隔符
sep
,为每列分割的字符,设置为\t
即可; - 读取行数
nrows
,为此次读取文件的函数,是数值类型(由于数据集比较大,可以先设置为100);
train_df.head(5)
label | text | |
---|---|---|
0 | 2 | 2967 6758 339 2021 1854 3731 4109 3792 4149 15... |
1 | 11 | 4464 486 6352 5619 2465 4802 1452 3137 5778 54... |
2 | 3 | 7346 4068 5074 3747 5681 6093 1777 2226 7354 6... |
3 | 2 | 7159 948 4866 2109 5520 2490 211 3956 5520 549... |
4 | 3 | 3646 3055 3055 2490 4659 6065 3370 5814 2465 5... |
同样的方法加载测试集数据。
test_df = pd.read_csv(r'test_a.csv', sep='\t')
test_df.head(5)
text | |
---|---|
0 | 5399 3117 1070 4321 4568 2621 5466 3772 4516 2... |
1 | 2491 4109 1757 7539 648 3695 3038 4490 23 7019... |
2 | 2673 5076 6835 2835 5948 5677 3247 4124 2465 5... |
3 | 4562 4893 2210 4761 3659 1324 2595 5949 4583 2... |
4 | 4269 7134 2614 1724 4464 1324 3370 3370 2106 2... |
数据分析
读取完训练集后,初步查看数据格式后,可以对数据集进行数据分析的操作。
读取了所有的训练集数据,从下面几个角度对数据集进行数据分析:
- 赛题数据中,新闻文本的长度是多少?
- 赛题数据中,字符分布是怎么样的?
- 赛题数据的类别分布是怎么样的,哪些类别比较多?
- 赛题数据中,不同类别的文本长度分布如何?
- 赛题数据中,不同类别的字符分布是怎么样的?
统计数据集中所有句子所包含字符的平均个数
由上面的表格可以知道,训练集的每行句子的字符使用空格进行隔开,所以可以分割,然后统计单词的个数来得到每个句子的长度。
%pylab inline
train_df['text_len'] = train_df['text'].apply(lambda x: len(x.split(' ')))
print(train_df['text_len'].describe())
Populating the interactive namespace from numpy and matplotlib
count 200000.000000
mean 907.207110
std 996.029036
min 2.000000
25% 374.000000
50% 676.000000
75% 1131.000000
max 57921.000000
Name: text_len, dtype: float64
对新闻句子的统计可以得出,赛题的训练数据总共20w条,给定的文本比较长,每个句子平均由907个字符构成,最短的句子长度为2,最长的句子长度为57921。其中75%以下的数据长度在1131以下。
下图将句子长度绘制了直方图,可见大部分训练集的句子的长度都几种在2000以内。
_ = plt.hist(train_df['text_len'], bins=200)
plt.xlabel('Text char count in train dataset')
plt.title("Histogram of char count")
Text(0.5, 1.0, 'Histogram of char count')
_ = plt.hist(train_df[train_df['text_len']<5000]['text_len'], bins=200)plt.xlabel('Text char count in train dataset')plt.title("Histogram of char count")
Text(0.5, 1.0, 'Histogram of char count')
同样统计测试集文本长度:
%pylab inlinetest_df[