Skip to content

Commit 1e00d22

Browse files
committed
correct prediction
1 parent a576570 commit 1e00d22

File tree

11 files changed

+80
-148
lines changed

11 files changed

+80
-148
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ wheels/
3232

3333
Thumbs.db
3434

35+
keras_image_classifier_web/uploads
36+
3537
# PyInstaller
3638
# Usually these files are written by a python script from a template
3739
# before PyInstaller builds the exe, so as to inject date/other infos into it.
Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,32 @@
11
from keras.models import model_from_json
2+
from keras.preprocessing.image import load_img, img_to_array
3+
from PIL import Image
4+
import numpy as np
25

3-
model = model_from_json('models/cnn_bi_classifier_architecture.json')
6+
json = open('models/cnn_bi_classifier_architecture.json', 'r').read()
7+
8+
model = model_from_json(json)
49
model.load_weights('models/cnn_bi_classifier_weights.h5')
510

611
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
712

8-
model.predict_classes()
13+
def predict(filename, label):
14+
img = Image.open(filename)
15+
img = img.resize((150, 150), Image.ANTIALIAS)
16+
17+
input = np.asarray(img)
18+
input = np.expand_dims(input, axis=0)
19+
20+
print(input.shape)
21+
22+
output = model.predict(input)
23+
24+
print('This is a ' + label)
25+
print('Probability that it is a dog ' + str(output[0][0]))
26+
27+
28+
for i in range(100):
29+
predict('bi_classifier_data/training/cat/cat.' + str(i) + '.jpg', 'cat')
30+
predict('bi_classifier_data/training/dog/dog.' + str(i) + '.jpg', 'dog')
31+
32+
Lines changed: 28 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -1,115 +1,46 @@
11
import os
2+
from keras.models import model_from_json
23
import sqlite3
34
import uuid
45

56
from flask import Flask, request, session, g, redirect, url_for, abort, \
6-
render_template, flash
7+
render_template, flash
78
from flask import send_from_directory
89
from werkzeug.utils import secure_filename
910

1011
UPLOAD_FOLDER = '../uploads'
1112
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
1213

13-
app = Flask(__name__) # create the application instance :)
14-
app.config.from_object(__name__) # load config from this file , flaskr.py
14+
app = Flask(__name__) # create the application instance :)
15+
app.config.from_object(__name__) # load config from this file , flaskr.py
1516

1617
# Load default config and override config from an environment variable
17-
app.config.update(dict(
18-
DATABASE=os.path.join(app.root_path, 'keras_image_projects.db'),
19-
SECRET_KEY='development-key',
20-
USERNAME='root',
21-
PASSWORD='chen0469'
22-
))
2318
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
2419
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
2520

21+
model = model_from_json(open(os.path.join('models', '/cnn_bi_classifier_architecture.json')).read())
22+
model.load_weights(os.path.join('models', '/cnn_bi_classifier_weights.h5'))
2623

27-
def connect_db():
28-
"""Connects to the specific database."""
29-
rv = sqlite3.connect(app.config['DATABASE'])
30-
rv.row_factory = sqlite3.Row
31-
return rv
32-
33-
34-
def get_db():
35-
"""Opens a new database connection if there is none yet for the
36-
current application context.
37-
"""
38-
if not hasattr(g, 'sqlite_db'):
39-
g.sqlite_db = connect_db()
40-
return g.sqlite_db
41-
42-
43-
@app.teardown_appcontext
44-
def close_db(error):
45-
"""Closes the database again at the end of the request."""
46-
if hasattr(g, 'sqlite_db'):
47-
g.sqlite_db.close()
48-
49-
50-
def init_db():
51-
db = get_db()
52-
with app.open_resource('schema.sql', mode='r') as f:
53-
db.cursor().executescript(f.read())
54-
db.commit()
55-
56-
57-
@app.cli.command('initdb')
58-
def initdb_command():
59-
"""Initializes the database."""
60-
init_db()
61-
print('Initialized the database.')
24+
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
6225

6326

6427
@app.route('/')
65-
def show_entries():
66-
db = get_db()
67-
cur = db.execute('select id, description, name from projects order by id desc')
68-
entries = cur.fetchall()
69-
return render_template('show_entries.html', entries=entries)
70-
71-
72-
@app.route('/add', methods=['POST'])
73-
def add_entry():
74-
if not session.get('logged_in'):
75-
abort(401)
76-
db = get_db()
77-
db.execute('insert into projects (name, description) values (?, ?)',
78-
[request.form['name'], request.form['description'], str(uuid.uuid4())])
79-
db.commit()
80-
flash('New entry was successfully posted')
81-
return redirect(url_for('show_entries'))
82-
83-
84-
@app.route('/login', methods=['GET', 'POST'])
85-
def login():
86-
error = None
87-
if request.method == 'POST':
88-
if request.form['username'] != app.config['USERNAME']:
89-
error = 'Invalid username'
90-
elif request.form['password'] != app.config['PASSWORD']:
91-
error = 'Invalid password'
92-
else:
93-
session['logged_in'] = True
94-
flash('You were logged in')
95-
return redirect(url_for('show_entries'))
96-
return render_template('login.html', error=error)
97-
98-
99-
@app.route('/logout')
100-
def logout():
101-
session.pop('logged_in', None)
102-
flash('You were logged out')
103-
return redirect(url_for('show_entries'))
28+
def classifiers():
29+
return render_template('classifiers.html')
10430

