机器学习day7

ops/2025/2/8 17:31:05/

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

代码

import numpy as np
import torch
import torch.nn as nn
import torch.optim as optimizer
import matplotlib.pyplot as pltclass1_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 xmodel = 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 / w2intercept = -b / w2x_min, x_max = 0, 5x = np.array([x_min, x_max])y = slope * x + interceptax1.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.ppmy.cn/ops/156770.html

相关文章

【Python】第一弹---解锁编程新世界:深入理解计算机基础与Python入门指南

✨个人主页: 熬夜学编程的小林 💗系列专栏: 【C语言详解】 【数据结构详解】【C详解】【Linux系统编程】【MySQL】【Python】 目录 1、计算机基础概念 1.1、什么是计算机 1.2、什么是编程 1.3、编程语言有哪些 2、Python 背景知识 2.…

【leetcode100】岛屿的周长

1、题目描述 给定一个 row x col 的二维网格地图 grid ,其中:grid[i][j] 1 表示陆地, grid[i][j] 0 表示水域。 网格中的格子 水平和垂直 方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好…

【ArcGIS Pro简介2】

ArcGIS Pro是由Esri公司开发的一款专业地理信息系统(GIS)软件,用于创建、管理、分析和可视化地理空间数据。以下是关于ArcGIS Pro的详细介绍: 一、主要特点 现代化界面:ArcGIS Pro采用现代化的Ribbon界面&#xff0…

尚硅谷 vue3+TS 课程笔记

1. Vue3简介 2020年9月18日,Vue.js发布版3.0版本,代号:One Piece(n 经历了:4800次提交、40个RFC、600次PR、300贡献者 官方发版地址:Release v3.0.0 One Piece vuejs/core 截止2023年10月,最…

免费windows pdf编辑工具Epdf

Epdf(完全免费) 作者:不染心 时间:2025/2/6 Github: https://github.com/dog-tired/Epdf Epdf Epdf 是一款使用 Rust 编写的 PDF 编辑器,目前仍在开发中。它提供了一系列实用的命令行选项,方便用户对 PDF …

基于RTOS的STM32游戏机

1.游戏机的主要功能 所有游戏都来着B站JL单片机博主开源 这款游戏机具备存档与继续游戏功能,允许玩家在任何时候退出当前游戏并保存进度,以便日后随时并继续之前的冒险。不仅如此,游戏机还支持多任务处理,玩家可以在退出当前游戏…

c++ template-3

第 7 章 按值传递还是按引用传递 从一开始,C就提供了按值传递(call-by-value)和按引用传递(call-by-reference)两种参数传递方式,但是具体该怎么选择,有时并不容易确定:通常对复杂类…

小程序:如何暂时停用小程序?

一、点击左下角小程序的名称,》账号设置。 二、进入后点击“暂停服务”