smartyfy.mrindigi.com

AI & Machine Learning Master Course — 037. Text, dates, and mixed-type features

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 037: Text, dates, and mixed-type features

Prerequisites: Lesson 036. Learning outcome: Extract simple features while preserving prediction-time availability.

1. Mixed fields need different questions

A shipment record can contain a numeric mass, a package category, a free-text description, and a creation timestamp. Converting every field to a number does not make their meanings interchangeable. A useful feature is both interpretable as a measurement or representation and available at the moment the system must predict.

Suppose the decision is made when a parcel is accepted. Its description and acceptance time may be available. A note added after delivery saying “arrived late” is not. Historical tables often show the latest version of each record, concealing when text changed. Establish an as-of view, including ingestion delays and edit history, before experimenting with sophisticated text models.

2. Build a small text baseline

Bag-of-words features count selected tokens. In the training phrases blue box, red box, blue bag, the vocabulary is bag, blue, box, red. The phrase green box has one known token, box, and an unfamiliar token, green. A frozen count vectorizer represents it as [0, 0, 1, 0] in that vocabulary order.

This baseline discards word order beyond the chosen token or n-gram definition. “Not damaged” and “damaged” share a token whose meaning depends on context. Bigrams can preserve short phrases, but expand the feature space and may overfit rare expressions. Character n-grams can help with spelling variation, yet also create many features. Compare these designs on development data rather than assuming more columns are always better.

Tokenization is a model choice. CountVectorizer defaults lowercase text and use a token pattern that excludes single-character tokens. That can matter for product codes. Specify a deliberate vocabulary policy for the task, inspect examples, and document it. TF–IDF additionally learns document-frequency information, so its fitting also belongs inside the training partition. Do not learn vocabulary or IDF from held-out documents.

3. Dates represent clocks, cycles, and elapsed time

A timestamp can produce elapsed age, hour, weekday, or other calendar features. Each answers a different question. Age at acceptance is a duration relative to a fixed prediction cutoff. Subtracting the creation time from today instead would change old rows whenever the training script runs, damaging reproducibility and potentially importing future information.

Use timezone-aware timestamps for real instants. Convert to a consistent reference zone for elapsed durations, and choose the relevant local zone for business calendar features. A local day can be shorter or longer at daylight-saving transitions. UTC timestamps prevent ambiguity about instants but do not automatically identify the correct local weekday for a warehouse.

Weekdays are cyclic: Sunday and Monday are neighbors despite integer codes six and zero. For day d from zero through six, encode sine and cosine of 2πd/7. Both components are needed to distinguish positions around the circle. This representation describes a smooth weekly cycle; one-hot weekdays allow unrelated effects. Neither assumes holidays, special closures, or all calendar changes are captured.

A frozen vocabulary bag, blue, box, red maps green box to [0, 0, 1, 0]. A unit circle uses horizontal sine and vertical cosine of 2πd/7, placing Monday d = 0 at the top beside Sunday d = 6. A UTC timeline runs from 4 January 2026 at 23:00 to 5 January at 01:00, crossing midnight over two hours.
Freeze text vocabulary on training data. Calendar cycles need both sine and cosine, while elapsed age must use the fixed prediction cutoff and unambiguous instants. Open full-size diagram

4. Preserve meaning across the join

A mixed feature matrix combines representations horizontally while keeping rows aligned. If a text table is sorted differently from the numeric table, positional concatenation can attach another parcel’s description. Join on an audited unique key, verify expected row counts, and check whether any one-to-many join duplicates targets. Row alignment errors can survive shape checks and produce convincing but meaningless models.

For prediction-time aggregates, define the reference window exactly. “Previous seven days” must exclude the outcome being predicted and use only records already available at the cutoff. A future delivery timestamp or a customer’s eventual total orders is unsuitable for a decision made earlier. Feature engineering is therefore partly a temporal data-contract problem.

CPU lab: vocabulary and calendar features

The example needs only Python, NumPy’s installed environment, and scikit-learn; it runs locally without downloads. The date calculations themselves use the standard library. Both timestamps have explicit UTC offsets, so the elapsed duration is exactly two hours despite crossing midnight.

The cutoff is Monday, encoded as weekday zero and cycle coordinates (0, 1). The Sunday-to-Monday chord length is about 0.8678; Monday-to-Wednesday is about 1.5637. These are geometric distances on a unit circle, not measured differences in delivery difficulty. The example is a representation check, not a fitted predictive benchmark.

