<p>注意,您已经获得了数组<code>A</code>,我们可以从<code>A</code>继续。
如果使用基于沿帧轴的<strong>梯度<strong>的算法,则我们可以获得期望的数组<code>L</code></p>
<pre class="lang-py prettyprint-override"><code># The array: Age
A= np.array([[0,0,1,1,0,0],
[0,0,2,2,0,0],
[1,0,3,3,0,0],
[2,1,4,4,0,1],
[0,2,0,0,1,2],
[0,3,0,0,2,3],
[1,0,1,1,0,4]])
# Define two parameters
age = A.T
n = age.shape[0]
m = age.shape[1]
# Generate the gradient along frame-axis for the array A
# output: a new array grad_age
grad_age = np.zeros((n, m))
for i in range(n):
for j in range(m):
if j < m-1:
grad_age[i][j] = age[i][j+1] - age[i][j]
else: # In the old version, this condition was neglected.
grad_age[i][m-1] = 0 - age[i][m-1]
print("The array grad_age:")
print(grad_age)
# Find out the locations of elements in the array 'age'
# which are of negative gradient and modify related
# elements in the array 'age'
for i in range(n):
for j in reversed(range(m)):
t = grad_age[i][j]
if t < 0: #find out these index where gradient < 0
print(t) # for checking
for x in range(abs(int(t))):
age[i][j-x] += x
print("The array L:")
print(age.T)
</code></pre>
<p>结果是:</p>
<pre class="lang-py prettyprint-override"><code>The array grad_age:
[[ 0. 1. 1. -2. 0. 1. -1.]
[ 0. 0. 1. 1. 1. -3. 0.]
[ 1. 1. 1. -4. 0. 1. -1.]
[ 1. 1. 1. -4. 0. 1. -1.]
[ 0. 0. 0. 1. 1. -2. 0.]
[ 0. 0. 1. 1. 1. 1. -4.]]
-1.0
-2.0
-3.0
-1.0
-4.0
-1.0
-4.0
-2.0
-4.0
The array L:
[[0 0 4 4 0 0]
[0 0 4 4 0 0]
[2 0 4 4 0 0]
[2 3 4 4 0 4]
[0 3 0 0 2 4]
[0 3 0 0 2 4]
[1 0 1 1 0 4]]
</code></pre>