안경잡이개발자

728x90
반응형

다변인 선형회귀를 활용한 배추 가격 예측 AI 개발하기 7강 - 플라스크와 텐서플로우 연동하기

나동빈


  이번 시간에는 플라스크 웹 서버에서 텐서플로우(Tensorflow) 기반의 학습 모델을 이용해 '배추 가격을 예측'하는 서버 기능을 삽입해보도록 하겠습니다. 지난 시간에 이미 학습 모델을 파일 형태로 저장하는 방법에 대해서 알아보았으므로 수월하게 따라올 수 있을 겁니다.


※ 웹 클라이언트 소스코드 변경하기 ※


  가장 먼저 사용자로부터 '평균 온도', '최소 온도', '최대 온도', '강수량'을 입력 받을 수 있도록 웹 클라이언트 HTML 소스코드를 변경합니다. <form> 태그를 이용하면 플라스크 웹 서버에서 처리할 수 있도록 손쉽게 파라미터를 전달할 수 있습니다.


      <section>

        <h3 class="h3 text-center mb-5">배추 가격 예측하기</h3>

        <div class="row wow fadeIn">

          <div class="col-lg-6 col-md-12 px-4">

            <form action="/" method="post">

              <div class="form-group">

                <label for="formGroupExampleInput">평균 온도</label>

                <input type="text" name="avg_temp" class="form-control" placeholder="평균 온도를 입력하세요.">

              </div>

              <div class="form-group">

                <label for="formGroupExampleInput">최소 온도</label>

                <input type="text" name="min_temp" class="form-control" placeholder="최소 온도를 입력하세요.">

              </div>

              <div class="form-group">

                <label for="formGroupExampleInput">최대 온도</label>

                <input type="text" name="max_temp" class="form-control" placeholder="최대 온도를 입력하세요.">

              </div>

              <div class="form-group">

                <label for="formGroupExampleInput">강수량</label>

                <input type="text" name="rain_fall" class="form-control" placeholder="강수량을 입력하세요.">

              </div>

              <button type="submit" class="btn btn-primary btn-md pull-right">예측하기</button>

            </form>

          </div>

          <div class="col-lg-6 col-md-12">

            {% if price %}

              <h5 class="text-center mt-3">결과: {{ price }}</h5>

            {% endif %}

          </div>

        </div>

      </section>



  참고로 저는 아톰(Atom) 에디터를 이용하고 있습니다.



  이제 위와 같이 플라스크 웹 서버의 루트 폴더에 'model' 폴더를 생성하여 학습 모델이 담길 수 있도록 합시다.



  이제 사용자로부터 배추 가격 예측 요청(Request)이 들어오면 그 결과를 반환하도록 서버 소스코드를 수정합니다.


※ 플라스크 서버 소스코드 ※


# -*- coding: utf-8 -*-

from flask import Flask, render_template, request


import datetime

import tensorflow as tf

import numpy as np


app = Flask(__name__)


# 플레이스 홀더를 설정합니다.

X = tf.placeholder(tf.float32, shape=[None, 4])

Y = tf.placeholder(tf.float32, shape=[None, 1])


W = tf.Variable(tf.random_normal([4, 1]), name="weight")

b = tf.Variable(tf.random_normal([1]), name="bias")


# 가설을 설정합니다.

hypothesis = tf.matmul(X, W) + b


# 저장된 모델을 불러오는 객체를 선언합니다.

saver = tf.train.Saver()

model = tf.global_variables_initializer()


# 세션 객체를 생성합니다.

sess = tf.Session()

sess.run(model)


# 저장된 모델을 세션에 적용합니다.

save_path = "./model/saved.cpkt"

saver.restore(sess, save_path)


@app.route("/", methods=['GET', 'POST'])

def index():

    if request.method == 'GET':

        return render_template('index.html')

    if request.method == 'POST':

        # 파라미터를 전달 받습니다.

        avg_temp = float(request.form['avg_temp'])

        min_temp = float(request.form['min_temp'])

        max_temp = float(request.form['max_temp'])

        rain_fall = float(request.form['rain_fall'])


        # 배추 가격 변수를 선언합니다.

        price = 0


        # 입력된 파라미터를 배열 형태로 준비합니다.

        data = ((avg_temp, min_temp, max_temp, rain_fall), (0, 0, 0, 0))

        arr = np.array(data, dtype=np.float32)


        # 입력 값을 토대로 예측 값을 찾아냅니다.

        x_data = arr[0:4]

        dict = sess.run(hypothesis, feed_dict={X: x_data})

            

        # 결과 배추 가격을 저장합니다.

        price = dict[0]


        return render_template('index.html', price=price)


if __name__ == '__main__':

   app.run(debug = True)



  서버 소스코드를 수정한 이후에는 다시 서버를 재구동하시면 됩니다. 다만 혹시 위와 같이 'UTF-8' 인코딩 관련 오류가 발생한다면 다음과 같이 서버 소스코드 파일을 'UTF-8' 인코딩으로 저장해주도록 하세요.



※ 테스트 하기 ※


  이제 완성된 프로젝트를 테스트 하기 위해 먼저 서버를 구동시킵니다.



  웹 사이트를 새로고침 해서 임의의 온도 및 강수량 정보를 넣어 보겠습니다.



  예측 결과는 다음과 같이 정상적으로 잘 출력됩니다.



  이상으로 미니 프로젝트를 마치도록 하겠습니다.


728x90
반응형