10531

10632
def allowed_file(filename):
10733
return '.' in filename and \
10834
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
10935

11036

111-
@app.route('/projects/<token>/images', methods=['GET', 'POST'])
112-
def upload_file(token):
37+
@app.route('/about', methods=['GET'])
38+
def about():
39+
return 'about us'
40+
41+
42+
@app.route('/cats_vs_dogs', methods=['GET', 'POST'])
43+
def cats_vs_dogs():
11344
if request.method == 'POST':
11445
# check if the post request has the file part
11546
if 'file' not in request.files:
@@ -124,29 +55,22 @@ def upload_file(token):
12455
if file and allowed_file(file.filename):
12556
filename = secure_filename(file.filename)
12657
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
127-
return redirect(url_for('uploaded_file',
58+
return redirect(url_for('cats_vs_dogs_result',
12859
filename=filename))
129-
return '''
130-
<!doctype html>
131-
<title>Upload new File</title>
132-
<h1>Upload new File</h1>
133-
<form method=post enctype=multipart/form-bi_classifier_data>
134-
<p><input type=file name=file>
135-
<input type=submit value=Upload>
136-
</form>
137-
'''
138-
139-
140-
@app.route('/uploads/<filename>')
141-
def uploaded_file(filename):
60+
return render_template('cats_vs_dogs.html')
61+
62+
63+
@app.route('/cats_vs_dogs_result/<filename>')
64+
def cats_vs_dogs_result(filename):
65+
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
66+
return render_template('cats_vs_dogs_result.html', filename=filename)
67+
68+
69+
@app.route('/images/<filename>')
70+
def get_image(filename):
14271
return send_from_directory(app.config['UPLOAD_FOLDER'],
14372
filename)
14473

145-
@app.before_first_request
146-
def startup():
147-
init_db()
148-
14974

15075
if __name__ == '__main__':
15176
app.run(debug=True)
152-
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"class_name": "Sequential", "config": [{"class_name": "Conv2D", "config": {"name": "conv2d_1", "trainable": true, "batch_input_shape": [null, 150, 150, 3], "dtype": "float32", "filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_1", "trainable": true, "activation": "relu"}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_1", "trainable": true, "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_2", "trainable": true, "activation": "relu"}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_2", "trainable": true, "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_3", "trainable": true, "filters": 64, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_3", "trainable": true, "activation": "relu"}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_3", "trainable": true, "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}}, {"class_name": "Flatten", "config": {"name": "flatten_1", "trainable": true}}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "units": 64, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Dropout", "config": {"name": "dropout_1", "trainable": true, "rate": 0.5}}, {"class_name": "Dense", "config": {"name": "dense_2", "trainable": true, "units": 1, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_4", "trainable": true, "activation": "sigmoid"}}], "keras_version": "2.0.5", "backend": "tensorflow"}
4.65 MB
Binary file not shown.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{% extends "layout.html" %}
2+
{% block body %}
3+
<form method=post enctype=multipart/form-data>
4+
<p><input type=file name=file>
5+
<input type=submit value=Upload>
6+
</form>
7+
{% endblock %}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{% extends "layout.html" %}
2+
{% block body %}
3+
<form method=post enctype=multipart/form-data>
4+
<p><input type=file name=file>
5+
<input type=submit value=Upload>
6+
</form>
7+
{% endblock %}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{% extends "layout.html" %}
2+
{% block body %}
3+
<ul class=entries>
4+
<li><a href="{{ url_for('cats_vs_dogs') }}">Cats vs Dogs</a></li>
5+
</ul>
6+
{% endblock %}

keras_image_classifier_web/templates/layout.html

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,10 @@
11
<!doctype html>
2-
<title>Keras Image Classifier Web</title>
2+
<title>Flask Slingshot</title>
33
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
44
<div class=page>
5-
<h1>Keras Image Classifier</h1>
5+
<h1><a href="/">Image Classifier</a></h1>
66
<div class=metanav>
7-
{% if not session.logged_in %}
8-
<a href="{{ url_for('login') }}">log in</a>
9-
{% else %}
10-
<a href="{{ url_for('logout') }}">log out</a>
11-
{% endif %}
7+
<a href="{{ url_for('about') }}">About</a>
128
</div>
139
{% for message in get_flashed_messages() %}
1410
<div class=flash>{{ message }}</div>

keras_image_classifier_web/templates/login.html

Lines changed: 0 additions & 14 deletions
This file was deleted.

0 commit comments

Comments
 (0)