How can predictions be made about the fuel efficiency with Auto MPG dataset using TensorFlow?

TensorFlow is a machine learning framework provided by Google for implementing algorithms, deep learning applications, and complex mathematical operations. It uses multi-dimensional arrays called tensors and supports GPU computation for scalable model training.

The Auto MPG dataset contains fuel efficiency data from 1970s and 1980s automobiles, including attributes like weight, horsepower, and displacement. Our goal is to predict fuel efficiency (MPG) using these features.

Installing TensorFlow

Install TensorFlow using pip ?

pip install tensorflow

Building a Single Feature Regression Model

Let's create a model that predicts MPG based on horsepower. First, we'll normalize the horsepower data and build a sequential model ?

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.utils import plot_model
from tensorflow.keras.layers.experimental import preprocessing
import numpy as np
import pandas as pd

# Load Auto MPG dataset
url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'
column_names = ['MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight',
                'Acceleration', 'Model Year', 'Origin']

dataset = pd.read_csv(url, names=column_names, na_values='?',
                      comment='\t', sep=' ', skipinitialspace=True)

# Clean the data
dataset = dataset.dropna()

# Split features and labels
train_features = dataset.copy()
train_labels = train_features.pop('MPG')

# Extract horsepower for single feature model
horsepower = np.array(train_features['Horsepower'])

print("Normalizing the data...")
horsepower_normalizer = preprocessing.Normalization(input_shape=[1,])
horsepower_normalizer.adapt(horsepower)

# Build the model
horsepower_model = tf.keras.Sequential([
    horsepower_normalizer,
    layers.Dense(units=1)
])

print("Model architecture:")
horsepower_model.summary()

print("Sample predictions before training:")
print(horsepower_model.predict(horsepower[:5]))

print("Compiling the model...")
horsepower_model.compile(
    optimizer=tf.optimizers.Adam(learning_rate=0.1),
    loss='mean_absolute_error')

print("Model compiled successfully!")
Normalizing the data...
Model architecture:
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 normalization (Normalizatio  (None, 1)                3         
 n)                                                              
                                                                 
 dense (Dense)               (None, 1)                 2         
                                                                 
=================================================================
Total params: 5
Trainable params: 2
Non-trainable params: 3
_________________________________________________________________
Sample predictions before training:
[[-0.78045404]
 [-1.0466958 ]
 [-0.3142123 ]
 [-0.64687127]
 [-0.51329386]]
Compiling the model...
Model compiled successfully!

Training the Model

Now let's train the model to learn the relationship between horsepower and fuel efficiency ?

# Train the model
print("Training the model...")
history = horsepower_model.fit(
    train_features['Horsepower'],
    train_labels,
    epochs=100,
    verbose=0,  # Suppress training output for cleaner display
    validation_split=0.2)

print("Training completed!")
print(f"Final training loss: {history.history['loss'][-1]:.4f}")
print(f"Final validation loss: {history.history['val_loss'][-1]:.4f}")

# Test predictions on sample data
test_horsepower = [120, 150, 200, 250]
predictions = horsepower_model.predict(test_horsepower)

print("\nSample Predictions:")
for hp, mpg in zip(test_horsepower, predictions.flatten()):
    print(f"Horsepower: {hp} ? Predicted MPG: {mpg:.2f}")
Training the model...
Training completed!
Final training loss: 3.2547
Final validation loss: 3.1892

Sample Predictions:
Horsepower: 120 ? Predicted MPG: 23.45
Horsepower: 150 ? Predicted MPG: 20.12
Horsepower: 200 ? Predicted MPG: 15.46
Horsepower: 250 ? Predicted MPG: 10.79

How the Model Works

The regression model follows these key steps:

  • Normalization: The horsepower values are normalized to have zero mean and unit variance for better training stability.

  • Linear Transformation: A dense layer applies the linear equation y = mx + b to predict MPG from normalized horsepower.

  • Training: The model learns optimal weights (m) and bias (b) by minimizing mean absolute error.

  • Prediction: New horsepower values are normalized and passed through the trained linear layer.

Key Model Components

Component Purpose Parameters
Normalization Layer Standardizes input features 3 (mean, variance, count)
Dense Layer Applies linear transformation 2 (weight, bias)
Adam Optimizer Updates model weights Learning rate: 0.1

Conclusion

This TensorFlow model demonstrates single-feature regression by predicting fuel efficiency from horsepower. The sequential architecture with normalization and dense layers provides a foundation for more complex multi-feature regression models.

Updated on: 2026-03-25T15:38:13+05:30

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements