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

Huấn luyện mô hình tuyến tính với TensorFlow 1.x (Python)


TensorFlow (Google) framework học máy mã nguồn mở. Cài đặt: pip install tensorflow. Tensor: mảng đa chiều với Rank, Type, Shape.

Sử dụng Jupyter Notebook: pip install tensorflow.

Huấn luyện mô hình tuyến tính với TensorFlow 1.x (Python)

Ví dụ (TensorFlow 1.x style)

import tensorflow as tf

A = tf.get_variable("A", initializer=tf.constant([0.1]))
b = tf.get_variable("b", initializer=tf.constant([0.0]))

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

my_model = A * x + b
lossVal = tf.reduce_sum(tf.square(my_model - y))

my_optimizer = tf.train.GradientDescentOptimizer(0.01)
train = my_optimizer.minimize(lossVal)

x_train = [1.0, 2.5, 3.8, 4.9]
y_train = [1.7, 3.0, 6.6, 6.8]

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(1000):
        sess.run(train, {x: x_train, y: y_train})
        if i % 100 == 0:
            l_cost = sess.run(lossVal, {x: x_train, y: y_train})
            print(f"i: {i} cost: {l_cost}")
    l_A, l_b, l_cost = sess.run([A, b, lossVal], {x: x_train, y: y_train})
    print(f"A: {l_A} b: {l_b} cost: {l_cost}")

Đầu ra

i: 0 cost: 1.7808341979980469
i: 100 cost: 1.6947696208953857
i: 200 cost: 1.691591501235962
i: 300 cost: 1.6913959980010986
i: 400 cost: 1.6913844347000122
i: 500 cost: 1.6913840770721436
i: 600 cost: 1.6913843154907227
i: 700 cost: 1.691383719444275
i: 800 cost: 1.6913838386535645
i: 900 cost: 1.6913845539093018
A: [1.4599526] b: [0.07214472] cost: 1.6913845539093018

Giải thích

  • Import TensorFlow, alias tf.
  • Định nghĩa biến my_model = mô hình tuyến tính.
  • Huấn luyện bằng GradientDescentOptimizer.
  • Minimize loss bằng phương thức minimize().
  • Tạo 2 list dữ liệu train.
  • Chạy session, train 1000 bước, in loss mỗi 100 bước, cuối cùng in A, b, cost.