Read data, fit a model, predict: machine learning code walkthroughs

Artificial Intelligence 4 min 22 Mar 2023
Cover image for Read data, fit a model, predict: machine learning code walkthroughs
Hands-on machine learning in Python: k-NN and linear regression with Scikit-learn, plus CNN examples in TensorFlow.

Machine learning is how a program learns a task from data: find patterns, predict a value, classify a sample, or pick an action. You feed it examples, fit a model, then ask that model to generalize.

Two big buckets matter early on. Supervised learning trains on labeled examples. Unsupervised learning looks for structure in unlabeled data.

Machine learning with example code

Python is the default language for most ML work. Libraries cut the boilerplate so you can focus on the data and the model.

Scikit-learn is the first stop for classic algorithms. Here is a short k-NN classifier on the Iris dataset:

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

# Load the Iris dataset
iris = datasets.load_iris()

# Split features and labels
X = iris.data
y = iris.target

# Train / test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Fit a k-NN classifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

# Score on the test set
accuracy = knn.score(X_test, y_test)
print("Accuracy:", accuracy)

The snippet loads Iris, splits train and test, fits a 3-neighbor classifier, and prints accuracy. Accuracy is only one score, but it is a fine first check.

TensorFlow sits on the deep learning side. A compact CNN on MNIST looks like this:

import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D

# Load MNIST
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Normalize pixel values
x_train = x_train / 255.0
x_test = x_test / 255.0

# Build a small CNN
model = Sequential([
    Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
    MaxPooling2D((2,2)),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(x_train.reshape(-1,28,28,1), y_train, epochs=5, validation_data=(x_test.reshape(-1,28,28,1), y_test))

test_loss, test_acc = model.evaluate(x_test.reshape(-1,28,28,1), y_test)
print('Test accuracy:', test_acc)

Pixels get scaled to 0-1, a small ConvNet is compiled with Adam, then trained for a few epochs and evaluated on the held-out set.

Linear regression with Scikit-learn

Linear regression models how targets move with input features. A minimal Scikit-learn example:

import numpy as np
from sklearn.linear_model import LinearRegression

# Tiny sample dataset
X = np.array([[1, 3], [2, 5], [3, 7], [4, 9], [5, 11]])
y = np.array([5, 7, 9, 11, 13])

model = LinearRegression()
model.fit(X, y)

X_new = np.array([[6, 15]])
y_new = model.predict(X_new)

print("Prediction:", y_new)

The model fits the tiny table, then predicts for a new feature pair. Swap in real data and the same pattern still holds.

A CNN with TensorFlow

CNNs dominate image tasks. Fashion-MNIST is a slightly harder sibling of digit MNIST:

import tensorflow as tf
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten

(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

x_train = x_train / 255.0
x_test = x_test / 255.0

model = Sequential([
    Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
    MaxPooling2D((2,2)),
    Conv2D(64, (3,3), activation='relu'),
    MaxPooling2D((2,2)),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(x_train.reshape(-1,28,28,1), y_train, epochs=5, validation_data=(x_test.reshape(-1,28,28,1), y_test))

test_loss, test_acc = model.evaluate(x_test.reshape(-1,28,28,1), y_test)
print('Test accuracy:', test_acc)

Two conv blocks, a dense head, same training loop. Scikit-learn and TensorFlow cover a lot of ground between classical ML and deep nets. Start small, measure, then grow the model only when the data asks for it.

Machine learning shows up in product, science, and ops alike. The samples above are intentionally short so you can paste them, run them, and then bend them toward your own dataset.

Oğuzhan Koçaklı

I have worked professionally in marketing, gaming and blockchain since 2015. I have helped create and carry out marketing strategies for many major brands. These days I work on mobile games and blockchain integration for games. AI has been my hobby for many years.

All posts

Leave a Reply

Your email address will not be published. Required fields are marked *