smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
embed.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <cmath>
5#include <cstddef>
6#include <cstdint>
7#include <random>
8#include <utility>
9#include <vector>
10
11namespace smollergraph {
12namespace {
13
14// Scales a vector to a length of one, unless it's all zeros.
15void Normalise(Embedding& vector) {
16 float sum = 0;
17 for (float x : vector) sum += x * x;
18 if (sum == 0) return;
19 float scale = 1 / std::sqrt(sum);
20 for (float& x : vector) x *= scale;
21}
22
23} // namespace
24
25std::vector<Embedding> FastRP(const Graph& graph, std::string_view type,
26 uint32_t seed) {
27 size_t count = graph.node_count();
28 // Each number of a node's first vector is 1 or -1, with a chance of one in
29 // six each, and otherwise 0: a very sparse random projection, which keeps
30 // the vectors of unrelated nodes close to right angles from each other.
31 std::mt19937 random(seed);
32 std::vector<Embedding> round(count);
33 for (Embedding& vector : round) {
34 for (float& x : vector) {
35 uint32_t draw = random() % 6;
36 x = draw == 0 ? 1.0f : draw == 1 ? -1.0f : 0.0f;
37 }
38 }
39 // Each round goes through each node's neighbours, so they're read from
40 // disk once, for all five.
41 std::vector<std::vector<NodeId>> neighbours(count);
42 for (NodeId node = 0; node < count; ++node) {
43 neighbours[node] = graph.Neighbours(node, type, Direction::kBoth);
44 }
45 // Each round's weight in the embedding, as GDS's iterationWeights have them,
46 // with two rounds more than its default of three, as a species' relatives in
47 // a tree of taxa are four hops away, through the genus and the family.
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]) {
54 for (size_t i = 0; i < kEmbeddingSize; ++i) {
55 next[node][i] += round[neighbour][i];
56 }
57 }
58 Normalise(next[node]);
59 for (size_t i = 0; i < kEmbeddingSize; ++i) {
60 embeddings[node][i] += weight * next[node][i];
61 }
62 }
63 round = std::move(next);
64 }
65 return embeddings;
66}
67
68float Cosine(const Embedding& a, const Embedding& b) {
69 float dot = 0;
70 float a_squares = 0;
71 float b_squares = 0;
72 for (size_t i = 0; i < kEmbeddingSize; ++i) {
73 dot += a[i] * b[i];
74 a_squares += a[i] * a[i];
75 b_squares += b[i] * b[i];
76 }
77 if (a_squares == 0 || b_squares == 0) return 0;
78 return dot / std::sqrt(a_squares * b_squares);
79}
80
81std::vector<std::pair<NodeId, float>> MostSimilar(
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])});
87 }
88 // The k largest cosines go to the front, in order, and the rest stay
89 // unsorted behind them.
90 k = std::min(k, similar.size());
91 std::partial_sort(
92 similar.begin(), similar.begin() + k, similar.end(),
93 [](const auto& a, const auto& b) { return a.second > b.second; });
94 similar.resize(k);
95 return similar;
96}
97
98} // namespace smollergraph
A graph kept in three files of records, one for nodes, one for relationships and one for their proper...
Definition graph.h:113
size_t node_count() const
Definition graph.h:202
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.
Definition graph.cc:262
constexpr size_t kEmbeddingSize
How many numbers a node's embedding has.
Definition graph.h:90
std::array< float, kEmbeddingSize > Embedding
A node's embedding: a vector of numbers that stands for where the node is in the graph,...
Definition graph.h:96
uint32_t NodeId
Definition graph.h:20
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,...
Definition embed.cc:68
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.
Definition embed.cc:81
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,...
Definition embed.cc:25