自定义数据集 使用pytorch框架实现逻辑回归并保存模型,然后保存模型后再加载模型进行预测,对预测结果计算精确度和召回率及F1分数

python 复制代码
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import precision_score, recall_score, f1_score

# 数据准备
class1_points = np.array([[1.9, 1.2],
                          [1.5, 2.1],
                          [1.9, 0.5],
                          [1.5, 0.9],
                          [0.9, 1.2],
                          [1.1, 1.7],
                          [1.4, 1.1]])
class2_points = np.array([[3.2, 3.2],
                          [3.7, 2.9],
                          [3.2, 2.6],
                          [1.7, 3.3],
                          [3.4, 2.6],
                          [4.1, 2.3],
                          [3.0, 2.9]])

x_train = np.concatenate((class1_points, class2_points), axis=0)
y_train = np.concatenate((np.zeros(len(class1_points)), np.ones(len(class2_points))))

x_train_tensor = torch.tensor(x_train, dtype=torch.float32)
y_train_tensor = torch.tensor(y_train, dtype=torch.float32)

# 设置随机种子
seed = 42
torch.manual_seed(seed)

# 定义模型
class LogisticRegreModel(nn.Module):
    def __init__(self):
        super(LogisticRegreModel, self).__init__()
        self.fc = nn.Linear(2, 1)

    def forward(self, x):
        x = self.fc(x)
        x = torch.sigmoid(x)
        return x

model = LogisticRegreModel()

# 定义损失函数和优化器
criterion = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.05)

# 训练模型
epochs = 1000
for epoch in range(1, epochs + 1):
    y_pred = model(x_train_tensor)
    loss = criterion(y_pred, y_train_tensor.unsqueeze(1))
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if epoch % 50 == 0 or epoch == 1:
        print(f"epoch: {epoch}, loss: {loss.item()}")

# 保存模型
torch.save(model.state_dict(), 'model.pth')

# 加载模型
model = LogisticRegreModel()
model.load_state_dict(torch.load('model.pth'))
# 设置模型为评估模式
model.eval()

# 进行预测
with torch.no_grad():
    y_pred = model(x_train_tensor)
    y_pred_class = (y_pred > 0.5).float().squeeze()

# 计算精确度、召回率和F1分数
precision = precision_score(y_train_tensor.numpy(), y_pred_class.numpy())
recall = recall_score(y_train_tensor.numpy(), y_pred_class.numpy())
f1 = f1_score(y_train_tensor.numpy(), y_pred_class.numpy())

print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 Score: {f1:.4f}")
相关推荐
Tipriest_3 小时前
torch训练出的模型的组成以及模型训练后的使用和分析办法
人工智能·深度学习·torch·utils
QuiteCoder3 小时前
深度学习的范式演进、架构前沿与通用人工智能之路
人工智能·深度学习
周名彥3 小时前
### 天脑体系V∞·13824D完全体终极架构与全域落地研究报告 (生物计算与隐私计算融合版)
人工智能·神经网络·去中心化·量子计算·agi
MoonBit月兔3 小时前
年终 Meetup:走进腾讯|AI 原生编程与 Code Agent 实战交流会
大数据·开发语言·人工智能·腾讯云·moonbit
大模型任我行4 小时前
人大:熵引导的LLM有限数据训练
人工智能·语言模型·自然语言处理·论文笔记
weixin_468466854 小时前
YOLOv13结合代码原理详细解析及模型安装与使用
人工智能·深度学习·yolo·计算机视觉·图像识别·目标识别·yolov13
蹦蹦跳跳真可爱5894 小时前
Python----大模型(GPT-2模型训练加速,训练策略)
人工智能·pytorch·python·gpt·embedding
xwill*4 小时前
π∗0.6: a VLA That Learns From Experience
人工智能·pytorch·python
jiayong234 小时前
知识库概念与核心价值01
java·人工智能·spring·知识库
雨轩剑4 小时前
做 AI 功能不难,难的是把 App 发布上架
人工智能·开源软件