0

Golang 余弦相似度的简易算法

 2 years ago
source link: https://violarulan.github.io/blog/golang-simple-similarity-comparison/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Programmer, Data Analyst and Gamer

Golang 余弦相似度的简易算法

Oct 28, 2016
已阅读了一分钟
package main
 
import (
    "fmt"
    "errors"
    "math"
)
 
func Cosine(a []float64, b []float64) (cosine float64, err error) {
    count := 0
    length_a := len(a)
    length_b := len(b)
    if length_a > length_b {
        count = length_a
    } else {
        count = length_b
    }
    sumA := 0.0
    s1 := 0.0
    s2 := 0.0
    for k := 0; k < count; k++ {
        if k >= length_a {
            s2 += math.Pow(b[k], 2)
            continue
        }
        if k >= length_b {
            s1 += math.Pow(a[k], 2)
            continue
        }
        sumA += a[k] * b[k]
        s1 += math.Pow(a[k], 2)
        s2 += math.Pow(b[k], 2)
    }
    if s1 == 0 || s2 == 0 {
        return 0.0, errors.New("Vectors should not be null (all zeros)")
    }
    return sumA / (math.Sqrt(s1) * math.Sqrt(s2)), nil
}
 
func main(){
    cos, err := Cosine([]float64{0, 1, 0, 1, 1}, []float64{1, 0, 1, 0, 0})
    if err != nil {
        panic(err)
    }
    fmt.Println(cos)
}

回到文章列表


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK