-
Notifications
You must be signed in to change notification settings - Fork 679
/
projector.go
175 lines (144 loc) · 4.63 KB
/
projector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// _ _
// __ _____ __ ___ ___ __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
// \ V V / __/ (_| |\ V /| | (_| | || __/
// \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
// Copyright © 2016 - 2022 SeMI Technologies B.V. All rights reserved.
//
// CONTACT: hello@semi.technology
//
package projector
import (
"context"
"fmt"
"math/rand"
"time"
"github.com/danaugrs/go-tsne/tsne"
"github.com/pkg/errors"
"github.com/semi-technologies/weaviate/entities/models"
"github.com/semi-technologies/weaviate/entities/moduletools"
"github.com/semi-technologies/weaviate/entities/search"
txt2vecmodels "github.com/semi-technologies/weaviate/modules/text2vec-contextionary/additional/models"
"github.com/tailor-inc/graphql/language/ast"
"gonum.org/v1/gonum/mat"
)
func New() *FeatureProjector {
return &FeatureProjector{
fixedSeed: time.Now().UnixNano(),
}
}
type FeatureProjector struct {
fixedSeed int64
}
func (f *FeatureProjector) AdditonalPropertyDefaultValue() interface{} {
return &Params{}
}
func (f *FeatureProjector) AdditionalPropertyFn(ctx context.Context,
in []search.Result, params interface{}, limit *int,
argumentModuleParams map[string]interface{}, cfg moduletools.ClassConfig,
) ([]search.Result, error) {
if parameters, ok := params.(*Params); ok {
return f.Reduce(in, parameters)
}
return nil, errors.New("unknown params")
}
func (f *FeatureProjector) ExtractAdditionalFn(param []*ast.Argument) interface{} {
return parseFeatureProjectionArguments(param)
}
func (f *FeatureProjector) Reduce(in []search.Result, params *Params) ([]search.Result, error) {
if len(in) == 0 {
return nil, nil
}
if params == nil {
return nil, fmt.Errorf("no params provided")
}
dims := len(in[0].Vector)
if err := params.SetDefaultsAndValidate(len(in), dims); err != nil {
return nil, errors.Wrap(err, "invalid params")
}
matrix, err := f.vectorsToMatrix(in, dims, params)
if err != nil {
return nil, err
}
rand.Seed(f.fixedSeed) // TODO: don't use global random function
t := tsne.NewTSNE(*params.Dimensions, float64(*params.Perplexity),
float64(*params.LearningRate), *params.Iterations, false)
t.EmbedData(matrix, nil)
rows, cols := t.Y.Dims()
if rows != len(in) {
return nil, fmt.Errorf("incorrect matrix dimensions after t-SNE len %d != %d", len(in), rows)
}
for i := 0; i < rows; i++ {
vector := make([]float32, cols)
for j := range vector {
vector[j] = float32(t.Y.At(i, j))
}
up := in[i].AdditionalProperties
if up == nil {
up = models.AdditionalProperties{}
}
up["featureProjection"] = &txt2vecmodels.FeatureProjection{
Vector: vector,
}
in[i].AdditionalProperties = up
}
return in, nil
}
func (f *FeatureProjector) vectorsToMatrix(in []search.Result, dims int, params *Params) (*mat.Dense, error) {
items := len(in)
var neighbors []*txt2vecmodels.NearestNeighbor
if params.IncludeNeighbors {
neighbors = f.extractNeighborsAndRemoveDuplicates(in)
items += len(neighbors)
}
// concat all vectors to build gonum dense matrix
mergedVectors := make([]float64, items*dims)
for i, obj := range in {
if l := len(obj.Vector); l != dims {
return nil, fmt.Errorf("inconsistent vector lengths found: %d and %d", dims, l)
}
for j, dim := range obj.Vector {
mergedVectors[i*dims+j] = float64(dim)
}
}
withoutNeighbors := len(in) * dims
for i, neighbor := range neighbors {
neighborVector := neighbor.Vector
if l := len(neighborVector); l != dims {
return nil, fmt.Errorf("inconsistent vector lengths found: %d and %d", dims, l)
}
for j, dim := range neighborVector {
mergedVectors[withoutNeighbors-1+i*dims+j] = float64(dim)
}
}
return mat.NewDense(len(in), dims, mergedVectors), nil
}
func (f *FeatureProjector) extractNeighborsAndRemoveDuplicates(in []search.Result) []*txt2vecmodels.NearestNeighbor {
var out []*txt2vecmodels.NearestNeighbor
for _, obj := range in {
if obj.AdditionalProperties == nil || obj.AdditionalProperties["nearestNeighbors"] == nil {
continue
}
if neighbors, ok := obj.AdditionalProperties["nearestNeighbors"]; ok {
if nearestNeighbors, ok := neighbors.(*txt2vecmodels.NearestNeighbors); ok {
out = append(out, nearestNeighbors.Neighbors...)
}
}
}
return f.removeDuplicateNeighbors(out)
}
func (f *FeatureProjector) removeDuplicateNeighbors(in []*txt2vecmodels.NearestNeighbor) []*txt2vecmodels.NearestNeighbor {
seen := map[string]struct{}{}
out := make([]*txt2vecmodels.NearestNeighbor, len(in))
i := 0
for _, candidate := range in {
if _, ok := seen[candidate.Concept]; ok {
continue
}
out[i] = candidate
i++
seen[candidate.Concept] = struct{}{}
}
return out[:i]
}