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

9 visualizaciones (últimos 30 días)
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)

Respuestas (1)

Vaibhav
Vaibhav el 24 de Abr. de 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;
% Quadratic for small errors
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!

Categorías

Más información sobre Handle Classes en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by