From fdc2558da9d70dd6e4133d9cbb234c4423b84e90 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 23 Jul 2025 12:57:00 +0800 Subject: [PATCH] Wed Jul 23 12:57:00 CST 2025 inscode --- test01.py | 40 ++++++++++++++++++++++++++++++++++++++++ test02.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 test01.py create mode 100644 test02.py diff --git a/test01.py b/test01.py new file mode 100644 index 0000000..54be4af --- /dev/null +++ b/test01.py @@ -0,0 +1,40 @@ +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 diff --git a/test02.py b/test02.py new file mode 100644 index 0000000..93bbc26 --- /dev/null +++ b/test02.py @@ -0,0 +1,31 @@ +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 -- GitLab