0
0
TensorFlowml~5 mins

Prediction and evaluation in TensorFlow

Choose your learning style9 modes available
Introduction
Prediction helps us see what the model thinks about new data. Evaluation tells us how good the model is at making those guesses.
After training a model to check how well it learned.
When you want to guess outcomes for new, unseen data.
To compare different models and pick the best one.
To monitor model performance during development.
To understand if the model needs more training or tuning.
Syntax
TensorFlow
predictions = model.predict(new_data)
evaluation = model.evaluate(test_data, test_labels)
Use model.predict() to get the model's guesses on new inputs.
Use model.evaluate() to get loss and metrics on test data.
Examples
Get predictions for test inputs X_test.
TensorFlow
predictions = model.predict(X_test)
Calculate loss and accuracy on test data and labels.
TensorFlow
loss, accuracy = model.evaluate(X_test, y_test)
Predict only the first 5 new samples.
TensorFlow
predictions = model.predict(new_samples[:5])
Sample Model
This code trains a simple model to learn the identity function (output = input). Then it predicts values for new inputs and evaluates the model's error on test data.
TensorFlow
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np

# Create simple data: inputs and labels
X_train = np.array([[0], [1], [2], [3], [4], [5]], dtype=float)
y_train = np.array([0, 1, 2, 3, 4, 5], dtype=float)

X_test = np.array([[6], [7], [8]], dtype=float)
y_test = np.array([6, 7, 8], dtype=float)

# Build a simple model
model = models.Sequential([
    layers.Dense(1, input_shape=(1,))
])

# Compile model with optimizer and loss
model.compile(optimizer='sgd', loss='mean_squared_error', metrics=['mean_absolute_error'])

# Train model
model.fit(X_train, y_train, epochs=100, verbose=0)

# Predict on test data
predictions = model.predict(X_test)

# Evaluate model on test data
loss, mae = model.evaluate(X_test, y_test, verbose=0)

# Print results
print('Predictions:', predictions.flatten())
print(f'Test Loss: {loss:.4f}')
print(f'Test MAE: {mae:.4f}')
OutputSuccess
Important Notes
Predictions are usually arrays of numbers matching the model's output shape.
Evaluation returns loss first, then any metrics you asked for during compile.
Always evaluate on data the model has not seen before to get honest results.
Summary
Use model.predict() to get the model's guesses on new data.
Use model.evaluate() to measure how well the model performs.
Prediction and evaluation help you trust and improve your model.