Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

curtailment_classifier.py 5.0 KB

You have to be logged in to leave a comment. Sign In
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
  1. import altair as alt
  2. import pandas as pd
  3. from sklearn.svm import SVC
  4. from sklearn.linear_model import LogisticRegression
  5. from sklearn.compose import ColumnTransformer
  6. from sklearn.pipeline import Pipeline
  7. from sklearn.preprocessing import StandardScaler, OneHotEncoder
  8. from sklearn.model_selection import train_test_split, GridSearchCV
  9. from loguru import logger
  10. from src.conf import settings
  11. INPUT_DIR = settings.DATA_DIR / "processed/training/"
  12. OUTPUT_DIR = settings.DATA_DIR / "processed/results/"
  13. class BaseModel:
  14. def __init__(self, data, y_col, n_vars, c_vars):
  15. self.X = data[n_vars + c_vars].copy()
  16. self.y = data[y_col]
  17. self.n_vars = n_vars
  18. self.c_vars = c_vars
  19. def build_model(self, regressor, numeric_vars, categorical_vars):
  20. """Build a generic model
  21. """
  22. numeric_transformer = Pipeline(
  23. steps=[
  24. # Convert all numeric values to units of variance.
  25. # This helps us avoid weird number conditions when using
  26. # sklearn with very big and very small numbers.
  27. ("scaler", StandardScaler())
  28. ]
  29. )
  30. categorical_transformer = Pipeline(
  31. steps=[
  32. # Use one-hot encoding to handle categoricals like weekday and month
  33. ("onehot", OneHotEncoder(handle_unknown="ignore"))
  34. ]
  35. )
  36. preprocessor = ColumnTransformer(
  37. transformers=[
  38. ("num", numeric_transformer, numeric_vars),
  39. ("cat", categorical_transformer, categorical_vars),
  40. ]
  41. )
  42. clf = Pipeline(
  43. steps=[("preprocessor", preprocessor), ("classifier", regressor)]
  44. )
  45. return clf
  46. def model(self):
  47. """Define the relevant model for this class
  48. """
  49. raise NotImplementedError
  50. def fit_train_predict(self, clf, test_size=0.2):
  51. """
  52. """
  53. X_train, X_test, y_train, y_test = train_test_split(
  54. self.X.copy(), self.y.copy(), test_size=test_size
  55. )
  56. clf.fit(X_train, y_train)
  57. predictions = clf.predict_proba(X_test)
  58. predictions = pd.DataFrame(
  59. clf.predict_proba(X_test), columns=list(map(str, clf.classes_))
  60. ).assign(actual=y_test.values)
  61. return predictions
  62. def run(self, trials=100, test_size=0.2):
  63. """Resample and re-run the model multiple times.
  64. """
  65. clf = self.model()
  66. predictions = []
  67. for i in range(trials):
  68. p = self.fit_train_predict(clf, test_size=test_size).assign(trial=i)
  69. predictions.append(p)
  70. return pd.concat(predictions, ignore_index=True)
  71. class Logistic(BaseModel):
  72. def model(self):
  73. lr = LogisticRegression(fit_intercept=False)
  74. clf = self.build_model(lr, self.n_vars, self.c_vars)
  75. return clf
  76. class SVM(BaseModel):
  77. def model(self):
  78. sv = SVC(probability=True)
  79. clf = self.build_model(sv, self.n_vars, self.c_vars)
  80. return clf
  81. def plot_results(self, predictions):
  82. pass
  83. def LR_seasonal_load(df, y_col):
  84. """
  85. """
  86. model = Logistic(df, y_col, ["load"], ["is_weekday", "month"])
  87. results = model.run()
  88. return results
  89. def LR_seasonal_load_with_weather(df, y_col):
  90. """
  91. curtailment_event ~ load + C(is_weekday) + C(month) + t_mean + t_absmin + t_absmax + dswrf_mean + dswrf_absmax
  92. """
  93. model = Logistic(
  94. df,
  95. y_col,
  96. ["load", "t_mean", "t_absmax", "t_absmin", "dswrf_mean", "dswrf_absmax"],
  97. ["is_weekday", "month",],
  98. )
  99. results = model.run()
  100. return results
  101. def LR_seasonal_load_with_weather_capacity_weighted(df, y_col):
  102. model = Logistic(
  103. df,
  104. y_col,
  105. ["load", "t_wmean", "t_wmin", "t_wmax", "dswrf_wmean", "dswrf_absmax"],
  106. ["is_weekday", "month",],
  107. )
  108. results = model.run()
  109. return results
  110. def SVM_seasonal_load_with_weather_capacity_weighted(df, y_col):
  111. model = SVM(
  112. df,
  113. y_col,
  114. ["load", "t_wmean", "t_wmin", "t_wmax", "dswrf_wmean", "dswrf_absmax"],
  115. ["is_weekday", "month",],
  116. )
  117. results = model.run()
  118. return results
  119. registry = [
  120. LR_seasonal_load,
  121. LR_seasonal_load_with_weather,
  122. LR_seasonal_load_with_weather_capacity_weighted,
  123. SVM_seasonal_load_with_weather_capacity_weighted,
  124. ]
  125. if __name__ == "__main__":
  126. OUTPUT_DIR.mkdir(exist_ok=True)
  127. data = pd.read_parquet(INPUT_DIR / "1_labeled_curtailment_events.parquet")
  128. # ad-hoc minute feature labeling to support sklearn
  129. data["month"] = data["timestamp"].dt.month
  130. events = data.columns[data.columns.str.match(r"curtailment_event_\d.\d\d")]
  131. results = {}
  132. for m in registry:
  133. for event in events:
  134. logger.info("Training {m} on {event}", event=event, m=m.__name__)
  135. predictions = m(data, event)
  136. results[m.__name__] = {event: predictions}
  137. fn = OUTPUT_DIR / f"predictions-{m.__name__}-{event}.parquet"
  138. predictions.to_parquet(fn, index=False)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...