Say you want to sell your old phone on a resale site. Before you post it, you'd look at similar listings: same brand, similar age, same storage. From those, you'd guess a fair price. You're using what you know about each phone (its features) to predict the thing you care about (its price, the label).
A machine learning model does the same thing, but with thousands of listings, and it only ever sees a table of numbers. Understanding features and labels in machine learning is the first step to understanding any model: what goes in, what comes out, and what the model never gets to see.
What you need first: types of machine learning and the pandas DataFrame tutorial. The types of data lesson helps too.
Key terms
- Dataset: a table of examples. Each row is one thing (a phone, a student, a payment), and each column is one fact about it.
- Example (also called a sample, row, instance or observation): one row of the dataset.
- Feature: a column the model uses as an input, such as age in months or storage in GB.
- Label (also called the target): the column the model must predict, such as the price.
- X and y: the usual names in code. X is the table of features (capital, because it's a table), and y is the column of labels.
- Shape: the number of rows and columns, written (rows, columns).
A dataset is a table
Here are five second-hand phone listings. The prices are made up for this example:
import pandas as pd
phones = pd.DataFrame({
"brand": ["Samsung", "Redmi", "Apple", "Redmi", "Samsung"],
"age_months": [12, 30, 18, 6, 40],
"storage_gb": [128, 64, 128, 128, 64],
"screen_cracked": ["no", "no", "no", "no", "yes"],
"price_rs": [14500, 4200, 38000, 9800, 3100],
})
print(phones)
brand age_months storage_gb screen_cracked price_rs
0 Samsung 12 128 no 14500
1 Redmi 30 64 no 4200
2 Apple 18 128 no 38000
3 Redmi 6 128 no 9800
4 Samsung 40 64 yes 3100
Read it the way a model will:
- Each row is one example. Row 0 is a 12-month-old Samsung with 128 GB that sold for ₹14,500.
- Four columns are features: brand, age, storage and whether the screen is cracked. You'd know all four before you sell the phone.
- One column is the label: the price. It's the answer you want the model to learn to predict.
The picture below is worth keeping in your head for the whole course. Every supervised learning problem has this shape:
Features and labels in Python: X and y
In code, you split the table into two parts. drop(columns=...) returns the table without the label column, and square brackets pick out one column:
X = phones.drop(columns="price_rs") # every column except the label
y = phones["price_rs"] # just the label
print("X shape:", X.shape)
print("y shape:", y.shape)
print(y.tolist())
X shape: (5, 4)
y shape: (5,)
[14500, 4200, 38000, 9800, 3100]
X has 5 rows and 4 columns: five phones, four features each. y has 5 values and no second number in its shape, because it's a single column (a pandas Series). The rows line up: the first label belongs to the first row of X, and so on. If you ever sort or filter one of them without the other, the pairs get mixed up and the model learns nonsense.
Why the capital X and small y? It's a maths habit: capitals for tables (matrices), small letters for single columns (vectors). Every scikit-learn example you'll read uses these names, so it's worth using them too.
What a model actually sees: only numbers
A model is a maths formula. It multiplies, adds and compares numbers. It has no idea what "Samsung" means. Try giving it text and see what happens:
from sklearn.linear_model import LinearRegression
try:
LinearRegression().fit(X, y)
except ValueError as error:
print("ValueError:", error)
ValueError: could not convert string to float: 'Samsung'
That's the error you'll see the first time you forget this. (LinearRegression fits a straight-line formula; you'll learn it properly in the linear regression module. Here it's only a model that needs numbers.) The fix is to turn every text column into numbers first. The simplest way gives each category its own 0/1 column:
X_numbers = pd.get_dummies(X, dtype=int) # dtype=int gives 0 and 1, not True and False
print(X_numbers.to_string()) # to_string() prints every column, with no "..."
age_months storage_gb brand_Apple brand_Redmi brand_Samsung screen_cracked_no screen_cracked_yes
0 12 128 0 0 1 1 0
1 30 64 0 1 0 1 0
2 18 128 1 0 0 1 0
3 6 128 0 1 0 1 0
4 40 64 0 0 1 0 1
Now "brand" has become three columns. The Redmi in row 1 has a 1 under brand_Redmi and 0 under the other two. "Screen cracked" became two columns in the same way. This is called one-hot encoding, and encoding categorical data covers it fully, including when to use other methods.
So the model never sees your table. It sees a grid of numbers like the one above, plus a column of numbers to predict. Everything a model can learn has to be somewhere in those numbers.
Types of features
Features come in a few kinds, and each kind needs different handling before a model can use it:
| Kind | Examples | What a model needs |
|---|---|---|
| Numerical, continuous | age in months, price, temperature | Usually used as it is, sometimes rescaled |
| Numerical, discrete (counts) | number of rooms, previous orders | Used as it is |
| Categorical, no order (nominal) | brand, city, UPI app | One-hot encoding |
| Categorical, with order (ordinal) | small/medium/large, exam grade | Numbers that keep the order |
| Yes/no (binary) | screen cracked, is weekend | 0 and 1 |
| Dates and times | order time, joining date | Split into parts: hour, weekday, month |
| Text | product review, email | Turned into word counts or other numbers |
| Images and sound | photo of a leaf | Pixel values, usually for deep learning |
A common trap: a number isn't always a numerical feature. A PIN code like 208001 is a number, but 208002 isn't "one more" than 208001 in any useful way. It's a category. The same goes for roll numbers and phone numbers.
The label decides the kind of problem
Look at the label column, and you know what kind of machine learning problem you have:
| Label | Problem | Example |
|---|---|---|
| A number | Regression | Predict a phone's price in ₹ |
| One of a few categories | Classification | Predict whether a payment is fraud or not |
| No label at all | Unsupervised learning (for example, clustering) | Group shoppers by what they buy |
This is the same split you met in types of machine learning. Change the label, and the same data becomes a different problem. If the phones table had a column "sold within a week: yes or no" and you predicted that instead, it would be classification.
A real dataset: Palmer penguins
Real datasets are bigger and messier. The Palmer penguins data has measurements of 344 penguins from three islands in Antarctica.
Download the data: penguins.csv (14 KB), or from the original source, the palmerpenguins project. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("penguins.csv").
sns.load_dataset downloads a small practice dataset from the Seaborn project on GitHub the first time, then reuses the saved copy:
import seaborn as sns
penguins = sns.load_dataset("penguins")
print(penguins.shape)
print(penguins.head())
(344, 7)
species island bill_length_mm ... flipper_length_mm body_mass_g sex
0 Adelie Torgersen 39.1 ... 181.0 3750.0 Male
1 Adelie Torgersen 39.5 ... 186.0 3800.0 Female
2 Adelie Torgersen 40.3 ... 195.0 3250.0 Female
3 Adelie Torgersen NaN ... NaN NaN NaN
4 Adelie Torgersen 36.7 ... 193.0 3450.0 Female
[5 rows x 7 columns]
344 rows (penguins) and 7 columns. Suppose a researcher wants to predict a penguin's species from its measurements, so they don't need an expert to identify each bird. Then:
- Label:
species, one of three categories, so this is classification. - Features: the four measurements (bill length, bill depth, flipper length, body mass), plus
islandandsexif they're useful.
Before you go on, look at row 3 above. Predict: how many rows in the whole table have at least one missing value? Then run this:
print(penguins.isna().sum())
print("rows with any missing value:", penguins.isna().any(axis=1).sum())
species 0
island 0
bill_length_mm 2
bill_depth_mm 2
flipper_length_mm 2
body_mass_g 2
sex 11
dtype: int64
rows with any missing value: 11
isna() marks each missing cell as True, and sum() counts them per column. any(axis=1) asks "is anything missing in this row?", because axis=1 means "across the columns of each row". Only 11 rows have a gap, and most of those are just a missing sex. Many models refuse to train on missing values, so you have to decide what to do with them. Handle missing values in pandas covers the options. Here, dropping the few rows with missing measurements is fine:
features = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
clean = penguins.dropna(subset=features)
X = clean[features]
y = clean["species"]
print("X:", X.shape, " y:", y.shape)
print(y.value_counts())
X: (342, 4) y: (342,)
species
Adelie 151
Gentoo 123
Chinstrap 68
Name: count, dtype: int64
342 penguins with four features each, and their 342 species. value_counts() shows the label isn't evenly spread: there are more Adelie penguins than Chinstraps. That matters later, when you judge a model: a model that always says "Adelie" would already be right 44% of the time (151 ÷ 342).
Each row is a point
Here's the second picture to keep. With two features, each row is a point on a graph: one feature across, one feature up. Colour each point by its label:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 5.5))
colours = {"Adelie": "#c2410c", "Chinstrap": "#0f766e", "Gentoo": "#1d4ed8"}
for species, group in clean.groupby("species"):
ax.scatter(group["flipper_length_mm"], group["body_mass_g"], s=22, alpha=0.75,
color=colours[species], label=species)
ax.set_xlabel("Flipper length (mm)")
ax.set_ylabel("Body mass (g)")
ax.set_title("Each penguin is one point; colour is the label")
ax.legend(title="Species")
plt.show()
The Gentoos mostly sit in their own corner: big flippers, heavy bodies. A model would separate them easily with just these two features. Adelies and Chinstraps overlap, so these two features alone can't tell them apart. Another feature, such as bill length, might.
That's what a model is doing, in every algorithm in this course: looking at where the points of each label sit in the space of features, and learning a rule for new points. With four features the "graph" has four dimensions. You can't draw it, but the maths works the same way.
What makes a good feature?
Not every column should be a feature. Ask three questions about each one:
- Is it related to the label? Flipper length clearly is. A penguin's tag number isn't, and it only gives the model a way to memorise individual rows.
- Will you know it when you make the prediction? This is the one beginners miss. To predict whether a student will pass, "attended the final exam" is useless: by the time you know it, you know the result. A feature you won't have at prediction time is called leakage, and it makes a model look brilliant in testing and fail in real use. Data leakage shows how to spot it.
- Is it measured the same way for every row, now and later? If half the listings give storage in GB and half in MB, the model learns the mix-up.
Common mistakes
- Leaving the label inside X. Then the model "predicts" the price by reading the price. The score is perfect and the model is useless. Always
dropthe label column from X. - Shuffling X and y separately. The rows stop matching. Filter or sort the whole table first, then split it into X and y.
- Using ID columns as features. Customer IDs, roll numbers and row numbers let a model memorise, not learn.
- Treating codes as amounts. PIN codes, jersey numbers and product codes are categories, even though they're written as numbers.
- Expecting the model to understand text. Text and categories must become numbers first, or you get
could not convert string to float.
Practice
- A food delivery app wants to predict how many minutes an order will take to arrive. Its table has: restaurant name, distance in km, order time, number of items, weather, and actual delivery minutes. Which column is the label, and is this regression or classification?
Show the answer
The label is the actual delivery minutes, because that's what the app wants to predict. It's a number, so this is regression. The other five columns are possible features, and you'd know all of them when the order is placed.
- In the same table, someone adds a column "rider's GPS distance travelled". Would you use it as a feature? Why or why not?
Show the answer
No. You only know how far the rider travelled after the delivery is finished, which is when you already know the delivery time. At prediction time (when the customer places the order) this column doesn't exist yet. It's leakage: it would make the model look accurate in testing and be impossible to use.
- Load the Seaborn
tipsdataset withsns.load_dataset("tips"). You want to predict the tip. Make X and y, and print their shapes.
Show the answer
tips = sns.load_dataset("tips")
X_tips = tips.drop(columns="tip")
y_tips = tips["tip"]
print(X_tips.shape, y_tips.shape)
print(X_tips.columns.tolist())
(244, 6) (244,)
['total_bill', 'sex', 'smoker', 'day', 'time', 'size']
244 restaurant bills, 6 features each. Four of the features (sex, smoker, day, time) are categories, so they'd need encoding before a model could use them.
- A dataset of students has a column
roll_numberwith values like 101, 102, 103. Why is it a bad feature, even though it's numeric?
Show the answer
Roll numbers are labels for identity, not amounts: student 103 isn't "more" of anything than student 101. A model could use them to memorise individual students in the training data, which wouldn't help with new students. Drop ID columns before training.
- Predict, then check: after
pd.get_dummies(X, dtype=int)on the phones table, how many columns will there be if one more row adds the brand "Nokia"?
Show the answer
Eight. Today there are 7 columns: age_months, storage_gb, three brand columns and two screen columns. A new brand adds one more column, brand_Nokia, because each category gets its own column. This is why one-hot encoding can make very wide tables when a column has hundreds of categories, such as city names.
- In the penguin scatter plot, which species would a model find hardest to separate using only flipper length and body mass, and what would you try?
Show the answer
Adelie and Chinstrap, because their points overlap. Add another feature that differs between them. Bill length is a good candidate: Chinstraps have longer bills than Adelies of a similar size. Plot bill length against flipper length to check.
Interview questions
What is the difference between a feature and a label?
A feature is an input the model uses to make a prediction, such as a house's area. The label (or target) is the output the model learns to predict, such as the house's price. In supervised learning, the training data has both; at prediction time, only the features are known.
Why must categorical features be encoded before training most models?
Most models do arithmetic on their inputs, so they need numbers. Encoding turns categories into numbers without inventing a false order: one-hot encoding gives each category its own 0/1 column. Some libraries, such as LightGBM and CatBoost, can handle categories directly.
Key takeaways
- A dataset is a table: each row is one example, each column is one fact about it.
- Features (X) are the inputs; the label (y) is what you predict. Keep their rows matched.
- A model sees only numbers, so text and categories must be encoded first.
- A numeric label means regression, a category means classification, no label means unsupervised learning.
- Each row is a point in feature space; models learn where each label's points sit.
- A good feature is related to the label, known at prediction time, and measured consistently.
Frequently asked questions
Are "target" and "label" the same thing?
Yes. Both mean the column you want to predict. "Target" is more common for numbers (regression) and "label" for categories (classification), but people use them interchangeably.
How many features does a model need?
There's no fixed number. Start with the features a person would use to make the decision, check each one is known at prediction time, and add more only if they improve the score on data the model hasn't seen. More features can make a model worse if they're mostly noise.
What are "dimensions" in machine learning?
The number of features. A dataset with four features is four-dimensional, because each row is a point in a space with four axes. You can only draw two or three, but the models work the same way in any number.
What to learn next
- How a decision tree makes predictions: the next lesson, and the model you'll use most until the algorithm modules.
- How to frame a machine learning problem: turn a vague goal into a clear label, features and metric.
- The machine learning workflow: the steps every project follows.
- Encoding categorical data: turn categories into numbers properly.