Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

คำนวณ gradient ของอาร์เรย์ N มิติตาม axis ที่กำหนดใน Python


ภาพรวม

ใช้ numpy.gradient() คำนวณ gradient ของอาร์เรย์ N มิติ ใช้ central differences order 2 ที่จุดภายใน และ one-sided differences (forward/backward) order 1 หรือ 2 ที่ขอบเขต ผลลัพธ์มี shape เดียวกับ input

พารามิเตอร์

  • f: อาร์เรย์ N มิติ samples ของ scalar function
  • varargs (optional): spacing ระหว่างค่า f (default = 1)
  • edge_order (optional): {1, 2} accuracy ที่ขอบเขต (default 1)
  • axis (optional): axis ที่คำนวณ gradient (default None = ทุก axis)

ขั้นตอนการทำงาน

1. นำเข้า NumPy

import numpy as np

2. สร้างอาร์เรย์ 2D float

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

3. แสดงข้อมูลอาร์เรย์

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

4. คำนวณ gradient ตาม axis=0 (แนวตั้ง)

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

ตัวอย่างโค้ดเต็ม

import numpy as np
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))

ผลลัพธ์

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.]]

คำอธิบาย: Gradient ตาม axis=0 (แนวแถว) = ความต่างระหว่างแถว: [70-20, 85-35, 120-57] = [50, 50, 63] ทั้ง 2 แถวได้ค่าเท่ากันเพราะมีแค่ 2 แถว ใช้ forward/backward difference