This commit is contained in:
13002457275 2021-01-19 13:16:03 +08:00
parent a452c8f6f0
commit 1011f903f8
11 changed files with 220 additions and 123 deletions

151
test.py
View File

@ -1,112 +1,57 @@
import turtle
# -*- coding: utf-8 -*-
import sympy
import numpy as np
import math
import sys
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
import matplotlib.pyplot as plt
import matplotlib
tick = 0.1
# 解决无法显示中文问题fname是加载字体路径根据自身pc实际确定具体请百度
# zhfont1 = matplotlib.font_manager.FontProperties(fname='/System/Library/Fonts/Hiragino Sans GB W3.ttc')
position_human = (150,50*(3**0.5))
position_lion_1 = (0,0)
position_lion_2 = (150,150*(3**0.5))
# 随机产生3个参考节点坐标
maxy = 1000
maxx = 1000
cx = maxx * np.random.rand(3)
cy = maxy * np.random.rand(3)
dot1 = plot(cx, cy, 'k^')
speed_human = 10*tick
speed_lion_1 = 15*tick
speed_lion_2 = 20*tick
degree = 25
times = 0
#判断人在线上还是线下
# 生成盲节点,以及其与参考节点欧式距离
mtx = maxx * np.random.rand()
mty = maxy * np.random.rand()
# plt.hold('on')
dot2 = plot(mtx, mty, 'go')
da = math.sqrt(np.square(mtx - cx[0]) + np.square(mty - cy[0]))
db = math.sqrt(np.square(mtx - cx[1]) + np.square(mty - cy[1]))
dc = math.sqrt(np.square(mtx - cx[2]) + np.square(mty - cy[2]))
while(True): #使其无限循环下去
turtle.penup()
turtle.goto(position_human)
check_k = (position_lion_2[1]-position_lion_1[1])/(position_lion_2[0]-position_lion_1[0])
check_b = position_lion_2[1] - (check_k*position_lion_2[0])
check = check_k*position_human[0] + check_b
#以下是人前进代码
if(position_human[1]<check):
#人在线条之下
middle_dot = (((position_lion_2[0]+position_lion_1[0])/2),((position_lion_2[1]+position_lion_1[1])/2))
turtle.setheading(turtle.towards(middle_dot)+degree)
turtle.pendown()
turtle.fd(speed_human)
position_human = tuple(turtle.position())
print("below")
elif(position_human[1]>check):
axis_k = (position_human[1]-position_lion_1[1])/(position_human[0]-position_lion_1[0])
axis_b = position_human[1] - (axis_k*position_human[0])
middle_dot = (((position_lion_2[0]+position_lion_1[0])/2),((position_lion_2[1]+position_lion_1[1])/2))
vertical_k = -1/axis_k
vertical_b = middle_dot[1] - (vertical_k*middle_dot[0])
vertical_dot = ((vertical_b-axis_b)/(axis_k-vertical_k),(axis_k*((vertical_b-axis_b)/(axis_k-vertical_k)) + axis_b))
point_dot = ((2*vertical_dot[0]-middle_dot[0]),(2*vertical_dot[1]-middle_dot[1]))
turtle.pendown()
turtle.setheading(turtle.towards(point_dot) + degree)
turtle.fd(speed_human)
position_human = tuple(turtle.position())
print("above")
elif(position_human == check):
print("!!!!oneline")
break
distance_1 = turtle.distance(position_lion_1)
distance_2 = turtle.distance(position_lion_2)
if(distance_1<=speed_lion_1 or distance_2<=speed_lion_2):
print(times)
break
#以下是狮子追人代码
turtle.penup()
turtle.goto(position_lion_1)
turtle.setheading(turtle.towards(position_human))
turtle.pendown()
turtle.forward(speed_lion_1)
position_lion_1 = tuple(turtle.position())
turtle.penup()
turtle.goto(position_lion_2)
turtle.setheading(turtle.towards(position_human))
turtle.pendown()
turtle.forward(speed_lion_2)
position_lion_2 = tuple(turtle.position())
times = times + 1
# axis_k = (position_human[1]-position_lion_1[1])/(position_human[0]-position_lion_1[0])
# axis_b = position_human[1] - (axis_k*position_human[0])
# middle_dot = (((position_lion_2[0]-position_lion_1[0])/2),((position_lion_2[1]-position_lion_1[1])/2))
# vertical_k = -1/axis_k
# vertical_b = middle_dot[1] - (vertical_k*middle_dot[0])
# 计算定位坐标
def triposition(xa, ya, da, xb, yb, db, xc, yc, dc):
x, y = sympy.symbols('x y')
f1 = 2 * x * (xa - xc) + np.square(xc) - np.square(xa) + 2 * y * (ya - yc) + np.square(yc) - np.square(ya) - (
np.square(dc) - np.square(da))
f2 = 2 * x * (xb - xc) + np.square(xc) - np.square(xb) + 2 * y * (yb - yc) + np.square(yc) - np.square(yb) - (
np.square(dc) - np.square(db))
result = sympy.solve([f1, f2], [x, y])
locx, locy = result[x], result[y]
return [locx, locy]
# vertical_dot = ((vertical_b-axis_b)/(axis_k-vertical_k),(axis_k*((vertical_b-axis_b)/(axis_k-vertical_k)) + axis_b))
# 解算得到定位节点坐标
[locx, locy] = triposition(cx[0], cy[0], da, cx[1], cy[1], db, cx[2], cy[2], dc)
# plt.hold('on')
dot3 = plot(locx, locy, 'r*')
# point_dot = ((2*vertical_dot[0]-middle_dot[0]),(2*vertical_dot[1]-middle_dot[1]))
# turtle.pendown()
# turtle.goto(position_lion_2)
# turtle.penup()
# turtle.goto(position_human)
# turtle.pendown()
# turtle.setheading(turtle.towards(point_dot)+40)
# turtle.forward(100)
# turtle.penup()
# turtle.goto(position_human)
# turtle.setheading(turtle.towards(middle_dot))
# turtle.pendown()
# turtle.forward(100)
# turtle.penup()
# turtle.goto(position_lion_1)
# turtle.pendown()
# turtle.goto(position_lion_2)
# middle_dot = (((position_lion_2[0]-position_lion_1[0])/2),((position_lion_2[1]-position_lion_1[1])/2))
# print(middle_dot)
# turtle.penup()
# turtle.goto(position_human)
# turtle.pendown()
# turtle.setheading(turtle.towards(middle_dot) + 40 )
# turtle.fd(100)
input("ssssss")
# 显示脚注
x = [[locx, cx[0]], [locx, cx[1]], [locx, cx[2]]]
y = [[locy, cy[0]], [locy, cy[1]], [locy, cy[2]]]
for i in range(len(x)):
plt.plot(x[i], y[i], linestyle='--', color='g')
plt.title('Three point locate')
plt.legend(['Ref', '盲节点', 'Locate'], loc='lower right')
plt.show()
derror = math.sqrt(np.square(locx - mtx) + np.square(locy - mty))
print(derror)

