#!/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()
神经网络-前向传播 -0827
于 2025-08-27 18:29:48 首次发布
#!/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()
1972

被折叠的 条评论
为什么被折叠?



