import random
xs = [x*0.1 for x in range(0,10)];
ys = [x*0.6+0.32 for x in xs];
w = random.random()
b = random.random()
for _ in range(1000):
for x,y in zip(xs,ys):
o = w*x+b
e =o-y;
loss = e**2
dw = -2*e*x
db = -2*e
w = w+0.1*dw
b = w+ 0.1*db;
print(w,b)
利用plt画出动画图像效果,如下图是sigmod随着w不同,而动态变化的代码
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3,3,500)
def sigmod(x):
return 1/(1+np.exp(-x));
plt.ion()#开启会话,动态画图之前,调用该方法,则不用show了
for i in range(100):
w+=0.1
y = sigmod(w*x);
plt.clf();#清空
plt.plot(x, y)
#锁定范围
plt.xlim(-3,3)
plt.ylim(0,1)
plt.pause(0.1)#休眠0.1秒
plt.ioff() #关闭会话
y = sigmod(x)
plt.plot(x,y)
plt.show()
动态播放图片,PIL与plt的转换
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
plt.ion()#开启会话,动态画图之前,调用该方法,则不用show了
for i in range(1,9):
st = str(i)+".jpg";
img = Image.open(st)
plt.clf();#清空
plt.imshow(img)
plt.pause(1)#休眠0.1秒
plt.ioff() #关闭会话
利用PIL画出验证码图像
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random
#验证码生成
#随机字母
def randChar():
return chr(random.randint(65,90));
def randChar2():
return str(random.randint(0,9))
#随机颜色生成
#随机颜色1
def randColor1():
return (random.randint(64,255),
random.randint(64, 255),
random.randint(64, 255))
#随机颜色2
def randColor2():
return (random.randint(32,127),
random.randint(32, 127),
random.randint(32, 127))
for _ in range(600):
#创建画板
wid = 240;
h=60;
img = Image.new("RGB",(wid,h),(255,255,255));
#创建字体对象
font = ImageFont.truetype("1.ttf",50)
#创建Draw对象
draw = ImageDraw.Draw(img)
for x in range(wid):
for y in range(h):
draw.point((x,y),fill=randColor1());
nums="";
for i in range(4):
num = randChar2();
nums = nums+str(num)
draw.text((10+60*i,10), num, fill=randColor2(), font=font)
img.filter(ImageFilter.BLUR)
img.save("pic/"+nums+".jpg");