forked from Charles57-CWU/DSCVizTests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasic_Cross_Validation.py
134 lines (102 loc) · 3.94 KB
/
Basic_Cross_Validation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""
This script will run cross validation against various classification models from the scikit-learn library
Add column headers, fix missing values, and make sure class labels are in numeric form, before running models
Make sure there is only one class column, and the remaining columns are attributes you'd like to run in the model
"""
# import models
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import SGDClassifier
# import metrics/utilities
import pandas as pd
from sklearn.model_selection import cross_validate
# clear warnings
import warnings
def warn(*args, **kwargs):
pass
warnings.warn = warn
# =====================================================
class CrossValidateModels:
def __init__ (self, dataset_name, class_column_name):
self.dataset_name = dataset_name
self.class_column_name = class_column_name
self.x = None
self.y = None
# csv to data and labels
def get_data_and_labels(self):
# read the dataset file
data = pd.read_csv(self.dataset_name)
# labels
self.y = data[self.class_column_name]
data.drop([self.class_column_name], axis=1, inplace=True)
# data
attributes = data.columns.values.tolist()
print(attributes)
self.x = data[attributes]
# =====================================================
# run through tests
def run_tests(self, number_of_folds):
# create dataframe header
fold_names = ['Model']
for i in range(number_of_folds):
fold_names.append('Fold_' + str(i+1))
fold_names.append('AVG')
print(fold_names)
# results dataframe
results = pd.DataFrame(columns=fold_names)
# run through models you select, easy to add more
models = ['DT', 'SGD', 'NB', 'SVM', 'KNN', 'LR', 'MLP', 'RF']
for model in models:
if model == 'DT':
clf = DecisionTreeClassifier()
elif model == 'SGD':
clf = SGDClassifier()
elif model == 'RF':
clf = RandomForestClassifier()
elif model == 'NB':
clf = GaussianNB()
elif model == 'SVM':
clf = SVC()
elif model == 'KNN':
clf = KNeighborsClassifier()
elif model == 'LR':
clf = LogisticRegression()
elif model == 'MLP':
clf = MLPClassifier()
else:
clf = None
# run cross validation
cv = cross_validate(clf, self.x, self.y, cv=number_of_folds)
# get scores
_splits = list(map(lambda n: '%.2f' % n, cv['test_score']))
# get average
_avg = '{:.2f}'.format(cv['test_score'].mean())
# combine into dataframe row
row = [model]
for split in _splits:
row.append(split)
row.append(_avg)
print(row)
# add result
results.loc[(len(results.index))] = row
return results
# =====================================================
if __name__ == '__main__':
# input filename
dataset_name = 'iris_dataset.csv'
class_column_name = 'class'
# number of folds for CV
number_of_folds = 3
# output filename
output_csv_name = 'CWU_RESULTS1.csv'
m = CrossValidateModels(dataset_name, class_column_name)
# run models
m.get_data_and_labels()
results = m.run_tests(number_of_folds)
# output results
results.to_csv(output_csv_name, index=False)