python 使用Softmax回归处理IrIs数据集

本文章包含以下内容:

        数据: lris数据集;

        模型: Softmax回归模型;

        损失函数:交叉嫡损失;

        优化器:梯度下降法;

        评价指标:准确率。

1.实验数据集

        Iris(1).csv无法上传,这里就不提供下载了,它长这样

         lris数据集,也称为鸢尾花数据集,包含了3种鸢尾花类别(Setosa · Versicolour - Virginica),每种类别有50个样本,共计150个样本。其中每个样本中包含了4个属性:花尊长度﹑花芎宽度﹑花瓣长度以及花瓣宽度,本实验通过鸢尾花这4个属性来判断该样本的类别。

2.读取数据集

        实验中将数据集划分为三个部分:训练集:用于确定模型参数;

        验证集:与训练集独立的样本集合,用于使用提前停止策略选择最优模型;

        测试集:用于估计应用效果。

        在本实验中,将80%的数据用于模型训练, 10%的数据用于模型验证,10%的数据用于模型测试。

3.模型构建

        使用Softmax回归模型进行鸢尾花分类实验,将模型的输入维度定义为4,输出维度定义为3。

4.模型训练

        使用训练集和验证集进行模型训练,共训练80个epoch,其中每隔10个epoch打印训练集上的指标,并且保存准确率最高的模型作为最佳模型。

5.模型评价

        使用测试数据对在训练过程中保存的最佳模型进行评价,观察模型在测试集上的准确率情况。

6.模型预测 

        使用保存好的模型,对测试集中的数据进行模型预测,并取出1条数据观察模型效果。

代码如下:

import numpy as np
import pandas as pd
import torch
from torch import nn


# 读取数据
def read_data(file):
    # 读取csv文件,并存入data,带标签 dataframe
    data = pd.read_csv(file)
    data = data.sample(frac=1).reset_index(drop=True)  # 打乱数据集
    y = list(data['Species'])  # 标签
    len_data = len(y)  # 数据个数
    # labels 删除的列标签,axis=1 删除列,inplace=True 改变原数据
    data.drop(labels=['Id', 'Species'], axis=1, inplace=True)  # 删除Id,Species列
    # Species 转独热向量
    for i in range(len(y)):
        if y[i] == 'Iris-setosa':
            y[i] = [1, 0, 0]
        elif y[i] == 'Iris-versicolor':
            y[i] = [0, 1, 0]
        elif y[i] == 'Iris-virginica':
            y[i] = [0, 0, 1]
    y = torch.Tensor(y)  # 转张量
    data = torch.Tensor(data.values)  # 转张量
    # train 训练
    # verification 验证
    # test 测试
    return [[data[0:int(len_data * 0.8)], y[0:int(len_data * 0.8)]],
            [data[int(len_data * 0.8):int(len_data * 0.9)], y[int(len_data * 0.8):int(len_data * 0.9)]],
            [data[int(len_data * 0.9):len_data], y[int(len_data * 0.9):len_data]]]


# 初始化参数 通过从均值为0﹑标准差为0.01的正态分布中采样随机数来初始化权重
# 并将偏置初始化为0。
def chushi():
    # 返回从正态分布中提取的随机数的张量,该正态分布的均值是mean,标准差是std。
    # requires_grad=True 表示需要计算梯度,注意size=(4,3)列向量
    w = torch.normal(mean=0.1, std=0.01, size=(4, 3), requires_grad=True)
    return w


# 测试函数,比较准确率
def ceshi(w, f, l):
    c = 0
    # 模型计算出所有的结果
    l1 = softmax(f, w)
    for i in range(len(l)):
        # 如果最大值对应的l值是1,说明验证正确。
        s = -1
        t = float('-inf')
        for j in range(len(l[0])):
            if l1[i][j] > t:
                t = l1[i][j]
                s = j
        if l[i][s]:
            c = c + 1
    return c / len(l)


# 该函数接收批量大小﹑特征矩阵和标签向量作为输入,生成大小为batch_size的小批量,每个小批量包含一组特征和标签。
def data_iter(batch_size, features, labels):  # 批量 特征 标签
    for i in range(len(labels) - batch_size):
        test_index = np.random.choice(len(features), batch_size, replace=False)
        yield features[test_index], labels[test_index]


def softexp(A):
    A = A.exp()
    A_sum = A.sum(axis=1, keepdims=True)
    A = A / A_sum
    return A


# 模型  输入特征为x﹑权重为w
def softmax(X, w):
    S = torch.matmul(X, w)
    return softexp(S)


# 交叉熵损失函数,返回损失值,其中y_hat为预测值, y为真实值。
def cross_entropy_loss(y_hat, y):
    lo = 0
    for i in range(len(y)):
        lo -= (torch.log(y_hat) * y).sum()
    return lo / len(y)


