开始使用免费开始使用

多元线性回归

在大多数情况下,单变量线性回归很难得到足够准确的预测模型。本练习中,您将进行多元回归,也就是使用多个特征。

您将使用 price_log 作为目标变量,size_logbedrooms 作为特征。这些张量都已定义并可直接使用。您还将把损失函数从均方误差切换为平均绝对误差:keras.losses.mae()。最后,预测值按如下方式计算:params[0] + feature1*params[1] + feature2*params[2]。注意,我们将参数向量 params 定义为一个变量,而不是使用 3 个独立变量。其中,params[0] 是截距,params[1]params[2] 是斜率。

本练习是课程的一部分

Python 中的 TensorFlow 入门

查看课程

练习说明

  • 定义一个线性回归模型并返回预测值。
  • loss_function() 以参数向量为输入。
  • 使用平均绝对误差作为损失函数。
  • 完成最小化操作。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Define the linear regression model
def linear_regression(params, feature1 = size_log, feature2 = bedrooms):
	return params[0] + feature1*____ + feature2*____

# Define the loss function
def loss_function(____, targets = price_log, feature1 = size_log, feature2 = bedrooms):
	# Set the predicted values
	predictions = linear_regression(params, feature1, feature2)
  
	# Use the mean absolute error loss
	return keras.losses.____(targets, predictions)

# Define the optimize operation
opt = keras.optimizers.Adam()

# Perform minimization and print trainable variables
for j in range(10):
	opt.minimize(lambda: loss_function(____), var_list=[____])
	print_results(params)
编辑并运行代码