R or Python - loop the test data - Prediction validation next 24 hours (96 values each day)

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



R or Python - loop the test data - Prediction validation next 24 hours (96 values each day)



I have a large dataset, below the training and test datasets



train_data is from 2016-01-29 to 2017-12-31


head(train_data)
date Date_time Temp Ptot JFK AEH ART CS CP
1 2016-01-29 2016-01-29 00:00:00 30.3 1443.888 52.87707 49.36879 28.96548 6.239999 49.61212
2 2016-01-29 2016-01-29 00:15:00 30.3 1410.522 49.50248 49.58356 26.37977 5.024000 49.19649
3 2016-01-29 2016-01-29 00:30:00 30.3 1403.191 50.79809 49.04253 26.15317 5.055999 47.48126
4 2016-01-29 2016-01-29 00:45:00 30.3 1384.337 48.88359 49.14100 24.52135 5.088000 46.19261
5 2016-01-29 2016-01-29 01:00:00 30.1 1356.690 46.61842 48.80624 24.28208 5.024000 43.00352
6 2016-01-29 2016-01-29 01:15:00 30.1 1341.985 48.09687 48.87748 24.49988 4.975999 39.90505



test_data is from 2018-01-01 to 2018-07-12


tail(test_data)
date Date_time Temp Ptot JFK AEH ART CS CP
86007 2018-07-12 2018-07-12 22:30:00 64.1 1458.831 82.30099 56.93944 27.20252 2.496 54.41050
86008 2018-07-12 2018-07-12 22:45:00 64.1 1457.329 61.68535 54.28934 28.59752 3.728 54.15208
86009 2018-07-12 2018-07-12 23:00:00 63.5 1422.419 80.56367 56.40752 27.99190 3.520 53.85705
86010 2018-07-12 2018-07-12 23:15:00 63.5 1312.021 52.25757 56.40283 22.03727 2.512 53.72166
86011 2018-07-12 2018-07-12 23:30:00 63.5 1306.349 65.65347 56.20145 22.77093 3.680 52.71584
86012 2018-07-12 2018-07-12 23:45:00 63.5 1328.528 57.47283 57.73747 19.50940 2.432 52.37458



I want to make a prediction validation loop for 24 hours(Each day from 2018-01-01 to 2018-07-12) in test_data . Each day prediction is (96) values-15 minute sampling-. In other words, I have to select 96 values each time and put them in the test_data shown in the code and calculate MAPE.



Target variable: Ptot



Predictors: Temp, JFK, AEH, ...etc



I finished running the prediction as shown below


input = train_data[c("Temp","JFK","AEH","ART","CS","CP","RLF", "FH" ,"TJF" ,"GH" , "JPH","JEK", "KL",
"MH","MC","MRH", "PH","OR","RP","RC","RL","SH", "SPC","SJH","SMH","VWK","WH","Month","Day",
"Year","hour")]
target = train_data["Ptot"]

glm_model <- glm(Ptot~ ., data= c(input, target), family=gaussian)



I want to iterate through the "test_data" -create a loop- by taking each time 96 observation -96 rows- from the test table sequentially until the end of the dataset and calculate MAPE and save all of the value. I implemented this in R.



As shown below in fig. each time take 96 rows from (test_data) and put them in "test_data" in the function. It is just an explanation, not showing all 96 values :)
enter image description here



This is the function I have to create a loop for it


pred<- predict.glm(glm_model,test_data)

mape <- function(actual, pred)
return(100 * mean(abs((actual- pred)/actual)))



I will show how to make first-day prediction validation



1- select 96 values from test_data(i.e 2018-01-01)


One_day_data <- test_data[test_data$date == "2018-01-01",]



2- Put one day values in the function


pred<- predict.glm(glm_model,One_day_data )



3- This is the prediction results after running pred (96 values =one day)


print(pred)
67489 67490 67491 67492 67493 67494 67495 67496 67497 67498
1074.164 1069.527 1063.726 1082.404 1077.569 1071.265 1070.776 1073.686 1061.720 1063.554
67499 67500 67501 67502 67503 67504 67505 67506 67507 67508
1074.264 1067.393 1071.111 1076.754 1079.700 1071.244 1097.977 1089.862 1091.817 1098.025
67509 67510 67511 67512 67513 67514 67515 67516 67517 67518
1125.495 1133.786 1136.545 1138.473 1176.555 1183.483 1184.795 1186.220 1192.328 1187.582
67519 67520 67521 67522 67523 67524 67525 67526 67527 67528
1186.513 1254.844 1262.021 1258.816 1240.280 1229.237 1237.582 1250.030 1243.189 1262.266
67529 67530 67531 67532 67533 67534 67535 67536 67537 67538
1251.563 1242.417 1259.352 1269.760 1271.318 1266.984 1260.113 1247.424 1200.905 1198.161
67539 67540 67541 67542 67543 67544 67545 67546 67547 67548
1202.372 1189.016 1193.479 1194.668 1207.064 1199.772 1189.068 1176.762 1188.671 1208.944
67549 67550 67551 67552 67553 67554 67555 67556 67557 67558
1199.216 1193.544 1215.866 1209.969 1180.115 1182.482 1177.049 1196.165 1145.335 1146.028
67559 67560 67561 67562 67563 67564 67565 67566 67567 67568
1161.821 1163.816 1114.529 1112.068 1113.113 1107.496 1073.080 1082.271 1097.888 1095.782
67569 67570 67571 67572 67573 67574 67575 67576 67577 67578
1081.863 1068.071 1061.651 1072.511 1057.184 1068.474 1062.464 1061.535 1054.550 1050.287
67579 67580 67581 67582 67583 67584
1038.086 1045.610 1038.836 1030.429 1031.563 1019.997



