Predict Fuel Efficiency Using Tensorflow in Python


Predicting fuel efficiency is crucial for optimizing vehicle performance and reducing carbon emissions, and this can esily be predicted using tensorflow, a library of python. 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. Let's dive into the process of utilizing Tensorflow in Python to make accurate fuel efficiency predictions.

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 label. By analyzing this dataset, we can train our model to recognize patterns and make predictions based on similar vehicle characteristics.

Preparing the dataset

Before building the predictive model, we need to prepare the dataset. This involves handling missing values and normalizing the features. Missing values can disrupt the training process, so we eliminate them from the dataset. Normalizing the features, such as horsepower and weight, ensures that each feature is on a similar scale. This step is crucial because features with large numerical ranges can dominate the model's learning process. Normalizing the dataset ensures fair treatment for all features during training.

How to Predict Fuel Efficiency Using TensorFlow?

Below are the steps that we will follow to predict fuel efficiency using Tensorflow −

  • Import necessary libraries − We import tensorflow, Keras, layers, and pandas.

  • Load the Auto MPG dataset. We also specify the column names and handle any missing values.

  • Separate the dataset into features and labels − We separate the dataset into two parts − features (input variables) and labels (output variable).

  • Normalize the features − We normalize the features using min-max scaling.

  • Dataset splitting into training and testing sets.

  • Define the model architecture − We define a simple sequential model with three dense layers, where each layer has sixty-four neurons and uses the ReLU activation function.

  • Compile the model − We compile the model with the mean squared error (MSE) loss function and the RMSprop optimizer.

  • Train the model − Model Training on the training set for 1000 epochs and specify a validation split of 0.2.

  • Evaluate the model − Model evaluation on the test set and calculate the mean MSE and the fuel efficiency and absolute error (MAE).

  • Calculate fuel efficiency for a new car − We create a new car's features using a pandas DataFrame. We normalize the new car's features using the same scaling factors as the original dataset.

  • Predict the new car’s fuel efficiency using the trained model.

  • Print the predicted fuel efficiency − We print the predicted fuel efficiency of the new car to the console

  • Print the test metrics − We print the test MAE and MSE to the console.

The program below uses Tensorflow to build a neural network model for predicting fuel efficiency from the Auto MPG dataset.

Example

# Import necessary libraries
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import pandas as pd

# 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 the dataset into features and labels
cfeatures = dataset.drop('MPG', axis=1)
labels = dataset['MPG']

# Normalize the features using min-max scaling
normalized_features = (cfeatures - cfeatures.min()) / (cfeatures.max() - cfeatures.min())

# Split the dataset into training and testing sets
train_features = normalized_features[:300]
test_features = normalized_features[300:]
train_labels = labels[:300]
test_labels = labels[300:]

# Define the model architecture for this we will use sequential API of the keras
model1 = keras.Sequential([
   layers.Dense(64, activation='relu', input_shape=[len(train_features.keys())]),
   layers.Dense(64, activation='relu'),
   layers.Dense(1)
])
#if you want summary of the model’s architecture you can use the code: model1.summary()

# Model compilation
optimizer = tf.keras.optimizers.RMSprop(0.001)
model1.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse'])

# Train the model
Mhistory = model1.fit(
   train_features, train_labels,
   epochs=1000, validation_split = 0.2, verbose=0)

# Evaluate the model on the test set
test_loss, test_mae, test_mse = model1.evaluate(test_features, test_labels)
# Train the model
model1.fit(train_features, train_labels, epochs=1000, verbose=0)

# Calculation of the fuel efficiency for a new car
new_car_features = pd.DataFrame([[4, 121, 110, 2800, 15.4, 81, 3]], columns=column_names[1:])

normalized_new_car_features = (new_car_features - cfeatures.min()) / (cfeatures.max() - cfeatures.min())
fuel_efficiencyc = model1.predict(normalized_new_car_features)

# Print the test metrics
print("Test MAE:", test_mae)
print("Test MSE:", test_mse)
print("Predicted Fuel Efficiency:", fuel_efficiencyc[0][0])

Output

C:\Users\Tutorialspoint>python image.py
3/3 [==============================] - 0s 2ms/step - loss: 18.8091 - mae: 3.3231 - mse: 18.8091
1/1 [==============================] - 0s 90ms/step
Test MAE: 3.3230929374694824
Test MSE: 18.80905532836914
Predicted Fuel Efficiency: 24.55885

Conclusion

In conclusion, using Tensorflow in Python to predict fuel efficiency is a powerful tool that can assist both manufacturers and consumers in making informed decisions. We can accurately predict fuel efficiency by analyzing various vehicle features and training a neural network model.

This information can lead to the development of more fuel-efficient vehicles, reducing environmental impact and saving costs for consumers. Tensorflow's versatility and ease of use make it a valuable asset in the pursuit of improved fuel efficiency in the automotive industry.

Updated on: 25-Jul-2023

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements