python - 2d numpy 数组中的平方和(形成一个正方形的 4 个值)。Python
问题描述
我正在寻找在矩阵内形成正方形的二维数组中的每个 4 点组合
in4x4 = np.array(([1,2,3,4],[2,3,4,1],[3,4,1,2],[4,3,1,2]))
print(in4x4)
array([[1, 2, 3, 4],
[2, 3, 4, 1],
[3, 4, 1, 2],
[4, 3, 1, 2]])
预期输出:
print(out3x3)
array([[ 8, 12, 12],
[12, 12, 8],
[14, 9, 6]]
目前我正在使用numpy.diff
几个步骤。感觉应该有一个更清洁的方法。我目前做的计算示例:
diff3x4 = np.diff(a4x4,axis=0)
a3x4 = a4x4[0:3,:] * 2 + d3x4
d3x3 = np.diff(a3x4)
a3x3 = a3x4[:,0:3] * 2 + d3x3
是否有一个干净的可能矢量化的方法?速度令人担忧。看了scipy.convolve
但似乎不适合我的目的,但也许我只是配置内核错误。
解决方案
您可以使用 kerenl 进行 2-D 卷积以获得所需的结果。
实现二维卷积并测试您提供的输入的简单代码:
import numpy as np
def conv2d(a, f):
s = f.shape + tuple(np.subtract(a.shape, f.shape) + 1)
strd = np.lib.stride_tricks.as_strided
subM = strd(a, shape = s, strides = a.strides * 2)
return np.einsum('ij,ijkl->kl', f, subM)
in4x4 = np.array(([1,2,3,4],[2,3,4,1],[3,4,1,2],[4,3,1,2]))
k = np.ones((2,2))
print(conv2d(in4x4, k))
输出:
[[ 8. 12. 12.]
[12. 12. 8.]
[14. 9. 6.]]
如果您可以使用内置函数,则可以使用如下所示:
import numpy as np
from scipy import signal
in4x4 = np.array(([1,2,3,4],[2,3,4,1],[3,4,1,2],[4,3,1,2]))
k = np.ones((2,2))
signal.convolve2d(in4x4, k, 'valid')
哪个输出:
array([[ 8., 12., 12.],
[12., 12., 8.],
[14., 9., 6.]])
signal.convolve2d(in4x4, k, '有效')
推荐阅读
- php - 用自定义短信替换 WooCommerce 购物车运输部分
- pine-script - TradingView Forward 测试策略错误 - 每根柱执行多个订单而不是一个
- directory - vsftpd 匿名默认目录路径是什么?
- c# - 这是使用 HttpClient 的坏模式吗?
- graphql - 阿波罗、乐观创造和重定向
- symfony - 如何修复无法自动装配“..)”的参数 $em:它引用了接口“Doctrine\Common\Persistence\ObjectManager”
- kivy - Expansion panel is not expanding in kivymd
- python - Creating an Assistant. How can I loop it to go back to the top to listen for its name? Just asking about how I could loop the program
- c++ - 我在 [class.copy.elision] 中找不到确认初始化 `T x = T();` 符合强制复制省略的条件
- php - Twilio Paging Information