We can get the actual value from "Ptot"


actual<- One_day_data$Ptot
[1] 1113.398 1110.637 1111.582 1110.816 1101.921 1111.091 1108.501 1112.535 1104.631 1108.284
[11] 1110.994 1106.585 1111.397 1117.406 1106.690 1101.783 1101.605 1110.183 1104.162 1111.829
[21] 1117.093 1125.493 1118.417 1127.879 1133.574 1136.395 1139.048 1141.850 1145.630 1141.288
[31] 1141.897 1140.310 1138.026 1121.849 1122.069 1120.479 1120.970 1111.594 1109.572 1116.355
[41] 1115.454 1113.911 1115.509 1113.004 1119.440 1112.878 1117.642 1100.516 1099.672 1109.223
[51] 1105.088 1107.167 1114.355 1110.620 1110.499 1110.161 1107.868 1118.085 1108.166 1106.347
[61] 1114.036 1106.968 1109.807 1113.943 1106.869 1104.390 1102.446 1110.770 1114.684 1114.142
[71] 1118.877 1128.470 1133.922 1128.420 1134.058 1142.529 1126.432 1127.824 1124.561 1130.823
[81] 1122.907 1117.422 1116.851 1114.980 1114.543 1108.584 1120.410 1120.900 1109.226 1101.367
[91] 1098.330 1110.474 1106.010 1108.451 1095.196 1096.007



4- Run Mape function and save the results (I have the actual values)


mape <- function(actual, pred)
return(100 * mean(abs((actual- pred)/actual)))



5- Do the same thing it for next 24 hours (i.e 2018-01-02) and so on



Incomplete Solution, it is not correct! (I think it should be done by something like this)


result_df =
for (i in 1:96)
test_data<- test_data[i,]
pred<- predict.glm(glm_model,test_data)
result_df$pred[i] <- pred
result_df$Actual[i+1] <- result_df$pred[i]

mape[i] <- function(actual, pred)
return(100 * mean(abs((actual- pred)/actual)))





SUMMARY: I want to store all of the values of mape by passing one day incrementally each time to pred.



NOTE: I will appreciate if you can show me the loop process in R and/or Python.





Please show a long non-loop form of applying your function as it is not immediately clear from text.
– Parfait
Aug 12 at 1:20





@ Parfait I just have to put each time 96 values in test_data and do mape
– King Julien
Aug 12 at 1:23






So, each time change test_data values by putting in it 96 values
– King Julien
Aug 12 at 1:27





The test_data is from 2018-01-01 to 2018-07-12
– King Julien
Aug 12 at 1:35





I updated the time period for you
– King Julien
Aug 12 at 1:38




3 Answers
3



Consider building a generalized function, mape_calc, to receive a subset data frame as input and call the function in R's by. As the object-oriented wrapper to tapply, by will subset the main data frame by each distinct date, passing subsets into defined function for calculation.


by


tapply


by



Within the method, a new, one-row data frame is built to align mape with each date. Then all rows are binded together with do.call:


do.call


mape_calc <- function(sub_df)
pred <- predict.glm(glm_model, sub_df)
actual <- sub_df$Ptot
mape <- 100 * mean(abs((actual - pred)/actual))

new_df <- data.frame(date = sub_df$date[[1]], mape = mape)

return(new_df)


# LIST OF ONE-ROW DATAFRAMES
df_list <- by(test_data, test_data$date, map_calc)

# FINAL DATAFRAME
final_df <- do.call(rbind, df_list)



Should you have same setup in Python pandas and numpy (possibly statsmodels for glm model), use pandas DataFrame.groupby as the counterpart to R's by. Of course adjust below pseudocode to your actual needs.


DataFrame.groupby


by


import pandas as pd
import numpy as np
import statsmodels.api as sm
...

train_data = sm.add_constant(train_data)
model_formula = 'Ptot ~ Temp + JFK + AEH + ART + CS + CP ...'
glm_model = sm.glm(formula = model_formula,
data = train_data.drop(columns=['date','Date_time']),
family = sm.families.Gaussian()).fit()

