Why NumPy?
Deep learning works with numbers arranged in tables and grids. NumPy is the Python library that handles such arrays quickly. Keras and TensorFlow accept NumPy arrays directly, so NumPy knowledge is a must.
Creating Arrays
python
import numpy as np
a = np.array([1, 2, 3]) # 1D array (vector)
b = np.array([[1, 2, 3], [4, 5, 6]]) # 2D array (matrix)
print(a.shape) # (3,)
print(b.shape) # (2, 3) -> 2 rows, 3 columns
print(b.dtype) # int64
zeros = np.zeros((2, 3))
ones = np.ones((2, 3))
rand = np.random.rand(2, 3) # random numbers between 0 and 1
seq = np.arange(0, 10, 2) # [0 2 4 6 8]
Understanding Shape
Shape tells you the size of each dimension. It is the most important idea in deep learning. A very common error message is about a shape mismatch, so get used to checking .shape.
| Data | Typical shape |
| A list of 1000 house prices | (1000,) |
| A table of 1000 houses with 8 features | (1000, 8) |
| 60000 grayscale 28 x 28 images | (60000, 28, 28) |
| 32 color photos 224 x 224 | (32, 224, 224, 3) |
Reshape
python
x = np.arange(12) # shape (12,)
y = x.reshape(3, 4) # shape (3, 4)
z = x.reshape(2, -1) # -1 means: figure it out -> (2, 6)
print(y)
Indexing and Slicing
python
m = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(m[0, 1]) # 2 (row 0, column 1)
print(m[:, 0]) # [1 4 7] (first column)
print(m[1:, :2]) # [[4 5] [7 8]]
Math Operations and Broadcasting
python
a = np.array([1.0, 2.0, 3.0])
print(a * 2) # [2. 4. 6.]
print(a + 10) # [11. 12. 13.]
print(a.mean(), a.std(), a.max())
# Broadcasting: a smaller array is stretched to fit a bigger one
m = np.ones((2, 3))
row = np.array([1, 2, 3])
print(m + row) # row is added to each row of m
Dot Product (The Heart of Neural Networks)
python
inputs = np.array([1.0, 2.0, 3.0])
weights = np.array([0.2, 0.8, -0.5])
bias = 0.1
output = np.dot(inputs, weights) + bias
print(output) # 0.4
This single line is what a neuron does: multiply inputs by weights, add them up and add a bias.
Normalization
Neural networks learn better when the input numbers are small and on a similar scale. Image pixels go from 0 to 255, so we divide by 255.
python
images = np.random.randint(0, 256, size=(5, 28, 28))
images = images.astype("float32") / 255.0
print(images.min(), images.max()) # between 0.0 and 1.0
Train and Test Split
python
from sklearn.model_selection import train_test_split
import numpy as np
X = np.random.rand(100, 4)
y = np.random.randint(0, 2, size=100)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape) # (80, 4) (20, 4)
Why split? We train on one part and test on data the model has never seen. It is like practicing with homework and then checking your knowledge with a surprise exam.
Conclusion
You will use NumPy in every lesson. Check shapes often, normalize your data and split it into training and test sets.
Quick Summary: NumPy arrays have shapes. Use reshape, slicing, dot product and normalization, and always split your data.