使用TensorFlow(Python)預測燃油效率


預測燃油效率對於最佳化車輛效能和減少碳排放至關重要,這可以使用Tensorflow(Python的一個庫)輕鬆預測。在本文中,我們將探討如何利用流行的機器學習庫TensorFlow來使用Python預測燃油效率。透過基於Auto MPG資料集構建預測模型,我們可以準確地估計車輛的燃油效率。讓我們深入瞭解使用Python中的TensorFlow進行準確的燃油效率預測的過程。

Auto MPG資料集

為了準確預測燃油效率,我們需要一個可靠的資料集。來自UCI機器學習儲存庫的Auto MPG資料集為我們的模型提供了必要的資訊。它包含各種屬性,例如氣缸數、排量、重量、馬力、加速效能、產地和車型年份。這些屬性用作特徵,而燃油效率(以每加侖英里數或MPG衡量)則用作標籤。透過分析此資料集,我們可以訓練我們的模型以識別模式並根據類似的車輛特徵進行預測。

準備資料集

在構建預測模型之前,我們需要準備資料集。這包括處理缺失值和規範化特徵。缺失值會擾亂訓練過程,因此我們將其從資料集中刪除。規範化特徵(例如馬力和重量)可確保每個特徵具有相似的比例。此步驟至關重要,因為數值範圍較大的特徵可能會主導模型的學習過程。規範化資料集可確保在訓練期間對所有特徵進行公平處理。

如何使用TensorFlow預測燃油效率?

以下是我們將遵循的步驟,以使用Tensorflow預測燃油效率:

  • 匯入必要的庫 - 我們匯入tensorflow、Keras、layers和pandas。

  • 載入Auto MPG資料集。我們還指定列名並處理任何缺失值。

  • 將資料集分為特徵和標籤 - 我們將資料集分為兩部分 - 特徵(輸入變數)和標籤(輸出變數)。

  • 規範化特徵 - 我們使用最小-最大縮放來規範化特徵。

  • 將資料集分成訓練集和測試集。

  • 定義模型架構 - 我們定義一個具有三個密集層的簡單順序模型,其中每一層都有六十四個神經元並使用ReLU啟用函式。

  • 編譯模型 - 我們使用均方誤差 (MSE) 損失函式和RMSprop最佳化器來編譯模型。

  • 訓練模型 - 在訓練集上訓練模型1000個epoch,並指定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

# 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

結論

總之,在Python中使用TensorFlow預測燃油效率是一種強大的工具,可以幫助製造商和消費者做出明智的決策。透過分析各種車輛特徵和訓練神經網路模型,我們可以準確地預測燃油效率。

這些資訊可以導致開發更節能的車輛,減少對環境的影響併為消費者節省成本。TensorFlow的多功能性和易用性使其成為改進汽車行業燃油效率的有價值的資產。

更新於:2023年7月25日

600 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告