使用Python中的Tensorflow预测燃油效率

使用Python中的Tensorflow预测燃油效率

预测燃油效率对于优化车辆性能和减少碳排放至关重要,这可以使用 Python 库 Tensorflow 轻松预测。在本文中,我们将探讨如何利用流行的机器学习库 Tensorflow 的强大功能,使用 Python 来预测燃油效率。通过基于 Auto MPG 数据集构建预测模型,我们可以准确估计车辆的燃油效率。让我们深入了解在 Python 中利用 Tensorflow 进行准确燃油效率预测的过程。

自动 MPG 数据集

为了准确预测燃油效率,我们需要可靠的数据集。 Auto MPG 数据集源自 UCI 机器学习存储库,为我们的模型提供了必要的信息。它包含各种属性,例如气缸数量、排量、重量、马力、加速度、原产地和型号年份。这些属性充当特征,而燃油效率(以每加仑英里数或 MPG 为单位衡量)充当标签。通过分析该数据集,我们可以训练模型识别模式并根据相似的车辆特征进行预测。

准备数据集

在构建预测模型之前,我们需要准备数据集。这涉及处理缺失值和标准化特征。缺失值可能会破坏训练过程,因此我们将它们从数据集中删除。对马力和重量等特征进行标准化可确保每个特征都处于相似的范围内。这一步至关重要,因为具有大数值范围的特征可以主导模型的学习过程。标准化数据集可确保在训练期间公平对待所有特征。

如何使用 TensorFlow 预测燃油效率?

以下是我们使用 Tensorflow 预测燃油效率时将遵循的步骤 -

  • 导入必要的库 - 我们导入tensorflow、Keras、layers 和 pandas。

  • 加载 Auto MPG 数据集。我们还指定列名称并处理任何缺失值。

  • 将数据集分为特征和标签 - 我们将数据集分为两部分 - 特征(输入变量)和标签(输出变量)。

  • 标准化特征 - 我们使用最小-最大缩放来标准化特征。

  • 数据集分为训练集和测试集。

  • 定义模型架构 - 我们定义一个具有三个密集层的简单顺序模型,其中每层有 64 个神经元并使用 ReLU 激活函数。

  • 编译模型 - 我们使用均方误差 (MSE) 损失函数和 RMSprop 优化器编译模型。

  • 训练模型 - 在训练集上进行 1000 个时期的模型训练,并指定验证分割为 0.2。

  • 评估模型 - 在测试集上进行模型评估并计算平均 MSE 以及燃油效率和绝对误差 (MAE)。

  • 计算新车的燃油效率 - 我们使用 pandas DataFrame 创建新车的功能。我们使用与原始数据集相同的缩放因子来标准化新车的特征。

  • 使用经过训练的模型预测新车的燃油效率。

  • 打印预测燃油效率 - 我们将新车的预测燃油效率打印到控制台

  • 打印测试指标 - 我们将测试 MAE 和 MSE 打印到控制台。

下面的程序使用 Tensorflow 构建神经网络模型,用于根据 Auto MPG 数据集预测燃油效率。

示例

# Import necessary libraries import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import pandas as pd 1. 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) 1. Drop missing values dataset = raw_dataset.dropna() 1. Separate the dataset into features and labels cfeatures = dataset.drop('MPG', axis=1) labels = dataset['MPG'] 1. Normalize the features using min-max scaling normalized_features = (cfeatures - cfeatures.min()) / (cfeatures.max() - cfeatures.min()) 1. 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:] 1. 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() 1. Model compilation optimizer = tf.keras.optimizers.RMSprop(0.001) model1.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse']) 1. Train the model Mhistory = model1.fit( train_features, train_labels, epochs=1000, validation_split = 0.2, verbose=0) 1. Evaluate the model on the test set test_loss, test_mae, test_mse = model1.evaluate(test_features, test_labels) 1. Train the model model1.fit(train_features, train_labels, epochs=1000, verbose=0) 1. 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) 1. Print the test metrics print("Test MAE:", test_mae) print("Test MSE:", test_mse) print("Predicted Fuel Efficiency:", fuel_efficiencyc[0][0]) 登录后复制