如何解决如何将numpy数组的元素设置为numpy数组?
我想将self.weights
的特定元素(是一个numpy
数组)设置为另一个numpy
数组,但是出现了两个错误:
“ TypeError:只有大小为1的数组可以转换为Python标量”
“ ValueError:设置具有序列的数组元素。”
示例:
self.weights=np.empty(some size)
self.weights[i]=np.random.randn(some size)
这是我的代码:
import numpy as np
import sys
np.set_printoptions(threshold=sys.maxsize)
class NeuralNetwork:
def __init__(self,inputs,hiddensSizes,outputs,lr,epochs):
self.inputs = inputs
self.inputsSize = self.inputs.shape[1]
self.outputs = outputs
self.outputsSize = self.outputs.shape[1]
self.lr = lr
self.epochs = epochs
self.hiddensSizes = hiddensSizes
self.weights = np.empty(len(self.hiddensSizes) + 1)
self.combinedLayers = np.hstack((self.inputsSize,self.hiddensSizes,self.outputsSize))
for i in range(len((self.weights))):
self.weights[i] = np.random.randn(self.combinedLayers[i],self.combinedLayers[i + 1]) #ERROR IS HERE
NN = NeuralNetwork(np.array([[0,1,1],[0,0]]),(3,4),np.array([[0,0],1]]),0.1,10000)
print(NN.weights)
解决方法
以下代码返回相同的错误。
import numpy as np
weights = np.empty(3)
weights[0] = [1,2]
ValueError: setting an array element with a sequence.
但这可行:
weights[0] = 1
数组的每个元素都应具有相同数量的维数(与标准python列表不同)。默认值为1,这就是您所使用的情况。 要指定深度,只需传入一个元组即可。 查看以下内容:
weights = np.empty((3,5))
weights[0] = [1,2]
也会返回错误:
ValueError: cannot copy sequence with size 2 to array axis with dimension 5
但是以下内容将起作用,因为我的分配列表具有预期的尺寸:
weights[0] = [1,2,3,4,5]
希望您能从那里弄清楚。
,由于np.random.randn(self.combinedLayers[i],self.combinedLayers[i + 1])
的形状不断变化,因此最好使用list
:
# code code code
self.weights = []
# code code code
for ....:
self.weights.append(np.random.randn(self.combinedLayers[i],self.combinedLayers[i + 1]))
# code code code
但是,如果您想使用NumPy
,则将object
数据类型用作:
# code code code
self.weights = np.empty(len(self.hiddensSizes) + 1,dtype = 'object')
# code code code
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。