-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path[code]assignment_2.py
More file actions
470 lines (343 loc) · 25.5 KB
/
[code]assignment_2.py
File metadata and controls
470 lines (343 loc) · 25.5 KB
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# -*- coding: utf-8 -*-
"""Assignment 2
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ThgeMhjIQhE4KQVc5RMJoubqSikhlCVP
All Tasks:
ML ASSIGNMENT 2
1. Use Dataframe constructor in Pandas to create your own Dataframe.
2. Print a chosen record (row) or a chosen column (data field).
3. Print rows that satisfy a condition on one of the column entries. For example, if you create a DataFrame of players' performance in a cricket match and each record has the runs scored by the player in a cricket match, then you should be able to the print records of players who scored more than 50 runs.
4. Also sort the records based on the number of runs scored by each player.
5. Use vectorised operations. For example, you may be required to compute the percentage runs scored by each player, where the percentage is with respect to the total runs scored by the team in an innings.
6. Add a new column to the Dataframe. For example, you may want to add the number written on the player's jersey.
7. Export the Dataframe to a file in pickle format and save it as a file. Read the pickle file back to the program.
8. Use matplotlib library to make a scatter plot of columns that contain numeric
9. data. Provide labels to the axes.
10. Implement linear regression to model the dependency between two variables - the predictor x and target y. You can choose any two columns in your data frame as the two variables. Print the coefficients obtained from linear regression and plot the straight line on the scatter plot. Do not use any inbuilt function for implementing linear regression. You need to formulate a linear system of equations and solve them using pseudo inverse. You can compare your result with that produced by the fit() function of LinearRegression model in sklearn.
## **Task 1**
"""
#Assignment 2 by Sanyam Jain (P20QC001)
# Task 1: Use DataFrame constructor in Pandas to create your own Dataframe.
# Dataset used - https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv
# import pandas as pd
# data = {
# 'total_bill':['16.99','10.34','21.01','23.68','24.59'],
# 'tip':['1.01','1.66','3.5','3.31','3.61'],
# 'sex':['F','M','M','M','M'],
# 'smoker':['N','N','N','N','N'],
# 'day':['Sunday','Sunday','Sunday','Sunday','Sunday'],
# 'time':['Dinner','Dinner','Breakfast','Dinner','Lunch'],
# 'table_size':['2','3','3','3','4']
# }
# df=pd.DataFrame(data)
# df
import pandas as pd
data = {
'total_bill':['16.99','10.34','21.01','23.68','24.59','25.29','8.77','26.88','15.04','14.78','10.27','35.26','15.42','18.43','14.83','21.58','10.33','16.29','16.97','20.65','17.92','20.29','15.77','39.42','19.82','17.81','13.37','12.69','21.7','19.65','9.55','18.35','15.06','20.69','17.78','24.06','16.31','16.93','18.69','31.27','16.04','17.46','13.94','9.68','30.4','18.29','22.23','32.4','28.55','18.04','12.54','10.29','34.81','9.94','25.56','19.49','38.01','26.41','11.24','48.27','20.29','13.81','11.02','18.29','17.59','20.08','16.45','3.07','20.23','15.01','12.02','17.07','26.86','25.28','14.73','10.51','17.92','27.2','22.76','17.29','19.44','16.66','10.07','32.68','15.98','34.83','13.03','18.28','24.71','21.16','28.97','22.49','5.75','16.32','22.75','40.17','27.28','12.03','21.01'],
'tip':['1.01', '1.66', '3.5', '3.31', '3.61', '4.71', '2', '3.12', '1.96', '3.23', '1.71', '5', '1.57', '3', '3.02', '3.92', '1.67', '3.71', '3.5', '3.35', '4.08', '2.75', '2.23', '7.58', '3.18', '2.34', '2', '2', '4.3', '3', '1.45', '2.5', '3', '2.45', '3.27', '3.6', '2', '3.07', '2.31', '5', '2.24', '2.54', '3.06', '1.32', '5.6', '3', '5', '6', '2.05', '3', '2.5', '2.6', '5.2', '1.56', '4.34', '3.51', '3', '1.5', '1.76', '6.73', '3.21', '2', '1.98', '3.76', '2.64', '3.15', '2.47', '1', '2.01', '2.09', '1.97', '3', '3.14', '5', '2.2', '1.25', '3.08', '4', '3', '2.71', '3', '3.4', '1.83', '5', '2.03', '5.17', '2', '4', '5.85', '3', '3', '3.5', '1', '4.3', '3.25', '4.73', '4', '1.5', '3'],
'sex':['F', 'M', 'M', 'M', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'M', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'F', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'M', 'M', 'F', 'F', 'M', 'M', 'M', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'F', 'M', 'M', 'M', 'M', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'F', 'M', 'M', 'M', 'F', 'F', 'F', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'M', 'M', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'F', 'F', 'M', 'M', 'M', 'M'],
'smoker':['N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'Y', 'N', 'Y', 'N', 'Y', 'Y', 'Y', 'Y', 'N', 'N', 'N', 'Y', 'N', 'Y', 'N', 'N', 'Y', 'Y', 'N', 'N', 'Y', 'N', 'N', 'N', 'Y', 'N', 'N', 'Y', 'N', 'N', 'N', 'N', 'N', 'N', 'Y', 'N', 'Y', 'Y', 'N', 'Y', 'Y', 'Y', 'Y'],
'day':['Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Sunday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Saturday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Thursday', 'Friday', 'Friday', 'Friday', 'Friday', 'Friday', 'Friday', 'Friday', 'Friday', 'Friday'],
'time':['Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Lunch', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Dinner'],
'table_size':['2', '3', '3', '2', '4', '4', '2', '4', '2', '2', '2', '4', '2', '4', '2', '2', '3', '3', '3', '3', '2', '2', '2', '4', '2', '4', '2', '2', '2', '2', '2', '4', '2', '4', '2', '3', '3', '3', '3', '3', '3', '2', '2', '2', '4', '2', '2', '4', '3', '2', '2', '2', '4', '2', '4', '2', '4', '2', '2', '4', '2', '2', '2', '4', '3', '3', '2', '1', '2', '2', '2', '3', '2', '2', '2', '2', '2', '4', '2', '2', '2', '2', '1', '2', '2', '4', '2', '2', '2', '2', '2', '2', '2', '2', '2', '4', '2', '2', '2']
}
df=pd.DataFrame(data)
df
"""## **Task 2**"""
# Task 2: Print a chosen record (row) or a chosen column (data field).
# Printing Chosen Record
print ("Please enter your row number, we have total 5 rows from 0 to 4")
chosen_record = input()
print (df.loc[int(str(chosen_record))])
# Task 2: Print a chosen record (row) or a chosen column (data field).
# Printing Chosen Column
print ("Please enter which column you want to print, total_bill, tip, sex, smoker, day, time table_size?")
chosen_column = input()
print (df[(str(chosen_column))])
# For Task 2, We can always print the columns and rows directly using the dataframe object applying different methods like:
# 1. Slicing
# 2. iloc (used in printing record)
# Task 2.1: Slicing
df[1:2] # Prints row with index 1 (returns DataFrame)
# Task 2.2: iloc (using Labels)
df.iloc[1] # returns pandas series
"""## **Task 3**"""
# Task 3: Print rows that satisfy a condition on one of the column entries.
# For task 3 we will print following
# 1. Total tip collected in time=='Dinner'
# 2. Maximum tip with maximum table size
df
# Task 3.1: Total tip collected in time=='Dinner'
# First find the records where time==Dinner and column==tip and then convert to list of integers
collected_tip = (df.tip[(df['time']=='Dinner')]).to_list()
collected_tip # This will print ['1.01', '1.66', '3.31'] which is string hence need to convert
new_tips=collected_tip # storing previous list to a temporary list called new_tips (fruitful when the list is unknown size)
for i in range(0,len(collected_tip)):
new_tips[i]=float(collected_tip[i])
print (new_tips)
print("Sum is: "+ str(sum(new_tips)))
# Task 3.2: tip with maximum table size
df['table_size'].max() # max() function returns the maximum value among the column of a dataframe.
tip_max = df.tip[df['table_size']==df['table_size'].max()] # Satisfies the condition of maximum table size in column entries
print (tip_max)
"""## **Task 4**"""
# Task 4: Also sort the records based on the total bill paid by the customer
# 1. Sort with function
# 2. Sort without function
df
# Task 4.1: with function
df.sort_values(by='total_bill')
# Task 4.2: without function
# Aprroach will be like:
# 1. Fetch the column by which you want to sort the DataFrame
# 2. Sort the column
# 3. Fetch associated rows with each value of the column from DataFrame
# 4.2.1:
handler_column = df['total_bill']
temp_handler = handler_column
for eachitem in range (0, len(handler_column)):
temp_handler[eachitem] = float(handler_column[eachitem])
# print (handler_column[eachitem])
final_list = temp_handler.to_list()
# Apply sorting algorithm to the list/array now
final_list
# 4.2.2: Using Bubble sort
preserver_list = final_list
temp_list = final_list
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
bubbleSort(final_list)
print ("Sorted list is:")
for i in range(len(final_list)):
# print (final_list[i])
temp_list[i]=float(final_list[i])
temp_list
sorted_array = temp_list
print (df)
print (sorted_array)
# Task 4.2.3: Fetch associated rows with each value of the column from DataFrame (This method works for only distinct total_bill values)
# df.loc[df['total_bill']==10.34]
for item in sorted_array:
for i in (df['total_bill']):
if(item == i):
print (df.loc[df['total_bill']==i])
#Phew!!!!!
"""## **Task 5 + Task 6**"""
# Task 5: Use vectorised operations.
# For example, you may be required to compute the percentage runs scored by each player,
# where the percentage is with respect to the total runs scored by the team in an innings.
df
# In our case we can compare percentage ratio of total bill versus tip given.
# We can add a new column once calculated for each customer
# df['tip/bill']=(df['tip']/df['total_bill'])*100
df['tip/bill'] = df['tip'] # Just to initialize the DataFrame of size same with the dataset
rows_count=df.shape[0] # Gives row count
for x in range (0,rows_count):
percentage = (float(df.tip[x])/df.total_bill[x])*100
df['tip/bill'][x]=float(percentage)
print (percentage)
df # Task 6 Addedd a new column to DataFrame namely tip/bill
"""## **Task 7**"""
# Task 7: Export the Dataframe to a file in pickle format and save it as a file. Read the pickle file back to the program.
df.to_pickle("./assignment2.pkl") # to_pickle saves the df as pkl file
read_df = pd.read_pickle("./assignment2.pkl") # reads the pkl file and unload it to a dataframe object
read_df
"""## **Task 8** + **Task 9**"""
# Task 8+9: Use matplotlib library to make a scatter plot of columns that contain numeric
# In our example, we can make a scatter plot as x-asis for total bill and y axis as tip and vice versa.
# Also printing labels
import matplotlib.pyplot as plt
# Task 8.1: x-axis: total_bill , y-axis: tip
plt.scatter(df['total_bill'],df['tip'])
plt.xlabel("total bill")
plt.ylabel("tip")
# Task 8.2: y-axis: total_bill , x-axis: tip
plt.scatter(df['tip'],df['total_bill'])
plt.xlabel("tip")
plt.ylabel("total bill")
"""### **Task 10**"""
# Task 10:Implement linear regression to model the dependency
# between two variables - the predictor x and target y. You can choose any two
# columns in your data frame as the two variables.
# Print the coefficients obtained from linear regression and plot the straight line on the scatter plot.
# Do not use any inbuilt function for implementing linear regression.
# You need to formulate a linear system of equations and solve them using pseudo inverse.
# You can compare your result with that produced by the fit()
# function of LinearRegression model in sklearn.
df
# Choosing total_bill and tip as two variables.
# Let us again plot tip vs total_bill
plt.scatter(df['total_bill'],df['tip'], marker='+')
plt.xlabel("total bill")
plt.ylabel("tip")
# Print the coefficients obtained from linear regression and plot the straight line on the scatter plot.
# convert all stuff to float
predictorX = df['total_bill']
for datax in range (0,len(df['total_bill'])):
predictorX[datax]=float(df['total_bill'][datax])
# print (predictorX)
targetY = df['tip']
for datay in range (0,len(df['tip'])):
targetY[datay]=float(df['tip'][datay])
# print (predictorX)
# print (targetY)
X = predictorX
Y = targetY
"""---
---
This is using
# Using inverse
from numpy.linalg import inv
inv(X^T * X) * X^T * y (Inverse Method)
This is prone to the matrix which is non invertible.
"""
# Print the coefficients obtained from linear regression and plot the straight line on the scatter plot.
# convert all stuff to float
import numpy as np
predictorX = df['total_bill']
for datax in range (0,len(df['total_bill'])):
predictorX[datax]=float(df['total_bill'][datax])
# print (predictorX)
targetY = df['tip']
for datay in range (0,len(df['tip'])):
targetY[datay]=float(df['tip'][datay])
# print (predictorX)
# print (targetY)
X = predictorX
Y = targetY
# Using inverse
from numpy.linalg import inv
X = X.to_numpy(dtype=np.float).reshape((-1,1))
b = inv(X.T.dot(X)).dot(X.T).dot(Y) # Least squares inv(X^T * X) * X^T * y (Inverse Method)
# This is prone with the matrix being non invertible.
print(b)
ycap = X.dot(b)
plt.scatter(X, Y)
plt.plot(X, ycap, color='red')
plt.xlabel("total bill")
plt.ylabel("tip")
plt.xlim(8,30)
plt.ylim(0,5)
plt.show()
"""---
---
This is using
# Pseudo Inverse
from numpy.linalg import pinv
b = pinv(X).dot(Y) # Pseudo Inverse

"""
# Print the coefficients obtained from linear regression and plot the straight line on the scatter plot.
# convert all stuff to float
# import numpy as np
from numpy.linalg import pinv
predictorX = df['total_bill']
for datax in range (0,len(df['total_bill'])):
predictorX[datax]=float(df['total_bill'][datax])
# print (predictorX)
targetY = df['tip']
for datay in range (0,len(df['tip'])):
targetY[datay]=float(df['tip'][datay])
# print (predictorX)
# print (targetY)
X = predictorX
Y = targetY
# Using pseudo inverse
from numpy.linalg import inv
X = X.to_numpy(dtype=np.float).reshape((-1,1))
# b = inv(X.T.dot(X)).dot(X.T).dot(Y) # Least squares inv(X^T * X) * X^T * y (Inverse Method)
b = pinv(X).dot(Y) # Pseudo Inverse
print(b)
yhat = X.dot(b)
plt.scatter(X, Y)
plt.plot(X, yhat, color='red')
plt.xlabel("total bill")
plt.ylabel("tip")
plt.xlim(8,30)
plt.ylim(0,5)
plt.show()
"""## **Basic Approach for calculating Linear Regression without function.**"""
X = df['total_bill']
tab = pd.DataFrame()
tab['X']=X
tab['Y']=Y
tab
# for x in range (0,rows_count):
# percentage = (float(df.tip[x])/df.total_bill[x])*100
# df['tip/bill'][x]=float(percentage)
# print (percentage)
# plt.plot(X,Y)
tab['XY']=tab['X'] # Just to initializae with the same size
for each in range(0, tab.shape[0]):
product = float(tab.X[each]) * float(tab.Y[each])
tab['XY'][each]=float(product) # writing the actual values
print(product)
tab
tab['X2']=tab['X'] # Just to initializae with the same size
for each in range(0, tab.shape[0]):
square = float(tab.X[each]) * float(tab.X[each])
tab['X2'][each]=float(square) # writing the actual values
# print(square)
tab['Y2']=tab['X'] # Just to initializae with the same size
for each in range(0, tab.shape[0]):
square = float(tab.Y[each]) * float(tab.Y[each])
tab['Y2'][each]=float(square) # writing the actual values
# print(square)
tab
"""Line : Y=a+bX

"""
# now that we have X, Y, XY, X2, Y2 we need sum of each of them total sum so that we can further calculate coefficients
sigmaX = sum(tab['X'])
sigmaY = sum(tab['Y'])
sigmaXY = sum(tab['XY'])
sigmaX2 = sum(tab['X2'])
sigmaY2 = sum(tab['Y2'])
# Find a
num_a = (sigmaY*sigmaX2)-(sigmaX*sigmaXY)
denom_a = (5*(sigmaX2))-((sigmaX)**2)
a = num_a/denom_a
print (a)
# Find b
num_b = (5*sigmaXY)-(sigmaX*sigmaY)
denom_b = (5*sigmaX2)-(sigmaX**2)
b=num_b/denom_b
print(b)
"""EQUATION OF LINE: y= -0.09462 + 0.15640x"""
# y = a + b*X
# PLEASE NOTE THAT y is our preictor and Y is our dataframe for Y values
# PLEASE NOTE THAT y is our preictor and Y is our dataframe for Y values
# PLEASE NOTE THAT y is our preictor and Y is our dataframe for Y values
y= -0.09462 + 0.15640*X
plt.plot(X, y, color='#58b970', label='Regression Line')
plt.scatter(X,Y,color='#ef5423', label='Scatter Plot')
plt.xlabel('Billing amount')
plt.ylabel('Tip given')
plt.legend()
plt.show()
"""## Using Builtin Function"""
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
X = df['total_bill'].values.reshape(-1,1)
# reshaping (5,7) to (35,1) to solve in one dimension
reg = LinearRegression()
reg =reg.fit(X,y)
y_target = reg.predict(X)
y_target
plt.plot(X,y_target,color='#58b970', label='Regression Line')
plt.scatter(X,Y,color='#ef5423', label='Scatter Plot')
plt.xlabel('Billing amount')
plt.ylabel('Tip given')
plt.legend()
plt.show()
"""END"""