Repository navigation
Expand file tree
/
Copy pathxor_example.py
More file actions
123 lines (96 loc) · 3.55 KB
/
Copy pathxor_example.py
File metadata and controls
123 lines (96 loc) · 3.55 KB
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
import numpy as np
from nn.layers.activations import ReLU, Sigmoid
from nn.layers.linear import Linear
from nn.loss import MSELoss
from nn.model import Sequential
from nn.optim import SGD
def train_model(
model, criterion, optimizer, x, y, epochs=1000, batch_size=32, print_every=100
):
"""
Train a neural network model on the provided data.
Args:
model: The neural network model to train
criterion: Loss function
optimizer: Optimization algorithm
x: Input features
y: Target values
epochs: Number of training epochs
batch_size: Size of mini-batches
print_every: How often to print training progress
Returns:
model: The trained model
losses: List of losses during training
"""
losses = []
num_samples = len(x)
num_batches = (num_samples + batch_size - 1) // batch_size # Ceiling division
for epoch in range(epochs):
epoch_loss = 0.0
# Shuffle data at the beginning of each epoch
indices = np.random.permutation(num_samples)
x_shuffled = x[indices]
y_shuffled = y[indices]
# Process mini-batches
for i in range(num_batches):
# Get mini-batch
start_idx = i * batch_size
end_idx = min((i + 1) * batch_size, num_samples)
batch_x = x_shuffled[start_idx:end_idx]
batch_y = y_shuffled[start_idx:end_idx]
# Forward pass
outputs = model(batch_x)
loss = criterion(outputs, batch_y)
# Backward pass
grad_output = criterion.backward()
model.backward(grad_output)
# Update weights
optimizer.step()
# Accumulate loss
epoch_loss += loss
# Calculate average loss for the epoch
avg_loss = epoch_loss / num_batches
losses.append(avg_loss)
# Print progress
if (epoch + 1) % print_every == 0:
print(f"Epoch [{epoch+1}/{epochs}], Loss: {avg_loss:.6f}")
return model, losses
def xor_example():
# Generate some simple data
input_size = 2
hidden_size = 4
output_size = 1
num_samples = 100
# Create XOR-like data
x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32)
y = np.array([[0], [1], [1], [0]], dtype=np.float32)
# Repeat data to create more samples
x = np.tile(x, (num_samples // 4 + 1, 1))[:num_samples]
y = np.tile(y, (num_samples // 4 + 1, 1))[:num_samples]
# Add some noise to make it more realistic
x += np.random.normal(0, 0.05, x.shape).astype(np.float32)
# Create a simple model with named layers
model = Sequential(
[
Linear(input_size, hidden_size, name="layer1"),
ReLU(),
Linear(hidden_size, hidden_size, name="layer2"),
ReLU(),
Linear(hidden_size, output_size, name="layer3"),
Sigmoid(),
]
)
# Prepare loss function and optimizer
criterion = MSELoss()
optimizer = SGD(model, learning_rate=0.1, momentum=0.9)
# Train the model
print("Starting training...")
trained_model, losses = train_model(model, criterion, optimizer, x, y, epochs=1000)
print("\nFinal predictions:")
test_inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32)
predictions = model(test_inputs)
print("Input => Output (Expected)")
for i in range(4):
print(f"{test_inputs[i].tolist()} => {predictions[i][0]:.4f} ({y[i%4][0]})")
print("\nTraining complete!")
print(f"Final loss: {losses[-1]}")