nlp構建_使用NLP構建自殺性推文分類器

nlp構建

Over the years, suicide has been one of the major causes of death worldwide, According to Wikipedia, Suicide resulted in 828,000 global deaths in 2015, an increase from 712,000 deaths in 1990. This makes suicide the 10th leading cause of death worldwide. There is also increasing evidence that the Internet and social media can influence suicide-related behaviour. Using Natural Language Processing, a field in Machine Learning, I built a very simple suicidal ideation classifier which predict whether a text is likely to be suicidal or not.

多年來,自殺一直是全世界主要的死亡原因之一。據維基百科稱 ,自殺導致2015年全球死亡828,000人,比1990年的712,000人有所增加。這使自殺成為全球第十大死亡原因。 越來越多的證據表明,互聯網和社交媒體可以影響 自殺相關行為 。 使用機器學習中的自然語言處理這一領域,我建立了一個非常簡單的自殺意念分類器,該分類器可預測文本是否可能具有自殺意味。

數據 (Data)

I used a Twitter crawler which I found on Github, made some few changes to the code by removing hashtags, links, URL and symbols whenever it crawls data from Twitter, the data were crawled based on query parameters which contain words like:

我使用了一個在Github上找到的Twitter搜尋器,通過在每次從Twitter抓取數據時刪除標簽,鏈接,URL和符號來對代碼進行了一些更改,這些數據是根據包含以下單詞的查詢參數進行抓取的:

Depressed, hopeless, Promise to take care of, I dont belong here, Nobody deserve me, I want to die etc.

沮喪,絕望,無極照顧,我不屬于這里,沒人值得我,我想死等等。

Although some of the text we’re in no way related to suicide at all, I had to manually label the data which were about 8200 rows of tweets. I also sourced for more Twitter Data and I was able to concatenate with the one I previously had which was enough for me to train.

盡管有些文本根本與自殺無關,但我不得不手動標記大約8200行tweet數據。 我還獲得了更多的Twitter數據,并且能夠與以前擁有的足以進行訓練的數據相結合。

建立模型 (Building the Model)

數據預處理 (Data Preprocessing)

I imported the following libraries:

我導入了以下庫:

import pickle
import re
import numpy as np
import pandas as pd
from tqdm import tqdm
import nltk
nltk.download('stopwords')

I then wrote a function to clean the text data to remove any form of HTML markup, keep emoticon characters, remove non-word character and lastly convert to lowercase.

然后,我編寫了一個函數來清除文本數據,以刪除任何形式HTML標記,保留表情符號字符,刪除非單詞字符并最后轉換為小寫字母。

def preprocess_tweet(text):
text = re.sub('<[^>]*>', '', text)
emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text)
lowercase_text = re.sub('[\W]+', ' ', text.lower())
text = lowercase_text+' '.join(emoticons).replace('-', '')
return text

After that, I applied the preprocess_tweet function to the tweet dataset to clean the data.

之后,我將preprocess_tweet函數應用于tweet數據集以清理數據。

tqdm.pandas()df = pd.read_csv('data.csv')
df['tweet'] = df['tweet'].progress_apply(preprocess_tweet)

Then I converted the text to tokens by using the .split() method and used word stemming to convert the text to their root form.

然后,我使用.split()方法將文本轉換為標記,并使用詞干將文本轉換為其根形式。

from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()def tokenizer_porter(text):
return [porter.stem(word) for word in text.split()]

Then I imported the stopwords library to remove stop words in the text.

然后,我導入了停用詞庫,以刪除文本中的停用詞。

from nltk.corpus import stopwords
stop = stopwords.words('english')

Testing the function on a single text.

在單個文本上測試功能。

[w for w in tokenizer_porter('a runner likes running and runs a lot') if w not in stop]

Output:

輸出:

['runner', 'like', 'run', 'run', 'lot']

矢量化器 (Vectorizer)

