Homework 9#
Neural-Network Regression and Classification
Coverage: Lectures 24–25. The convolutional classifier is explained below; no implementation or convolution derivation is required.
Due: Sunday, November 22, 2026, at 11:59 p.m. Eastern Time.
Total: 100 points.
Instructions#
Answer the six lettered parts. Show your mathematical steps in parts 1(a) and 2(a). Use short, evidence-based paragraphs or bullet points for the other parts; no separate report is required.
All computational code is supplied. Run its cells in order without editing them and write your responses in the answer text cells. You are not expected to study the implementation or write code.
Submit a PDF of your completed notebook, including your name, answers, generated tables, and figures, through Gradescope. Check that equations and figures are legible. The supplied-code sections may be collapsed when printing.
Use a standard CPU Google Colab runtime. The notebook uses NumPy, pandas, SciPy, Matplotlib, scikit-learn, and PyTorch. No package installation or Google Drive is needed. The first run downloads the two datasets, including an approximately 203 MB activity archive. If a source is unavailable, upload the teaching-team copies of
airfoil_self_noise.datandhuman_activity_data.npzto the Colab Files panel; the same checksums are required.Report approximately four significant digits. Small differences across software versions are acceptable. Base your conclusions on the outputs you obtain; a particular model ranking is not required for credit.
Relevant course material: Deep neural networks and training and generalization.
Student details#
First name:
Last name:
Purdue email:
Problem 1: Predicting airfoil self-noise (50 points)#
Credit: Brooks, Pope, and Marcolini (1989), Airfoil Self-Noise, UCI Machine Learning Repository, licensed CC BY 4.0. The data describe NACA 0012 airfoils in wind-tunnel experiments. The supplied training comparisons and questions were constructed for this course.
We predict scaled sound-pressure level (dB) from five inputs: frequency (Hz), angle of attack (degrees), chord length (m), free-stream velocity (m/s), and suction-side displacement thickness (m). There are 1,503 observations. Our question is how training choices affect a neural regression model and what its predictions establish.
(a) Count parameters and calculate a regularized loss (10 points)#
Work this part by hand. The small network has five inputs, one hidden layer of 20 tanh units, and one linear output. Both layers include biases. Count its trainable scalar parameters, showing weights and biases separately.
For a batch of \(m\) standardized targets, the supplied training objective is
The penalty includes all weights and biases, with no factor of \(1/2\). For four residuals \((-1,2,-2,1)\), \(\sum_j\theta_j^2=12\), and \(\lambda=0.01\), calculate the MSE, penalty, and total \(J\). Derive the penalty’s contribution to \(\partial J/\partial\theta_j\). The four residuals are a separate arithmetic example, not the fitted model’s measured errors.
Your answer:
The supplied experiment fixes a random split of approximately 70% training, 15% validation, and 15% test rows. Predictor and target standardization use training rows only. The histograms and scatterplots below also use only training data. A random row split can place related experimental configurations in different subsets; it does not represent a new airfoil family or a new wind tunnel.
from IPython import get_ipython
get_ipython().run_line_magic("matplotlib", "inline")
import copy
import hashlib
import io
from pathlib import Path
from urllib.request import urlopen
import zipfile
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from IPython.display import display
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler
R_SEED = 53909
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
plt.rcParams.update({'font.size': 10, 'figure.dpi': 110})
R_SHA256 = '74c75fd71783f1e6b71f8a622b993dc592897a97cd689c5090a07147a1b097b3'
r_path = Path('airfoil_self_noise.dat')
if r_path.exists():
r_raw = r_path.read_bytes()
else:
r_url = 'https://archive.ics.uci.edu/static/public/291/airfoil%2Bself%2Bnoise.zip'
with urlopen(r_url, timeout=60) as response:
r_archive = zipfile.ZipFile(io.BytesIO(response.read()))
r_raw = r_archive.read(next(n for n in r_archive.namelist()
if n.endswith('airfoil_self_noise.dat')))
if hashlib.sha256(r_raw).hexdigest() != R_SHA256:
raise RuntimeError('Airfoil checksum mismatch. Ask the teaching team for the original file.')
r_data = np.loadtxt(io.BytesIO(r_raw))
assert r_data.shape == (1503, 6) and np.isfinite(r_data).all()
r_X, r_y = r_data[:, :5], r_data[:, 5]
r_train, r_remaining = train_test_split(np.arange(len(r_y)), test_size=.30,
random_state=R_SEED)
r_valid, r_test = train_test_split(r_remaining, test_size=.50, random_state=R_SEED+1)
r_sx = StandardScaler().fit(r_X[r_train])
r_sy = StandardScaler().fit(r_y[r_train, None])
r_Xtr = torch.tensor(r_sx.transform(r_X[r_train]), dtype=torch.float32)
r_Ytr = torch.tensor(r_sy.transform(r_y[r_train, None]), dtype=torch.float32)
r_Xva = torch.tensor(r_sx.transform(r_X[r_valid]), dtype=torch.float32)
r_Yva = torch.tensor(r_sy.transform(r_y[r_valid, None]), dtype=torch.float32)
r_split_table = pd.DataFrame({'Split': ['Train', 'Validation', 'Test'],
'Rows': [len(r_train), len(r_valid), len(r_test)]})
display(r_split_table)
print(f'Training target mean = {r_sy.mean_[0]:.4f} dB; SD = {r_sy.scale_[0]:.4f} dB')
print('All three split-index sets are disjoint:',
not (set(r_train)&set(r_valid) or set(r_train)&set(r_test) or set(r_valid)&set(r_test)))
r_labels = ['Frequency (Hz)', 'Angle of attack (deg)', 'Chord length (m)',
'Free-stream speed (m/s)', 'Displacement thickness (m)',
'Scaled sound pressure (dB)']
fig, axes = plt.subplots(2, 3, figsize=(11, 6))
for j, ax in enumerate(axes.flat):
ax.hist(r_data[r_train, j], bins=24, edgecolor='white')
ax.set(xlabel=r_labels[j], ylabel='Training rows')
fig.suptitle('Explore training data only: marginal distributions')
fig.tight_layout(); plt.show()
fig, axes = plt.subplots(1, 3, figsize=(11, 3.5))
for ax, i, j in zip(axes, [1, 3, 0], [4, 2, 5]):
ax.scatter(r_data[r_train, i], r_data[r_train, j], s=12, alpha=.35)
ax.set(xlabel=r_labels[i], ylabel=r_labels[j])
ax.grid(alpha=.2)
fig.suptitle('Training data: joint support and a response relationship')
fig.tight_layout(); plt.show()
The reference is the \(5\rightarrow20\rightarrow1\) tanh network, trained by Adam with batch size 50, learning rate 0.01, and \(\lambda=0\). We vary one choice at a time: batch size in \(\{10,25,50,100\}\), learning rate in \(\{0.001,0.01,0.1\}\), or \(\lambda\) in \(\{0,10^{-6},10^{-3}\}\). The shared reference is fitted only once. We also fit a larger network with five hidden layers of 100 tanh units each, using the reference training settings. This gives nine runs.
Every run completes exactly 120 epochs, an epoch being one pass through the training rows. The code restores that run’s lowest-validation-MSE checkpoint, then selects the candidate with the lowest validation MSE. The MSE curves exclude the penalty. Matching architectures start with identical parameters and receive the same row permutation each epoch; batching and the number of optimizer updates still differ. This is a bounded comparison using one initialization and one split, not an exhaustive hyperparameter search. The test labels do not enter selection.
R_EPOCHS = 120
def r_network(large=False):
widths = [5]+([100]*5 if large else [20])+[1]
layers = []
for j in range(len(widths)-1):
layers.append(torch.nn.Linear(widths[j], widths[j+1]))
if j < len(widths)-2:
layers.append(torch.nn.Tanh())
return torch.nn.Sequential(*layers)
def r_fit(batch, lr, penalty, large=False):
# Reset both sources of randomness: matching architectures start identically,
# and every candidate receives the same shuffled row order in each epoch.
torch.manual_seed(R_SEED)
net = r_network(large)
optimizer = torch.optim.Adam(net.parameters(), lr=lr)
generator = torch.Generator().manual_seed(R_SEED+10)
history, best_mse, best_epoch, steps = [], np.inf, 0, 0
for epoch in range(1, R_EPOCHS+1):
net.train()
order = torch.randperm(len(r_Xtr), generator=generator)
for ids in order.split(batch):
optimizer.zero_grad()
mse = torch.mean((net(r_Xtr[ids])-r_Ytr[ids])**2)
l2 = sum(torch.sum(p*p) for p in net.parameters())
loss = mse+penalty*l2 # All weights AND biases; no factor 1/2.
if not torch.isfinite(loss):
raise RuntimeError('Non-finite training loss; do not use this run.')
loss.backward()
optimizer.step()
steps += 1
net.eval()
with torch.no_grad():
tr_mse = float(torch.mean((net(r_Xtr)-r_Ytr)**2))
va_mse = float(torch.mean((net(r_Xva)-r_Yva)**2))
history.append([tr_mse, va_mse])
if va_mse < best_mse:
best_mse, best_epoch = va_mse, epoch
best_state = copy.deepcopy(net.state_dict())
net.load_state_dict(best_state)
net.eval()
return {'model': net, 'history': np.asarray(history), 'best_epoch': best_epoch,
'validation_mse': best_mse, 'updates': steps,
'parameters': sum(p.numel() for p in net.parameters())}
# Predeclared one-factor-at-a-time comparisons. The reference occurs only once.
r_specs = [
('Reference', 50, .01, 0., False),
('Batch 10', 10, .01, 0., False),
('Batch 25', 25, .01, 0., False),
('Batch 100', 100, .01, 0., False),
('Rate 0.001', 50, .001, 0., False),
('Rate 0.1', 50, .1, 0., False),
('L2 1e-6', 50, .01, 1e-6, False),
('L2 1e-3', 50, .01, 1e-3, False),
('Large network', 50, .01, 0., True),
]
r_runs = {name: r_fit(batch, lr, penalty, large)
for name, batch, lr, penalty, large in r_specs}
r_candidate_table = pd.DataFrame([
{'Candidate': name, 'Batch': batch, 'Learning rate': lr, 'L2 coefficient': penalty,
'Parameters': r_runs[name]['parameters'], 'Updates': r_runs[name]['updates'],
'Restored epoch': r_runs[name]['best_epoch'],
'Validation RMSE (dB)': np.sqrt(r_runs[name]['validation_mse'])*r_sy.scale_[0]}
for name, batch, lr, penalty, large in r_specs])
display(r_candidate_table.round(5))
r_selected = min(r_runs, key=lambda name: r_runs[name]['validation_mse'])
r_model = r_runs[r_selected]['model']
print('Selected from validation data:', r_selected)
print(f'Each candidate completed {R_EPOCHS} epochs; all stopped at this fixed budget.')
print('Validation checkpoints are restored; plotted MSE excludes the L2 penalty.')
r_groups = [
('Batch size', ['Batch 10', 'Batch 25', 'Reference', 'Batch 100']),
('Learning rate', ['Rate 0.001', 'Reference', 'Rate 0.1']),
('L2 coefficient', ['Reference', 'L2 1e-6', 'L2 1e-3']),
('Architecture', ['Reference', 'Large network']),
]
fig, axes = plt.subplots(2, 2, figsize=(11, 7))
for ax, (title, names) in zip(axes.flat, r_groups):
for name in names:
ax.plot(np.arange(1, R_EPOCHS+1), r_runs[name]['history'][:, 1], label=name)
if title == 'Architecture':
ax.plot(np.arange(1, R_EPOCHS+1), r_runs[r_selected]['history'][:, 0],
'k--', alpha=.7, label='Selected: training MSE')
ax.set(xlabel='Epoch', ylabel='MSE (standardized target)', title=title, yscale='log')
ax.legend(fontsize=8); ax.grid(alpha=.2)
fig.suptitle('Validation comparisons; one initialization and one split')
fig.tight_layout(); plt.show()
r_linear = LinearRegression().fit(r_sx.transform(r_X[r_train]), r_y[r_train])
def r_predict(x):
with torch.no_grad():
z = r_model(torch.tensor(r_sx.transform(x), dtype=torch.float32)).numpy()
return r_sy.inverse_transform(z).ravel()
def r_metrics(truth, prediction):
return {'RMSE (dB)': float(np.sqrt(np.mean((truth-prediction)**2))),
'MAE (dB)': float(np.mean(np.abs(truth-prediction)))}
(b) Interpret the training experiments (20 points)#
Explain why the different variable scales motivate standardization and why its statistics must come from the training subset. State the distinct roles of training, validation, and test data.
Use the candidate table and curves to compare batch size, learning rate, regularization, and the larger architecture. Report the selected candidate, its restored epoch, and its validation RMSE. Does the larger network improve this comparison? Explain why equal epoch counts are not equal optimizer-update budgets and why these runs do not identify a universally best setting or prove convergence.
Your answer:
The selected network and its checkpoint are now fixed. The next cell evaluates it and a fixed linear-regression baseline on the test rows. It also draws the requested prediction curves: frequency 2,500 Hz, chord length 0.1 m, displacement thickness 0.01 m, angles of attack \(0^\circ\), \(5^\circ\), and \(10^\circ\), with velocity spanning the training range.
For each point on a curve, the code measures the distance to its nearest training input in standardized five-dimensional space. The reference line is the 95th percentile of the distances from each training row to its nearest other training row. This is a descriptive indication of sparse joint support, not a calibrated uncertainty estimate or an error bound. Being inside every input’s individual range does not ensure a well-sampled combination of inputs.
# Freeze the selected candidate and restored checkpoint before this cell.
r_predictions = {'Linear': r_linear.predict(r_sx.transform(r_X[r_test])),
'Selected neural': r_predict(r_X[r_test])}
r_test_table = pd.DataFrame([{'Model': name, **r_metrics(r_y[r_test], pred)}
for name, pred in r_predictions.items()])
display(r_test_table.round(4))
r_reduction = 100*(1-r_test_table.iloc[1]['RMSE (dB)']/r_test_table.iloc[0]['RMSE (dB)'])
print(f'Test RMSE reduction relative to linear regression: {r_reduction:.2f}%')
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.6))
r_limits = [r_y[r_test].min()-2, r_y[r_test].max()+2]
for name, pred in r_predictions.items():
axes[0].scatter(r_y[r_test], pred, s=16, alpha=.6, label=name)
axes[1].scatter(pred, r_y[r_test]-pred, s=16, alpha=.6, label=name)
axes[0].plot(r_limits, r_limits, 'k--', lw=1)
axes[1].axhline(0, color='gray')
axes[0].set(xlabel='Observed (dB)', ylabel='Predicted (dB)', title='Final test predictions')
axes[1].set(xlabel='Predicted (dB)', ylabel='Observed − predicted (dB)', title='Final test residuals')
for ax in axes:
ax.legend(fontsize=9); ax.grid(alpha=.2)
fig.tight_layout(); plt.show()
# A descriptive support check uses ONLY training inputs to define the reference.
# This is a distance, not a calibrated uncertainty or error bound.
r_neighbors = NearestNeighbors(n_neighbors=2).fit(r_sx.transform(r_X[r_train]))
r_training_nn = r_neighbors.kneighbors(return_distance=True)[0][:, 0]
# kneighbors(X=None) excludes each training row itself.
r_support_cutoff = float(np.quantile(r_training_nn, .95))
r_speed = np.linspace(r_X[r_train, 3].min(), r_X[r_train, 3].max(), 100)
r_curve_rows = []
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
for angle in [0, 5, 10]:
x_curve = np.column_stack([np.full(100, 2500.), np.full(100, angle),
np.full(100, .1), r_speed, np.full(100, .01)])
prediction = r_predict(x_curve)
distances = r_neighbors.kneighbors(r_sx.transform(x_curve), n_neighbors=1,
return_distance=True)[0].ravel()
axes[0].plot(r_speed, prediction, label=f'{angle}°')
axes[1].plot(r_speed, distances, label=f'{angle}°')
r_curve_rows.append({'Angle (deg)': angle, 'Min prediction (dB)': float(prediction.min()),
'Max prediction (dB)': float(prediction.max()),
'Min distance': float(distances.min()),
'Max distance': float(distances.max()),
'Above support cutoff (%)': float(100*np.mean(distances>r_support_cutoff)),
'Increasing at every grid step': bool(np.all(np.diff(prediction)>0))})
axes[0].set(xlabel='Free-stream speed (m/s)', ylabel='Scaled sound pressure (dB)',
title='Selected network: requested prediction curves')
axes[1].axhline(r_support_cutoff, color='black', ls=':', label='Training NN 95th percentile')
axes[1].set(xlabel='Free-stream speed (m/s)', ylabel='Nearest training distance',
title='Support in standardized five-input space')
for ax in axes:
ax.legend(fontsize=8); ax.grid(alpha=.2)
fig.tight_layout(); plt.show()
r_curve_table = pd.DataFrame(r_curve_rows)
display(r_curve_table.round(4))
print(f'Training nearest-neighbor 95th-percentile distance = {r_support_cutoff:.4f}')
print('Distances above this descriptive cutoff flag sparse joint support;')
print('they are not a statistical test, prediction interval, or error guarantee.')
r_audit = {
'sha256': hashlib.sha256(r_raw).hexdigest(),
'split_sizes': [len(r_train), len(r_valid), len(r_test)],
'training_target_mean': float(r_sy.mean_[0]), 'training_target_sd': float(r_sy.scale_[0]),
'epochs_per_candidate': R_EPOCHS,
'candidates': r_candidate_table.to_dict('records'), 'selected': r_selected,
'test': r_test_table.to_dict('records'), 'rmse_reduction_percent': float(r_reduction),
'curves': r_curve_rows, 'support_cutoff': r_support_cutoff,
'training_speed_range': [float(r_speed.min()), float(r_speed.max())],
'maximum_neural_test_absolute_error': float(np.max(np.abs(r_y[r_test]-r_predictions['Selected neural']))),
}
(c) Assess predictions and their limits (20 points)#
Report the two test RMSEs and MAEs in dB, and calculate the percentage reduction in RMSE relative to the linear baseline, \(100(1-\mathrm{RMSE}_{\mathrm{neural}}/\mathrm{RMSE}_{\mathrm{linear}})\); a negative value means an increase. Use the prediction/residual plots to qualify the aggregate comparison.
Describe how the predicted sound level changes with airspeed for the three angles. Using the distance plot or table, assess support for these curves. Does a smooth or increasing prediction curve establish the physical trend or its reliability? Name a validation design needed before using the model in a new experimental regime. Keep the fitted models fixed after inspecting the test results.
Your answer:
Problem 2: Recognizing activity from floor vibrations (50 points)#
Credit: Activity-classification problem contributed by Dr. Ali Lenjani, based on the joint study by Lenjani, Dyke, Bilionis, Yeum, Choi, Lund, and Maghareh, Hierarchical Convolutional Neural Networks Information Fusion for Activity Source Detection in Smart Buildings (2019). The measurements come from the Human Activity Benchmark of Madarshahian, Caicedo, and Arocha Zambrana, Benchmark problem for human activity identification using floor vibrations (2016). We use the course’s repackaged archive. The compact models, preprocessing, evaluation split, and questions here are a classroom adaptation, not a reproduction of either paper’s results.
Four sensors record the floor vibration from an event. We first classify its broad type—bag, ball, or jump—and then its detailed type: bag-high, bag-low, ball-high, ball-low, d-jump, j-jump, or w-jump. The high/low labels distinguish drop conditions; the three jump labels identify the three participants represented in this dataset.
There are 4,025 events, each with four simultaneous sensor traces of 3,305 samples. Each of the seven detailed classes has 115 events at each of five locations. The four traces of an event stay together in the same subset. Physical amplitude units and sampling rate are not documented in this archive, so plots use stored amplitude units and sample index.
(a) Calculate class probabilities and cross-entropy (10 points)#
Work this part by hand. A three-class network returns logits \(\mathbf z=(\log 2,0,0)\) in the order (bag, ball, jump). The probabilities and single-event cross-entropy are
where \(y\) is the true class and \(\log\) is the natural logarithm. Calculate all three probabilities, the predicted class, and the loss if the true class is (i) bag and (ii) ball. Explain the difference between these two losses. Does the largest probability make this prediction certain or establish that the probabilities are calibrated?
Your answer:
The split is fixed at approximately 70% training, 15% validation, and 15% test, stratified by the combination of detailed class and location. Every split therefore contains all five locations. This tests held-out events from represented classes and locations, rather than transfer to an unseen location.
To keep CPU computation manageable, the code averages each consecutive block of five samples, reducing each trace from 3,305 to 661 values. This retains a coarse signal shape while discarding some fast temporal detail. It then uses one training-only mean and standard deviation per sensor, computed across training events and sample positions. The same transformation is applied to validation and test events. There is no separate normalization of each event, so relative event amplitudes are retained.
The supplied CNN uses eight length-9 filters with stride 2 (moving two positions between filter evaluations), followed by max pooling by 5, sixteen length-5 filters followed by max pooling by 4, a 32-unit dense hidden layer, and a three- or seven-logit output. Hidden activations are ReLU. Adam uses learning rate \(10^{-3}\), weight decay \(10^{-5}\), and batches of 64. Each classifier runs for at most 20 epochs, stops after eight epochs without a validation-cross-entropy improvement greater than \(10^{-6}\), and restores its best saved checkpoint. The plotted cross-entropies exclude the optimizer’s penalty. All settings are fixed before test evaluation.
from pathlib import Path
from urllib.request import urlopen
from copy import deepcopy
import hashlib
import json
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score, balanced_accuracy_score
from IPython.display import display
ACTIVITY_SEED = 53992
ACTIVITY_URL = ('https://www.dropbox.com/scl/fi/g2qpm6gp8wz5kdza32u7g/'
'human_activity_data.npz?rlkey=2yox5b3wty3oe8f5hejyanxeo&dl=1')
ACTIVITY_SHA256 = 'be93a2fa01110046bbaf175e3bb772ca4ff0c69e31b61db47a6d50846eea3b3f'
activity_file = Path('human_activity_data.npz')
if not activity_file.exists():
with urlopen(ACTIVITY_URL, timeout=120) as activity_response:
activity_bytes = activity_response.read()
if hashlib.sha256(activity_bytes).hexdigest() != ACTIVITY_SHA256:
raise ValueError('Activity data checksum mismatch; contact the teaching team.')
activity_file.write_bytes(activity_bytes)
del activity_bytes
activity_digest = hashlib.sha256(activity_file.read_bytes()).hexdigest()
if activity_digest != ACTIVITY_SHA256:
raise ValueError('Activity data checksum mismatch; contact the teaching team.')
with np.load(activity_file, allow_pickle=False) as activity_archive:
activity_raw = activity_archive['features'].copy()
activity_y_coarse = activity_archive['labels_1'].copy()
activity_y_fine = activity_archive['labels_2'].copy()
activity_locations = activity_archive['loc_ids'].copy()
assert activity_raw.shape == (4025, 4, 3305)
assert np.isfinite(activity_raw).all()
activity_coarse_names = ['bag', 'ball', 'jump']
activity_fine_names = ['bag-high', 'bag-low', 'ball-high', 'ball-low', 'd-jump', 'j-jump', 'w-jump']
activity_fine_to_coarse = np.array([0, 0, 1, 1, 2, 2, 2])
assert np.array_equal(activity_fine_to_coarse[activity_y_fine], activity_y_coarse)
# Fixed block averaging reduces 3305 samples to 661, at the cost of fast details.
activity_signals = activity_raw.reshape(4025, 4, 661, 5).mean(axis=-1)
del activity_raw
activity_all = np.arange(len(activity_y_fine))
activity_strata = 5 * activity_y_fine + activity_locations
activity_train, activity_holdout = train_test_split(activity_all, test_size=0.30,
random_state=ACTIVITY_SEED, stratify=activity_strata)
activity_valid, activity_test = train_test_split(activity_holdout, test_size=0.50,
random_state=ACTIVITY_SEED + 1, stratify=activity_strata[activity_holdout])
# Training-only sensor-wise scaling preserves between-event amplitude differences.
activity_mean = activity_signals[activity_train].mean(axis=(0, 2), keepdims=True)
activity_sd = activity_signals[activity_train].std(axis=(0, 2), keepdims=True)
activity_x = (activity_signals - activity_mean) / activity_sd
activity_x_t = torch.tensor(activity_x, dtype=torch.float32)
activity_labels = {'coarse': activity_y_coarse, 'fine': activity_y_fine}
activity_names = {'coarse': activity_coarse_names, 'fine': activity_fine_names}
activity_split_table = pd.DataFrame([
{'split': name, 'events': len(ids), 'locations present': ', '.join(map(str, sorted(set(activity_locations[ids]))))}
for name, ids in [('training', activity_train), ('validation', activity_valid), ('test', activity_test)]])
display(activity_split_table)
display(pd.DataFrame({'class': activity_coarse_names, 'all events': np.bincount(activity_y_coarse),
'training': np.bincount(activity_y_coarse[activity_train]),
'validation': np.bincount(activity_y_coarse[activity_valid]), 'test': np.bincount(activity_y_coarse[activity_test])}))
activity_figures = []
activity_example = activity_train[0]
activity_fig, activity_axes = plt.subplots(4, 1, figsize=(9, 6), sharex=True, constrained_layout=True)
for activity_sensor, activity_ax in enumerate(activity_axes):
activity_ax.plot(np.arange(661), activity_signals[activity_example, activity_sensor], lw=0.9)
activity_ax.set_ylabel(f'Sensor {activity_sensor + 1}')
activity_axes[0].set_title(f'Training {activity_fine_names[activity_y_fine[activity_example]]} event: block-averaged signals (source units unspecified)')
activity_axes[-1].set_xlabel('Block index (5 original samples per block)')
activity_figures.append(activity_fig)
plt.show()
A one-dimensional convolutional neural network (CNN) applies the same short learned filters along the sensor traces, pools nearby responses, and passes the resulting features to dense layers. Sharing filters allows a local signal pattern to be detected at different positions. Pooling can reduce sensitivity to small shifts; it does not guarantee exact translation invariance or reliable transfer to a new building. The final layer returns three or seven logits. No CNN implementation or convolution derivation is required.
The two classifiers use a predeclared architecture and training schedule. Checkpoints are selected separately using validation cross-entropy. Training and validation curves are shown before test evaluation; the final test results below do not select architectures, settings, or checkpoints.
torch.set_num_threads(2)
torch.use_deterministic_algorithms(True)
class ActivityCNN(nn.Module):
def __init__(self, num_classes):
super().__init__()
self.features = nn.Sequential(nn.Conv1d(4, 8, 9, stride=2, padding=4), nn.ReLU(), nn.MaxPool1d(5),
nn.Conv1d(8, 16, 5, padding=2), nn.ReLU(), nn.MaxPool1d(4))
self.classifier = nn.Sequential(nn.Flatten(), nn.Linear(16 * 16, 32), nn.ReLU(), nn.Linear(32, num_classes))
def forward(self, x):
return self.classifier(self.features(x)) # unnormalized logits
def activity_evaluate(model, ids, targets):
model.eval()
with torch.no_grad():
logits = torch.cat([model(activity_x_t[ids[i:i + 128]]) for i in range(0, len(ids), 128)])
truth = torch.tensor(targets[ids], dtype=torch.long)
return float(nn.functional.cross_entropy(logits, truth)), float((logits.argmax(1) == truth).float().mean()), logits
def activity_train_model(task):
torch.manual_seed(ACTIVITY_SEED)
model = ActivityCNN(len(activity_names[task]))
targets = activity_labels[task]
target_tensor = torch.tensor(targets, dtype=torch.long)
generator = torch.Generator().manual_seed(ACTIVITY_SEED + 2)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-5)
history, best_loss, best_epoch, best_state, stale = [], float('inf'), 0, None, 0
for epoch in range(1, 21):
model.train()
shuffled = activity_train[torch.randperm(len(activity_train), generator=generator).numpy()]
for start in range(0, len(shuffled), 64):
ids = shuffled[start:start + 64]
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(activity_x_t[ids]), target_tensor[ids])
loss.backward()
optimizer.step()
training_loss, training_accuracy, _ = activity_evaluate(model, activity_train, targets)
validation_loss, validation_accuracy, _ = activity_evaluate(model, activity_valid, targets)
history.append([training_loss, validation_loss, training_accuracy, validation_accuracy])
if validation_loss < best_loss - 1e-6:
best_loss, best_epoch, best_state, stale = validation_loss, epoch, deepcopy(model.state_dict()), 0
else:
stale += 1
if stale >= 8:
break
model.load_state_dict(best_state)
model.eval()
return {'model': model, 'history': np.asarray(history), 'best_epoch': best_epoch,
'validation_cross_entropy': best_loss, 'parameters': sum(p.numel() for p in model.parameters()),
'stopping_reason': 'patience (8 epochs)' if stale >= 8 else 'epoch cap (20)'}
activity_runs = {}
for activity_task in ['coarse', 'fine']:
activity_runs[activity_task] = activity_train_model(activity_task)
print(f"Completed {activity_task} CNN: {len(activity_runs[activity_task]['history'])} epochs; restored epoch {activity_runs[activity_task]['best_epoch']}.", flush=True)
activity_validation_rows = []
activity_fig, activity_axes = plt.subplots(2, 2, figsize=(11, 7), constrained_layout=True)
for activity_row, activity_task in enumerate(['coarse', 'fine']):
activity_run = activity_runs[activity_task]
activity_history = activity_run['history']
activity_epochs = np.arange(1, len(activity_history) + 1)
for activity_col, activity_metric in enumerate(['Cross-entropy', 'Accuracy']):
activity_ax = activity_axes[activity_row, activity_col]
activity_offset = 0 if activity_col == 0 else 2
activity_ax.plot(activity_epochs, activity_history[:, activity_offset], label='training')
activity_ax.plot(activity_epochs, activity_history[:, activity_offset + 1], label='validation')
activity_ax.axvline(activity_run['best_epoch'], color='k', ls=':', label='restored epoch')
activity_ax.set(xlabel='Epoch', ylabel=activity_metric, title=f'{len(activity_names[activity_task])}-class CNN')
activity_ax.legend(fontsize=8)
activity_val_loss, activity_val_accuracy, _ = activity_evaluate(activity_run['model'], activity_valid, activity_labels[activity_task])
activity_validation_rows.append({'task': activity_task, 'parameters': activity_run['parameters'],
'completed epochs': len(activity_history), 'restored epoch': activity_run['best_epoch'],
'stopping reason': activity_run['stopping_reason'], 'validation cross-entropy': activity_val_loss,
'validation accuracy': activity_val_accuracy})
activity_figures.append(activity_fig)
plt.show()
activity_validation_table = pd.DataFrame(activity_validation_rows)
display(activity_validation_table)
For a class, recall is the fraction of events in that true class predicted correctly. Balanced accuracy is the arithmetic mean of the class recalls; ordinary accuracy weights classes by their frequency. In each confusion matrix below, rows are true classes and columns are predicted classes. The annotations give event counts and row percentages, so a row’s diagonal percentage is its recall.
# All choices are frozen. The following test results do not change either model.
activity_test_results = {}
activity_fig, activity_axes = plt.subplots(1, 2, figsize=(12, 5), constrained_layout=True)
for activity_col, activity_task in enumerate(['coarse', 'fine']):
activity_test_loss, _, activity_logits = activity_evaluate(activity_runs[activity_task]['model'], activity_test, activity_labels[activity_task])
activity_prediction = activity_logits.argmax(1).numpy()
activity_truth = activity_labels[activity_task][activity_test]
activity_cm = confusion_matrix(activity_truth, activity_prediction, labels=np.arange(len(activity_names[activity_task])))
activity_recall = np.diag(activity_cm) / activity_cm.sum(axis=1)
activity_normalized_cm = activity_cm / activity_cm.sum(axis=1, keepdims=True)
activity_test_results[activity_task] = {'cross_entropy': activity_test_loss,
'accuracy': accuracy_score(activity_truth, activity_prediction),
'balanced_accuracy': balanced_accuracy_score(activity_truth, activity_prediction),
'confusion_matrix': activity_cm.tolist(), 'recall': activity_recall.tolist(), 'prediction': activity_prediction.tolist()}
activity_ax = activity_axes[activity_col]
activity_image = activity_ax.imshow(activity_normalized_cm, cmap='Blues', vmin=0, vmax=1)
for activity_i in range(len(activity_cm)):
for activity_j in range(len(activity_cm)):
activity_ax.text(activity_j, activity_i, f'{activity_cm[activity_i, activity_j]}\n{activity_normalized_cm[activity_i, activity_j]:.1%}',
ha='center', va='center', fontsize=7, color='white' if activity_normalized_cm[activity_i, activity_j] > .5 else 'black')
activity_ax.set(xticks=np.arange(len(activity_cm)), yticks=np.arange(len(activity_cm)),
xticklabels=activity_names[activity_task], yticklabels=activity_names[activity_task],
xlabel='Predicted label', ylabel='True label', title=f'{len(activity_cm)}-class test confusion: count and row %')
activity_ax.tick_params(axis='x', labelrotation=45)
activity_fig.colorbar(activity_image, ax=activity_axes, label='Fraction within each true class', shrink=.75)
activity_figures.append(activity_fig)
plt.show()
activity_collapsed_prediction = activity_fine_to_coarse[np.asarray(activity_test_results['fine']['prediction'])]
activity_collapsed_accuracy = accuracy_score(activity_y_coarse[activity_test], activity_collapsed_prediction)
activity_collapsed_balanced = balanced_accuracy_score(activity_y_coarse[activity_test], activity_collapsed_prediction)
activity_metric_rows = [{'task': task, 'test cross-entropy': result['cross_entropy'],
'test accuracy': result['accuracy'], 'test balanced accuracy': result['balanced_accuracy']}
for task, result in activity_test_results.items()]
activity_metric_rows.append({'task': 'fine prediction collapsed to coarse', 'test cross-entropy': np.nan,
'test accuracy': activity_collapsed_accuracy, 'test balanced accuracy': activity_collapsed_balanced})
display(pd.DataFrame(activity_metric_rows).round(5))
for activity_task in ['coarse', 'fine']:
display(pd.DataFrame({'class': activity_names[activity_task], 'test count': np.bincount(activity_labels[activity_task][activity_test]),
'test recall': activity_test_results[activity_task]['recall']}))
activity_majority_accuracy = float(np.mean(activity_y_coarse[activity_test] == 2))
print(f'Always predicting jump: test accuracy {activity_majority_accuracy:.5f}, balanced accuracy {1/3:.5f}.')
activity_audit = {'source_url': ACTIVITY_URL, 'sha256': activity_digest, 'raw_shape': [4025, 4, 3305],
'processed_shape': list(activity_signals.shape),
'split_counts': {'train': len(activity_train), 'validation': len(activity_valid), 'test': len(activity_test)},
'sensor_training_means': activity_mean.ravel().tolist(), 'sensor_training_sd': activity_sd.ravel().tolist(),
'validation': activity_validation_rows, 'test': activity_test_results,
'collapsed_fine_accuracy': activity_collapsed_accuracy, 'collapsed_fine_balanced_accuracy': activity_collapsed_balanced,
'majority_baseline_accuracy': activity_majority_accuracy,
'coarse_test_counts': np.bincount(activity_y_coarse[activity_test]).tolist(),
'fine_test_counts': np.bincount(activity_y_fine[activity_test]).tolist(),
'locations_in_each_split': {name: sorted(map(int, np.unique(activity_locations[ids])))
for name, ids in [('train', activity_train), ('validation', activity_valid), ('test', activity_test)]}}
(b) Assess broad activity classification (20 points)#
Report the training, validation, and test event counts and the coarse classifier’s restored epoch. Briefly describe what the loss/accuracy curves show about training and validation.
Report coarse test accuracy, balanced accuracy, and each class’s recall. Identify the largest off-diagonal count in the coarse confusion matrix and explain what it means. Compare against always predicting the most frequent training class. Why are the four sensor traces not four independent test examples, and why is overall accuracy alone insufficient for these class proportions?
Your answer:
(c) Assess detailed activity classification (20 points)#
Report the seven-class test accuracy, balanced accuracy, and lowest class recall. Identify the largest off-diagonal count in its confusion matrix. Describe whether the errors mainly confuse members of the same broad class or different broad classes, using the displayed counts.
The supplied table also maps the seven-class model’s predicted labels back to bag, ball, or jump. Compare that collapsed accuracy with the directly trained three-class classifier’s accuracy. Does finer classification necessarily provide better broad classification in this run?
All five locations occur in each subset. Explain what this limits about the conclusion, and propose a split that would assess transfer to a new location. Would that split also establish performance in a new building or for previously unseen people?
Your answer: