luanshiyinyang / luanshiyinyang.github.io Goto Github PK
View Code? Open in Web Editor NEW个人博客的主题及内容源码仓库(Hexo+Matery),欢迎fork后创建自己的博客网站,注意源码为hexo分支。
个人博客的主题及内容源码仓库(Hexo+Matery),欢迎fork后创建自己的博客网站,注意源码为hexo分支。
https://luanshiyinyang.github.io/python/2018/05/01/OneLineCode/
一行Python代码可以实现什么丧心病狂的功能。
https://luanshiyinyang.github.io/tensorflow2/2019/11/04/RNN/
介绍循环神经网络相关内容以及在TensorFlow2中如何实现RNN模型。
使用Dropout缓解过拟合 本案例将演示在PyTorch中如何使用Dropout缓解过拟合。 介绍 过拟合指的是模型随着训练在训练集上的损失不断降低,但是在某个时间点之后再测试集上的损失却开始飙升,这是因为随着训练模型对训练数据的拟合效果越来越好,从而使得泛化能力降低,这个在深度学习中一般称为过拟合问题。 过拟合有很多解决办法,如添加惩罚项(L1,L2正则化)、EarlyStopping技术等,在神经网络中有一种独有的方式就是Dropout,简单的说就是随机丢弃上一层与当前层的部分神经元连接从而控制拟合过程。 大量实验表明在神经网络中0.5的Dropout有较好的效果。 步骤 生成数据集 生成类似分布数据集,可视化数据分布。 这样的数据集很容易过拟合。 代码 import torch import matplotlib.pyplot as plt %matplotlib inline torch.manual_seed(2019) sample_num = 30 # 样本数据量 # 训练数据 x_train = torch.unsqueeze(torch.linspace(-1, 1, sample_num), dim=1) y_train = x_train + 0.3 * torch.normal(torch.zeros(sample_num, 1), torch.ones(sample_num, 1)) # 指定均值、标准差的正太数据 # 验证数据 x_valid = torch.unsqueeze(torch.linspace(-1, 1, sample_num), dim=1) y_valid = x_valid + 0.3 * torch.normal(torch.zeros(sample_num, 1), torch.ones(sample_num, 1)) # 可视化数据分布 plt.figure(figsize=(12, 8)) plt.scatter(x_train.data.numpy(), y_train.data.numpy(), c='red', label='train') plt.scatter(x_valid.data.numpy(), y_valid.data.numpy(), c='blue', label='valid') plt.legend(loc='best') plt.ylim((-2.5, 2.5)) plt.show() 数据分布 模型构建 搭建一个没有添加Dropout和一个添加Dropout的模型 代码 import torch.nn hidden_num = 100 # 隐层神经元越多越容易过拟合 net_overfitting = torch.nn.Sequential( torch.nn.Linear(1, hidden_num), torch.nn.ReLU(), torch.nn.Linear(hidden_num, hidden_num), torch.nn.ReLU(), torch.nn.Linear(hidden_num, 1), ) net_dropout = torch.nn.Sequential( torch.nn.Linear(1, hidden_num), torch.nn.Dropout(0.5), torch.nn.ReLU(), torch.nn.Linear(hidden_num, hidden_num), torch.nn.Dropout(0.5), torch.nn.ReLU(), torch.nn.Linear(hidden_num, 1), ) 进行训练 代码 import torch.optim import numpy as np optimizer_overfit = torch.optim.Adam(net_overfitting.parameters(), lr=0.01) optimizer_dropout = torch.optim.Adam(net_dropout.parameters(), lr=0.01) loss_func = torch.nn.MSELoss() # 这个回归预测问题mse具有较好效果 losses_train_1, losses_train_2, losses_valid_1, losses_valid_2 = [], [], [], [] # 开始训练 for t in range(500): pred_overfit = net_overfitting(x_train) pred_dropout = net_dropout(x_train) loss_overfit = loss_func(pred_overfit, y_train) loss_dropout = loss_func(pred_dropout, y_train) optimizer_overfit.zero_grad() optimizer_dropout.zero_grad() loss_overfit.backward() loss_dropout.backward() optimizer_overfit.step() optimizer_dropout.step() if t % 10 == 0: # 改成eval模式即测试模式 net_overfitting.eval() net_dropout.eval() # 过拟合网络 losses_train_1.append(loss_overfit.data.numpy()) # 将训练集损失加入列表 pred1 = net_overfitting(x_valid) losses_valid_1.append(loss_func(pred1, y_valid).data.numpy()) # Dropout网络 losses_train_2.append(loss_dropout.data.numpy()) pred2 = net_dropout(x_valid) losses_valid_2.append(loss_func(pred2, y_valid).data.numpy()) # 切换回训练模式 net_overfitting.train() net_dropout.train() plt.figure(figsize=(12, 8)) plt.subplot(2, 1, 1) plt.plot(np.arange(len(losses_train_1)), losses_train_1, label='overfit train loss') plt.plot(np.arange(len(losses_train_1)), losses_valid_1, label='overfit valid loss') plt.subplot(2, 1, 2) plt.plot(np.arange(len(losses_train_1)), losses_train_2, label='dropout train loss') plt.plot(np.arange(len(losses_train_1)), losses_valid_2, label='dropout valid loss') plt.legend(loc='best') plt.show() 演示效果 可以看到,在没有Dropout的网络上,训练集损失迅速降低,验证集损失反而有升高趋势。 但是,添加了dropout,尽管训练效率变低,但是验证集上的效果被控制住,模型更有泛化能力。 补充说明 本案例使用PyTorch框架,如果你是神经网络的新手建议你使用这个框架,上手容易,网络搭建结构化。(参考莫烦教程) 本类框架案例均用代码和效果说话,关于神经网络的原理可以见我的其他博客。 具体完整代码见我的Github,欢迎star或者fork。(开发环境为Jupyter)
https://luanshiyinyang.github.io/tensorflow2/2019/10/03/AdvancedOperation/
介绍TensorFlow2的一些高级API使用。
https://luanshiyinyang.github.io/pytorch/2019/04/27/Dropout/
演示PyTorch中如何使用Dropout防止过拟合。
https://luanshiyinyang.github.io/tensorflow2/2019/10/10/NeuralNetwork/
介绍TensorFlow2的一些高级API使用。
https://luanshiyinyang.github.io/%E5%8D%9A%E5%AE%A2/6666/01/01/README/
关于jekyll的Markdown文件的头部语法说明。
https://luanshiyinyang.github.io/tensorflow2/2019/11/17/AutoEncoder/
介绍自编码器在TensorFlow2中如何实现。
https://luanshiyinyang.github.io/fastai/2019/05/08/MoreAboutModel/
本案例利用mnist手写数据集,详细介绍fastai中模型的生态。
https://luanshiyinyang.github.io/tensorflow2/2019/09/21/Introduction/
介绍TensorFlow2的优劣之处。
模型本地化存储以及批训练 本案例使用简单神经网络显示如何保存模型以及数据批处理。 步骤 生成训练数据集 还是使用回归时生成的数据集 代码 import torch import matplotlib.pyplot as plt %matplotlib inline torch.manual_seed(2019) x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) y = x.pow(2) + 0.2*torch.rand(x.size()) # 绘制散点图显示数据点分布 plt.scatter(x.data.numpy(), y.data.numpy()) plt.show() 看一下训练数据分布 搭建神经网络 代码 import torch.nn as nn class Net(nn.Module): def init(self): super(Net, self).init() self.hidden = nn.Sequential( nn.Linear(1, 10), nn.ReLU(), nn.Linear(10, 1) ) def forward(self, x): return self.hidden(x) 简单训练神经网络 代码 net1 = Net() optimizer = torch.optim.Adam(net1.parameters(), lr=0.001) loss_func = torch.nn.MSELoss() losses = [] for epoch in range(100): pred = net1(x) loss = loss_func(pred, y) losses.append(loss.data.numpy()) optimizer.zero_grad() loss.backward() optimizer.step() plt.plot([i for i in range(100)], losses) plt.show() 保存并提取训练完的模型 代码 pred1 = net1(x[:10]) print("pred1",pred1) torch.save(net1, 'my_model.pkl') net2 = torch.load('my_model.pkl') pred2 = net2(x[:10]) print("pred2", pred2) 演示效果 可以看到,模型的效果是一致的保存是成功的。 保存并提取训练完模型的参数 很多时候,模型保存很费空间,只保存模型参数,下次使用将参数加载进未训练的新模型对象即可。 代码 torch.save(net1.state_dict(), 'params_model.pkl') net3 = Net() net3.load_state_dict(torch.load('params_model.pkl')) print(net1(x[:10]).data.numpy()) print(net3(x[:10]).data.numpy()) 演示效果 可以看到,预测结果依然没有改变。 批量数据训练 代码 from torch.utils.data import Dataset, TensorDataset, DataLoader dataset = TensorDataset(torch.unsqueeze(torch.Tensor(x), dim=1), torch.unsqueeze(torch.Tensor(y), dim=1)) loader = DataLoader( dataset=dataset, batch_size=32, shuffle=True, num_workers=2, ) net = Net() loss_func = nn.MSELoss() optimizer = torch.optim.Adam(net.parameters(), lr=0.001) losses = [] for epoch in range(100): # 每次取出一批数据训练 for step, (batch_x, batch_y) in enumerate(loader): print(batch_x.shape) pred = net(batch_x) loss = loss_func(pred, batch_y) losses.append(loss.data.numpy()) optimizer.zero_grad() loss.backward() optimizer.step() plt.plot([i for i in range(100)], losses) plt.show() 演示效果 可以看到,对于批量提取器,当数据不足以满足一批时会取出剩余的所有数据。 训练效果 图片波动大是因为每一批取出了损失。 补充说明 本案例使用PyTorch框架,如果你是神经网络的新手建议你使用这个框架,上手容易,网络搭建结构化。 本类框架案例均用代码和效果说话,关于神经网络的原理可以见我的其他博客。 具体代码见我的Github,欢迎star或者fork。(开发环境为Jupyter)
https://luanshiyinyang.github.io/tensorflow2/2019/09/30/BasicOperations/
介绍TensorFlow2的一些基础API使用。
https://luanshiyinyang.github.io/2019/04/23/PyTorch-Optimizer/#
神经网络中不同优化器 本案例简单使用未调参的几个不同优化器显示训练结果。 步骤 生成数据集 使用之前的二次分布点数据集。 代码 x = torch.linspace(-1, 1, 1000) # 维度为(1000) x = torch.unsqueeze(x, dim=1) # 维度为(1000, 1) # 从给定序列生成正太数据 y = x.pow(2) + 0.1 * torch.randn(x.size()) plt.scatter(x.numpy(), y.numpy(), lw=0) plt.show() 可视化 定义网络结构 代码 # 定义网络结构 import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class Net(nn.Module): def init(self): super(Net, self).init() self.hidden = torch.nn.Linear(1, 20) self.output = torch.nn.Linear(20, 1) def forward(self, x): x = F.relu(self.hidden(x)) x = self.output(x) return x 构建网络集和优化器集合 代码 nets = [Net(), Net(), Net(), Net()] optimizers = [optim.SGD(nets[0].parameters(), lr=learning_rate), optim.Adam(nets[1].parameters(), lr=learning_rate), optim.RMSprop(nets[2].parameters(), lr=learning_rate, alpha=0.9), optim.Adagrad(nets[3].parameters(), lr=learning_rate), ] loss_func = nn.MSELoss() losses = [[], [], [], []] 训练过程可视化 代码 for epoch in range(epochs): for step, (batch_x, batch_y) in enumerate(loader): for net, optimizer, loss_this in zip(nets, optimizers, losses): output = net(batch_x) loss = loss_func(output, batch_y) optimizer.zero_grad() loss.backward() optimizer.step() loss_this.append(loss.data.numpy()) 可视化 补充说明 本案例使用PyTorch框架,如果你是神经网络的新手建议你使用这个框架,上手容易,网络搭建结构化。 本类框架案例均用代码和效果说话,关于神经网络的原理可以见我的其他博客。 具体完整代码见我的Github,欢迎star或者fork。(开发环境为Jupyter)
https://luanshiyinyang.github.io/pytorch/2019/04/26/Graph/
演示PyTorch中如何使用动态运算图。
https://luanshiyinyang.github.io/fastai/2019/05/10/Training/
讲述如何使用fastai的模型进行训练,具体讲解不同的训练方式及技巧。
https://luanshiyinyang.github.io/2019/04/25/PyTorch-GAN/#
简单搭建GAN 本案例通过一个函数区间让网络进行学习,最终稳定在一个函数区间内。 步骤 优秀作品生成 代码 # 产生32个优秀作品交给discriminator鉴别 temp = np.random.uniform(1, 2, size=BATCH_SIZE)[:, np.newaxis] good_paintings = torch.from_numpy(temp * np.power(POINTS, 2) + (temp-1)).float() 模型构建 代码 # 搭建网络结构 # Generator,主要任务是产生一些随机作品 G = nn.Sequential( nn.Linear(IDEA_NUM, 128), nn.ReLU(), nn.Linear(128, MAX_POINTS), # 利用全连接提取随机特征 ) # Discriminator,主要任务是鉴别作品 D = nn.Sequential( nn.Linear(MAX_POINTS, 128), nn.ReLU(), nn.Linear(128, 1), nn.Sigmoid(), # 映射为概率 ) opt_D = torch.optim.Adam(D.parameters(), lr=LR_D) opt_G = torch.optim.Adam(G.parameters(), lr=LR_G) 训练过程 代码 # 下面是训练的交互过程,使用matplotlib交互模式 %matplotlib qt5 plt.figure(figsize=(12, 8)) plt.ion() for epoch in range(10000): g_ideas = torch.randn(BATCH_SIZE, IDEA_NUM) # 随机产生idea g_paintings = G(g_ideas) # Generator生成作品 # 接着拿优秀作品与G产生的作品给D,让D判断这两批作品是优秀作品的概率 prob0 = D(good_paintings) prob1 = D(g_paintings) # 计算有多少来自优秀作者的作品猜对了,有多少来自G的画猜对了,最大化猜对的次数 # log(D(x)) + log(1-D(G(z))这就是论文提到的,但是torch没有最大化score只有最小化loss,这是一致的 D_loss = - torch.mean(torch.log(prob0) + torch.log(1. - prob1)) G_loss = torch.mean(torch.log(1. - prob1)) # 网络调整 opt_D.zero_grad() D_loss.backward(retain_graph=True) opt_D.step() opt_G.zero_grad() G_loss.backward() opt_G.step() if epoch % 30 == 0: plt.cla() plt.plot(POINTS[0], g_paintings.data.numpy()[0], c='green', lw=3, label='Generated painting',) # 始终显示上下边界 plt.plot(POINTS[0], 2 * np.power(POINTS[0], 2) + 1, c='blue', lw=3, label='above bound') plt.plot(POINTS[0], 1 * np.power(POINTS[0], 2) - 1, c='red', lw=3, label='below bound') plt.text(-0.6, 2.7, 'D accuracy={:.2f}'.format(prob0.data.numpy().mean()), fontdict={'size': 13}) plt.text(-0.6, 2.5, 'D score={:.2f}'.format(-D_loss.data.numpy()), fontdict={'size': 13}) plt.ylim((-3, 3)) plt.legend(loc='upper center', fontsize=10) plt.draw() plt.pause(0.01) plt.ioff() plt.show() 运行结果 可以看到,只要不断训练GAN最终产生符合高分的优秀作品 补充说明 本案例使用PyTorch框架,如果你是神经网络的新手建议你使用这个框架,上手容易,网络搭建结构化。(参考莫烦教程) 本类框架案例均用代码和效果说话,关于神经网络的原理可以见我的其他博客。 具体完整代码见我的Github,欢迎star或者fork。(开发环境为Jupyter)
https://luanshiyinyang.github.io/2019/04/26/PyTorch-%E5%8A%A8%E6%80%81%E8%AE%A1%E7%AE%97%E5%9B%BE/
动态计算图 本案例主要对PyTorch进行一个动态运算的演示。 介绍 由于这部分属于PyTorch的独有内容,TensorFlow没有此类特性,且没有理论介绍,这里简单介绍这个所谓的动态到底是什么。 如果熟悉TensorFlow的使用流程就应该知道,先搭建网络结构(计算图),一旦搭建完成这个运算模式是不能改变的(当然dynamic_rnn是为了配合RNN网络的例外,但是本质上还是静态思维),数据在这个算图中流动,且输入输出的数据维度是固定的。其实很多时候这样就够了,静态图可以保证运算的高效率。 但是总有一些例外如RNN,有时候RNN的time step是不一样的,设置train的时候batch_size也是不一样的。而在TensorFlow中可以使用上面的dynamic_rnn修改batch_size,但是time_step则不方便了,所以这样看来PyTorch确实有优势之处。 步骤 定义RNN结构 这里使用之前利用相差pi/2的三角函数进行预测的例子,在网络内部定义一个动态修改的time step长度。 代码 # 模型结构搭建 class RNN(nn.Module): def init(self): super(RNN, self).init() self.rnn = nn.RNN( input_size=1, hidden_size=32, num_layers=1, batch_first=True, ) self.out = nn.Linear(32, 1) def forward(self, x, h_state): # x维度 (batch, time_step, input_size) # h_state维度 (n_layers, batch, hidden_size) # r_out维度 (batch, time_step, output_size) r_out, h_state = self.rnn(x, h_state) # 动态调整过程(在之前写RNN的时候,time_step是定长的,所以没有这一步) outputs = [] for time_step in range(r_out.size(1)): outputs.append(self.out(r_out[:, time_step, :])) return torch.stack(outputs, dim=1), h_state rnn = RNN() print(rnn) 训练模型 这里修改了模型训练的数据产生方式,使之长度随机。 代码 import torch.optim as optim optimizer = torch.optim.Adam(rnn.parameters(), lr=LR) loss_func = nn.MSELoss() h_state = None %matplotlib qt5 plt.figure(1, figsize=(12, 8)) plt.ion() step = 0 # 这里还是使用sin去预测cos for i in range(EPOCHS): random_steps = np.random.randint(1, 4) # 随机生成time steps start, end = step * np.pi, (step + random_steps) * np.pi # 不同time step step += random_steps steps = np.linspace(start, end, 10 * random_steps, dtype=np.float32) print("this steps is {}".format(len(steps))) x_np = np.sin(steps) y_np = np.cos(steps) x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis]) # 维度(batch_size, time_step, input_size) y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis]) pred, h_state = rnn(x, h_state) h_state = h_state.data loss = loss_func(pred, y) optimizer.zero_grad() loss.backward() optimizer.step() # 真实值预测值对比 plt.plot(steps, y_np, 'r-') plt.plot(steps, pred.data.numpy().flatten(), 'b-') plt.draw() plt.pause(0.05) plt.ioff() plt.show() 运行结果 可以看到,逐渐拟合。 补充说明 本案例使用PyTorch框架,如果你是神经网络的新手建议你使用这个框架,上手容易,网络搭建结构化。(参考莫烦教程) 本类框架案例均用代码和效果说话,关于神经网络的原理可以见我的其他博客。 具体完整代码见我的Github,欢迎star或者fork。(开发环境为Jupyter)
https://luanshiyinyang.github.io/2019/08/28/Jupyter-more/#
Jupyter进阶教程 简介 Jupyter Notebook是一款交互式的笔记本或者代码编辑器,支持几十种编程语言,不过主要还是为以Python和R为首的数据科学使用,其前身是Ipython,关于Jupyter的基本安装和使用不多提及。 本教程主要提及一些Jupyter的进阶技巧,基本的使用及快捷键等在入门教程中已经提及了。 主要介绍常用的shell命令及Jupyter封装的魔法方法,探索外部插件的使用。
https://luanshiyinyang.github.io/pytorch/2019/04/18/Classification/
演示PyTorch中实现分类模型的方法。
https://luanshiyinyang.github.io/2019/04/24/AutoEncoder/
title: PyTorch构建自编码器 date: 2019-04-24 categories: ‘PyTorch’ description: 演示PyTorch中如何构建GAN网络。 tags: - 深度学习 - PyTorch updated: music-id: —
https://luanshiyinyang.github.io/fastai/2019/05/05/Fastai-Start/
Fastai深度学习框架快速入门。
https://luanshiyinyang.github.io/fastai/2019/05/06/Fastai-CNNDemo/
在这个案例中将从手写集开始了解fastai的使用模式。
https://luanshiyinyang.github.io/keras/2019/05/03/Model/
Keras实现模型的存储(落地)与读取(加载)。
https://luanshiyinyang.github.io/tensorflow2/2019/11/02/CNN/
介绍卷积神经网络相关内容以及在TensorFlow2中如何实现CNN模型。
https://luanshiyinyang.github.io/keras/2019/05/04/AutoEncoder/
Keras实现自动编码器(AutoEncoder)。
https://luanshiyinyang.github.io/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/2019/06/01/Colorization/
使用类VGG的卷积神经网络结构进行图片自动着色。
https://luanshiyinyang.github.io/posts/2019-05-11-Fastai-CVData
详细解释Fastai模块中图片数据集的读入、预处理、增广等。
https://luanshiyinyang.github.io/keras/2019/05/02/RNN/
Keras实现RNN进行MNIST分类。
https://luanshiyinyang.github.io/keras/2019/05/01/CNN/
Keras实现CNN进行MNIST分类。
https://luanshiyinyang.github.io/pytorch/2019/04/25/GAN/
演示PyTorch中如何构建GAN网络。
https://luanshiyinyang.github.io/%E5%8D%9A%E5%AE%A2/2019/08/01/README/
关于jekyll的Markdown文件的头部说语法明。
https://luanshiyinyang.github.io/tensorflow2/2019/09/21/Introduction/
介绍TensorFlow2的优劣之处。
https://luanshiyinyang.github.io/tensorflow2/2019/11/24/GAN/
介绍GAN在TensorFlow2中如何实现。
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.