CodeBlanks Logo Icon CodeBlanks

Feature extraction

Feature extraction derives new features from existing ones.

Feature extraction

Producing numbers the model can use from raw data (dates, text, images) is called feature extraction. Dates are the classic example:

from datetime import date
d = date(2024, 3, 15)
print(d.year, d.month, d.weekday())   # 2024 3 4  (0 = Monday)
hafta_sonu = d.weekday() >= 5

The model doesn't understand the text "2024-03-15"; but pieces like "month 3", "Friday", "not a weekend" carry a lot of information for sales prediction.

Features from text

The simplest method for text is counting words. CountVectorizer opens a column for each word:

from sklearn.feature_extraction.text import CountVectorizer
metin = ["ucuz ürün ucuz", "kaliteli ürün"]
cv = CountVectorizer()
X = cv.fit_transform(metin).toarray()
print(cv.get_feature_names_out())   # ['kaliteli' 'ucuz' 'ürün']
print(X)                            # [[0 2 1] [1 0 1]]

Simple counts like length, number of exclamation marks and capital-letter ratio are strong features for spam detection too.

Practice Count words

Turn the yorumlar list into a count matrix with CountVectorizer. Print the words with get_feature_names_out() and the matrix with toarray() on separate lines.

Starter code

model.py
from sklearn.feature_extraction.text import CountVectorizer

yorumlar = ["harika film", "kötü film kötü", "harika oyuncu"]

# buraya yaz

Sample solution

model.py
from sklearn.feature_extraction.text import CountVectorizer

yorumlar = ["harika film", "kötü film kötü", "harika oyuncu"]

cv = CountVectorizer()
X = cv.fit_transform(yorumlar)
print(cv.get_feature_names_out())
print(X.toarray())

Expected output

['film' 'harika' 'kötü' 'oyuncu']
[[1 1 0 0]
 [1 0 2 0]
 [0 1 0 1]]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If <code>date(2024, 3, 16).weekday()</code> is 5, is that day a weekend?

  • No, Monday
  • It can't be determined
  • Yes, Saturday Correct answer
  • No, Friday

Explanation: weekday 0 = Monday ... 5 = Saturday, 6 = Sunday.

2 Get the names of the word columns.

Question
adlar = cv.____()
Answer
adlar = cv.get_feature_names_out()

Explanation: get_feature_names_out gives the words in column order.

3 Match the raw data with the features.

Term Meaning
Date Month, weekday
Text Word counts
Location Distance to centre
Image Pixel values

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation