17 for (
float x : vector) sum += x * x;
19 float scale = 1 / std::sqrt(sum);
20 for (
float& x : vector) x *= scale;
25std::vector<Embedding>
FastRP(
const Graph& graph, std::string_view type,
31 std::mt19937 random(seed);
32 std::vector<Embedding> round(count);
34 for (
float& x : vector) {
35 uint32_t draw = random() % 6;
36 x = draw == 0 ? 1.0f : draw == 1 ? -1.0f : 0.0f;
41 std::vector<std::vector<NodeId>> neighbours(count);
42 for (
NodeId node = 0; node < count; ++node) {
48 constexpr float kWeights[] = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f};
49 std::vector<Embedding> embeddings(count);
50 for (
float weight : kWeights) {
51 std::vector<Embedding> next(count);
52 for (
NodeId node = 0; node < count; ++node) {
53 for (
NodeId neighbour : neighbours[node]) {
55 next[node][i] += round[neighbour][i];
58 Normalise(next[node]);
60 embeddings[node][i] += weight * next[node][i];
63 round = std::move(next);
74 a_squares += a[i] * a[i];
75 b_squares += b[i] * b[i];
77 if (a_squares == 0 || b_squares == 0)
return 0;
78 return dot / std::sqrt(a_squares * b_squares);
82 const std::vector<Embedding>& embeddings,
NodeId node,
size_t k) {
83 std::vector<std::pair<NodeId, float>> similar;
84 for (
NodeId other = 0; other < embeddings.size(); ++other) {
85 if (other == node)
continue;
86 similar.push_back({other,
Cosine(embeddings[node], embeddings[other])});
90 k = std::min(k, similar.size());
92 similar.begin(), similar.begin() + k, similar.end(),
93 [](
const auto& a,
const auto& b) { return a.second > b.second; });
A graph kept in three files of records, one for nodes, one for relationships and one for their proper...
size_t node_count() const
std::vector< NodeId > Neighbours(NodeId node, std::string_view type, Direction direction=Direction::kOut) const
Returns the nodes the hops along relationships of type lead to.
constexpr size_t kEmbeddingSize
How many numbers a node's embedding has.
std::array< float, kEmbeddingSize > Embedding
A node's embedding: a vector of numbers that stands for where the node is in the graph,...
float Cosine(const Embedding &a, const Embedding &b)
How alike two embeddings are: the cosine of the angle between them, 1 when they point the same way,...
std::vector< std::pair< NodeId, float > > MostSimilar(const std::vector< Embedding > &embeddings, NodeId node, size_t k)
Returns the k nodes whose embeddings are most like node's, with their cosines, the most alike first.
std::vector< Embedding > FastRP(const Graph &graph, std::string_view type, uint32_t seed)
Returns an embedding for each node, in the order of their ids, computed with FastRP,...