【问题标题】:Can a function return a numpy parameter in python?函数可以在python中返回一个numpy参数吗?
【发布时间】: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


【解决方案1】:

mse_cost_function 是一个返回函数的函数。

对代价函数建模的 lambda 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多