線性迴歸

Python 的 TensorFlow 入門

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

什麼是線性迴歸?

此圖為房屋室內坪數(平方英呎)的自然對數與房價(美元)的自然對數之散佈圖。

Python 的 TensorFlow 入門

什麼是線性迴歸?

此圖為在散佈圖上擬合的迴歸線,變數為房屋室內坪數(平方英呎)的自然對數與房價(美元)的自然對數。

Python 的 TensorFlow 入門

線性迴歸模型

  • 線性迴歸模型假設線性關係
    • $price = intercept + size*slope + error$
  • 這是單變量迴歸的例子。
    • 只有一個特徵 size
  • 多元迴歸具有多個特徵。
    • 例如 sizelocation
Python 的 TensorFlow 入門

在 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)
Python 的 TensorFlow 入門

在 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())
Python 的 TensorFlow 入門

一起來練習吧!

Python 的 TensorFlow 入門

Preparing Video For Download...