[英]How to set element of numpy array to be numpy array?
我想將self.weights
一個特定元素(一個numpy
數組)設置為另一個numpy
數組,但是我得到了這兩個錯誤:
“類型錯誤:只有大小為 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, 0, 1, 1], [0, 0, 0, 0, 0]]), (3, 4), np.array([[0, 1, 0], [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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.