作为我的ML大学课程的一部分,我正在学习线性回归。奇怪的是,我遇到了以下问题,不确定如何解决。
给定两个向量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是一个返回function的函数。
对成本函数进行建模的λJ(theta_0,theta_1)
所以j是功能。像任何函数(或更普遍地可调用)一样,它可以获取输入(在这种情况下为两个)。
为了进行更简单的说明,这是一个函数add_x
,该函数采用x并返回一个新函数,该函数采用z并计算z + x
def add_x(x):
return lambda z: z+x
g = add_x(3)
print(type(g)) # -> <class 'function'>
print(g(2)) # 5