线性回归

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...