Skip to content

Commit de09807

Browse files
python3 compatibility for web service example
1 parent 2a95c89 commit de09807

File tree

4 files changed

+38
-14
lines changed

4 files changed

+38
-14
lines changed

supervised_class/app.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
from __future__ import print_function, division
2+
from builtins import range, input
3+
# Note: you may need to update your version of future
4+
# sudo pip install -U future
5+
16
# https://deeplearningcourses.com/c/data-science-supervised-machine-learning-in-python
27
# https://www.udemy.com/data-science-supervised-machine-learning-in-python
38
import pickle
@@ -11,7 +16,7 @@
1116
if not os.path.exists('mymodel.pkl'):
1217
exit("Can't run without the model!")
1318

14-
with open('mymodel.pkl') as f:
19+
with open('mymodel.pkl', 'rb') as f:
1520
model = pickle.load(f)
1621

1722
class MainHandler(tornado.web.RequestHandler):
@@ -27,9 +32,9 @@ def post(self):
2732
# body: three=four&one=two
2833
# arguments: {'three': ['four'], 'one': ['two']}
2934
params = self.request.arguments
30-
x = np.array(map(float, params['input']))
35+
x = np.array(list(map(float, params['input'])))
3136
y = model.predict([x])[0]
32-
self.write(json.dumps({'prediction': y}))
37+
self.write(json.dumps({'prediction': y.item()}))
3338
self.finish()
3439

3540
if __name__ == "__main__":

supervised_class/app_caller.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
from __future__ import print_function, division
2+
from builtins import range, input
3+
# Note: you may need to update your version of future
4+
# sudo pip install -U future
5+
16
# https://deeplearningcourses.com/c/data-science-supervised-machine-learning-in-python
27
# https://www.udemy.com/data-science-supervised-machine-learning-in-python
38
import requests
@@ -13,13 +18,16 @@
1318
while True:
1419
i = np.random.choice(N)
1520
r = requests.post("http://localhost:8888/predict", data={'input': X[i]})
21+
print("RESPONSE:")
22+
print(r.content)
1623
j = r.json()
17-
print j
18-
print "target:", Y[i]
24+
print(j)
25+
print("target:", Y[i])
1926

2027
plt.imshow(X[i].reshape(28, 28), cmap='gray')
28+
plt.title("Target: %d, Prediction: %d" % (Y[i], j['prediction']))
2129
plt.show()
2230

23-
response = raw_input("Continue? (Y/n)\n")
31+
response = input("Continue? (Y/n)\n")
2432
if response in ('n', 'N'):
2533
break

supervised_class/app_trainer.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
from __future__ import print_function, division
2+
from builtins import range, input
3+
# Note: you may need to update your version of future
4+
# sudo pip install -U future
5+
16
# https://deeplearningcourses.com/c/data-science-supervised-machine-learning-in-python
27
# https://www.udemy.com/data-science-supervised-machine-learning-in-python
38
import pickle
@@ -7,15 +12,15 @@
712

813
if __name__ == '__main__':
914
X, Y = get_data()
10-
Ntrain = len(Y) / 4
15+
Ntrain = len(Y) // 4
1116
Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain]
1217

1318
model = RandomForestClassifier()
1419
model.fit(Xtrain, Ytrain)
1520

1621
# just in case you're curious
1722
Xtest, Ytest = X[Ntrain:], Y[Ntrain:]
18-
print "test accuracy:", model.score(Xtest, Ytest)
23+
print("test accuracy:", model.score(Xtest, Ytest))
1924

2025
with open('mymodel.pkl', 'wb') as f:
2126
pickle.dump(model, f)

supervised_class/util.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
# https://deeplearningcourses.com/c/data-science-supervised-machine-learning-in-python
22
# https://www.udemy.com/data-science-supervised-machine-learning-in-python
3+
from __future__ import print_function, division
4+
from builtins import range, input
5+
# Note: you may need to update your version of future
6+
# sudo pip install -U future
7+
8+
39
import numpy as np
410
import pandas as pd
511

612
def get_data(limit=None):
7-
print "Reading in and transforming data..."
13+
print("Reading in and transforming data...")
814
df = pd.read_csv('../large_files/train.csv')
915
data = df.as_matrix()
1016
np.random.shuffle(data)
@@ -30,14 +36,14 @@ def get_donut():
3036

3137
# distance from origin is radius + random normal
3238
# angle theta is uniformly distributed between (0, 2pi)
33-
R1 = np.random.randn(N/2) + R_inner
34-
theta = 2*np.pi*np.random.random(N/2)
39+
R1 = np.random.randn(N//2) + R_inner
40+
theta = 2*np.pi*np.random.random(N//2)
3541
X_inner = np.concatenate([[R1 * np.cos(theta)], [R1 * np.sin(theta)]]).T
3642

37-
R2 = np.random.randn(N/2) + R_outer
38-
theta = 2*np.pi*np.random.random(N/2)
43+
R2 = np.random.randn(N//2) + R_outer
44+
theta = 2*np.pi*np.random.random(N//2)
3945
X_outer = np.concatenate([[R2 * np.cos(theta)], [R2 * np.sin(theta)]]).T
4046

4147
X = np.concatenate([ X_inner, X_outer ])
42-
Y = np.array([0]*(N/2) + [1]*(N/2))
48+
Y = np.array([0]*(N//2) + [1]*(N//2))
4349
return X, Y

0 commit comments

Comments
 (0)