# 从数据集中随机抽取小批量样本,根据参数计算损失的梯度;然后朝着减少损失的方向更新参数。
# 实现小批量随机梯度下降更新,该函数接受模型参数集合﹑学习速率和批量大小作为输入。
def sgd(params, lr, batch_size, X, y, y_hat):
    # dw = (1.0 / batch_size) * torch.matmul((y - y_hat).T,X)
    # params.data = params + lr * dw.T
    params.data -= lr * params.grad / batch_size
    params.grad.zero_()


def xunlian(batch_size, features, labels, f_verify, l_verify, w):
    lr = 0.03  # 学习率
    num_epochs = 81  # 循环次数
    net = softmax  # 模型
    loss = cross_entropy_loss  # 损失函数
    stop = 0  # 上一回的验证集准确率早停用
    for epoch in range(num_epochs):
        for X, y in data_iter(batch_size, features, labels):
            y_hat = net(X, w)  # 计算y_hat
            l = loss(y_hat, y)  # X和y 的小批量损失
            # 因为l形状是(batch_size,1),而不是一个标量。l中的所有元素被加到一起,
            # 并以此计算关于[w,b]的梯度
            l.sum().backward()
            sgd(w, lr, batch_size, X, y, y_hat)  # 使用参数的梯度更新参数
        if epoch % 10 == 0:  # 每循环10次执行
            with torch.no_grad():  # 输出当前误差,循环次数
                train_l = loss(net(features, w), labels)
                print(f'epoch {epoch}, loss {float(train_l.mean()):f}')
                c = ceshi(w[:], features, labels, )  # 看一看在训练集上的准确率
                print('训练集准确率:', c * 100, "%")
                c = ceshi(w[:], f_verify, l_verify)  # 看一看在验证集上的准确率
                if stop > c:  # 准确率下降,早停
                    print('验证集准确率:', c * 100, "%-》早停")
                    break
                else:
                    print('验证集准确率:', c * 100, "%")
                    stop = c
                    W = w  # 拿验证集准确率最高的
    return W, stop


file = 'Iris(1).csv'  # 数据文件
[[X_train, y_train],
 [X_verification, y_verification],
 [X_test, y_test, ]] = read_data(file)  # 读取数据集
w = chushi()  # 初始化 w
batch_size = 1  # 批量大小为 8
# 训练函数
[w, c] = xunlian(batch_size, X_train, y_train, X_verification, y_verification, w)
print('训练完成====================================')
c = ceshi(w[:], X_test, y_test)  # 测试集准确率
print('测试集准确率:', c * 100, "%")
print('所得w如下:\n', w)
print('例子:\n X值:', X_test[0:1])
print('实际y', y_test[0:1])
print('预测y', softmax(X_test[0:1], w))
# print(w)

结果示例:

epoch 0, loss 68.055267
训练集准确率: 63.33333333333333 %
验证集准确率: 66.66666666666666 %
epoch 10, loss 27.553486
训练集准确率: 90.83333333333333 %
验证集准确率: 100.0 %
epoch 20, loss 18.791990
训练集准确率: 95.83333333333334 %
验证集准确率: 100.0 %
epoch 30, loss 17.222626
训练集准确率: 95.0 %
验证集准确率: 100.0 %
epoch 40, loss 18.608782
训练集准确率: 92.5 %
验证集准确率: 100.0 %
epoch 50, loss 14.631225
训练集准确率: 95.83333333333334 %
验证集准确率: 100.0 %
epoch 60, loss 15.789186
训练集准确率: 95.0 %
验证集准确率: 100.0 %
epoch 70, loss 16.089447
训练集准确率: 95.0 %
验证集准确率: 100.0 %
epoch 80, loss 12.320921
训练集准确率: 96.66666666666667 %
验证集准确率: 100.0 %
训练完成====================================
测试集准确率: 100.0 %
所得w如下:
 tensor([[ 1.6637,  1.3427, -2.6891],
        [ 3.2052,  0.6697, -3.5951],
        [-4.0419, -0.4740,  4.8318],
        [-1.8177, -2.4302,  4.5498]], requires_grad=True)
例子:
 X值: tensor([[5.4000, 3.4000, 1.5000, 0.4000]])
实际y tensor([[1., 0., 0.]])
预测y tensor([[9.9477e-01, 5.2329e-03, 4.3153e-14]], grad_fn=<DivBackward0>)

进程已结束,退出代码为 0
epoch 0, loss 108.753929
训练集准确率: 70.0 %
验证集准确率: 40.0 %
epoch 10, loss 34.283939
训练集准确率: 85.83333333333333 %
验证集准确率: 73.33333333333333 %
epoch 20, loss 28.772650
训练集准确率: 88.33333333333333 %
验证集准确率: 80.0 %
epoch 30, loss 15.300897
训练集准确率: 96.66666666666667 %
验证集准确率: 93.33333333333333 %
epoch 40, loss 17.209322
训练集准确率: 95.0 %
验证集准确率: 93.33333333333333 %
epoch 50, loss 13.655725
训练集准确率: 95.83333333333334 %
验证集准确率: 86.66666666666667 %-》早停
训练完成====================================
测试集准确率: 100.0 %
所得w如下:
 tensor([[ 1.4083,  1.2524, -2.3524],
        [ 2.7663,  0.2030, -2.6643],
        [-3.4667, -0.2554,  4.0330],
        [-1.5833, -1.7317,  3.6147]], requires_grad=True)
