Spaces:
Sleeping
Sleeping
Upload 5 files
Browse filesFiles changed (5)
- app.pyAdded+72
- cyberbullying.ipynbAdded+1343
- model.pklAdded+3
- requirements.txtAdded+7
- textcleaning.pyAdded+49
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import streamlit as st
import joblib
from textcleaning import clean_documents
import pandas as pd
model = joblib.load("model\model.pkl")
import streamlit as st
import pandas as pd
import joblib
model = joblib.load("model/model.pkl")
st.set_page_config(
page_title="Cyberbullying Detection",
page_icon="🛡️",
layout="centered"
)
st.markdown(
"""
<h1 style='text-align:center;color:#4CAF50;'>
🛡️ Automated Cyberbullying Detection & Classification System
</h1>
<p style='text-align:center;font-size:18px;color:gray;'>
Enter a social media message below to detect whether it contains cyberbullying.
</p>
<hr>
""",
unsafe_allow_html=True,
)
user_text = st.text_area(
"✍️ Enter Text",
placeholder="Type or paste a message here...",
height=180
)
col1, col2 = st.columns([1, 1])
with col1:
predict = st.button("🔍 Predict", use_container_width=True)
with col2:
clear = st.button("🗑️ Clear Output", use_container_width=True)
if clear:
st.rerun()
if predict:
if user_text.strip():
user_series = pd.Series([user_text])
with st.spinner("Analyzing text..."):
prediction = model.predict(user_series)[0]
st.markdown("---")
st.subheader("📊 Prediction Result")
if prediction == "not_cyberbullying":
st.success(f"✅ **Prediction:** {prediction}")
else:
st.error(f"🚨 **Prediction:** {prediction}")
else:
st.warning("⚠️ Please enter some text before clicking Predict.")
st.markdown("---")
st.caption("Developed using Streamlit | Scikit-learn | NLP | TF-IDF | Logistic Regression")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343{ "cells": [ { "cell_type": "markdown", "id": "853bb63c", "metadata": {}, "source": [ "**Problem Statement :**\n", "\n", "\n", "The widespread use of social media has led to a significant increase in cyberbullying, exposing users to abusive, offensive, and harmful online content. Manually identifying such content is time-consuming and inefficient due to the large volume of online interactions. \n", "\n", "Therefore, an automated machine learning-based system is needed to accurately detect and identify cyberbullying, helping create a safer and more secure online environment." ] }, { "cell_type": "markdown", "id": "6f7b53a4", "metadata": {}, "source": [ "**Objective :**\n", "* Develop a machine learning-based system to detect cyberbullying in online messages.\n", "* Automatically identify and classify harmful content into different cyberbullying categories.\n", "* Improve the accuracy and efficiency of cyberbullying detection.\n", "* Reduce the need for manual content monitoring and moderation.\n", "* Support social media platforms in creating a safer online environment." ] }, { "cell_type": "markdown", "id": "15404fec", "metadata": {}, "source": [ "**Step-0 :** Importing the Libraries " ] }, { "cell_type": "code", "execution_count": null, "id": "7ee11b2e", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "[nltk_data] Downloading package punkt to\n", "[nltk_data] C:\\Users\\pyara\\AppData\\Roaming\\nltk_data...\n", "[nltk_data] Package punkt is already up-to-date!\n", "[nltk_data] Downloading package punkt_tab to\n", "[nltk_data] C:\\Users\\pyara\\AppData\\Roaming\\nltk_data...\n", "[nltk_data] Package punkt_tab is already up-to-date!\n", "[nltk_data] Downloading package stopwords to\n", "[nltk_data] C:\\Users\\pyara\\AppData\\Roaming\\nltk_data...\n", "[nltk_data] Package stopwords is already up-to-date!\n", "[nltk_data] Downloading package wordnet to\n", "[nltk_data] C:\\Users\\pyara\\AppData\\Roaming\\nltk_data...\n", "[nltk_data] Package wordnet is already up-to-date!\n" ] } ], "source": [ "import numpy as np\n", "import pandas as pd\n", "\n", "\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "\n", "\n", "# Regular Expressions\n", "import re \n", "\n", "# -------------------\n", "# Data Cleaning\n", "# -------------------\n", "\n", "import nltk\n", "\n", "\n", "# For word tokenization\n", "from nltk.tokenize import word_tokenize\n", "nltk.download(\"punkt\")\n", "nltk.download(\"punkt_tab\")\n", "\n", "# For Removing the stop words \n", "from nltk.corpus import stopwords\n", "nltk.download(\"stopwords\")\n", "\n", "# For Stemming or Lemmitization\n", "from nltk.stem import WordNetLemmatizer,PorterStemmer\n", "nltk.download('wordnet')\n", "\n", "# -----------------\n", "# Model Building \n", "# -----------------\n", "\n", "import sklearn\n", "\n", "# For Splitting the data into train and test \n", "from sklearn.model_selection import train_test_split\n", "\n", "# For Data Preprocessing\n", "\n", "# Binary Bag of word\n", "from sklearn.feature_extraction.text import CountVectorizer\n", "\n", "\n", "# tfidf vectorizer\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "\n", "\n", "# Pipeline\n", "from sklearn.pipeline import Pipeline\n", "from sklearn.preprocessing import FunctionTransformer\n", "\n", "# Algorithms\n", "from sklearn.neighbors import KNeighborsClassifier\n", "from sklearn.naive_bayes import GaussianNB\n", "from sklearn.tree import DecisionTreeClassifier\n", "from sklearn.linear_model import LogisticRegression\n", "\n", "\n", "from sklearn.model_selection import GridSearchCV\n", "\n", "# Metrics \n", "\n", "from sklearn.metrics import accuracy_score\n", "\n", "from textcleaning import clean_documents\n", "\n" ] }, { "cell_type": "markdown", "id": "6d2c01fe", "metadata": {}, "source": [ "**Step-1 :** Data Collection" ] }, { "cell_type": "code", "execution_count": null, "id": "2cb4a921", "metadata": {}, "outputs": [], "source": [ "df=pd.read_csv(r\"..\\data\\cyberbullying_tweets.csv\")" ] }, { "cell_type": "code", "execution_count": null, "id": "59fa36a0", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>tweet_text</th>\n", " <th>cyberbullying_type</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>In other words #katandandre, your food was cra...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>Why is #aussietv so white? #MKR #theblock #ImA...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>@XochitlSuckkks a classy whore? Or more red ve...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>@Jason_Gio meh. :P thanks for the heads up, b...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>@RudhoeEnglish This is an ISIS account pretend...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>...</th>\n", " <td>...</td>\n", " <td>...</td>\n", " </tr>\n", " <tr>\n", " <th>47687</th>\n", " <td>Black ppl aren't expected to do anything, depe...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>47688</th>\n", " <td>Turner did not withhold his disappointment. Tu...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>47689</th>\n", " <td>I swear to God. This dumb nigger bitch. I have...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>47690</th>\n", " <td>Yea fuck you RT @therealexel: IF YOURE A NIGGE...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>47691</th>\n", " <td>Bro. U gotta chill RT @CHILLShrammy: Dog FUCK ...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "<p>47692 rows × 2 columns</p>\n", "</div>" ], "text/plain": [ " tweet_text cyberbullying_type\n", "0 In other words #katandandre, your food was cra... not_cyberbullying\n", "1 Why is #aussietv so white? #MKR #theblock #ImA... not_cyberbullying\n", "2 @XochitlSuckkks a classy whore? Or more red ve... not_cyberbullying\n", "3 @Jason_Gio meh. :P thanks for the heads up, b... not_cyberbullying\n", "4 @RudhoeEnglish This is an ISIS account pretend... not_cyberbullying\n", "... ... ...\n", "47687 Black ppl aren't expected to do anything, depe... ethnicity\n", "47688 Turner did not withhold his disappointment. Tu... ethnicity\n", "47689 I swear to God. This dumb nigger bitch. I have... ethnicity\n", "47690 Yea fuck you RT @therealexel: IF YOURE A NIGGE... ethnicity\n", "47691 Bro. U gotta chill RT @CHILLShrammy: Dog FUCK ... ethnicity\n", "\n", "[47692 rows x 2 columns]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df" ] }, { "cell_type": "markdown", "id": "a990f269", "metadata": {}, "source": [ "Step 2 - EDA (Data Understanding)" ] }, { "cell_type": "code", "execution_count": null, "id": "83f93fea", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(47692, 2)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# checking the shape\n", "\n", "df.shape" ] }, { "cell_type": "code", "execution_count": null, "id": "1c68c2aa", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<class 'pandas.DataFrame'>\n", "RangeIndex: 47692 entries, 0 to 47691\n", "Data columns (total 2 columns):\n", " # Column Non-Null Count Dtype\n", "--- ------ -------------- -----\n", " 0 tweet_text 47692 non-null str \n", " 1 cyberbullying_type 47692 non-null str \n", "dtypes: str(2)\n", "memory usage: 7.4 MB\n" ] } ], "source": [ "df.info()" ] }, { "cell_type": "markdown", "id": "edc46152", "metadata": {}, "source": [ "**Observation :**\n", "\n", "* It contains 47656 records and 2 feature " ] }, { "cell_type": "code", "execution_count": null, "id": "18eab2cf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "np.int64(0)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Checking the null values\n", "\n", "df.isnull().sum().sum()" ] }, { "cell_type": "code", "execution_count": null, "id": "5ce01375", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "np.int64(36)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.duplicated().sum()\n", "\n" ] }, { "cell_type": "markdown", "id": "aa7689df", "metadata": {}, "source": [ "**Observation** \n", "\n", "* There are **no null values**\n", "* There are **duplicates**, we need to remove them " ] }, { "cell_type": "code", "execution_count": null, "id": "e233229d", "metadata": {}, "outputs": [], "source": [ "# removing the duplicates \n", "\n", "df.drop_duplicates(inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "781286c6", "metadata": {}, "outputs": [], "source": [ "# resetting the index\n", "\n", "df.reset_index(inplace=True,drop=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "17fa89a8", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>tweet_text</th>\n", " <th>cyberbullying_type</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>In other words #katandandre, your food was cra...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>Why is #aussietv so white? #MKR #theblock #ImA...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>@XochitlSuckkks a classy whore? Or more red ve...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>@Jason_Gio meh. :P thanks for the heads up, b...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>@RudhoeEnglish This is an ISIS account pretend...</td>\n", " <td>not_cyberbullying</td>\n", " </tr>\n", " <tr>\n", " <th>...</th>\n", " <td>...</td>\n", " <td>...</td>\n", " </tr>\n", " <tr>\n", " <th>47651</th>\n", " <td>Black ppl aren't expected to do anything, depe...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>47652</th>\n", " <td>Turner did not withhold his disappointment. Tu...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>47653</th>\n", " <td>I swear to God. This dumb nigger bitch. I have...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>47654</th>\n", " <td>Yea fuck you RT @therealexel: IF YOURE A NIGGE...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>47655</th>\n", " <td>Bro. U gotta chill RT @CHILLShrammy: Dog FUCK ...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "<p>47656 rows × 2 columns</p>\n", "</div>" ], "text/plain": [ " tweet_text cyberbullying_type\n", "0 In other words #katandandre, your food was cra... not_cyberbullying\n", "1 Why is #aussietv so white? #MKR #theblock #ImA... not_cyberbullying\n", "2 @XochitlSuckkks a classy whore? Or more red ve... not_cyberbullying\n", "3 @Jason_Gio meh. :P thanks for the heads up, b... not_cyberbullying\n", "4 @RudhoeEnglish This is an ISIS account pretend... not_cyberbullying\n", "... ... ...\n", "47651 Black ppl aren't expected to do anything, depe... ethnicity\n", "47652 Turner did not withhold his disappointment. Tu... ethnicity\n", "47653 I swear to God. This dumb nigger bitch. I have... ethnicity\n", "47654 Yea fuck you RT @therealexel: IF YOURE A NIGGE... ethnicity\n", "47655 Bro. U gotta chill RT @CHILLShrammy: Dog FUCK ... ethnicity\n", "\n", "[47656 rows x 2 columns]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df" ] }, { "cell_type": "code", "execution_count": null, "id": "24186d13", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "cyberbullying_type\n", "religion 7997\n", "age 7992\n", "ethnicity 7959\n", "gender 7948\n", "not_cyberbullying 7937\n", "other_cyberbullying 7823\n", "Name: count, dtype: int64" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df['cyberbullying_type'].value_counts()" ] }, { "cell_type": "markdown", "id": "42c11240", "metadata": {}, "source": [] }, { "cell_type": "markdown", "id": "0caa0281", "metadata": {}, "source": [ "**Step 3 :** Feature Engineering" ] }, { "cell_type": "markdown", "id": "b5e37845", "metadata": {}, "source": [ "The data set contain an ordered collection of the categorization and i want to shuffle it " ] }, { "cell_type": "code", "execution_count": null, "id": "583fd140", "metadata": {}, "outputs": [], "source": [ "# Shuffling the data \n", "from sklearn.utils import shuffle \n", "\n", "df=shuffle(df)" ] }, { "cell_type": "code", "execution_count": null, "id": "de37e95d", "metadata": {}, "outputs": [], "source": [ "# Reseting the index \n", "df.reset_index(drop=True,inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "07243f8d", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>tweet_text</th>\n", " <th>cyberbullying_type</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>are you an idiot? what is hindutwa the temple ...</td>\n", " <td>religion</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>stoled reply and ill give u sum emojiz = luv u...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>@seijohgorl hoy mami keito AAAA okay so um ika...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>The girl that used to bully me in high school ...</td>\n", " <td>age</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>@boxedariel @LostSailorNY No one said she should.</td>\n", " <td>gender</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " tweet_text cyberbullying_type\n", "0 are you an idiot? what is hindutwa the temple ... religion\n", "1 stoled reply and ill give u sum emojiz = luv u... ethnicity\n", "2 @seijohgorl hoy mami keito AAAA okay so um ika... ethnicity\n", "3 The girl that used to bully me in high school ... age\n", "4 @boxedariel @LostSailorNY No one said she should. gender" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Verifying the modified data \n", "df.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "59c6e2f8", "metadata": {}, "outputs": [], "source": [ "# renaming the columns \n", "\n", "df.rename(columns={'tweet_text':'tweet','cyberbullying_type':'type'},inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "87f9a2f7", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>tweet</th>\n", " <th>type</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>are you an idiot? what is hindutwa the temple ...</td>\n", " <td>religion</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>stoled reply and ill give u sum emojiz = luv u...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>@seijohgorl hoy mami keito AAAA okay so um ika...</td>\n", " <td>ethnicity</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>The girl that used to bully me in high school ...</td>\n", " <td>age</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>@boxedariel @LostSailorNY No one said she should.</td>\n", " <td>gender</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " tweet type\n", "0 are you an idiot? what is hindutwa the temple ... religion\n", "1 stoled reply and ill give u sum emojiz = luv u... ethnicity\n", "2 @seijohgorl hoy mami keito AAAA okay so um ika... ethnicity\n", "3 The girl that used to bully me in high school ... age\n", "4 @boxedariel @LostSailorNY No one said she should. gender" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.head()" ] }, { "cell_type": "markdown", "id": "987abb18", "metadata": {}, "source": [ "**Step 4 :** X and y" ] }, { "cell_type": "code", "execution_count": null, "id": "c24afc85", "metadata": {}, "outputs": [], "source": [ "# Selecting the target and input features \n", "\n", "y=df['type']\n", "X=df['tweet']" ] }, { "cell_type": "code", "execution_count": null, "id": "488cb0aa", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(47656,)" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Checking \n", "\n", "X.shape" ] }, { "cell_type": "code", "execution_count": null, "id": "925425bf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 are you an idiot? what is hindutwa the temple ...\n", "1 stoled reply and ill give u sum emojiz = luv u...\n", "2 @seijohgorl hoy mami keito AAAA okay so um ika...\n", "3 The girl that used to bully me in high school ...\n", "4 @boxedariel @LostSailorNY No one said she should.\n", "Name: tweet, dtype: str" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "47b9b2bc", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(47656,)" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y.shape" ] }, { "cell_type": "code", "execution_count": null, "id": "b1b24cf0", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 religion\n", "1 ethnicity\n", "2 ethnicity\n", "3 age\n", "4 gender\n", "Name: type, dtype: str" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y.head()" ] }, { "cell_type": "markdown", "id": "61418db3", "metadata": {}, "source": [ "**Step 5 :** Data Cleaning\n" ] }, { "cell_type": "code", "execution_count": null, "id": "23049510", "metadata": {}, "outputs": [], "source": [ "\n", "# # text cleaning function \n", "\n", "# def cleaning(document):\n", "# # Lower casing\n", "# document=document.lower()\n", " \n", "# # Removing the Numbers and Special Symbols and puntuation\n", "# regex=r\"[^a-zA-Z]+\"\n", "# document=re.sub(regex,\" \",document)\n", "\n", "# # word Tokenization\n", "# document=word_tokenize(document)\n", "\n", "# # Removing the stopwords \n", "# stop_words=set(stopwords.words('english'))\n", "# document=[ word for word in document if word not in stop_words ]\n", "\n", "# # Stemming or Lemmitization \n", "# lemmitizer=WordNetLemmatizer()\n", "# document=[lemmitizer.lemmatize(word) for word in document]\n", "\n", "# # Join and return\n", "# return \" \".join(document)" ] }, { "cell_type": "code", "execution_count": null, "id": "617d7f31", "metadata": {}, "outputs": [], "source": [ "# def clean_documents(corpus):\n", "# return corpus.apply(cleaning)" ] }, { "cell_type": "code", "execution_count": null, "id": "2ea66530", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 are you an idiot? what is hindutwa the temple ...\n", "1 stoled reply and ill give u sum emojiz = luv u...\n", "2 @seijohgorl hoy mami keito AAAA okay so um ika...\n", "3 The girl that used to bully me in high school ...\n", "4 @boxedariel @LostSailorNY No one said she should.\n", "Name: tweet, dtype: str" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X.head()" ] }, { "cell_type": "markdown", "id": "0c89291f", "metadata": {}, "source": [ "**Step 6 :** Train-Test Split" ] }, { "cell_type": "code", "execution_count": null, "id": "eebe9cf2", "metadata": {}, "outputs": [], "source": [ "X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,shuffle=True,random_state=1)" ] }, { "cell_type": "markdown", "id": "7247f506", "metadata": {}, "source": [ "**Step 7 :** Data Preprocessing" ] }, { "cell_type": "code", "execution_count": null, "id": "248ea06a", "metadata": {}, "outputs": [], "source": [ "# vectorizer=CountVectorizer(binary=True)\n", "# binary_bow=vectorizer.fit_transform(X_train)" ] }, { "cell_type": "code", "execution_count": null, "id": "fdc0aeeb", "metadata": {}, "outputs": [], "source": [ "# vectorizer.get_feature_names_out()" ] }, { "cell_type": "code", "execution_count": null, "id": "07d4039a", "metadata": {}, "outputs": [], "source": [ "# tfidf_matrix=vectorizer.fit_transform(X_train)" ] }, { "cell_type": "code", "execution_count": null, "id": "59d966d6", "metadata": {}, "outputs": [], "source": [ "\n", "# from sklearn.preprocessing import FunctionTransformer\n", "# preprocessing_pipeline=Pipeline([(\"cleaning\",FunctionTransformer(clean_documents)),\n", "# ('Preprocessing',TfidfVectorizer())\n", "# ])" ] }, { "cell_type": "code", "execution_count": null, "id": "4a044aae", "metadata": {}, "outputs": [], "source": [ "# preprocessing_pipeline.named_steps[\"Preprocessing\"]" ] }, { "cell_type": "code", "execution_count": null, "id": "37871dff", "metadata": {}, "outputs": [], "source": [ "prepocessing=Pipeline([('preprocessing',TfidfVectorizer())])" ] }, { "cell_type": "markdown", "id": "4921cdf1", "metadata": {}, "source": [ "**Step 8 :** Base Line Models" ] }, { "cell_type": "code", "execution_count": null, "id": "79df75ed", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The accuracy of the model knn is 0.24234158623583718\n", "The accuracy of the model tree is 0.7906000839278221\n", "The accuracy of the model logistic is 0.836970205623164\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "d:\\Data Science\\DataScienceProject\\CyberBullying\\venv\\Lib\\site-packages\\sklearn\\linear_model\\_logistic.py:599: ConvergenceWarning: lbfgs failed to converge after 100 iteration(s) (status=1):\n", "STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT\n", "\n", "Increase the number of iterations to improve the convergence (max_iter=100).\n", "You might also want to scale the data as shown in:\n", " https://scikit-learn.org/stable/modules/preprocessing.html\n", "Please also refer to the documentation for alternative solver options:\n", " https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n", " n_iter_i = _check_optimize_result(\n" ] } ], "source": [ "models={\"knn\":KNeighborsClassifier(),\n", " 'tree':DecisionTreeClassifier(),\n", " 'logistic':LogisticRegression()\n", " }\n", "\n", "for name,model in models.items():\n", " pipe=Pipeline([('preprocessing',TfidfVectorizer()),\n", " (name,model)])\n", " \n", " pipe.fit(X_train,y_train)\n", "\n", " # prediction\n", " y_pred=pipe.predict(X_test)\n", "\n", " # Accuracy \n", " print(f\"The accuracy of the model {name} is {accuracy_score(y_test,y_pred)}\")" ] }, { "cell_type": "markdown", "id": "da62dfed", "metadata": {}, "source": [ "**Step 8 :** Hyper Parameter tunning" ] }, { "cell_type": "code", "execution_count": null, "id": "088cb35e", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "d:\\Data Science\\DataScienceProject\\CyberBullying\\venv\\Lib\\site-packages\\sklearn\\linear_model\\_logistic.py:1403: FutureWarning: 'penalty' was deprecated in version 1.8 and will be removed in 1.10. To avoid this warning, leave 'penalty' set to its default value and use 'l1_ratio' or 'C' instead. Use l1_ratio=0 instead of penalty='l2', l1_ratio=1 instead of penalty='l1', l1_ratio set to a float between 0 and 1 instead of penalty='elasticnet', and C=np.inf instead of penalty=None.\n", " warnings.warn(\n", "d:\\Data Science\\DataScienceProject\\CyberBullying\\venv\\Lib\\site-packages\\sklearn\\linear_model\\_logistic.py:1429: UserWarning: Inconsistent values: penalty=l1 with l1_ratio=0.0. penalty is deprecated. Please use l1_ratio only.\n", " warnings.warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Best Parameters: {'lr__penalty': 'l1'}\n", "Best CV Score: 0.8317071852476218\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "d:\\Data Science\\DataScienceProject\\CyberBullying\\venv\\Lib\\site-packages\\sklearn\\linear_model\\_sag.py:348: ConvergenceWarning: The max_iter was reached which means the coef_ did not converge\n", " warnings.warn(\n" ] } ], "source": [ "\n", "\n", "pipeline = Pipeline([\n", " (\"tfidf\", TfidfVectorizer()),\n", " (\"lr\", LogisticRegression(solver=\"saga\", random_state=42))\n", "])\n", "\n", "param_grid = {\n", " \"lr__penalty\": [\"l1\", \"l2\"]\n", "}\n", "\n", "grid_search = GridSearchCV(\n", " estimator=pipeline,\n", " param_grid=param_grid,\n", " cv=5,\n", " scoring=\"accuracy\",\n", " n_jobs=-1\n", ")\n", "\n", "grid_search.fit(X_train, y_train)\n", "\n", "print(\"Best Parameters:\", grid_search.best_params_)\n", "print(\"Best CV Score:\", grid_search.best_score_)\n" ] }, { "cell_type": "markdown", "id": "062f7300", "metadata": {}, "source": [ " **Step 11 : Best Model Selection**" ] }, { "cell_type": "code", "execution_count": null, "id": "8f632b63", "metadata": {}, "outputs": [], "source": [ "final_pipeline=Pipeline([('cleaning',FunctionTransformer(clean_documents)),\n", " ('preproccessing',TfidfVectorizer()),\n", " ('model',LogisticRegression(solver=\"saga\", random_state=42,penalty='l1'))\n", " ])" ] }, { "cell_type": "code", "execution_count": null, "id": "477e908b", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "d:\\Data Science\\DataScienceProject\\CyberBullying\\venv\\Lib\\site-packages\\sklearn\\linear_model\\_logistic.py:1403: FutureWarning: 'penalty' was deprecated in version 1.8 and will be removed in 1.10. To avoid this warning, leave 'penalty' set to its default value and use 'l1_ratio' or 'C' instead. Use l1_ratio=0 instead of penalty='l2', l1_ratio=1 instead of penalty='l1', l1_ratio set to a float between 0 and 1 instead of penalty='elasticnet', and C=np.inf instead of penalty=None.\n", " warnings.warn(\n", "d:\\Data Science\\DataScienceProject\\CyberBullying\\venv\\Lib\\site-packages\\sklearn\\linear_model\\_logistic.py:1429: UserWarning: Inconsistent values: penalty=l1 with l1_ratio=0.0. penalty is deprecated. Please use l1_ratio only.\n", " warnings.warn(\n", "d:\\Data Science\\DataScienceProject\\CyberBullying\\venv\\Lib\\site-packages\\sklearn\\linear_model\\_sag.py:348: ConvergenceWarning: The max_iter was reached which means the coef_ did not converge\n", " warnings.warn(\n" ] } ], "source": [ "final_model=final_pipeline.fit(X_train,y_train)" ] }, { "cell_type": "markdown", "id": "dec1d3ee", "metadata": {}, "source": [ "**Step 10 : Model Evaluation**" ] }, { "cell_type": "code", "execution_count": null, "id": "5364887f", "metadata": {}, "outputs": [], "source": [ "y_pred=final_model.predict(X_test)" ] }, { "cell_type": "code", "execution_count": null, "id": "842b1b01", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy:\n", "0.835396558959295\n" ] } ], "source": [ "print(\"Accuracy:\")\n", "print(accuracy_score(y_test,y_pred))" ] }, { "cell_type": "markdown", "id": "c71ebaf0", "metadata": {}, "source": [ "**Step 12 : Save Complete Pipeline**" ] }, { "cell_type": "code", "execution_count": null, "id": "ad14101d", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "<>:2: SyntaxWarning: \"\\m\" is an invalid escape sequence. Such sequences will not work in the future. Did you mean \"\\\\m\"? A raw string is also an option.\n", "<>:2: SyntaxWarning: \"\\m\" is an invalid escape sequence. Such sequences will not work in the future. Did you mean \"\\\\m\"? A raw string is also an option.\n", "C:\\Users\\pyara\\AppData\\Local\\Temp\\ipykernel_18096\\856584563.py:2: SyntaxWarning: \"\\m\" is an invalid escape sequence. Such sequences will not work in the future. Did you mean \"\\\\m\"? A raw string is also an option.\n", " joblib.dump(final_model,'..\\model\\model.pkl')\n" ] }, { "data": { "text/plain": [ "['..\\\\model\\\\model.pkl']" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import joblib\n", "joblib.dump(final_model,'..\\model\\model.pkl')" ] }, { "cell_type": "code", "execution_count": null, "id": "d69d9b70", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python (cyber-env)", "language": "python", "name": "cyber-env" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.3" } }, "nbformat": 4, "nbformat_minor": 5}123version https://git-lfs.github.com/spec/v1oid sha256:752516bd98c5c31c5ec7fb18c69c5768107d4af355211d3033f5e9311c4d0542size 32958681234567streamlit
numpy
pandas
joblib
scikit-learn
matplotlib
seaborn12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
import nltk
# For word tokenization
from nltk.tokenize import word_tokenize
nltk.download("punkt")
nltk.download("punkt_tab")
# For Removing the stop words
from nltk.corpus import stopwords
nltk.download("stopwords")
# For Stemming or Lemmitization
from nltk.stem import WordNetLemmatizer,PorterStemmer
nltk.download('wordnet')
import re
# tfidf vectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
def cleaning(document):
# Lower casing
document=document.lower()
# Removing the Numbers and Special Symbols and puntuation
regex=r"[^a-zA-Z]+"
document=re.sub(regex," ",document)
# word Tokenization
document=word_tokenize(document)
# Removing the stopwords
stop_words=set(stopwords.words('english'))
document=[ word for word in document if word not in stop_words ]
# Stemming or Lemmitization
lemmitizer=WordNetLemmatizer()
document=[lemmitizer.lemmatize(word) for word in document]
# Join and return
return " ".join(document)
def clean_documents(corpus):
return corpus.apply(cleaning)app.pyAdded+72
cyberbullying.ipynbAdded+1343
model.pklAdded+3
requirements.txtAdded+7
textcleaning.pyAdded+49