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

PhotoSearchModel.swift: "cosine_similarity" function #26

Closed
HKdAlex opened this issue Nov 11, 2023 · 3 comments
Closed

PhotoSearchModel.swift: "cosine_similarity" function #26

HKdAlex opened this issue Nov 11, 2023 · 3 comments

Comments

@HKdAlex
Copy link
Contributor

HKdAlex commented Nov 11, 2023

Is this function actually correct?

func cosine_similarity(A: MLShapedArray<Float32>, B: MLShapedArray<Float32>) -> Float {
        let magnitude = vDSP.rootMeanSquare(A.scalars) * vDSP.rootMeanSquare(B.scalars)
        let dotarray = vDSP.dot(A.scalars, B.scalars)
        return  dotarray / magnitude
 }

This line does not seem to be calculating the magnitude of a vector which is supposed to the square root of the sum of squares (RSS) but is actually calculating the RMS (the square root of the mean sum of squares):

let magnitude = vDSP.rootMeanSquare(A.scalars) * vDSP.rootMeanSquare(B.scalars)

My suggested correction would be:

let magnitude = vDSP.sumOfSquares(A.scalars).squareRoot() * vDSP.sumOfSquares(B.scalars).squareRoot()

I am not good at this stuff but trying t figure it out.

@mazzzystar
Copy link
Owner

Thank you for the correction, I indeed should not have divided by 1/n when calculating the sum, you are right. Can you submit a PR (Pull Request)?

@HKdAlex
Copy link
Contributor Author

HKdAlex commented Nov 13, 2023

Yes, submitted a pull request, though I never did it before. Hoping I did it correctly.

@mazzzystar
Copy link
Owner

@HKdAlex Merged, your implementation is correct, thank you for pointing it out !

mazzzystar added a commit that referenced this issue Jan 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants