在 Python 中获取向量的 1-范数
如何在 Python 中计算两个向量 ||a - b||_1 = sum(|a_i - b_i|)
之差的 1-范数?
a = [1,2,3,4]
b = [2,3,4,5]
||a - b||_1 = 4
How can I calculate the 1-norm of the difference of two vectors, ||a - b||_1 = sum(|a_i - b_i|)
in Python?
a = [1,2,3,4]
b = [2,3,4,5]
||a - b||_1 = 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Python 具有强大的内置类型,但Python 列表不是数学向量或矩阵。 您可以使用列表来完成此操作,但对于除琐碎操作之外的任何操作来说,这可能会很麻烦。
如果您发现自己经常需要向量或矩阵运算,该领域的标准是NumPy,它可能已经像 Python 一样为您的操作系统进行了打包。
我和其他人一样对你想要做什么感到困惑,但也许 numpy.linalg.norm 函数会有所帮助:
展示它是如何在幕后工作的:
Python has powerful built-in types, but Python lists are not mathematical vectors or matrices. You could do this with lists, but it will likely be cumbersome for anything more than trivial operations.
If you find yourself needing vector or matrix arithmetic often, the standard in the field is NumPy, which probably already comes packaged for your operating system the way Python also was.
I share the confusion of others about exactly what it is you're trying to do, but perhaps the numpy.linalg.norm function will help:
To show how that's working under the covers:
在 NumPy 中,对于两个向量
a
和b
,这只是In NumPy, for two vectors
a
andb
, this is just您似乎要求两个数组的配对组件之间的差异之和:
You appear to be asking for the sum of the differences between the paired components of the two arrays:
目前尚不清楚这里到底需要什么,但这是我的猜测
It is not clear what exactly is required here, but here is my guess
使用 Numpy,您可以使用线性代数包计算两个向量之间的任何范数。
示例:
Using Numpy you can calculate any norm between two vectors using the linear algebra package.
Example: