Losses in forecasting _cosine similarity class ,mean square logarithmic error , and huber class
8 ビュー (過去 30 日間)
古いコメントを表示
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)
0 件のコメント
回答 (1 件)
Vaibhav
2024 年 4 月 24 日
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);
fprintf('Mean Square Logarithmic Error: %f\n', msle);
fprintf('Huber Loss: %f\n', huberL);
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!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Handle Classes についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!