SQL 中的稀疏点积

发布于 2024-07-25 22:42:43 字数 343 浏览 0 评论 0原文

想象一下,我有一个存储一系列稀疏向量的表。 稀疏向量意味着它仅在数据结构中显式存储非零值。 我可以有一个 100 万维向量,但我只存储非零维度的值。 因此,大小与非零条目的数量成正比,而不是与向量的维数成正比。

表定义将是这样的: 矢量_id:整数 维度:整数 value : float

现在,在正常编程领域,我可以在 O(|v1| + |v2|) 时间内计算两个向量的内积或点积。 基本上,该算法是存储按维度排序的稀疏向量,并迭代每个维度中的维度,直到发现维度之间的冲突,然后将共享维度的值相乘,然后不断相加,直到到达任一向量的末尾。

在 SQL 中实现这一点的最快方法是什么?

Imagine I have a table which stores a series of sparse vectors. A sparse vector means that it stores only the nonzero values explicitly in the data structure. I could have a 1 million dimensional vector, but I only store the values for the dimensions which are nonzero. So the size is proportional to the number of nonzero entries, not the dimensionality of the vector.

Table definition would be something like this:
vector_id : int
dimension : int
value : float

Now, in normal programming land I can compute the inner product or dot product of two vectors in O(|v1| + |v2|) time. Basically the algorithm is to store the sparse vectors sorted by dimension and iterate through the dimensions in each until you find collisions between dimensions and multiply the values of the shared dimension and keep adding those up until you get to the end of either one of the vectors.

What's the fastest way to pull this off in SQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

草莓酥 2024-08-01 22:42:43

您应该能够在一个查询中复制此算法:

select sum(v1.value * v2.value)
from vectors v1
inner join vectors v2
on v1.dimension = v2.dimension
where v1.vector_id = ...
and v2.vector_id = ...

You should be able to replicate this algorithm in one query:

select sum(v1.value * v2.value)
from vectors v1
inner join vectors v2
on v1.dimension = v2.dimension
where v1.vector_id = ...
and v2.vector_id = ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文