For this project, I used the Hashing Vectorizer because it data-independent, which means that it is very low memory scalable to large datasets and it doesn’t store vocabulary dictionary in memory. I then created a tokenizer function for the Hashing Vectorizer

在此項目中,我使用了Hashing Vectorizer,因為它與數據無關,這意味著它的內存非常低,可擴展到大型數據集,并且不將詞匯表存儲在內存中。 然后,我為Hashing Vectorizer創建了tokenizer函數

def tokenizer(text):
text = re.sub('<[^>]*>', '', text)
emoticons = re.findall('(?::|;|=)(?:-)?(?:\(|D|P)',text.lower())
text = re.sub('[\W]+', ' ', text.lower())
text += ' '.join(emoticons).replace('-', '')
tokenized = [w for w in tokenizer_porter(text) if w not in stop]
return tokenized

Then I created the Hashing Vectorizer object.

然后,我創建了哈希向量化器對象。

from sklearn.feature_extraction.text import HashingVectorizervect = HashingVectorizer(decode_error='ignore', n_features=2**21, 
preprocessor=None,tokenizer=tokenizer)

模型 (Model)

For the Model, I used the stochastic gradient descent classifier algorithm.

對于模型,我使用了隨機梯度下降分類器算法。

from sklearn.linear_model import SGDClassifier
clf = SGDClassifier(loss='log', random_state=1)

培訓與驗證 (Training and Validation)

X = df["tweet"].to_list()
y = df['label']

For the model, I used 80% for training and 20% for testing.

對于模型,我使用了80%的訓練和20%的測試。

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,
y,
test_size=0.20,
random_state=0)

Then I transformed the text data to vectors with the Hashing Vectorizer we created earlier:

然后,使用之前創建的Hashing Vectorizer將文本數據轉換為矢量:

X_train = vect.transform(X_train)
X_test = vect.transform(X_test)

Finally, I then fit the data to the algorithm

最后,然后將數據擬合到算法中

classes = np.array([0, 1])
clf.partial_fit(X_train, y_train,classes=classes)

Let's test the accuracy on our test data:

讓我們在測試數據上測試準確性:

print('Accuracy: %.3f' % clf.score(X_test, y_test))

Output:

輸出:

Accuracy: 0.912

I had an accuracy of 91% which is fair enough, after that, I then updated the model with the prediction

我的準確度是91%,這還算公允,之后,我用預測更新了模型

clf = clf.partial_fit(X_test, y_test)

測試和做出預測 (Testing and Making Predictions)

I added the text “I’ll kill myself am tired of living depressed and alone” to the model.

我在模型中添加了文本“我會厭倦生活在沮喪和孤獨中,殺死自己”。

label = {0:'negative', 1:'positive'}
example = ["I'll kill myself am tired of living depressed and alone"]
X = vect.transform(example)
print('Prediction: %s\nProbability: %.2f%%'
%(label[clf.predict(X)[0]],np.max(clf.predict_proba(X))*100))

And I got the output:

我得到了輸出:

Prediction: positive
Probability: 93.76%

And when I used the following text “It’s such a hot day, I’d like to have ice cream and visit the park”, I got the following prediction:

當我使用以下文字“天氣真熱,我想吃冰淇淋并參觀公園”時,我得到以下預測:

Prediction: negative
Probability: 97.91%

The model was able to predict accurately for both cases. And that's how you build a simple suicidal tweet classifier.

該模型能夠準確預測這兩種情況。 這就是您構建簡單的自殺性推文分類器的方式。

You can find the notebook I used for this article here

您可以在這里找到我用于本文的筆記本

Thanks for reading 😊

感謝您閱讀😊

翻譯自: https://towardsdatascience.com/building-a-suicidal-tweet-classifier-using-nlp-ff6ccd77e971

nlp構建

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392136.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392136.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392136.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

域名跳轉

案例&#xff1a;當訪問lsx.com網站&#xff0c;是我最早論壇的域名。回車之后會自動跳轉到lshx.com。 為什么藥lsx跳轉到lshx.com呢&#xff1f; 為了統一品牌。建議換成了lshx.com。所有之前的lsx.com就不要用了&#xff0c;就讓它跳轉到lshx.com。是因為之前lsx.com上有很多…

