python machine learning之情感分析

本文介绍了使用Python进行情感分析的步骤,包括数据处理、n-gram模型、TF-IDF和Logistic Regression模型的构建。此外,还探讨了如何使用out-of-core学习处理大数据,并通过LDA进行主题建模,利用LDA分解词袋矩阵,最后通过可视化工具pyLDAvis展示了结果。实验结果显示,情感分析模型准确率为0.878,而LDA主题建模能有效揭示文本中的主题结构。
摘要由CSDN通过智能技术生成
步骤:

数据与输出
重排打散

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值