ML (MachineLearning)

프로펫(Prophet) 라이브러리 사용하기

567Rabbit 2024. 4. 23. 18:10
  • install : pip install prophet
  • 위 에러 발생시 : conda install -c conda-forge prophet

 

 

임포트하기

 

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
import seaborn as sns
from prophet import Prophet

 

 

 

 

아보카도 데이터

 

 

 

프로펫 분석을 위해, 두개의 컬럼만 가져오기 ('Date', 'AveragePrice')

 

avocado_prophet_df = df[['Date','AveragePrice']]

 

 

avocado_prophet_df

  Date AveragePrice
0 2015-01-04 1.33
1 2015-01-04 1.35
2 2015-01-04 0.93
3 2015-01-04 1.08
4 2015-01-04 1.28
... ... ...
7 2018-03-25 1.63
8 2018-03-25 1.71
9 2018-03-25 1.87
10 2018-03-25 1.93
11 2018-03-25 1.62

 

 

 

 

ds 와 y 로 컬럼명 셋팅

 

avocado_prophet_df.columns = ['ds','y']

 

avocado_prophet_df

 

  ds y
0 2015-01-04 1.33
1 2015-01-04 1.35
2 2015-01-04 0.93
3 2015-01-04 1.08
4 2015-01-04 1.28
... ... ...
7 2018-03-25 1.63
8 2018-03-25 1.71
9 2018-03-25 1.87
10 2018-03-25 1.93
11 2018-03-25 1.62

 

 

 

 

프로펫 예측

 

# 1. 라이브러리를 변수로 만들고
prophet = Prophet()

 

# 2. 데이터로 학습시킨다
prophet.fit(avocado_prophet_df)

 

# 3. 예측하고자 하는 기간을 정해서, 비어있는 데이터프레임을 만든다
future = prophet.make_future_dataframe(periods=365, freq='D')  #365일

 

# 4. 예측을 한다
forecast = prophet.predict(future)

 

 

 

# 차트로 확인
prophet.plot(forecast)
plt.savefig('chart1.jpg')
plt.show()

 

 

prophet.plot_components(forecast)
plt.savefig('chart2.jpg')
plt.show()

 

 

 

 

 

 

region 이 west 인 아보카도의 가격을 예측하시오.

 

df = df[df['region'].str.contains('West')]

df = df.loc[ : , 'Date':'AveragePrice']

 

import pandas as pd

df = pd.DataFrame(df)

df = df.rename(columns={'Date':'ds', 'AveragePrice':'y'})

 

 

prophet = Prophet()

prophet.fit(df)

future = prophet.make_future_dataframe(periods=365, freq='D')

 

forecast = prophet.predict(future)

 

 

prophet.plot(forecast)
plt.show()

 

 

 

 

prophet.plot_components(forecast)
plt.show()

 

 

 

 

 

 

시카고 범죄 데이터

 

 

df_prophet = chicago_df.resample('D').size().to_frame().reset_index().rename(columns={'Date':'ds', 0:'y'})

prophet = Prophet()

prophet.fit(df_prophet)

future = prophet.make_future_dataframe(periods=365, freq='D')

forecast = prophet.predict(future)

 

 

prophet.plot(forecast)

 

 

 

prophet.plot_components(forecast)