Análisis de Sentimientos Con Python (Parte 1)
Análisis de Sentimientos Con Python (Parte 1)
1 reviews_train = []
2 for line in open('../data/movie_data/full_train.txt', 'r'):
3 reviews_train.append(line.strip())
4 reviews_test = []
5 for line in open('../data/movie_data/full_test.txt', 'r'):
6 reviews_test.append(line.strip())
"This isn't the comedic Robin Williams, nor is it the quirky/insane Robin Williams of
recent thriller fame. This is a hybrid of the classic drama without over-dramatization,
mixed with Robin's new love of the thriller. But this isn't a thriller, per se. This is more
a mystery/suspense vehicle through which Williams attempts to locate a sick boy and
his keeper.<br /><br />Also starring Sandra Oh and Rory Culkin, this Suspense Drama
plays pretty much like a news report, until William's character gets close to achieving
his goal.<br /><br />I must say that I was highly entertained, though this movie fails to
teach, guide, inspect, or amuse. It felt more like I was watching a guy (Williams), as he
was actually performing the actions, from a third person perspective. In other words,
it felt real, and I was able to subscribe to the premise of the story.<br /><br />All in all,
it's worth a watch, though it's definitely not Friday/Saturday night fare.<br /><br />It
rates a 7.7/10 from...<br /><br />the Fiend :."
Nota: Comprender y poder usar expresiones regulares es un requisito previo para realizar
cualquier tarea de procesamiento de lenguaje natural. Si no está familiarizado con ello,
quizás comience con el siguiente tutorial: Regex Tutorial.
DESPÚES
"this isnt the comedic robin williams nor is it the quirky insane robin williams of recent
thriller fame this is a hybrid of the classic drama without over dramatization mixed with
robins new love of the thriller but this isnt a thriller per se this is more a mystery
suspense vehicle through which williams attempts to locate a sick boy and his keeper
also starring sandra oh and rory culkin this suspense drama plays pretty much like a
news report until williams character gets close to achieving his goal i must say that i
was highly entertained though this movie fails to teach guide inspect or amuse it felt
more like i was watching a guy williams as he was actually performing the actions from
a third person perspective in other words it felt real and i was able to subscribe to the
premise of the story all in all its worth a watch though its definitely not friday saturday
night fare it rates a from the fiend"
Nota: hay muchas formas diferentes y más sofisticadas para realizar limpieza de datos en
texto, que probablemente produzcan mejores resultados que los realizados en este
tutorial. La parte 1 de este tutorial está centrado en realizar la limpieza de los datos lo
más simple posible.
VECTORIZACIÓN
Para que los datos tengan sentido para nuestro algoritmo de aprendizaje automático,
necesitaremos convertir cada reseña a una representación numérica, lo que llamamos
vectorización.
La forma más simple para vectorizar estos datos es crear una matriz muy grande con una
columna para cada palabra única en su corpus (donde corpus son todos los 50.000
comentarios). Luego transformamos cada reseña en una fila que contenga 0 y 1, donde
1 significa que la palabra en el corpus correspondiente a esa columna y aparece en una
reseña. Dicho esto, cada fila de la matriz será muy díspersa (en su mayoría ceros). Este
proceso también se conoce como hot encoding.
Nota: Las etiquetas que usamos serán los mismas para el entrenamiento y las pruebas
porque ambos conjuntos de datos están estructurados de la misma manera, donde los
primeros 12.500 son positivos y los últimos 12.500 son negativos.
1 from sklearn.linear_model import LogisticRegression
2 from sklearn.metrics import accuracy_score
3 from sklearn.model_selection import train_test_split
4
5 target = [1 if i < 12500 else 0 for i in range(25000)]
1 final_model = LogisticRegression(C=0.05)
2 final_model.fit(X, target)
3 print ("Final Accuracy: %s"% accuracy_score(target, final_model.predict(X_test)))
Como una prueba de validez, revisaremos las 5 palabras más discriminatorias para las
reseñas tanto positivas como negativas. Haremos esto observando los coeficientes más
grandes y pequeños, respectivamente.
1 feature_to_coef = {
2 word: coef for word, coef in zip(
3 cv.get_feature_names(), final_model.coef_[0]
4 )
5 }
Finalmente tendremos un clasificador muy simple con una muy buena precisión.