是否有比此列表理解更简单的Numpy阵列广播表达式?

发布于 2025-01-27 02:56:11 字数 477 浏览 4 评论 0原文

在此代码段中:

triangles = np.float32([[[0, -2], [-2, 3], [1, 1]], [[0, -1], [-1, 3], [1, 1]]])
centers = np.average(triangles, axis=1)
samples = np.float32([t-centers[i] for i, t in enumerate(triangles)])

我想将样本作为阵列广播扣除,即类似于triangles-Centers的东西,由于以下原因是不起作用的:

ValueError: operands could not be broadcast together with shapes (2,3,2) (2,2) 

是否有:定义样本的简单方法比列表理解?

In this code snippet:

triangles = np.float32([[[0, -2], [-2, 3], [1, 1]], [[0, -1], [-1, 3], [1, 1]]])
centers = np.average(triangles, axis=1)
samples = np.float32([t-centers[i] for i, t in enumerate(triangles)])

I would like to express samples as an array broadcast subtraction, i.e. something similar to triangles-centers, which doesn't work due to:

ValueError: operands could not be broadcast together with shapes (2,3,2) (2,2) 

Is there a simpler way to define samples than a list comprehension?

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

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

发布评论

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

评论(3

ペ泪落弦音 2025-02-03 02:56:11

使用 numpy.mean.mean keepdims = true在轴上保持一个长度-1维度,您要遵守:

samples = triangles - np.mean(triangles, axis=1, keepdims=True)

Use numpy.mean with keepdims=True to keep a length-1 dimension in the axis you're taking the mean over:

samples = triangles - np.mean(triangles, axis=1, keepdims=True)
ゝ偶尔ゞ 2025-02-03 02:56:11

我相信这做了您想要的。只需重塑中心以匹配行大小即可。

samples = triangles - centers.reshape(triangles.shape[0],-1,triangles.shape[2])

I believe this does what you want. Just reshape the centers to match the row size.

samples = triangles - centers.reshape(triangles.shape[0],-1,triangles.shape[2])
烟雨扶苏 2025-02-03 02:56:11

受@Tim Roberts上面答案的启发:

triangles = np.float32([[[0, -2], [-2, 3], [1, 1]], [[0, -1], [-1, 3], [1, 1]]])
centers = np.average(triangles, axis=1)
samples = triangles-centers[:, None, :]

Inspired by an answer above from @Tim Roberts:

triangles = np.float32([[[0, -2], [-2, 3], [1, 1]], [[0, -1], [-1, 3], [1, 1]]])
centers = np.average(triangles, axis=1)
samples = triangles-centers[:, None, :]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文