返回Python中給定軸上的N維陣列的梯度


梯度使用內部點的二階精確中心差分以及邊界處的一階或二階精確單側(向前或向後)差分來計算。因此,返回的梯度與輸入陣列具有相同的形狀。第一個引數f是一個包含標量函式樣本的N維陣列。第二個引數是varargs,即f值之間的間距。所有維度預設單元間距。

第三個引數是edge_order{1, 2},即使用N階精確差分在邊界處計算梯度。預設值:1。第四個引數是Gradient,它僅沿給定的軸或軸計算。預設值(axis = None)是計算輸入陣列所有軸的梯度。axis可以為負數,在這種情況下,它從最後一個軸計數到第一個軸。該方法返回一個ndarray列表,對應於f相對於每個維度的導數。每個導數都與f具有相同的形狀。

步驟

首先,匯入所需的庫:

import numpy as np

使用array()方法建立一個numpy陣列。我們添加了浮點型元素:

arr = np.array([[20, 35, 57], [70, 85, 120]], dtype = float)

顯示陣列:

print("Our Array...\n",arr)

檢查維度:

print("\nDimensions of our Array...\n",arr.ndim)

獲取資料型別:

print("\nDatatype of our Array object...\n",arr.dtype)

梯度使用內部點的二階精確中心差分以及邊界處的一階或二階精確單側(向前或向後)差分來計算。因此,返回的梯度與輸入陣列具有相同的形狀:

print("\nResult (gradient)...\n",np.gradient(arr, axis = 0))

示例

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of float type
arr = np.array([[20, 35, 57], [70, 85, 120]], dtype = float)

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array.
print("\nResult (gradient)...\n",np.gradient(arr, axis = 0))

輸出

Our Array...
[[ 20. 35. 57.]
[ 70. 85. 120.]]

Dimensions of our Array...
2

Datatype of our Array object...
float64

Result (gradient)...
[[50. 50. 63.]
[50. 50. 63.]]

更新於:2022年2月25日

116次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告