提交 fdc2558d 编写于 作者: R root

Wed Jul 23 12:57:00 CST 2025 inscode

上级 359494af
import numpy as np
class SimpleRNN:
def __init__(self, input_size, hidden_size):
self.Wx = np.random.randn(hidden_size, input_size) # 输入权重
self.Wh = np.random.randn(hidden_size, hidden_size) # 隐藏状态权重
self.b = np.zeros((hidden_size, 1)) # 偏置项
def forward(self, x, h_prev):
h_next = np.tanh(np.dot(self.Wx, x) + np.dot(self.Wh, h_prev) + self.b)
return h_next
# 测试 SimpleRNN
def test_simple_rnn():
# 参数设置
input_size = 30 # 输入向量的维度
hidden_size = 20 # 隐藏状态的维度
seq_length = 5 # 序列长度
# 初始化 RNN
rnn = SimpleRNN(input_size, hidden_size)
# 生成随机输入序列 (input_size, seq_length)
np.random.seed(42) # 固定随机种子以便复现结果
x_sequence = [np.random.randn(input_size, 1) for _ in range(seq_length)] # 每个时间步的输入 (input_size, 1)
# 初始隐藏状态 (hidden_size, 1)
h = np.zeros((hidden_size, 1))
# 前向传播
print("RNN 前向传播测试:")
for t, x in enumerate(x_sequence):
h = rnn.forward(x, h)
print(f"时间步 {t}:")
print(f"输入 x_{t} 的形状: {x.shape}, 值:\n{x.T}")
print(f"隐藏状态 h_{t} 的形状: {h.shape}, 值:\n{h.T}")
print("-" * 50)
if __name__ == "__main__":
test_simple_rnn()
\ No newline at end of file
import torch
# 创建一个 2x3 的全 0 张量
a = torch.zeros(2, 3)
print(a)
# 创建一个 2x3 的全 1 张量
b = torch.ones(2, 3)
print(b)
# 创建一个 2x3 的随机数张量
c = torch.randn(2, 3)
print(c)
# 从 NumPy 数组创建张量
import numpy as np
numpy_array = np.array([[1, 2], [3, 4]])
tensor_from_numpy = torch.from_numpy(numpy_array)
print(tensor_from_numpy)
# 在指定设备(CPU/GPU)上创建张量
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
d = torch.randn(2, 3, device=device)
print(torch.cuda.is_available())
print(d)
# 逐元素乘法(要求形状相同)
X = torch.tensor([[1, 2], [3, 4]])
Y = torch.tensor([[5, 6], [7, 8]])
Z = X * Y # 或 torch.mul(X, Y)
print("逐元素乘法结果:\n", Z)
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册