Skip to content

Commit

Permalink
agregando caso extra sobre el pipeline de transformers
Browse files Browse the repository at this point in the history
  • Loading branch information
EdwinFLopez committed Jun 15, 2024
1 parent 21fc418 commit c58f37c
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 53 deletions.
129 changes: 83 additions & 46 deletions caso02/caso_analitica_nlp_twitter.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"source": [
"## Introducción\n",
"\n",
"En este Caso 3 debes realizar un análisis sentimental, sintáctico y gramatical de comentarios Twitter. La base de datos la puedes descargar desde eStudy (Caso 3 dataset), la cual contiene un CSV de mensajes enviados a Twitter con las siguientes columnas:\n",
"En este Caso 2 debes realizar un análisis sentimental, sintáctico y gramatical de comentarios Twitter. La base de datos la puedes descargar desde eStudy (Caso 3 dataset), la cual contiene un CSV de mensajes enviados a Twitter con las siguientes columnas:\n",
"\n",
"1. Puntuación sentimental o polaridad (-5 = negativa ... 0 = neutral ... 5 = positiva) (por calcular)\n",
"2. Id del tweet\n",
Expand Down Expand Up @@ -58,32 +58,37 @@
"1. [Getting Started with Sentiment Analysis using Python](https://huggingface.co/blog/sentiment-analysis-python) \n",
"2. [Pipelines](https://huggingface.co/docs/transformers/main_classes/pipelines)\n",
"\n",
"---\n"
"---"
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": [
"\n",
"### Librerías Necesarias"
],
"id": "45543ed5114c2431"
},
{
"cell_type": "code",
"id": "initial_id",
"metadata": {},
"source": [
"# Librerías\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import textstat\n",
"import pandas as pd\n",
"import os\n",
"import re\n",
"import seaborn as sns\n",
"from textblob import TextBlob\n",
"import textstat\n",
"\n",
"from collections import Counter\n",
"from wordcloud import WordCloud\n",
"import re\n",
"import nltk\n",
"from nltk.corpus import stopwords\n",
"from nltk.tokenize import word_tokenize\n",
"from nltk.stem import WordNetLemmatizer\n",
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"from sklearn.cluster import KMeans\n",
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"from textblob import TextBlob\n",
"from wordcloud import WordCloud\n",
"\n",
"\n",
"from caso02.descomprimir_dataset import unzip_dataset\n"
"from caso02.descomprimir_dataset import unzip_dataset"
],
"outputs": [],
"execution_count": null
Expand All @@ -97,18 +102,44 @@
"# Cargar dataset y descomprimir en /datos\n",
"csv_dataset_path = unzip_dataset()\n",
"print(csv_dataset_path)\n",
"\n",
"tweets_df = pd.read_csv(csv_dataset_path)\n",
"tweets_muestra = tweets_df.sample(n=50000)\n",
"tweets_df.describe()\n",
"\n",
"tweets_df.describe()"
],
"outputs": [],
"execution_count": null
},
{
"metadata": {},
"cell_type": "markdown",
"source": [
"### Descarga de recursos necesarios de NLTK\n",
"Iniciamos la ruta dentro de \"./data/nltk_data\" relativa al proyecto.\n",
"Debe ser antes del import de la librería para que tenga efecto.\n",
"Por defecto, se usa en la ruta del usuario, lo que puede ser problemático en otras instalaciones y proyectos."
],
"id": "bda63680547bc426"
},
{
"metadata": {},
"cell_type": "code",
"source": [
"#Descarga de recursos necesarios de NLTK\n",
"nltk.download('punkt')\n",
"nltk.download('stopwords')\n",
"nltk.download('wordnet')\n",
"nltk.download('omw-1.4')\n",
"nltk.download('words')\n",
"# Procesamiento del dataframe\n"
"os.environ[\"NLTK_DATA\"]=os.path.abspath('./data/nltk_data')\n",
"import nltk\n",
"from nltk.corpus import stopwords\n",
"from nltk.stem import WordNetLemmatizer\n",
"from nltk.tokenize import word_tokenize\n",
"\n",
"nltk.data.path.append(os.path.abspath('./data/nltk_data'))\n",
"nltk.download('punkt', download_dir=os.path.abspath('./data/nltk_data'))\n",
"nltk.download('stopwords', download_dir=os.path.abspath('./data/nltk_data'))\n",
"nltk.download('wordnet', download_dir=os.path.abspath('./data/nltk_data'))\n",
"nltk.download('omw-1.4', download_dir=os.path.abspath('./data/nltk_data'))\n",
"nltk.download('words', download_dir=os.path.abspath('./data/nltk_data'))"
],
"id": "7eb60f3b3cd512fe",
"outputs": [],
"execution_count": null
},
Expand All @@ -135,7 +166,7 @@
"source": [
"# Otros Códigos\n",
"tweets_df.columns = ['target', 'ids', 'date', 'flag', 'user', 'text']\n",
"tweets_df.head()\n"
"tweets_df.head()"
],
"outputs": [],
"execution_count": null
Expand Down Expand Up @@ -178,7 +209,7 @@
"cell_type": "code",
"source": [
"#1.\n",
"def limpieza_Datos(text):\n",
"def limpieza_datos(text):\n",
" text = text.lower()\n",
" text = re.sub(r'\\d+', '', text) \n",
" text = re.sub(r'\\s+', ' ', text)\n",
Expand All @@ -188,7 +219,7 @@
" return text\n",
"\n",
"#Aplicamos la funcion Limpieza de Datos en el Dataset\n",
"tweets_df['text'] = tweets_df['text'].apply(limpieza_Datos)\n",
"tweets_df['text'] = tweets_df['text'].apply(limpieza_datos)\n",
"\n",
"#Printamos los Datos para visualizar la limpieza\n",
"tweets_df.head(100)"
Expand All @@ -203,13 +234,13 @@
"source": [
"#2.\n",
"stop_words = set(stopwords.words('english'))\n",
"def tokenizar_y_eliminar_Stopwords(text):\n",
"def tokenizar_y_eliminar_stopwords(text):\n",
" tokens = word_tokenize(text)\n",
" tokens_filtrados = [word for word in tokens if word not in stop_words]\n",
" return tokens_filtrados\n",
"\n",
"#Aplicamos la función sobre el dataset\n",
"tweets_df['tokens'] = tweets_df['text'].apply(tokenizar_y_eliminar_Stopwords)"
"tweets_df['tokens'] = tweets_df['text'].apply(tokenizar_y_eliminar_stopwords)"
],
"id": "d649c2554b461d10",
"outputs": [],
Expand Down Expand Up @@ -264,13 +295,10 @@
" plt.show()\n",
"\n",
"metodo_elbow(X)\n",
"\n",
"kmeans = KMeans(n_clusters=3, max_iter=300, n_init=10, random_state=0)\n",
"clusters = kmeans.fit_predict(X)\n",
"\n",
"tweets_df['cluster'] = clusters\n",
"\n",
"tweets_df.head()\n"
"tweets_df.head()"
],
"id": "48c78b7461b78f9d",
"outputs": [],
Expand Down Expand Up @@ -317,7 +345,7 @@
"polarity_counts.plot(kind='bar', title='Distribución de las Polaridades de los Tweets')\n",
"plt.xlabel('Polaridad')\n",
"plt.ylabel('Cantidad de Tweets')\n",
"plt.show()\n"
"plt.show()"
],
"outputs": [],
"execution_count": null
Expand All @@ -340,7 +368,7 @@
"plt.ylabel('Complejidad de Lectura')\n",
"plt.show()\n",
"\n",
"print(tweets_df.head(100))\n"
"tweets_df.head(100)"
],
"id": "15df0463515bc6aa",
"outputs": [],
Expand All @@ -359,19 +387,19 @@
"id": "2f2b7d68a71f23cd",
"metadata": {},
"source": [
"#2. \n",
"\n",
"#2.\n",
"tweets_positivos = tweets_df[tweets_df['polarity'] > 0]\n",
"tweets_negativos = tweets_df[tweets_df['polarity'] < 0]\n",
"\n",
"frecuencia_palabras_positivas = Counter([word for tokens in tweets_positivos['lemmatized_tokens'] for word in tokens])\n",
"\n",
"frecuencia_palabras_negativas = Counter([word for tokens in tweets_negativos['lemmatized_tokens'] for word in tokens])\n",
"\n",
"palabras_comunes_positivas = frecuencia_palabras_positivas.most_common(20)\n",
"palabras_comunes_negativas = frecuencia_palabras_negativas.most_common(20)\n",
"\n",
"df_palabras_positivas = pd.DataFrame(palabras_comunes_positivas, columns=['Palabra', 'Frecuencia'])\n",
"df_palabras_negativas = pd.DataFrame(palabras_comunes_negativas, columns=['Palabra', 'Frecuencia'])\n"
"df_palabras_negativas = pd.DataFrame(palabras_comunes_negativas, columns=['Palabra', 'Frecuencia'])"
],
"outputs": [],
"execution_count": null
Expand Down Expand Up @@ -461,7 +489,7 @@
"source": [
"Interpretación de Resultados:\n",
"\n",
"- El resultado de la grafica de disperción nos indica que la polaridad de los tweets (si son más positivos o negativos) no tiene un impacto directo en la cantidad de seguidores que un usuario puede tener en este conjunto de datos.\n",
"- El resultado de la gráfica de dispersión nos indica que la polaridad de los tweets (si son más positivos o negativos) no tiene un impacto directo en la cantidad de seguidores que un usuario puede tener en este conjunto de datos.\n",
"\n",
"- Otros factores como la relevancia del contenido, la interacción con otros usuarios, la frecuencia de publicación y la popularidad previa pueden influir más en el número de seguidores de un usuario en esta muestra."
],
Expand All @@ -485,7 +513,6 @@
"metadata": {},
"source": [
"#4.a\n",
"\n",
"tweets_extremos = tweets_df[(tweets_df['polarity'] == 5) | (tweets_df['polarity'] == -5)]\n",
"\n",
"#Se identifican las frecuencias de palabras en los tweets con polaridad extrema\n",
Expand Down Expand Up @@ -513,7 +540,6 @@
"cell_type": "code",
"source": [
"#4.b\n",
"\n",
"tweets_df['tema_love'] = tweets_df['processed_text'].apply(lambda text: 1 if 'love' in text else 0)\n",
"usuarios_love = tweets_df[tweets_df['tema_love'] == 1]\n",
"\n",
Expand All @@ -531,7 +557,7 @@
"plt.ylabel('Complejidad de lectura')\n",
"plt.show()\n",
"\n",
"print(tweets_df[['user', 'polarity', 'cluster']].head(50))"
"tweets_df[['user', 'polarity', 'cluster']].head(50)"
],
"id": "168b3315195527a3",
"outputs": [],
Expand Down Expand Up @@ -573,7 +599,7 @@
"cell_type": "code",
"source": [
"#Agrupamos por mes y se calcula la polaridad promedio\n",
"polaridad_mensual = tweets_df.resample('M', on='date')['polarity'].mean().reset_index()\n",
"polaridad_mensual = tweets_df.resample('ME', on='date')['polarity'].mean().reset_index()\n",
"\n",
"#Se grafica la polaridad promedio mes a mes para análisis exhaustivo\n",
"plt.figure(figsize=(14, 7))\n",
Expand All @@ -599,7 +625,7 @@
"metadata": {},
"cell_type": "markdown",
"source": [
"Para identificar a los Trolls e Influencer debemos tener en cuenta las suigientes caractetístcas:\n",
"Para identificar a los Trolls e Influencer debemos tener en cuenta las siguientes características:\n",
"- Trolls:\n",
" - Generan una gran cantidad de tweets con polaridad negativa.\n",
" - Pueden tener un alto número de menciones negativas en sus tweets.\n",
Expand Down Expand Up @@ -682,7 +708,16 @@
"metadata": {},
"source": [
"# Respuesta\n",
"print(\"Respuestas\")"
"from transformers import pipeline\n",
"\n",
"# Creamos un analisis de sentimientos usando el pipeline\n",
"nlp = pipeline(\"sentiment-analysis\", model=\"finiteautomata/bertweet-base-sentiment-analysis\")\n",
"resultados_analisis_sentimientos = nlp(tweets_df['text'].tolist())\n",
"\n",
"\n",
"\n",
"# Display the DataFrame with sentiment analysis results\n",
"#tweets_df.head()"
],
"outputs": [],
"execution_count": null
Expand Down Expand Up @@ -721,7 +756,7 @@
"plt.xlabel('Fecha')\n",
"plt.ylabel('Promedio polaridad')\n",
"plt.grid(True)\n",
"plt.show()\n"
"plt.show()"
],
"outputs": [],
"execution_count": null
Expand Down Expand Up @@ -850,7 +885,9 @@
"polaridad_por_hora = tweets_muestra.groupby('hour_of_day')['polarity'].mean()\n",
"\n",
"#Calculamos la polaridad promedio por día de la semana\n",
"polaridad_por_dia_semana = tweets_muestra.groupby('day_of_week')['polarity'].mean()"
"polaridad_por_dia_semana = tweets_muestra.groupby('day_of_week')['polarity'].mean()\n",
"\n",
"\n"
],
"id": "d0619234c99d808f",
"outputs": [],
Expand Down
23 changes: 16 additions & 7 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
pandas~=2.2.1
nltk
numpy~=1.26.4
streamlit~=1.33.0
requests~=2.31.0
matplotlib~=3.8.3
seaborn~=0.13.2
beautifulsoup4
geopandas
matplotlib
nltk
numpy
pandas
pyogrio
regex
requests
scikit-learn
seaborn
shapely
streamlit
textblob
textstat
transformers
wordcloud
emoji

0 comments on commit c58f37c

Please sign in to comment.