Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added loss function and unit test for Poisson Loss #211

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions MLlib/loss_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,62 @@ def loss(X, Y, W):
y_pred = np.dot(X, W).T
L = np.sum(np.true_divide((np.abs(Y - y_pred) * 100), Y)) / X.shape[0]
return L


class PoisonLoss():
"""
Calculate Poisson Loss.
"""

@staticmethod
def loss(X, Y, W):
"""
Calculate Poisson Loss.

PARAMETERS
==========

X: ndarray(dtype=float)
Input vector
Y: ndarray(dtype=float)
Output vector
W: ndarray(dtype=float)
Weights

RETURNS
=======

float or ndarray
array of Poisson losses or
float value of Poisson loss
(depending on the parameters)
"""

y_pred = np.dot(X, W).T
return np.mean(y_pred - Y * np.log(y_pred), axis=-1)

@staticmethod
def derivative(X, Y, W):
"""
Calculate derivative for Poisson Loss method.

PARAMETERS
==========

X: ndarray(dtype=float)
Input vector
Y: ndarray(dtype=float)
Output vector
W: ndarray(dtype=float)
Weights

RETURNS
=======

ndarray
array of derivatives
"""

M = X.shape[0]
y_pred = np.dot(X, W).T
return np.dot(1 - Y / y_pred, X) / M
26 changes: 26 additions & 0 deletions MLlib/tests/test_loss_func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from MLlib.loss_func import PoisonLoss
import numpy as np


def test_poisson_loss():
X = np.array([[0.32794909, 0.69075792],
[0.9059869, 0.77822567],
[0.77191135, 0.73130334],
[0.78795424, 0.89521624],
[0.96298287, 0.29203895],
[0.17946441, 0.75993963],
[0.05451229, 0.85694996],
[0.2915702, 0.0805041],
[0.57499626, 0.10640506],
[0.95203463, 0.78138885],
[0.51214417, 0.8854669],
[0.94145457, 0.84719198]])
Y = np.array([[0.78936729, 0.8704933, 0.88695031, 0.98672232, 0.29796081,
0.59689156, 0.88899604, 0.85520577, 0.18910425, 0.84729253,
0.53142304, 0.7346871]])
W = np.array([[0.15736584],
[0.3036601]])

poissonLoss = np.array([1.19509275])

assert np.isclose(PoisonLoss.loss(X, Y, W), poissonLoss).all()