机器学习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)

运行结果如下

相关推荐
动物园猫27 分钟前
校园异常行为目标检测数据集:5类别 | 目标检测
人工智能·目标检测·计算机视觉
ShallWeL35 分钟前
NVIDIA Jetson 早期系列演进
人工智能·嵌入式硬件·边缘计算·智能硬件
IT_陈寒1 小时前
SpringBoot自动装配坑了我一天,原来问题出在这
前端·人工智能·后端
lisw051 小时前
社会技术需要社会协调!
人工智能·机器学习·软件工程
血小溅1 小时前
Claude Code 高效使用指南:让 AI 真正完成任务,而不只是生成代码
人工智能
ZGi.ai2 小时前
ZGI工作流引擎:把AI应用的执行过程从黑盒变成流程图
人工智能·低代码·流程图·ai应用·ai工作流·zgi
物联网软硬件开发-轨物科技2 小时前
【轨物方案】从传感器到AI诊断:箱变智能化技术栈四层架构精讲
人工智能·架构
星期一研究室2 小时前
创作分发这件事,来看看Codex是怎么做的
人工智能·黑客·微信
LLM精进之路2 小时前
把论文变成可提问的科研知识库:Zotero + Obsidian + Codex(ChatGPT 5.6)联动升级版教程,让你释放双手
人工智能
爱学习的章鱼哥2 小时前
一些AI实操的经验与感想
人工智能·ai·ai作画·ai编程·ai写作·ai经验