Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การฝึกโมเดล Linear ด้วย TensorFlow ใน Python


บทนำ

TensorFlow เฟรมเวิร์ก ML จาก Google โค้ดเปิด ใช้กับ Python ใช้ในงานวิจัยและการผลิต

การติดตั้ง

pip install tensorflow

คุณสมบัติ Tensor

  • Rank - มิติของเทนเซอร์
  • Type - ชนิดข้อมูลองค์ประกอบ
  • Shape - ขนาดแถวและคอลัมน์

ตัวอย่าง: Linear Regression ด้วย TensorFlow 1.x Style (Session)

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}")

หมายเหตุ: รันบน Jupyter Notebook ติดตั้ง TensorFlow ด้วย pip install tensorflow

ผลลัพธ์

i: 0 cost: 1.7808
i: 100 cost: 1.6948
i: 200 cost: 1.6916
...
i: 900 cost: 1.6914
A: [1.4599526] b: [0.07214472] cost: 1.6913845539093018

คำอธิบาย

  • นำเข้าแพ็กเกจและตั้งชื่อย่อ
  • กำหนดตัวแปร my_model เก็บสมการ Linear
  • ใช้ GradientDescentOptimizer ฝึกโมเดล
  • ลด loss ให้น้อยที่สุดด้วย minimize
  • สร้างข้อมูลฝึก 2 ลิสต์
  • รัน Session ฝึก 1000 รอบ แสดง cost ทุก 100 รอบ
  • แสดงค่า A, b, cost สุดท้าย