步骤:
数据与输出
重排打散
import pyprind
import pandas as pd
import os
basepath = ''
#将原始的txt文件都组合起来到一个csv中去
labels = {
'pos':1,'neg':0}
pbar = pyprind.ProgBar(50000)
df = pd.DataFrame()
for s in ('test','train'):
for l in ('pos','neg'):
path = os.path.join(basepath,s,l)
for file in os.listdir(path):
with open(os.path.join(path,file),'r',encoding='utf-8') as infile:
txt = infile.read()
df = df.append([[txt,labels[l]]],ignore_index=True)
pbar.update()
df.columns = ['review','sentiment']
import numpy as np
np.random.seed(0)
df = df.reindex(np.random.permutation(df.index))
df.to_csv(movie_data.csv,index=False,encoding='utf-8')
#看一下数据
df = pd.read_csv('movie_data.csv',encoding='utf-8')
df.head(3)
bag-of-words词袋模型
词袋模型
n-gram模型
将文本里面的内容按照字节进行大小为N的滑动窗口操作,形成了长度是N的字节片段序列。
n-gram模型
使用sklearn中的CountVectorizer进行特征提取
tf-idf
获取词频.tf(t,d)是前一个部分的词频,idf(t,d)是逆文档频率
link
使用CountVectorizer将文本中的词语转换为词频矩阵
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer()#将文本中词语转换为 词频矩阵(类
docs = np.array(['today is raining','the air is wet','today is raining