Python入门,实现神经网络

avatar 2024年04月19日18:09:16 0 103 views
博主分享免费Java教学视频,B站账号:Java刘哥

一、先实现一层的神经网络

我们自己心里推测一下:如花去了,小明就去。如花不去,小明不去

# 1. 引入类库
from numpy import random, dot, exp, array


# 2. forward propagation 前向传播:根据输入计算输出
def fp(input):
    # 利用矩阵乘法一次性计算4个z出来
    z = dot(input, weights)
    # 使用Sigmoid函数,让z范围在0-1之间
    return 1 / (1 + exp(-z))


# 3. backward propagation 反向传播:根据误差调整权重
def bp(y, output):
    # 看看我们计算出来的(随机权重乘出来的)和实际的误差
    error = y - output
    # 计算斜率,计算在Sigmoid函数中,该值所在点处的斜率
    slope = output * (1 - output)
    # 计算增量, 增量=误差*斜率
    return error * slope


# 2. 加载数据
X = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])  # 4个样本,每个样本3个特征(分别是如花、小美、小强是否去看电影)
y = array([[0, 1, 1, 0]]).T  # 表示4个样本中,小明是否去看电影

# 3. 设置随机权重
random.seed(1)  # 每次运行,生成的随机数相同
weights = random.random((3, 1)) * 2 - 1  # 生成3行1列的随机数,随机数范围为(-1, 1)
print(weights)

# 4. 循环
for i in range(10000):
    output = fp(X)
    delta = bp(y, output)
    # 更新权重,计算权重需要变化的增量
    weights = weights + dot(X.T, delta)

print(weights)  # 以上目的就是生成一个权重矩阵。
# 最后计算是,输入 与 权重矩阵 点乘
print(fp([1, 1, 0]))  # [0.9999225] 即小明去看电影的概率为99.99%

 

二、情况复杂了

现在,情况复杂了

现在我们推测,如花和大美两人去一个,小强就去;两人同时去,小强就不去

如果用之前的代码,运行结果是 0.5

或者输入已经运行过的数据,答案也是0.5

说明单层神经网络不能满足我们的需求

 

三、双层神经网络

# 1. 引入类库
from numpy import random, dot, exp, array


# 2. forward propagation 前向传播:根据输入计算输出
def fp(input):
    # 利用矩阵乘法一次性计算4个z出来。使用Sigmoid函数,让z范围在0-1之间
    l1 = 1 / (1 + exp(-dot(input, w0)))
    l2 = 1 / (1 + exp(-dot(l1, w1)))
    return l1, l2


# 3. backward propagation 反向传播:根据误差调整权重
def bp(l1, l2, y):
    error = y - l2
    slope = l2 * (1 - l2)
    l1_delta = error * slope

    l0_slope = l1 * (1 - l1)
    l0_error = l1_delta.dot(w1.T)

    l0_delta = l0_slope * l0_error

    return l0_delta, l1_delta


# 2. 加载数据
X = array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]])  # 4个样本,每个样本3个特征(分别是如花、小美、小强是否去看电影)
y = array([[0, 1, 1, 0]]).T  # 表示4个样本中,小明是否去看电影

# 3. 设置随机权重
random.seed(1)  # 每次运行,生成的随机数相同
w0 = random.random((3, 4)) * 2 - 1  # 生成3行4列的随机数,随机数范围为(-1, 1)
w1 = random.random((4, 1)) * 2 - 1  # 生成4行1列的随机数,随机数范围为(-1, 1)

# 4. 循环
for i in range(1000):
    l0 = X
    l1, l2 = fp(l0)
    l0_delta, l1_delta = bp(l1, l2, y)

    w1 = w1 + dot(l1.T, l1_delta)
    w0 = w0 + dot(l0.T, l0_delta)

print(fp([[0, 0, 1]])[1])  # 对已经训练过的数据进行预测,[[0.03504843]] = 0,正确
print(fp([[0, 1, 1]])[1])  # 对已经训练过的数据进行预测,[[0.95467404]] = 1,正确
print(fp([[1, 0, 1]])[1])  # 对已经训练过的数据进行预测,[[0.96199055]] = 1,正确

print(fp([[1, 0, 1]])[1])  # 对新数据进行预测,[[0.96199055]] 如花去了=>小明也去
print(fp([[1, 1, 0]])[1])  # 对新数据进行预测,[[0.03606592]] 如花和大美都去了=>小明不去

 

图片和代码参考:https://www.bilibili.com/video/BV1XE411C7mS

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0