def mape_calc(dt, sub_df):
pred = glm_model.predict(sub_df.drop(columns=['date','Date_time','Ptot']))
actual = sub_df['Ptot']
mape = 100 * np.mean(np.abs((actual - pred)/actual))

new_df = pd.DataFrame('date': dt, 'mape': mape, index=[0])

return new_df

# LIST OF ONE-ROW DATAFRAMES
df_list = [mape_calc(i, g) for i, g in test_data.groupby('date')]

# FINAL DATAFRAME
final_df = pd.concat(df_list, ignore_index=True)





This is exactly what I was expecting! Thank you so much @Parfait
– King Julien
Aug 12 at 19:08





Dear @Parfait I just want to make sure I understood everything, I appreciate your efforts, by sub_df you mean putting the complete dataset-I mean all of the test_data in this case? am I right?
– King Julien
Aug 12 at 19:58





Or sub_df it is just a parameter? I will be grateful if you let me know what is inside sub_df ?Thanks
– King Julien
Aug 12 at 20:01





sub_df is just a parameter to function. When by calls the function, it passes a subset of test_data which will be the value of sub_df.
– Parfait
Aug 12 at 20:33


by





You made my day buddy! thanks
– King Julien
Aug 12 at 20:37



It sounds to me like you are looking for an introduction to python. Forgive me if I have misunderstood. I realize my answer is very simple.



I am happy to answer your question about how to do a loop in python. I will
give you two examples. I am going to assume that you are using "ipython" which
would allow you to type the following and test it out. I will show you a
for loop and a while loop.



I will demonstrate summing a bunch of numbers. Note that loops must be indented to work. This is a feature of python that freaks out newbies.



So ... inside an ipython environment.


In [21]: data = [1.1, 1.3, 0.5, 0.8, 0.9]

In [22]: def sum1(data):
summ=0
npts=len(data)
for i in range(npts):
summ+=data[i]
return summ

In [23]: sum1(data)
Out[23]: 4.6000000000000005

In [24]: def sum2(data):
summ=0;i=0
npts=len(data)
while i<npts:
summ+=data[i]
i+=1
return summ
#Note that in a while loop you must increment "i" on your own but a for loop
#does it for you ... just like every other language!
In [25]: sum2(data)
Out[25]: 4.6000000000000005



I ignored the question of how to get your data into an array. Python supports both lists (which is what I used in the example) and actual arrays (via numpy). If this is of interest to you, we can talk about numpy next.



There are all kinds of wonderful function for reading data files as well.





I want to update "the One_day_data" in this function shown in the step 5 pred<- predict.glm(glm_model,One_day_data )
– King Julien
Aug 12 at 3:15





I will appreciate if you go through my last section (Incomplete Solution) I updated it now
– King Julien
Aug 12 at 3:18





I want to store all of the values of mape by passing one day incrementally to pred.
– King Julien
Aug 12 at 3:21



OK -- I don't know how to read "R" ... but it looks kind of C-like with elements of Matlab (which means matplotlib and numpy will work great for you!)



I can make your syntax "pythonic". That does not mean I am giving you running code.
We assume that you are interested in learning python. If you are a student asking
for someone else to do your homework, then I will be irritated. Regardless, I would very much appreciate if you would accept one of my answers as I could use some reputation on this site. I just got on it tonight even though I have been coding since 1975.



Here's how to do a function:


def mape(actual, pred):
return(100 * mean(abs((actual-pred)/actual)))



You are obviously using arrays ... you probably want numpy which will work much like I think you expect R to work.


for i in range(2,97):
test=test_data[i]
pred=predict.glm(glm_model,test)
#don't know what this dollar sign thing means
#so I didn't mess with it
result_df$pred[i] =pred
result_df$Actual[i+1] = result_df$pred[i]



I guess the dollar sign is some kind of appending thing. You can certainly append to an array in python. At this point if you want more help you need to break this into questions like ... "How do I create and fill an array in numpy?"



Good luck!





Dear @Richard Sonnenfeld can I explain for you step by step in chat room, the dollar sign means two things, first select a table name "pred" and "Actual" in our case, second if the variable name is not there create it and(i.e add pred values in it )
– King Julien
Aug 12 at 3:49





Can you please explain for me what range(2,97) will do? I want each time to take 96 values from test_data. And I think Python indexing will start from zero, R indexing will start from one. So in python case I presume it should be range(0,95), am I right?
– King Julien
Aug 12 at 3:56





Sorry out of time tonight. It sounds like you really are a beginner (at python). Welcome to a great language! You should probably point that out to people if you want more help. Just posting your code was probably not a bad approach, but probably do it in smaller chunks. In the meantime ... install Anaconda and use ipython and mess with numpy numpy.org
– Richard Sonnenfeld
Aug 12 at 3:57






Thank you, Professor, I am glad to talk to you! :) Have a wonderful dreams
– King Julien
Aug 12 at 3:59






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered