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

运行结果如下

相关推荐
curd_boy7 小时前
【Redis】Redis从缓存到AI向量平台
人工智能·redis·缓存
kyriewen8 小时前
GPT-6 发布当晚,三大 AI 集体宕机 4 小时——我扒完时间线,发现最该慌的不是宕机
人工智能·程序员·ai编程
GrepowTattu8 小时前
从2026世界机器人大会看机器人补能:为什么智能充电正在成为重要一环
人工智能·机器人
IT_陈寒8 小时前
React Hooks闭包陷阱差点让我加班到凌晨
前端·人工智能·后端
揽秀亭长8 小时前
视频转文字工具对比:从字幕生成到文本整理
人工智能·音视频
工业甲酰苯胺8 小时前
AI低代码破局:制造业数智转型落地实战
大数据·人工智能·低代码·制造
CaseyWei8 小时前
Harness 架构 Multi‑Agent(多智能体)完整深度解析
人工智能·ai·架构·harness
eaglewgs9 小时前
关于AI书写测试用例,谈一下我的思考
人工智能·测试开发·ai·测试用例·agent·测试经验·agent测试开发
熊野君9 小时前
第 4 章 技术产品经理核心能力模型
大数据·人工智能·产品经理
问天_观心9 小时前
大模型微调学习(一)
开发语言·人工智能·学习·语言模型·github