-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsvr.py
86 lines (64 loc) · 2.59 KB
/
svr.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
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 13:42:18 2020
@author: Maria
"""
# Support Vector Regression
import matplotlib.pyplot as plt
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.model_selection import GridSearchCV
import joblib
###############################################
# SVR #
###############################################
class svr:
def __init__(self, X_train, y_train, X_test, y_test):
self.X_train = X_train
self.y_train = y_train
self.y_test = y_test
regr = SVR(C=1.0,
epsilon=0.2,
gamma='scale',
kernel='poly'
)
regr.fit(X_train, y_train)
# Prediction and Error
self.predictions = regr.predict(X_test)
self.errors = abs(self.predictions - y_test)
self.mse = mean_squared_error(y_test, self.predictions)
self.mae = mean_absolute_error(y_test, self.predictions)
filename = 'models/svr.sav'
joblib.dump(regr, filename)
def getPredictions(self):
return self.predictions
def getMAE(self):
return self.mae
def getMSE(self):
return self.mse
def getName(self):
return "SVR"
###############################################
# VISUALISATION #
###############################################
def svr_graph(self):
plt.scatter(self.y_test, self.predictions, c='#FF7AA6') #FF7AA6 #EA526F
plt.xlabel('True Values [Days survived]')
plt.ylabel('Predictions [Days survived]')
plt.plot(np.unique(self.y_test), np.poly1d(np.polyfit(self.y_test, self.predictions, 1))(np.unique(self.y_test)))
plt.show()
def grid_search(self):
param_grid = {'kernel': ['rbf','poly','sigmoid'], # rbf
'gamma': ['scale', 'auto'], # scale
'C': [0.1, 1, 10, 100], # 100
'epsilon': [0.0001, 0.001, 0.01, 0.1, 1, 10], # 10
'shrinking':[True, False] # True
}
grid = GridSearchCV(SVR(), param_grid, refit = True, verbose = 3)
# fitting the model for grid search
grid.fit(self.X_train, self.y_train)
print("\nBest params:", grid.best_params_)
print("\nBest score:", grid.best_score_)
return grid.best_params_