Back to section lessons
18 min · easy · Lesson 4 of 8

NumPy: turning text into numbers

Build simple numeric text features, understand shape and dtype, and calculate mean squared error.

Lesson contents
  1. 1 Models work with numbers
  2. 2 ndarray, shape and dtype
  3. 3 Indexing and views
  4. 4 Mean squared error
  5. 5 Task
  6. 6 Common mistake

Models work with numbers

The model's mathematical layers expect numbers rather than text. First, convert text to a numeric representation. For the first experiment, use three simple features: the number of characters, words and unique words.

For two texts, this gives a table with two rows and three columns:

texts = ["API не отвечает", "Диск почти заполнен"]

features = []
for text in texts:
    words = text.split()
    features.append([len(text), len(words), len(set(words))])

print(features)  # [[15, 3, 3], [19, 3, 3]]

len(text) counts characters, including spaces. text.split() splits a string into words, while set(words) removes duplicates. The second string in the example contains 19 characters, three words and three distinct words.

ndarray, shape and dtype

NumPy's main data structure is called ndarray. shape gives the size along each axis, and dtype specifies the element type:

import numpy as np

features = np.asarray([[15, 3, 3], [19, 3, 3]], dtype=np.float32)
print(features.shape)  # (2, 3)
print(features.dtype)  # float32

The project uses float32. This type takes half as much memory as float64 and matches PyTorch's default parameter type.

Indexing and views

A NumPy slice often returns a view that refers to the original memory:

import numpy as np

values = np.array([1, 2, 3], dtype=np.float32)
part = values[:2]
part[0] = 99
print(values)  # [99.  2.  3.]

Use .copy() if you need an independent array. This distinction matters when splitting data: changing one array should not silently modify another.

Mean squared error

Mean squared error, or MSE, averages the squared differences between correct values and predictions:

y_true = [1, 3]
y_pred = [2, 5]
errors = [-1, -2]
squares = [1, 4]
MSE = (1 + 4) / 2 = 2.5

In NumPy, write the formula directly:

import numpy as np

y_true = np.asarray([1, 3], dtype=np.float32)
y_pred = np.asarray([2, 5], dtype=np.float32)
error = y_true - y_pred
value = np.mean(error ** 2)
print(float(value))  # 2.5

np.asarray turns lists into arrays. Subtracting arrays finds the difference for each pair of elements; you can't subtract ordinary Python lists this way.

Compare floating-point results with a tolerance. Use pytest.approx in pytest, or NumPy's isclose and allclose functions.

Task

Implement the following in exercises/lesson04.py:

def text_features(texts) -> np.ndarray:
    ...

def mse(y_true, y_pred) -> float:
    ...

text_features returns an array of shape [n, 3] with columns chars, words, unique_words. Its type must be np.float32. An empty list must produce shape (0, 3), rather than (0,).

mse accepts two arrays with the same shape, rejects mismatched shapes and empty input, then returns an ordinary Python float.

Hints

Count unique words with len(set(words)). For an empty result, create np.empty((0, 3), dtype=np.float32) explicitly.

Check y_true.shape == y_pred.shape after converting both arguments with np.asarray(..., dtype=np.float32).

Check

python -m pytest -q tests/test_exercises.py --student exercises -k lesson04

The tests check the shape, float32, a manually calculated MSE, and that input values are not modified accidentally.

Where to find the solution

The reference is in solutions/lesson04.py. Before comparing, check the empty list separately: it often produces an array with the wrong shape.

python -m pytest -q tests/test_exercises.py --student solutions -k lesson04

Common mistake

len(set(text)) counts unique characters. Split the text into words first, then pass the word list to set.

Done reading?

Mark the lesson as read to move your track progress forward.

Practice

Fix a local lab. The agent checks your work and gives hints if you get stuck.

Full access to all labs

$134 $67.00 for one year −50%

One payment, no auto-renewal · Terms

Buy for $67.00