Python 데이터 분석

RandomForest 예제 2 - django를 활용(patient 데이터 사용)

코딩탕탕 2022. 11. 22. 18:12

 

 

 

 

 

url.py

from django.contrib import admin
from django.urls import path
from myapp import views 

urlpatterns = [
    path("admin/", admin.site.urls),
    
    path("", views.MainFunc),
    path("show", views.ShowFunc),
    path("list", views.ListFunc)
]

 

views.py

from django.shortcuts import render
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pickle

def MainFunc(request):
    df = pd.read_csv('https://raw.githubusercontent.com/pykwon/python/master/testdata_utf8/patient.csv', index_col=0)
    df1 = df.head(3)
    
    df_x = df.drop(columns = ['STA'])
    df_y = df['STA']
    
    x_train, x_test, y_train, y_test = train_test_split(df_x, df_y, test_size = 0.2, random_state = 1)
    print(x_train.shape, x_test.shape, y_train.shape, y_test.shape) # (160, 9) (40, 9) (160, 1) (40, 1)
    
    model = RandomForestClassifier(n_estimators=500, criterion='entropy')
    model.fit(x_train, y_train)
    
    pred = model.predict(x_test)
    
    acc = accuracy_score(y_test, pred) # 0.85
    
    pickle.dump(model, open('model.sav', mode = 'wb'))
    del model



    return render(request, 'main.html', {'df':df1.to_html, 'acc':acc})

def ShowFunc(request):
    return render(request, 'show.html')

def ListFunc(request):
    import pickle
    
    model = pickle.load(open('model.sav', 'rb'))
    
    AGE = request.POST.get('AGE')
    SEX = request.POST.get('SEX')
    RACE = request.POST.get('RACE')
    SER = request.POST.get('SER')
    CAN = request.POST.get('CAN')
    CRN = request.POST.get('CRN')
    INF = request.POST.get('INF')
    CPR = request.POST.get('CPR')
    HRA = request.POST.get('HRA')
    
    data = { AGE:[AGE],
                SEX:[SEX],
                RACE:[RACE],
                SER:[SER],
                CAN:[CAN],
                CRN:[CRN],
                INF:[INF],
                CPR:[CPR],
                HRA:[HRA]
        }
    
    x_test = pd.DataFrame(data, columns=[AGE, SEX, RACE, SER, CAN, CRN, INF, CPR, HRA])
    print(x_test)
    print(model)
    pred = model.predict(x_test)
    print(pred)
    
    return render(request, 'list.html', {'pred':pred[0]})

 

main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>분류모델의 정확도 : {{acc}}</p>
<p>patient 데이터 일부 보기 : {{df | safe}}</p>

<a href="/show">입원 환자 데이터를 입력해 생사 여부 확인하기</a>
</body>
</html>

 

 

show.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
table, th, td {
	border: 1px solid #bcbcbc;
	word-break : break-all;
	}
</style>
</head>
<body>
<p>입원 환자 데이터를 입력해 생사 여부 확인을 위한 자료 입력</p>

<pre>
AGE : 나이
SEX : 성별
RACE : 인종
SER : 중환자 치료실에서 받은 치료
CAN : 암 존재 여부
INF : 중환자 치료실에서의 감염 여부
CPR : 중환자 치료실 도착 전 CPR 여부
HPA : 중환자 치료실에서의 심박수
예) AGE SEX RACE SER CAN INF CPR HPA
    27  1    1   0   0   1   0   88
</pre>
<form action="/list" method="post" id='list'> {% csrf_token %}
<table border="1">
	<tr>
		<th>AGE</th><th>SEX</th><th>RACE</th><th>SER</th>	
	</tr>
	<tr>
		<td>
			<input type="text" id="AGE" name="AGE"/>
		</td>
		<td>
			<input type="text" id="SEX" name="SEX"/>
		</td>
		<td>
			<input type="text" id="RACE" name="RACE"/>
		</td>
		<td>
			<input type="text" id="SER" name="SER"/>
		</td>
	</tr>
	<tr>
		<th>CAN</th><th>CRN</th><th>INF</th><th>CPR</th><th>HRA</th>
	</tr>
	<tr>
		<td>
			<input type="text" id="CAN" name="CAN"/>
		</td>
		<td>
			<input type="text" id="CRN" name="CRN"/>
		</td>
		<td>
			<input type="text" id="INF" name="INF"/>
		</td>			
		<td>
			<input type="text" id="CPR" name="CPR"/>
		</td>
		<td>
			<input type="text" id="HRA" name="HRA"/>
		</td>
	</tr>
	<tr>
		<td>
			<button type="submit">확인</button>
		</td>
	</tr>
</table>
</form>
</body>
</html>

 

 

list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>예측 결과 : {{pred}}</p>
{% if pred == 1 %}
<p>생존</p>
{% else %}
<p>사망</p>
{% endif %}
</body>
</html>