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

train_classifiers.py 4.2 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
  1. #!/usr/bin/env python
  2. import os
  3. import click
  4. from pathlib import Path
  5. import json
  6. import pickle
  7. import numpy as np
  8. from tqdm import tqdm
  9. from collections import defaultdict
  10. from torch.utils.data import Dataset
  11. from sklearn.ensemble import RandomForestClassifier
  12. from sklearn.metrics import (
  13. balanced_accuracy_score,
  14. accuracy_score,
  15. )
  16. class SmokeDataset(Dataset):
  17. def __init__(self, dates, X, y, distance_bins_km, density_categories,
  18. sequence_length, look_ahead):
  19. self.dates = dates
  20. self.X = X
  21. self.y = y
  22. self.distance_bins_km = distance_bins_km
  23. self.density_categories = density_categories
  24. self.sequence_length = sequence_length
  25. self.look_ahead = look_ahead
  26. self._len = max(0, len(X) - (sequence_length + look_ahead) + 1)
  27. def __len__(self):
  28. return self._len
  29. def __getitem__(self, i):
  30. midpoint = (i + self.sequence_length)
  31. xx = self.X[i : midpoint].ravel()
  32. yy = self.y[midpoint : midpoint + self.look_ahead].ravel()
  33. return xx, yy
  34. def get_dates(self, i):
  35. midpoint = (i + self.sequence_length)
  36. dx = self.dates[i : midpoint].ravel()
  37. dy = self.dates[midpoint : midpoint + self.look_ahead].ravel()
  38. return dx, dy
  39. def load_training_config(configfile):
  40. with open(configfile, 'r') as f:
  41. return json.load(f)
  42. def load_datasets(datafile, config):
  43. data = np.load(datafile)
  44. dtype = 'datetime64[D]'
  45. train_range = np.array(config['train_date_range'], dtype=dtype)
  46. val_range = np.array(config['validation_date_range'], dtype=dtype)
  47. test_range = np.array(config['test_date_range'], dtype=dtype)
  48. dates = data['dates']
  49. dist_bins = data['distance_bins_km']
  50. density_categories = data['density_categories']
  51. get_idx = lambda d_range: np.logical_and(
  52. d_range[0] <= dates,
  53. dates <= d_range[1]
  54. )
  55. idx = {
  56. 'train': get_idx(train_range),
  57. 'validation': get_idx(val_range),
  58. 'test': get_idx(test_range),
  59. }
  60. datasets = []
  61. for Xi, yi in zip(data['features'], data['densities']):
  62. datasets.append({
  63. subset: SmokeDataset(
  64. dates[jj], Xi[jj], yi[jj],
  65. dist_bins, density_categories,
  66. config['sequence_length'],
  67. config['look_ahead'],
  68. )
  69. for subset, jj in idx.items()
  70. })
  71. site_info = {
  72. 'latitudes': data['latitudes'],
  73. 'longitudes': data['longitudes'],
  74. 'names': data['names'],
  75. }
  76. return site_info, datasets
  77. def train_eval_classifier(dataset):
  78. datasets = {
  79. dname: tuple(map(np.vstack, zip(*
  80. [dataset[dname][i] for i in range(len(dataset[dname]))]
  81. )))
  82. for dname in ('train', 'validation', 'test')
  83. }
  84. cls = RandomForestClassifier()
  85. cls.fit(*datasets['train'])
  86. statistics = defaultdict(dict)
  87. for dname, (X, y) in datasets.items():
  88. print(f'Evaluationg {dname}')
  89. ypred = cls.predict(X)
  90. statistics[dname]['balanced_accuracy'] = [
  91. balanced_accuracy_score(y[:, i], ypred[:, i], adjusted=True)
  92. for i in range(y.shape[1])
  93. ]
  94. statistics[dname]['smoke_accuracy'] = [
  95. balanced_accuracy_score(y[:, i] > 0, ypred[:, i] > 0, adjusted=True)
  96. for i in range(y.shape[1])
  97. ]
  98. print(statistics)
  99. return cls, dict(statistics)
  100. @click.command()
  101. @click.argument('datafile', type=click.Path(
  102. path_type=Path, exists=True
  103. ))
  104. @click.argument('configfile', type=click.Path(
  105. path_type=Path, exists=True
  106. ))
  107. @click.argument('outputfile', type=click.Path(
  108. path_type=Path
  109. ))
  110. def main(datafile, configfile, outputfile):
  111. config = load_training_config(configfile)
  112. site_info, datasets = load_datasets(datafile, config)
  113. result = {
  114. 'configuration': config,
  115. 'classifiers': [],
  116. 'statistics': [],
  117. }
  118. for name, dset in zip(site_info['names'], datasets):
  119. print(f'Training classifier for {name}...')
  120. cls, statistics = train_eval_classifier(dset)
  121. result['classifiers'].append(cls)
  122. result['statistics'].append(statistics)
  123. with open(outputfile, 'wb') as f:
  124. pickle.dump(result, f)
  125. if __name__ == '__main__':
  126. main()
Tip!

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

Comments

Loading...