-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAI.py
204 lines (157 loc) · 6.02 KB
/
AI.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# %%
import os
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.keras as keras
from time import time
from tqdm import tqdm
from functools import cache
from platform import system as ps
from src.zsoc import OCV_curve
from src.dataset import build_dataset, import_k_para
# shut off tensorflow warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# verify that we are on the GPU
print("Num GPUs Available: ", len(
tf.config.experimental.list_physical_devices('GPU')))
print("Num CPUs Available: ", len(
tf.config.experimental.list_physical_devices('CPU')))
# %% build/load dataset
if not os.path.exists('./res/K_para_ordered.csv'):
print("K_para_ordered.csv not found. Generating...")
t = time()
kp = pd.read_csv('./res/K_para.csv')
# calculate zsoc for each entry's K0-K7 columns
kpk = kp.iloc[:, 4:12].to_numpy()
z = np.array([OCV_curve(k)['Vo'] for k in kpk])
z = np.sum(z, axis=1)
# sort kp by zsoc
kp = kp.iloc[np.argsort(z)]
kp.to_csv('./res/K_para_ordered.csv')
t, _ = time(), print("Building dataset...")
df = build_dataset(f='./res/K_para_ordered.csv', cache=f'./res/dataset_{ps()}.pkl')
df = df.sample(frac=1).reset_index(drop=True)
print(f"Done. Took {time()-t:.2f}s.")
kp = import_k_para(f'./res/K_para_ordered.csv')
nsamples = kp.shape[0]
print(f"Dataset has {nsamples} samples.")
t, _ = time(), print("Generating zsoc vectors...")
zsoc = np.array([OCV_curve(kp[i])['Vo'] for i in range(nsamples)])
print(f"Done. Took {time()-t:.2f}s.")
# %% define the model
# class mse_custom(tf.keras.losses.MeanSquaredError):
# def __init__(self, name='mse_custom'):
# super().__init__(name=name)
# def call(self, y_true, y_pred):
# """mean squared error between zsoc vectors"""
# y_true = tf.argmax(y_true, axis=-1)
# y_pred = tf.argmax(y_pred, axis=-1)
# z_true = tf.gather(zsoc, y_true)
# z_pred = tf.gather(zsoc, y_pred)
# return super().call(z_true, z_pred)
# %% generate 3d histograms (preprocessing )
# do a simple 3d histogram of the data using numpy
shape = (8, 8, 8)
def hist3dgenerator():
for i, row in enumerate(df.itertuples()):
V, I, t = row.V, row.I, row.t
h = np.histogramdd(
(V, I, t),
bins=shape,
range=((V.min(), V.max()), ((I.min()), (I.max())), (0, t[-1]))
)[0]
# h = h / h.mean()
h = h.reshape(*shape, 1)
yield h
# use tqdm
print("Generating 3d histograms...")
t = time()
cache = f'./res/hist_{ps()}.npy'
if os.path.exists(cache) and False:
hist = np.load(cache)
else:
hist = np.array([h for h in tqdm(hist3dgenerator(), total=len(df))])
np.save(cache, hist)
print(f"Done. Took {time()-t:.2f}s.")
# %% define the models
def CNN_char(df: pd.DataFrame):
"""do a dummy tf.keras model that just takes the raw v, i, t vectors and predicts the i"""
t, _ = time(), print("Building model CNN_char...")
model = keras.Sequential()
model.add(keras.layers.Conv3D(32, (3, 3, 3), activation='relu', input_shape=(*shape, 1)))
model.add(keras.layers.MaxPool3D((2, 2, 2)))
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Conv3D(32, (3, 3, 3), activation='relu'))
model.add(keras.layers.MaxPool3D((2, 2, 2)))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dense(nsamples, activation='softmax'))
model.summary()
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
print(f"Done. Took {time()-t:.2f}s.")
y = np.eye(nsamples)[df.i - 1]
model.fit(hist, y, epochs=10, batch_size=16)
return model
def CNN_flatten2d(df: pd.DataFrame):
"""do a dummy tf.keras model that just takes the raw v, i, t vectors and predicts the i"""
from src.layers import Flatten2D
t, _ = time(), print("Building model CNN_char...")
model = keras.Sequential()
model.add(keras.layers.Input(shape=(*shape, 1)))
model.add(Flatten2D())
model.add(keras.layers.Conv3D(32, (2, 2, 2), activation='relu'))
model.add(keras.layers.MaxPool3D((3, 3, 3)))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dense(nsamples, activation='softmax'))
model.summary()
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
print(f"Done. Took {time()-t:.2f}s.")
y = np.eye(nsamples)[df.i - 1]
model.fit(hist, y, epochs=10, batch_size=16)
return model
def CNN_flatten1d(df: pd.DataFrame):
"""do a dummy tf.keras model that just takes the raw v, i, t vectors and predicts the i"""
from src.layers import FlattenHistogram1D
t, _ = time(), print("Building model CNN_char...")
model = keras.Sequential()
model.add(keras.layers.Input(shape=(*shape, 1)))
model.add(FlattenHistogram1D())
model.add(keras.layers.Conv3D(32, (2, 2, 2), activation='relu'))
model.add(keras.layers.MaxPool3D((3, 3, 3)))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dense(nsamples, activation='softmax'))
model.summary()
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
print(f"Done. Took {time()-t:.2f}s.")
y = np.eye(nsamples)[df.i - 1]
model.fit(hist, y, epochs=10, batch_size=16)
return model
# %% train the model
models = [
('base_encoding', CNN_char),
('flatten2d_encoding', CNN_flatten2d),
('flatten1d_encoding', CNN_flatten1d),
]
# for name, model in models:
# m = model(df)
# m.save(f'./res/{name}_{ps()}.h5')
m = CNN_flatten1d(df)
# evaluate model
y = np.eye(nsamples)[df.i - 1]
print(m.evaluate(hist, y))
# %%