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

คืนค่า gradient ของอาร์เรย์ N มิติตาม axis 1 ใน Python


ภาพรวม

ใช้ numpy.gradient() คำนวณ gradient ของอาร์เรย์ N มิติ ตาม axis=1 (แนวนอน/คอลัมน์) ใช้ central differences order 2 ที่จุดภายใน และ one-sided differences ที่ขอบเขต

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

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=1

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

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

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

คำอธิบาย: Gradient ตาม axis=1 (แนวคอลัมน์) คำนวณความต่างระหว่างคอลัมน์: Row 0: (35-20)/1=15, (57-20)/2=18.5, (57-35)/1=22 Row 1: (85-70)/1=15, (120-70)/2=25, (120-85)/1=35