基础代码
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
# 创建一个简单的模型
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = nn.Linear(10, 1) # 输入特征维度为3,输出为1
self.sofamax = nn.Softmax(dim=1) # 输入特征维度为3,输出为1
self.linear1 = nn.Linear(10, 1) # 输入特征维度为3,输出为1
# self.sofamax1 = nn.Softmax(dim=1) # 输入特征维度为3,输出为1
self.sig = nn.Sigmoid()
def forward(self, x):
out = self.linear(x)
out = self.sofamax(out)
out = self.linear1(x)
# out = self.sofamax1(out)
out = self.sig(out)
return out
# 准备数据
# x_train = torch.tensor([[1, 2, 3, 1, 2, 1, 2, 3, 1, 2], [4, 5, 6,5, 6, 4, 5, 6,5, 6], [4, 5, 6,5, 6, 7, 8, 7, 8, 9]], dtype=torch.float32)
# y_train = torch.tensor([[1], [1], [0]], dtype=torch.float32)
x_train = torch.tensor(np.random.random((100, 10)), dtype=torch.float32)
y_train = torch.tensor(np.random.randint(0, 2, (100, 1)), dtype=torch.float32)
print("x_train shape:", x_train.shape)
print("y_train shape:", y_train.shape)
# 创建模型实例、损失函数和优化器
model = Model()
criterion = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 训练模型
num_epochs = 1000
for epoch in range(num_epochs):
# 前向传播
outputs = model(x_train)
loss = criterion(outputs, y_train)
# 反向传播和优化
optimizer.zero_grad() # 清零梯度
loss.backward() # 反向传播
optimizer.step() # 更新权重
if (epoch+1) % 100 == 0:
print(f"Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}")
# 使用训练好的模型进行预测
x_test = torch.tensor([[1, 4, 6, 2, 1, 6, 2, 4, 6, 1], [3, 6, 9, 2, 4, 6, 2, 4, 6, 2]], dtype=torch.float32)
preds = model(x_test)
print("预测结果:")
print(preds)
x_train shape: torch.Size([100, 10])
y_train shape: torch.Size([100, 1])
Epoch [100/1000], Loss: 0.6853
Epoch [200/1000], Loss: 0.6840
Epoch [300/1000], Loss: 0.6831
Epoch [400/1000], Loss: 0.6823
Epoch [500/1000], Loss: 0.6816
Epoch [600/1000], Loss: 0.6809
Epoch [700/1000], Loss: 0.6802
Epoch [800/1000], Loss: 0.6796
Epoch [900/1000], Loss: 0.6790
Epoch [1000/1000], Loss: 0.6784
预测结果:
tensor([[0.9321],
[0.9668]], grad_fn=