TensorFlow is often associated with deep learning, but it is also a solid toolkit for traditional machine learning workflows. With the Keras API you can build linear models, logistic regression classifiers, and even clustering objectives using the same training loop, optimizers, and data pipelines. This page focuses on using TensorFlow for classic ML tasks and keeps neural networks to a minimum.
Quick link: If you want a scikit-learn perspective or side-by-side comparisons, visit scikit.html.
compile(), fit(), and callbacks across models.tf.data handles batching, shuffling, and preprocessing.Convert arrays to tf.data.Dataset objects, then batch and shuffle for efficient training.
For classical ML, a single Dense layer often represents the entire model.
Choose the loss and metrics that match the ML task (MSE, log loss, accuracy).
Fit the model and evaluate on a test set, just like with scikit-learn.
Linear regression can be implemented as a single linear layer with a mean squared error loss.
# X_train, y_train are NumPy arrays
model = tf.keras.Sequential([
tf.keras.layers.Dense(1, input_shape=(num_features,))
])
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.05),
loss="mse",
metrics=["mae"]
)
model.fit(X_train, y_train, epochs=100, batch_size=32, validation_split=0.2)
loss, mae = model.evaluate(X_test, y_test)
mean_absolute_error for interpretable evaluation.Logistic regression is a linear model with a sigmoid activation (binary) or softmax (multiclass). You can represent it with one Dense layer.
model = tf.keras.Sequential([
tf.keras.layers.Dense(1, activation="sigmoid", input_shape=(num_features,))
])
model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy", tf.keras.metrics.AUC()]
)
model.fit(X_train, y_train, epochs=50, batch_size=64, validation_split=0.2)
probs = model.predict(X_test)
Dense(num_classes, activation="softmax")categorical_crossentropy or sparse_categorical_crossentropyTensorFlow can run classic K-Means by optimizing cluster centers with vectorized operations. Below is a minimal example using TensorFlow ops for the update loop.
k = 3
centers = tf.Variable(tf.random.normal([k, num_features]))
for step in range(20):
distances = tf.norm(X[:, None, :] - centers[None, :, :], axis=2)
assignments = tf.argmin(distances, axis=1)
new_centers = []
for i in range(k):
mask = tf.equal(assignments, i)
cluster_points = tf.boolean_mask(X, mask)
new_centers.append(tf.reduce_mean(cluster_points, axis=0))
centers.assign(tf.stack(new_centers))
tf.random.shuffle to sample initial centers from data.tf.data.Dataset.from_tensor_slicesbatch(), shuffle(), prefetch()MeanAbsoluteError, MeanSquaredErrorAccuracy, AUCPrecision, Recallmodel.save() to export SavedModeltf.keras.callbacks.EarlyStoppingtf.keras.callbacks.ModelCheckpointKeep models linear: One Dense layer gives you classic regression or logistic regression.
Monitor metrics: Use MAE for regression and AUC/F1 for classification.
Use validation splits: Avoid overfitting even with simple models.
Track experiments: Log hyperparameters and random seeds for reproducibility.