|
import glob |
|
import os |
|
|
|
from model import LinearClassifier |
|
from flax import nnx |
|
import optax |
|
from data_loading import get_time_series_tf |
|
import jax.numpy as jnp |
|
import numpy as np |
|
from copy import deepcopy |
|
|
|
|
|
def loss_fn(model: LinearClassifier, batch): |
|
logits = model(batch['feature']) |
|
loss = optax.softmax_cross_entropy_with_integer_labels( |
|
logits=logits, labels=batch['label'] |
|
).mean() |
|
return loss, logits |
|
|
|
@nnx.jit |
|
def train_step(model: LinearClassifier, optimizer: nnx.Optimizer, batch): |
|
"""Train for a single step.""" |
|
grad_fn = nnx.value_and_grad(loss_fn, has_aux=True) |
|
(loss, logits), grads = grad_fn(model, batch) |
|
optimizer.update(grads) |
|
|
|
@nnx.jit |
|
def eval_step(model: LinearClassifier, metrics: nnx.MultiMetric, batch): |
|
loss, logits = loss_fn(model, batch) |
|
metrics.update(loss=loss, logits=logits, labels=batch['label']) |
|
|
|
|
|
|
|
def get_results(features_path): |
|
print(features_path) |
|
|
|
train_loader, val_loader, test_loader, in_features = get_time_series_tf( |
|
features_path=features_path |
|
) |
|
|
|
model = LinearClassifier( |
|
in_features=in_features, |
|
out_features=8, |
|
rngs=nnx.Rngs(0) |
|
) |
|
|
|
|
|
learning_rate = 0.005 |
|
optimizer = nnx.Optimizer( |
|
model, |
|
optax.adamw(learning_rate=learning_rate) |
|
) |
|
|
|
|
|
metrics = nnx.MultiMetric( |
|
accuracy=nnx.metrics.Accuracy(), |
|
loss=nnx.metrics.Average('loss'), |
|
) |
|
|
|
epochs = 100 |
|
|
|
best_accuracy = 0.0 |
|
best_model = deepcopy(model) |
|
patience = 0 |
|
|
|
for epoch in range(epochs): |
|
if patience == 10: |
|
break |
|
for batch in train_loader: |
|
batch = { |
|
'feature' : jnp.array(batch[0]), |
|
'label' : jnp.array(batch[1]) |
|
} |
|
train_step(model, optimizer, batch) |
|
for batch in val_loader: |
|
batch = { |
|
'feature' : jnp.array(batch[0]), |
|
'label' : jnp.array(batch[1]) |
|
} |
|
eval_step(model, metrics, batch) |
|
|
|
results = metrics.compute() |
|
|
|
accuracy = results['accuracy'].item() |
|
if accuracy > best_accuracy: |
|
best_accuracy = accuracy |
|
best_model = deepcopy(model) |
|
patience = 0 |
|
else: |
|
patience += 1 |
|
metrics.reset() |
|
|
|
print(f"best eval accuracy: {best_accuracy}") |
|
|
|
|
|
for batch in test_loader: |
|
batch = { |
|
'feature' : jnp.array(batch[0]), |
|
'label' : jnp.array(batch[1]) |
|
} |
|
eval_step(best_model, metrics, batch) |
|
|
|
|
|
results = metrics.compute() |
|
accuracy = results['accuracy'].item() |
|
print(f"test accuracy: {accuracy}") |
|
|
|
|
|
directory = '../big_model_inference' |
|
pattern = os.path.join(directory, '*.pt') |
|
exclude_file = 'all_cow_ids.pt' |
|
for features_path in glob.glob(pattern): |
|
if os.path.basename(features_path) != exclude_file: |
|
get_results(features_path) |
|
|
|
|