1. Imdb影评的数据集介绍
这是用于二分类情感分类的数据集,其包含的数据比以前的基准数据集要多得多。 我们提供了25,000电影评论用于训练,而25,000条电影评论用于测试。 也有其他未标记的数据可供使用。 提供原始文本和已处理的单词格式袋。 有关更多详细信息,请参见发行版中的自述文件。
Imdb 影评的数据集包含有
25000 训练数据集
25000 测试数据集
2. 数据下载
数据集地址:http://ai.stanford.edu/~amaas/data/sentiment/
下载后解压,会看到有两个文件夹,test和train:
我们点进train中,会发现正样本和负样本已经分好类了:
neg和pos分别是负样本和正样本,unsup是未标注的样本,可用后续需要采用。其他的都自己去看看吧。
打开pos文件,看看里面啥样:
都是一个个文本。
注意到,这些文本一般都不短…
数据集中,共有5w条文本,test集和train集各半,每个集合中,pos和neg也是各半。
import os as os
import numpy as np
from sklearn.model_selection import train_test_split
datapath = r'./aclImdb'
save_dir = r'./data'
def get_data(datapath):
pos_files = os.listdir(datapath + '/pos')
neg_files = os.listdir(datapath + '/neg')
print(len(pos_files))
print(len(neg_files))
pos_all = []
neg_all = []
for pf, nf in zip(pos_files, neg_files):
with open(datapath + '/pos' + '/' + pf, encoding='utf-8') as f:
s = f.read()
pos_all.append(s)
with open(datapath + '/neg' + '/' + nf, encoding='utf-8') as f:
s = f.read()
neg_all.append(s)
X_orig= np.array(pos_all + neg_all)
Y_orig = np.array([1 for _ in range(len(pos_all))] + [0 for _ in range(len(neg_all))])
print("X_orig:", X_orig.shape)
print("Y_orig:", Y_orig.shape)
return X_orig, Y_orig
def generate_train_data():
X_orig, Y_orig = get_data(datapath+r'/train')
X_test, Y__test = get_data(datapath+r'/test')
X = np.concatenate([X_orig, X_test])
Y = np.concatenate([Y_orig, Y__test])
np.random.seed = 1
random_indexs = np.random.permutation(len(X))
X = X[random_indexs]
Y = Y[random_indexs]
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.1)
print("X_train:", X_train.shape)
print("y_train:", y_train.shape)
print("X_test:", X_test.shape)
print("y_test:", y_test.shape)
print("x_val:", X_val.shape)
print("y_val:", y_val.shape)
np.savez(save_dir + '/imdb_train', x=X_train, y=y_train)
np.savez(save_dir + '/imdb_test', x=X_test, y=y_test)
np.savez(save_dir + '/imdb_val', x=X_val, y=y_val)
if __name__ == '__main__':
generate_train_data()
执行上述代码就可以得到下面三个文件,方便以后做训练
imdb_test.npz
imdb_train.npz
imdb_val.npz