当前位置: 首页 > article >正文

NLP实践项目1——判断推文的负面情绪

数据来源:https://datahack.analyticsvidhya.com/contest/linguipedia-codefest-natural-language-processing-1/?utm_source=word-embeddings-count-word2veec&utm_medium=blogicon-default.png?t=O83Ahttps://datahack.analyticsvidhya.com/contest/linguipedia-codefest-natural-language-processing-1/?utm_source=word-embeddings-count-word2veec&utm_medium=blog

 导入库

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
from nltk.corpus import stopwords
import nltk
import re

nltk.download('stopwords')
stop_words = set(stopwords.words('english'))

 文本预处理

# 文本预处理函数
def preprocess_text(text):
    # 移除特殊字符、数字等
    text = re.sub(r'[^a-zA-Z\s]', '', text)
    # 转换为小写
    text = text.lower()
    # 去除停用词
    text = ' '.join([word for word in text.split() if word not in stop_words])
    return text

读取数据集并处理

# 读取本地CSV文件
data = pd.read_csv("F:/Sentiment analysis/Data_dictionary/train_2kmZucJ.csv")
# 删除缺失值的行
data = data.dropna(subset=['tweet', 'label'])
# 应用预处理函数到推文内容
data['tweet'] = data['tweet'].apply(preprocess_text)
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data['tweet'], data['label'], test_size=0.2, random_state=42)

 定义训练函数

#定义训练函数
def train(model,model_name):
    model.fit(X_train_vectorized, y_train)
    predictions = model.predict(X_test_vectorized)
    print(model_name + " Accuracy:", accuracy_score(y_test, predictions))
    print(classification_report(y_test, predictions))
使用TF-IDF向量化推文内容
vectorizer = TfidfVectorizer(max_features=1000)
X_train_vectorized = vectorizer.fit_transform(X_train)
X_test_vectorized = vectorizer.transform(X_test)

以朴素贝叶斯模型为例

# 以朴素贝叶斯算法为例
nb_model = MultinomialNB()
train(nb_model,"Naive Bayes")

导入预测数据集并保存预测结果

# 导入预测数据集
test= pd.read_csv("F:/Sentiment analysis/Data_dictionary/test_oJQbWVk.csv")
test_predictions = nb_model.predict(vectorizer.transform(test['tweet']))
# 将预测结果保存
results_df = pd.DataFrame({
    'id': test['id'],
    'label': test_predictions
})
results_df.to_csv("predictions.csv", index=False)
print("预测结果已保存")

完整代码为

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
from nltk.corpus import stopwords
import nltk
import re

nltk.download('stopwords')
stop_words = set(stopwords.words('english'))
# 文本预处理函数
def preprocess_text(text):
    # 移除特殊字符、数字等
    text = re.sub(r'[^a-zA-Z\s]', '', text)
    # 转换为小写
    text = text.lower()
    # 去除停用词
    text = ' '.join([word for word in text.split() if word not in stop_words])
    return text
# 读取本地CSV文件
data = pd.read_csv("F:/Sentiment analysis/Data_dictionary/train_2kmZucJ.csv")
# 删除缺失值的行
data = data.dropna(subset=['tweet', 'label'])
# 应用预处理函数到推文内容
data['tweet'] = data['tweet'].apply(preprocess_text)
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data['tweet'], data['label'], test_size=0.2, random_state=42)

#定义训练函数
def train(model,model_name):
    model.fit(X_train_vectorized, y_train)
    predictions = model.predict(X_test_vectorized)
    print(model_name + " Accuracy:", accuracy_score(y_test, predictions))
    print(classification_report(y_test, predictions))

# 使用TF-IDF向量化推文内容
vectorizer = TfidfVectorizer(max_features=1000)
X_train_vectorized = vectorizer.fit_transform(X_train)
X_test_vectorized = vectorizer.transform(X_test)
# 以朴素贝叶斯算法为例
nb_model = MultinomialNB()
train(nb_model,"Naive Bayes")
# 导入预测数据集
test= pd.read_csv("F:/Sentiment analysis/Data_dictionary/test_oJQbWVk.csv")
test_predictions = nb_model.predict(vectorizer.transform(test['tweet']))
# 将预测结果保存
results_df = pd.DataFrame({
    'id': test['id'],
    'label': test_predictions
})
results_df.to_csv("predictions.csv", index=False)
print("预测结果已保存")


http://www.kler.cn/news/368874.html

相关文章:

  • 排序
  • Python应用指南:利用高德地图API实现路径规划
  • 1通道10GSPS或2通道5G 14 bit数字化仪
  • spygalss cdc 检测的bug(二)
  • 智能工厂的软件设计 专有名词(juncture/relation/selection):意识形态及认知计算机科学的架构、系统和运用
  • 面向对象与设计模式第二节:设计模式实战
  • C++的 / 运算符
  • 如何构建一个支持GPU的Llamafile容器
  • 【知识科普】正则表达式深入解读
  • C语言 | Leetcode C语言题解之第514题自由之路
  • 基于知识图谱的教学案例问答系统
  • el-date-picker时间范围搜索条件,watch监听
  • 接口自动化-框架搭建(Python+request+pytest+allure)
  • MySQL第四次作业
  • C++-继承
  • 传知代码-ChatGPT多模态命名实体识别
  • 用python将pdf转成图片转换成对应的word文件
  • 9.Three.js的光源
  • [C++11] 右值引⽤与移动语义
  • Python实践:爬取电影数据并进行数据分析
  • ORACLE数据库基于SQL*PLUS开启:闪回查询
  • 小程序中设置可拖动区域
  • Centos Stream 9部署Zabbix7.0LTS
  • Python实现深度学习模型预测控制(tensorflow)DL-MPC(Deep Learning Model Predictive Control
  • RabbitMQ常见问题持续汇总
  • 无人机机载激光雷达横向对比表