학습된 사이킷런 추정기 저장

import pickle
import os

dest = os.path.join('movieclassifier', 'pkl_objects')

if not os.path.exists(dest):
    os.makedirs(dest)

pickle.dump(stop, open(os.path.join(dest, 'stopwords.pkl'), 'wb'), protocol=4)
pickle.dump(clf, open(os.path.join(dest, 'classifier.pkl'), 'wb'), protocol=4)
from sklearn.feature_extraction.text import HashingVectorizer
import re
import os
import pickle

cur_dir = os.path.dirname(__file__)

stop = pickle.load(open(os.path.join(cur_dir, 'pkl_objects', 'stopwords.pkl'), 'rb'))

def tokenizer(text):
    text = re.sub('<[^>]*>', '', text)
    emoticons = re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', text.lower())
    text = re.sub('[\\W]+', ' ', text.lower()) + ' '.join(emoticons).replace('-', '')
    return [w for w in text.split() if w not in stop]

vect = HashingVectorizer(decode_error='ignore', n_features=2**21, preprocessor=None, tokenizer=tokenizer)
import pickle
import re
import os
from vectorizer import vect
import numpy as np

clf = pickle.load(open(os.path.join('pkl_objects', 'classifier.pkl'), 'rb'))

label = {0:'양성', 1:'음성'}

example = ['I love this movie']

X = vect.transform(example)

print('예측: %s\\n확률: %.2f%%' % (label[clf.predict(X)[0]], np.max(clf.predict_proba(X))*100))

데이터를 저장하기 위해 SQLite 데이터베이스 설정

import sqlite3

conn = sqlite3.connect('reviews.sqlite')

c = conn.cursor()

c.execute('DROP TABLE IF EXISTS review_db')

c.execute('CREATE TABLE review_db (review TEXT, sentiment INTEGER, date TEXT)')

example1 = 'I love this movie'
c.execute("INSERT INTO review_db (review, sentiment, date) VALUES (?, ?, DATETIME('now'))", (example1, 1))

example2 = 'I dislike this movie'
c.execute("INSERT INTO review_db (review, sentiment, date) VALUES (?, ?, DATETIME('now'))", (example2, 0))

c.execute("SELECT * FROM review_db WHERE date BETWEEN '2017-01-01 00:00:00' AND DATETIME('now')")

results = c.fetchall()

conn.commit()
conn.close()

print(results)

플라스크 웹 애플리케이션 개발

첫 번째 플라스크 애플리케이션

1st_flask_app_1/
  app.py
  templates/
    first_app.html
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('first_app.html')

if __name__ == '__main__':
    app.run()