Making and shaping arrays
Last updated
Data rarely arrives in the shape a model wants. A sensor sends one long stream of numbers; a model wants a table with one row per example. In this lesson you'll make arrays from scratch, read their shape, and change it with reshape, the move you'll make in almost every lesson from here on.
By the end of this lesson you can
- Make arrays with
np.array,zeros,ones,arangeandlinspace - Read an array's
shapeandndim - Change an array's shape with
reshape, using-1for the length NumPy can work out - Turn a stream of measurements into a data matrix with one row per example
Arrays from scratch
Lesson 0.1 made arrays from lists. NumPy can also make them to a size you name. Run each cell:
np.arraywith a list of lists makes a 2-D array: here two penguins, two measurements each.np.zeros(3)andnp.ones((2, 3))fill an array of a given shape with 0 or 1. Note the inner brackets: the shape(2, 3)is one tuple. Models start like this: weights set to zero or to small numbers, then changed by training.np.arange(0, 10, 2)counts likerange: from 0, up to but not including 10, in steps of 2.np.linspace(0, 1, 5)gives 5 evenly spaced numbers from 0 to 1, including both ends. You'll use it to draw smooth curves: 100 points along the x-axis, and a function worked out at every one.
The dots after numbers (0., 1.) mean they're decimals. zeros, ones and linspace make float64 arrays unless you ask for something else.
Shape and reshape
reshape gives the same numbers a new shape. Step through it first:
a = np.arange(12): twelve numbers in one row. Its shape is (12,): one axis, 12 long.Now in code. Run each cell and watch the shape:
ahas shape(12,)andndim1: one direction.a.reshape(3, 4)reads the same twelve numbers, in the same order, into 3 rows of 4. Shape(3, 4),ndim2.(2, 2, 3)is a 3-D array: 2 blocks of 2 rows of 3. Images (height × width × colour) and batches of sentences (sentences × words × numbers per word) are 3-D like this.-1means "work it out". 12 numbers in rows of 3 must be 4 rows, soreshape(-1, 3)is(4, 3).flatten()goes back to one row.
The rule: the numbers keep their order, and the new shape must hold exactly as many as the old one. 3 × 4 = 12 and 2 × 2 × 3 = 12, so both fit.
Rows of examples
Here's why reshaping matters for machine learning. Say a logger recorded three measurements for each penguin it saw, one after another: bill length, bill depth, flipper length, then the same for the next penguin. That's one long stream of numbers. Run the notebook:
flat.reshape(-1, 3) cuts the stream into rows of 3: one row per penguin, one column per measurement. NumPy works out that 12 numbers make 4 rows.
That table is the shape of all data in this course. Machine learning has names for its parts:
- each row is an example (one penguin),
- each column is a feature (one thing measured about it),
- the whole table is the data matrix, written .
Its shape is : examples, features. n, d = X.shape unpacks the two numbers, and you'll see that line at the top of many models in this course.
Wrong way: a shape that doesn't fit
Try to put 12 numbers into 5 rows of 3:
5 × 3 = 15, and there are only 12 numbers, so NumPy stops with a ValueError that says it cannot reshape array of size 12 into shape (5,3). This one is a helpful error: it names both sizes.
In practice it usually means one of two things. Either the data has a missing or extra value (a logger skipped a reading, so the stream isn't a multiple of 3), or you guessed the number of rows. Use -1 for the length you don't know, and check size when the error appears: X.size divided by the number of features must be a whole number.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- NumPy: Array creation: np.array, zeros, ones, arange and linspace
- NumPy: numpy.reshape: reshape, and -1 for a length NumPy works out
- NumPy: the absolute basics for beginners: shape, ndim and size
- Goodfellow, Bengio and Courville, Deep Learning, chapter 2: Linear Algebra: scalars, vectors, matrices and tensors, and the design matrix