Это для сглаживания пути al go на Udacity AI для робототехники, с помощью градиентного спуска сглаживается путь, по которому проходит робот.
Это тест 5, урок 15.
Но Когда я пытаюсь построить путь итеративно, чтобы увидеть, как GD корректирует путь на каждой итерации, значения x удваиваются, и я получаю дополнительную строку, я только пытаюсь построить newpath
, а не старую.
%matplotlib inline
import matplotlib.pyplot as plt
# -----------
# User Instructions
#
# Define a function smooth that takes a path as its input
# (with optional parameters for weight_data, weight_smooth,
# and tolerance) and returns a smooth path. The first and
# last points should remain unchanged.
#
# Smoothing should be implemented by iteratively updating
# each entry in newpath until some desired level of accuracy
# is reached. The update should be done according to the
# gradient descent equations given in the instructor's note
# below (the equations given in the video are not quite
# correct).
# -----------
from copy import deepcopy
# thank you to EnTerr for posting this on our discussion forum
def printpaths(path,newpath):
for old,new in zip(path,newpath):
print('['+ ', '.join('%.3f'%x for x in old) + \
'] -> ['+ ', '.join('%.3f'%x for x in new) +']')
#for plotting
fig = plt.figure
#ax = plt.axes()
plt.gca().invert_yaxis()
# Don't modify path inside your function.
path = [[0, 0],
[0, 1],
[0, 2],
[1, 2],
[2, 2],
[3, 2],
[4, 2],
[4, 3],
[4, 4]]
def smooth(path, weight_data = 0.5, weight_smooth = 0.1, tolerance = 0.000001):
# Make a deep copy of path into newpath
newpath = deepcopy(path)
change = tolerance
count = 0
print("before\n")
printpaths(path, newpath)
plt.gca().invert_yaxis()
plt.plot(path)
plt.show()
while(change >= tolerance):
change = 0.0
for i in range(1,len(path)-1,1):
for j in range(len(path[0])):
newpath_before = newpath[i][j]
newpath[i][j] += weight_data * (path[i][j] - newpath[i][j]) + weight_smooth * (newpath[i-1][j]
+ newpath[i+1][j] - 2.0 * newpath[i][j])
change += abs(newpath_before - newpath[i][j])
print("change: {}\n".format(change))
print("\ncount: {}\n".format(count))
printpaths(path, newpath)
print("\n")
plt.gca().invert_yaxis()
plt.plot(newpath)
plt.show()
count +=1
return newpath # Leave this line for the grader!
printpaths(path,smooth(path))
Координаты представлены в формате (y, x), поэтому я переворачиваю ось, но все равно значения x находятся в диапазоне от 0 до 4, а не от 0 до 8.