我需要做的是將 2D 矩陣擴展到 3D 并用任意數量的零填充第三軸。回傳的錯誤是:
所有輸入陣列必須具有相同的維數,但索引 0 處的陣列有 3 維,索引 1 處的陣列有 0 維
我應該糾正什么?
import numpy as np
kernel = np.ones((3,3)) / 9
kernel = kernel[..., None]
print(type(kernel))
print(np.shape(kernel))
print(kernel)
i = 1
for i in range(27):
np.append(kernel, 0, axis = 2)
print(kernel)
uj5u.com熱心網友回復:
我應該使用什么來代替 np.append()?
使用concatenate():
import numpy as np
kernel = np.ones((3,3)) / 9
kernel = kernel[..., None]
print(type(kernel))
print(np.shape(kernel))
print(kernel)
print('-----------------------------')
append_values = np.zeros((3,3))
append_values = append_values[..., None]
i = 1
for i in range(2):
kernel = np.concatenate((kernel, append_values), axis=2)
print(kernel.shape)
print(kernel)
但最好append_values在第三維中生成具有所需形狀的陣列以避免回圈:
append_values = np.zeros((3,3,2)) # or (3,3,27)
kernel = np.concatenate((kernel, append_values), axis=2)
print(kernel.shape)
print(kernel)
uj5u.com熱心網友回復:
查看輸出和錯誤 - 完全錯誤,而不僅僅是一個錯誤!
<class 'numpy.ndarray'>
(3, 3, 1)
...
In [94]: np.append(kernel, 0, axis = 2)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [94], in <cell line: 1>()
----> 1 np.append(kernel, 0, axis = 2)
File <__array_function__ internals>:5, in append(*args, **kwargs)
File ~\anaconda3\lib\site-packages\numpy\lib\function_base.py:4817, in append(arr, values, axis)
4815 values = ravel(values)
4816 axis = arr.ndim-1
-> 4817 return concatenate((arr, values), axis=axis)
File <__array_function__ internals>:5, in concatenate(*args, **kwargs)
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 3 dimension(s) and the array at index 1 has 0 dimension(s)
正如你的shape節目kernel是3d(3,3,1)。 np.append取標量 0,并創建一個陣列np.array(0), 和呼叫concatenate。 concatenate,如果您花時間閱讀其檔案,則需要匹配數量的維度。
但是我對您的代碼的主要不滿是您在np.append沒有捕獲結果的情況下使用了它。同樣,如果您花時間閱讀檔案,您會發現這np.append并不能在原地作業。它不會修改kernel. 當它作業時,它會回傳一個新陣列。在回圈中重復這樣做是低效的。
看起來您采用了串列追加模型,沒有太多考慮將其應用于陣列。這不是如何編碼numpy。
正如另一個答案所示,concatenate如果您想制作 (3,3,28) 陣列,則使用 (3,3,27) 陣列 0 來做一個。
或者制作一個 (3,3,28) 陣列,然后將一個 (3,3,1) 陣列復制到相應的列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/518595.html
標籤:Python麻木的矩阵
上一篇:串列理解
下一篇:在熊貓資料框中總結玩家的每次游戲
