-
Notifications
You must be signed in to change notification settings - Fork 0
/
SVC-grid_search.py
86 lines (70 loc) · 2.45 KB
/
SVC-grid_search.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
from train_utils import *
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVC
import sys
# from sklearn.cross_validation import cross_val_predict
# from sklearn.metrics import accuracy_score
# Parse Command Line Arguments
graph = False
if 'plot' in sys.argv:
graph = True
__author__ = 'hsheth'
CORES = 4
# Load the data
Xunscaled, yfull = load_data("training_data_FINAL.csv")
# Feature Scaling
Xfull, scaler = feature_scaling(Xunscaled)
enPickle(scaler, "feature_scaler.pickle")
# Partition data into training and testing
Xtrain, Xtest, ytrain, ytest = partition_data([.8, .2], Xfull, yfull)
def perform_grid_search(grid):
gridModel = GridSearchCV(SVC(shrinking=False, cache_size=400),
param_grid=grid, scoring='accuracy', verbose=1, n_jobs=CORES)
gridModel.fit(Xtrain, ytrain)
return gridModel
# Grid Search for C and gamma (general)
gridFirst = [
{
'kernel': ['rbf'],
'gamma': np.logspace(-6, 0, num=13),
'C': np.logspace(-1, 9, num=21),
},
# {
# 'kernel': ['linear'],
# 'C': [1, 5, 10, 50, 100, 500, 1000, 5000, 10000],
# },
]
# gridFirst = [{'kernel': ['rbf'], 'gamma': [5e-2, 1e-2, 5e-3, 1e-3, 5e-4, 1e-4], 'C': [1, 5, 10, 50, 100, 500, 1000]}]
# First Model (general)
gridModelGen = perform_grid_search(gridFirst)
print("Gen - Best Score on CV Data:")
print(gridModelGen.best_score_)
print("Gen - Best Parameters:")
print(gridModelGen.best_params_)
print("Gen - Best Score on Testing Data:")
print(gridModelGen.best_estimator_.score(Xtest, ytest))
# Make a Plot
if graph:
plotGridSearchResults(gridFirst, gridModelGen, "Grid Search Model 1 Results")
# Grid Search (focused)
gridSecond = [{
'kernel': ['rbf'],
'gamma': np.logspace(-6, -5, num=9),
'C': np.logspace(5, 7, num=9),
}]
# Second Model (focused)
gridModelFocus = perform_grid_search(gridSecond)
print("Focus - Best Score on CV Data:")
print(gridModelFocus.best_score_)
print("Focus - Best Parameters:")
print(gridModelFocus.best_params_)
print("Focus - Best Score on Testing Data:")
print(gridModelFocus.best_estimator_.score(Xtest, ytest))
# Plot the Focused/Zoomed In Grid Search Results
if graph:
plotGridSearchResults(gridSecond, gridModelFocus, "Grid Search Zoomed Results")
# Save Results
enPickle(gridModelGen, "grid_search_gen.pickle")
enPickle(gridModelFocus, "grid_search_focus.pickle")
print("Saved modelGen and modelFocus to pickle files")
#interact(gl=globals(), lo=locals())