Feature Engineering and Model Evaluation in Machine Learning and Deep Learning / Start Here

Read and adapt the supplied data scripts

Lesson 3 of 39. Open to read. No account needed.

A Selection Has a Shape and an Origin

A table's first number may be a distance, a weight, an identifier or a target. Before fitting anything, you need to read its rows and columns intentionally. This lesson checks that you can trace the supplied Python, select the intended observations, and explain whether an edit changes the original input.

An array stores values in numbered positions. A two-dimensional array has rows and columns; its shape is (number_of_rows, number_of_columns). A DataFrame is pandas' labelled table: its columns have names and its rows have an index. The two types support similar inspection tasks, but their selection and ownership rules must not be assumed identical.

Use the shared CPU environment from setup. In a new Bash terminal, create the owned task folder and move into it:

practice_root="$HOME/feature-evaluation-practice"
mkdir -p "$practice_root/read-arrays-and-tables"
cd "$practice_root/read-arrays-and-tables"
../.venv/bin/python -m pip check

mkdir -p tolerates an existing folder. Inspect saved work before replacing a file on a repeat visit. The explicit interpreter selects the shared environment without activation; pip check should finish without broken requirements. This task reads generated fictional inputs, saves no result/data/plot file and contacts no service. Importing the neighbouring inputs.py may create an owned __pycache__ bytecode cache. It is harmless to keep and is not source data. The generated table exists in the Python process; a new run recreates it.

Predict a Small Selection First

The maintained run.py below begins with this excerpt:

    values = np.array([[10, 2], [20, 3], [30, 4]], dtype=float)
    mask = values[:, 0] >= 20
    selected = values[mask]

Treat the first column as fictional distance in kilometres and the second as weight in kilograms. Python numbers positions from zero. values.shape is (3, 2): three observations, two quantities each.values[:, 0] selects all rows and column zero, giving a one-dimensional array with shape (3,); the comma in that shape denotes a one-element tuple. ≥20 compares each distance and produces a boolean mask, one true/false value per row.

Predict the mask and selected rows before running: [False, True, True] should retain the last two rows, so selected.shape is (2, 2). A row mask describes positions on the row axis; a two-entry mask cannot describe three rows. This will matter in the independent repair.

shape is an attribute, accessed without parentheses. tolist() is a method: calling it returns an ordinary Python list for readable output. A function is called directly, such as inspect_arrays(); a bound method belongs to an object, such as data.head(3). The dot identifies the owner and parentheses invoke the operation. You do not need to implement a class to use these objects.

Know When an Edit Shares Storage

The same function demonstrates two NumPy indexing cases:

    view = values[:2]
    view[0, 0] = 99
    independent = values[[0, 2]]
    independent[0, 0] = -1

Basic slicing, values[:2], creates a view in this example: it shares the original array's storage. Changing view[0, 0] to 99 therefore changes the original first distance. Advanced indexing with the integer list [0, 2] creates a copy; changing its first value to -1 leaves the original at 99. The boolean selection selected is also a copy, so it retains its earlier two rows after the original is edited. None of these mutations concerns a real parcel or the later generated table; they are isolated to this small demonstration.

When you need an independent NumPy working array, write .copy() explicitly rather than relying on a vague idea of “a slice.” A view can be useful when shared edits are intended; a copy costs separate storage. Do not transfer this NumPy rule blindly to pandas or rely on chained assignment there. The table walkthrough uses explicit labelled row/column selection and does not modify pandas data through an intermediate selection.

Supply the Original Parcel Generator

Save this complete file as inputs.py in the current task folder:

"""Original fictional parcel recipe; no external data or final-challenge sample."""
import numpy as np
import pandas as pd


def make_parcels(n=600, seed=17):
    """Independent fictional parcels, with both regression and binary targets."""
    rng = np.random.default_rng(seed)
    distance = rng.uniform(10, 120, n)
    weight = rng.lognormal(mean=1.3, sigma=0.4, size=n)
    hour = rng.integers(0, 24, n)
    load = rng.uniform(0, 1, n)
    service = rng.choice(["economy", "priority"], size=n, p=[0.65, 0.35])
    duration = (
        0.07 * distance + 0.2 * weight + 2 * load
        + 1.5 * (service == "economy")
        + 0.8 * np.sin(2 * np.pi * hour / 24)
        + rng.normal(0, 1.2, n)
    )
    duration = np.maximum(duration, 0.1)
    late = (duration > 8).astype(int)
    data = pd.DataFrame({
        "parcel_id": [f"parcel-{i:04d}" for i in range(n)],
        "distance_km": distance,
        "weight_kg": weight,
        "dispatch_hour": hour,
        "load_at_dispatch": load,
        "service": service,
        "duration_hours": duration,
        "late": late,
        "final_status": np.where(late, "arrived-late", "arrived-within-window"),
    })
    # Introduce missing measurements after generating targets. The complete
    # values describe the fictional process; they are not available to a model.
    for column in ["distance_km", "weight_kg"]:
        data.loc[rng.random(n) < 0.06, column] = np.nan
    return data

