python - 如何优雅地在 numpy 中编写自定义元素函数?
问题描述
我想使用 np.meshgrid 函数在 2D 网格上做一些事情:
import numpy as np
def gauss2d(x, y):
return np.exp(-(np.power(x-np.arange(10), 2) + np.power(y-np.arange(10), 2)) / 2).sum()
x, y = np.meshgrid(np.arange(5), np.arange(6))
z = gauss2d(x, y)
但出现错误:
ValueError: operands could not be broadcast together with shapes (6,5) (10,)
我只能通过一个简单的嵌套 for 循环实现来做到这一点:
z = np.zeros_like(x)
for i in range(x.shape[1]):
for j in range(x.shape[0]):
z[i, j] = gauss2d(x[i, j], y[i, j])
那么,如何以一种 numpy 的方式优雅地完成它呢?
解决方案
做reshape
第一个,这样 numpy 就知道你每次都在处理两个数字。
In [25]: x = np.reshape(x, [-1, 1])
In [26]: y = np.reshape(y, [-1, 1])
In [28]: def gauss2d(x, y):
...: return np.exp(-(np.power(x-np.arange(10), 2) + np.power(y-np.arange
...: (10), 2)) / 2).sum()
...:
...:
In [29]: gauss2d(x, y)
Out[29]: 26.295857532549885
推荐阅读
- python - 为什么所有值都附加到列表winning_numbers?
- python - 无服务器并将图像从 Lambda 端点上传到 S3
- javascript - 提交表单时未执行脚本
- python - aiohttp: client.get() returns html tag rather than file
- python - 非标准周编号
- iexpress - Windows IExpress 是否仍然暴露漏洞?
- kubernetes - 使用 minikube 将 pod 连接到本地进程
- node.js - TypeError:UserModel.create 不是函数,Sequelize
- python - 从 Django 的 UserModel 扩展并使用它来登录
- java - 为什么我在 java 中收到死代码警告?