-
Notifications
You must be signed in to change notification settings - Fork 0
/
SVR.py
75 lines (57 loc) · 1.89 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
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 24 18:31:50 2021
@author: adgbh
"""
"""
import libraries
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
"""
Import dataset
"""
dataset = pd.read_csv("Position_Salaries.csv")
x = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, -1].values
"""
Reshaping the label or Dependent Matrix
"""
y = y.reshape(len(y),1) # reshaping y since sklearn accepts(feature scaling) only 2d array
"""
Feature scaling
Using two standard scalers because we have to reverse the scaling to the original value where x and y are differently scaled
"""
from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
x = sc_x.fit_transform(x[:, :])
sc_y = StandardScaler()
y = sc_y.fit_transform(y[:, :])
"""
Training the SVR Model
"""
from sklearn.svm import SVR
svr_regressor = SVR(kernel = 'rbf') #Refers to the Guassian RBF kernel for the regressor
svr_regressor.fit(x, y)
print (sc_y.inverse_transform(svr_regressor.predict(sc_x.transform([[6.5]])))) # using the standard scaler to get the predicted salary in original scale
"""
plotting the results on a graph
"""
plt.scatter(sc_x.inverse_transform(x),sc_y.inverse_transform(y) , color='red')
plt.plot(sc_x.inverse_transform(x), sc_y.inverse_transform(svr_regressor.predict(x)), color='blue')
plt.xlabel('Job Level')
plt.ylabel('Salary')
plt.title('SVR Model to predict salary')
plt.show()
"""
Smoothing the curve
"""
x_grid = np.arange(min(sc_x.inverse_transform(x)), max(sc_x.inverse_transform(x)), 0.1)
x_grid = x_grid.reshape(len(x_grid),1)
plt.scatter(sc_x.inverse_transform(x),sc_y.inverse_transform(y) , color='black')
plt.plot(x_grid, sc_y.inverse_transform(svr_regressor.predict(sc_x.transform(x_grid))), color='green') # we use a transform here because the x_grid is reverted to unscaled value
plt.xlabel('Job Level')
plt.ylabel('Salary')
plt.title('SVR Model to predict salary')
plt.show()