-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJazmynFuller_HW2.py
366 lines (190 loc) · 8.03 KB
/
JazmynFuller_HW2.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
#!/usr/bin/env python
# coding: utf-8
# ## HomeWork 2 EDA, Data Visualization and Linear Regression Model
# # Due on 9/30/2019 mid-night
# ## Late Policy: Take off 50% after one day, 80% after two days
# In[154]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
import random
import warnings
warnings.filterwarnings('ignore')
# ## Loading our MPG3 dataset
# In[155]:
mpg = pd.read_csv("mpg3.csv")
mpg.head()
# In[156]:
mpg.shape
# # Question 1: Check to see if there are any missing values. Fix the missing values by imputing value from the mean. After fixing missing values, you should still have 405 rows
# In[157]:
# Type your code here\
df = sns.load_dataset('mpg')
na_replacement = mpg.mean()
mpg.fillna(na_replacement, inplace=True)
mpg.isnull().any()
mpg.shape
# # Question 2 : Use Boxplot to see if there are any outliers on ALL of the numerical fields (Hint you should have 402 rows now after outliers removal)
# In[158]:
sns.boxplot(x=mpg['displacement']);
# In[159]:
sns.boxplot(x=mpg['acceleration']);
# In[160]:
sns.boxplot(x=mpg['model_year']);
# In[161]:
sns.boxplot(x=mpg['horsepower']);
# In[162]:
sns.boxplot(x=mpg['mpg']);
# In[163]:
sns.boxplot(x=mpg['weight']);
# In[164]:
sns.boxplot(x=mpg['cylinders']);
# ### Removing outliers
# In[165]:
mpg = mpg[mpg.mpg < 90]
mpg = mpg[mpg.weight < 10000 ]
mpg = mpg[mpg.cylinders < 20 ]
mpg.shape
# # Question 3 : Remove any duplicates rows. Hint after removal, you should have 400 rows now
# In[166]:
# Show number of rows before
print("Before duplicates removal: ", mpg.shape)
# Type your code here to remove duplicated rows
mpg.drop_duplicates(keep='first',inplace=True)
# hint: Google how to remove duplicate rows in pandas dataframe and you will find the link
# https://pandas.pydata.org/pandas-docs/version/0.17/generated/pandas.DataFrame.drop_duplicates.html
# Show number of rows before
print("After duplicates removal: ", mpg.shape)
# # Question 4: Create a pair plot
# In[167]:
sns.pairplot(mpg);
# # Question 5: Create a FacetGrid of a scatter plot of mpg vs weight for different country
# In[168]:
g = sns.FacetGrid(mpg, col='origin')
g.map(plt.scatter, 'mpg', 'weight');
# # Now Load the adult income dataset and do some EDA and answer the following questions based on the Adult income dataset
# In[169]:
adult = pd.read_csv("adult.data.csv")
adult.head()
# In[170]:
adult.isnull().any()
# In[171]:
print(adult.shape)
adult.describe()
# # Question 6 : Which two martial-status is most common
# In[172]:
most_common_marital_status = adult['marital-status'].value_counts();
print(most_common_marital_status)
print("\nThe two most common marital-statuses are Married-civ-spuse (%s recorded) and Never-married (%s recorded)" % (most_common_marital_status.iloc[0], most_common_marital_status.iloc[1]))
# # Question 7: Plot the age distribution broken down by different martial-status using a FacetGrid
# In[173]:
h = sns.FacetGrid(adult, col='marital-status')
h.map(plt.hist,'age',bins=20);
# # Question 8: Create a Facet Grid for fnlwgt against age broken down by race and sex. You should have 10 sub-plots
# In[174]:
fnl_vs_age = adult[['fnlwgt','age','race','sex']]
m = sns.FacetGrid(fnl_vs_age, row='sex' ,col='race')
m = m.map(plt.hist,'age',bins=10).set_axis_labels("Age", "Fnlwgt")
# # Now Load the housing data and answer all the remaining questions based on the housing dataset
# In[175]:
housing = pd.read_csv("USA_housing.csv")
housing.head()
# In[176]:
# a scatter plot comparing num_children and num_pets
housing.plot(kind='scatter',x='Income',y='Price',color='blue');
plt.show()
housing.shape
# In[177]:
housing.plot(kind='scatter', x = "HouseAge", y = "Price", color = "blue");
# In[178]:
housing.plot(kind='scatter', x = "NumberOfRooms", y = "Price", color = "green");
# # Question 9: Use a pair plot or individual scatter plots, pick ONE variable that best explains house price
# In[179]:
# Type your answer (ie which variable affect the Price the most)
housing.plot(kind='scatter', x = "HouseAge", y = "Price", color = "blue");
housing.plot(kind='scatter', x = "NumberOfRooms", y = "Price", color = "orange");
housing.plot(kind='scatter', x = "Population", y = "Price", color = "red");
housing.plot(kind='scatter', x = "AreaNumberOfBedrooms", y = "Price", color = "green");
housing.plot(kind='scatter', x = "Income", y = "Price", color = "purple");
print('\nBased on the plots, I believe the income of the homeowners best explains house price.')
#housing.plot(kind='scatter', x = "AreaNumberOfBedrooms", y = "Price", color = "yellow");
# In[180]:
# from sklearn.model_selection import train_test_split
# X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
# model2 = LinearRegression()
# model2.fit(X_train, Y_train)
# print('R-squared:', metrics.r2_score(Y_test, Y_pred))
# # Question 10: Use that variable to build a one-variable Linear Regression model of the house price. Make sure you split the data between Training and Testing set first, Save 20% as your testing data
# In[181]:
Xarray = housing['Income'].values
Yarray = housing['Price'].values
X = Xarray.reshape(-1, 1)
Y = Yarray.reshape(-1, 1)
model = LinearRegression()
model.fit(X, Y)
# ## Split data values
# In[182]:
# Show your R-square and RMSE
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
model = LinearRegression()
model.fit(X_train, Y_train)
Y_pred = model.predict(X_test)
print(X_train.shape)
print(X_test.shape)
print(Y_train.shape)
print(Y_test.shape)
print('R-squared: ', metrics.r2_score(Y_test, Y_pred))
print('RMSE:', np.sqrt(metrics.mean_squared_error(Y_test, Y_pred)))
# ## Non-Split
# In[183]:
modelA = LinearRegression()
modelA.fit(X, Y)
Y_predA = modelA.predict(X)
print('R-squared: ', metrics.r2_score(Y, Y_predA))
print('RMSE:', np.sqrt(metrics.mean_squared_error(Y, Y_predA)))
# In[185]:
plt.scatter(X_test, Y_test, color='gray')
plt.scatter(X_test, Y_pred, color='red', linewidth=2)
plt.show()
# # Question 11: Now do a 10-fold Cross Validation of your model. Does your model pass cross validation?
# In[186]:
# Show your work here
rsquare = []
for i in range(10):
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state = random.randint(1,1000))
model1 = LinearRegression()
model1.fit(X_train, Y_train)
Y_pred = model1.predict(X_test)
rsquare.append(metrics.r2_score(Y_test, Y_pred))
r2df = pd.DataFrame({'Trial':range(10), 'R_squared': rsquare})
r2df
r2df.plot.bar(x='Trial',y='R_squared')
x = r2df['R_squared'].mean();
print('The mean of the r-squared values is %s \n' % x)
print('My model appears to pass the testing data as the R-squared values are within the same range')
# # Question 12: Now pick ONE more variable in addition to the variable you choose from Question 9 and build a two-variables Linear Regression model of the house price. Make sure you split the data into training and testing set first
# In[187]:
# Show your work here
X = housing[['Population','Income']].values.reshape(-4, 2)
Y = housing['Price'].values.reshape(-1, 1)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0);
# # Question 13: Do a 10-fold Cross Validation of your two-variable model. Does your model pass cross validation?
# In[188]:
# Show your work here
rsquare = []
for i in range(10):
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state = random.randint(1,1000))
model3 = LinearRegression()
model3.fit(X_train, Y_train)
Y_pred = model3.predict(X_test)
rsquare.append(metrics.r2_score(Y_test, Y_pred))
r2df1 = pd.DataFrame( {'trial': range(10), 'Rsquare': rsquare})
r2df1.plot.bar(x='trial', y='Rsquare')
print('The mean of the r-squared values is %s' % r2df1['Rsquare'].mean())
print('Based off of my r-squared value, it passes the cross validation.')
# In[ ]:
# In[ ]: