-
Notifications
You must be signed in to change notification settings - Fork 0
/
ML_Algorithm.py
270 lines (183 loc) · 6.77 KB
/
ML_Algorithm.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# Linear Regression :
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# data = pd.read_csv("Datasets/tips.csv")
# print(data.head())
# print(data.info())
# print(data.shape)
# print(data.describe())
# print(data.sample(10))
# print(data.groupby("day").count())
# df2 = data.groupby('day').sum()
# df2.drop(['smoker','sex','time'], inplace=True, axis=1)
# df2['percent'] = df2['tip'] / df2['total_bill'] * 100
# print(df2)
# df3 = data.groupby('smoker').sum()
# df3['percent'] =df3['tip'] / df3['total_bill'] * 100
# print(df3)
# df4 = data.groupby(['day','size']).sum()
# df4['percent'] = df4['tip'] / df4['total_bill'] * 100
# print(df4)
# sns.catplot(x='day', kind='count', data=data, color='green')
# plt.show()
# sns.catplot(x='day', hue='size', kind='count', data=data)
# plt.show()
# data.replace({'sex':{'Male': 0 ,'Female': 1 }, 'smoker': {'No': 0 , 'Yes': 1}}, inplace=True)
# print(data.head())
# days = pd.get_dummies(data['day'], dtype=int)
# print(days.sample(10)
# data = pd.concat([data, days], axis=1)
# times = pd.get_dummies(data['time'], dtype=int)
# data = pd.concat([data, times], axis=1)
# print(data.sample(3))
# X = data[['sex', 'smoker', 'size', 'Fri', 'Sat', 'Sun', 'Dinner']]
# print(X)
# y = data[['tip']]
# print(Y)
# from sklearn.model_selection import train_test_split
# from sklearn.linear_model import LinearRegression
# from sklearn import metrics
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.25, random_state= 26)
# print(X_train)
# print(y_train)
# reg = LinearRegression()
# reg.fit(X_train, y_train)
# predict = reg.predict(X_test)
# print(predict)
# print(y_test)
# sns.displot(y_test-predict)
# g = sns.FacetGrid(data, col='time', row='sex')
# g = sns.FacetGrid(data, col='time', hue='sex')
# g = sns.FacetGrid(data, col='time')
# g.map(sns.scatterplot, 'total_bill', 'tip')
# g.map(sns.scatterplot, 'total_bill','tip','sex')
# g.map_dataframe(sns.scatterplot, x='total_bill',y='tip',hue='sex')
# g.add_legend()
# sns.relplot(data=data, x='total_bill', y='tip', hue='day', col='time', row='sex', style='time')
# sns.relplot(data=data, x='total_bill', y='tip', hue='smoker', style='time')
# sns.relplot(data=data, x='total_bill', y='tip', hue='smoker', style='time', kind='line')
# sns.relplot(data=data, x='total_bill', y='tip', size='size')
# sns.scatterplot(data=data, x='total_bill', y='tip', hue='size', size='size',
# sizes=(20, 200), legend='full'
# )
# sns.regplot(data=data, x='total_bill', y='tip')
# pl = sns.PairGrid(data)
# pl.map(sns.scatterplot)
# plt.show()
# print('Mean aboulute error:', metrics.mean_absolute_error(y_test,predict))
# print('Mean squared error:', metrics.mean_squared_error(y_test,predict))
# print('Root Mean squared error:', np.sqrt(metrics.mean_squared_error(y_test,predict)))
# New Data
# print(X.head())
# new_customer = np.array([0,1,2,1,0,0,1]).reshape(1, -1)
# new_customer = np.array([0,1,3,1,0,0,0]).reshape(1, -1)
# print(new_customer)
# new_customer_Predict = reg.predict(new_customer)
# print(new_customer_Predict)
# data = pd.read_csv('/Datasets/boston.csv')
# data = data.rename(columns={'medv':'price'})
# print(data.head())
# print(data.shape)
# print(data.columns)
# print(data.info())
# print(data.nunique())
# print(data.isnull().sum())
# print(data.describe())
# def select_data (df, lower ,upper):
# mask = (df < lower | df > upper)
# selected_data = df[mask]
# return select_data
# corr = select_data()
# corr = data.corr()
# max_corr =corr[corr >= 0.5]
# max_corr =corr[corr <= -0.5]
# print(corr.shape)
# plt.figure(figsize=(10, 10))
# plt.figure(figsize=(15, 8))
# sns.heatmap(max_corr, annot=True,cmap='coolwarm', cbar=True)
# sns.heatmap(corr, annot=True,cmap='coolwarm', cbar=True)
# plt.show()
# X = data[['zn']]
# X = data[['rm']]
# y = data['price']
# print(X)
# print(y)
# from sklearn.model_selection import train_test_split
# X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state = 4)
# print(X_train)
# print(X_test)
# print(y_train)
# print(y_test)
# from sklearn.linear_model import LinearRegression
# slr = LinearRegression()
# slr.fit(X_train, y_train)
# print(slr.intercept_)
# print(slr.coef_)
# from sklearn import metrics
# y_pred = slr.predict(X_train)
# print('R^2:',metrics.r2_score(y_train, y_pred))
# print('MAE:',metrics.mean_absolute_error(y_train, y_pred))
# print('MSE:',metrics.mean_squared_error(y_train, y_pred))
# print('RMSE:',np.sqrt(metrics.mean_squared_error(y_train, y_pred)))
# sns.scatterplot(x=y_train, y=y_pred)
# plt.scatter(y_train, y_pred)
# plt.show()
# sns.displot(y_train-y_pred)
# plt.show()
#Multiple Linear Regression (MLR)
data = pd.read_csv('Datasets/boston.csv')
data = data.rename(columns={'medv':'price'})
X = data.drop(['price'], axis = 1)
y = data['price']
# print(X)
# Spliting DataSets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3, random_state = 4)
# print(X_train)
#Import Llibrary For Linear Regression
# from sklearn.linear_model import LinearRegression
#Create a Linear Regression
# MLR = LinearRegression()
#Training The Model
# MLR.fit(X_train, y_train)
# print(MLR.intercept_)
# print(MLR.coef_)
# coefficients = pd.DataFrame([X_train.columns,MLR.coef_]).T
# coefficients = coefficients.rename(columns={0:'Fetures',1: 'Coefficients'})
# print(coefficients)
# Model Prediction on Train data
# y_pred = MLR.predict(X_train)
# from sklearn import metrics
# Model Evaluation
# print('R ^ 2:', metrics.r2_score(y_train, y_pred))
# print('MAE :', metrics.mean_absolute_error(y_train, y_pred))
# print('MSE :', metrics.mean_squared_error(y_train, y_pred))
# print('RMSE :', np.sqrt(metrics.mean_squared_error(y_train, y_pred)))
# Visualizing the differences between actual and predicted values
# sns.scatterplot(x=y_train, y=y_pred)
# plt.scatter(y_train, y_pred)
# plt.show()
# Histogram of Residuals
# sns.displot(y_train-y_pred)
# plt.show()
# Creates a Polynomial Regression Model for the given degree
from sklearn.preprocessing import PolynomialFeatures
poly_features = PolynomialFeatures(degree = 2)
#Transform the features to degree
quadratic_x_train = poly_features.fit_transform(X_train)
# Fit the transform features to linear regression
from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(quadratic_x_train, y_train)
# predict on trainig data
y_train_predict = reg.predict(quadratic_x_train)
# predict onn test data
y_test_predict = reg.predict(poly_features.fit_transform(X_test))
# R2.score for test data
from sklearn import metrics
print('R ^ 2 :', metrics.r2_score(y_test, y_test_predict))
# R2.score for train data
from sklearn import metrics
print('R ^ 2 :', metrics.r2_score(y_train, y_train_predict))