softmax回归pytorch实现代码
时间: 2023-10-26 19:09:04 浏览: 114
Sure, 这是一个简单的 softmax 回归 PyTorch 实现代码:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
# 定义 softmax 回归模型
class SoftmaxRegression(nn.Module):
def __init__(self, in_dim, out_dim):
super(SoftmaxRegression, self).__init__()
self.linear = nn.Linear(in_dim, out_dim)
def forward(self, x):
y = self.linear(x)
y = F.softmax(y, dim=1)
return y
# 加载数据集
x_train = torch.randn(1000, 10)
y_train = torch.randint(0, 5, (1000,))
x_test = torch.randn(200, 10)
y_test = torch.randint(0, 5, (200,))
# 定义模型、损失函数、优化器
model = SoftmaxRegression(10, 5)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
# 训练模型
for epoch in range(100):
model.train()
optimizer.zero_grad()
y_pred = model(x_train)
loss = criterion(y_pred, y_train)
loss.backward()
optimizer.step()
# 测试模型
if epoch % 10 == 0:
model.eval()
correct = 0
with torch.no_grad():
y_pred = model(x_test)
_, predicted = torch.max(y_pred, 1)
correct += (predicted == y_test).sum().item()
acc = correct / len(y_test)
print(f"Epoch [{epoch+1}/100], Loss: {loss.item():.4f}, Accuracy: {acc:.4f}")
```
希望能够帮到你!
阅读全文