AlgoDaily

Skill Development

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

From Concepts To Code

Why this lesson matters

In Fundamental Understanding, you built the mental model: data becomes features, features become vectors, models learn patterns, and evaluation keeps us honest.

Now we turn that understanding into Python habits.

By the end of this lesson, you should feel more comfortable writing small pieces of code that:

  • represent real-world data as rows and features
  • separate inputs from prediction targets
  • transform data without mixing up training and validation information
  • organize ML code into reusable functions

We are not building the full predictive project yet. That comes later. Here, we are sharpening the Python skills you will need when the datasets get more realistic.

From Concepts To Code

The ML Coding Stack

Skill development is mostly translation

A beginner-friendly way to think about ML programming is:

real-world observation
        ↓
Python row / dictionary
        ↓
feature vector
        ↓
model input
        ↓
prediction

For now, your most important Python tools are not fancy libraries. They are:

  • lists for collections of rows or vectors
  • dictionaries for named fields
  • loops for processing many examples
  • functions for reusable steps
  • clear variable names so your data flow is readable

Libraries like NumPy, pandas, and scikit-learn will become useful, but these core Python patterns are the foundation underneath them.

The ML Coding Stack

Rows Become Vectors

Turning records into ML-ready pieces

In the previous lesson, Vectors Hold Features introduced the idea that a row can become a feature vector.

Here is the Python version of that idea.

We will use a tiny housing example because it connects naturally to predictive analytics: using known facts about a home to predict a price.

```python
homes = [
    {"size_sqft": 850, "bedrooms": 1, "age_years": 12, "price_k": 260},
    {"size_sqft": 1200, "bedrooms": 2, "age_years": 8, "price_k": 340},
    {"size_sqft": 1600, "bedrooms": 3, "age_years": 15, "price_k": 420},
]

feature_names = ["size_sqft", "bedrooms", "age_years"]

X = [[home[name] for name in feature_names] for home in homes]
y = [home["price_k"] for home in homes]

print("Feature names:", feature_names)
print("First feature vector:", X[0])
print("Targets:", y)
print("Rows x features:", len(X), "x", len(X[0]))
```

Find The Target

You are building a supervised model to predict home price.

A row has these fields:

  • size_sqft
  • bedrooms
  • age_years
  • price_k

Which field should usually be the prediction target, y?

Transform With Care

Preprocessing becomes code

In Before Modeling, you saw that preprocessing matters. In Python, preprocessing is a set of transformations you apply consistently.

One important habit: learn transformation settings from the training data, then reuse them elsewhere.

For example, if we scale home sizes, we compute the mean and standard deviation from the training rows only. Then we apply those same numbers to validation or future rows.

```python
rows = [
    {"size_sqft": 850, "price_k": 260},
    {"size_sqft": 1200, "price_k": 340},
    {"size_sqft": 1600, "price_k": 420},
    {"size_sqft": 2000, "price_k": 520},
    {"size_sqft": 1000, "price_k": 300},  # pretend validation row
]

train = rows[:4]
validation = rows[4:]

def mean(values):
    return sum(values) / len(values)

def std(values):
    avg = mean(values)
    variance = sum((value - avg) ** 2 for value in values) / len(values)
    return variance ** 0.5

train_sizes = [row["size_sqft"] for row in train]
size_mean = mean(train_sizes)
size_std = std(train_sizes)

def scale_size(row):
    return (row["size_sqft"] - size_mean) / size_std

print("Training mean:", round(size_mean, 2))
print("Training std:", round(size_std, 2))
print("Scaled training sizes:", [round(scale_size(row), 2) for row in train])
print("Scaled validation size:", round(scale_size(validation[0]), 2))
```

Leakage Check

True or false?

It is safe to compute scaling statistics using both training rows and validation rows, because validation rows are not labels.

Functions Create Pipelines

Reusable steps beat copy-paste

Machine learning code becomes much easier to reason about when each step has a job.

A function might:

  • convert one row into a feature vector
  • scale a value
  • compute a distance
  • make a simple prediction

Below is a tiny nearest-neighbor predictor. Do not worry about mastering the algorithm yet. Focus on the structure: data goes in, a prediction comes out.

```python
training_examples = [
    {"features": [-1.2, 1], "price_k": 260},
    {"features": [-0.3, 2], "price_k": 340},
    {"features": [0.4, 3], "price_k": 420},
    {"features": [1.1, 4], "price_k": 520},
]

new_home_features = [-0.1, 2]

def distance(vector_a, vector_b):
    squared_diffs = [(a - b) ** 2 for a, b in zip(vector_a, vector_b)]
    return sum(squared_diffs) ** 0.5

def predict_with_nearest_neighbor(examples, new_features):
    nearest = min(
        examples,
        key=lambda row: distance(row["features"], new_features)
    )
    return nearest["price_k"], nearest

prediction, neighbor = predict_with_nearest_neighbor(training_examples, new_home_features)

print("New home features:", new_home_features)
print("Nearest known features:", neighbor["features"])
print("Predicted price:", prediction, "k")
```

Name The Keyword

Fill in the blank.

In Python, the keyword used to create a reusable function is:

_____

Readable ML Code

A practical coding checklist

When you write Python for machine learning, aim for code that another learner could follow.

Use this checklist:

  • Name your inputs clearly: X, features, or feature_matrix
  • Name your target clearly: y, target, or prices
  • Keep rows consistent: every feature vector should have the same order and length
  • Separate steps: load data, transform data, predict, then evaluate
  • Avoid leakage: do not let validation or future data influence training steps
  • Prefer small functions: each one should do one job

This is the skill layer between theory and projects. In Application Mastery, these habits will help you work through more realistic predictive tasks.

Readable ML Code

Best Next Habit

You are writing Python code that converts raw rows into feature vectors.

Which habit best supports reliable machine learning code?

Open interactive view →