项目 | 内容 |
---|---|
这个做业属于哪一个课程 | 人工智能实战 2019(北京航空航天大学) |
这个做业的要求在哪里 | 第三次做业:使用minibatch的方式进行梯度降低 |
我在这个课程的目标是 | 了解人工智能的基础理论知识,锻炼实践能力 |
这个做业在哪一个具体方面帮助我实现目标 | 学习梯度降低的原理和几种算法,并经过代码实践来练习 |
做业正文 | 见下文 |
其余参考文献 | 无 |
见课堂课件内容python
import numpy as np import matplotlib.pyplot as plt from pathlib import Path x_data_name="TemperatureControlXData.dat" y_data_name="TemperatureControlYData.dat" def ReadData(): Xfile=Path(x_data_name) Yfile=Path(y_data_name) if Xfile.exists() & Yfile.exists(): X=np.load(Xfile) Y=np.load(Yfile) return X.reshape(1,-1),Y.reshape(1,-1) else: return None,None def GetBatchSamples(X,Y,batch_size,max_iter,r_index): X_batch=[] Y_batch=[] for i in range(0,max_iter): index=r_index[i*batch_size:(i+1)*batch_size] X_batch.append(X[0][index].reshape(1,batch_size)) Y_batch.append(Y[0][index].reshape(1,batch_size)) return X_batch,Y_batch def ForwardCalculationBatch(w,b,batch_x): z=np.dot(w,batch_x)+b return z def BackPropagationBatch(x,y,z): k=x.shape[1] dz=z-y dw=np.dot(dz,x.T)/k db=np.dot(dz,np.ones(k).reshape(batch_size,1))/k return dw, db def UpdateWeights(w,b,dw,db,eta): w=w-eta*dw b=b-eta*db return w,b def CheckLoss(w,b,x,y): k=x.shape[1] z=np.dot(w,x)+b LOSS=(z-y)**2 loss=LOSS.sum()/k/2 return loss def random_index(n): test=np.arange(n) np.random.shuffle(test) return test if __name__ == '__main__': X, Y=ReadData() num_example=X.shape[1] num_feature=X.shape[0] eta=0.01 batch_range=[5,10,15] batch_result={} for batch_size in batch_range: max_epoch=50 max_iter=int(num_example/batch_size) w,b=0,0 loss_result=[] for epoch in range(max_epoch): r_index=random_index(num_example) X_batch,Y_batch=GetBatchSamples(X,Y,batch_size,max_iter,r_index) for iteration in range(0,max_iter): x=X_batch[iteration] y=Y_batch[iteration] z=ForwardCalculationBatch(w,b,x) dw,db=BackPropagationBatch(x,y,z) w,b=UpdateWeights(w,b,dw,db,eta) erro=CheckLoss(w,b,X,Y) loss_result.append(erro) batch_result[str(batch_size)]=loss_result plt.figure(figsize=(16, 10)) p5,=plt.plot(batch_result['5']) p10,=plt.plot(batch_result['10']) p15,=plt.plot(batch_result['15']) plt.legend([p5,p10,p15],["batch_size=5","batch_size=10","batch_size=15"]) plt.ylim(0.006,0.1) plt.xlim(0,800) plt.xlabel('epoch') plt.ylabel('loss') plt.title("Learning Rate "+str(eta)) plt.show()
当eta=0.1时
算法
当eta=0.05时
app
当eta=0.01时
dom
能够看到,eta越小,均方差损失loss的波动程度越小。同时,在eta必定的状况下,batch_size越大,loss的波动程度也越小。函数
问题2:为何是椭圆而不是圆?如何把这个图变成一个圆?
答:损失函数\(Loss=\frac{1}{2m}\sum_{i=1}^{m}{(x_iw+b-y_i)^2}\)
\(=\sum_{i=1}^{m}{(x_i^2w^2+b^2+2x_ibw-2y_ib-2x_iy_iw+y_i^2)}\)
可得,损失函数为椭圆函数。
所以,当\(\sum_{i=1}^{m}{x_i^2}=1\)时,椭圆函数退化为圆。学习
为何中心是个椭圆区域而不是一个点?
答:理论上loss的最小值是一个点,可是计算机的计算是离散的,颜色相同的区域因为loss很是接近,因而被计算机视为是loss相同的点。人工智能