36
优化算法/Adam.py Normal file
View File

@ -0,0 +1,36 @@
# Adam
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from AA import Function
ff = Function()
for i in range(48):
# 绘制原来的函数
plt.plot(ff.points_x, ff.points_y, c="b", alpha=0.5, linestyle="-")
# 算法开始
lr = pow(1.2,-i)*2
rou1,rou2 = 0.9,0.9 # 原来的算法中rou2=0.999,但是效果很差
delta = 1e-8
x = -20
s,r = 0,0
t = 0
Adam_x, Adam_y = [], []
for it in range(1000):
Adam_x.append(x), Adam_y.append(ff.f(x))
t += 1
g = ff.df(x)
s = rou1 * s + (1 - rou1)*g
r = rou2 * r + (1 - rou2)*g*g # 积累平方梯度
s = s/(1-pow(rou1,t))
r = r/(1-pow(rou2,t))
x = x - lr /(delta + np.sqrt(r)) * s
plt.xlim(-20, 20)
plt.ylim(-2, 10)
plt.plot(Adam_x, Adam_y, c="r", linestyle="-")
plt.scatter(Adam_x[-1],Adam_y[-1],90,marker = "X",color="g")
plt.title("Adam,lr=%f"%(lr))
# plt.savefig("Adam,lr=%f"%(lr) + ".png")
plt.show()
plt.clf()

0
优化算法/__init__.py Normal file
View File

2
优化算法/test.py Normal file
View File

@ -0,0 +1,2 @@
lr = pow(2,-2)*16
print(lr)

View File

