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