自定义数据集 使用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}")
相关推荐
没事勤琢磨20 分钟前
如何让 OpenClaw 控制使用浏览器:让 AI 像真人一样操控你的浏览器
人工智能
用户51914958484523 分钟前
CrushFTP 认证绕过漏洞利用工具 (CVE-2024-4040)
人工智能·aigc
牛马摆渡人52840 分钟前
OpenClaw实战--Day1: 本地化
人工智能
前端小豆41 分钟前
玩转 OpenClaw:打造你的私有 AI 助手网关
人工智能
BugShare1 小时前
写一个你自己的Agent Skills
人工智能·程序员
机器之心1 小时前
英伟达护城河被AI攻破,字节清华CUDA Agent,让人人能搓CUDA内核
人工智能·openai
后端小肥肠2 小时前
公众号躺更神器!OpenClaw+Claude Skill 实现自动读对标 + 写文 + 配图 + 存入草稿箱
人工智能·aigc·agent
爱可生开源社区3 小时前
SCALE | 重构 AI 时代数据库能力的全新评估标准
人工智能
Jahzo3 小时前
openclaw本地化部署体验与踩坑记录--飞书机器人配置
人工智能·开源
Narrastory3 小时前
明日香 - Pytorch 快速入门保姆级教程(一)
人工智能·pytorch·深度学习