简体   繁体   English

使用 NumPy 写出分段函数?

[英]Write down piecewise functions using NumPy?

I'm new to NumPy and trying to figure out how can I write down piecewise-defined function.我是 NumPy 的新手,并试图弄清楚如何写下分段定义的 function。 I'm having a derivative of MSE_Loss function using ReLU as activation function:我有一个 MSE_Loss function 的衍生物,使用 ReLU 作为激活 function: 在此处输入图像描述

I have all parameters I need.我有我需要的所有参数。 My question is: how to use NumPy to handle piecewise functions (preferable without using loops)?我的问题是:如何使用 NumPy 来处理分段函数(最好不使用循环)?

EDITED : For example, I can write down the following function using NumPy following way:编辑:例如,我可以使用 NumPy 以下方式写下以下 function : 在此处输入图像描述

def loss_derivative(X, y, w, b):
    n = len(y)
    sigma = sigmoid(X @ w + b)
    return (X.T @ ((sigma - y) * sigma * (1 - sigma))) / n

How can I implement function with the same input for the piecewise formula from above?如何使用上面的分段公式相同的输入来实现 function?

I think the easiest way for this example is using condition multiplier as follows (not all elements in your function is defined in your question, so I am guessing them. However, you can fix it easily if it is not the case):我认为此示例最简单的方法是使用条件乘数,如下所示(并非 function 中的所有元素都在您的问题中定义,所以我猜测它们。但是,如果不是这种情况,您可以轻松修复它):

def loss_derivative(X, y, w):
    n = len(y)
    return X.T @ (((X @ w - y) / n) * ((X @ w) > 0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM