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 SparseCategoricalCrossEntropy Loss Function #40

Closed
Closed
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
23 changes: 23 additions & 0 deletions MLlib/loss_func.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np
from MLlib.activations import sigmoid
from MLlib.activations import softmax


class MeanSquaredError():
Expand Down Expand Up @@ -34,6 +35,28 @@ def loss(X, Y, W):
M = X.shape[0]
return np.sum(np.absolute(np.dot(X, W).T - Y)) / M

class SparseCategoricalCrossEntropy():
@staticmethod
def loss(X,Y,W,n):
# n = total number of classes for classification
# W of dimension (X.shape[1],n)
Yprime = []
for ydash in Y:
for y in ydash:
y=int(y)
yprime = list([0]*y+[1]+[0]*(n-y-1))
Yprime.append(yprime)
Yprime = np.array(Yprime)
H=np.dot(X,W)
for i in range(len(H)):
H[i]=softmax(H[i])
loss=0
for y in range(len(Yprime)):
for feature_index in range(len(Yprime[y])):
if Yprime[y][feature_index] ==1:
loss-=np.log(H[y][feature_index])
return loss

@staticmethod
def derivative(X, Y, W):
M = X.shape[0]
Expand Down