机器学习——numpy逻辑回归(手写数字识别)

该博客介绍了如何使用Python和Scikit-Learn库进行手写数字识别,特别是针对1和7的二分类问题。首先,从MNIST数据集中加载并预处理训练和测试数据,然后实现逻辑回归模型进行二分类。接着,展示多分类任务,将所有10个数字转换为one-hot编码,并使用多类别逻辑回归模型进行训练。最后,对模型进行评估并输出测试准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二分类——识别1、7

import numpy as np
import struct
import matplotlib.pyplot as plt
import os
from PIL import Image
from sklearn.utils import gen_batches
np.random.seed(2022)

train_image_file = './案例/05 -手写数字识别/train-images-idx3-ubyte'
train_label_file = './案例/05 -手写数字识别/train-labels-idx1-ubyte'
test_image_file = './案例/05 -手写数字识别/t10k-images-idx3-ubyte'
test_label_file = './案例/05 -手写数字识别/t10k-labels-idx1-ubyte'

def decode_image(path: str) -> np.ndarray:
    with open(path, 'rb') as f:
        magic, num, rows, cols = struct.unpack('>IIII', f.read(16))
        images = np.fromfile(f, dtype=np.uint8).reshape(-1, 784)
        images = np.array(images, dtype = float)
    return images

def decode_label(path: str) -> np.ndarray:
    with open(path, 'rb') as f:
        magic, n = struct.unpack('>II',f.read(8))
        labels = np.fromfile(f, dtype=np.uint8)
        labels = np.array(labels, dtype = float)
    return labels

def load_data() -> tuple:
    train_X = decode_image(train_image_file)
    train_Y = decode_label(train_label_file)
    test_X = decode_image(test_image_file)
    test_Y = decode_label(test_label_file)
    return (train_X, train_Y, test_X, test_Y)


trainX, trainY, testX, testY = load_data() # (60000, 784),(60000,)
# digit1 and digit2 are two digits used for binary classification. You could change their values.
digit1 = 1
digit2 = 7

idx = (trainY == digit1)+(trainY==digit2) # 600000
trainX, trainY = trainX[idx, :], trainY[idx] # (13007, 784),(13007,)
num_train, num_feature = trainX.shape # (13007, 784)
idx = (testY == digit1)+(testY==digit2) # 100000
testX, testY = testX[idx, :], testY[idx] # (2163, 784),(2163,)
num_test = testX.shape[0] # 2163

plt.figure(1, figsize=(20,5))
for i in range(4):
    idx = np.random.choice(range(num_train))
    plt.subplot(int('14'+str(i+1)))
    plt.imshow(trainX[idx,:].reshape((28,28)))
    plt.title('label is %d'%trainY[idx])
plt.show()

print('number of features is %d'%num_feature)
print('number of training samples is %d'%num_train)
print('number of testing samples is %d'%num_test)
trainY[np.where(trainY == digit1)], trainY[ np.where(trainY ==digit2)] = 0,1
testY[np.where(testY == digit1)], testY[np.wher
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非零因子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值