Escolar Documentos
Profissional Documentos
Cultura Documentos
Aprende a analizar texto utilizando NLTK. Analiza los sentimientos de las personas
y clasifica críticas de películas.
o Tokenización
o Para las palabras
o Etiquetado POS
Clasificación de texto
La PNL permite que la computadora interactúe con los humanos de una manera
natural. Ayuda a la computadora a comprender el lenguaje humano y derivar un
significado de él. La PNL es aplicable en varias problemáticas, desde
reconocimiento de voz, traducción de idiomas, clasificación de documentos hasta
extracción de información. El análisis de la revisión de películas es uno de los
ejemplos clásicos para demostrar un modelo sencillo de bolsa de palabras de la
PNL en las reseñas de películas.
packages
Requirement already satisfied: six in /home/northout/anaconda2/lib/python2.7/site-
[33mYou are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command. [0m
#Loading NLTK
import nltk
Tokenización
Tokenización de oraciones
text="""Hello Mr. Smith, how are you doing today? The weather is great, and city is
awesome.
tokenized_text=sent_tokenize(text)
print(tokenized_text)
['Hello Mr. Smith, how are you doing today?', 'The weather is great, and city is
Tokenización de palabras
tokenized_word=word_tokenize(text)
print(tokenized_word)
['Hello', 'Mr.', 'Smith', ',', 'how', 'are', 'you', 'doing', 'today', '?', 'The', 'weather', 'is',
'great', ',', 'and', 'city', 'is', 'awesome', '.', 'The', 'sky', 'is', 'pinkish-blue', '.', 'You',
fdist = FreqDist(tokenized_word)
print(fdist)
fdist.most_common(2)
fdist.plot(30,cumulative=False)
plt.show()
Las palabras clave se consideran como ruido en el texto. El texto puede contener
palabras de parada como es, am, are, this, a, an, the, etc.
En NLTK para eliminar palabras clave, debe crear una lista de palabras clave y
filtrar su lista de tokens de estas palabras.
from nltk.corpus import stopwords
stop_words=set(stopwords.words("english"))
print(stop_words)
{'their', 'then', 'not', 'ma', 'here', 'other', 'won', 'up', 'weren', 'being', 'we', 'those', 'an',
'them', 'which', 'him', 'so', 'yourselves', 'what', 'own', 'has', 'should', 'above', 'in',
'myself', 'against', 'that', 'before', 't', 'just', 'into', 'about', 'most', 'd', 'where', 'our', 'or',
'such', 'ours', 'of', 'doesn', 'further', 'needn', 'now', 'some', 'too', 'hasn', 'more', 'the',
'yours', 'her', 'below', 'same', 'how', 'very', 'is', 'did', 'you', 'his', 'when', 'few', 'does',
'down', 'yourself', 'i', 'do', 'both', 'shan', 'have', 'itself', 'shouldn', 'through',
'themselves', 'o', 'didn', 've', 'm', 'off', 'out', 'but', 'and', 'doing', 'any', 'nor', 'over',
'had', 'because', 'himself', 'theirs', 'me', 'by', 'she', 'whom', 'hers', 're', 'hadn', 'who',
'he', 'my', 'if', 'will', 'are', 'why', 'from', 'am', 'with', 'been', 'its', 'ourselves', 'ain',
'couldn', 'a', 'aren', 'under', 'll', 'on', 'y', 'can', 'they', 'than', 'after', 'wouldn', 'each',
'once', 'mightn', 'for', 'this', 'these', 's', 'only', 'haven', 'having', 'all', 'don', 'it', 'there',
'until', 'again', 'to', 'while', 'be', 'no', 'during', 'herself', 'as', 'mustn', 'between', 'was',
Eliminando Stopwords
filtered_sent=[]
for w in tokenized_sent:
if w not in stop_words:
filtered_sent.append(w)
print("Tokenized Sentence:",tokenized_sent)
print("Filterd Sentence:",filtered_sent)
Tokenized Sentence: ['Hello', 'Mr.', 'Smith', ',', 'how', 'are', 'you', 'doing', 'today', '?']
La normalización del léxico considera otro tipo de ruido en el texto. Por ejemplo,
conexión, conectado, conectando palabra reduce a una palabra común
"conectar". Reduce las formas relacionadas de forma derivada de una palabra a
una raíz común.
Tallo
# Stemming
ps = PorterStemmer()
stemmed_words=[]
for w in filtered_sent:
stemmed_words.append(ps.stem(w))
print("Filtered Sentence:",filtered_sent)
print("Stemmed Sentence:",stemmed_words)
Lemmatización
#Lexicon Normalization
lem = WordNetLemmatizer()
stem = PorterStemmer()
word = "flying"
print("Lemmatized Word:",lem.lemmatize(word,"v"))
print("Stemmed Word:",stem.stem(word))
Etiquetado POS
tokens=nltk.word_tokenize(sent)
print(tokens)
['Albert', 'Einstein', 'was', 'born', 'in', 'Ulm', ',', 'Germany', 'in', '1879', '.']
nltk.pos_tag(tokens)
[('Albert', 'NNP'),
('Einstein', 'NNP'),
('was', 'VBD'),
('born', 'VBN'),
('in', 'IN'),
('Ulm', 'NNP'),
(',', ','),
('Germany', 'NNP'),
('in', 'IN'),
('1879', 'CD'),
('.', '.')]
POS etiquetado: Albert / NNP Einstein / NNP era / nacido en VBD / VBN en / IN
Ulm / NNP, /, Alemania / NNP en / IN 1879 / CD ./.
Hoy en día las empresas quieren entender, ¿qué salió mal con sus últimos
productos? ¿Qué piensan los usuarios y el público en general sobre la última
característica? Puede cuantificar dicha información con una precisión razonable
utilizando el análisis de sentimientos.
Clasificación de texto
# Import pandas
import pandas as pd
Cargando datos
data.head()
PhraseId ID de sentencia Frase Sentimiento
0 1 1 Una serie de aventuras 1
que demuestran el
adagio ...
1 2 1 Una serie de aventuras 2
que demuestran el
adagio ...
2 3 1 Una serie 2
3 4 1 UNA 2
4 5 1 serie 2
data.info()
<class 'pandas.core.frame.DataFrame'>
data.Sentiment.value_counts()
2 79582
3 32927
1 27273
4 9206
0 7072
Sentiment_count=data.groupby('Sentiment').count()
plt.bar(Sentiment_count.index.values, Sentiment_count['Phrase'])
plt.xlabel('Review Sentiments')
plt.ylabel('Number of Review')
plt.show()
Doc 1: Me encantan los perros. Doc 2: Odio los perros y los tejidos. Doc 3: Tejer
es mi pasatiempo y pasión.
#tokenizer to remove unwanted elements from out data like symbols and numbers
token = RegexpTokenizer(r'[a-zA-Z0-9]+')
cv = CountVectorizer(lowercase=True,stop_words='english',ngram_range =
(1,1),tokenizer = token.tokenize)
text_counts= cv.fit_transform(data['Phrase'])
predicted= clf.predict(X_test)
tf=TfidfVectorizer()
text_tf= tf.fit_transform(data['Phrase'])
predicted= clf.predict(X_test)
Bueno, obtuvo una tasa de clasificación del 58.65% usando las funciones TF-IDF,
lo que no se considera una buena precisión. Necesitamos mejorar la precisión
usando algún otro preprocesamiento o ingeniería de características. Vamos a
sugerir en el cuadro de comentarios algún enfoque para mejorar la precisión.
Conclusión