from datetime import datetime
import math
from sklearn.feature_extraction.text import CountVectorizer
texts = ['blue box', 'red box', 'blue bag']
vectorizer = CountVectorizer()
vectorizer.fit(texts)
print(vectorizer.get_feature_names_out().tolist())
print(vectorizer.transform(['green box']).toarray().tolist())
assert 'green' not in vectorizer.vocabulary_
created = datetime.fromisoformat('2026-01-04T23:00:00+00:00')
cutoff = datetime.fromisoformat('2026-01-05T01:00:00+00:00')
age_hours = (cutoff - created).total_seconds() / 3600
assert age_hours == 2
weekday = cutoff.weekday()
cyclic = (math.sin(2*math.pi*weekday/7), math.cos(2*math.pi*weekday/7))
print(age_hours, weekday, tuple(round(x, 4) for x in cyclic))
sun = (math.sin(2*math.pi*6/7), math.cos(2*math.pi*6/7))
mon = (0., 1.)
wed = (math.sin(2*math.pi*2/7), math.cos(2*math.pi*2/7))
print(round(math.dist(sun, mon), 4), round(math.dist(mon, wed), 4))

Four practice questions with worked answers

Practice 1

Using vocabulary bag, blue, box, red, encode “blue blue box”.

Answer: The counts are [0, 2, 1, 0]. Repeated blue contributes two occurrences, not a new column. A binary representation would instead record presence, yielding [0, 1, 1, 0]. Choose counts or presence according to the task and validate the choice.

Practice 2

A note was written Tuesday but refers to an event on Monday. Can Monday’s predictor use it?

Answer: Not if the note was unavailable at Monday’s decision cutoff. Event time and availability time are separate. The historical feature query must respect when the system could actually obtain the note, including processing delays, rather than only the date mentioned in its text.

Practice 3

Why use both sine and cosine for weekday instead of sine alone?

Answer: One coordinate can map different cycle positions to the same value. The pair locates an angle on the circle and preserves the wraparound neighborhood. For Monday at angle zero, sine is zero and cosine is one; both together distinguish it from the opposite direction when such a position exists.

Practice 4

A numeric table contains 100 unique parcel IDs. Joining descriptions yields 120 rows. What should happen before modeling?

Answer: Investigate the join cardinality. Some IDs may have multiple description versions or duplicate records. Define the required as-of description, resolve duplicates through an explicit rule, and assert the expected row count. Do not accept 120 rows as 120 independent parcels or silently duplicate their labels.

Five multiple-choice questions

Question 1

Where should a learned vocabulary be fitted?

  • A. Training and final test documents together
  • B. Only future documents
  • C. Training documents

Correct: C. Validation and future documents use the fixed training vocabulary; otherwise the representation has seen held-out information.

Question 2

Which feature is cyclic?

  • A. Hour of day
  • B. A unique tracking number
  • C. Parcel mass

Correct: A. Hours wrap from the end of one day to the start of another; the other examples do not have that periodic structure.

Question 3

What can bag-of-words lose?

  • A. All numeric representation
  • B. Token occurrence information
  • C. Word order and negation context

Correct: C. Counts retain occurrences but may miss meaning carried by ordering and phrases.

Question 4

Why record a prediction cutoff?

  • A. To remove the need for validation
  • B. To make elapsed and historical features reproducible
  • C. To guarantee no missing values

Correct: B. A fixed cutoff anchors what was available and the reference time for durations. It does not solve other data problems.

Question 5

What verifies row identity after a mixed-table join?

  • A. Matching array width
  • B. A higher training score
  • C. An audited key and cardinality checks

Correct: C. Equal shapes and good scores do not show that each description belongs to the correct observation.

Common pitfalls

Do not treat timestamp integers as automatically useful continuous variables. Do not compute durations with naive local datetimes across timezone changes. Avoid feeding personal identifiers or unrestricted free text into experiments without an appropriate data permission and minimization review; synthetic examples sidestep those concerns here.

Summary

Different field types need deliberate representations. Learn text statistics on training documents, anchor date features to explicit cutoffs and zones, represent cycles intentionally, and preserve row identity across joins. Availability checks belong before model fitting, not after a suspiciously high score appears.

Primary sources and further reading