import numpy as np and import pandas as pd give short local names to those libraries. make_parcels(n=600, seed=17) is a function with two default arguments: number of observations and a random-generator seed. Calling it returns a new DataFrame. It reads no website, downloaded dataset, customer record or model.

The generator's blocks make the input origins visible:

  • default_rng(seed) creates a local random-number generator. Its methods draw values. Distances lie from 10 km up to 120 km; dispatch hours are integers 0 through 23; load is a dimensionless fraction from 0 up to 1. The positive, skewed weight draw uses lognormal: its mean 1.3/spread 0.4 are choices for a normally distributed logarithm of weight, not the mean/spread of weight in kilograms. The task does not require deriving that distribution. Bigger log-mean generally shifts draws toward larger weights. The service draw has economy/priority probabilities 0.65/0.35; probabilities describe the draw, not guaranteed counts in every sample.
  • duration defines an artificial process in hours: distance, weight, dispatch load, an economy-service increment and a repeating hour effect plus noise. The sine term is a smooth wave repeating every 24 hours, with maximum magnitude 0.8 hours here. It explains where variation came from; a later lesson teaches cyclical feature design. The normal(0,1.2,n) noise has chosen centre 0/spread 1.2. maximum(duration,0.1) prevents nonpositive generated durations. These constants describe a teaching law, not a fitted model or a claim about real delivery times.
  • late is an integer class target: 1 when duration exceeds 8 hours, otherwise 0. The separate duration column can support a regression task. np.where creates the matching final-status text. parcel_id labels a row; none of these roles makes the column automatically eligible as a predictor.
  • The DataFrame dictionary pairs names with equal-length columns. Finally, each measurement column gets an independent missing-value draw with probability 0.06. data.loc[mask, column] = np.nan sets those measurements to a missing marker. This happens after target generation: the full underlying measurements made the fictional outcome but are not returned as hidden replacement features.

A seed records how this teaching sample was generated; it is not a guarantee of model quality or identical random behavior across future library versions. This task and earlier examples use seed 17. The independent final challenge uses fresh seed 1701 of the same law; do not generate or evaluate that sample here. Row IDs are unique within this table, not across every possible seeded run: include the scenario seed when comparing identities between runs.

Run the Complete Inspection

Save this complete file as run.py beside inputs.py:

"""Read shapes, ownership and a generated teaching table; no model fitting."""
import numpy as np
from inputs import make_parcels


def inspect_arrays():
    values = np.array([[10, 2], [20, 3], [30, 4]], dtype=float)
    mask = values[:, 0] >= 20
    selected = values[mask]
    print("array_shape:", values.shape)
    print("row_mask:", mask.tolist())
    print("selected_rows:", selected.tolist())
    view = values[:2]
    view[0, 0] = 99
    independent = values[[0, 2]]
    independent[0, 0] = -1
    print("original_after_view_edit:", values[0, 0])
    print("original_after_copy_edit:", values[0, 0])
    print("selected_rows_after_original_edit:", selected.tolist())


def inspect_parcels():
    data = make_parcels(n=600, seed=17)
    print("parcel_shape:", data.shape)
    print("unique_parcel_ids:", data["parcel_id"].nunique())
    print("missing_by_column:", data.isna().sum().to_dict())
    print("late_counts:", data["late"].value_counts().sort_index().to_dict())
    available_distance = data["distance_km"].notna()
    subset = data.loc[available_distance, ["distance_km", "service"]]
    print("observed_distance_subset:", subset.shape)
    print("first_three_rows:")
    print(data.head(3).to_string(index=False))
    assert len(data) == 600 and data["parcel_id"].is_unique
    assert set(data["late"].unique()) == {0, 1}
    assert len(subset) == int(available_distance.sum())


if __name__ == "__main__":
    inspect_arrays()
    inspect_parcels()

from inputs import make_parcels loads the function from the supplied neighbouring file. inspect_arrays() executes the small example already explained. inspect_parcels() calls the generator with explicit 600/17 arguments, then inspects its returned table. The final if __name__ == "__main__" runs those functions when the file is executed as a script; importing it does not run them. This lets another check inspect a function without producing its whole report.

Read the labelled table operations before running:

ExpressionInput → result and reason
data.shapeTable → row/column counts; it does not say which columns should train a model
data["parcel_id"].nunique()ID column → number of distinct row labels
data.isna().sum()Missing-value table → count per column; boolean true entries sum to counts
data["late"].value_counts().sort_index()Class column → counts ordered by class label, not by frequency
data["distance_km"].notna()Distance column → one labelled true/false value per row
data.loc[available_distance,["distance_km","service"]]Row mask plus explicit column list → observed-distance subset with two columns
data.head(3)Table → first three rows for inspection, not a representative performance sample