@ -0,0 +1,29 @@
# 动量 + 梯度下降法
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from AA import Function
ff = Function()
for i in range(10):
# 绘制原来的函数
plt.plot(ff.points_x, ff.points_y, c="b", alpha=0.5, linestyle="-")
# 算法开始
lr = 0.002
m = 1 - pow(0.5,i)
x = -20
v = 1.0
GDM_x, GDM_y = [], []
for it in range(1000):
GDM_x.append(x), GDM_y.append(ff.f(x))
v = m * v - lr * ff.df(x)
x = x + v
plt.xlim(-20, 20)
plt.ylim(-2, 10)
plt.plot(GDM_x, GDM_y, c="r", linestyle="-")
plt.scatter(GDM_x[-1],GDM_y[-1],90,marker = "x",color="g")
plt.title("Gradient descent + momentum,lr=%f,m=%f"%(lr,m))
# plt.savefig("Gradient descent + momentum,lr=%f,m=%f"%(lr,m) + ".png")
plt.show()
plt.clf()

29
优化算法/牛顿法.py Normal file
View File

@ -0,0 +1,29 @@
# # 牛顿法
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from AA import Function
ff = Function()
for i in range(72):
# 绘制原来的函数
plt.plot(ff.points_x, ff.points_y, c="b", alpha=0.5, linestyle="-")
# 算法开始
alpha= pow(1.2,-i)*20
x = -20.0
Newton_x, Newton_y = [], []
for it in range(1000):
Newton_x.append(x), Newton_y.append(ff.f(x))
g = ff.df(x)
gg = ff.ddf(x)
x = x - g/(gg+alpha)
plt.xlim(-20, 20)
plt.ylim(-2, 10)
plt.plot(Newton_x, Newton_y, c="r", linestyle="-")
plt.scatter(Newton_x[-1],Newton_y[-1],90,marker = "x",color="g")
plt.title("Newton,alpha=%f"%(alpha))
# plt.savefig("Newton,alpha=%f"%(alpha) + ".png")
plt.show()
plt.clf()

View File

@ -0,0 +1,26 @@
# 纯粹的梯度下降法,GD
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from AA import Function
ff = Function()
for i in range(10):
# 绘制原来的函数
plt.plot(ff.points_x, ff.points_y, c="b", alpha=0.5, linestyle="-")
# 算法开始
lr = pow(2,-i)*16
x = -20.0
GD_x, GD_y = [], []
for it in range(1000):
GD_x.append(x), GD_y.append(ff.f(x))
dx = ff.df(x)
x = x - lr * dx
plt.xlim(-20, 20)
plt.ylim(-2, 10)
plt.plot(GD_x, GD_y, c="r", linestyle="--")
plt.title("Gradient descent,lr=%f"%(lr))
# plt.savefig("Gradient descent,lr=%f"%(lr) + ".png")
plt.show()
plt.clf()

View File

@ -1,5 +1,5 @@
import numpy as np
a1 = np.array([i for i in range(1,5)])
a1 = np.array([1,2,3,4])
np.exp2(a1)
np.power(3, a1)
np.log10(a1)

View File

@ -1,19 +0,0 @@
import numpy as np
import pandas as pd
a = np.array([1,2])
b = a.reshape(1,2)
# b = np.mat(a)
c = np.array([[1,2],[1,3],[1,4]])
# d = c.reshape(3,2)
d = np.mat(c)
print(f"a is {a} {a.shape} shape {a.shape[0]}, b is {b} {b.shape} shape {b.shape[0],b.shape[1]}, "
f"c is {c} {c.shape}, d is {d} {d.shape}")
# 注意 e = np.mat([[2],[1],[3]]) 是错误的
# 矩阵与矩阵相乘, 矩阵与数组相乘完全不同
e = np.array([[2],[1],[3]])
print(f"c*e is {c*e}\n")
f = np.mat([[2],[1]])
print(f" c shape is {c}, and f shape is {f} \n"
f"c*f ",c*f)

View File

@ -0,0 +1,36 @@
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2-3
def df(x):
return 2*x
def plotf(loss):
x = range(len(loss))
plt.plot(x,loss)
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.show()
def main():
x = 15
lr = 0.1
steps = 40
loss = []
for i in range(steps):
loss.append(f(x))
print(loss[i])
x = x-lr*df(x)
# y = f(x)
# print(y)
plotf(loss)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,13 @@
import torch
from torch.autograd import Variable
a = Variable(torch.rand(1, 4), requires_grad=True)
b = a**2
c = b*2
d = c.mean()
e = c.sum()
d.backward(retain_graph=True) # fine
e.backward(retain_graph=True) # fine
d.backward() # also fine
e.backward() # error will occur!