-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
166 lines (128 loc) · 4.21 KB
/
run.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
import argparse
import json
import plotly
import pandas as pd
from sqlalchemy import create_engine
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import *
from sklearn.externals import joblib
from train_classifier import *
app = Flask(__name__)
def tokenize(text):
"""
clean and tokenize the text
"""
tokens = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for tok in tokens:
clean_tok = lemmatizer.lemmatize(tok).lower().strip()
clean_tokens.append(clean_tok)
return clean_tokens
#grab the table_name in the argument
parser=argparse.ArgumentParser()
parser.add_argument("--table_name", default="message_table", type=str)
args = parser.parse_args()
# load data
engine = create_engine('sqlite:///message_classification.db')
df = pd.read_sql_table(args.table_name, engine)
# load model
model = joblib.load("model")
# index webpage displays cool visuals and receives user input text for model
@app.route('/')
@app.route('/index')
def index():
"""
Create visualizations with plotly and render the website with the plots
"""
# extract data needed for visuals
genre_counts = df.groupby('genre').count()['message']
genre_names = list(genre_counts.index)
# create visuals
graphs = [
#bar chart of the genres
{
'data': [
Bar(
x=genre_names,
y=genre_counts
)
],
'layout': {
'title': 'Distribution of Message Genres',
'yaxis': {
'title': "Count"
},
'xaxis': {
'title': "Genre"
}
}
},
#Bar chart of numbers of messages in each category
{
'data': [
Bar(
x=list(df.iloc[:, 4:].astype("int").sum().sort_values(ascending=False).index),
y=list(df.iloc[:, 4:].astype("int").sum().sort_values(ascending=False).values)
)
],
'layout': {
'title': 'Numbers of messages in each category',
'yaxis': {
'title': "Count"
},
'xaxis': {
'title': "Category"
}
}
},
#Heatmap chart of the correlation matrix of the categories
{
'data': [
Heatmap(
x=list(df.drop('child_alone',axis=1).iloc[:, 7:].columns),
y=list(df.drop('child_alone',axis=1).iloc[:, 7:].columns),
z=np.array(df.drop('child_alone',axis=1).iloc[:, 7:].astype("int").corr().replace(1, np.nan)),
colorscale = 'Viridis'
)
],
'layout': {
'title': 'Correlation matrix of the categories',
'width':1000,
'height':1000
}
}
]
# encode plotly graphs in JSON
ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
# render web page with plotly graphs
return render_template('master.html', ids=ids, graphJSON=graphJSON)
# web page that handles user query and displays model results
@app.route('/go')
def go():
"""
make prediction with the `query` the user inputs;
render the '/go' page with the classfication result
"""
# save user input in query
query = request.args.get('query', '')
# use model to predict classification for query
classification_labels = model.predict([query])[0]
classification_results = dict(zip(df.columns[4:], classification_labels))
# This will render the go.html Please see that file.
return render_template(
'go.html',
query=query,
classification_result=classification_results
)
def main():
"""
the app will be run on http://0.0.0.0:3002/
"""
app.run(host='0.0.0.0', port=3002, debug=True)
if __name__ == '__main__':
main()