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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from sklearn.model_selection import train_test_split, cross_val_score
|
| 6 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 7 |
+
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_curve, auc
|
| 8 |
+
|
| 9 |
+
from sklearn.utils import shuffle
|
| 10 |
+
from sklearn.model_selection import learning_curve
|
| 11 |
+
import gender_guesser.detector as gender
|
| 12 |
+
|
| 13 |
+
def read_datasets():
|
| 14 |
+
""" Reads users profile from csv files """
|
| 15 |
+
genuine_users = pd.read_csv("data/users.csv")
|
| 16 |
+
fake_users = pd.read_csv("data/fusers.csv")
|
| 17 |
+
x = pd.concat([genuine_users, fake_users])
|
| 18 |
+
y = [1] * len(genuine_users) + [0] * len(fake_users)
|
| 19 |
+
return x, y
|
| 20 |
+
|
| 21 |
+
def predict_sex(names):
|
| 22 |
+
sex_predictor = gender.Detector(case_sensitive=False)
|
| 23 |
+
sex_code = []
|
| 24 |
+
for name in names:
|
| 25 |
+
first_name = name.split(' ')[0]
|
| 26 |
+
sex = sex_predictor.get_gender(first_name)
|
| 27 |
+
if sex == 'female':
|
| 28 |
+
sex_code.append(2)
|
| 29 |
+
# elif sex == 'mostly_female':
|
| 30 |
+
# sex_code.append(-1)
|
| 31 |
+
elif sex == 'male':
|
| 32 |
+
sex_code.append(1)
|
| 33 |
+
# elif sex == 'mostly_male':
|
| 34 |
+
# sex_code.append(1)
|
| 35 |
+
else:
|
| 36 |
+
sex_code.append(0) # Assign a default value for unknown genders
|
| 37 |
+
return sex_code
|
| 38 |
+
|
| 39 |
+
def extract_features(x):
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
x['sex_code'] = predict_sex(x['name'])
|
| 43 |
+
|
| 44 |
+
feature_columns_to_use = ['statuses_count', 'followers_count', 'friends_count', 'favourites_count', 'listed_count', 'sex_code']
|
| 45 |
+
x = x[feature_columns_to_use]
|
| 46 |
+
return x
|
| 47 |
+
|
| 48 |
+
# Rest of your code...
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
|
| 53 |
+
plt.figure()
|
| 54 |
+
plt.title(title)
|
| 55 |
+
if ylim is not None:
|
| 56 |
+
plt.ylim(*ylim)
|
| 57 |
+
plt.xlabel("Training examples")
|
| 58 |
+
plt.ylabel("Score")
|
| 59 |
+
|
| 60 |
+
train_sizes, train_scores, test_scores = learning_curve(
|
| 61 |
+
estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
|
| 62 |
+
train_scores_mean = np.mean(train_scores, axis=1)
|
| 63 |
+
train_scores_std = np.std(train_scores, axis=1)
|
| 64 |
+
test_scores_mean = np.mean(test_scores, axis=1)
|
| 65 |
+
test_scores_std = np.std(test_scores, axis=1)
|
| 66 |
+
|
| 67 |
+
plt.grid()
|
| 68 |
+
plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
|
| 69 |
+
train_scores_mean + train_scores_std, alpha=0.1,
|
| 70 |
+
color="r")
|
| 71 |
+
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
|
| 72 |
+
test_scores_mean + test_scores_std, alpha=0.1, color="g")
|
| 73 |
+
plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
|
| 74 |
+
label="Training score")
|
| 75 |
+
plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
|
| 76 |
+
label="Cross-validation score")
|
| 77 |
+
|
| 78 |
+
plt.legend(loc="best")
|
| 79 |
+
return plt
|
| 80 |
+
|
| 81 |
+
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
|
| 82 |
+
target_names=['Fake','Genuine']
|
| 83 |
+
plt.imshow(cm, interpolation='nearest', cmap=cmap)
|
| 84 |
+
plt.title(title)
|
| 85 |
+
plt.colorbar()
|
| 86 |
+
tick_marks = np.arange(len(target_names))
|
| 87 |
+
plt.xticks(tick_marks, target_names, rotation=45)
|
| 88 |
+
plt.yticks(tick_marks, target_names)
|
| 89 |
+
plt.tight_layout()
|
| 90 |
+
plt.ylabel('True label')
|
| 91 |
+
plt.xlabel('Predicted label')
|
| 92 |
+
|
| 93 |
+
def plot_roc_curve(y_test, y_pred):
|
| 94 |
+
false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, y_pred)
|
| 95 |
+
|
| 96 |
+
print("False Positive rate: ", false_positive_rate)
|
| 97 |
+
print("True Positive rate: ", true_positive_rate)
|
| 98 |
+
|
| 99 |
+
roc_auc = auc(false_positive_rate, true_positive_rate)
|
| 100 |
+
|
| 101 |
+
plt.title('Receiver Operating Characteristic')
|
| 102 |
+
plt.plot(false_positive_rate, true_positive_rate, 'b',
|
| 103 |
+
label='AUC = %0.2f' % roc_auc)
|
| 104 |
+
plt.legend(loc='lower right')
|
| 105 |
+
plt.plot([0, 1], [0, 1], 'r--')
|
| 106 |
+
plt.xlim([-0.1, 1.2])
|
| 107 |
+
plt.ylim([-0.1, 1.2])
|
| 108 |
+
plt.ylabel('True Positive Rate')
|
| 109 |
+
plt.xlabel('False Positive Rate')
|
| 110 |
+
plt.show()
|
| 111 |
+
|
| 112 |
+
def train(X_train, y_train, X_test):
|
| 113 |
+
""" Trains and predicts dataset with a Random Forest classifier """
|
| 114 |
+
clf = RandomForestClassifier(n_estimators=40, oob_score=True)
|
| 115 |
+
clf.fit(X_train, y_train)
|
| 116 |
+
print("The best classifier is: ", clf)
|
| 117 |
+
|
| 118 |
+
# Estimate score
|
| 119 |
+
scores = cross_val_score(clf, X_train, y_train, cv=5)
|
| 120 |
+
print(scores)
|
| 121 |
+
print('Estimated score: %0.5f (+/- %0.5f)' % (scores.mean(), scores.std() / 2))
|
| 122 |
+
|
| 123 |
+
title = 'Learning Curves (Random Forest)'
|
| 124 |
+
plot_learning_curve(clf, title, X_train, y_train, cv=5)
|
| 125 |
+
plt.show()
|
| 126 |
+
|
| 127 |
+
# Predict
|
| 128 |
+
y_pred = clf.predict(X_test)
|
| 129 |
+
import pickle
|
| 130 |
+
with open('data.pkl','wb') as file:
|
| 131 |
+
pickle.dump(clf,file)
|
| 132 |
+
return y_test, y_pred
|
| 133 |
+
|
| 134 |
+
print("Reading datasets...\n")
|
| 135 |
+
x, y = read_datasets()
|
| 136 |
+
x.describe()
|
| 137 |
+
|
| 138 |
+
print("Extracting features...\n")
|
| 139 |
+
x = extract_features(x)
|
| 140 |
+
print(x.columns)
|
| 141 |
+
print(x.describe())
|
| 142 |
+
|
| 143 |
+
print("Splitting datasets into train and test dataset...\n")
|
| 144 |
+
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=44)
|
| 145 |
+
|
| 146 |
+
print("Training datasets...\n")
|
| 147 |
+
y_test, y_pred = train(X_train, y_train, X_test)
|
| 148 |
+
|
| 149 |
+
print('Classification Accuracy on Test dataset: ', accuracy_score(y_test, y_pred))
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
cm = confusion_matrix(y_test, y_pred)
|
| 154 |
+
print('Confusion matrix, without normalization')
|
| 155 |
+
print(cm)
|
| 156 |
+
plot_confusion_matrix(cm)
|
| 157 |
+
|
| 158 |
+
cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
|
| 159 |
+
print('Normalized confusion matrix')
|
| 160 |
+
print(cm_normalized)
|
| 161 |
+
plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix')
|
| 162 |
+
|
| 163 |
+
print(classification_report(y_test, y_pred, target_names=['Fake', 'Genuine']))
|
| 164 |
+
|
| 165 |
+
plot_roc_curve(y_test, y_pred)
|