-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregression.py
186 lines (135 loc) · 4.66 KB
/
regression.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import operator
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.metrics import classification_report
# Correlation Matrix
df = pd.read_csv("auto-mpg.csv")
#del df['origin']
#d.head()
sns.heatmap(df.corr(), annot = True, square = True, vmin = -1, vmax = 1, center = 0, cmap = 'coolwarm')
# Pair-Plot
sns.pairplot(df, hue = "origin", diag_kind = "origin")
## Linear and Polynomial Regression
# Split dataset
X = df['weight'].values
y = df['mpg'].values
X = X[:, np.newaxis]
y = y[:, np.newaxis]
X_train = X[:-20]
y_train = y[:-20]
X_test = X[-20:]
y_test = y[-20:]
# Simple Linear Regression
model = LinearRegression()
model.fit(X_train, y_train)
y_train_pred = model.predict(X_train) # mpg train prediction
y_test_pred = model.predict(X_test) # mpg test prediction
mse = model.score(X, y)
print(f"MSE = {mse}")
plt.scatter(X_train, y_train, color = "black", s = 10)
plt.plot(X_train, y_train_pred, color = "green", linewidth = 3)
plt.show()
# Polynomial Regression Degree 2
X = df['weight'].values
y = df['mpg'].values
X = X[:, np.newaxis]
y = y[:, np.newaxis]
polynomial_features= PolynomialFeatures(degree = 2)
X_poly = polynomial_features.fit_transform(X)
X_poly_train = X_poly[:-20]
y_train = y[:-20]
X_poly_test = X_poly[-20:]
y_test = y[-20:]
model = LinearRegression()
model.fit(X_poly_train, y_train)
y_train_pred = model.predict(X_poly_train)
y_test_pred = model.predict(X_poly_test)
rmse_test = np.sqrt(mean_squared_error(y_test,y_test_pred))
print('\nTest RMSE: %8.15f' % rmse_test)
rmse = np.sqrt(mean_squared_error(y_train,y_train_pred))
print('\nTraining RMSE: %8.15f' % rmse)
plt.scatter(X, y, s=10)
sort_axis = operator.itemgetter(0)
sorted_zip = sorted(zip(X, y_train_pred), key=sort_axis)
X_poly_train, y_train_pred = zip(*sorted_zip)
plt.plot(X_poly_train, y_train_pred, color='m')
plt.show()
# Polynomial Regression Degree 3
X = df['weight'].values
y = df['mpg'].values
X = X[:, np.newaxis]
y = y[:, np.newaxis]
polynomial_features= PolynomialFeatures(degree = 3)
X_poly = polynomial_features.fit_transform(X)
X_poly_train = X_poly[:-20]
y_train = y[:-20]
X_poly_test = X_poly[-20:]
y_test = y[-20:]
model = LinearRegression()
model.fit(X_poly_train, y_train)
y_train_pred = model.predict(X_poly_train)
y_test_pred = model.predict(X_poly_test)
rmse_test = np.sqrt(mean_squared_error(y_test,y_test_pred))
print('\nTest RMSE: %8.15f' % rmse_test)
rmse = np.sqrt(mean_squared_error(y_train,y_train_pred))
print('\nTraining RMSE: %8.15f' % rmse)
plt.scatter(X, y, s=10)
sort_axis = operator.itemgetter(0)
sorted_zip = sorted(zip(X, y_train_pred), key=sort_axis)
X_poly_train, y_train_pred = zip(*sorted_zip)
plt.plot(X_poly_train, y_train_pred, color='m')
plt.show()
# Polynomial Regression Degree 4
X = df['weight'].values
y = df['mpg'].values
X = X[:, np.newaxis]
y = y[:, np.newaxis]
polynomial_features= PolynomialFeatures(degree = 4)
X_poly = polynomial_features.fit_transform(X)
X_poly_train = X_poly[:-20]
y_train = y[:-20]
X_poly_test = X_poly[-20:]
y_test = y[-20:]
model = LinearRegression()
model.fit(X_poly_train, y_train)
y_train_pred = model.predict(X_poly_train)
y_test_pred = model.predict(X_poly_test)
rmse_test = np.sqrt(mean_squared_error(y_test,y_test_pred))
print('\nTest RMSE: %8.15f' % rmse_test)
rmse = np.sqrt(mean_squared_error(y_train,y_train_pred))
print('\nTraining RMSE: %8.15f' % rmse)
plt.scatter(X, y, s=10)
sort_axis = operator.itemgetter(0)
sorted_zip = sorted(zip(X, y_train_pred), key=sort_axis)
X_poly_train, y_train_pred = zip(*sorted_zip)
plt.plot(X_poly_train, y_train_pred, color='m')
plt.show()
# Logistic Regression
f = pd.read_csv("auto-mpg.csv")
df = df[df['origin'] != 'Europe']
feature_cols = ['mpg', 'displacement', 'horsepower', 'weight','acceleration']
X = df[feature_cols]
y = df['origin']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state = 10)
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
fig, ax = plt.subplots()
cnf_matrix = metrics.confusion_matrix(y_test, y_pred)
sns.heatmap(pd.DataFrame(cnf_matrix), annot = True, cmap = "coolwarm" , fmt = 'g')
ax.xaxis.set_label_position("top")
plt.title('Confusion Matrix', y = 1.1)
plt.ylabel('Actual')
plt.xlabel('Predicted')
print(classification_report(y_test, y_pred))