返回Python中N維陣列的梯度
梯度使用二階精確中心差分法在內部點計算,並在邊界使用一階或二階精確單側(前向或後向)差分法。因此,返回的梯度與輸入陣列具有相同的形狀。第一個引數f是一個包含標量函式樣本的N維陣列。第二個引數是可變引數,即f值之間的間距。所有維度的預設單位間距。
第三個引數是edge_order{1, 2},即使用N階精確差分法在邊界計算梯度。預設值:1。第四個引數是梯度,它僅沿給定的軸或軸計算。預設值(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))
示例
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))輸出
Our Array... [ 20. 35. 57. 70. 85. 120.] Dimensions of our Array... 1 Datatype of our Array object... float64 Result (gradient)... [15. 18.5 17.5 14. 25. 35. ]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP