# Generate synthetic sensor data
# Normal: temp 20-40, vibration 0.5-2.0
temp_normal = np.random.uniform(20, 40, n_samples // 3)
vib_normal = np.random.uniform(0.5, 2.0, n_samples // 3)
# Warning: temp 35-55, vibration 1.5-4.0
temp_warning = np.random.uniform(35, 55, n_samples // 3)
vib_warning = np.random.uniform(1.5, 4.0, n_samples // 3)
# Critical: temp 50-80, vibration 3.5-7.0
temp_critical = np.random.uniform(50, 80, n_samples // 3)
vib_critical = np.random.uniform(3.5, 7.0, n_samples // 3)
np.column_stack([temp_normal, vib_normal]),
np.column_stack([temp_warning, vib_warning]),
np.column_stack([temp_critical, vib_critical]),
y = np.zeros((n_samples, 3))
y[100:200, 1] = 1 # warning
y[200:, 2] = 1 # critical
X_norm = (X - X_mean) / X_std
indices = np.random.permutation(n_samples)
# Split: 80% train, 20% test
split = int(0.8 * n_samples)
X_train, X_test = X_norm[:split], X_norm[split:]
y_train, y_test = y[:split], y[split:]
exp_z = np.exp(z - np.max(z, axis=1, keepdims=True))
return exp_z / exp_z.sum(axis=1, keepdims=True)
return (z > 0).astype(float)
# Network: 2 inputs -> 16 hidden (ReLU) -> 3 outputs (softmax)
W1 = np.random.randn(2, 16) * 0.3
W2 = np.random.randn(16, 3) * 0.3
for epoch in range(epochs):
# Cross-entropy loss. The 1e-8 is a numerical safety epsilon:
# softmax outputs can be extremely small, and log(0) is -inf.
loss = -np.mean(np.sum(y_train * np.log(a2 + 1e-8), axis=1))
delta2 = (a2 - y_train) / len(y_train)
db2 = np.sum(delta2, axis=0, keepdims=True)
delta1 = (delta2 @ W2.T) * relu_derivative(z1)
db1 = np.sum(delta1, axis=0, keepdims=True)
W1 -= learning_rate * dW1
b1 -= learning_rate * db1
W2 -= learning_rate * dW2
b2 -= learning_rate * db2
preds = np.argmax(a2, axis=1)
targets = np.argmax(y_train, axis=1)
acc = np.mean(preds == targets)
print(f"Epoch {epoch:4d} | Loss: {loss:.4f} | Train Acc: {acc:.2%}")
z1_test = X_test @ W1 + b1
z2_test = a1_test @ W2 + b2
a2_test = softmax(z2_test)
test_preds = np.argmax(a2_test, axis=1)
test_targets = np.argmax(y_test, axis=1)
test_acc = np.mean(test_preds == test_targets)
print(f"\nTest Accuracy: {test_acc:.2%}")
labels = ["Normal", "Warning", "Critical"]
print("\nSample predictions (first 10 test samples):")
pred_label = labels[test_preds[i]]
true_label = labels[test_targets[i]]
confidence = a2_test[i][test_preds[i]]
status = "correct" if test_preds[i] == test_targets[i] else "WRONG"
print(f" Predicted: {pred_label:8s} ({confidence:.2%}) | "
f"Actual: {true_label:8s} | {status}")
Comments