part1

线性回归

在这里插入图片描述

Softmax与分类模型

Softmax处理图像分类问题,2*2像素灰度图像。x1、x2、x3、x4为四个像素,标签对应离散值,绘制神经网络图,将输出当作置信度。
为解决输出范围不确定和离散值误差问题,采用softmax operator 来解决问题,其将输出值变为和为1的概率分布。
采用交叉熵来衡量概率分布的差异,最小化交叉熵损失函数等价于最大化训练数据集所有标签类别的联合预测概率。
过程中我们需要获取Fashion-MINIST训练集

mnist_train = torchvision.datasets.FashionMNIST(root='/home/kesci/input/FashionMNIST2065', train=True, download=True, transform=transforms.ToTensor())
mnist_test = torchvision.datasets.FashionMNIST(root='/home/kesci/input/FashionMNIST2065', train=False, download=True, transform=transforms.ToTensor())
X, y = [], []
for i in range(10):
    X.append(mnist_train[i][0]) # 将第i个feature加到X中
    y.append(mnist_train[i][1]) # 将第i个label加到y中
show_fashion_mnist(X, get_fashion_mnist_labels(y))

定义softmax,建立回归模型,定义损失函数、准确率后,可以开始训练模型并进行模型预测

X, y = iter(test_iter).next()

true_labels = d2l.get_fashion_mnist_labels(y.numpy())
pred_labels = d2l.get_fashion_mnist_labels(net(X).argmax(dim=1).numpy())
titles = [true + '\n' + pred for true, pred in zip(true_labels, pred_labels)]

d2l.show_fashion_mnist(X[0:9], titles[0:9])

多层感知机

多层感知机神经网络图包含输入层、隐藏层和输出层。小批量样本:批量大小n、输入个数d、隐藏单元h,X-nd,H-nh。
激活函数用来引入非线性变换
ReLU函数

%matplotlib inline
import torch
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("/home/kesci/input")
import d2lzh1981 as d2l
print(torch.__version__)
def xyplot(x_vals, y_vals, name):
    # d2l.set_figsize(figsize=(5, 2.5))
    plt.plot(x_vals.detach().numpy(), y_vals.detach().numpy())
    plt.xlabel('x')
    plt.ylabel(name + '(x)')
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x.relu()
xyplot(x, y, 'relu')

Sigmoid函数(0-1之间变换)

y = x.sigmoid()
xyplot(x, y, 'sigmoid')

tanh函数(-1-1变换)

y = x.tanh()
xyplot(x, y, 'tanh')

原则上大多数使用ReLu,但其只能在隐藏层中使用。分类器对应sigmoid函数,避免梯度消失避免使用sigmoid和tanh函数。神经网络层数较多时使用ReLu函数。
多层感知机是至少有一个隐藏层的全连接层神经网络,每个隐藏层的输出通过激活函数进行变换。
训练过程

num_epochs, lr = 5, 100.0
# def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
#               params=None, lr=None, optimizer=None):
#     for epoch in range(num_epochs):
#         train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
#         for X, y in train_iter:
#             y_hat = net(X)
#             l = loss(y_hat, y).sum()
#             
#             # 梯度清零
#             if optimizer is not None:
#                 optimizer.zero_grad()
#             elif params is not None and params[0].grad is not None:
#                 for param in params:
#                     param.grad.data.zero_()
#            
#             l.backward()
#             if optimizer is None:
#                 d2l.sgd(params, lr, batch_size)
#             else:
#                 optimizer.step()  # “softmax回归的简洁实现”一节将用到
#             
#             
#             train_l_sum += l.item()
#             train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
#             n += y.shape[0]
#         test_acc = evaluate_accuracy(test_iter, net)
#         print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
#               % (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))

d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)

订正
对于只含有一个隐藏层的多层感知机,输入是256 \times 256256×256的图片,隐藏单元个数是1000,输出类别个数是10,则模型的所有权重矩阵W{i}W i的元素数量之和是
(256*256+10)*1000=6554600

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值