np.random.random(10)是生成10个0-1的随机数,没有负值。
numpy.random.rand()产生从[0,1)[0,1)[0,1)之间的随机数,没有负值。
numpy.random.randn()产生服从正态分布的随机数,会出现负值。
三个输入神经元,一个输出神经元。
import numpy as np
import matplotlib.pyplot as plt
# 输入数据
X = np.array([[1,3,3],
[1,4,3],
[1,1,1]])
# 标签
Y = np.array([1,1,-1])
# 权值初始化,1行3列,取值范围 -1---1
W = (np.random.random(3)-0.5)*2
print(W)
#学习率设置
lr = 0.1
# 计算迭代次数
n = 0
#神经网络输出
O = 0
def update():
global X, Y, W,lr, n
n += 1
O = np.sign(np.dot(X, W.T))
W_C = lr*(Y-O.T).dot(X)/int(X.shape[0])
W = W + W_C
return W
for _ in range(100):
W = update()
print(W)
print(n)
O = np.sign(np.dot(X, W.T))
if (O == Y.T).all(): #如果实际输出等于期望输出,模型收敛,循环结束
print('Finished')
break
#正样本
x1 = [3,4]
y1 = [3,3]
#fu样本
x2 = [1]
y2 = [1]
# 斜率和截距
k = -W[1]/W[2]
D = -W[0]/W[2]
print('k=', k)
print('d=', D)
xdata = np.linspace(0,5)
plt.figure()
plt.plot(xdata, xdata*k+D,'r')
plt.plot(x1,y1,'bo')
plt.plot(x2,y2,'yo')
plt.show()