Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Predict Fuel Efficiency Using Tensorflow in Python
Predicting fuel efficiency is crucial for optimizing vehicle performance and reducing carbon emissions. In this article, we will explore how to leverage the power of TensorFlow, a popular machine learning library, to predict fuel efficiency using Python. By building a predictive model based on the Auto MPG dataset, we can estimate a vehicle's fuel efficiency accurately.
Auto MPG Dataset
To predict fuel efficiency accurately, we need a reliable dataset. The Auto MPG dataset, sourced from the UCI Machine Learning Repository, provides the necessary information for our model. It contains various attributes like the number of cylinders, displacement, weight, horsepower, acceleration, origin, and model year. These attributes serve as features, while fuel efficiency (measured in miles per gallon, or MPG) acts as the target variable.
Data Preparation Steps
Before building the predictive model, we need to prepare the dataset. This involves handling missing values and normalizing the features ?
Handle missing values Remove rows with missing data to ensure clean training
Feature normalization Scale features using min-max scaling to ensure all features contribute equally
Train-test split Divide data into training and testing sets
Building the Fuel Efficiency Prediction Model
Here's a complete implementation using TensorFlow and Keras to predict fuel efficiency ?
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import pandas as pd
import numpy as np
# Load the Auto MPG dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
column_names = ['MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight',
'Acceleration', 'Model_Year', 'Origin']
raw_dataset = pd.read_csv(url, names=column_names, na_values='?',
comment='\t', sep=' ', skipinitialspace=True)
# Drop missing values
dataset = raw_dataset.dropna()
# Separate features and target
features = dataset.drop('MPG', axis=1)
target = dataset['MPG']
# Normalize features using min-max scaling
normalized_features = (features - features.min()) / (features.max() - features.min())
# Split into train and test sets
train_size = int(0.8 * len(dataset))
train_features = normalized_features[:train_size]
test_features = normalized_features[train_size:]
train_target = target[:train_size]
test_target = target[train_size:]
# Define the neural network model
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=[len(train_features.columns)]),
layers.Dense(64, activation='relu'),
layers.Dense(32, activation='relu'),
layers.Dense(1)
])
# Compile the model
model.compile(
optimizer=tf.keras.optimizers.RMSprop(0.001),
loss='mse',
metrics=['mae']
)
# Train the model
history = model.fit(
train_features, train_target,
epochs=1000,
validation_split=0.2,
verbose=0
)
# Evaluate on test set
test_loss, test_mae = model.evaluate(test_features, test_target, verbose=0)
# Predict fuel efficiency for a new car
new_car_data = pd.DataFrame({
'Cylinders': [4],
'Displacement': [120.0],
'Horsepower': [110.0],
'Weight': [2800.0],
'Acceleration': [15.4],
'Model_Year': [81],
'Origin': [3]
})
# Normalize new car features using same scaling
normalized_new_car = (new_car_data - features.min()) / (features.max() - features.min())
# Make prediction
predicted_mpg = model.predict(normalized_new_car, verbose=0)
print(f"Test MAE: {test_mae:.2f}")
print(f"Test MSE: {test_loss:.2f}")
print(f"Predicted Fuel Efficiency: {predicted_mpg[0][0]:.2f} MPG")
Test MAE: 2.85 Test MSE: 15.42 Predicted Fuel Efficiency: 24.73 MPG
Model Architecture
Our neural network consists of three hidden layers with 64, 64, and 32 neurons respectively, using ReLU activation. The final layer outputs a single value representing the predicted MPG. We use Mean Squared Error (MSE) as the loss function and RMSprop optimizer for training.
Key Features of the Implementation
| Component | Purpose | Configuration |
|---|---|---|
| Input Features | Vehicle characteristics | 7 features (cylinders, displacement, etc.) |
| Hidden Layers | Pattern recognition | 3 layers with 64, 64, 32 neurons |
| Activation | Non-linear mapping | ReLU for hidden layers |
| Output | Fuel efficiency prediction | Single neuron (MPG value) |
Conclusion
TensorFlow provides a powerful framework for building fuel efficiency prediction models using neural networks. The combination of proper data preprocessing, normalization, and a well-designed neural network architecture enables accurate MPG predictions based on vehicle characteristics, helping both manufacturers and consumers make informed decisions about fuel efficiency.
