Home > Article > Backend Development > Predicting fuel efficiency using Tensorflow in Python
Predicting fuel efficiency is critical to optimizing vehicle performance and reducing carbon emissions, and can be easily predicted using the Python library Tensorflow. In this article, we’ll explore how to leverage the power of the popular machine learning library Tensorflow to predict fuel efficiency using Python. By building a predictive model based on the Auto MPG dataset, we can accurately estimate a vehicle's fuel efficiency. Let’s take a deep dive into the process of making accurate fuel efficiency predictions using Tensorflow in Python.
To accurately predict fuel efficiency, we need reliable data sets. The Auto MPG dataset originates from the UCI Machine Learning Repository and provides the necessary information for our model. It contains various attributes such as number of cylinders, displacement, weight, horsepower, acceleration, country of origin, and model year. These attributes serve as characteristics, while fuel efficiency (measured in miles per gallon, or MPG) serves as the label. By analyzing this dataset, we can train the model to recognize patterns and make predictions based on similar vehicle characteristics.
Before building the prediction model, we need to prepare the data set. This involves handling missing values and normalizing features. Missing values can disrupt the training process, so we remove them from the dataset. Standardizing characteristics such as horsepower and weight ensures that each characteristic is in a similar range. This step is crucial because features with large numerical ranges can dominate the model’s learning process. Normalizing the dataset ensures that all features are treated fairly during training.
Here are the steps we will follow when predicting fuel efficiency using Tensorflow -
Import the necessary libraries - we import tensorflow, Keras, layers and pandas.
Load Auto MPG data set. We also specify column names and handle any missing values.
Separate the dataset into features and labels - We split the dataset into two parts - features (input variables) and labels (output variables).
Normalized Features - We use min-max scaling to normalize features.
The data set is divided into training set and test set.
Define model architecture - We define a simple sequential model with three dense layers, with 64 neurons in each layer and using the ReLU activation function.
Compile the model - We compile the model using the mean square error (MSE) loss function and the RMSprop optimizer.
Train model - Train the model for 1000 epochs on the training set and specify a validation split of 0.2.
Evaluate the model - Perform model evaluation on the test set and calculate the average MSE as well as fuel efficiency and absolute error (MAE).
Calculate the fuel efficiency of a new car - We use pandas DataFrame to create a function for a new car. We normalize the features of new cars using the same scaling factor as the original dataset.
Use a trained model to predict the fuel efficiency of new cars.
Print predicted fuel efficiency - We print the predicted fuel efficiency of new cars to the console
Print test metrics - We print the test MAE and MSE to the console.
The following program uses Tensorflow to build a neural network model for predicting fuel efficiency based on the Auto MPG dataset.
# 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])
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
In conclusion, using Tensorflow in Python to predict fuel efficiency is a powerful tool that can help manufacturers and consumers make informed decisions. By analyzing various vehicle characteristics and training a neural network model, we can accurately predict fuel efficiency.
This information can promote the development of more fuel-efficient vehicles, reduce environmental impact and save costs for consumers. Tensorflow's versatility and ease of use make it a valuable asset for the automotive industry in its quest to improve fuel efficiency.
The above is the detailed content of Predicting fuel efficiency using Tensorflow in Python. For more information, please follow other related articles on the PHP Chinese website!