-
Notifications
You must be signed in to change notification settings - Fork 13
实战案例
- 案例均在anaconda上运行,主要掌握anaconda环境的概念,针对不同的练习建立对应的环境。
- 练习相关访问链接: https://pan.baidu.com/s/1-P6O09QDiRS4Vo98x9-i7w 提取码: wsvt
- 本课程实战练习多采用深度神经网络,需要大量算力,笔记本仅供练习使用,实际训练时请参考下节服务器典型配置。
- 机型1
- 机型 32核 Intel(R) Xeon(R) Gold 6248R CPU
- CPU平台 Intel/CascadelakeR
- 镜像 CentOS 8.3 V100S
- CPU 32核
- 内存 128G
- 系统盘容量 200GB
- GPU V100S*4
- 机型2
功能 | 参数/工具名称 | 版本号 |
---|---|---|
操作系统 | CentOS 7.7 | 内核linux mstation 3.10.0-1062.18.1.el7.x86 64 |
CPU | 12vCPU | - |
内存 | 128GB | - |
GPU 2卡 | NVIDIA GP100GL Quadro | - |
高性能计算需要CUDA、cuDNN的支持。其中
- CUDA(ComputeUnified Device Architecture),是显卡厂商NVIDIA推出的运算平台。 CUDA是一种由NVIDIA推出的通用并行计算架构,该架构使GPU能够解决复杂的计算问题。
- NVIDIA cuDNN是用于深度神经网络的GPU加速库。它强调性能、易用性和低内存开销。NVIDIA cuDNN可以集成到更高级别的机器学习框架中,如谷歌的Tensorflow、加州大学伯克利分校的流行caffe软件。
- CUDA与CUDNN的关系:CUDA是一个工作台,cuDNN是基于CUDA的深度学习GPU加速库,有了它才能在GPU上完成深度学习的计算。要了解操作系统、NVIDIA CUDA、CUDA驱动程序以及NVIDIA cuDNN 8.3.1的支持信息,请查看支持矩阵https://docs.nvidia.com/deeplearning/cudnn/archives/cudnn-831/support-matrix/index.html
- 安装CUDA,访问 https://developer.nvidia.com/cuda-toolkit-archive 选择合适版本
验证CUDA版本,使用
nvidia-smi
确认 NVIDIA Cuda compilernvcc -V
- 安装cuDNN的信息,请查看NVIDA官网 https://docs.nvidia.com/deeplearning/cudnn/archives/cudnn-831/install-guide/index.html
pip install torch
即可
- 前置条件:安装CUDA和cuDNN
- 选择安装命令 访问https://pytorch.org/get-started/locally/ ,选择本机适合的CUDA版本,获得相应的命令行。 如
pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio===0.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html
注意:conda 安装GPU版本torch耗时,可使用清华镜像,参考 https://cloud.tencent.com/developer/article/1837355 包括以下步骤
- 修改.condarc文件,增加清华镜像链接,并将链接中的https修改为http格式,删掉-default。
- 注意使用镜像需要去除代码-c pytorch,即命令行为
conda install pytorch torchvision torchaudio cudatoolkit=11.3
- 验证是否成功
import torch
torch.cuda.is_available()
返回true 为安装CUDA成功
https://speech.ee.ntu.edu.tw/~hylee/ml/ml2021-course-data/hw/Pytorch/Pytorch_Tutorial_1.pdf
- DNN训练过程的步骤
- Tensor的概念:构造、操作符、CPU或者GPU选择、
- 如何计算梯度:反向计算
- Dataset & Dataloader装载数据,读数据和预处理,返回计算样本,数据集的大小
- torch.nn定义神经网络,定义输入,输出,线性层,权重和偏差矩阵,激活函数,损失函数,前向计算,计算输出值
- torch.optim优化神经网络,优化算法
- Neural Network Training神经网络训练
- 读数据
- 将数据集放到Dataloader
- 构建模型并选择CPU或者GPU
- 设置损失函数
- 设置优化器
- iterate n_epochs
- set model to train mode
- iterate through the dataloader
- set gradient to zero
- move data to device (cpu/cuda)
- forward pass (compute output)
- compute loss
- compute gradient (backpropagation)
- update model with optimizer
- Neural Network Validation神经网络验证
- set model to evaluation mode
- iterate through the dataloader
- move data to device (cpu/cuda)
- disable gradient calculation
- forward pass (compute output)
- compute loss
- accumulate loss
- compute averaged loss
- Neural Network Validation神经网络测试
- set model to evaluation mode
- iterate through the dataloader
- move data to device (cpu/cuda)
- disable gradient calculation
- forward pass (compute output)
- collect prediction
- Saving/Loading a Neural Network保存训练好的神经网络模型
https://speech.ee.ntu.edu.tw/~hylee/ml/ml2021-course-data/hw/HW01/HW01.pdf
- 学会使用jupyter notebook运行Python程序
- 熟悉Pytorch
- 掌握使用深度神经网络预测的方法
- 理解深度神经网络的训练方法,如调整超参数、特征选择、正则化
- 熟悉评价指标 RMSE
- L2 regularization 方法1:
torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-2)
'optim_hparas': { # hyper-parameters for the optimizer (depends on which optimizer you are using)
'lr': 0.001, # learning rate of SGD
'momentum': 0.9 # momentum for SGD
'weight_decay': 1e-2 # weight_decay for SGD
},
- L2 regularization 方法2 参考链接:https://github.com/christianversloot/machine-learning-articles/blob/main/how-to-use-l1-l2-and-elastic-net-regularization-with-pytorch.md
def compute_l2_loss(self, w):
return torch.square(w).sum()
def cal_loss(self, pred, target):
''' Calculate loss '''
# TODO: you may implement L1/L2 regularization here
# return self.criterion(pred, target)
loss = self.criterion(pred, target)
# L2 regularization
l2_weight = 1.0
l2_params = []
for param in model.parameters():
l2_params.append(param.view(-1))
l2_reg = l2_weight * model.compute_l2_loss(torch.cat(l2_params))
loss += l2_reg
return loss
- 在当前环境下安装Python依赖包
pip install -r requirements.txt
- 阅读代码注释
- 读数据,做预处理
- 定义网络:初始化模型,定义层数
- 激活函数
- 损失函数
- 前向计算:forward 计算结果 model(x)
- 反向计算:loss.backward()
- 保存模型
- https://github.com/GoogleCloudPlatform/tensorflow-without-a-phd/blob/master/tensorflow-mnist-tutorial/
- https://github.com/pytorch/examples/tree/master/mnist
- 学会用命令行运行Python程序
python main.py
- 熟悉Pytorch
- 掌握使用深度神经网络分类的方法
- 熟悉分类算法的评价指标
pip install tensorflow pip install matplotlib
- 理解Pytorch特点 https://pytorch.org/
- 参考 https://speech.ee.ntu.edu.tw/~hylee/ml/ml2021-course-data/hw/Pytorch/Pytorch_Tutorial_1.pdf
使用jupyter notebook, 逐步运行
-
- 建立程序运行环境
可以用命令行,也可以用可视化界面建立
- 建立程序运行环境
conda create --name envname
-
- 安装依赖
pip install -r requirements.txt
- 安装依赖
-
- 运行程序
python main.py
- 运行程序
- 代码链接:https://github/ga642381/ML2021-Spring/blob/main/HW03/HW03.ipynb
- 练习说明:https://speech.ee.ntu.edu.tw/~hylee/ml/ml2021-course-data/hw/HW03/HW03.pdf
- 参考代码:https://github.com/1am9trash/HUNG_YI_LEE_ML_2021/blob/main/hw/hw3/hw3_code.ipynb
- 参考代码:https://github.com/bettermorn/IAICourse/blob/main/Code/MLSpringHW03/HW03MultiClassGPU.ipynb
- 说明:本代码需在 Python3.7运行,否则会有如下错误 Can't pickle <function at 0x0000002F2175B048>: attribute lookup on main failed
- 依赖文件:https://github.com/bettermorn/IAICourse/blob/main/Code/MLSpringHW03/requirements.txt
- 代码需要调整的地方
- 设置 os.environ['WANDB_CONSOLE'] = 'off' 否则会出现 AssertionError: can only test a child process 参考https://github.com/wandb/client/issues/1994
- 初始化模型之前增加以下代码,以消除以下警告,参考 https://stackoverflow.com/questions/64772335/pytorch-w-parallelnative-cpp206 [W ParallelNative.cpp:206] Warning: Cannot set number of intraop threads after parallel work has started or after set_num_threads call when using native parallel backend (function set_num_threads)
import os
# 装载数据的时候无法使用并行,只能使用单线程
os.environ["OMP_NUM_THREADS"] = "1"
亦可在构造data loader时设置 num_workers =0
- 用卷积神经网络解决图像分类问题。
- 用数据增强来提高性能。
- 了解如何利用未标记的数据以及它的好处。
程序运行环境安装依赖文件修改为 https://github.com/bettermorn/IAICourse/blob/main/Code/MLSpringHW03/requirements.txt
下载实验所需数据 food-11.zip 链接: https://pan.baidu.com/s/1LZsL74UcR1lxkxUHTwzraQ 提取码: ipfm
- 链接: https://github.com/bubbliiiing/faster-rcnn-pytorch
- 参考:https://github.com/chenyuntc/simple-faster-rcnn-pytorch 可使用模型voc_weights_vgg.pth 对应bakcbone = vgg 模型voc_weights_resnet.pth 对应 backbone = resnet60 完成预测
- 熟悉对象检测的原理
- 熟悉对象检测应用的模型
Anaconda3 2021.11 windows version 环境安装依赖文件修改为 https://github.com/bettermorn/IAICourse/blob/main/Code/Ex04/requirements.txt
使用此命令pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple
- 下载好模型和数据文件 参考 https://github.com/bubbliiiing/faster-rcnn-pytorch#%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD
- 下载代码 https://github.com/bubbliiiing/faster-rcnn-pytorch
TSAI库的教程代码 https://github.com/timeseriesAI/tsai/tree/main/tutorial_nbs
代码: https://github.com/timeseriesAI/tsai/tree/main/tutorial_nbs/01_Intro_to_Time_Series_Classification.ipynb
- 导入依赖库
- 准备数据
1.下载数据 了解UCR数据集以及时序数据的特点:样本数、变量数和时序长度 2. 预处理数据集 将Y放到类别集中,预处理数据以提升训练速度。batch_tfms,标准化
- 构造builder
- 定义模型
- 定义learn
- 保存初始模型
- 训练模型
- 寻找合适的学习率
learn.lr_find()
替换learn.lr_find(suggestions=False)
- 训练模型 fit_one_cycle 保存训练后的模型
- 绘制指标曲线
- 预测数据
- 准备测试集,可包括有标签和无标签的
- 使用模型预测
- 输出预测结果 有标签的 test_probas,test_targets,test_preds,accuracy 无标签的:test_probas
https://github.com/timeseriesAI/tsai/tree/main/tutorial_nbs/04_Intro_to_Time_Series_Regression.ipynb
选择dsid = 'Covid3Month' ,其他数据集可能会存在问题
- 导入依赖库
- 准备数据
- 下载数据 了解UCR数据集以及时序数据的特点:样本数、变量数和时序长度
- 预处理数据集 检查训练集和验证集的数据量比例,将Y放到类别集中,预处理数据以提升训练速度。batch_tfms,标准化
- 构造builder
- 定义learn 选择模型,评价指标,寻找合适的学习率
- 查看损失函数
- 训练模型
- 训练模型 fit_one_cycle
- 导出训练后的模型
- 预测数据
- 使用模型预测 无标签数据
- 输出预测结果 probas preds skm.mean_squared_errorMSE
- 选择dsid = 'Covid3Month' ,其他数据集可能会存在问题
- 运行结果,可参考 https://github.com/bettermorn/IAICourse/blob/main/Code/Ex05/10_Time_Series_Classification_and_Regression_with_MiniRocket.ipynb
所有的特征将在第一阶段被计算出来,然后传递给将创建批次的数据加载器。这些特征在整个训练过程中都会保持不变。注意:为了避免在使用离线特征计算时出现泄漏,只用训练样本来拟合MiniRocketFeatures是很重要的。
- 导入依赖库
- 准备数据
- 下载数据 了解UCR数据集以及时序数据的特点:样本数、变量数和时序长度
- 预处理数据集 抽取特征 mrf.fit() ,保存模型,batch_tfms,标准化数据集,装载数据
- 构造模型
- 定义learn 选择模型,评价指标,构建模型 build_ts_model 线性分类头
- 寻找合适的学习率
- 训练模型
- 训练模型 fit_one_cycle 绘制损失曲线
- 导出训练后的模型
- 预测数据
- 构造新的特征new_feat
- 装载模型,传递新特征
- 输出预测结果 probas preds skm.accuracy_score
- 与离线方法类似,在每个minibatch重新计算特征。在这种情况下,不计算固定的特征一次。在线模式比离线扫描方案要慢一些,但提供了更多的灵活性。这里有一些潜在的用途。
- 可以试验不同的缩放技术(无标准化、按样本标准化、正常化等)
- 使用数据增强方法 TSMagScale(), TSWindowWarp()
- 在线计算的另一个用途是实验训练核子和偏置。要做到这一点需要对MRF代码进行修改。
https://github.com/timeseriesAI/tsai/tree/main/tutorial_nbs/07_Time_Series_Classification_with_Transformers.ipynb 注:运行此代码需要较高内存
- 一般来说,与其他时间序列模型相比,当使用相同的数据集时,转化器需要一个较低的lr。使用learn.lr_find()来了解好的lr可能是什么,这很重要。
- 论文作者建议按特征对数据进行标准化。这可以通过在创建TSDataLoaders时加入TSStandardize(by_var=True)作为batch_tfm来实现。
- 当用TST处理长时间序列时,可以使用max_w_len来减少内存大小,从而避免gpu问题。
- 已经尝试过不同类型的位置编码器。根据经验,默认的那个工作得很好。
- 在使用它的一些情况下,可能需要增加 dropout > .1 和/或 fc_dropout > 0,以达到良好的性能。
- 可以尝试使用其他关键的超参数,如d_model、n_layers、n_heads等,但根据经验,没有看到重大的区别。
- 避免过拟合 增加Dropout。在TST中,有2种类型。应用于MHAttention和Feed-Forward层。通常是0-0.3。默认:0.1。应用于全连接头。通常是0-0.8。默认值:0。
- 导入依赖库
- 准备数据
- 下载数据 了解UCR数据集以及时序数据的特点:样本数、变量数和时序长度
- 预处理数据集 预处理数据以提升训练速度。batch_tfms,标准化
- 构造模型
- 定义learn 选择模型TST(dls.vars, dls.c, dls.len),损失函数LabelSmoothingCrossEntropyFlat(), 评价指标RocAuc(), accuracy
- 寻找合适的学习率
- 训练模型
- 训练模型 fit_one_cycle
- 绘制损失曲线、Roc_Auc_Score、accuracy
- 代码中数据集'FaceDetection'如不可用,可选择试验数据集为 'StandWalkJump'
- 对多分类,metrics采用RocAuc(),不能用RocAucBinary(),否则会出现以下错误
ValueError: multi_class must be in (‘ovo‘, ‘ovr‘)
具体解释参考https://github.com/timeseriesAI/tsai/issues/70
- 熟悉时序预测的方法
- 熟悉tsai的使用
- 下载代码 https://github.com/timeseriesAI/tsai
- 用Conda创建 tsai 环境,Python版本3.8.12,并安装运行依赖包
pip install tsai
- 预习 https://github.com/bettermorn/IAICourse/wiki/%E6%97%B6%E9%97%B4%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90%E6%96%B9%E6%B3%95
旅行推销员问题(英语:Travelling salesman problem, TSP):给定一系列城市和每对城市之间的距离,求解访问每一座城市一次并回到起始城市的最短回路。 它是组合优化中的一个NP难问题,在运筹学和理论计算机科学中非常重要。
- 熟悉遗传算法原理
- 在conda新建环境deap,python version:3.9.10
- 下载https://github.com/bettermorn/IAICourse/blob/main/Code/DeapEx/requirements.txt, 在deap环境里运行
pip install -r requirements.txt
,安装依赖库 deap,seaborn,latex,version_information - 在conda终端运行
conda install -c conda-forge ffmpeg
- 安装texlive 参考https://www.tug.org/texlive/acquire-netinstall.html 注:安装时间较长,可能为2小时以上
- 完成以上1-5步后,可以正常运行代码,参考样例为 https://github.com/bettermorn/IAICourse/blob/main/Code/DeapEx/AEC.03%20-%20Solving%20the%20TSP%20with%20GAs.ipynb
- https://github.com/ga642381/ML2021-Spring/blob/main/HW05/HW05.ipynb
- 参考例子:https://github.com/bettermorn/IAICourse/blob/main/Code/MLSpringHW05/HW05cpu.ipynb
- 理解SeqtoSeq
- 理解transformer的原理
- 熟悉训练技巧
- 用子词单元对数据进行标记
- 标签平滑正则化
- 学习率调度
- 反向翻译
- Windows10运行到spm.SentencePieceTrainer.train 时会出现以下问题 RuntimeError: Internal: C:\projects\sentencepiece\src\trainer_interface.cc(406) [!sentences_.empty()] 相关参考 https://github.com/google/sentencepiece/issues/517 待解决!
- 自注意力机制结合了RNN(考虑整个序列)和CNN(平行处理)的优势,学习使用transformer, https://github.com/ga642381/ML2021-Spring/blob/main/HW04/HW04.ipynb
- https://github.com/ga642381/ML2021-Spring/blob/main/HW06/HW06.ipynb
- https://github.com/bettermorn/IAICourse/tree/main/Code/GAN
- 理解GAN模型的原理
- Tips from Soumith https://github.com/soumith/ganhacks
- Tips in DCGAN: Guideline for network architecture design for image generation https://arxiv.org/abs/1511.06434
- Improved techniques for training GANs: https://arxiv.org/abs/1606.03498
- Tips from BigGAN:: https://arxiv.org/abs/1809.11096
- 生成器:ConvTranspose + BatchNorm + ReLU
- 鉴别器:Conv+BatchNorm+LeakyReLU
- 移除判别器中的最后一个sigmoid层。
- 计算损失时不要取对数。
- 将判别器的权重剪切为常数。
- 使用RMSProp或SGD作为优化器。
- paper:https://arxiv.org/pdf/1701.07875.pdf
- code: https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/wgan/wgan.py
- 使用梯度惩罚而不是权重剪裁。
- 使用Adam而不是RMSProp作为优化器。
- paper:https://arxiv.org/abs/1704.00028
- code:https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/wgan_gp/wgan_gp.py
- 鉴别器: perform spectral normalization on the weights of each layer.
- code: https://github.com/pfnet-research/sngan_projection
- 输入:段落+问题
- 输出:答案(文中的文字)
- 理解预训练模型
- 理解Bert模型的原理
- 调优Bert Chinese预训练模型
- 调整超参数 两个窗口起始位置之间的距离,doc_stride,切成小的window
- 提高预处理效果:阻止模型在训练期间学习不正确的内容,例如答案不是总在窗口的中间。QA_Dataset(Dataset) def getitem(self, idx): 考虑找位置的机率
- 提高后处理效果:evaluate 方法中,解决 预测的结束位置标号< 预测的开始位置
- 关键字附近根据部分查看
- 理解训练技巧
- 应用线性学习衰减 https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate
- Automatic mixed precision:设置为 FP16
- Gradient accumulation:参考https://kozodoi.me/python/deep%20learning/pytorch/tutorial/2021/02/19/gradient-accumulation.html
- Ensemble
计算机视觉中的无监督异常检测。机器学习模型是否能够告诉测试图像与训练图像属于同一类别(分布)
- 理解无监督学习在计算机视觉中的应用
- 理解auto-encoder原理
- 什么时候停止训练?训练应该在mse损失收敛时停止
- 在推理过程中,我们计算输入图像和重建图像之间的重建误差。
- 重构误差将被称为异常性(异常分数)。
- 一个图像的异常性可以作为衡量它的分布在训练期间未被发现的可能性的指标
- 使用异常度作为预测值。
- 熟悉无监督学习的评估指标 ROC_AUC score
- 选择autoencoder
- 简单的:FCN autoencoder
- 中等的:CNN autoencoder,Try smaller models (less layers),Smaller batch size
- 强的:Add BatchNorm,Train for longer
- 更强的:Add an extra classifier,Sample random noises as anomaly images, Or one-classification (OCC) with GANs: OCGAN https://arxiv.org/pdf/1903.08550.pdf, End-to-end OCC https://ieeexplore.ieee.org/document/9059022,paper pool for Anomaly Detection, https://github.com/hoya012/awesome-anomaly-detection#anomaly-classification-target
- 训练技巧
- 将图形像素转换为较小的数字,避免gradient炸裂。
- https://github.com/ga642381/ML2021-Spring/blob/main/HW12/HW12_ZH.ipynb
- SARSA: https://github.com/YutaroOgawa/Deep-Reinforcement-Learning-Book/blob/master/program/2_5_Sarsa.ipynb
- Q-learning: https://github.com/YutaroOgawa/Deep-Reinforcement-Learning-Book/blob/master/program/2_6_Qlearning.ipynb
- Qlearning_CartPole.ipynb: https://github.com/YutaroOgawa/Deep-Reinforcement-Learning-Book/blob/master/program/3_4_Qlearning_CartPole.ipynb
- DQN:https://github.com/YutaroOgawa/Deep-Reinforcement-Learning-Book/blob/master/program/5_3and5_4_DQN.ipynb
- A2C:https://github.com/YutaroOgawa/Deep-Reinforcement-Learning-Book/blob/master/program/6_5_A2C_Advanced_ActorCritic.ipynb
- 理解强化学习原理
- 熟悉OpenAI的gym
- 定义Observation/State,Action,Reward
- 设计Agent(learn和sample)和Network
- 使用以下方法训练Agent
- 策略型Policy Gradient:使Actor获得较好的参数
- 动作价值型:策略依赖型SARSA,动作价值函数Q的更新依赖于求取at+1的策略,学得的行为价值方程直接逼近最优行为价值,与行为策略有关;
- 动作价值型:策略关闭型Q-learning,动作价值函数Q的更新不依赖于动作的决定方法,学得的行为价值方程直接逼近最优行为价值,与行为策略无关;
- DQN:用神经网络表示动作价值函数Q;
- A2C:用神经网络表示动作价值函数Q,并且用神经网络构建Actor和Critic.因为总奖励本身可以表示为状态的价值加上动作的优势值:Q(s,a)=V(s)+A(s,a)。需要Advantage学习的存储类。
- 理解构建知识图谱的流程和原理
- 理解知识图谱所用相关人工智能技术