神经网络-前向传播 -0827


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import torch

def init_network():
    network = {}
    # 转为 torch Tensor
    network['W1'] = torch.tensor([[0.1, 0.3, 0.5],
                                  [0.2, 0.4, 0.6]], dtype=torch.float32)
    network['b1'] = torch.tensor([0.1, 0.2, 0.3], dtype=torch.float32)
    network['W2'] = torch.tensor([[0.1, 0.4],
                                  [0.2, 0.5],
                                  [0.3, 0.6]], dtype=torch.float32)
    network['b2'] = torch.tensor([0.1, 0.2], dtype=torch.float32)
    network['W3'] = torch.tensor([[0.1, 0.3],
                                  [0.2, 0.4]], dtype=torch.float32)
    network['b3'] = torch.tensor([0.1, 0.2], dtype=torch.float32)
    return network

def forward(network, x):
    # 如果 x 是 numpy,需要转为 Tensor
    if isinstance(x, np.ndarray):
        x = torch.from_numpy(x).float()

    W1, W2, W3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']

    a1 = torch.matmul(x, W1) + b1
    z1 = torch.sigmoid(a1)

    a2 = torch.matmul(z1, W2) + b2
    z2 = torch.sigmoid(a2)

    a3 = torch.matmul(z2, W3) + b3
    y = a3  # identity function 可以直接返回 a3
    return y

def main():
    network = init_network()
    x = np.array([1.0, 0.5])
    y = forward(network, x)
    print(y)  # tensor([0.3168, 0.6963])

if __name__ == "__main__":
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值