text
string
Classification
from nltk.corpus import names
l = ([(name, 'male') for name in names.words('male.txt')] +
[(name, 'female') for name in names.words('female.txt')])
print("\nNumber of male names:")
print(len(names.words('male.txt')))
print("\nNumber of female names:")
print(len(names.words('female.txt')))
male_names = names.words('male.txt')
female_names = names.words('female.txt')
print("\nFirst 10 male names:")
print(male_names[0:15])
print("\nFirst 10 female names:")
print(female_names[0:15])
import random
random.shuffle(n)
def gender_features(word):
return{'last_letter' : word[-1]}
feature_sets = [(gender_features(n), gender) for (n, gender) in l]
train_set, test_set = feature_sets[1000:], feature_sets[:1000]
from nltk import NaiveBayesClassifier
model = NaiveBayesClassifier.train(train_set)
model.classify(gender_features('#whatever he asks'))
model.classify(gender_features('#whatever he asks'))
Clustering
Hierarchical
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
documents = ['Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much.',
'They were the last people you’d expect to be involved in anything strange or mysterious, because they just didn’t hold with such nonsense.',
'Mr. Dursley was the director of a firm called Grunnings, which made drills.',
'He was a big, beefy man with hardly any neck, although he did have a very large mustache.',
'Mrs. Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors.',
'The Dursley s had a small son called Dudley and in their opinion there was no finer boy anywhere.']
documents
vectorizer = TfidfVectorizer(stop_words = 'english')
X = vectorizer.fit_transform(documents)
terms = vectorizer.get_feature_names()
from sklearn.metrics.pairwise import cosine_similarity
dist = 1- cosine_similarity(X)
dist
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import ward, dendrogram
linkage_matrix = ward(dist)
fig, ax = plt.subplots(figsize = (8,8)) #set size
ax = dendrogram(linkage_matrix, orientation = 'right', labels = documents);
plt.tick_params(\
axis = 'x',
which = 'both',
bottom = 'off',
top = 'off',
labelbottom = 'off')
plt.tight_layout()
K Means
model = KMeans(n_clusters = 2, init = 'k-means++', max_iter = 100, n_init = 1)
model.fit(X)
# top ten terms/words per cluster
order_centroids = model.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(2):
print("Cluster Number:", i),
for c in order_centroids[i, :10]:
print('%s' % terms[c])
Y = vectorizer.transform(["Harry Potter is not Harry Styles"])
model.predict(Y)
Preprocessing
External Data Preprocessing(importing dataset, defining the function)
import re
import nltk
import inflect
from nltk import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem import LancasterStemmer, WordNetLemmatizer
file = open("dataset path.txt", encoding = 'utf-8').read()
words = word_tokenize(file)
def to_lowercase(words):
#'''Convert all the characters into lowercase from the list of tokenized words'''
new_words = []
for word in words:
new_word = word.lower()
new_words.append(new_word)
return new_words
words = to_lowercase(words)
#print(words)
def remove_punctuation(words):
#'''Remove all the punctuation marks from the list of tokenized words'''
new_words = []
for word in words:
new_word = re.sub(r'[^\w\s]', '', word)
if new_word != '':
new_words.append(new_word)
return new_words
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card