kaggle竞赛——入门二(Natural Language Processing with Disaster Tweets)

2023-10-18 17:40

本文主要是介绍kaggle竞赛——入门二(Natural Language Processing with Disaster Tweets),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

比赛地址:https://www.kaggle.com/c/nlp-getting-started/submit

"""
__author__:shuangrui Guo
__description__:
"""
import pandas as pd
import numpy as np
import re
import nltk
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from nltk.stem import SnowballStemmer
import seaborn as sns
from sklearn.svm import SVC
from sklearn.metrics import f1_score
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectKBest ,chi2#读取数据集
train = pd.read_csv('./data/train.csv')
test = pd.read_csv('./data/test.csv')
#在keyword存在61个空值,location列存在2533个空值
#print(train.isnull().sum())#可视化,在条形图顶部显示数字
# plt.figure()
# ax = train['target'].value_counts().plot.bar()
# for p in ax.patches:
#     ax.annotate(np.round(p.get_height(),decimals=2),
#                 ((p.get_x()+p.get_width()/2.0),p.get_height()),
#                 ha='center',
#                 va='center',
#                 xytext=(0,5),
#                 textcoords='offset points')
# plt.title('True vs False Disaster Tweets')
# plt.xlabel('True vs False')
# plt.xticks(rotation=360)
# plt.show()#清洗文本
#使用SnowballStemmer来把句子中的单词词干化
stemmer = SnowballStemmer('english')
stopwords_list = stopwords.words('english')def clean_content(string:str):cleaned = []temp=re.sub("[^a-zA-Z]"," ",string).split()for word in temp:if word not in stopwords_list:cleaned.append(stemmer.stem(word))return " ".join(cleaned).lower()
train['cleaned']=train['text'].apply(clean_content)#步骤二:去除一些没有用的词与符号
def review_cleaning(text):text = re.sub(r'([!”#$%&’()*+,-./:;<=>?[\]^_`{|}~])'," ",text)text = re.sub(r'http',' ',text)text = re.sub(r'https',' ',text)text = re.sub(r'http\S+',' ',text)text = re.sub(r'https\S+',' ',text)text = re.sub(r'co',' ',text)text = re.sub(r'\s+',' ',text)text = re.sub(r'\d+',' ',text)text = re.sub(r'[^a-zA-Z0-9]+',' ',text)return texttrain['cleaned'] = train['cleaned'].apply(review_cleaning)#删除一些只有一个单词的行:
train['cleaned'] = [t for t in train['cleaned'] if len(t)>1]#创建训练集与测试集
#train['cleaned'] = train['cleaned'].values#创建tf-idf
tfidf = TfidfVectorizer(analyzer='word',max_features=10000,ngram_range=(1,3),stop_words='english')
X = tfidf.fit_transform(train['cleaned'])
X_train,X_test,y_train,y_test = train_test_split(X,train['target'].tolist(),test_size=0.2,stratify=train['target'].tolist())pipeline = Pipeline([('mutual_info_classif',SelectKBest(chi2,k=6500)),('classifier',SVC(kernel='rbf',random_state=0,verbose=True,gamma=1,C=1,degree=6,shrinking=True,probability=False,cache_size=5))]
)model = pipeline.fit(X_train,y_train)
y_pred = model.predict(X_test)
print(f1_score(y_test,y_pred))#在真正的测试集上进行预测并保存
test['cleaned'] = test['text'].apply(clean_content)
test['cleaned'] = test['cleaned'].apply(review_cleaning)testing = tfidf.transform(test['cleaned'])
test_pred = model.predict(testing)
test['target'] = test_pred
columns = ['id','target']
submission = test[columns]
submission.to_csv('./submission.csv',index=False)

目前的不足:

文本清洗部分觉得有些奇怪

使用TFIDF的结果直接去划分训练集和测试集不能理解

SelectKBest的作用不清楚

Pipeline的使用不了解

这篇关于kaggle竞赛——入门二(Natural Language Processing with Disaster Tweets)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/234164

相关文章

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

Redis 配置文件使用建议redis.conf 从入门到实战

《Redis配置文件使用建议redis.conf从入门到实战》Redis配置方式包括配置文件、命令行参数、运行时CONFIG命令,支持动态修改参数及持久化,常用项涉及端口、绑定、内存策略等,版本8... 目录一、Redis.conf 是什么?二、命令行方式传参(适用于测试)三、运行时动态修改配置(不重启服务

MySQL DQL从入门到精通

《MySQLDQL从入门到精通》通过DQL,我们可以从数据库中检索出所需的数据,进行各种复杂的数据分析和处理,本文将深入探讨MySQLDQL的各个方面,帮助你全面掌握这一重要技能,感兴趣的朋友跟随小... 目录一、DQL 基础:SELECT 语句入门二、数据过滤:WHERE 子句的使用三、结果排序:ORDE

Python中OpenCV与Matplotlib的图像操作入门指南

《Python中OpenCV与Matplotlib的图像操作入门指南》:本文主要介绍Python中OpenCV与Matplotlib的图像操作指南,本文通过实例代码给大家介绍的非常详细,对大家的学... 目录一、环境准备二、图像的基本操作1. 图像读取、显示与保存 使用OpenCV操作2. 像素级操作3.

POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能

《POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能》ApachePOI是一个流行的Java库,用于处理MicrosoftOffice格式文件,提供丰富API来创建、读取和修改O... 目录前言:Apache POIEasyPoiEasyExcel一、EasyExcel1.1、核心特性

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis