- pandas - matplotlib - seaborn - scikit-learn - paths: - ./NANUMMYEONGJO.TTF - ./NANUMMYEONGJOBOLD.TTF - ./common.py import pandas as pd from pyodide.http import open_url from common import * import numpy as np # 넘파이 배열 출력시 소숫점 자릴수 지정 np.set_printoptions(formatter={'float_kind': lambda x: "{0:0.2f}".format(x)}) from datetime import datetime # 경고 문구 제거 import warnings warnings.filterwarnings( 'ignore' ) # 판다스에서 csv 를 데이터 프레임으로 읽어옴 매출데이터 = pd.read_csv(open_url( "http://dreamplan7.cafe24.com/pyscript/csv/avocado.csv" )) # 3개 필드만 추려서 데이터 프레임을 다시 만듬 매출데이터 = 매출데이터[[ 'Date', 'Total Volume', 'AveragePrice' ]] # 영문 제목을 한글로 변경 매출데이터.columns = [ '날짜', '매출량', '평균가격' ] 주간매출_매출량=매출데이터.fillna(0) \ .groupby('날짜', as_index=False)[['매출량']].sum() \ .sort_values(by='날짜', ascending=True) 주간매출_평균가=매출데이터.fillna(0) \ .groupby('날짜', as_index=False)[['평균가격']].mean() \ .sort_values(by='날짜', ascending=True) 주간매출데이터=pd.merge(주간매출_매출량, 주간매출_평균가, on='날짜') # 날짜(시간값) 추가 주간매출데이터.insert(1, '날짜(시간값)', '', True) for i in 주간매출데이터['날짜'].index: 주간매출데이터['날짜(시간값)'].loc[i]=time.mktime( datetime.strptime( 주간매출데이터['날짜'].loc[i], '%Y-%m-%d' ).timetuple() ) # 10000으로 나눈 매출량 필드 추가 주간매출데이터.insert(3, '매출량(만)', 주간매출데이터['매출량']/10000, True) # 훈련학습용으로 날짜를 연도, 월, 일로 나눈다 주간매출데이터.insert(4, '연도', '', True) 주간매출데이터.insert(5, '월', '', True) 주간매출데이터.insert(6, '일', '', True) 주간매출데이터.insert(7, '주', '', True) for i in 주간매출데이터['날짜'].index: 임시=str(주간매출데이터['날짜'].loc[i]).split('-') 연도=int(임시[0]) 월=int(임시[1]) 일=int(임시[2]) 주간매출데이터['연도'].loc[i]=연도 주간매출데이터['월'].loc[i]=월 주간매출데이터['일'].loc[i]=일 주간매출데이터['주'].loc[i]=str( datetime(연도, 월, 일).isocalendar()[1] ) createElementDiv( document, Element, 'output2' ).write(주간매출데이터) 주간매출데이터훈련_넘파이 = 주간매출데이터[['날짜(시간값)', '연도', '월', '일', '주', '평균가격']].to_numpy() 주간매출데이터목표_넘파이 = 주간매출데이터['매출량(만)'].to_numpy() 주간매출데이터훈련_넘파이 = 주간매출데이터훈련_넘파이.astype(np.float) print(주간매출데이터훈련_넘파이[:5]) 주간매출데이터훈련_넘파이 = np.column_stack(( 주간매출데이터훈련_넘파이 , 주간매출데이터훈련_넘파이[:,0] ** 2, 주간매출데이터훈련_넘파이[:,1] ** 2, 주간매출데이터훈련_넘파이[:,2] ** 2, 주간매출데이터훈련_넘파이[:,3] ** 2, 주간매출데이터훈련_넘파이[:,4] ** 2, 주간매출데이터훈련_넘파이[:,5] ** 2 )) print(주간매출데이터훈련_넘파이[:5]) from sklearn.model_selection import train_test_split 훈련용데이터, 테스트데이터, 훈련용목표, 테스트목표 = \ train_test_split( 주간매출데이터훈련_넘파이, 주간매출데이터목표_넘파이, random_state=100, shuffle=False) #print(훈련용데이터[0:5]) #print(훈련용목표[0:5]) #print(테스트데이터[0:5]) #print(테스트목표[0:5]) from sklearn.preprocessing import StandardScaler 스케일러 = StandardScaler() 스케일러.fit(훈련용데이터) 훈련용데이터_스케일 = 스케일러.transform(훈련용데이터) 테스트데이터_스케일 = 스케일러.transform(테스트데이터) # 선형 회귀 알고리즘 # 훈련, 최적의 그래프를 찾아준다 from sklearn.linear_model import LinearRegression 선형회귀모델 = LinearRegression() 선형회귀모델.fit(훈련용데이터_스케일, 훈련용목표) print("훈련용모델 정확도") print(선형회귀모델.score(훈련용데이터_스케일, 훈련용목표)) print("테스트모델 정확도") print(선형회귀모델.score(테스트데이터_스케일, 테스트목표)) 훈련용목표예측 = 선형회귀모델.predict(훈련용데이터_스케일) 테스트목표예측 = 선형회귀모델.predict(테스트데이터_스케일) import matplotlib.pyplot as plt import matplotlib.font_manager as fm import matplotlib as mat # 기준 폰트 변경 : legend 의 한글을 적용하려면 필수 fm.fontManager.addfont('./NANUMMYEONGJO.TTF') # 폰트명 : NanumMyeongjo mat.rc('font', family='NanumMyeongjo') ################### # 폰트 목록 출력 ( 폰트 추가 후 정확한 이름을 확인하려면 필요 #font_list = [font.name for font in fm.fontManager.ttflist] #for f in font_list: # print(f) ################### # 개별 폰트 적용 NanumMyengjo = fm.FontProperties( fname='./NANUMMYEONGJO.TTF' ) NanumMyengjoBold = fm.FontProperties( fname='./NANUMMYEONGJOBOLD.TTF' ) # 그래프 fig = plt.figure( figsize=(15, 7) ) plt.xticks( 주간매출데이터['날짜(시간값)'].to_numpy(), 주간매출데이터[['날짜']].to_numpy()[:,0], rotation=90, fontsize=8) plt.title('주간 아보카도 매출량', fontproperties=NanumMyengjoBold, fontsize=32 ); plt.plot( 훈련용데이터[:,0], 훈련용목표, marker='o', color='#c14549', label='원본' ) plt.plot( 훈련용데이터[:,0], 훈련용목표예측, marker='d', color='blue', label='훈련패턴' ) plt.plot( 테스트데이터[:, 0], 테스트목표, marker='o', color='#c14549' ) plt.plot( 테스트데이터[:, 0], 테스트목표예측, marker='d', color='green', label='예측패턴' ) plt.xlabel('날짜', fontsize=16) plt.ylabel('매출량(단위:만)', fontsize=12) # loc : 표 하단 중앙 #plt.legend( # loc=8 #) plt.legend( shadow=True ) ax = plt.gca() # 축만 그리드 ax.xaxis.grid(True) # 배경색, 마진 조정 ax.set_facecolor('#e8e7d2') ax.margins(x=0.01, y=0.02) # 주위 이상한 여백 없애기 fig.tight_layout() fig