The pandas mask is built from the same table, so its row index matches. .loc uses labels; the NumPy selectors above use integer positions. The three assert statements check the supplied 600-row contract, ID uniqueness, both classes, and agreement between selected rows and true mask entries. A failed assertion raises AssertionError; inspect the data or edited arguments rather than deleting the check to manufacture success. .to_dict() and .to_string() only format values for display; they do not fit or change a model.

From the owned task folder:

../.venv/bin/python run.py

Illustrative excerpt from the pinned reference run:

array_shape: (3, 2)
row_mask: [False, True, True]
selected_rows: [[20.0, 3.0], [30.0, 4.0]]
original_after_view_edit: 99.0
original_after_copy_edit: 99.0
parcel_shape: (600, 9)
unique_parcel_ids: 600
late_counts: {0: 350, 1: 250}
observed_distance_subset: (559, 2)

The reference has 41 missing distance entries and 30 missing weight entries. These are 71 missing cells, not necessarily 71 different observations. Selecting nonmissing distance retains 600−41=559 rows, regardless of weight missingness. Inspect all labelled fields, not just the final successful exit. The exact sample counts belong to the supplied seed/pins; changing inputs changes them. This task does not select predictors, split rows, impute measurements or fit a model. The next lesson audits which information is allowed at prediction time.

Independent Repair: Wrong Axis

Save the following intentionally broken complete file as broken_mask.py. Predict the mask's shape, whether the command can succeed, and the likely final error before running it:

"""Intentional row-mask error for independent diagnosis."""
import numpy as np

values = np.array([[10, 2], [20, 3], [30, 4]], dtype=float)
row_mask = values[0] >= 20
print(values[row_mask])

Run it from the same task folder with ../.venv/bin/python broken_mask.py. Its expected failure is part of the task, not evidence that package installation has broken. Read the last exception line, then identify which expression selected a row where you wanted a column. Create a corrected fix_mask.py that selects rows whose distance is at least 20 km. Success is two rows [20,3] and [30,4], plus an explanation of why the mask length now matches. Attempt before opening hints.

Also explain: why does changing the basic slice change values, while changing the integer-indexed result leaves it alone? Would seeing 600 unique IDs or both classes establish that every numeric column is a valid model feature?

Answer and Reasoning

Hint 1: Row selection with a boolean mask needs one value for each row. Hint 2: values[0] is the first row, whose shape is (2,). Hint 3: values[:, 0] selects the first column across all three rows.

The broken mask has two values for three row positions. NumPy raises IndexError reporting axis 0 size 3 versus mask size 2. Read the sizes as evidence of the indexing mistake; reinstalling NumPy or changing versions will not repair which axis was selected.

One complete reference fix_mask.py is:

"""One explained correction: a length-three mask for the three row positions."""
import numpy as np

values = np.array([[10, 2], [20, 3], [30, 4]], dtype=float)
row_mask = values[:, 0] >= 20
selected = values[row_mask]
assert selected.tolist() == [[20.0, 3.0], [30.0, 4.0]]
print(selected)

It produces [False, True, True], which indexes the three row positions correctly. The assertion checks the two expected rows. A list of row positions such as [1,2] selects the same rows for this literal example, but it does not express the distance condition and would not adapt when values changed.

The basic slice shares NumPy storage; integer/boolean advanced indexing returns a copy in these examples. Both facts can be true even when printed values look identical. ID uniqueness and class support are useful input checks, but eligibility requires a prediction-time argument. For example, eventual duration and status cannot become safe inputs simply because the table contains them.

Diagnose, Resume and Reset

DifferenceInspect before changing anything
Cannot import inputsConfirm both files are in the named task folder and the filename is exactly inputs.py, not .txt
Cannot import NumPy/pandasSelect the checked shared interpreter; return to setup's import/path diagnosis
IndexError from broken maskCompare mask length with the indexed axis; this deliberate failure needs an indexing repair
TypeError: ... object is not callable after shape()shape is an attribute, not a method
Counts differCheck explicit arguments, unchanged generator, package pins and edited inputs; tiny samples need not contain both classes
Unexpected edit changes originalCheck basic slicing versus advanced indexing and whether .copy() was required

A new terminal needs only the owned cwd and explicit interpreter again. A fresh process reconstructs the original arrays; the earlier 99 edit is not persisted into the generator or a later run. This is why rerunning run.py after the broken task is safe and produces the same teaching inputs under the same pins.

Keep starter files, your correction, wanted terminal notes and the shared .venv. No result/data/plot artifact or background service is created. Python may keep its owned __pycache__ bytecode cache; leave that cache in place. Nothing is required to delete. If you chose to save a summary.txt yourself, remove only that named owned file after preserving your notes. To repeat the broken-task attempt, preserve your solution first and restore its supplied block; do not delete the whole practice root or the shared environment.

References

34 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy