当前位置: 首页 > article >正文

机器学习day7

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

代码

import numpy as np
import torch
import torch.nn as nn
import torch.optim as optimizer
import matplotlib.pyplot as plt
 
class1_points = np.array([[2.1, 1.8],
                          [1.9, 2.4],
                          [2.2, 1.2],
                          [1.8, 1.5],
                          [1.3, 1.7],
                          [1.6, 2.1],
                          [1.7, 1.4]])
 
class2_points = np.array([[3.5, 3.4],
                          [3.8, 2.7],
                          [3.4, 2.9],
                          [3.1, 3.6],
                          [3.9, 2.4],
                          [4.0, 2.8],
                          [3.3, 2.5]])
 
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()
 
cri = nn.BCELoss()
lr = 0.05
optimizer = optimizer.SGD(model.parameters(), lr=lr)
 
fig, (ax1, ax2) = plt.subplots(1, 2)
epoch_list = []
epoch_loss = []
 
epoches = 1000
for epoch in range(1, epoches + 1):
    y_pre = model(x_train_tensor)
    loss = cri(y_pre, 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()}")
        w1, w2 = model.fc.weight.data[0]
        b = model.fc.bias.data[0]
 
        slope = -w1 / w2
        intercept = -b / w2
 
        x_min, x_max = 0, 5
        x = np.array([x_min, x_max])
        y = slope * x + intercept
 
        ax1.clear()
        ax1.plot(x, y, 'r')
        ax1.scatter(x_train[:len(class1_points), 0], x_train[:len(class1_points), 1])
        ax1.scatter(x_train[len(class1_points):, 0], x_train[len(class1_points):, 1])
 
        ax2.clear()
        epoch_list.append(epoch)
        epoch_loss.append(loss.item())
        ax2.plot(epoch_list, epoch_loss, 'b')
        plt.pause(1)

from sklearn.metrics import accuracy_score, recall_score, f1_score

# 进行预测
with torch.no_grad():
    y_pred = model(x_train_tensor)
    y_pred_class = (y_pred > 0.5).float()  # 使用阈值0.5将概率转化为二分类结果

# 计算准确率、召回率和F1分数
accuracy = accuracy_score(y_train, y_pred_class)
recall = recall_score(y_train, y_pred_class)
f1 = f1_score(y_train, y_pred_class)

print(f"准确率: {accuracy:.4f}")
print(f"召回率: {recall:.4f}")
print(f"F1分数: {f1:.4f}")


http://www.kler.cn/a/531882.html

相关文章:

  • 什么是LPU?会打破全球算力市场格局吗?
  • C#方法作用
  • C语言实现字符串排序:从代码到原理深度解析
  • Docker入门篇(Docker基础概念与Linux安装教程)
  • GESP2023年9月认证C++六级( 第三部分编程题(2)小杨的握手问题)
  • 计算机网络概述
  • 红黑树的封装
  • 680.验证回文串||
  • 基于“蘑菇书”的强化学习知识点(二):强化学习中基于策略(Policy-Based)和基于价值(Value-Based)方法的区别
  • Debezium Oracle Connector SCN处理优化指南
  • Linux篇——权限
  • 02.03 递归运算
  • 中间件漏洞之CVE-2024-53677
  • C++ 游戏开发:完整指南
  • 浅谈《图解HTTP》
  • Baklib如何在知识管理领域成为领军者与六款产品的综合评析
  • Skyeye 云 VUE 版本 v3.15.6 发布
  • [Java]抽象类
  • 【Three.js+React】教程002:添加lil-gui控制器和加载GLTF模型
  • 股票入门知识
  • 文字显示省略号
  • 如何创建折叠式Title
  • 探秘Linux IO虚拟化:virtio的奇幻之旅
  • HTTP异步Client源码解析
  • 01:安装和部署
  • Alibaba grpc Dubbo view