使用numpy.fromfunction()生成3D数组时遇参数类型问题
使用numpy.fromfunction生成3D数组时的参数问题
我在使用numpy.fromfunction()生成3D数组时遇到了问题:
- 我定义的lambda表达式接收三个参数
i、j、k,预期它们是单个整数索引,但实际得到的是三个形状为(100, 100)的numpy数组:i.shape = (100, 100) j.shape = (100, 100) k.shape = (100, 100) - 这导致lambda调用的
self.dist_p_to_plane()函数崩溃,因为它只能处理单个整数坐标。 - 我参照numpy文档实现3维场景,文档提到“生成的数组在坐标(x, y, z)处的值为fn(x, y, z)”,难道是numpy的实现存在问题?
相关代码片段:
check_reset_flag_fun = lambda i,j,k: self.dist_p_to_plane([i,j,k], plane_equation) > min_dist reset_flag_mtx = np.fromfunction(check_reset_flag_fun, (100,100,100), dtype=int) matrix[reset_flag_mtx] = reset_val
问题原因
numpy.fromfunction的设计逻辑是向量化传递索引网格,而非逐个传递单个整数索引。文档中的“坐标(x,y,z)”是逻辑上的描述,实际实现中,它会生成广播后的索引数组(对应你看到的(100,100)形状),以此实现高效的批量计算,避免循环每个元素。问题出在你的dist_p_to_plane()函数不支持numpy数组输入,仅能处理单个数值。
解决方案
1. 向量化改造目标函数(推荐)
修改dist_p_to_plane(),让它支持numpy数组运算,这是最符合numpy设计理念的高效方案。
假设原函数是处理单个点的:
def dist_p_to_plane(self, point, plane_equation): a, b, c, d = plane_equation x, y, z = point numerator = abs(a*x + b*y + c*z + d) denominator = (a**2 + b**2 + c**2)**0.5 return numerator / denominator
改成支持数组输入的版本:
import numpy as np def dist_p_to_plane(self, point_arr, plane_equation): a, b, c, d = plane_equation x, y, z = point_arr numerator = np.abs(a*x + b*y + c*z + d) denominator = np.sqrt(a**2 + b**2 + c**2) return numerator / denominator
改造后原代码无需修改,i、j、k作为数组传入时会自动执行向量化运算。
2. 用numpy.vectorize包装函数(性能较差)
如果无法修改dist_p_to_plane(),可以用np.vectorize()将其包装成支持数组输入的函数,但本质是循环遍历每个元素,性能远低于向量化实现:
vectorized_dist = np.vectorize(lambda x,y,z: self.dist_p_to_plane([x,y,z], plane_equation)) check_reset_flag_fun = lambda i,j,k: vectorized_dist(i,j,k) > min_dist reset_flag_mtx = np.fromfunction(check_reset_flag_fun, (100,100,100), dtype=int)
3. 手动生成索引网格遍历(不推荐)
完全放弃fromfunction,手动生成所有索引后逐个计算,性能最差,仅适合极小尺寸数组:
reset_flag_mtx = np.zeros((100,100,100), dtype=bool) for i in range(100): for j in range(100): for k in range(100): if self.dist_p_to_plane([i,j,k], plane_equation) > min_dist: reset_flag_mtx[i,j,k] = True matrix[reset_flag_mtx] = reset_val
内容的提问来源于stack exchange,提问作者Mateuszq28
相关产品推荐
相关产品推荐

