-
Notifications
You must be signed in to change notification settings - Fork 0
/
fitbit.py
171 lines (147 loc) · 4.8 KB
/
fitbit.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
# -*- coding: utf-8 -*-
"""fitbit.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1vGtVqbRHl__kANCP85WzzmYh32XNCvtG
"""
import tensorflow as tf
from tensorflow import keras
import json
import csv
import math
import numpy as np
import matplotlib
from matplotlib import pyplot as plt,dates
import fitbit
import pandas as pd
import datetime
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import functools
print(keras.__version__)
tf.__version__
timeInBed = []
readiness = []
for i in range(1, 17):
number = 'Users/bhoan/Desktop/Fitbit/p'
if (i < 10):
number = number + '0'
csvv = number + str(i) + '/pmsys/wellness.csv'
number = number + str(i) + '/fitbit/sleep.json'
f = open(number)
data = json.load(f)
data2 = []
dates2 = []
with open(csvv, 'r') as csvfile:
csvreader = csv.reader(csvfile)
fields = next(csvreader)
for row in csvreader:
data2.append(row[1])
dates2.append(row[0])
converted_date2 = matplotlib.dates.datestr2num(dates2)
dates = []
for point in data:
dates.append(point['dateOfSleep'])
actualDates = []
converted_date = matplotlib.dates.datestr2num(dates)
for i in range(len(data)):
for j in range(len(data2)):
if converted_date[i] == math.floor(converted_date2[j]):
if converted_date[i] not in actualDates:
actualDates.append(converted_date[i])
timeInBed.append(data[i]['timeInBed']/60.0)
readiness.append(ord(data2[j]) - ord('0'))
label_encoder = LabelEncoder()
onehot_encoder = OneHotEncoder(sparse=False)
def encode_labels(labels,fit=True):
if(fit): label_encoder.fit(labels)
#print(label_encoder.classes_)
#rint(label_encoder.classes_.shape)
integer_encoded = label_encoder.transform(labels)
integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
if(fit): onehot_encoder.fit(integer_encoded)
onehot_encoded = onehot_encoder.transform(integer_encoded)
return onehot_encoded
X_val = np.array(timeInBed)
X_val = X_val.reshape(1490, 1, 1)
Y_val = encode_labels(np.array(readiness))
Y_val = Y_val.reshape(1490, 1, 5)
print(X_val.shape)
print(Y_val.shape)
seq = [
tf.keras.layers.Dense(5, activation='softmax')
]
keras_model = tf.keras.Sequential(seq)
#Top5 & Top3 Accuracy to check
top5_acc = functools.partial(keras.metrics.top_k_categorical_accuracy, k=5)
top5_acc.__name__ = 'top5_acc'
top3_acc = functools.partial(keras.metrics.top_k_categorical_accuracy, k=3)
top3_acc.__name__ = 'top3_acc'
keras_model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
history = keras_model.fit(X_val, Y_val, epochs = 10, batch_size = 1)
print(keras_model.summary())
res = keras_model.predict([[[5]]])
res
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model train vs validation loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train'])
keras_model.save( "Users/bhoan/model.h5" )
!pip install tensorflowjs
import tensorflowjs
tensorflowjs.converters.save_keras_model(keras_model, 'Users/bhoan/')
res = keras_model.predict([9])
summ = 0
for i in range(5):
summ = summ + res[0][i]*(i+1)
print(summ)
f = open('p06/fitbit/sleep.json')
g = open('p06/pmsys/wellness.csv')
data = json.load(f)
data2 = []
dates2 = []
with open('wellness.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
fields = next(csvreader)
for row in csvreader:
data2.append(row[1])
dates2.append(row[0])
converted_date2 = matplotlib.dates.datestr2num(dates2)
print(len(data))
print(len(data2))
dates = []
timeInBed = []
readiness = []
actualDates = []
for point in data:
dates.append(point['dateOfSleep'])
converted_date = matplotlib.dates.datestr2num(dates)
for i in range(len(data)):
for j in range(len(data2)):
if converted_date[i] == math.floor(converted_date2[j]):
if converted_date[i] not in actualDates and ord(data2[j]) - ord('3') < 0:
actualDates.append(converted_date[i])
timeInBed.append(data[i]['timeInBed']/60.0)
readiness.append(ord(data2[j]) - ord('3'))
avgFatigue = sum(readiness)/len(actualDates)
avgSleep = sum(timeInBed)/len(actualDates)
print(avgFatigue)
print(avgSleep)
#readiness = readiness[1:]
#readiness.append(0)
x_axis = actualDates
y_axis = readiness
y_axis2 = timeInBed
plt.figure(figsize=(20,10))
plt.ylim(-5, 10)
plt.plot_date(x_axis, y_axis,'.')
plt.plot_date(x_axis, y_axis2,'.')