例子:
 X值: tensor([[5.2000, 4.1000, 1.5000, 0.1000]])
实际y tensor([[1., 0., 0.]])
预测y tensor([[9.9853e-01, 1.4738e-03, 8.8739e-14]], grad_fn=<DivBackward0>)

进程已结束,退出代码为 0

你们可以改一下批量大小,建议改为2的幂次,最好不要大于64,能加快训练速度(虽然本来也不慢)。

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要导入必要的库和数据集: ```python import numpy as np from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target ``` 接着,我们将数据集分为训练集和测试集: ```python from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 然后,我们需要对数据进行预处理。首先,我们需要对特征进行归一化处理: ```python from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) ``` 接下来,我们需要对标签进行one-hot编码: ```python def one_hot(y): n_classes = len(np.unique(y)) return np.eye(n_classes)[y] y_train = one_hot(y_train) y_test = one_hot(y_test) ``` 现在,我们可以实现softmax回归算法。首先,我们需要定义一个softmax函数: ```python def softmax(z): e = np.exp(z - np.max(z, axis=1, keepdims=True)) return e / np.sum(e, axis=1, keepdims=True) ``` 然后,我们定义一个损失函数: ```python def cross_entropy_loss(y_true, y_pred): return -np.mean(np.sum(y_true * np.log(y_pred), axis=1)) ``` 接下来,我们可以开始训练模型了。我们需要定义一个函数来计算梯度: ```python def grad(X, y_true, y_pred): m = X.shape[0] return 1/m * np.dot(X.T, (y_pred - y_true)) ``` 然后,我们需要定义一个函数来进行模型训练: ```python def fit(X, y, lr=0.1, n_epochs=1000): n_features = X.shape[1] n_classes = y.shape[1] W = np.random.randn(n_features, n_classes) b = np.zeros(n_classes) losses = [] for epoch in range(n_epochs): z = np.dot(X, W) + b y_pred = softmax(z) loss = cross_entropy_loss(y, y_pred) losses.append(loss) grad_W = grad(X, y, y_pred) grad_b = np.mean(y_pred - y, axis=0) W -= lr * grad_W b -= lr * grad_b if (epoch+1) % 100 == 0: print(f"Epoch {epoch+1}/{n_epochs}, loss={loss:.4f}") return W, b, losses ``` 现在,我们可以对模型进行训练: ```python W, b, losses = fit(X_train, y_train) ``` 最后,我们可以使用训练好的模型对测试集进行预测,并计算准确率: ```python def predict(X, W, b): z = np.dot(X, W) + b y_pred = softmax(z) return np.argmax(y_pred, axis=1) y_pred = predict(X_test, W, b) accuracy = np.mean(y_pred == np.argmax(y_test, axis=1)) print(f"Accuracy: {accuracy:.2f}") ``` 完整代码如下: ```python import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler def softmax(z): e = np.exp(z - np.max(z, axis=1, keepdims=True)) return e / np.sum(e, axis=1, keepdims=True) def cross_entropy_loss(y_true, y_pred): return -np.mean(np.sum(y_true * np.log(y_pred), axis=1)) def grad(X, y_true, y_pred): m = X.shape[0] return 1/m * np.dot(X.T, (y_pred - y_true)) def fit(X, y, lr=0.1, n_epochs=1000): n_features = X.shape[1] n_classes = y.shape[1] W = np.random.randn(n_features, n_classes) b = np.zeros(n_classes) losses = [] for epoch in range(n_epochs): z = np.dot(X, W) + b y_pred = softmax(z) loss = cross_entropy_loss(y, y_pred) losses.append(loss) grad_W = grad(X, y, y_pred) grad_b = np.mean(y_pred - y, axis=0) W -= lr * grad_W b -= lr * grad_b if (epoch+1) % 100 == 0: print(f"Epoch {epoch+1}/{n_epochs}, loss={loss:.4f}") return W, b, losses def predict(X, W, b): z = np.dot(X, W) + b y_pred = softmax(z) return np.argmax(y_pred, axis=1) iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) def one_hot(y): n_classes = len(np.unique(y)) return np.eye(n_classes)[y] y_train = one_hot(y_train) y_test = one_hot(y_test) W, b, losses = fit(X_train, y_train) y_pred = predict(X_test, W, b) accuracy = np.mean(y_pred == np.argmax(y_test, axis=1)) print(f"Accuracy: {accuracy:.2f}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值