markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Get Model's Validation Accuracy and Test Accuracy | pipeline.fit(X_train, y_train)
#y_pred = pipeline.predict(X_val)
print ('Training Accuracy', pipeline.score(X_train, y_train))
pipeline.fit(X_val, y_val)
print ('Validation Accuracy', pipeline.score(X_val, y_val)) | Training Accuracy 0.9884200196270854
Validation Accuracy 0.9919924634950542
| MIT | Kaggle_Challenge_Sprint_Study_Guide2.ipynb | JimKing100/DS-Unit-2-Kaggle-Challenge |
Prepare data for feature selection Feature selection | # https://scikit-learn.org/stable/modules/feature_selection.html
## After testing, found most suitable columns and will remap for final modelling
very_important_columns = [ # ran with what the test data can do
'fl_date', # get month and bin
# 'op_unique_carrier', # most extensive name list
# 'origin', # nee... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
remapping crs_dep_time | # Time weight: 0-500 = 1, 501-1000 = 8, 1001-1500 = 10, 1501-2000 = 8, 2001 > = 5
df_.crs_dep_time = df_.crs_dep_time // 100
crs_dep_time_remap = {
0: 0.10,
1: 0.10,
2: 0.10,
3: 0.10,
4: 0.10,
5: 0.10,
6: 0.80,
7: 0.80,
8: 0.80,
9: 0.80,
10: 0.80,
11: 1,
12: 1,
... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
remapping fl_date to month | df_["month"] = [ i [5:7] for i in df_.fl_date ]
# change to datetime and get day of week
df_
# don't drop next time
df_ = df_.drop(labels="fl_date", axis=1)
df_.head()
df_.isna().sum()
df_.month.unique()
# Month weight = Oct = 1, Nov, Jan = 5, Dec = 10
month_remap = {
'10': 0.10,
'11': 0.50,
'12': 1,
... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
remapping weather | df_.weather_type.unique()
df_.head()
df_ = pd.get_dummies(df_, columns=['weather_type'], drop_first=True)
# # Weather weight: Snow=10, Rain=5, Cloudy=2, Sunny=1
# weather_remap = {
# "Rainy": 0.50,
# "Sunny": 0.10,
# "Snowy": 1,
# "Cloudy": 0.20
# }
# df_.weather_type = df_.weather_type.map(weather_rem... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Smote and balance | df_checkpoint = df_.copy()
df_checkpoint = df_checkpoint.sample(frac=0.25)
X = df_checkpoint[df_checkpoint.columns.difference(['arr_delay'])]
y = df_checkpoint["arr_delay"]
print(X.shape)
print(y.shape)
y = pd.DataFrame(y)
y[y < 0] = 0
y.shape
sns.histplot(y); # super imbalanced.
# check version number
import imblearn
... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
16 MILLION ROWS but balanced. | y.arr_delay
# remerge y to X... sample frac... resplit.
X["arr_delay"] = y.arr_delay
X_checkpoint = X.copy()
X_checkpoint = X_checkpoint.sample(frac=0.15)
X = X_checkpoint[X_checkpoint.columns.difference(['arr_delay'])]
y = X_checkpoint["arr_delay"]
y = pd.DataFrame(y)
print(X.shape)
print(y.shape) | (2521746, 7)
(2521746, 1)
| MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Main Task: Regression ProblemThe target variable is ARR_DELAY. We need to be careful which columns to use and which don't. For example, DEP_DELAY is going to be the perfect predictor, but we can't use it because in real-life scenario, we want to predict the delay before the flight takes of --> We can use average delay... | # X = X.replace([np.inf, -np.inf], np.nan)
# X = X.dropna()
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,train_size=0.75,random_state=42)
from sklearn.linear_model import Lasso, Ridge, SGDRegressor, ElasticNet
from sklearn.tree import DecisionTreeRegressor
f... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Naive Bayes Model | # 0.0361 score
from sklearn import naive_bayes
gnb = naive_bayes.GaussianNB()
gnb.fit(X_train, y_train)
y_pred = gnb.predict(X_test)
from sklearn import metrics
print(metrics.accuracy_score(y_test, y_pred))
# save the model to disk
filename = 'finalized_Naive_Bayes.sav'
pickle.dump(gnb, open(filename, 'wb')) | /Users/louisrossi/opt/anaconda3/envs/ml/lib/python3.8/site-packages/sklearn/utils/validation.py:63: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
return f(*args, **kwargs)
| MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Lasso (not good) | # 0.060 score unscaled: scaled data 0.041: after trimming huge 0.034
model = Lasso(alpha=0.5)
cv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=42)
scores = cross_val_score(model, X_train, y_train, scoring='neg_mean_absolute_error', cv=cv, n_jobs=-1)
# force scores to be positive
scores = absolute(scores)
print... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Random Forest Classifier Model | # 0.036 score unscaled: scaled same
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
clf = RandomForestClassifier(max_depth=3, random_state=42, n_jobs=-1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
# 0.03 score
from sklearn.metrics import accuracy_score
... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Gridsearch cells. Do not run. | # # parameter grid
# parameter_candidates = {
# 'n_estimators':[270, 285, 300],
# 'max_depth':[3]
# }
# from sklearn import datasets, svm
# from sklearn.model_selection import GridSearchCV
# grid_result = GridSearchCV(clf, param_grid=parameter_candidates, n_jobs=-1)
# the_fit = grid_result.fit(X_train, y_train.... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Random Forest tuned | # 0.036 score unscaled frac=0.25 : scaled full data score SAME 0.036
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
clf = RandomForestClassifier(max_depth=3, n_estimators=285, random_state=42, n_jobs=-1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
# sc... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Linear/Log Regression | from sklearn.linear_model import LinearRegression
reg = LinearRegression().fit(X_train, y_train)
print(reg.score(X_train, y_train))
# save the model to disk
filename = 'finalized_LinReg.sav'
pickle.dump(reg, open(filename, 'wb'))
reg.coef_
reg.intercept_ | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Decision Tree | from sklearn.tree import DecisionTreeClassifier
from sklearn import metrics
clf_dt = DecisionTreeClassifier()
clf_dt = clf_dt.fit(X_train,y_train)
y_pred = clf_dt.predict(X_test)
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
# save the model to disk
filename = 'finalized_Decision_Tree.sav'
pickle.dump(clf_... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
SVM (do not run) | # from sklearn.preprocessing import StandardScaler
# from sklearn.preprocessing import Normalizer
# scaler = StandardScaler()
# scaler.fit(df_checkpoint)
# X = scaler.transform(df_checkpoint.loc[:, df_checkpoint.columns != 'arr_delay'])
# X = df_checkpoint[df_checkpoint.columns.difference(['arr_delay'])]
# y = df_check... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
XGBoost | # import xgboost as xgb
# from sklearn.metrics import mean_squared_error
# data_dmatrix = xgb.DMatrix(data=X, label=y)
# xg_reg = xgb.XGBRegressor(objective ='reg:linear', # not XGBClassifier() bc regression.
# colsample_bytree = 0.3,
# learning_rate = 0.1,
# ... | _____no_output_____ | MIT | .ipynb_checkpoints/ML_play_around-testing1-checkpoint.ipynb | bmskarate/LH_midterm_project |
Semi-supervised Learning in pomegranateMost classical machine learning algorithms either assume that an entire dataset is either labeled (supervised learning) or that there are no labels (unsupervised learning). However, frequently it is the case that some labeled data is present but there is a great deal of unlabeled... | %pylab inline
from pomegranate import *
from sklearn.semi_supervised import LabelPropagation
from sklearn.datasets import make_blobs
import seaborn, time
seaborn.set_style('whitegrid')
numpy.random.seed(1) | Populating the interactive namespace from numpy and matplotlib
| MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
Let's first generate some data in the form of blobs that are close together. Generally one tends to have far more unlabeled data than labeled data, so let's say that a person only has 50 samples of labeled training data and 4950 unlabeled samples. In pomegranate you a sample can be specified as lacking a label by provi... | X, y = make_blobs(10000, 2, 3, cluster_std=2)
x_min, x_max = X[:,0].min()-2, X[:,0].max()+2
y_min, y_max = X[:,1].min()-2, X[:,1].max()+2
X_train = X[:5000]
y_train = y[:5000]
# Set the majority of samples to unlabeled.
y_train[numpy.random.choice(5000, size=4950, replace=False)] = -1
# Inject noise into the problem... | _____no_output_____ | MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
Now let's take a look at the data when we plot it. | plt.figure(figsize=(8, 8))
plt.scatter(X_train[y_train == -1, 0], X_train[y_train == -1, 1], color='0.6')
plt.scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], color='c')
plt.scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], color='m')
plt.scatter(X_train[y_train == 2, 0], X_train[y_train == 2, 1], ... | _____no_output_____ | MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
The clusters of unlabeled data seem clear to us, and it doesn't seem like the labeled data is perfectly faithful to these clusters. This can typically happen in a semisupervised setting as well, as the data that is labeled is sometimes biased either because the labeled data was chosen as it was easy to label, or the da... | model_a = NaiveBayes.from_samples(NormalDistribution, X_train[y_train != -1], y_train[y_train != -1])
print "Supervised Learning Accuracy: {}".format((model_a.predict(X_test) == y_test).mean())
model_b = NaiveBayes.from_samples(NormalDistribution, X_train, y_train)
print "Semisupervised Learning Accuracy: {}".format((... | Supervised Learning Accuracy: 0.8706
Semisupervised Learning Accuracy: 0.9274
| MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
It seems like we get a big bump in test set accuracy when we use semi-supervised learning. Let's visualize the data to get a better sense of what is happening here. | def plot_contour(X, y, Z):
plt.scatter(X[y == -1, 0], X[y == -1, 1], color='0.2', alpha=0.5, s=20)
plt.scatter(X[y == 0, 0], X[y == 0, 1], color='c', s=20)
plt.scatter(X[y == 1, 0], X[y == 1, 1], color='m', s=20)
plt.scatter(X[y == 2, 0], X[y == 2, 1], color='r', s=20)
plt.contour(xx, yy, Z)
plt... | _____no_output_____ | MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
The contours plot the decision boundaries between the different classes with the left figures corresponding to the partially labeled training set and the right figures corresponding to the test set. We can see that the boundaries learning using only the labeled data look a bit weird when considering the unlabeled data,... | print "Supervised Learning: "
%timeit NaiveBayes.from_samples(NormalDistribution, X_train[y_train != -1], y_train[y_train != -1])
print
print "Semi-supervised Learning: "
%timeit NaiveBayes.from_samples(NormalDistribution, X_train, y_train)
print
print "Label Propagation (sklearn): "
%timeit LabelPropagation().fit(X_tr... | Supervised Learning:
100 loops, best of 3: 1.94 ms per loop
Semi-supervised Learning:
1 loop, best of 3: 961 ms per loop
Label Propagation (sklearn):
1 loop, best of 3: 4.11 s per loop
| MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
It is quite a bit slower to do semi-supervised learning than simple supervised learning in this example. This is expected as the simple supervised update for naive Bayes is a trivial MLE across each dimension whereas the semi-supervised case requires EM to converge to complete. However, it is still faster to do semi-su... | X = numpy.empty(shape=(0, 2))
X = numpy.concatenate((X, numpy.random.normal(4, 1, size=(300, 2)).dot([[-2, 0.5], [2, 0.5]])))
X = numpy.concatenate((X, numpy.random.normal(3, 1, size=(650, 2)).dot([[-1, 2], [1, 0.8]])))
X = numpy.concatenate((X, numpy.random.normal(7, 1, size=(800, 2)).dot([[-0.75, 0.8], [0.9, 1.5]])))... | _____no_output_____ | MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
Now let's take a look at the accuracies that we get when training a model using just the labeled examples versus all of the examples in a semi-supervised manner. | d1 = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X_train[y_train == 0])
d2 = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X_train[y_train == 1])
d3 = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X_train[y_train == 2])
model_a = BayesClassifier(... | Supervised Learning Accuracy: 0.929787234043
Semisupervised Learning Accuracy: 0.96170212766
| MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
As expected, the semi-supervised method performs better, getting rid of nearly half of the errors. Let's visualize the landscape in the same manner as before in order to see why this is the case. | xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, 0.1), numpy.arange(y_min, y_max, 0.1))
Z1 = model_a.predict(numpy.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
Z2 = model_b.predict(numpy.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
plt.figure(figsize=(16, 16))
plt.subplot(221)
plt.title("Training Data, Supervised ... | _____no_output_____ | MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
Immediately, one would notice that the decision boundaries when using semi-supervised learning are smoother than those when using only a few samples. This can be explained mostly because having more data can generally lead to smoother decision boundaries as the model does not overfit to spurious examples in the dataset... | d1 = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X_train[y_train == 0])
d2 = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X_train[y_train == 1])
d3 = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X_train[y_train == 2])
model = BayesClassifier([d... | Supervised Learning:
100 loops, best of 3: 3.73 ms per loop
Semi-supervised Learning:
10 loops, best of 3: 147 ms per loop
Label Propagation (sklearn):
1 loop, best of 3: 1 s per loop
| MIT | tutorials/Tutorial_8_Semisupervised_Learning.ipynb | nlzimmerman/pomegranate |
**Classification** Setup First, let's make sure this notebook works well in both python 2 and 3, import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures: | # To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
MNIST | from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train=X_train.reshape(X_train.shape[0],28*28)
X_test=X_test.reshape(X_test.shape[0],28*28)
28*28
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
some_digit = X_train[36000]
some_digit_image = some_digit.res... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Binary classifier | y_train_5 = (y_train == 5)
y_test_5 = (y_test == 5)
from sklearn.linear_model import SGDClassifier
sgd_clf = SGDClassifier(max_iter=5, random_state=42)
sgd_clf.fit(X_train, y_train_5)
sgd_clf.predict([some_digit]) | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
sklearn cross_val | from sklearn.model_selection import cross_val_score
cross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring="accuracy") | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
reimplemented crossval | from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone
skfolds = StratifiedKFold(n_splits=3, random_state=42)
for train_index, test_index in skfolds.split(X_train, y_train_5):
clone_clf = clone(sgd_clf)
X_train_folds = X_train[train_index]
y_train_folds = (y_train_5[train_index... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
ROC curves | from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_train_5, y_scores)
def plot_roc_curve(fpr, tpr, label=None):
plt.plot(fpr, tpr, linewidth=2, label=label)
plt.plot([0, 1], [0, 1], 'k--')
plt.axis([0, 1, 0, 1])
plt.xlabel('False Positive Rate', fontsize=16)
plt.ylabel('True P... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Multiclass classification | sgd_clf.fit(X_train, y_train)
sgd_clf.predict([some_digit])
some_digit_scores = sgd_clf.decision_function([some_digit])
some_digit_scores
np.argmax(some_digit_scores)
sgd_clf.classes_
sgd_clf.classes_[5]
from sklearn.multiclass import OneVsOneClassifier
ovo_clf = OneVsOneClassifier(SGDClassifier(max_iter=5, random_stat... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
normalizing confusion matrix | row_sums = conf_mx.sum(axis=1, keepdims=True)
norm_conf_mx = conf_mx / row_sums
np.fill_diagonal(norm_conf_mx, 0)
plt.matshow(norm_conf_mx, cmap=plt.cm.gray)
save_fig("confusion_matrix_errors_plot", tight_layout=False)
plt.show()
cl_a, cl_b = 3, 5
X_aa = X_train[(y_train == cl_a) & (y_train_pred == cl_a)]
X_ab = X_trai... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Multilabel classification | from sklearn.neighbors import KNeighborsClassifier
y_train_large = (y_train >= 7)
y_train_odd = (y_train % 2 == 1)
y_multilabel = np.c_[y_train_large, y_train_odd]
knn_clf = KNeighborsClassifier()
knn_clf.fit(X_train, y_multilabel)
knn_clf.predict([some_digit]) | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
**Warning**: the following cell may take a very long time (possibly hours depending on your hardware). | y_train_knn_pred = cross_val_predict(knn_clf, X_train, y_multilabel, cv=3, n_jobs=-1)
f1_score(y_multilabel, y_train_knn_pred, average="macro") | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Multioutput classification | noise = np.random.randint(0, 100, (len(X_train), 784))
X_train_mod = X_train + noise
noise = np.random.randint(0, 100, (len(X_test), 784))
X_test_mod = X_test + noise
y_train_mod = X_train
y_test_mod = X_test
some_index = 5500
plt.subplot(121); plot_digit(X_test_mod[some_index])
plt.subplot(122); plot_digit(y_test_mod[... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Extra material Dummy (ie. random) classifier | from sklearn.dummy import DummyClassifier
dmy_clf = DummyClassifier()
y_probas_dmy = cross_val_predict(dmy_clf, X_train, y_train_5, cv=3, method="predict_proba")
y_scores_dmy = y_probas_dmy[:, 1]
fprr, tprr, thresholdsr = roc_curve(y_train_5, y_scores_dmy)
plot_roc_curve(fprr, tprr) | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
KNN classifier | from sklearn.neighbors import KNeighborsClassifier
knn_clf = KNeighborsClassifier(n_jobs=-1, weights='distance', n_neighbors=4)
knn_clf.fit(X_train, y_train)
y_knn_pred = knn_clf.predict(X_test)
from sklearn.metrics import accuracy_score
accuracy_score(y_test, y_knn_pred)
from scipy.ndimage.interpolation import shift
d... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Exercise 1. An MNIST Classifier With Over 97% AccuracyHint:the KNeighborsClassifier works quite well for this task; you just need to find goodhyperparameter values (try a grid search on the weights and n_neighbors hyperparameters). | from sklearn.model_selection import GridSearchCV
grid_search.best_params_
grid_search.best_score_
from sklearn.metrics import accuracy_score
y_pred = grid_search.predict(X_test)
accuracy_score(y_test, y_pred) | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
2. Data AugmentationWrite a function that can shift an MNIST image in any direction (left, right, up, or down) by onepixel.5 Then, for each image in the training set, create four shifted copies (one per direction) and addthem to the training set. Finally, train your best model on this expanded training set and measure... | from scipy.ndimage.interpolation import shift
def shift_image(image, dx, dy):
pass
image = X_train[1000]
shifted_image_down = shift_image(image, 0, 5)
shifted_image_left = shift_image(image, -5, 0)
plt.figure(figsize=(12,3))
plt.subplot(131)
plt.title("Original", fontsize=14)
plt.imshow(image.reshape(28, 28), inte... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
3. Spam classifierDownload examples of spam and ham from Apache SpamAssassin’s public datasets.Unzip the datasets and familiarize yourself with the data format.Split the datasets into a training set and a test set.Write a data preparation pipeline to convert each email into a feature vector. Your preparationpipeline s... | import os
import tarfile
from six.moves import urllib
DOWNLOAD_ROOT = "http://spamassassin.apache.org/old/publiccorpus/"
HAM_URL = DOWNLOAD_ROOT + "20030228_easy_ham.tar.bz2"
SPAM_URL = DOWNLOAD_ROOT + "20030228_spam.tar.bz2"
SPAM_PATH = os.path.join("datasets", "spam")
def fetch_spam_data(spam_url=SPAM_URL, spam_pat... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Next, let's load all the emails: | HAM_DIR = os.path.join(SPAM_PATH, "easy_ham")
SPAM_DIR = os.path.join(SPAM_PATH, "spam")
ham_filenames = [name for name in sorted(os.listdir(HAM_DIR)) if len(name) > 20]
spam_filenames = [name for name in sorted(os.listdir(SPAM_DIR)) if len(name) > 20]
len(ham_filenames)
len(spam_filenames) | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
We can use Python's `email` module to parse these emails (this handles headers, encoding, and so on): | import email
import email.policy
def load_email(is_spam, filename, spam_path=SPAM_PATH):
directory = "spam" if is_spam else "easy_ham"
with open(os.path.join(spam_path, directory, filename), "rb") as f:
return email.parser.BytesParser(policy=email.policy.default).parse(f)
ham_emails = [load_email(is_sp... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Let's look at one example of ham and one example of spam, to get a feel of what the data looks like: | print(ham_emails[1].get_content().strip())
print(spam_emails[6].get_content().strip()) | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Some emails are actually multipart, with images and attachments (which can have their own attachments). Let's look at the various types of structures we have: | def get_email_structure(email):
if isinstance(email, str):
return email
payload = email.get_payload()
if isinstance(payload, list):
return "multipart({})".format(", ".join([
get_email_structure(sub_email)
for sub_email in payload
]))
else:
return e... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
It seems that the ham emails are more often plain text, while spam has quite a lot of HTML. Moreover, quite a few ham emails are signed using PGP, while no spam is. In short, it seems that the email structure is useful information to have. Now let's take a look at the email headers: | for header, value in spam_emails[0].items():
print(header,":",value) | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
There's probably a lot of useful information in there, such as the sender's email address (12a1mailbot1@web.de looks fishy), but we will just focus on the `Subject` header: | spam_emails[0]["Subject"] | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Okay, before we learn too much about the data, let's not forget to split it into a training set and a test set: | import numpy as np
from sklearn.model_selection import train_test_split
X = np.array(ham_emails + spam_emails)
y = np.array([0] * len(ham_emails) + [1] * len(spam_emails))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Okay, let's start writing the preprocessing functions. First, we will need a function to convert HTML to plain text. Arguably the best way to do this would be to use the great [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/) library, but I would like to avoid adding another dependency to this project, so... | import re
from html import unescape
def html_to_plain_text(html):
text = re.sub('<head.*?>.*?</head>', '', html, flags=re.M | re.S | re.I)
text = re.sub('<a\s.*?>', ' HYPERLINK ', text, flags=re.M | re.S | re.I)
text = re.sub('<.*?>', '', text, flags=re.M | re.S)
text = re.sub(r'(\s*\n)+', '\n', text, ... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Let's see if it works. This is HTML spam: | html_spam_emails = [email for email in X_train[y_train==1]
if get_email_structure(email) == "text/html"]
sample_html_spam = html_spam_emails[7]
print(sample_html_spam.get_content().strip()[:1000], "...") | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
And this is the resulting plain text: | print(html_to_plain_text(sample_html_spam.get_content())[:1000], "...") | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Great! Now let's write a function that takes an email as input and returns its content as plain text, whatever its format is: | def email_to_text(email):
html = None
for part in email.walk():
ctype = part.get_content_type()
if not ctype in ("text/plain", "text/html"):
continue
try:
content = part.get_content()
except: # in case of encoding issues
content = str(part.get_... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Let's throw in some stemming! For this to work, you need to install the Natural Language Toolkit ([NLTK](http://www.nltk.org/)). It's as simple as running the following command (don't forget to activate your virtualenv first; if you don't have one, you will likely need administrator rights, or use the `--user` option):... | try:
import nltk
stemmer = nltk.PorterStemmer()
for word in ("Computations", "Computation", "Computing", "Computed", "Compute", "Compulsive"):
print(word, "=>", stemmer.stem(word))
except ImportError:
print("Error: stemming requires the NLTK module.")
stemmer = None | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
We will also need a way to replace URLs with the word "URL". For this, we could use hard core [regular expressions](https://mathiasbynens.be/demo/url-regex) but we will just use the [urlextract](https://github.com/lipoja/URLExtract) library. You can install it with the following command (don't forget to activate your v... | try:
import urlextract # may require an Internet connection to download root domain names
url_extractor = urlextract.URLExtract()
print(url_extractor.find_urls("Will it detect github.com and https://youtu.be/7Pq-S557XQU?t=3m32s"))
except ImportError:
print("Error: replacing URLs requires the urlext... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
We are ready to put all this together into a transformer that we will use to convert emails to word counters. Note that we split sentences into words using Python's `split()` method, which uses whitespaces for word boundaries. This works for many written languages, but not all. For example, Chinese and Japanese scripts... | from sklearn.base import BaseEstimator, TransformerMixin
class EmailToWordCounterTransformer(BaseEstimator, TransformerMixin):
def __init__(self, strip_headers=True, lower_case=True, remove_punctuation=True,
replace_urls=True, replace_numbers=True, stemming=True):
self.strip_headers = stri... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Let's try this transformer on a few emails: | X_few = X_train[:3]
X_few_wordcounts = EmailToWordCounterTransformer().fit_transform(X_few)
X_few_wordcounts | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
This looks about right! Now we have the word counts, and we need to convert them to vectors. For this, we will build another transformer whose `fit()` method will build the vocabulary (an ordered list of the most common words) and whose `transform()` method will use the vocabulary to convert word counts to vectors. The... | from scipy.sparse import csr_matrix
class WordCounterToVectorTransformer(BaseEstimator, TransformerMixin):
def __init__(self, vocabulary_size=1000):
self.vocabulary_size = vocabulary_size
def fit(self, X, y=None):
total_count = Counter()
for word_count in X:
for word, count ... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
What does this matrix mean? Well, the 64 in the third row, first column, means that the third email contains 64 words that are not part of the vocabulary. The 1 next to it means that the first word in the vocabulary is present once in this email. The 2 next to it means that the second word is present twice, and so on. ... | vocab_transformer.vocabulary_ | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
We are now ready to train our first spam classifier! Let's transform the whole dataset: | from sklearn.pipeline import Pipeline
preprocess_pipeline = Pipeline([
("email_to_wordcount", EmailToWordCounterTransformer()),
("wordcount_to_vector", WordCounterToVectorTransformer()),
])
X_train_transformed = preprocess_pipeline.fit_transform(X_train)
from sklearn.linear_model import LogisticRegression
fro... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Over 98.7%, not bad for a first try! :) However, remember that we are using the "easy" dataset. You can try with the harder datasets, the results won't be so amazing. You would have to try multiple models, select the best ones and fine-tune them using cross-validation, and so on.But you get the picture, so let's stop n... | from sklearn.metrics import precision_score, recall_score
X_test_transformed = preprocess_pipeline.transform(X_test)
log_clf = LogisticRegression(random_state=42)
log_clf.fit(X_train_transformed, y_train)
y_pred = log_clf.predict(X_test_transformed)
print("Precision: {:.2f}%".format(100 * precision_score(y_test, y_... | _____no_output_____ | Apache-2.0 | 03_classification.ipynb | mbenkhemis/handson-ml |
Natural Language ProcessingThis chapter covers text analysis, also known as natural language processing. We'll cover tokenisation of text, removing stop words, counting words, performing other statistics on words, and analysing the parts of speech. The focus here is on English, but many of the methods-and even the lib... | import pandas as pd
import string
df = pd.read_csv(
"https://github.com/aeturrell/coding-for-economists/raw/main/data/smith_won.txt",
delimiter="\n",
names=["text"],
)
df.head() | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
We need to do a bit of light text cleaning before we get on to the more in-depth natural language processing. We'll make use of vectorised string operations as seen in the [Introduction to Text](text-intro) chapter. First, we want to put everything in lower case: | df["text"] = df["text"].str.lower()
df.head() | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Next, we'll remove the punctuation from the text. You may not always wish to do this but it's a good default. | translator = string.punctuation.maketrans({x: "" for x in string.punctuation})
df["text"] = df["text"].str.translate(translator)
df.head() | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Okay, we now have rows and rows of lower case words without punctuation.```{admonition} ExerciseRemove all vowels from the vector of text using `str.translate`.``` While we're doing some text cleaning, let's also remove the excess whitespace found in, for example, the first entry. Leaning on the cleaning methods from t... | df["text"] = df["text"].str.replace("\s+?\W+", " ", regex=True) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
This searches for multiple whitespaces that preceede non-word characters and replaces them with a single whitespace. TokenisationWe're going to now see an example of tokenisation: the process of taking blocks of text and breaking them down into tokens, most commonly a word but potentially all one and two word pairs. N... | import re
word_pattern = r"\w+"
tokens = re.findall(word_pattern, df.iloc[0, 0])
tokens | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
This produced a split of a single line into one word tokens that are represented by a list of strings. We could have also asked for other variations, eg sentences, by asking to split at every ".". Tokenisation using NLP toolsMany of the NLP packages available in Python come with built-in tokenisation tools. We'll use... | from nltk.tokenize import word_tokenize
word_tokenize(df.iloc[0, 0]) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
We have the same results as before when we used regex. Now let's scale this tokenisation up to our whole corpus while retaining the lines of text, giving us a structure of the form (lines x tokens): | df["tokens"] = df["text"].apply(lambda x: word_tokenize(x))
df.head() | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
**nltk** also has a `sent_tokenize` function that tokenises sentences, although as it makes use of punctuation you must take care with what pre-cleaning of text you undertake. Removing Stop WordsStop words are frequent but uninformative words such as 'that', 'which', 'the', 'is', 'and', and 'but'. These words tend to ... | import nltk
stopwords = nltk.corpus.stopwords.words(
"english"
) # Note that you may need to download these on your machine using nltk.download() within Python
words_filtered = [
word.lower() for word in df.loc[0, "tokens"] if word.lower() not in stopwords
]
words_filtered | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Having filtered the first entry, we can see that words such as 'an' and 'into' have disappeared but we have retained more informative words such as 'inquiry' and 'nature'. Processing one entry is not enough: we need all of the lines to have stopwords removed. So we can now scale this up to the full corpus with **pandas... | df["tokens"] = df["tokens"].apply(
lambda x: [word.lower() for word in x if word.lower() not in stopwords]
)
df.head() | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Now we have a much reduced set of words in our tokens, which will make the next step of analysis more meaningful. Counting TextThere are several ways of performing basic counting statistics on text. We saw one in the previous chapter, `str.count()`, but that only applies to one word at a time. Often, we're interested ... | from collections import Counter
fruit_list = [
"apple",
"apple",
"orange",
"satsuma",
"banana",
"orange",
"mango",
"satsuma",
"orange",
]
freq = Counter(fruit_list)
freq | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Counter returns a `collections.Counter` object where the numbers of each type in a given input list are summed. The resulting dictionnary of unique counts can be extracted using `dict(freq)`, and `Counter` has some other useful functions too including `most_common()` which, given a number `n`, returns `n` tuples of the... | freq.most_common(10) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Say we wanted to apply this not just to every line in our corpus separately, but to our whole corpus in one go; how would we do it? `Counter` will happily accept a list but our dataframe token column is currently a vector of lists. So we must first transform the token column to a single list of all tokens and then appl... | import itertools
merged_list = list(itertools.chain(*df["tokens"].to_list()))
freq = Counter(merged_list)
freq.most_common(10) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Looking at the tuples representing the 10 most words in the corpus, there are some interesting patterns. "price" and "labour" are hardly surprises, while "silver" perhaps reflects the time in which the book was written a little more. "one", "upon", and "may" are candidates for context-specific stopwords; while our NLTK... | import requests
response = requests.get("https://github.com/aeturrell/coding-for-economists/raw/main/data/smith_won.txt")
raw_text = response.text
raw_text[:100] | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Great, so we have our raw text. Let's now tokenise it using **nltk**. | from nltk.tokenize import sent_tokenize
sent_list = sent_tokenize(raw_text)
df_sent = pd.DataFrame({"text": sent_list})
df_sent.head() | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Now we just need to apply all of the cleaning procudures we did before——that is lowering the case, removing punctuation, and removing any excess whitespace. | df_sent["text"] = (df_sent["text"]
.str.lower()
.str.translate(translator)
.str.replace("\s+?\W+", " ", regex=True))
df_sent.head() | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
We'll use this tokenised version by sentence in the next section. TF-IDFTerm frequency - inverse document frequency, often referred to as *tf-idf*, is a measure of term counts (where terms could be 1-grams, 2-grams, etc.) that is weighted to try and identify the most *distinctively* frequent terms in a given corpus. I... | from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
vectorizer = CountVectorizer(stop_words=stopwords)
X = vectorizer.fit_transform(df["text"])
print(f"The shape of the resulting tf matrix is {np.shape(X)}")
vectorizer.get_feature_names()[500:510] | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
This created a matrix of 5,160 terms by 7,750 "documents" (actually sentences in our example) running with more or less the default settings. The only change we made to those default settings was to pass in a list of stopwords that we used earlier. The other default settings tokenise words using a regex of "(?u)\b\w\w+... | type(X) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
ie, it's a *sparse matrix*. Sparse matrices are more efficient for your computer when there are many missing zeros in a matrix. They do all of the usual things that matrices (arrays) do, but are just more convenient in this case. Most notably, we can perform counts with them and we can turn them into a regular matrix u... | counts_df = pd.DataFrame(X.toarray(), columns=vectorizer.get_feature_names()).T
counts_df = counts_df.sum(axis=1)
counts_df = counts_df.sort_values(ascending=False)
counts_df.head()
import matplotlib.pyplot as plt
# Plot settings
plt.style.use(
"https://github.com/aeturrell/coding-for-economists/raw/main/plot_styl... | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Let's see what happens when we ask only for bi-grams. | # Count bigrams:
vectorizer = CountVectorizer(stop_words=stopwords, ngram_range=(2, 2), max_features=300)
bigrams_df = (
pd.DataFrame(
vectorizer.fit_transform(df["text"]).toarray(),
columns=vectorizer.get_feature_names(),
)
.T.sum(axis=1)
.sort_values(ascending=False)
)
# Plot top n 2-... | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
As you might expect, the highest frequency with which 2-grams occur is less than the highest frequency with which 1-grams occur.Now let's move on to the inverse document frequency. The most common definition is $$\mathrm{idf}(t, D) = \log \frac{N}{|\{d \in D: t \in d\}|}$$where $D$ is the set of documents, $N=|D|$, an... | from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(stop_words=stopwords, sublinear_tf=True)
X = tfidf_vectorizer.fit_transform(df["text"])
counts_tfidf = (
pd.DataFrame(X.toarray(), columns=tfidf_vectorizer.get_feature_names())
.T.sum(axis=1)
.sort_values(ascendi... | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
There are small differences between this ranking of terms versus the original tf 1-gram version above. In the previous one, words such as 'one' were slightly higher in the ranking but their common appearance in multiple documents (lines) downweights them here. In this case, we also used the sublinear option, which uses... | max_val = np.argmax(np.dot(X[0, :], X[1:, :].T))
print(max_val)
print(
f"Cosine similarity is {round(np.dot(X[0], X[max_val+1].T).toarray().flatten()[0], 2)}"
)
for i, sent in enumerate(df.iloc[[0, max_val + 1], 0]):
print(f"Sentence {i}:")
print("\t" + sent.strip() + "\n") | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
We can see from this example *why* the sentence we found is the most similar in the book to the title: it contains a phrase that is very similar to part of the title. It's worth noting here that tf-idf (and tf) do not care about *word order*, they only care about frequency, and so sometimes the most similar sentences a... | df_test = pd.DataFrame({"text": ["poverty is a trap and rearing children in it is hard and perilous",
"people in different trades can meet and develop a conspiracy which ultimately hurts consumers by raising prices"]})
| _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Now we need to i) create the vector space, ii) express WoN in the vector space, iii) express the test texts in the vector space, iv) find which rows of the WoN match best the test texts, and v) print out those rows. | from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(stop_words=stopwords, sublinear_tf=True)
# i)
model = tfidf_vectorizer.fit(df_sent["text"])
# ii)
X = tfidf_vectorizer.transform(df_sent["text"])
# iii)
Y = tfidf_vectorizer.transform(df_test["text"])
# iv)
max_index_pos = n... | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Now, armed with the rows of $X$, we are ready for the final part, v) | for y_pos, x_pos in enumerate(max_index_pos):
print(f'Sentence number {y_pos}:')
print(f' test: {df_test.loc[y_pos, "text"]}')
print(f' WoN: {df_sent.loc[x_pos, "text"]} \n') | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Using a Special VocabularyBut why should the basis vectors come from the terms in another text? Couldn't they come from anywhere? The answer is, of course, yes. We could choose any set of basis vectors we liked to define our vector space, and express a text in it. For this, we need a *special vocabulary*.Let's see an ... | vocab = ["work",
"wage",
"labour",
"real price",
"money price",
"productivity"] | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
That done, we now plug our special vocab into `CountVectorizer` to tell it to ignore anything that isn't relevant (isn't in our vocab). | vectorizer = CountVectorizer(vocabulary=vocab, ngram_range=(1, 2))
counts_df = (
pd.DataFrame(
vectorizer.fit_transform(df_sent["text"]).toarray(),
columns=vectorizer.get_feature_names(),
)
.T.sum(axis=1)
.sort_values(ascending=False)
)
# Plot counts from our vocab
num_to_plot = len(voc... | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Note that we did not pass `stopwords` in this case; there's no need, because passing a `vocab` effectively says to categorise any word that is *not* in the special vocabulary as a stopword. We also still passed an n-gram range to ensure our longest n-gram, with $n=2$, was counted. Filtering Out Frequent and Infrequent... | from nltk.text import Text
w_o_n = Text(word_tokenize(raw_text)) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Now let's imagine we're interested in the context of a particular term, say 'price'. We can run: | w_o_n.concordance("price") | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
This gives us context for all fo the occurrences of the terms. Context is useful, but there's more than one kind. What about *where* in a text references to different ideas or terms appear? We can do that with *text dispersion plot*, as shown below for a selection of terms. | w_o_n.dispersion_plot(["price", "labour", "production", "America"]) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Stemming and LemmatisationYou may have wondered, in these examples, what about words that mean the same but have different endings, for example "work", "working", "worked", and "works"? In most of the examples shown, we've only counted one of these words and thereby could *underestimate* their prescence. If what we r... | from nltk import LancasterStemmer
# create an object of class LancasterStemmer
lancaster = LancasterStemmer()
cleaner_text = raw_text.translate(translator).lower()
stem_tokens = [lancaster.stem(term.lower()) for term in word_tokenize(cleaner_text)
if term.lower() not in stopwords]
stem_tokens[120:135] | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Now we have "pric" instead of price, and "compon" instead of "compnonent", and so on. The stemming has taken away the ends of the words, leaving us with just their stem. Let's see if a word count following this approach will be different. | freq = Counter(stem_tokens)
freq.most_common(10) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
In this case, the words that are most frequent are much the same: but you can imagine this could easily have *not* been the case and, if you're interested in fully capturing a topic, it's a good idea to at least check a stemmed version for comparison. *Lemmatisation* is slightly different; it's a bit more intelligent t... | from nltk import WordNetLemmatizer
# create an object of class LancasterStemmer
wnet_lemma = WordNetLemmatizer()
lemma_tokens = [wnet_lemma.lemmatize(term.lower()) for term in word_tokenize(cleaner_text)
if term.lower() not in stopwords]
freq = Counter(lemma_tokens)
freq.most_common(10) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
The lemmatised words we're dealing with are more *understandable* than in the case of stemming, but note that the top ten most frequent words have changed a little too. Part of Speech TaggingSentences are made up of verbs, nouns, adjectives, pronouns, and more of the building blocks of language. Sometimes, when you're... | from nltk import pos_tag
example_sent = "If we are going to die, let us die looking like a Peruvian folk band."
pos_tagged_words = pos_tag(word_tokenize(example_sent))
for word, pos in pos_tagged_words:
if(word not in string.punctuation):
print(f'The word "{word}" is a {pos}') | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
**nltk** uses contractions to refer to the different parts of speech: IN is a preposition, PRP a personal pronoun, VBP a verb (in non 3rd person singular present), JJ is an adjective, NN a noun, and so on.When might you actually use PoS tagging? You can imagine thinking about how the use of language is different or has... | import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp(example_sent)
pos_df = pd.DataFrame([(token.text, token.lemma_, token.pos_, token.tag_) for token in doc],
columns=["text", "lemma", "pos", "tag"])
pos_df | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
For those brave enough for the pun, **spacy** also has some nifty visualisation tools. | from spacy import displacy
doc = nlp("When you light a candle, you also cast a shadow.")
displacy.render(doc, style="dep") | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Named Entity RecognitionThis is another NLP tool that helps to pick apart the parts of language, in this case it's a method for extracting all of the entities named in a text, whether they be people, countries, cars, whatever.Let's see an example. | text = "TAE Technologies, a California-based firm building technology to generate power from nuclear fusion, said on Thursday it had raised $280 million from new and existing investors, including Google and New Enterprise Associates."
doc = nlp(text)
displacy.render(doc, style="ent") | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Pretty impressive stuff, but a health warning that there are plenty of texts that are not quite as clean as this one! As with the PoS tagger, you can extract the named entities in a tabular format for onward use: | pd.DataFrame([(ent.text, ent.start_char, ent.end_char, ent.label_) for ent in doc.ents],
columns=["text", "start_pos", "end_pos", "label"]) | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
The table below gives the different label meanings in Named Entity Recognition:| Label | Meaning ||------- |--------------------- || geo | Geographical entity || org | Organisation || per | Person || gpe | Geopolitical entity || date | Time indicator || art ... | import textstat
test_data = (
"Playing games has always been thought to be important to "
"the development of well-balanced and creative children; "
"however, what part, if any, they should play in the lives "
"of adults has never been researched that deeply. I believe "
"that playing games is ever... | _____no_output_____ | MIT | text-nlp.ipynb | lnsongxf/coding-for-economists |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.