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

运行结果如下

相关推荐
平凡而伟大(心之所向)几秒前
一文讲清楚自我学习和深度学习
人工智能·深度学习·机器学习
挣扎与觉醒中的技术人4 分钟前
如何本地部署大模型及性能优化指南(附避坑要点)
人工智能·opencv·算法·yolo·性能优化·audiolm
ZHOU_WUYI13 分钟前
Measuring short-form factuality in large language models (SimpleQA) 论文简介
人工智能·自然语言处理
码上飞扬18 分钟前
大语言模型的逻辑:从“鹦鹉学舌”到“举一反三”
人工智能·语言模型·自然语言处理
Luis Li 的猫猫33 分钟前
随机森林算法详解
人工智能·算法·随机森林·机器学习
青云交1 小时前
Java 大视界 -- Java 大数据在智能金融反欺诈中的技术实现与案例分析(114)
java·大数据·机器学习·金融·实时监控·反欺诈·智能金融
何仙鸟1 小时前
机器学习之逻辑回归
人工智能·机器学习·逻辑回归
永霖光电_UVLED1 小时前
Rohm发布TOLL封装650V GaN HEMT,引领汽车用GaN器件大规模生产新浪潮
人工智能·生成对抗网络·汽车
Luis Li 的猫猫1 小时前
突破光学成像局限:全视野光学血管造影技术新进展
论文阅读·图像处理·人工智能·算法·目标检测
Tolalal2 小时前
DDK:Distilling Domain Knowledge for Efficient Large Language Models
人工智能·语言模型·自然语言处理·知识蒸馏