设置线性回归
单变量线性回归用于识别单个特征与目标张量之间的关系。在本练习中,我们将使用房产的占地面积和价格。正如视频中所述,我们将对两个张量取自然对数,它们分别为 price_log 和 size_log。
在本练习中,您将定义模型和损失函数。然后,您将针对两个不同的 intercept 和 slope 值评估损失函数。请记住,预测值由 intercept + features*slope 给出。另外,keras.losses.mse() 可供您使用。此外,slope 和 intercept 已经被定义为变量。
本练习是课程的一部分
Python 中的 TensorFlow 入门
练习说明
- 定义一个函数,使用
intercept、features和slope返回线性回归的预测值,且不使用add()或multiply()。 - 通过将模型变量
intercept和slope作为参数,完成loss_function()。 - 使用
targets和predictions计算均方误差。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define a linear regression model
def linear_regression(intercept, slope, features = size_log):
return ____
# Set loss_function() to take the variables as arguments
def loss_function(____, ____, features = size_log, targets = price_log):
# Set the predicted values
predictions = linear_regression(intercept, slope, features)
# Return the mean squared error loss
return keras.losses.____
# Compute the loss for different slope and intercept values
print(loss_function(0.1, 0.1).numpy())
print(loss_function(0.1, 0.5).numpy())