Linear regression

TensorFlow เบื้องต้นใน Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

Linear regression คืออะไร?

ภาพแสดง scatter plot ของลอการิทึมธรรมชาติของขนาดบ้าน (ตารางฟุต) เทียบกับลอการิทึมธรรมชาติของราคาบ้าน (ดอลลาร์)

TensorFlow เบื้องต้นใน Python

Linear regression คืออะไร?

ภาพแสดงเส้น regression ที่ fit กับ scatter plot ของลอการิทึมธรรมชาติของขนาดบ้าน (ตารางฟุต) เทียบกับลอการิทึมธรรมชาติของราคาบ้าน (ดอลลาร์)

TensorFlow เบื้องต้นใน Python

โมเดล linear regression

  • โมเดล linear regression สมมติว่ามีความสัมพันธ์เชิงเส้น:
    • $price = intercept + size*slope + error$
  • นี่คือตัวอย่างของ univariate regression
    • มี feature เดียว คือ size
  • โมเดล multiple regression มี feature มากกว่าหนึ่งตัว
    • เช่น size และ location
TensorFlow เบื้องต้นใน Python

Linear regression ใน TensorFlow

# Define the targets and features
price = np.array(housing['price'], np.float32)
size = np.array(housing['sqft_living'], np.float32)

# Define the intercept and slope
intercept = tf.Variable(0.1, np.float32)
slope = tf.Variable(0.1, np.float32)
# Define a linear regression model
def linear_regression(intercept, slope, features = size):
    return intercept + features*slope
# Compute the predicted values and loss
def loss_function(intercept, slope, targets = price, features = size):
    predictions = linear_regression(intercept, slope)
    return tf.keras.losses.mse(targets, predictions)
TensorFlow เบื้องต้นใน Python

Linear regression ใน TensorFlow

# Define an optimization operation
opt = tf.keras.optimizers.Adam()
# Minimize the loss function and print the loss
for j in range(1000):
    opt.minimize(lambda: loss_function(intercept, slope),\
    var_list=[intercept, slope])
    print(loss_function(intercept, slope))
tf.Tensor(10.909373, shape=(), dtype=float32)
...
tf.Tensor(0.15479447, shape=(), dtype=float32)
# Print the trained parameters
print(intercept.numpy(), slope.numpy())
TensorFlow เบื้องต้นใน Python

มาฝึกกันเถอะ!

TensorFlow เบื้องต้นใน Python

Preparing Video For Download...