Upload mandelbrot_approximation.py
Browse filesI trained a neural network to learn the fractal shape from pixel coordinates using PyTorch, NumPy, and Matplotlib. This isn’t curve-fitting. This is pure function learning.
- Added positional encodings to represent spatial patterns
- Increased epochs and depth for better generalization
- And tuned resolution + loss functions
The model approximated the Mandelbrot set with stunning accuracy, no image inputs, just math.

- mandelbrot_approximation.py +129 -0
mandelbrot_approximation.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""mandelbrot-approximation.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1M-DGWstZXLQZdi3hkl_r5P-oSiTcSSLA
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
def mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iter=100):
|
| 13 |
+
|
| 14 |
+
x = np.linspace(xmin, xmax, width)
|
| 15 |
+
y = np.linspace(ymin, ymax, height)
|
| 16 |
+
|
| 17 |
+
X, Y = np.meshgrid(x, y)
|
| 18 |
+
C = X + 1j * Y
|
| 19 |
+
|
| 20 |
+
iterations = np.zeros_like(C, dtype=np.float32)
|
| 21 |
+
Z = np.zeros_like(C)
|
| 22 |
+
mask = np.full(C.shape, True, dtype=bool)
|
| 23 |
+
|
| 24 |
+
for i in range(max_iter):
|
| 25 |
+
Z[mask] = Z[mask]**2 + C[mask]
|
| 26 |
+
escaped = np.abs(Z) > 2
|
| 27 |
+
iterations[escaped & mask] = i / max_iter
|
| 28 |
+
mask[escaped] = False
|
| 29 |
+
|
| 30 |
+
labels = iterations
|
| 31 |
+
return X, Y, labels
|
| 32 |
+
|
| 33 |
+
def add_positional_encoding(X):
|
| 34 |
+
x, y = X[:, 0], X[:, 1]
|
| 35 |
+
encoded = np.stack([
|
| 36 |
+
x, y,
|
| 37 |
+
np.sin(2 * np.pi * x), np.cos(2 * np.pi * x),
|
| 38 |
+
np.sin(2 * np.pi * y), np.cos(2 * np.pi * y)
|
| 39 |
+
], axis=1)
|
| 40 |
+
return encoded
|
| 41 |
+
|
| 42 |
+
X, Y, labels = mandelbrot_set(-1.5, -0.8, -0.2, 0.2, 1000, 1000)
|
| 43 |
+
X_train = np.stack([X.ravel(), Y.ravel()], axis=1)
|
| 44 |
+
X_train_encoded = add_positional_encoding(X_train)
|
| 45 |
+
y_train = labels.ravel()
|
| 46 |
+
|
| 47 |
+
mask = (y_train > 0.05) & (y_train < 0.95)
|
| 48 |
+
X_train_boundary = X_train[mask]
|
| 49 |
+
y_train_boundary = y_train[mask]
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
import torch.nn as nn
|
| 53 |
+
import torch.optim as optim
|
| 54 |
+
from torch.optim.lr_scheduler import StepLR
|
| 55 |
+
from torch.utils.data import TensorDataset, DataLoader
|
| 56 |
+
import matplotlib.pyplot as plt
|
| 57 |
+
|
| 58 |
+
X_train_encoded = add_positional_encoding(X_train)
|
| 59 |
+
X_tensor = torch.tensor(X_train_encoded, dtype=torch.float32)
|
| 60 |
+
y_tensor = torch.tensor(y_train, dtype=torch.float32)
|
| 61 |
+
|
| 62 |
+
dataset = TensorDataset(X_tensor, y_tensor)
|
| 63 |
+
loader = DataLoader(dataset, batch_size = 1024, shuffle = True)
|
| 64 |
+
|
| 65 |
+
class MandelbrotNet(nn.Module):
|
| 66 |
+
def __init__(self):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.model = nn.Sequential(
|
| 69 |
+
nn.Linear(6, 256),
|
| 70 |
+
nn.ReLU(),
|
| 71 |
+
*[layer for _ in range(6) for layer in (nn.Linear(256, 256), nn.ReLU())],
|
| 72 |
+
nn.Linear(256, 1),
|
| 73 |
+
nn.Identity()
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
def forward(self, x):
|
| 77 |
+
return self.model(x)
|
| 78 |
+
|
| 79 |
+
model = MandelbrotNet()
|
| 80 |
+
criterion = nn.MSELoss()
|
| 81 |
+
optimizer = optim.Adam(model.parameters(), lr=1e-3)
|
| 82 |
+
scheduler = StepLR(optimizer, step_size=30, gamma=0.5)
|
| 83 |
+
|
| 84 |
+
epochs = 100
|
| 85 |
+
losses = []
|
| 86 |
+
|
| 87 |
+
for epoch in range(epochs):
|
| 88 |
+
total_loss = 0.0
|
| 89 |
+
for batch_X, batch_y in loader:
|
| 90 |
+
preds = model(batch_X)
|
| 91 |
+
loss = criterion(preds, batch_y.unsqueeze(1))
|
| 92 |
+
optimizer.zero_grad()
|
| 93 |
+
loss.backward()
|
| 94 |
+
optimizer.step()
|
| 95 |
+
|
| 96 |
+
total_loss += loss.item()
|
| 97 |
+
|
| 98 |
+
scheduler.step()
|
| 99 |
+
avg_loss = total_loss / len(loader)
|
| 100 |
+
losses.append(avg_loss)
|
| 101 |
+
print(f"Epoch {epoch+1}/{epochs}, Loss: {avg_loss:.4f}")
|
| 102 |
+
|
| 103 |
+
plt.plot(losses)
|
| 104 |
+
plt.title("Training Loss")
|
| 105 |
+
plt.xlabel("Epoch")
|
| 106 |
+
plt.ylabel("MSE Loss")
|
| 107 |
+
plt.grid(True)
|
| 108 |
+
plt.show()
|
| 109 |
+
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
y_pred = model(X_tensor).squeeze().numpy()
|
| 112 |
+
|
| 113 |
+
# Reshape to image grid
|
| 114 |
+
pred_image = y_pred.reshape(X.shape) # shape: (height, width)
|
| 115 |
+
true_image = labels
|
| 116 |
+
fig, axs = plt.subplots(1, 2, figsize=(12, 5))
|
| 117 |
+
|
| 118 |
+
axs[0].imshow(true_image, cmap='inferno', extent=[-2, 1, -1.5, 1.5])
|
| 119 |
+
axs[0].set_title("Ground Truth Mandelbrot Set")
|
| 120 |
+
|
| 121 |
+
axs[1].imshow(pred_image, cmap='inferno', extent=[-2, 1, -1.5, 1.5])
|
| 122 |
+
axs[1].set_title("Model Approximation (DL)")
|
| 123 |
+
|
| 124 |
+
for ax in axs:
|
| 125 |
+
ax.set_xlabel("Re")
|
| 126 |
+
ax.set_ylabel("Im")
|
| 127 |
+
|
| 128 |
+
plt.tight_layout()
|
| 129 |
+
plt.show()
|