Elastic Stack 安裝

Elastic Stack 是一套支持數據采集、存儲、分析、并可視化全面的分析工具&#xff0c;簡稱 ELK&#xff08;Elasticsearch&#xff0c;Logstash&#xff0c;Kibana&#xff09;的縮寫。 安裝Elastic Stack 時&#xff0c;必須相關組件使用相同的版本&#xff0c;例如&#xff1…

區塊鏈去中心化分布式_為什么漸進式去中心化是區塊鏈的最大希望

區塊鏈去中心化分布式by Arthur Camara通過亞瑟卡馬拉(Arthur Camara) 為什么漸進式去中心化是區塊鏈的最大希望 (Why Progressive Decentralization is blockchain’s best hope) 不變性是區塊鏈的最大優勢和最大障礙。 逐步分權可能是答案。 (Immutability is blockchain’s…

編譯原理—語義分析(Java)

遞歸下降語法制導翻譯 實現含多條簡單賦值語句的簡化語言的語義分析和中間代碼生成。 測試樣例 begin a:2; b:4; c:c-1; area:3.14*a*a; s:2*3.1416*r*(hr); end #詞法分析 public class analyzer {public static List<String> llistnew ArrayList<>();static …

linux問題總結

linux問題總結 編寫后臺進程的管理腳本&#xff0c;使用service deamon-name stop的時候&#xff0c;出現如下提示&#xff1a;/sbin/service: line 66: 23299 Terminated env -i LANG"$LANG" PATH"$PATH" TERM"$TERM" "${SERVICEDIR}/${SE…

linux vi行尾總是顯示顏色,【轉載】Linux 下使用 vi 沒有顏色的解決辦法

vi 是沒有顏色的&#xff0c;vim 是有顏色的。我們可以通過 rpm -qa |grep vim 看看系統中是否安裝了下面 3 個 rpm 包&#xff0c;如果有就是安裝了 vim 。[rootBetty ~]# rpm -qa |grep vimvim-minimal-7.0.109-7.el5vim-enhanced-7.0.109-7.el5vim-common-7.0.109-7.el5如果…

時間序列分析 lstm_LSTM —時間序列分析

時間序列分析 lstmNeural networks can be a hard concept to wrap your head around. I think this is mostly due to the fact that they can be used for so many different things such as classification, identification or just simply regression.神經網絡可能是一個難…

關于計算圓周率PI的經典程序

短短幾行代碼&#xff0c;卻也可圈可點。如把變量s放在PI表達式中&#xff0c;還有正負值的處理&#xff0c;都堪稱經典。尤其是處處考慮執行效率的思想令人敬佩。 /* pi/41-1/31/5-1/71/9-…… */ #include <stdio.h> int main(){ int s1; float pi0.,n1.,…

華為產品技術學習筆記之路由原理(一)

路由器&#xff1a;路由器是一種典型的網絡連接設備&#xff0c;用來進行路由選擇和報文轉發。路由器與它直接相連的網絡的跳數為0&#xff0c;通過一臺路由器可達的網絡的跳數為1.路由協議&#xff1a;路由器之間維護路由表的規則&#xff0c;用以發現路由&#xff0c;生成路由…

Linux網絡配置:設置IP地址、網關DNS、主機名

查看網絡信息 1、ifconfig eth0 2、ifconfig -a 3、ip add 設置主機名需改配置文件&#xff1a; /etc/hosts /etc/sysconfig/network vim /etc/sysconfig/network NETWORKINGyes NETWORKING_IPV6no HOSTNAMEwendyhost Linux配置網絡 方法一&#xff1a; 1、使用setup命令進入如…

編譯原理—小型(簡化)高級語言分析器前端(Java)

實現一個一遍掃描的編譯前端&#xff0c;將簡化高級語言的部分語法成分&#xff08;含賦值語句、分支語句、循環語句等&#xff09;翻譯成四元式&#xff08;或三地址代碼&#xff09;&#xff0c;還要求有合理的語法出錯報錯和錯誤恢復功能。 測試樣例 beginwhile a<b do…

linux boot菜單列表,Bootstrap 下拉菜單(Dropdowns)簡介

Bootstrap 下拉菜單是可切換的&#xff0c;是以列表格式顯示鏈接的上下文菜單。這可以通過與 下拉菜單(Dropdown) JavaScript 插件 的互動來實現。如需使用下拉菜單&#xff0c;只需要在 class .dropdown 內加上下拉菜單即可。下面的實例演示了基本的下拉菜單&#xff1a;實例主…

dynamodb管理ttl_如何使用DynamoDB TTL和Lambda安排臨時任務

dynamodb管理ttlby Yan Cui崔燕 如何使用DynamoDB TTL和Lambda安排臨時任務 (How to schedule ad-hoc tasks with DynamoDB TTL and Lambda) CloudWatch Events let you easily create cron jobs with Lambda. However, it’s not designed for running lots of ad-hoc tasks,…

5g創業的構想_數據科學項目的五個具體構想

5g創業的構想Do you want to enter the data science world? Congratulations! That’s (still) the right choice.您想進入數據科學世界嗎&#xff1f; 恭喜你&#xff01; 那(仍然)是正確的選擇。 The market currently gets tougher. So, you must be mentally prepared f…

Microsoft Windows Phone 7 Toolkit Silverlight SDK XNA Game Studio 4.0 開發工具套件正式版下載...

Windows Phone 7開發工具套件包括Visual Studio 2010 Express for Windows Phone、Windows Phone模擬器、Expression Blend 4 for Windows Phone、XNA Game Studio 4.0和新增加的必應地圖SDK。 英文版的光盤鏡像&#xff1a;點擊下載 文檔中心&#xff1a;Windows Phone develo…

數據挖掘—Apriori算法(Java實現)

算法描述 &#xff08;1&#xff09;掃描全部數據&#xff0c;產生候選1-項集的集合C1&#xff1b; &#xff08;2&#xff09;根據最小支持度&#xff0c;由候選1-項集的集合C1產生頻繁1-項集的集合L1&#xff1b; &#xff08;3&#xff09;對k>1&#xff0c;重復執行步驟…

怎么匯報一周開發工作情況_如何在沒有經驗的情況下獲得第一份開發人員工作

怎么匯報一周開發工作情況Whether you’ve done a coding bootcamp or taught yourself, getting your first developer job with only a few months of coding under your belt is hard.無論您是完成了編碼訓練營還是自學了&#xff0c;僅靠幾個月的編碼就很難拿到第一份開發人…

vue.js的認知

Vue.js&#xff08;讀音 /vju?/, 類似于 view&#xff09; 是一套構建用戶界面的漸進式框架。 Vue 只關注視圖層&#xff0c; 采用自底向上增量開發的設計。 Vue 的目標是通過盡可能簡單的 API 實現響應的數據綁定和組合的視圖組件。 Vue 學習起來非常簡單&#xff0c;。轉載于…

c語言中的無符號字節,C語言之有符號數和無符號數

我們知道&#xff0c;在C語言中存在無符號數和有符號數(一些高級語言如Java里面是沒有無符號數的)&#xff0c;但是對于計算機而言&#xff0c;其本身并不區別有符號數和無符號數&#xff0c;因為在計算機里面都是0或者1&#xff0c;但是在我們的實際使用中有時候需要使用有符號…

8種排序算法比較

8種排序算法&#xff0c;各算法名稱見下表或見源碼。運行程序時&#xff0c;將需要你輸入一數值&#xff0c;以確定對多少隨機數進行排序。然后將會顯示各排序算法的耗時。并且你可選擇時否進行正序和反序測試。 由于水平有限&#xff0c;可能存在一些錯誤&#xff0c;還請各位…