假设我有两个向量并希望获取它们的点积;这很简单,
import numpy as np
a = np.random.rand(3)
b = np.random.rand(3)
result = np.dot(a,b)
Run Code Online (Sandbox Code Playgroud)
如果我有一堆向量并且我希望每个向量都被点缀,那么最简单的代码是
# 5 = number of vectors
a = np.random.rand(5,3)
b = np.random.rand(5,3)
result = [np.dot(aa,bb) for aa, bb in zip(a,b)]
Run Code Online (Sandbox Code Playgroud)
批处理此计算的两种方法是使用乘法和求和以及 einsum,
result = np.sum(a*b, axis=1)
# or
result = np.einsum('ij,ij->i', a, b)
Run Code Online (Sandbox Code Playgroud)
但是,这些都不会分派到 BLAS 后端,因此仅使用单个核心。N当非常大时,比如 100 万,这并不是很好。
tensordot确实分派到 BLAS 后端。使用tensordot进行此计算的一种糟糕方法是
np.diag(np.tensordot(a,b, axes=[1,1])
Run Code Online (Sandbox Code Playgroud)
这很糟糕,因为它分配了一个N*N矩阵,而大多数元素都是浪费的。
另一种(非常快)的方法是隐藏的inner1d函数
from numpy.core.umath_tests import inner1d
result = inner1d(a,b)
Run Code Online (Sandbox Code Playgroud)
但这似乎不可行,因为可能公开导出它的问题已经过时了。这仍然归结为用 C 语言编写循环,而不是使用多个内核。
有没有办法在多个核心上同时获得dot …
我正在尝试处理 fetch 中的 500 个内部服务器错误。如果发生内部错误,服务器会回复一条消息。我想提取该消息。
const req = new Request(url, {
method: node.method,
mode: 'cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
fetch(req)
.then((response) => {
if (response.status === 500) {
// res.json extracts the body from the response as a promise, chain
// .then on it and throw an error to be caught in the lower catch.
response.json()
.then((json) => {
const { message, stackTrace } = json;
throw new ServerException(message, stackTrace); // note 1
})
.catch((error) => …Run Code Online (Sandbox Code Playgroud) 有没有办法在不使用回调和重新执行成本函数的情况下使用 scipy.minimize 在每次迭代的基础上访问成本函数?
options.disp 似乎打算这样做,但只会导致优化器打印终止消息。
将它打印到标准输出并使用contextlib.redirect_stdoutwithio.StringIO收集它并在之后解析数据会很好,但我找不到一种方法来有效地访问每次迭代的成本函数。