深度学习实验:Softmax实现手写数字识别_案例1 softmax实现手写数字识别(1)

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

        # display epoch valiation info
        print('Epoch [{}]\t Average validation loss {:.4f}\t Average validation accuracy {:.4f}\n'.format(
            epoch, avg_val_loss, avg_val_acc))

    return epoch_train_loss, epoch_train_acc

def validate(self):
    logits_set, labels_set = [], []
    for images, labels in self.val_loader:
        logits = self.model.forward(images)
        logits_set.append(logits)
        labels_set.append(labels)

    logits = np.concatenate(logits_set)
    labels = np.concatenate(labels_set)
    loss, acc = self.criterion.forward(logits, labels)
    return loss, acc

def test(self):
    logits_set, labels_set = [], []
    for images, labels in self.test_loader:
        logits = self.model.forward(images)
        logits_set.append(logits)
        labels_set.append(labels)

    logits = np.concatenate(logits_set)
    labels = np.concatenate(labels_set)
    loss, acc = self.criterion.forward(logits, labels)
    return loss, acc

if name == ‘main’:
# You can modify the hyerparameters by yourself.
relu_cfg = {
‘data_root’: ‘data’,
‘max_epoch’: 10,
‘batch_size’: 100,
‘learning_rate’: 0.1,
‘momentum’: 0.9,
‘display_freq’: 50,
‘activation_function’: ‘relu’,
}

runner = Solver(relu_cfg)
relu_loss, relu_acc = runner.train()

test_loss, test_acc = runner.test()
print('Final test accuracy {:.4f}\n'.format(test_acc))

# You can modify the hyerparameters by yourself.
sigmoid_cfg = {
    'data_root': 'data',
    'max_epoch': 10,
    'batch_size': 100,
    'learning_rate': 0.1,
    'momentum': 0.9,
    'display_freq': 50,
    'activation_function': 'sigmoid',
}

runner = Solver(sigmoid_cfg)
sigmoid_loss, sigmoid_acc = runner.train()

test_loss, test_acc = runner.test()
print('Final test accuracy {:.4f}\n'.format(test_acc))

plot_loss_and_acc({
    "relu": [relu_loss, relu_acc],
    "sigmoid": [sigmoid_loss, sigmoid_acc],
})

dataloader.py



import os
import struct
import numpy as np

class Dataset(object):

def __init__(self, data_root, mode='train', num_classes=10):
    assert mode in ['train', 'val', 'test']

    # load images and labels
    kind = {'train': 'train', 'val': 'train', 'test': 't10k'}[mode]
    labels_path = os.path.join(data_root, '{}-labels-idx1-ubyte'.format(kind))
    images_path = os.path.join(data_root, '{}-images-idx3-ubyte'.format(kind))

    with open(labels_path, 'rb') as lbpath:
        magic, n = struct.unpack('>II', lbpath.read(8))
        labels = np.fromfile(lbpath, dtype=np.uint8)

    with open(images_path, 'rb') as imgpath:
        magic, num, rows, cols = struct.unpack('>IIII', imgpath.read(16))
        images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784)

    if mode == 'train':
        # training images and labels
        self.images = images[:55000]  # shape: (55000, 784)
        self.labels = labels[:55000]  # shape: (55000,)

    elif mode == 'val':
        # validation images and labels
        self.images = images[55000:]  # shape: (5000, 784)
        self.labels = labels[55000:]  # shape: (5000, )

    else:
        # test data
        self.images = images  # shape: (10000, 784)
        self.labels = labels  # shape: (10000, )

    self.num_classes = 10

def __len__(self):
    return len(self.images)

def __getitem__(self, idx):
    image = self.images[idx]
    label = self.labels[idx]

    # Normalize from [0, 255.] to [0., 1.0], and then subtract by the mean value
    image = image / 255.0
    image = image - np.mean(image)

    return image, label

class IterationBatchSampler(object):

def __init__(self, dataset, max_epoch, batch_size=2, shuffle=True):
    self.dataset = dataset
    self.batch_size = batch_size
    self.shuffle = shuffle

def prepare_epoch_indices(self):
    indices = np.arange(len(self.dataset))

    if self.shuffle:
        np.random.shuffle(indices)

    num_iteration = len(indices) // self.batch_size + int(len(indices) % self.batch_size)
    self.batch_indices = np.split(indices, num_iteration)

def __iter__(self):
    return iter(self.batch_indices)

def __len__(self):
    return len(self.batch_indices)

class Dataloader(object):

def __init__(self, dataset, sampler):
    self.dataset = dataset
    self.sampler = sampler

def __iter__(self):
    self.sampler.prepare_epoch_indices()

    for batch_indices in self.sampler:
        batch_images = []
        batch_labels = []
        for idx in batch_indices:
            img, label = self.dataset[idx]
            batch_images.append(img)
            batch_labels.append(label)

        batch_images = np.stack(batch_images)
        batch_labels = np.stack(batch_labels)

        yield batch_images, batch_labels

def __len__(self):
    return len(self.sampler)

def build_dataloader(data_root, max_epoch, batch_size, shuffle=False, mode=‘train’):
dataset = Dataset(data_root, mode)
sampler = IterationBatchSampler(dataset, max_epoch, batch_size, shuffle)
data_lodaer = Dataloader(dataset, sampler)
return data_lodaer


loss.py



import numpy as np

a small number to prevent dividing by zero, maybe useful for you

EPS = 1e-11

