# Losses in forecasting _cosine similarity class ,mean square logarithmic error , and huber class

5 views (last 30 days)
NN on 1 Apr 2021
Answered: Vaibhav on 24 Apr 2024
How can i write the code for calculating cosine similarity class ,mean square logarithmic error , and huber class in matlab code for Ypred and Ytrue.(prediction and actual value)

Vaibhav on 24 Apr 2024
Hi NN
Cosine similarity measures the cosine of the angle between two non-zero vectors. MSLE is a variant of the Mean Squared Error (MSE) that focuses on the logarithm of the predictions and actual values, penalizing underestimates more than overestimates. The Huber loss is less sensitive to outliers in data than the squared error loss. It’s quadratic for small errors and linear for large errors.
Here is the example code for your reference:
% Example data
Ytrue = [1, 2, 3, 4, 5];
Ypred = [1.1, 1.9, 3.2, 4.1, 4.9];
% Calculate losses
cosSim = cosine_similarity(Ytrue, Ypred);
msle = mean_square_logarithmic_error(Ytrue, Ypred);
huberL = huber_loss(Ytrue, Ypred, 1.35); % delta is a hyperparameter, adjust as needed
% Display results
fprintf('Cosine Similarity: %f\n', cosSim);
Cosine Similarity: 0.999310
fprintf('Mean Square Logarithmic Error: %f\n', msle);
Mean Square Logarithmic Error: 0.001317
fprintf('Huber Loss: %f\n', huberL);
Huber Loss: 0.008000
function huberLoss = huber_loss(Ytrue, Ypred, delta)
% Calculate the absolute difference
absDiff = abs(Ytrue - Ypred);
% Calculate Huber loss
huberLoss = zeros(size(absDiff));
isSmallError = absDiff < delta;
huberLoss(isSmallError) = 0.5 * absDiff(isSmallError).^2;
% Linear for large errors
huberLoss(~isSmallError) = delta * (absDiff(~isSmallError) - 0.5 * delta);
% Mean of all losses
huberLoss = mean(huberLoss);
end
function msle = mean_square_logarithmic_error(Ytrue, Ypred)
% Ensure positive values, as logarithm of zero or negative numbers is undefined
Ytrue(Ytrue <= 0) = eps; % eps is the smallest positive number in MATLAB
Ypred(Ypred <= 0) = eps;
% Calculate MSLE
msle = mean((log(Ytrue + 1) - log(Ypred + 1)).^2);
end
function cosineSimilarity = cosine_similarity(Ytrue, Ypred)
% Ensure the vectors are row vectors
Ytrue = Ytrue(:)';
Ypred = Ypred(:)';
% Calculate the cosine similarity
cosineSimilarity = dot(Ytrue, Ypred) / (norm(Ytrue) * norm(Ypred));
end
Hope it helps!