-
Notifications
You must be signed in to change notification settings - Fork 1
/
train.py
182 lines (140 loc) · 6.52 KB
/
train.py
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
#!/usr/bin/python2
import argparse
import logging
import os
import sys
import numpy as np
from nilm.markov import fit_data
from nilm.network import DenoisingAutoencoder
from nilm.preprocess import (confidence_estimator, get_changed_data,
solve_constant_energy, sort_data)
from nilm.timeseries import TimeSeries
log = logging.getLogger(__name__)
def apply_preprocess(aggregated, devices, method, threshold=np.float32(0.0)):
"""
Apply the given preprocessing method to the devices.
"""
if method == 'raw':
return
indicators = [d.indicators(threshold) for d in devices]
if method == 'constant':
(energies, _) = solve_constant_energy(aggregated, indicators)
for (e, d) in zip(energies, devices):
log.info('Setting constant energy %s for device %s.' % (e, d.name))
d.powers = e * d.indicators(np.float32(10))
elif method == 'interval':
energy_dict = confidence_estimator(aggregated, devices, sort_data,
threshold)
for d in devices:
log.info('Setting constant energy %s for device %s.' %
(energy_dict[d.name], d.name))
d.powers = energy_dict[d.name] * d.indicators(np.float32(10))
elif method == 'edge':
energy_dict = confidence_estimator(aggregated, devices,
get_changed_data, threshold)
for d in devices:
log.info('Setting constant energy %s for device %s.' %
(energy_dict[d.name], d.name))
d.powers = energy_dict[d.name] * d.indicators(np.float32(10))
elif method == 'markov':
agg = dict((time, power) for (time, power) in enumerate(aggregated))
device = [i for i in xrange(len(devices))]
active = {}
for i, d in enumerate(devices):
active[(i,0)] = 0
for t, ind in enumerate(d.indicators(threshold)):
active[(i,t+1)] = ind * 1
for d in device:
print devices[d].name
try:
p = fit_data(agg, d, active, 3, device)
for (t, power) in p.iteritems():
devices[d].powers[t-1] = power
except KeyError:
devices[d].powers = np.zeros(len(devices[d].powers))
def main():
parser = get_parser()
args = parser.parse_args()
format = '%(asctime)s %(message)s'
logging.basicConfig(filename=args.log, level=logging.DEBUG, format=format)
device_files = [os.path.abspath(os.path.join(args.dir, p)) for p in
os.listdir(args.dir)]
agg_path = os.path.abspath(args.aggregated)
if agg_path in device_files:
device_files.remove(agg_path)
agg_data = TimeSeries(path=agg_path)
agg_data.array = agg_data.array[0:len(agg_data.array)/5*4]
device_in = []
for dev_path in device_files:
dev = TimeSeries(os.path.basename(dev_path).split('.')[0],
path=dev_path)
dev.intersect(agg_data)
device_in.append(dev)
apply_preprocess(agg_data.powers, device_in, args.preprocess,
np.float32(25.00))
for dev in device_in:
log.info('Training: %s' % dev.name)
activations = dev.activations(np.float32(25.0))
log.info('Activations:')
for a in activations:
log.info('From %s to %s lasting %s' % (dev.times[a[0]],
dev.times[a[1]-1],
a[1] - a[0]))
if len(activations) == 0:
log.info('No activations found.')
continue
window_size = sum([a[1] - a[0] for a in activations])/len(activations)
length = min(len(dev.array), len(agg_data.array))
log.info('Window size: %s' % window_size)
log.info('Series length: %s' % length)
agg_windows = []
dev_windows = []
window_size = min(1500, window_size)
window_size = max(8, window_size)
log.info('Computing windows...')
std_dev = np.std(np.random.choice(agg_data.powers, 10000))
max_power = dev.powers.max()
log.info('Std Dev: %s' % std_dev)
log.info('Max Power: %s' % max_power)
for i in xrange(0, length - window_size + 1, window_size):
if agg_data.times[i+window_size-1] - agg_data.times[i] > window_size:
log.info('Throwing out from %s to %s' %
(agg_data.times[i], agg_data.times[i+window_size-1]))
continue
dev_window = np.divide(dev.powers[i+3:i+window_size-3], max_power)
agg_window = agg_data.powers[i:i+window_size]
mean = agg_window.mean(axis=None)
agg_window = np.divide(np.subtract(agg_window, mean), std_dev)
dev_windows.append(dev_window)
agg_windows.append(agg_window)
agg_windows = np.array(agg_windows)
dev_windows = np.array(dev_windows)
agg_windows.shape = (len(agg_windows), window_size, 1)
dev_windows.shape = (len(dev_windows), window_size - 6, 1)
log.info('Training network...')
network = DenoisingAutoencoder(window_size)
network.train(agg_windows, dev_windows)
log.info('Saving model to: %s' % os.path.join(args.out,
dev.name + '.yml'))
network.save_model(os.path.join(args.out, dev.name + '.yml'))
log.info('Saving weight to: %s' % os.path.join(args.out,
dev.name + '.h5'))
network.save_weights(os.path.join(args.out, dev.name + '.h5'))
return 0
def get_parser():
parser = argparse.ArgumentParser(description='Train neural networks for the'
' given devices.')
parser.add_argument('-o', '--out', required=True, help='Output directory.')
parser.add_argument('-a', '--aggregated', required=True,
help='Aggregated power usage file.')
parser.add_argument('-d', '--dir', required=True,
help='Directory containing device files.')
parser.add_argument('-l', '--log', default='/tmp/agg.log',
help='File to write log to.')
parser.add_argument('-p', '--preprocess',
choices=['raw','constant','interval','edge', 'markov'],
default='raw',
help='Which preprocessing algorithm to use.')
return parser
if __name__ == '__main__':
sys.exit(main())