自定义数据集 使用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}")
相关推荐
wb0430720110 分钟前
阿明的二次创业——从阿明用 AI 开第二家店,看 AI 原生创业的四阶段方法论
大数据·人工智能·架构
Godspeed Zhao10 分钟前
Level 4自动驾驶系统设计0——功能与场景0
人工智能·机器学习·自动驾驶
Dola_Zou13 分钟前
边缘智能的“黑暗森林”:工业 AI 模型下沉的资产防护与变现密码
人工智能·安全·自动化·软件工程·软件加密
青岛前景互联信息技术有限公司14 分钟前
前景互联·新一代智能接处警系统:AI+大模型+Agent智能接处警一体化解决方案
大数据·人工智能·物联网
xin_yao_xin17 分钟前
Claude Code 安装与 DeepSeek-V4 模型配置(2026 最新)
人工智能·ai·大模型·deepseek·claude code
北京软秦科技有限公司17 分钟前
通用零部件来料材质证书智能把关,IACheck搭配AI报告审核通审Agent版比对订单与报告参数
人工智能·材质
Charlotte_jc20 分钟前
ai agent 真实项目开发工程实践
人工智能
CCC:CarCrazeCurator22 分钟前
大模型核心注意力机制技术深度报告:MHA、MQA、GQA 与 MLA 技术原理、性能对比与场景适配
人工智能·机器学习·自动驾驶·transformer
卢卡上学23 分钟前
CodeBuddy 与 WorkBuddy 完整联动方案,研发 + 办公双线提效!
人工智能·腾讯workbuddy·腾讯codebuddy
秋924 分钟前
Python工程师面试常问提问和回答(AI工程化方向 · 2026版)
人工智能·python·面试