项目 | 内容 |
---|---|
这个做业属于哪一个课程 | 人工智能实战 2019(北京航空航天大学) |
这个做业的要求在哪里 | 人工智能实战第五次做业(我的) |
我在这个课程的目标是 | 了解人工智能的基础理论知识,锻炼实践能力 |
这个做业在哪一个具体方面帮助我实现目标 | 学习运用线性二分类,并经过代码实践来练习完成逻辑与门和逻辑或门 |
做业正文 | 见下文 |
其余参考文献 | 无 |
将其做为一个线性二分类问题来解决,并运用课件中关于线性二分类的内容。python
import numpy as np import matplotlib.pyplot as plt from pathlib import Path import math def ReadAndData(GATE):#创建逻辑与门和逻辑或门的训练数据 X = np.array([0,0,1,1,0,1,0,1]).reshape(2,4) AND = np.array([0,0,0,1]).reshape(1,4) OR = np.array([0,1,1,1]).reshape(1,4) if GATE=='AND': return X,AND if GATE=='OR': return X,OR def Sigmoid(x):#激活函数 s=1/(1+np.exp(-x)) return s def ForwardCalculation(W,B,X):#前向计算 z = np.dot(W, X) + B a = Sigmoid(z) return a def BackPropagation(X,Y,A,w,b,eta,sample):#反向传播 dloss_z = A - Y db = np.sum(dloss_z) / sample dw = np.dot(dloss_z, X.T) / sample w = w - eta * dw b = b - eta * db return w,b def CheckLoss(w, b, X, Y, sample):#计算损失函数值 A = ForwardCalculation(w, b, X) p1 = Y * np.log(A) p2 = (1-Y) * np.log(1-A) LOSS = -(p1 + p2) loss = np.sum(LOSS) / sample return loss def InitialParameters():#初始化W和B W = np.zeros((1,2)) B = 0.0 return W,B def ShowResult(W,B,X,Y,GATE):#做图 w = -W[0,0]/W[0,1] b = -B/W[0,1] x = np.array([0,1]) y = w * x + b plt.plot(x,y,label='w1 = '+str(round(W[0,0],3))+', w2 = '+str(round(W[0,1],3)) +', b = '+str(round(B,3))) for i in range(4): if Y[0,i] == 0: plt.scatter(X[0,i],X[1,i],marker="o",c='b',s=64) else: plt.scatter(X[0,i],X[1,i],marker="^",c='r',s=64) plt.axis([-0.1,1.1,-0.1,1.1]) plt.title(GATE) plt.xlabel("X1") plt.ylabel("X2") plt.legend(loc='upper right') plt.show() if __name__ == '__main__': W,B = InitialParameters() eta = 0.2 MAX = 10000 #最大迭代次数 eps = 1e-2 loss = 0 GATE = 'OR' X, Y = ReadAndData(GATE) for i in range(MAX): Z = ForwardCalculation(W, B, X) W, B = BackPropagation(X, Y, Z ,W , B ,eta ,4) loss = CheckLoss(W,B,X,Y,4) if loss < eps: break; ShowResult(W,B,X,Y,GATE)
逻辑与门
函数
逻辑或门
学习