Diff of /Models/randomforest.py [000000] .. [efbc2d]

Switch to unified view

a b/Models/randomforest.py
1
# Importing the libraries
2
import numpy as np
3
import matplotlib.pyplot as plt
4
import pandas as pd
5
from sklearn.ensemble import RandomForestClassifier
6
from sklearn.model_selection import train_test_split, cross_val_score
7
from sklearn.model_selection import GridSearchCV
8
from sklearn.metrics import accuracy_score, roc_auc_score, roc_curve
9
10
# Importing the dataset
11
dataset = pd.read_csv('../Dataset/diabetes.csv')
12
X = dataset.iloc[:, :-1].values
13
y = dataset.iloc[:, 8].values
14
15
# Splitting the dataset into the Training set and Test set
16
from sklearn.model_selection import train_test_split
17
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, 
18
                                                    random_state = 42)
19
20
# Feature Scaling
21
from sklearn.preprocessing import StandardScaler
22
sc = StandardScaler()
23
X_train = sc.fit_transform(X_train)
24
X_test = sc.transform(X_test)
25
26
# Parameter evaluation
27
rfclf = RandomForestClassifier(random_state=42)
28
parameters={'n_estimators': [50, 100],
29
            'max_features': ['auto', 'sqrt', 'log2'],
30
            'max_depth' : [4,5,6,7],
31
            'criterion' :['gini', 'entropy']
32
}
33
gridsearch=GridSearchCV(rfclf, parameters, cv=50, scoring='roc_auc', n_jobs = -1)
34
gridsearch.fit(X, y)
35
print(gridsearch.best_params_)
36
print(gridsearch.best_score_)
37
38
39
rf = RandomForestClassifier(n_estimators=100, criterion = 'gini', max_depth = 6, 
40
                            max_features = 'auto', random_state=0)
41
rf.fit(X_train, y_train)
42
print("Accuracy on training set: {:.3f}".format(rf.score(X_train, y_train)))
43
print("Accuracy on test set: {:.3f}".format(rf.score(X_test, y_test)))
44
45
y_pred = rf.predict(X_test)
46
47
# Making the Confusion Matrix
48
from sklearn.metrics import classification_report, confusion_matrix
49
cm = confusion_matrix(y_test, y_pred)
50
51
print('TP - True Negative {}'.format(cm[0,0]))
52
print('FP - False Positive {}'.format(cm[0,1]))
53
print('FN - False Negative {}'.format(cm[1,0]))
54
print('TP - True Positive {}'.format(cm[1,1]))
55
print('Accuracy Rate: {}'.format(np.divide(np.sum([cm[0,0],cm[1,1]]),np.sum(cm))))
56
print('Misclassification Rate: {}'.format(np.divide(np.sum([cm[0,1],cm[1,0]]),np.sum(cm))))
57
58
round(roc_auc_score(y_test,y_pred),5)