| |
| import pandas as pd |
| import numpy as np |
| from sklearn import model_selection |
| from sklearn.feature_extraction.text import CountVectorizer |
| from sklearn.linear_model import LogisticRegression |
|
|
|
|
| |
| def load_data(): |
|
|
| |
| PATH = 'SMSSpamCollection' |
| df = pd.read_csv(PATH, delimiter = "\t", names=["classe", "message"]) |
|
|
| |
| X = df['message'] |
| y = df['classe'] |
|
|
| return X, y |
|
|
| |
| def split_data(X, y): |
|
|
| |
| ntest = 2000/(3572+2000) |
|
|
| |
| X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=ntest, random_state=0) |
|
|
| return X_train, y_train |
|
|
| |
| def spam_classifier_model(Xtrain, ytrain): |
|
|
| |
| model_logistic_regression = LogisticRegression() |
| model_logistic_regression = model_logistic_regression.fit(Xtrain, ytrain) |
|
|
| |
| coeff = model_logistic_regression.coef_ |
| coef_abs = np.abs(coeff) |
|
|
| |
| quantiles = np.quantile(coef_abs,[0, 0.25, 0.5, 0.75, 0.9, 1]) |
|
|
| |
| index = np.where(coeff[0] > quantiles[1]) |
| newXtrain = Xtrain[:, index[0]] |
|
|
| |
| model_logistic_regression = LogisticRegression() |
|
|
| |
| model_logistic_regression.fit(newXtrain, ytrain) |
|
|
| return model_logistic_regression, index |
|
|
| |
| data_input, data_output = load_data() |
|
|
| |
| X_train, ytrain = split_data(data_input, data_output) |
|
|
| |
| vectorizer = CountVectorizer(stop_words='english', binary=True, min_df=10) |
| Xtrain = vectorizer.fit_transform(X_train.tolist()) |
| Xtrain = Xtrain.toarray() |
|
|
| |
| model_logistic_regression, index = spam_classifier_model(Xtrain, ytrain) |
|
|
|
|