我的数据科学关于灾难响应管道的python代码显示了一个错误,我不知道原因。
我执行:
python app/runn.py ../models/classifier.pkl sqlite:///../data/DisasterResponse.db
并收到此错误:
sqlite3.OperationalError:无法打开数据库文件
我该如何解决?
我的代码:
import json
import plotly
import pandas as pd
import pickle
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 Bar
from sklearn.externals import joblib
from sqlalchemy import create_engine
app = Flask(__name__)
def tokenize(text):
'''
INPUT
text: Text to be processed
OUTPUT
Returns a processed text variable that was tokenized, lower cased, stripped, and lemmatized
'''
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
# load data
engine = create_engine('sqlite:///../data/DisasterResponse.db')
df = pd.read_sql_table('DisasterMessage', engine)
print(df.head())
# load model
model = pickle.load(open("../models/classifier.pkl", 'rb'))
print(model)
X = df.message.values
y = df.iloc[:,5:]
keys = list(y.columns)
my_dict = {key: None for key in keys}
for key, value in my_dict.items():
my_dict[key] = ((y[key] == 1)).sum()
# index webpage displays cool visuals and receives user input text for model
@app.route('/')
@app.route('/index')
def index():
# extract data needed for visuals
genre_counts = df.groupby('genre').count()['message']
genre_names = list(genre_counts.index)
### data for visualizing category counts.
label_sums = df.iloc[:, 4:].sum()
label_names = list(label_sums.index)
# create visuals
graphs = [
{
'data': [
Bar(
x=genre_names,
y=genre_counts
)
],
'layout': {
'title': 'Distribution of Message Genres',
'yaxis': {
'title': "Count"
},
'xaxis': {
'title': "Genre"
}
}
},
{
'data': [
Bar(
x=label_names,
y=label_sums,
)
],
'layout': {
'title': 'Distribution of categories',
'yaxis': {
'title': "Count"
},
'xaxis': {
},
}
}
]
# 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():
# 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():
app.run(host='0.0.0.0', port=3001, debug=True)
if __name__ == '__main__':
main()
这是堆栈跟踪:
Traceback (most recent call last):
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 2228, in _wrap_pool_connect
return fn()
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 365, in unique_connection
return _ConnectionFairy._checkout(self)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 822, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 554, in checkout
rec = pool._do_get()
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 1346, in _do_get
return self._create_connection()
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 370, in _create_connection
return _ConnectionRecord(self)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 499, in __init__
self.__connect(first_connect_check=True)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 701, in __connect
connection = pool._invoke_creator(self)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
return dialect.connect(*cargs, **cparams)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 437, in connect
return self.dbapi.connect(*cargs, **cparams)
sqlite3.OperationalError: unable to open database file
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "app/runn.py", line 37, in <module>
df = pd.read_sql_table('DisasterMessage', engine)
File "/opt/conda/lib/python3.6/site-packages/pandas/io/sql.py", line 240, in read_sql_table
meta.reflect(only=[table_name], views=True)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/sql/schema.py", line 4097, in reflect
with bind.connect() as conn:
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 2171, in connect
return self._connection_cls(self, **kwargs)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 103, in __init__
else engine.raw_connection()
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 2259, in raw_connection
self.pool.unique_connection, _connection
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 2232, in _wrap_pool_connect
e, dialect, self
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1528, in _handle_dbapi_exception_noconnection
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 296, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 276, in reraise
raise value.with_traceback(tb)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 2228, in _wrap_pool_connect
return fn()
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 365, in unique_connection
return _ConnectionFairy._checkout(self)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 822, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 554, in checkout
rec = pool._do_get()
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 1346, in _do_get
return self._create_connection()
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 370, in _create_connection
return _ConnectionRecord(self)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 499, in __init__
self.__connect(first_connect_check=True)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/pool.py", line 701, in __connect
connection = pool._invoke_creator(self)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
return dialect.connect(*cargs, **cparams)
File "/opt/conda/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 437, in connect
return self.dbapi.connect(*cargs, **cparams)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file (Background on this error at: http://sqlalche.me/e/e3q8)