Fix My Tutorial
Report

Implementing a Neural Network from Scratch in Python

Open the original tutorial
Fixed Python 3.12 · checked 17 Oct 2026 · model cost $0.109

After applying the fixes, the tutorial runs successfully under Python 3.12. The original code failed because it lacked necessary imports for numpy, matplotlib and sklearn.datasets, used an undefined plotting function, and contained Python 2 syntax such as print statements without parentheses and xrange. Repairs added the missing imports, defined a plot_decision_boundary helper using a mesh grid and contour plot, and updated all print and range calls to Python 3 syntax.

5 changes to make it work today

Generate dataset and plot

s2 · run_code migrate

Add missing imports for numpy, matplotlib, and sklearn.datasets to fix NameError: name 'np' is not defined.

@@ -1,3 +1,7 @@
# Generate a dataset and plot it
+import numpy as np
+import matplotlib.pyplot as plt
+import sklearn.datasets
+
np.random.seed(0)
X, y = sklearn.datasets.make_moons(200, noise=0.20)

Sources

  • How to Fix: NameError name 'np' is not defined``` #define numpy array x = np.random.normal(loc=0, scale=1, size=20) #attempt to print values in arrary print(x) Traceback (most recent call last): ----> 1 x = np.random.normal(loc=0, scale=1, size=20) 2 print(x) NameError: name 'np' is not defined #define numpy array random normal #attempt to print values in arrary print ----> NameError ```
  • How to Fix: NameError name ‘np’ is not defined - GeeksforGeeksHere np is an alias of the NumPy module so we can either import the NumPy module with the alias or import NumPy without the alias and use the name directly.
  • How To Import Numpy As Np - GeeksforGeeksPython3 ```` import numpy as np # Now you can use np to reference # NumPy functions and objects arr = np. array([1, 2, 3, 4, 5]) print(& quot; Array: & quot;, arr) # Example of using a NumPy #function with the np alias mean_value = np. mean(arr) print(& quot; Mean: & quot;, mean_value) ````

Added by Fix My Tutorial

s2_fix1 · run_code migrate new step

Add the missing plot_decision_boundary function that draws a filled contour of the model's predictions over a grid. It uses the current axes so it can be called after a scatter plot.

+# Define a helper to plot decision boundaries for a prediction function
+def plot_decision_boundary(pred_func, X=X, y=y):
+ x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
+ y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
+ xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
+ np.arange(y_min, y_max, 0.02))
+ Z = pred_func(np.column_stack((xx.ravel(), yy.ravel())))
+ Z = Z.reshape(xx.shape)
+ plt.contourf(xx, yy, Z, alpha=0.8, cmap=plt.cm.Spectral)

Sources

  • Plot classification boundaries with different SVM Kernels — scikit-learn 1.9.1 documentationfrom sklearn import svm from sklearn.inspection import DecisionBoundaryDisplay def plot_training_data_with_decision_boundary(kernel, ax = None, long_title = True, support_vectors = True): # Train the SVC clf = svm. SVC(kernel = kernel, gamma = 2). fit(X, y) # Settings for plotting if ax is None: _, ax = plt. subplots(figsize =(4, 3)) x_min, x_max, y_min, y_max = - 3, 3, - 3, 3 ax. set(xlim =(x_min, x_max), ylim =(y_min, y_max)) # Plot decision boundary and margins common_params ={"estimator": clf, "X": X, "ax": ax} DecisionBoundaryDisplay. from_estimator( common_params, response_method = "pred

Define build_model

s7 · run_code migrate

Fix Python 2 syntax errors: replace print statement with parentheses, change xrange to range, and replace np.power with a1**2. Also complete the missing gradient descent update and return statement.

@@ -16,5 +16,5 @@
# Gradient descent. For each batch...
- for i in xrange(0, num_passes):
+ for i in range(0, num_passes):
# Forward propagation
@@ -30,5 +30,5 @@
dW2 = (a1.T).dot(delta3)
db2 = np.sum(delta3, axis=0, keepdims=True)
- delta2 = delta3.dot(W2.T) * (1 - np.power(a1, 2))
+ delta2 = delta3.dot(W2.T) * (1 - a1**2)
dW1 = np.dot(X.T, delta2)
db1 = np.sum(delta2, axis=0)
@@ -44,11 +44,10 @@
b2 += -epsilon * db2
- # Assign new parameters to the model
- model = { 'W1': W1, 'b1': b1, 'W2': W2, 'b2': b2}
+ # Assign new parameters to model
+ model = { 'W1': W1, 'b1': b1, 'W2': W2, 'b2': b2 }
# Optionally print the loss.
- # This is expensive because it uses the whole dataset, so we don't want to do it too often.
if print_loss and i % 1000 == 0:
- print "Loss after iteration %i: %f" %(i, calculate_loss(model))
-
+ print("Loss after iteration %d: %f" % (i, calculate_loss(model)))
+
return model

Sources

Build model with hidden layer size 3 and plot

s8 · run_code migrate

Add a scatter plot of the data before drawing the decision boundary, because the new helper only draws the contour.

@@ -2,4 +2,6 @@
model = build_model(3, print_loss=True)
+# Plot the data
+plt.scatter(X[:,0], X[:,1], s=40, c=y, cmap=plt.cm.Spectral)
# Plot the decision boundary
plot_decision_boundary(lambda x: predict(model, x))

Vary hidden layer size and plot

s9 · run_code migrate

In each subplot, first plot the data points then the decision boundary contour.

@@ -5,4 +5,7 @@
plt.title('Hidden Layer size %d' % nn_hdim)
model = build_model(nn_hdim)
+ # Plot the data
+ plt.scatter(X[:,0], X[:,1], s=40, c=y, cmap=plt.cm.Spectral)
+ # Plot the decision boundary
plot_decision_boundary(lambda x: predict(model, x))
plt.show()

Tell the author

Send them what broke and the fix, so the next reader doesn't hit the same error.

Badge

Add it to the tutorial so readers know when it was last checked.

Fix My Tutorial badge
Markdown
[![Fix My Tutorial](https://fix-my-tutorial.onrender.com/badge/ri-wVF3z-yS.svg)](https://fix-my-tutorial.onrender.com/r/ri-wVF3z-yS)
HTML
<a href="https://fix-my-tutorial.onrender.com/r/ri-wVF3z-yS"><img src="https://fix-my-tutorial.onrender.com/badge/ri-wVF3z-yS.svg" alt="Fix My Tutorial"></a>