【发布时间】:2020-02-20 03:50:31
【问题描述】:
作为我的 ML uni 课程的一部分,我正在学习线性回归。奇怪的是,我遇到了以下问题,我不知道该怎么做。
给定两个向量 x 和 y:
x = np.linspace(x_min, x_max,50)
y = np.random.randint(-5/2,5/2, size=50)
y = y + 3 + 2*x
我需要在这两个方法中填写代码:
def linear_hypothesis(theta_0, theta_1):
''' Combines given arguments in a linear equation and returns it as a function
Args:
theta_0: first coefficient
theta_1: second coefficient
Returns:
lambda that models a linear function based on theta_0, theta_1 and x
'''
def mse_cost_function(x, y):
''' Implements MSE cost function as a function J(theta_0, theta_1) on given tranings data
Args:
x: vector of x values
y: vector of ground truth values y
Returns:
lambda J(theta_0, theta_1) that models the cost function
'''
然后应该通过以下代码调用上述函数:
j = mse_cost_function(x, y)
print(j(2.1, 2.9))
这让我很困惑。我不确定每个函数的返回类型应该是什么,我不明白这行j(2.1, 2.9) 应该做什么,因为 j 是这个方法的返回值。有人可以启发我吗?感谢您的帮助!
【问题讨论】:
-
写得很清楚——
mse_cost_function应该返回一个函数(一个 lambda),这就是为什么做j(2.1, 2.9)是完全合理的 -
在 Python 函数中,几乎所有其他函数都是"first class objects",这意味着您可以将它们存储在变量中,将它们作为参数传递或返回其他函数的值等。
标签: python function numpy linear-regression data-science