Skip to main content

11.11 Neural-network code sketches

Source: Structural ideas from Computational Physics (Landau, Páez, Bordeianu), §11.10 listings. Original sketches only — do not paste Neuron.py, SimpleNet.py, KmeansCluster.py, Keras.py, or VPython/OpenCV path dumps. Continues 11.10.

Graded arithmetic lives in 11.1b–11.9b. This page maps how pieces fit in a local notebook.

Single sigmoid neuron​

# neuron_sketch.py — original structure
import math

def sigmoid(z):
return 1.0 / (1.0 + math.exp(-z))

class Neuron:
def __init__(self, weights, bias=0.0):
self.weights = list(weights)
self.bias = bias

def feedforward(self, inputs):
s = self.bias + sum(w * x for w, x in zip(self.weights, inputs))
return sigmoid(s)

# n = Neuron([-1.0, 1.0], 0.0); print(n.feedforward([12.0, 8.0])) # ≈ 0.017986

Shallow 2–2–1 net​

# shallow_net_sketch.py — original structure
class NeuralNetwork:
def __init__(self):
w = [0.0, 1.0]
self.h1 = Neuron(w)
self.h2 = Neuron(w)
self.out = Neuron(w)

def feedforward(self, x):
a = self.h1.feedforward(x)
b = self.h2.feedforward(x)
return self.out.feedforward([a, b])

# network.feedforward([2.0, 3.0]) ≈ 0.7216

Train loop (MSE + backprop)​

Random-init weights; for each epoch and sample: forward → ∂L\partial\mathcal{L} chain rule → w←w−η∂L/∂ww\leftarrow w-\eta\partial\mathcal{L}/\partial w. Print Loss every few epochs. (Details in 11.3.)

kk-means on (index,mass)(index, mass)​

# kmeans_sketch.py — structure
# X = [[i+1, mass_i], ...]
# init k centroids; assign; update means; scatter by label
# sklearn: KMeans(n_clusters=3, random_state=42).fit(X)

Keras one-unit Dense​

# keras_dense_sketch.py — local TF only
# model = Sequential([Dense(1, input_shape=[1])])
# model.compile(loss="mse", optimizer=Adam(...))
# model.fit(r, v, epochs=2000, verbose=0)

Visualization note​

Book listings mix NumPy, Matplotlib, Pandas paths, and GUIs. Keep the math; swap display layers. This course grades stdout locks, not CDN screenshots.

Takeaway​

SketchSection
Neuron / 2–2–1§11.2
SimpleNet train§11.3
kk-means / Perceptron / SGD§11.7
Keras Dense§11.8
OpenCV hist / MOG2§11.9
Quiz

NN code sketches

1 / 3

A single sigmoid neuron computes…

Pick an answer to see if you are right.

Next: 11.11b NN sketch labs.