Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xây dựng mô hình Sequential trên Auto MPG với TensorFlow (hồi quy tuyến tính)


TensorFlow (Google) là framework học máy mã nguồn mở, dùng Python. Tensor là mảng đa chiều với 3 thuộc tính: Rank (số chiều), Type (kiểu dữ liệu), Shape (hình dạng).

Cài đặt: pip install tensorflow

Bài toán hồi quy: dự đoán biến liên tục. Dữ liệu Auto MPG: xe hơi thập niên 70-80, đặc trưng: trọng lượng, mã lực, dung tích... Dự đoán MPG.

Mô hình Sequential: xếp chồng các lớp (layers). Chạy trên Google Colab (Python trên trình duyệt, GPU miễn phí).

Ví dụ

print("Xây dựng Sequential model với 1 lớp Dense")
linear_model = tf.keras.Sequential([
    normalizer,
    layers.Dense(units=1)
])

print("Dự đoán ban đầu")
linear_model.predict(train_features[:10])
linear_model.layers[1].kernel

print("Biên dịch mô hình")
linear_model.compile(
    optimizer=tf.optimizers.Adam(learning_rate=0.1),
    loss='mean_absolute_error')

print("Huấn luyện (fit) mô hình")
history = linear_model.fit(
    train_features, train_labels,
    epochs=150,
    verbose=0,
    validation_split=0.25)

print("Vẽ biểu đồ loss dự đoán")
plot_loss(history)

print("Đánh giá kết quả")
test_results['linear_model'] = linear_model.evaluate(
    test_features, test_labels, verbose=0)

Nguồn mã: TensorFlow Regression Tutorial

Đầu ra

Xây dựng mô hình Sequential trên Auto MPG với TensorFlow (hồi quy tuyến tính)

Giải thích

  • Xây dựng kiến trúc Sequential bằng Keras API.
  • Dự đoán MPG ban đầu (chưa train).
  • Công thức hồi quy tuyến tính: y = mx + b.
  • Biên dịch mô hình với optimizer Adam (lr=0.1), loss MAE.
  • Huấn luyện 150 epochs, validation split 25%.
  • Vẽ biểu đồ loss qua các epoch.
  • Đánh giá trên tập test.