-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodeling.py
More file actions
952 lines (749 loc) · 39.9 KB
/
modeling.py
File metadata and controls
952 lines (749 loc) · 39.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
import pandas as pd
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LassoLars
from sklearn.linear_model import TweedieRegressor
from sklearn.preprocessing import PolynomialFeatures
#import r2
from sklearn.metrics import r2_score
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.metrics import make_scorer
def get_starbucks_Q1_2023_data_for_prediction():
"""
Retrieves and prepares Quarter 1, 2023 data for Starbucks Q2 revenue prediction.
This function reads the data from the file 'values_for_prediction_ford_adjusted.csv'. The predicted features line is
is the same for all companies since it is void of the target (revenue for each). The word ford is in the file name because
it was the first company the file was made for.
The function selects statistically significant features relevant for Starbucks revenue prediction, and returns
a pandas DataFrame containing these features.
Returns:
pandas DataFrame: A DataFrame containing the statistically significant features
for Starbucks revenue prediction in Quarter 1, 2023.
"""
# Read the data for Quarter 1, 2023
this_is_it = pd.read_csv('values_for_prediction_ford_adjusted.csv')
# Select statistically significant features for revenue prediction
starbucks_revenue_prediction = this_is_it[['population', 'median_house_income', 'unemp_rate',
'home_ownership_rate', 'government_spending', 'gdp_deflated',
'violent_crime_rate','cpi_all_items_avg', 'eci', 'dow', 's_and_p',
'Man_new_order', 'hdi','auto_loan', 'velocity_of_money',
'case_shiller_index','c_e_s_housing', 'c_e_s_health',
'ease_of_doing_business']]
return starbucks_revenue_prediction
def starbucks_scaled_df(train, test, starbucks_revenue_prediction):
"""
Scale the train, and test data using the MinMaxScaler.
Parameters:
train (pandas DataFrame): The training data.
test (pandas DataFrame): The test data.
starbucks_revenue_prediction (pandas DataFrame): The data for Starbucks revenue prediction.
Returns:
Tuple of:
X_train_scaled (pandas DataFrame): The scaled training data.
X_test_scaled (pandas DataFrame): The scaled test data.
y_train (pandas Series): The target variable for the training data.
y_test (pandas Series): The target variable for the test data.
X_train (pandas DataFrame): The original training data.
starbucks_revenue_prediction_scaled (pandas DataFrame): The scaled Starbucks revenue prediction data.
"""
X_train = train[['population', 'median_house_income', 'unemp_rate',
'home_ownership_rate', 'government_spending', 'gdp_deflated',
'violent_crime_rate','cpi_all_items_avg', 'eci', 'dow', 's_and_p',
'Man_new_order', 'hdi','auto_loan', 'velocity_of_money',
'case_shiller_index','c_e_s_housing', 'c_e_s_health',
'ease_of_doing_business']]
X_test = test[['population', 'median_house_income', 'unemp_rate',
'home_ownership_rate', 'government_spending', 'gdp_deflated',
'violent_crime_rate','cpi_all_items_avg', 'eci', 'dow', 's_and_p',
'Man_new_order', 'hdi','auto_loan', 'velocity_of_money',
'case_shiller_index','c_e_s_housing', 'c_e_s_health',
'ease_of_doing_business']]
y_train = train.adjusted_revenue_S
y_test = test.adjusted_revenue_S
# Make our scaler object
scaler = MinMaxScaler()
# Fit our scaling object and use it to transform train and test data
X_train_scaled = pd.DataFrame(scaler.fit_transform(X_train),
columns=X_train.columns,
index=X_train.index)
X_test_scaled = pd.DataFrame(scaler.transform(X_test),
columns=X_test.columns,
index=X_test.index)
# Scale the Starbucks revenue prediction data
starbucks_revenue_prediction_scaled = pd.DataFrame(scaler.transform(starbucks_revenue_prediction.values.reshape(1, -1)),
columns=starbucks_revenue_prediction.columns,
index=starbucks_revenue_prediction.index)
return X_train_scaled, X_test_scaled, y_train, y_test, X_train, starbucks_revenue_prediction_scaled
def starbucks_metrics_reg(y, yhat):
"""
Calculate evaluation metrics for regression predictions.
Parameters:
y_true (array-like): The true target values.
y_pred (array-like): The predicted target values.
Returns:
tuple: A tuple containing the Root Mean Squared Error (RMSE) and R-squared (R2) values.
"""
# calculate rmse
rmse = mean_squared_error(y, yhat, squared=False)
# calculate r2
r2 = r2_score(y, yhat)
return rmse, r2
def starbucks_baseline_model(train, y_train):
"""
Creates a baseline model using the mean of the target variable and evaluates its performance.
Parameters:
train (pandas DataFrame): The training data containing the feature variables.
y_train (pandas Series): The target variable for the training data.
Returns:
pandas DataFrame: A DataFrame containing the evaluation metrics of the baseline model.
The function creates a baseline model by setting the predicted value as the mean of the target variable (y_train).
It calculates the root mean squared error (RMSE) and R^2 score of the baseline model using the y_train values
and an array filled with the mean value. The RMSE and R^2 score are added to a DataFrame for comparison.
"""
# Set baseline
baseline = round(y_train.mean(), 2)
# Make an array to send into mean_square_error function
baseline_array = np.repeat(baseline, len(train))
# Evaluate the baseline RMSE and R2
rmse, r2 = starbucks_metrics_reg(y_train, baseline_array)
# Add results to a DataFrame for comparison
starbucks_metrics_df = pd.DataFrame(data=[
{
'model': 'Baseline',
'rmse': rmse,
'r2': r2
}
])
# Print baseline
print(f'Baseline mean is: {baseline}')
return starbucks_metrics_df
def starbucks_LassoLars_model(X_train_scaled, y_train, starbucks_metrics_df):
"""
Performs LassoLars regression and evaluates the model's performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
starbucks_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the LassoLars model.
"""
# Define the model and the hyperparameter grid
model = LassoLars(normalize=False)
param_grid = {
'alpha': [0.00001, 0.0001, 0.001, 0.01,0.1,0.25,0.5,0.75, 1],
'normalize': [True, False]
}
# Define scoring metrics and create dictionary to house them
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=model,
param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Retrieve best model for modeling predictions
best_model = grid_search.best_estimator_
# Get the best model rmse
best_score = grid_search.best_score_
# Get the best model associated r2
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
starbucks_metrics_df.loc[1] = ['LassoLars', abs(best_score), corresponding_r2]
return starbucks_metrics_df, best_model
def starbucks_Generalized_Linear_Model(X_train_scaled, y_train, starbucks_metrics_df):
"""
Fits a Generalized Linear Model (GLM) and evaluates its performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
starbucks_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the GLM.
"""
# Define the model and the hyperparameter grid
model = TweedieRegressor()
param_grid = {
'alpha': [0.00001, 0.0001, 0.001, 0.01,0.1,0.25,0.5,0.75, 1],
'power': [0, 1, 2] # Example values for power
}
# define scoring metrics and create a dictionary to house them
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Get the best model rmse
best_score = grid_search.best_score_
# Get the best model r2
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
starbucks_metrics_df.loc[2] = ['Generalized Linear Model', abs(best_score), corresponding_r2]
return starbucks_metrics_df
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer, mean_squared_error, r2_score
def starbucks_polynomial_regression(X_train_scaled, y_train, starbucks_metrics_df):
"""
Performs polynomial regression and evaluates the model's performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
starbucks_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the polynomial regression model.
sklearn Pipeline: The best-fit polynomial regression model.
The function creates a pipeline for polynomial regression, which includes transforming the features with different
polynomial degrees and applying linear regression. It then performs hyperparameter tuning to find the best polynomial
degree using GridSearchCV based on R2 score. The best-fit polynomial regression model and the evaluation metrics
(RMSE and R2) are added to the provided metrics DataFrame.
"""
# Create the pipeline
pipeline = Pipeline([
('polynomialfeatures', PolynomialFeatures()),
('linearregression', LinearRegression())
])
# Define the hyperparameter grid
param_grid = {
'polynomialfeatures__degree': [1, 2, 3, 4, 5]
}
# Define the scoring functions
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=pipeline, param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Get the best model rmse
best_score = grid_search.best_score_
# Get the best model r2
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
starbucks_metrics_df.loc[3] = ['Polynomial Regression(PR)', abs(best_score), corresponding_r2]
return starbucks_metrics_df
def starbucks_prediction_Q2_2023_revenue(model, starbucks_revenue_prediction_scaled):
"""
Make revenue predictions for Starbucks in Q2 2023 using the provided model.
Parameters:
model: The trained model for revenue prediction.
starbucks_revenue_prediction_scaled: The preprocessed single line of data containing scaled feature variables
for predicting Starbucks revenue in Q2 2023.
Returns:
None
This function takes a preprocessed single line of data (`starbucks_revenue_prediction_scaled`) containing the
scaled feature variables needed for revenue prediction in Q2 2023. It uses the provided `model` to make predictions
for the Starbucks revenue and then prints the predicted value.
Note: The model should be compatible with the scaled input data (`starbucks_revenue_prediction_scaled`) to ensure
correct predictions. The predicted revenue value will be displayed as output using the 'print' statement.
"""
# Pass the preprocessed single line of data to the best_model
pred_value = model.predict(starbucks_revenue_prediction_scaled)
# Print the predicted value
print('Starbucks predicted 2023 Q2 revenue is' , pred_value)
def best_model_on_test(X_test_scaled, best_model, y_test):
"""
Evaluate the best-fit model on the test dataset.
Parameters:
X_test_scaled (pandas DataFrame): The scaled feature variables of the test data.
best_model: The best-fit regression model obtained from hyperparameter tuning.
y_test (pandas Series): The true target variable for the test data.
Returns:
tuple: A tuple containing the Root Mean Squared Error (RMSE) and R-squared (R2) metrics.
This function evaluates the performance of the best-fit regression model on the test dataset. It uses the model
to make predictions on the scaled feature variables (`X_test_scaled`) and then compares the predictions with the
true target variable (`y_test`). The evaluation metrics, RMSE, and R2 are calculated based on this comparison.
The function returns a tuple containing the RMSE and R2 metrics, providing an assessment of the model's performance
on the test data. A lower RMSE and a higher R2 indicate better model performance.
"""
sb_pred_test = best_model.predict(X_test_scaled)
rmse, r2 = starbucks_metrics_reg(y_test, sb_pred_test)
return rmse, r2
def get_ford_Q1_2023_data_for_prediction():
"""
Retrieves and prepares Quarter 1, 2023 data for Ford's Q2 revenue prediction.
This function reads the data from the file 'values_for_prediction_ford_adjusted.csv'. The predicted features line is
is the same for all companies since it is void of the target (revenue for each). The word Ford is in the file name because
it was the first company the file was made for.
The function selects statistically significant features relevant for Ford's revenue prediction, and returns
a pandas DataFrame containing these features.
Returns:
pandas DataFrame: A DataFrame containing the statistically significant features
for Ford's revenue prediction in Quarter 1, 2023.
"""
# prepare 2023 quarter 1 data for prediction of quarter 2 revenue
this_is_it = pd.read_csv('values_for_prediction_ford_adjusted.csv')
# select statistically significant features
ford_revenue_prediction = this_is_it[['population','median_house_income','misery_index',
'gdp_deflated','violent_crime_rate','cpi_all_items_avg',
'eci','prime', 'gini', 'hdi', 'cli','velocity_of_money',
'consumer_confidence_index','c_e_s_health',
'ease_of_doing_business']]
return ford_revenue_prediction
def ford_scaled_df(train, test, ford_revenue_prediction):
"""
Scale the data for Ford's revenue prediction and prepare the datasets.
Parameters:
train (pandas DataFrame): The training data containing the feature variables and the adjusted revenue for Ford.
test (pandas DataFrame): The test data containing the feature variables and the adjusted revenue for Ford.
ford_revenue_prediction (pandas DataFrame): The data for Ford's revenue prediction in Q2 2023.
Returns:
tuple: A tuple containing the scaled training data, scaled test data, target variables for training and test,
original training data, and the scaled Ford's Q1 2023 revenue prediction data.
This function scales the feature variables in both the training and test datasets using MinMaxScaler.
The function then prepares the necessary datasets for training and evaluation, including scaled training and
test data, target variables (adjusted revenue) for both training and test data, and the scaled data for Ford's
revenue prediction in Q2 2023.
The function returns a tuple containing the scaled datasets and relevant variables for further analysis and modeling.
"""
X_train = train[['population', 'median_house_income', 'misery_index',
'gdp_deflated', 'violent_crime_rate', 'cpi_all_items_avg',
'eci', 'prime', 'gini', 'hdi', 'cli', 'velocity_of_money',
'consumer_confidence_index', 'c_e_s_health',
'ease_of_doing_business']]
X_test = test[['population', 'median_house_income', 'misery_index',
'gdp_deflated', 'violent_crime_rate', 'cpi_all_items_avg',
'eci', 'prime', 'gini', 'hdi', 'cli', 'velocity_of_money',
'consumer_confidence_index', 'c_e_s_health',
'ease_of_doing_business']]
y_train = train.adjusted_revenue_B
y_test = test.adjusted_revenue_B
# Making our scaler
scaler = MinMaxScaler()
# Fitting our scaler and using it to transform train and test data
X_train_scaled = pd.DataFrame(scaler.fit_transform(X_train),
columns=X_train.columns,
index=X_train.index)
X_test_scaled = pd.DataFrame(scaler.transform(X_test),
columns=X_test.columns,
index=X_test.index)
# Scaling the Ford revenue prediction data
ford_revenue_prediction_scaled = pd.DataFrame(scaler.transform(ford_revenue_prediction.values.reshape(1, -1)),
columns=ford_revenue_prediction.columns,
index=ford_revenue_prediction.index)
return X_train_scaled, X_test_scaled, y_train, y_test, X_train, ford_revenue_prediction_scaled
def ford_metrics_reg(y, yhat):
"""
send in y_true, y_pred & returns RMSE, R2
"""
rmse = mean_squared_error(y, yhat, squared=False)
r2 = r2_score(y, yhat)
return rmse, r2
def ford_baseline_model(train, y_train):
"""
Creates a baseline model using the mean of the target variable and evaluates its performance.
Parameters:
train (pandas DataFrame): The training data containing the feature variables.
y_train (pandas Series): The target variable for the training data.
Returns:
pandas DataFrame: A DataFrame containing the evaluation metrics of the baseline model.
The function creates a baseline model by setting the predicted value as the mean of the target variable (y_train).
It calculates the root mean squared error (RMSE) and R^2 score of the baseline model using the y_train values
and an array filled with the mean value. The RMSE and R^2 score are added to a DataFrame for comparison.
Additionally, the function prints the baseline value and returns the DataFrame with the evaluation metrics.
"""
#set baseline
baseline = round(y_train.mean(),2)
#make an array to send into my mean_square_error function
baseline_array = np.repeat(baseline, len(train))
# Evaluate the baseline rmse and r2
rmse, r2 = ford_metrics_reg(y_train, baseline_array)
# add results to a dataframe for comparison
ford_metrics_df = pd.DataFrame(data=[
{
'model':'Baseline',
'rmse':rmse,
'r2':r2
}
])
# print baseline
print(f' Baseline mean is : {baseline}')
return ford_metrics_df
def ford_LassoLars_model(X_train_scaled, y_train, ford_metrics_df):
"""
Performs LassoLars regression and evaluates the model's performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
ford_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the LassoLars model.
"""
# Define the model and the hyperparameter grid
model = LassoLars(normalize=False)
param_grid = {
'alpha': [0.00001, 0.0001, 0.001, 0.01,0.1,0.25,0.5,0.75, 1],
'normalize': [True, False]
}
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=model,
param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Get the best model rmse and r2
best_model = grid_search.best_estimator_
# Get the best model rmse and r2
best_score = grid_search.best_score_
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
ford_metrics_df.loc[1] = ['LassoLars', abs(best_score), corresponding_r2]
return ford_metrics_df, best_model
def ford_Generalized_Linear_Model(X_train_scaled, y_train, ford_metrics_df):
"""
Fits a Generalized Linear Model (GLM) and evaluates its performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
ford_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the GLM.
"""
# Define the model and the hyperparameter grid
model = TweedieRegressor()
param_grid = {
'alpha': [0.00001, 0.0001, 0.001, 0.01,0.1,0.25,0.5,0.75, 1], # Example values for alpha
'power': [0, 1, 2] # Example values for power
}
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=model,
param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Get the best model rmse and r2
best_score = grid_search.best_score_
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
ford_metrics_df.loc[2] = ['Generalized Linear Model', abs(best_score), corresponding_r2]
return ford_metrics_df
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
def ford_polynomial_regression(X_train_scaled, y_train, ford_metrics_df):
"""
Performs polynomial regression and evaluates the model's performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
ford_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the polynomial regression model.
"""
# Create the pipeline
pipeline = Pipeline([
('polynomialfeatures', PolynomialFeatures()),
('linearregression', LinearRegression())
])
# Define the hyperparameter grid
param_grid = {
'polynomialfeatures__degree': [1, 2, 3, 4, 5]
}
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=pipeline,
param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Get the best model rmse and r2
best_score = grid_search.best_score_
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
ford_metrics_df.loc[3] = ['Polynomial Regression(PR)', abs(best_score), corresponding_r2]
return ford_metrics_df
def ford_prediction_Q2_2023_revenue(model, ford_revenue_prediction_scaled):
"""
Predicts Ford Motor Company's revenue for the second quarter of 2023.
Parameters:
model: Trained model to make predictions.
ford_revenue_prediction_scaled (pandas DataFrame): The scaled feature variables of the Ford revenue prediction data.
Returns:
None: The function prints the predicted revenue for Ford Motor Company for the second quarter of 2023.
"""
# Pass the preprocessed single line of data to the best_model
pred_value = model.predict(ford_revenue_prediction_scaled)
# Print the predicted value
print("Ford Motor Company's predicted 2023 Q2 revenue is" , pred_value)
def ford_best_model_on_test(X_test_scaled, best_model, y_test):
"""
Evaluates the best model on the test data.
Parameters:
X_test_scaled (pandas DataFrame): The scaled feature variables of the test data.
best_model: The best trained model to be evaluated.
y_test (pandas Series): The target variable for the test data.
Returns:
Tuple: Root Mean Squared Error (RMSE) and R^2 score of the best model on the test data.
"""
ford_pred_test = best_model.predict(X_test_scaled)
rmse, r2 = ford_metrics_reg(y_test, ford_pred_test)
return rmse, r2
def get_att_Q1_2023_data_for_prediction():
"""
Retrieves and prepares Quarter 1, 2023 data for ATT's Q2 revenue prediction.
This function reads the data from the file 'values_for_prediction_ford_adjusted.csv'. The predicted features line is
is the same for all companies since it is void of the target (revenue for each). The word ford is in the file name because
it was the first company the file was made for.
The function selects statistically significant features relevant for ATT's revenue prediction, and returns
a pandas DataFrame containing these features.
Returns:
pandas DataFrame: A DataFrame containing the statistically significant features
for ATT's revenue prediction in Quarter 1, 2023.
"""
# prepare 2023 quarter 1 data for prediction of quarter 2 revenue
this_is_it = pd.read_csv('values_for_prediction_ford_adjusted.csv')
# select statistically significant features
att_revenue_prediction = this_is_it[['home_ownership_rate','hdi','violent_crime_rate',
'ease_of_doing_business','population','c_e_s_health',
'construction_res','federal_fund_rate','auto_loan',
'eci','gdp_deflated','velocity_of_money','cpi_all_items_avg'
]]
return att_revenue_prediction
def att_scaled_df(train, test, att_revenue_prediction):
"""
This function scales the train, validate, and test data using the MinMaxScaler.
Parameters:
train (pandas DataFrame): The training data.
test (pandas DataFrame): The test data.
att_revenue_prediction (pandas DataFrame): The data for Ford revenue prediction.
Returns:
Tuple of:
X_train_scaled (pandas DataFrame): The scaled training data.
X_test_scaled (pandas DataFrame): The scaled test data.
y_train (pandas Series): The target variable for the training data.
y_test (pandas Series): The target variable for the test data.
X_train (pandas DataFrame): The original training data.
att_revenue_prediction_scaled (pandas DataFrame): The scaled ATT revenue prediction data.
"""
X_train = train[['home_ownership_rate','hdi','violent_crime_rate',
'ease_of_doing_business','population','c_e_s_health',
'construction_res','federal_fund_rate','auto_loan',
'eci','gdp_deflated','velocity_of_money','cpi_all_items_avg'
]]
X_test = test[['home_ownership_rate','hdi','violent_crime_rate',
'ease_of_doing_business','population','c_e_s_health',
'construction_res','federal_fund_rate','auto_loan',
'eci','gdp_deflated','velocity_of_money','cpi_all_items_avg'
]]
y_train = train.adjusted_revenue_A
y_test = test.adjusted_revenue_A
# Making our scaler
scaler = MinMaxScaler()
# Fitting our scaler and using it to transform train and test data
X_train_scaled = pd.DataFrame(scaler.fit_transform(X_train),
columns=X_train.columns,
index=X_train.index)
X_test_scaled = pd.DataFrame(scaler.transform(X_test),
columns=X_test.columns,
index=X_test.index)
# Scaling the Ford revenue prediction data
att_revenue_prediction_scaled = pd.DataFrame(scaler.transform(att_revenue_prediction.values.reshape(1, -1)),
columns=att_revenue_prediction.columns,
index=att_revenue_prediction.index)
return X_train_scaled, X_test_scaled, y_train, y_test, X_train, att_revenue_prediction_scaled
def att_metrics_reg(y, yhat):
"""
send in y_true, y_pred & returns RMSE, R2
"""
rmse = mean_squared_error(y, yhat, squared=False)
r2 = r2_score(y, yhat)
return rmse, r2
def att_baseline_model(train, y_train):
"""
Creates a baseline model using the mean of the target variable and evaluates its performance.
Parameters:
train (pandas DataFrame): The training data containing the feature variables.
y_train (pandas Series): The target variable for the training data.
Returns:
pandas DataFrame: A DataFrame containing the evaluation metrics of the baseline model.
The function creates a baseline model by setting the predicted value as the mean of the target variable (y_train).
It calculates the root mean squared error (RMSE) and R^2 score of the baseline model using the y_train values
and an array filled with the mean value. The RMSE and R^2 score are added to a DataFrame for comparison.
Additionally, the function prints the baseline value and returns the DataFrame with the evaluation metrics.
"""
#set baseline
baseline = round(y_train.mean(),2)
#make an array to send into my mean_square_error function
baseline_array = np.repeat(baseline, len(train))
# Evaluate the baseline rmse and r2
rmse, r2 = att_metrics_reg(y_train, baseline_array)
# add results to a dataframe for comparison
att_metrics_df = pd.DataFrame(data=[
{
'model':'Baseline',
'rmse':rmse,
'r2':r2
}
])
# print baseline
baseline = round(y_train.mean(),2)
print(f' Baseline mean is : {baseline}')
return att_metrics_df
def att_LassoLars_model(X_train_scaled, y_train, att_metrics_df):
"""
Performs LassoLars regression and evaluates the model's performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
att_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the LassoLars model.
"""
# Define the model and the hyperparameter grid
model = LassoLars(normalize=False)
param_grid = {
'alpha': [0.00001, 0.0001, 0.001, 0.01,0.1,0.25,0.5,0.75, 1],
'normalize': [True, False]
}
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=model,
param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Get the best model rmse and r2
best_model = grid_search.best_estimator_
# Get the best model rmse and r2
best_score = grid_search.best_score_
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
att_metrics_df.loc[1] = ['LassoLars', abs(best_score), corresponding_r2]
return att_metrics_df, best_model
def att_Generalized_Linear_Model(X_train_scaled, y_train, att_metrics_df):
"""
Fits a Generalized Linear Model (GLM) and evaluates its performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
att_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the GLM.
"""
# Define the model and the hyperparameter grid
model = TweedieRegressor()
param_grid = {
'alpha': [0.00001, 0.0001, 0.001, 0.01,0.1,0.25,0.5,0.75, 1],
'power': [0, 1, 2]
}
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=model,
param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Get the best model rmse and r2
best_score = grid_search.best_score_
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
att_metrics_df.loc[2] = ['Generalized Linear Model(GLM)', abs(best_score), corresponding_r2]
return att_metrics_df
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
def att_polynomial_regression(X_train_scaled, y_train, att_metrics_df):
"""
Performs polynomial regression and evaluates the model's performance.
Parameters:
X_train_scaled (pandas DataFrame): The scaled feature variables of the training data.
y_train (pandas Series): The target variable for the training data.
att_metrics_df (pandas DataFrame): A DataFrame to store the evaluation metrics.
Returns:
pandas DataFrame: The updated metrics DataFrame with the evaluation metrics of the polynomial regression model.
"""
# Create the pipeline
pipeline = Pipeline([
('polynomialfeatures', PolynomialFeatures()),
('linearregression', LinearRegression())
])
# Define the hyperparameter grid
param_grid = {
'polynomialfeatures__degree': [1, 2, 3, 4, 5]
}
scoring = {
'RMSE': 'neg_root_mean_squared_error',
'r2': make_scorer(r2_score)
}
# Create the GridSearchCV object
grid_search = GridSearchCV(estimator=pipeline,
param_grid=param_grid, scoring=scoring, cv=5, refit='RMSE')
# Fit the GridSearchCV object to the training data
grid_search.fit(X_train_scaled, y_train)
# Get the best model rmse and r2
best_score = grid_search.best_score_
best_index = np.where(grid_search.cv_results_['mean_test_RMSE'] == grid_search.best_score_)[0]
corresponding_r2 = grid_search.cv_results_['mean_test_r2'][best_index][0]
# Add evaluation metrics to the provided metrics DataFrame
att_metrics_df.loc[3] = ['Polynomial Regression(PR)', abs(best_score), corresponding_r2]
return att_metrics_df
def att_prediction_Q2_2023_revenue(best_model, att_revenue_prediction_scaled):
"""
Make predictions for AT&T's revenue in Q2 2023 using the best selected model.
Parameters:
best_model (sklearn model): The best performing model obtained from the evaluation process.
att_revenue_prediction_scaled (pandas DataFrame): Scaled feature variables for AT&T's revenue prediction.
Returns:
None
This function takes the best performing model obtained from the model evaluation process and the scaled
feature variables for AT&T's revenue prediction in Q2 2023 as input arguments. It then uses the `predict`
method of the best_model to make revenue predictions for the specified quarter.
The predicted revenue value is stored in the variable `pred_value`, and it is printed to the console along
with an informative message indicating that it represents AT&T's predicted revenue for Q2 2023.
Note: The `att_revenue_prediction_scaled` should contain the same features used during model training and
should be preprocessed in the same way as the training data to ensure consistent results.
"""
# Pass the preprocessed single line of data to the best_model
pred_value = best_model.predict(att_revenue_prediction_scaled)
# Print the predicted value
print("ATT's predicted 2023 Q2 revenue is" , pred_value)
def att_best_model_on_test(X_test_scaled, best_model, y_test):
"""
Evaluate the best model's performance on the test data for AT&T's revenue prediction.
Parameters:
X_test_scaled (pandas DataFrame): The scaled feature variables of the test data.
best_model (sklearn model): The best performing model obtained from the evaluation process.
y_test (pandas Series): The target variable for the test data.
Returns:
Tuple (float, float): The root mean squared error (RMSE) and R^2 score of the best model's predictions.
This function takes the scaled feature variables of the test data (X_test_scaled), the best_model selected from
the evaluation process, and the target variable for the test data (y_test). It then uses the best_model to make
predictions on the test data and calculates the root mean squared error (RMSE) and R^2 score to evaluate the
performance of the model.
The function returns a tuple containing the RMSE and R^2 score as the evaluation metrics for the best model.
"""
att_pred_test = best_model.predict(X_test_scaled)
rmse, r2 = att_metrics_reg(y_test, att_pred_test)
return rmse, r2