Saturday, 10 August 2024

Forcasting by Using Model in Python

 Time Series Forecasting with ML Model

Following are the steps we need to following to Apply the model on the data. Below is the small example.

Step 1

Create the instance of the Prophet class 

Step 2 

Call  the Methods 

A) fit  method 

B) predict methods

Note:-The input to Prophet is always a dataframe with two columns: ds and y

a) The ds (datestamp) column having format like YYYY-MM-DD  or YYYY-MM-DD HH:MM:SS 

        b) y column should be numeric on which prediction is made

        c) settings for the forecasting procedure are passed into the constructor


Sample Example Code

import pandas as pd

from prophet import Prophet

df =pd.read_csv('1.csv')

print(df)

m = Prophet()

m.fit(df)

cast_future = m.make_future_dataframe(periods=365)

print(cast_future)

fcast = m.predict(cast_future)

print(fcast)

fcast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]

fig1 = m.plot(fcast)

fig2 = m.plot_components(fcast)

Practical Example for the  Model
import pandas as pd
import os,sys


source_folder = r".\\data"
data2=pd.DataFrame()

for file in os.listdir(source_folder):
    data= pd.read_csv(".\\data\\"+file+" ", dtype=str)
    data2=data2.append(data)
    print(file,"has been appended")


data2.head()
data2=data2.drop('Unnamed: 0',axis=1)
data2.head()
data2['test']=data2['HR'] .apply(lambda x: '{0:0>4}'.format(x))
data2.head()
data2['ds']=data2['DT'].str.cat(data2['test'],sep=" ")
data2.head()
data2['ds']=pd.to_datetime(data2['ds'])
data2['EXTRA'] = data2['EXTRA'].astype('float')
data2.info()
data3 = data2.rename(columns={'EXTRA': 'y', 'PLT': 'plts'})
data3.head()
data3=data3[['ds','y','plts']]
data3=data3.dropna()
data3
data3=data3.loc[data3['y']>=0] 
data3
from prophet import Prophet
def get_test(x):
    #for x in range(0,3):
    data4=data3.loc[data3['plts']==x]
    m = Prophet()
    m.fit(data4)
    cast_future = m.make_future_dataframe(periods=24000,freq='60min')  
    fcast = m.predict(cast_future)
    return fcast

list_olts =data3.olts.unique()
for x in range(0,3):
    y=list_olts[x]
    fc=get_test(y)
    fc=fc[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]
    fc['PLT_NAME']=y    
    fc.to_csv('./Predicted_DATA/'+y+'.csv')

No comments:

Post a Comment