X是指输入神经元
v是指输出神经元
2. 简单的线性神经网络例子:
说明
- 数据点为(3,3)、(4,3)、(1,1),其中(3,3)和(4,3)为正样本(1,1)为负样本
- 初始化权值的范围在[-1,1]
import numpy as np
import matplotlib.pyplot as plt
x_data = np.array([[1,3,3],[1,4,3],[1,1,1]])
y_data = np.array([[1,1,-1]])
w = (np.random.random(3)-0.5)*2
print(w)
lr = 0.11
out_data = 0
n = 0def update():global x_data,y_data,w,lr,nn += 1out_data = np.dot(x_data,w.T) w_c = lr*((y_data-out_data.T).dot(x_data))/int(x_data.shape[0])w = w+w_cfor i in range(100):update() out_data = np.sign(np.dot(x_data,w.T)) print("epoch:",i)print("w:",w)if(out_data==y_data.T).all(): print("#####################")print("finished")print("epoch:",i)print("#####################")break
x1 = [3,4]
y1 = [3,3]
x2 = [1]
y2 = [1]
k = -w[0,1]/w[0,2]
b = -w[0,0]/w[0,2]
print("k = ",k)
print("b = ",b)xdata =np.linspace(0,5)
plt.figure()
plt.plot(xdata,xdata*k+b,'r')
plt.scatter(x1,y1,c='b')
plt.scatter(x2,y2,c='y')
plt.show()
结果:
3.使用线性神经网络解决异或问题:
用一种简介的方式解决线性不可分的问题:用多个线性函数对区域进行划分,然后对各个神经元的输出做逻辑运算
解决异或问题需要利用曲线,所以构建跟多的输入属性即
(1,x1,x2,x12,x22,2x1x2)(1,x_1,x_2,x_1^2,x_2^2,2x_1x_2)(1,x1,x2,x12,x22,2x1x2)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
x_data = np.array([[1,0,0,0,0,0],[1,0,1,0,0,1],[1,1,0,1,0,0],[1,1,1,1,1,1]])
y_data = np.array([[-1,1,1,-1]])
poly_reg = PolynomialFeatures(degree=2)
x_poly = poly_reg.fit_transform([[0,0],[0,1],[1,0],[1,1]])
print(x_poly)
y_data = np.array([[-1,1,1,-1]])
w = (np.random.random(6)-0.5)*2
print(w)
lr = 0.11
out_data = 0
n = 0def update():global x_data,y_data,w,lr,nn += 1out_data = np.dot(x_data,w.T) w_c = lr*((y_data-out_data.T).dot(x_data))/int(x_data.shape[0])w = w+w_c
for i in range(1000):update()
x1 = [0,1]
y1 = [1,0]
x2 = [1,0]
y2 = [1,0]def calculate(x,root):"""进行公式推导,确定二次方程的解得到a/b/c返回函数的解"""a = w[0,5]b = w[0,2]+x*w[0,4]c = w[0,0]+x*w[0,1]+x*x*w[0,3]if root ==1:return(-b+np.sqrt(b*b-4*a*c))/(2*a)if root == 2:return(-b-np.sqrt(b*b-4*a*c))/(2*a)
xdata =np.linspace(-1,2)
plt.figure()
plt.plot(xdata,calculate(xdata,1),'r')
plt.plot(xdata,calculate(xdata,2),'r')
plt.plot(x1,y1,'bo')
plt.plot(x2,y2,'yo')
plt.show()
结果视图:
进击的巨人——三笠.阿克曼