多轮3D随机游走模拟运行触发数组转标量索引错误求助
问题排查与修复方案
错误原因
np.random.choice的size参数仅支持传入整数或整数组成的元组,你代码中传入的step_shape是np.random.randint生成的二维数组,不符合参数要求,直接触发类型错误。同时这行代码逻辑不符合三维随机游走的需求,你需要生成的是step_n步、每步对应3个维度的步长,不需要随机生成size的取值。- 初始位置
origin定义错误,你当前定义的origin = (step_n, dims)是存储参数的元组,不是路径的起点坐标,后续和步长数组拼接时会出现维度不匹配问题。
修复后完整代码
# 定义随机游走参数 import numpy as np import matplotlib.pyplot as plt from itertools import cycle colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') dims = 3 # 维度数量 n_runs = 10 # 运行轮次 step_n = 1000 # 步数 step_set = np.array([-1, 0, 1]) # 可选步长 runs = np.arange(n_runs) # 生成运行轮次数组 origin = np.zeros((1, dims)) # 设定路径起点为三维坐标原点(0,0,0) # 绘制路径 fig = plt.figure(figsize=(10,10), dpi=250) ax = fig.add_subplot(111, projection='3d') # 三维坐标系 ax.grid(False) ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = False ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') for i, col in zip(runs, colors): # 模拟三维步长,生成step_n步、每步3个维度的随机步长 steps = np.random.choice(a=step_set, size=(step_n, dims)) # 拼接起点与步长,累加得到完整路径 path = np.concatenate([origin, steps]).cumsum(0) start = path[:1] stop = path[-1:] ax.scatter3D(path[:,0], path[:, 1], path[:,2], c=col, alpha=0.25, s=1) ax.plot3D(path[:,0], path[:,1], path[:,2], c=col, alpha=0.5, lw=0.25) ax.plot(start[:, 0], start[:, 1], start[:,2], c=col, marker = '+') ax.plot(stop[:, 0], stop[:, 1], stop[:,2], c=col, marker ='o') plt.title('3D Random Walk') plt.savefig('random_walk_3d.png', dpi=250) plt.show()
内容的提问来源于stack exchange,提问作者Aiden Lee
相关产品推荐
相关产品推荐