class SoftmaxCrossEntropyLoss(object):

def forward(self, logits, labels):
    """
      Inputs: (minibatch)
      - logits: forward results from the last FCLayer, shape (batch_size, 10)
      - labels: the ground truth label, shape (batch_size, )
    """

    ############################################################################
    # TODO: Put your code here
    # Calculate the average accuracy and loss over the minibatch
    # Return the loss and acc, which will be used in solver.py
    # Hint: Maybe you need to save some arrays for backward

    self.one_hot_labels = np.zeros_like(logits)
    self.one_hot_labels[np.arange(len(logits)), labels] = 1

    self.prob = np.exp(logits) / (EPS + np.exp(logits).sum(axis=1, keepdims=True))

    # calculate the accuracy
    preds = np.argmax(self.prob, axis=1) # self.prob, not logits.
    acc = np.mean(preds == labels)

    # calculate the loss
    loss = np.sum(-self.one_hot_labels * np.log(self.prob + EPS), axis=1)
    loss = np.mean(loss)
    ############################################################################

    return loss, acc

def backward(self):

    ############################################################################
    # TODO: Put your code here
    # Calculate and return the gradient (have the same shape as logits)

    return self.prob - self.one_hot_labels
    ############################################################################

network.py



class Network(object):
def init(self):
self.layerList = []
self.numLayer = 0

def add(self, layer):
    self.numLayer += 1
    self.layerList.append(layer)

def forward(self, x):
    # forward layer by layer
    for i in range(self.numLayer):
        x = self.layerList[i].forward(x)
    return x

def backward(self, delta):
    # backward layer by layer
    for i in reversed(range(self.numLayer)): # reversed
        delta = self.layerList[i].backward(delta)

optimizer.py



import numpy as np

class SGD(object):
def init(self, model, learning_rate, momentum=0.0):
self.model = model
self.learning_rate = learning_rate
self.momentum = momentum

def step(self):
    """One backpropagation step, update weights layer by layer"""

    layers = self.model.layerList
    for layer in layers:
        if layer.trainable:

            ############################################################################
            # TODO: Put your code here
            # Calculate diff_W and diff_b using layer.grad_W and layer.grad_b.
            # You need to add momentum to this.

            # Weight update with momentum
            if not hasattr(layer, 'diff_W'):
                layer.diff_W = 0.0

            layer.diff_W = layer.grad_W + self.momentum * layer.diff_W
            layer.diff_b = layer.grad_b

            layer.W += -self.learning_rate * layer.diff_W
            layer.b += -self.learning_rate * layer.diff_b

            # # Weight update without momentum
            # layer.W += -self.learning_rate * layer.grad_W
            # layer.b += -self.learning_rate * layer.grad_b

img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化资料的朋友,可以戳这里获取

中…(img-jPZjEJqC-1715827975084)]
[外链图片转存中…(img-PddY2Ei5-1715827975084)]
[外链图片转存中…(img-CLgADxQR-1715827975084)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化资料的朋友,可以戳这里获取

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用Python实现手写数字识别softmax代码: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # 加载手写数字数据集 digits = load_digits() X, y = digits.data, digits.target # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # 定义softmax函数 def softmax(z): return np.exp(z) / np.sum(np.exp(z), axis=1, keepdims=True) # 定义交叉熵损失函数 def cross_entropy_loss(y_pred, y_true): m = y_pred.shape[0] p = softmax(y_pred) log_likelihood = -np.log(p[range(m), y_true]) loss = np.sum(log_likelihood) / m return loss # 定义softmax回归模型 class SoftmaxRegression: def __init__(self, n_features, n_classes, learning_rate=0.1): self.W = np.zeros((n_features, n_classes)) self.b = np.zeros(n_classes) self.learning_rate = learning_rate def fit(self, X, y, n_epochs=1000): m = X.shape[0] for epoch in range(n_epochs): # 前向传播 z = np.dot(X, self.W) + self.b y_pred = softmax(z) # 计算损失函数 loss = cross_entropy_loss(y_pred, y) # 反向传播 dz = y_pred - np.eye(self.W.shape[1])[y] dW = np.dot(X.T, dz) db = np.sum(dz, axis=0) # 更新参数 self.W -= self.learning_rate * dW self.b -= self.learning_rate * db # 打印损失函数 if epoch % 100 == 0: print("Epoch %d loss: %.4f" % (epoch, loss)) def predict(self, X): z = np.dot(X, self.W) + self.b y_pred = softmax(z) return np.argmax(y_pred, axis=1) # 训练softmax回归模型 model = SoftmaxRegression(n_features=X_train.shape[1], n_classes=len(np.unique(y_train))) model.fit(X_train, y_train) # 在测试集上评估模型性能 y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print("Accuracy:", accuracy) # 可视化模型预测结果 fig, axes = plt.subplots(4, 4, figsize=(8, 8)) for i, ax in enumerate(axes.flat): ax.imshow(X_test[i].reshape(8, 8), cmap='binary') ax.set_title("True:%d Pred:%d" % (y_test[i], y_pred[i])) ax.set_xticks([]) ax.set_yticks([]) plt.show() ``` 该代码使用softmax回归模型实现手写数字识别,其中softmax函数用于将模型输出转换为概率分布,交叉熵损失函数用于衡量模型预测结果与真实标签之间的差异。模型训练过程中使用梯度下降算法更新模型参数,最终在测试集上评估模型性能。最后,使用matplotlib库可视化模型预测结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值