如何将numpy矩阵weights正确插入到numpy数组lattice中
问题描述
我通过以下代码生成了weights矩阵:
import numpy as np import random weights = np.random.rand(9+1, 8) for i in range(8): # 7 to 8 weights[9][i] = random.uniform(.5,1.5)
随后尝试将其插入到lattice数组的某个元素中:
lattice = np.zeros((2,10,5)) lattice[0][0][0] = weights print(lattice)
执行后出现报错:
ValueError: setting an array element with a sequence.
我知道问题在于当前lattice存储的是float类型值,无法容纳矩阵,希望找到正确创建lattice数组以容纳矩阵的方法,并附上示例。
解决方案
核心是让lattice的维度或类型能够适配weights的结构,以下是两种实用方法:
方法1:扩展维度匹配weights形状(推荐)
weights是(10,8)的二维数组,只需给lattice增加对应维度,让每个元素位置能容纳这个二维数组。比如将lattice初始形状设为(2,10,5,10,8),这样每个lattice[x][y][z]就是一个(10,8)的数组:
import numpy as np import random # 生成weights weights = np.random.rand(10, 8) for i in range(8): weights[9][i] = random.uniform(.5,1.5) # 创建适配维度的lattice lattice = np.zeros((2,10,5,10,8)) # 赋值 lattice[0][0][0] = weights # 验证结果 print(lattice[0][0][0].shape) # 输出:(10, 8)
方法2:定义为对象类型(不推荐)
如果不想扩展维度,可以将lattice的类型设为object,这样每个元素可以存放任意对象(包括数组):
import numpy as np import random weights = np.random.rand(10, 8) for i in range(8): weights[9][i] = random.uniform(.5,1.5) # 创建对象类型的lattice lattice = np.zeros((2,10,5), dtype=object) # 赋值 lattice[0][0][0] = weights # 查看结果 print(lattice[0][0][0])
注意:对象类型的numpy数组会丢失数值类型的性能优化,运算效率大幅下降,仅在特殊场景下使用。
内容的提问来源于stack exchange,提问作者Rashid Abramov
相关产品推荐
相关产品推荐

