-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsteps.Rmd
1489 lines (1142 loc) · 45.2 KB
/
steps.Rmd
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: <br> Analysis Phases
date: "`r Sys.Date()`"
author: Ayaan Sharif
output:
rmdformats::downcute:
downcute_theme: "chaos"
self_contained: true
thumbnails: true
lightbox: true
gallery: false
highlight: tango
prompt: '$'
fig_width: 40 # set figure width to 6 inches
fig_height: 40 # set figure height to 4 inches
fig_caption: true
editor_options:
markdown:
wrap: 72
---
```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
knitr::opts_chunk$set(echo = TRUE, fig.width = 30, fig.height = 30)
```
# Report
### We will present the insights following the steps of the data analysis process:
🤔**Ask**: We identified the problem to be solved and how our insights
can guide business decisions.
💻**Prepare**: We gathered the relevant data, organized it, and verified
data integrity and credibility.
🧰**Process**: We selected tools to handle the data, cleaned it, and
ensured it was ready for analysis. We documented the cleaning process
and saved the cleaned data.
🧑🏻💻**Analyze**: We organized and formatted the data to answer our
questions, performed calculations, and identified trends and
relationships within the data.
📊**Share**: We created visualizations to share the most relevant
findings and related them to the original questions.
🎬**Act**: We presented the final conclusions and suggested an approach
to deal with the findings and next steps.
# 🤔**Ask**
## The business task
Analyze smart device usage data in order to gain insight into how people
are already using their smart devices. Then, using this information,
give high-level recommendations for how these trends can inform
Bellabeat marketing strategy.
**How current user trends can guide marketing strategy?**
## The stakeholders
- **Urška Sršen**: Bellabeat's cofounder and Chief Creative Officer
- **Sando Mur**: Mathematician and Bellabeat's cofounder; key member
of the Bellabeat executive team
- **Bellabeat marketing analytics team**: A team of data analysts
responsible for collecting, analyzing, and reporting data that helps
guide Bellabeat's marketing strategy.
# 💻**Prepare**
## Getting the data
To answer our main question (*How current user trends can guide
marketing strategy?*), we will use data from [**FitBit Fitness Tracker
Data**](https://www.kaggle.com/arashnic/fitbit) (CC0: Public Domain,
dataset made available through
[Mobius](https://www.kaggle.com/arashnic)). This Kaggle data set
contains personal fitness tracker from thirty three fitbit users. These
eligible Fitbit users consented to the submission of personal tracker
data, including minute-level output for physical activity, heart rate,
and sleep monitoring. It includes information about daily activity,
steps, and heart rate that can be used to explore users' habits.
A folder named`Fitabase Data 4.12.16-5.12.16` stores 18 `csv` files with
tracker data, including minute-level output for physical activity, heart
rate, and sleep monitoring.
To better read our files let's create a `path` variable to store the
folder path containing all `csv` files.
```{python fig.height = 3, fig.width = 5}
import os
path = './Fitabase Data 4.12.16-5.12.16'
## Get the full path of all the csv files.
full_path_list = [os.path.join(path,f) for\
f in os.listdir(path) if os.path.isfile(os.path.join(path,f)) ]
print('available files ' + str(len(full_path_list)))
full_path_list
```
Checking for integrity of our path list (should contain 18 file paths):
# 🧰**Process**
To clean and transform our data we will create a database using the
[sqlite3](https://docs.python.org/3/library/sqlite3.html) module as an
interface for [SQLite](https://www.sqlite.org/index.html) in **Python**.
By doing this we can use SQL queries to quickly interact with our data.
## Creating the database
First of all, we need to create the database. We do this by creating a
*connection* and starting a *cursor* in the desired database:
```{python}
import sqlite3 as sql
con = sql.connect("fitbit.db")
cur = con.cursor()
```
To easily insert all `csv` files as different tables in our database we
can create a helper function to return the name of the `csv` file
(without extension) to use as the table name.
```{python}
def get_table_name(full_path_list, i):
'''Returns name of csv file with no extension'''
return full_path_list[i].split('/')[-1].split('.')[0]
```
Having this we can use the `pandas` library to insert all files as
tables in our **fitbit.db** database. We do this by first reading the
file as a pandas dataframe object (using the `read_csv` method) then we
insert it into the database using the `to_sql` method with the proper
connection to the database.
```{python}
import pandas as pd
for i in range(0,18):
pd.read_csv(full_path_list[i]).to_sql(get_table_name(full_path_list, i), con, if_exists='append', index=False)
```
The `if_exists='append'` argument ensures we append the table to the
existing database.
We can do a quick sanity check and use `pandas` again to create a
dataframe object from a simple query to the newly populated database.
```{python}
import pandas as pd
# Simple query
df = pd.read_sql(f'SELECT * FROM {get_table_name(full_path_list, 0)}', con)
```
Now we can use the `head()` method to show the first 5 rows of data from
the first inserted table.
```{python }
df.head()
```
Finally, we can list all tables in our data base using a SQL query:
```{python}
# Listing all tables
cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cur.fetchall()
print(tables)
print(f'Total of {len(tables)} tables in database.')
```
## Checking for redundant information
We will work with the tables with daily logs of activitys. There are a
total of 5 tables with `daily` our `Day` in their names. Let's inspect
them for redundant information.
To take a closer look at the daily data, let's read table
`dailyActivity_merged` as a dataframe.
```{python}
dailyActivity_df = pd.read_sql(f'SELECT * FROM dailyActivity_merged', con)
dailyActivity_df.head()
```
We do the same for the `dailyIntensities_merged` table.
```{python}
dailyIntensities_df = pd.read_sql(f'SELECT * FROM dailyIntensities_merged', con)
dailyIntensities_df.head()
```
These tables appear to have shared columns. Let's first find out if they
have the same number of rows.
```{python}
print(f'dailyActivity_df length: {len(dailyActivity_df)}')
print(f'dailyIntensities_df length: {len(dailyIntensities_df)}')
```
The table `dailyIntensities_merged` seems to hold redundant information
already contained in `dailyActivity_merged`. The bellow query should
return empty if all 8 columns related to Distance and Minutes of
activity are redundant between these tables.
```{python}
query = """
SELECT VeryActiveDistance, ModeratelyActiveDistance, LightActiveDistance, SedentaryActiveDistance, VeryActiveMinutes,
FairlyActiveMinutes, LightlyActiveMinutes, SedentaryMinutes
FROM dailyActivity_merged
EXCEPT
SELECT VeryActiveDistance, ModeratelyActiveDistance, LightActiveDistance, SedentaryActiveDistance, VeryActiveMinutes,
FairlyActiveMinutes, LightlyActiveMinutes, SedentaryMinutes
FROM dailyIntensities_merged;
"""
cur.execute(query)
print(cur.fetchall())
```
The same ideia applies to tables `dailyActivity_merged` and
`dailySteps_merged`. Both have columns related to total steps taken by
date. In the former table this column is named `TotalSteps` and in the
latter, `StepTotal`. Again, we can execute a EXCEPT statement to check
if columns are redundant:
```{python}
query = """
SELECT TotalSteps from dailyActivity_merged
EXCEPT
SELECT StepTotal from dailySteps_merged;
"""
cur.execute(query)
print(cur.fetchall())
```
We repeat the same process for column `Calories` in
`dailyCalories_merged`:
```{python}
query = """
SELECT Calories from dailyActivity_merged
EXCEPT
SELECT Calories from dailyCalories_merged;
"""
cur.execute(query)
print(cur.fetchall())
```
So, tables `dailyIntensities_merged`, `dailySteps_merged` and
`dailyCalories_merged` will not be used further as all information on
them is contained in table `dailyActivity_merged`.
## Updating table to better read date information
We can update the ActivityDate column in `dailyActivity_merged` table to
match the standard **YYY-MM-DD** from SQLite.
- **RUN THIS ONLY ONCE AT IT CHANGES THE DATABASE**
```{python}
update_date = """
UPDATE dailyActivity_merged set ActivityDate =
SUBSTR(ActivityDate, -4)
|| "-" ||
CASE
WHEN LENGTH(
SUBSTR( -- picking month info
ActivityDate, 1, INSTR(ActivityDate, '/') - 1
)
) > 1 THEN
SUBSTR( -- picking month info
ActivityDate, 1, INSTR(ActivityDate, '/') - 1
)
ELSE '0' ||
SUBSTR( -- picking month info
ActivityDate, 1, INSTR(ActivityDate, '/') - 1
)
END
|| "-" ||
CASE
WHEN LENGTH(
SUBSTR( -- picking day info
SUBSTR(ActivityDate, INSTR(ActivityDate, '/') + 1), -- pick substring starting after first /
1, -- start new substring at first character of newly selected substring
INSTR(SUBSTR(ActivityDate, INSTR(ActivityDate, '/') + 1), '/') - 1 -- go all the way to next /
)
) > 1 THEN
SUBSTR( -- picking day info
SUBSTR(ActivityDate, INSTR(ActivityDate, '/') + 1), -- pick substring starting after first /
1, -- start new substring at first character of newly selected substring
INSTR(SUBSTR(ActivityDate, INSTR(ActivityDate, '/') + 1), '/') - 1 -- go all the way to next /
)
ELSE '0' ||
SUBSTR( -- picking day info
SUBSTR(ActivityDate, INSTR(ActivityDate, '/') + 1), -- pick substring starting after first /
1, -- start new substring at first character of newly selected substring
INSTR(SUBSTR(ActivityDate, INSTR(ActivityDate, '/') + 1), '/') - 1 -- go all the way to next /
)
END;
"""
cur.execute(update_date)
con.commit()
con.close()
```
To commit the changes we use the `commit()` method in our sql cursor. We
can close our connection to the database and check if tables were
updated.
## Data reagrding sleeping habbits
Beyond our `dailyActivity_merged` table, there is a separate table
holding sleep information. We can do a query to inspect the table.
```{python}
# Connect again to database
con = sql.connect("fitbit.db")
cur = con.cursor()
sleep_query = """
SELECT
*
FROM
sleepDay_merged;
"""
sleep_df = pd.read_sql(sleep_query, con)
sleep_df.head()
```
Updating the day to match SQLite format `YYYY-MM-DD` (**execute only
once**):
```{python}
update_date = """
UPDATE sleepDay_merged set SleepDay =
SUBSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), -4)
|| "-" ||
CASE
WHEN LENGTH(
SUBSTR( -- picking month info
SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), 1, INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') - 1
)
) > 1 THEN
SUBSTR( -- picking month info
SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), 1, INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') - 1
)
ELSE '0' ||
SUBSTR( -- picking month info
SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), 1, INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') - 1
)
END
|| "-" ||
CASE
WHEN LENGTH(
SUBSTR( -- picking day info
SUBSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') + 1), -- pick substring starting after first /
1, -- start new substring at first character of newly selected substring
INSTR(SUBSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') + 1), '/') - 1 -- go all the way to next /
)
) > 1 THEN
SUBSTR( -- picking day info
SUBSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') + 1), -- pick substring starting after first /
1, -- start new substring at first character of newly selected substring
INSTR(SUBSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') + 1), '/') - 1 -- go all the way to next /
)
ELSE '0' ||
SUBSTR( -- picking day info
SUBSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') + 1), -- pick substring starting after first /
1, -- start new substring at first character of newly selected substring
INSTR(SUBSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), INSTR(SUBSTR(SleepDay, 1, LENGTH(SleepDay) - 12), '/') + 1), '/') - 1 -- go all the way to next /
)
END;
"""
cur.execute(update_date)
con.commit()
con.close()
```
```{python}
con = sql.connect("fitbit.db")
cur = con.cursor()
```
Now we can check if the updates are correct:
- For the sleep table:
```{python}
sleep_query = """
SELECT *,
STRFTIME('%w',SleepDay) dow
FROM sleepDay_merged;
"""
sleep_df = pd.read_sql(sleep_query, con)
sleep_df.head()
```
The date now is in the proper `YYYY-MM-DD` format.
- For the activity table:
```{python}
dailyActivity_df = pd.read_sql('SELECT * FROM dailyActivity_merged', con)
dailyActivity_df.head()
```
Again, the dates are now in the proper format.
As was done in the sleep dataframe, we can use the function `STRFTIME()`
from SQLite to extract information on the day, month, year and day of
the week (*dow*) from the formated dates:
```{python}
full_info_activity = """
SELECT *,
STRFTIME('%d',ActivityDate) day,
STRFTIME('%m',ActivityDate) month,
STRFTIME('%Y',ActivityDate) year,
STRFTIME('%w',ActivityDate) dow
FROM dailyActivity_merged;
"""
full_dailyActivity_df = pd.read_sql(full_info_activity, con)
full_dailyActivity_df.head()
```
We saved the resulting query in a larger dataframe named
`full_dailyActivity_df`. The first 5 rows of this dataframe are as
follows.
# 🧑🏻💻**Analyze**
## Creating usefull dataframes
To ease our analyses further down the road, we can use our updated
tables to create helper dataframes.
First, a sanity check on our daily activity table:
```{python}
# Different users
cur.execute("SELECT COUNT(DISTINCT Id) FROM dailyActivity_merged;")
print('Different users: ', cur.fetchall()[0][0])
```
### Data on Average Calories, Steps and Distance by Id and by day of the week
```{python}
# Average Calories, Steps and Distance by Id and by day of the week
query = """
SELECT
Id,
STRFTIME('%w', ActivityDate) dow,
ROUND(AVG(Calories),2) AS avg_calories,
ROUND(AVG(TotalSteps),2) AS avg_steps,
ROUND(AVG(TotalDistance),2) AS avg_distance
FROM dailyActivity_merged
GROUP BY Id, STRFTIME('%w', ActivityDate);
"""
activity_dist = pd.read_sql(query, con)
activity_dist.head()
```
### "Boolean" column to check if date corresponds to weekend
```{python}
weekend_query = """
SELECT
Id,
ActivityDate,
SedentaryMinutes,
VeryActiveMinutes,
FairlyActiveMinutes,
LightlyActiveMinutes,
Calories,
TotalSteps,
TotalDistance,
CASE
WHEN STRFTIME('%w',ActivityDate) IN ('0','6')
THEN 1
ELSE 0
END weekend
FROM dailyActivity_merged;
"""
weekend_check = pd.read_sql(weekend_query, con)
weekend_check.head()
```
## NOTE: day of week 0-6 with Sunday==0
### Joining activity data with sleep data
```{python}
join_query = """
SELECT
A.Id,
A.ActivityDate,
A.SedentaryMinutes,
A.LightlyActiveMinutes,
S.TotalMinutesAsleep
FROM
dailyActivity_merged A
INNER JOIN sleepDay_merged S
ON
A.Id = S.Id AND
A.ActivityDate = S.SleepDay;
"""
activity_sleep_df = pd.read_sql(join_query, con)
activity_sleep_df.head()
```
## Initial exploratory visualizations
### How users spend their activity time?
In our `dailyActivity_df` there are four measures of how users spend
their time: \* `VeryActiveMinutes` that lead to `VeryActiveDistance` \*
`FairlyActiveMinutes` that lead to `ModeratelyActiveDistance` \*
`VeryLightlyActiveMinutes` that lead to `LightActiveDistance` \*
`SedentaryMinutes` that lead to `SedentaryActiveDistance`
We can plot each pair in a **scatter plot** (*Distance vs.* Minutes)
with a regression line to get estimate of the *speed* of users during
these activities. To ease the comparison, we'll plot all four graphs
with shared y-scale.
```{python}
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(rc={'figure.figsize': (10, 6)})
sns.set_style('whitegrid')
sns.set_palette('Set2')
fig, axes = plt.subplots(1, 4, figsize=(15, 5), sharey=True)
fig.suptitle('Distance per Minutes given kind of Activity')
sns.regplot(data = dailyActivity_df, x = 'VeryActiveMinutes', y = 'VeryActiveDistance', ax=axes[0])
axes[0].set_xlim([0,500])
sns.regplot(data = dailyActivity_df, x = 'FairlyActiveMinutes', y = 'ModeratelyActiveDistance', ax=axes[1])
axes[1].set_xlim([0,500])
sns.regplot(data = dailyActivity_df, x = 'LightlyActiveMinutes', y = 'LightActiveDistance', ax=axes[2])
axes[2].set_xlim([0,500])
sns.regplot(data = dailyActivity_df, x = 'SedentaryMinutes', y = 'SedentaryActiveDistance', ax=axes[3])
axes[3].set_xlim([0,500]);
plt.show()
```
**VeryActive** distances are *traveled* in shorter times (that is, they
have larger speeds represented by steeper regression lines).
*FairlyActiveMinutes* and *LightlyActiveMinutes* follow in speed. **It
would be interesting to know how this classification is done to actually
understand the difference between "Light" activities and "Moderate"
activities.**
### How does the number of steps taken in a day affect the amount of calories burned?
```{python}
sns.regplot(data = full_dailyActivity_df, x= 'TotalSteps', y ='Calories');
plt.show()
```
Once more, as expected the amount of calories burned in a day grows as
the user takes more steps. An inetersting fact is that the intercept of
the regression line represents the amount of burned calories in a day
with **no steps** taken. This is the amount of calories users are
burning in a very sedentary day. According to the [Healthline
site](https://www.healthline.com/health/calories-burned-sleeping#Determining-how-many-calories-you-burn),
this number corresponds to the *basal metabolic rate*:
> Your basal metabolic rate (BMR), on the other hand, represents the
> number of calories you individually burn a day at rest, or while
> you're sedentary. This includes sleeping and sitting.
This value can be calculated (again referring to
[Healthline](https://www.healthline.com/health/calories-burned-sleeping#Determining-how-many-calories-you-burn))
if we know the user's sex, weight, height and age. In their own
calculations, a 35-year-old man who weighs 175 pounds and is 5 feet 11
inches would have a *BMR* of 1,816 calories and a 35-year-old woman who
weighs 135 pounds and is 5 feet, 5 inches would have a *BMR* of 1,383
calories.
To compare these estimates with our data, we can get the intercept value
using the [scikit-learn](https://scikit-learn.org/stable/) package.
First of all, we'll do the necessary imports.
```{python}
import numpy as np
import sklearn
import sklearn.linear_model
# impor
from sklearn.linear_model import LinearRegression
```
Now we define our inputs (`X`) and outputs (`y`) for the regression.
This should be arrays so we take the `.values` from our dataframes:
```{python}
X = full_dailyActivity_df['TotalSteps'].values.reshape((-1, 1))
y = full_dailyActivity_df['Calories'].values
```
We call `.reshape()` on `X` because this array is required to be
two-dimensional, or to be more precise, to have one column and as many
rows as necessary. That's exactly what the argument (-1, 1) of
`.reshape()` specifies.
Next, we instantiate the model and fit it to the data
```{python}
model = LinearRegression()
model.fit(X, y)
```
With the fitted model, we can get the intercept value and the slope as
follows.
```{python}
print('intercept:', model.intercept_)
print('slope:', model.coef_)
```
With these, we would like to draw the regression line in the same figure
as the scatter plot for our data and see if the fit is similar to that
obtained with seaborn's regplot. To actually draw the line, we define a
`abline` function to use matplotlib to draw a line in 2D space from the
slope and intercept.
```{python}
def abline(slope, intercept):
"""Plot a line from slope and intercept"""
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = intercept + slope * x_vals
plt.plot(x_vals, y_vals, color= 'r', ls = '--')
plt.show()
sns.scatterplot(data = full_dailyActivity_df, x= 'TotalSteps', y ='Calories')
abline(model.coef_, model.intercept_);
plt.show()
```
That looks good! And, from our user data we see that the predicted *BMR*
is \~1665.74 (between those predicted for the 35-year-old woman and
man). We can further get information on the *BMR* of our users if we
filter only the data points with zero steps taken and get the statistics
on the Calories distribution. This can be done with the `describe`
method from `pandas` along with the mask for only `TotalSteps = 0`.
```{python}
full_dailyActivity_df[full_dailyActivity_df['TotalSteps']==0]['Calories'].describe()
full_dailyActivity_df[full_dailyActivity_df['Calories']==0]
```
We see that the minimum is 0 (seems like an outlier since 0 calories
burned in a day is impossible) and the maximum is 2664. We can also see
some quartiles along with mean and standard deviation.
Let's inspect the possible outliers:
**In SQL**: we can have this same output using SQL:
```{python}
query = """
SELECT *,
STRFTIME('%d',ActivityDate) day,
STRFTIME('%m',ActivityDate) month,
STRFTIME('%Y',ActivityDate) year,
STRFTIME('%w',ActivityDate) dow
FROM
dailyActivity_merged
WHERE
Calories = 0;
"""
outliers_calories = pd.read_sql(query, con)
outliers_calories
```
There are 4 rows with all zero values except for the `SedentaryMinutes`
column. In this column we see that users spent 1440 minutes of sedentary
activity in a single day. That's the whole day (!): 1440minutes divided
by 60minutes/hour = 24h. So, it seems the tracker may have been turned
off the entire day our experience some malfunction. We should get rid of
these data points in further analysis.
We redefine our `full_dailyActivity_df` dropping the outliers:
```{python}
full_info_activity = """
SELECT *,
STRFTIME('%d',ActivityDate) day,
STRFTIME('%m',ActivityDate) month,
STRFTIME('%Y',ActivityDate) year,
STRFTIME('%w',ActivityDate) dow
FROM
dailyActivity_merged
WHERE
Calories <> 0;
"""
full_dailyActivity_df = pd.read_sql(full_info_activity, con)
len(full_dailyActivity_df)
```
Our data frame is now 936 rows long, given we dropped the four outliers.
We can now see if these made a difference in the regression parameters.
To simplify our flow, let's turn the regression process into a single
function:
```{python}
def get_regression(full_dailyActivity_df, x ='TotalSteps', y = 'Calories'):
X = full_dailyActivity_df[x].values.reshape((-1, 1))
y = full_dailyActivity_df[y].values
model = LinearRegression()
model.fit(X, y)
print('intercept:', model.intercept_)
print('slope:', model.coef_)
sns.scatterplot(data = full_dailyActivity_df, x= x, y =y)
# plt.title('Calories burned by number of steps taken')
abline(model.coef_, model.intercept_);
plt.show()
return (model.intercept_, model.coef_)
get_regression(full_dailyActivity_df)
```
Wihtout the outliers, our fit has a slightly higher intercept of
\~1689.15 (correspondong to the *BMR*).
### Distribution according to type of activity
Excluding `SedentaryMinutes`, all users spend their daily time between
three types of activities: \* `VeryActiveMinutes`
*`FairlyActiveMinutes`* `VeryLightlyActiveMinutes`
We can use **histograms** to check how are this *minutes* distributed
accross users:
```{python}
fig, axes = plt.subplots(1, 3, figsize=(22, 5))
fig.suptitle('Distribution according to activity type')
sns.histplot(data = full_dailyActivity_df, x = 'VeryActiveMinutes', ax = axes[0]);
sns.histplot(data = full_dailyActivity_df, x = 'FairlyActiveMinutes', ax = axes[1]);
sns.histplot(data = full_dailyActivity_df, x = 'LightlyActiveMinutes', ax = axes[2]);
plt.show()
```
We can see from these plots that a great number of users (over 400)
spend very few minutes as Very or Fairly Active. The distribution of
`LightlyActiveMinutes` on the other hand is very symmetrical exluding
the very low minutes.
There is an issue here, however: it is not clear if all users were using
the tracker during the entire day in the analysed period. If a user logs
the whole day, then the sum
`VeryActiveMinutes + FairlyActiveMinutes + LightlyActiveMinutes + SedentaryMinutes`
should equal 1440 (the total number of minutes in a day).
Let's use SQL to select only those points where this condition is true:
```{python}
full_day_activity = """
SELECT *,
STRFTIME('%d',ActivityDate) day,
STRFTIME('%m',ActivityDate) month,
STRFTIME('%Y',ActivityDate) year,
STRFTIME('%w',ActivityDate) dow,
VeryActiveMinutes+FairlyActiveMinutes+LightlyActiveMinutes+SedentaryMinutes AS TotalMinutes
FROM
dailyActivity_merged
WHERE
Calories <> 0 AND
TotalMinutes = 1440;
"""
logged_day_df = pd.read_sql(full_day_activity, con)
logged_day_df.head()
print(f'There are {len(logged_day_df)} rows where users logged the whole day.')
```
We can, now, see the distributions in these rows:
```{python}
fig, axes = plt.subplots(1, 3, figsize=(22, 5))
fig.suptitle('Distribution according to activity type - Entire day logged')
sns.histplot(data = logged_day_df, x = 'VeryActiveMinutes', ax = axes[0]);
sns.histplot(data = logged_day_df, x = 'FairlyActiveMinutes', ax = axes[1]);
sns.histplot(data = logged_day_df, x = 'LightlyActiveMinutes', ax = axes[2]);
plt.show()
```
The behaviour here is similar. Let's see what happens to the days when
users did not logged the 24h:
```{python}
not_full_day = """
SELECT *,
STRFTIME('%d',ActivityDate) day,
STRFTIME('%m',ActivityDate) month,
STRFTIME('%Y',ActivityDate) year,
STRFTIME('%w',ActivityDate) dow,
VeryActiveMinutes+FairlyActiveMinutes+LightlyActiveMinutes+SedentaryMinutes AS TotalMinutes
FROM
dailyActivity_merged
WHERE
Calories <> 0 AND
TotalMinutes <> 1440;
"""
not_logged_day_df = pd.read_sql(not_full_day, con)
not_logged_day_df.head()
print(f'There are {len(not_logged_day_df)} rows where users logged parts of the day.')
fig, axes = plt.subplots(1, 3, figsize=(22, 5))
fig.suptitle('Distribution according to activity type - Partial day logged')
sns.histplot(data = not_logged_day_df, x = 'VeryActiveMinutes', ax = axes[0]);
sns.histplot(data = not_logged_day_df, x = 'FairlyActiveMinutes', ax = axes[1]);
sns.histplot(data = not_logged_day_df, x = 'LightlyActiveMinutes', ax = axes[2]);
plt.show()
```
Ok, now we see a difference! The `LightlyActiveMinutes` distribution is
very symmetric with no peak at very few minutes of activity. Users who
log the entire day may end up registering a lot of
`LightlyActiveMinutes` while those who log only a part of the day might
be registering only activities with higher demand.
Let's see the distribution of total logged time in this second group.
```{python}
sns.histplot(data = not_logged_day_df, x = 'TotalMinutes');
plt.show()
```
### Sleeping habits and week day distributions
We can use **histograms** again to see the distribution of sleeping time
for all users.
```{python}
sns.histplot(data = sleep_df, x = 'TotalMinutesAsleep');
plt.show()
```
According to the
[CDC](https://www.cdc.gov/sleep/about_sleep/how_much_sleep.html) an
adult should get **7 or more** hours of sleep per day. This corresponds
to 420 minutes. We can plot a line at this value to see how the users do
against this recommendation.
```{python}
sns.histplot(data = sleep_df, x = 'TotalMinutesAsleep')
plt.axvline(420, 0, 65, color='red');
plt.show()
```
The distribution is somewhat symmetric with 231 rows to the right of the
line (including the line) and 182 rows to the left.
We can further inspect the distribution of minutes asleep per week day:
```{python}
sns.boxplot(x="dow", y="TotalMinutesAsleep", data=sleep_df,
order = ['0','1','2','3','4','5','6']);
plt.show()
```
We can order this plot by the day of the week:
```{python}
sns.boxplot(x="dow", y="TotalMinutesAsleep", data=sleep_df,
order = ['0','1','2','3','4','5','6']);
plt.show()
```
There is no clear distinction between the days of the week. However we
can see that sunday has the largest median for `TotalMinutesAsleep` and
saturday appears to be the most spread oout distribution.
While we are looking at distributions across days of the week, we can
use our `activity_dist` dataframe to inspect the average values of
steps, calories and distances:
```{python}
fig, axes = plt.subplots(1, 3, figsize=(22, 5))
fig.suptitle('Distribution of average values across days of the week')
sns.boxplot(x="dow", y="avg_steps", data=activity_dist, ax=axes[0]);
sns.boxplot(x="dow", y="avg_calories", data=activity_dist, ax=axes[1]);
sns.boxplot(x="dow", y="avg_distance", data=activity_dist, ax=axes[2]);
plt.show()
```
### Distribution of calories and distance
```{python}
fig, axes = plt.subplots(1, 2, figsize=(22, 5))
fig.suptitle('Distribution of average values across days of the week')
sns.histplot(data=full_dailyActivity_df, x="Calories", ax = axes[0]);
sns.histplot(data=full_dailyActivity_df, x="TotalDistance", ax = axes[1]);
plt.show()
```
The distribution of burned calories is a bit skewed to the low calories
while the distance distribtion is higly skewed to lower distances.
### How does sedentary minutes change in weekends?
First of all, not considering the day of the week, let's take a look at
the distribtuion of `SedentaryMinutes`:
```{python}
sns.histplot(data = weekend_check, x = 'SedentaryMinutes');
plt.show()
```
To get a visual on how this distribution depends on weekends we can use
our `weekend_check` dataframe and use a facetplot to see two graphs (for
weekend being true or false). Besides this, I'll normalize the
distributions so we can compare both graphs (because there a lot fewer
weekends than week days - sadly...).
```{python}
g = sns.FacetGrid(data = weekend_check, col="weekend", height=6, aspect=.7)
g.map(sns.histplot, "SedentaryMinutes", kde=True, stat='density');
plt.show()
```
It seems there are two groups of users based on the distribution of
`SedentaryMinutes`. We can do a query to get the average
`SedentaryMinutes` per user:
```{python}
query = """
SELECT
Id,
AVG(SedentaryMinutes) AS AvgSedentaryMinutes
FROM
dailyActivity_merged
GROUP BY
Id
ORDER BY
AvgSedentaryMinutes DESC;
"""
avg_sed_minutes = pd.read_sql(query, con)
avg_sed_minutes
```