神经网络

单层神经网络

import numpy as np

X = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
y = np.array([[0], [1], [1], [0]])

w = np.random.random((3, 1))


def fp(X):
    z = np.dot(X, w)
    return 1 / (1 + np.exp(-z))


def bp(y, output):
    error = y - output
    slope = output * (1 - output)
    return error * slope


for i in range(100):
    output = fp(X)
    delta = bp(y, output)
    w = w + np.dot(X.T, delta)


print(fp([[1, 0, 0]]))

多层神经网络

import numpy as np

X = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
y = np.array([[0], [1], [1], [0]])

# 神经元个数                                                                                              
n = 4

w0 = np.random.random((3, n))
w1 = np.random.random((n, 1))


def fp(l0):
    l1 = 1 / (1 + np.exp(-np.dot(l0, w0)))
    l2 = 1 / (1 + np.exp(-np.dot(l1, w1)))
    return l1, l2


def bp(l1, l2, y):
    l1_error = y - l2
    l1_slope = l2 * (1 - l2)
    l1_delta = l1_error * l1_slope

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

    return l0_delta, l1_delta


for i in range(1000):
    l0 = X
    l1, l2 = fp(l0)
    l0_delta, l1_delta = bp(l1, l2, y)
    w1 = w1 + np.dot(l1.T, l1_delta)
    w0 = w0 + np.dot(l0.T, l0_delta)

print(fp([[1, 1, 1]])[1])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值