본문 바로가기

HealRo Project

자전거 이용률 예측 인공지능 개발

반응형

사용 데이터 셋

kaggle : Bike Sharing Demand 

 

Bike Sharing Demand

Forecast use of a city bikeshare system

www.kaggle.com

html

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>나는</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>

<div class ="container">
	<div ><h3>자전거 이용률 예측</h3> </div>
	<div class ="mt-4">
		<div class ="col-8">
			<label for = year>년도</label>
			<input class ="form-control" type ="number" id ="year">
			<label for = hour>시간대</label>
			<input class ="form-control" type ="number" id ="hour">
			<label for = windspeed >바람 속도</label>
			<input class ="form-control" type ="number" id ="windspeed">
			<label for = humidity>습도</label>
			<input class ="form-control" type ="number" id ="humidity">
			<label for = atemp>체감 온도</label>
			<input class ="form-control" type ="number" id ="atemp">
			<label for = temp>온도</label>
			<input class ="form-control" type ="number" id ="temp">
			<label for = weather>날씨 (1.맑음 2.먼지 3.약한 비,눈  4.강한 비)</label>
			<input class ="form-control" type ="number" id ="weather">
			<label for = workingday>근무일 (1.근무 2.휴일)</label>
			<input class ="form-control" type ="number" id ="workingday">
		</div>
	</div> 
	<div class ="row mb-4">
		<div class ="col-8"></div>
		<div class ="col-4">
			<button class ="btn btn-success btn-bg" id="btn"  >machine learning</button>
		</div>
	</div>
</div>



</body>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="js/socket.js"></script>
</html>

 

JS

$( document ).ready(function() {
    console.log( "ready!" );
});

$(function(){ 
	$("#btn").click(function(){ 
		
		var year = $('#year').val();
		var hour = $('#hour').val();
		var windspeed = $('#windspeed').val();
		var humidity = $('#humidity').val();
		var atemp = $('#atemp').val();
		var temp = $('#temp').val();
		var weather = $('#weather').val();
		var workingday = $('#workingday').val();
		
		var data = {
				year : year,
				hour : hour,
				windspeed : windspeed,
				humidity : humidity,
				atemp : atemp,
				temp : temp,
				weather : weather,
				workingday : workingday,
		}
		
		

		
		JSON.stringify(data);
		console.log(data);
		$.ajax({
	        type: "GET",
	        dataType: "jsonp",
	        data : data,
	        url: "http://localhost:5000/",
	        success: function (data) {
	        	
	        	alert('자전거 이용률 :'+data+'% 입니다.')
	            console.log('data는'+data);
	        }
	    });
		}); 
	});

 

 

python

from functools import wraps
import json

from flask import Flask
from flask_jsonpify import jsonpify
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from flask_restful import reqparse
import pandas as pd
import numpy as np


app = Flask(__name__)


@app.route('/', methods=['GET'])
def test():
    train = pd.read_csv("./train.csv")
    train["datetime"] = train["datetime"].astype("datetime64")
    train["hour"] = train["datetime"].dt.hour
    train["year"] = train["datetime"].dt.year
    
    y = train["count"] 
    train = train.drop(["casual","registered","count","datetime","holiday","season"], 1)
    print(train.dtypes)
    x_train,x_valid,y_train,y_valid = train_test_split(train,y,test_size = 0.33,random_state = 42)
    
    
    parser = reqparse.RequestParser()
    parser.add_argument('year', type=str)
    parser.add_argument('hour', type=str)
    parser.add_argument('windspeed', type=str)
    parser.add_argument('humidity', type=str)
    parser.add_argument('atemp', type=str)
    parser.add_argument('temp', type=str)
    parser.add_argument('weather', type=str)
    parser.add_argument('workingday', type=str)
    """
    parser.add_argument('holiday', type=str)
    parser.add_argument('season', type=str)
    """
    args = parser.parse_args()
    
    test = pd.DataFrame({'year': [args['year']], 'hour': [args['hour']], 'windspeed' :[args['windspeed']], 'humidity' : [args['humidity']],
                         'atemp' : [args['atemp']],'temp' : [args['temp']],'weather' : [args['weather']],'workingday' : [args['workingday']]
                         })
    
    test['year'] = test['year'].astype(np.int64)
    test['hour'] = test['hour'].astype(np.int64)
    test['windspeed'] = test['windspeed'].astype(np.float64)
    test['humidity'] =  test['humidity'].astype(np.int64)
    test['atemp'] = test['atemp'].astype(np.float64)
    test['temp'] = test['temp'].astype(np.float64)
    test['weather'] = test['weather'].astype(np.int64)
    test['workingday'] = test['workingday'].astype(np.int64)
    print(test.dtypes)
    
    rf = RandomForestRegressor()
    rf.fit(x_train,y_train)
    p = rf.predict(test)
    print(p)

    print("Accuracy is: ", rf.score (x_valid,y_valid))
    return jsonpify(np.array(p).tolist())

 

 

특이점 

1) cross domain 매개변수 최대 8개

2) 머신러닝 모델에서 돌리기 위해서 전처리로 data type을 맞춰줘야 함.

3) 모델의 predict 반환 값은 np.array인데 이것을 list형태로 고쳐서 json parsing 해야 함.

 

결과

반응형

'HealRo Project' 카테고리의 다른 글

Lgbm 설치  (0) 2020.01.27
Spring boot JS 경로 configure  (0) 2020.01.24
RandomForest Regressor 성능 분석  (0) 2020.01.24
flask Rest API GET 매개변수  (0) 2020.01.23
간단한 머신러닝 연동 테스트  (0) 2020.01.22