利用 torch.nn 实现 logistic 回归在人工构造的数据集上进行训练和测试,并对结果进行分析, 并从loss、训练集以及测试集上的准确率等多个角度对结果进行分析
时间: 2024-04-14 16:26:53 浏览: 163
好的,以下是使用torch.nn实现logistic回归在人工构造的数据集上进行训练和测试,并对结果进行分析的步骤:
首先,导入所需的和模块:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
```
然后,构建人工数据集:
```python
# 创建训练集数据
train_data = np.random.normal(0, 1, (100, 2))
train_labels = np.zeros((100,))
train_labels[train_data[:, 0] + train_data[:, 1] > 0] = 1
# 创建测试集数据
test_data = np.random.normal(0, 1, (20, 2))
test_labels = np.zeros((20,))
test_labels[test_data[:, 0] + test_data[:, 1] > 0] = 1
# 转换为Tensor类型
train_data = torch.from_numpy(train_data).float()
train_labels = torch.from_numpy(train_labels).float()
test_data = torch.from_numpy(test_data).float()
test_labels = torch.from_numpy(test_labels).float()
```
接下来,定义Logistic回归模型:
```python
class LogisticRegression(nn.Module):
def __init__(self, input_dim):
super(LogisticRegression, self).__init__()
self.linear = nn.Linear(input_dim, 1)
def forward(self, x):
out = torch.sigmoid(self.linear(x))
return out
model = LogisticRegression(2)
```
然后,定义损失函数和优化器:
```python
criterion = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
```
接着,进行模型的训练:
```python
num_epochs = 100
for epoch in range(num_epochs):
# 前向传播
outputs = model(train_data)
loss = criterion(outputs, train_labels.unsqueeze(1))
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
```
最后,对模型进行测试并分析结果:
```python
# 在训练集上进行预测
train_outputs = model(train_data)
_, train_predicted = torch.max(train_outputs, 1)
train_accuracy = torch.sum(train_predicted == train_labels).item() / train_labels.size(0)
# 在测试集上进行预测
test_outputs = model(test_data)
_, test_predicted = torch.max(test_outputs, 1)
test_accuracy = torch.sum(test_predicted == test_labels).item() / test_labels.size(0)
print('Train Accuracy: {:.2f}%'.format(train_accuracy * 100))
print('Test Accuracy: {:.2f}%'.format(test_accuracy * 100))
```
通过以上步骤,我们可以对logistic回归模型在人工构造的数据集上进行训练和测试,并分析结果。可以观察到每个epoch的loss逐渐减小,同时可以计算训练集和测试集上的准确率来评估模型的性能。
阅读全文