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

การทำงานของ Linear Regression ด้วย TensorFlow ใน Python


บทนำ

TensorFlow เฟรมเวิร์ก ML จาก Google โค้ดเปิด ใช้กับ Python ใช้ในงานวิจัยและการผลิต มีเทคนิคเพิ่มประสิทธิภาพ ใช้ NumPy และเทนเซอร์ รองรับ Deep Neural Networks สเกลได้ดี ใช้ GPU computation จัดการทรัพยากรอัตโนมัติ มีไลบรารี ML มากมาย เอกสารดี

การติดตั้ง

pip install tensorflow

Tensor

เทนเซอร์ = อาร์เรย์หลายมิติ สำหรับ Data flow graph

ตัวอย่าง: Linear Regression ด้วย Gradient Descent

def linear_reg(x):
    return A * x + b

def mean_square_error(y_pred, y_true):
    return tf.reduce_mean(tf.square(y_pred - y_true))

optimizer = tf.optimizers.SGD(learning_rate)

def run_optimization():
    with tf.GradientTape() as g:
        pred = linear_reg(X)
        loss = mean_square_error(pred, Y)
    gradients = g.gradient(loss, [A, b])
    optimizer.apply_gradients(zip(gradients, [A, b]))

ที่มา: TensorFlow Examples

ผลลัพธ์

ฟังก์ชัน Linear Regression ถูกเรียกใช้กับข้อมูล
เมื่อคำนวณจุดข้อมูลที่เหมาะสมแล้ว คำนวณ Mean Square Error
ใช้ Gradient Descent หา optimal weights
แสดงค่าบนคอนโซล

คำอธิบาย

  • สุ่มค่าเริ่มต้น weight (A) และ bias (b) จะอัปเดตเป็นค่าที่เหมาะสมหลังฝึก
  • สมการเส้นตรง: Ax + b โดย A = weight, b = bias
  • กำหนดฟังก์ชัน Mean Square Error
  • กำหนด Stochastic Gradient Descent Optimizer
  • กำหนดฟังก์ชัน optimization: คำนวณ gradients และอัปเดต weight/bias
  • ฝึกข้อมูลจำนวนขั้นตอนที่กำหนด