机器学习day4

自定义数据集 使用pytorch框架实现逻辑回归并保存模型,然后保存模型后再加载模型进行预测

python 复制代码
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)

运行结果如下

相关推荐
全栈开发圈7 分钟前
干货分享|鸿蒙6开发实战指南
人工智能·harmonyos·鸿蒙·鸿蒙系统
房产中介行业研习社36 分钟前
2026年1月房产中介管理系统排名
大数据·人工智能
沛沛老爹1 小时前
Web转AI架构篇 Agent Skills vs MCP:工具箱与标准接口的本质区别
java·开发语言·前端·人工智能·架构·企业开发
ZKNOW甄知科技1 小时前
IT自动分派单据:让企业服务流程更智能、更高效的关键技术
大数据·运维·数据库·人工智能·低代码·自动化
OpenCSG1 小时前
如何通过 AgenticOps x CSGHub 重塑企业 AI 生产力
人工智能
Nautiluss1 小时前
一起调试XVF3800麦克风阵列(十四)
linux·人工智能·音频·语音识别·dsp开发
地瓜伯伯1 小时前
elasticsearch性能调优方法原理与实战
人工智能·elasticsearch·语言模型·数据分析
ZCXZ12385296a1 小时前
YOLO13改进模型C3k2-SFHF实现:阻尼器类型识别与分类系统详解
人工智能·分类·数据挖掘
黑客思维者1 小时前
2025年AI垃圾(AI Slop)现象综合研究报告:规模、影响与治理路径
人工智能·搜索引擎·百度
Aspect of twilight2 小时前
QwenVL 模型输入细节
人工智能·qwen