美文网首页神经网络与深度学习
从零单排fastai脚本(1)

从零单排fastai脚本(1)

作者: 深度学习模型优化 | 来源:发表于2019-05-27 06:47 被阅读67次

    1 简单的模拟下线性回归的问题

    用这个来展示线性回归的过程。

    from matplotlib import animation, rc
    rc('animation', html='jshtml')
    
    a = nn.Parameter(tensor(-1.,1))
    
    fig = plt.figure()
    plt.scatter(x[:,0], y, c='orange')
    line, = plt.plot(x[:,0], x@a)
    plt.close()
    
    def animate(i):
        update()
        line.set_ydata(x@a)
        return line,
    
    animation.FuncAnimation(fig, animate, np.arange(0, 100), interval=20)
    

    2 jupyter notebook需要加载的东西

    请不要忘记如下代码

    %reload_ext autoreload
    %autoreload 2
    %matplotlib inline
    
    from fastai import *
    

    3 分割数据的处理

    数据集的名称是CAMVID。
    读取文件使用了open_image的fastai的内置函数。fastai的内置函数还真多,晕死掉!边用边记,然后边记边用吧!

    img_f = fnames[0]
    img = open_image(img_f)
    img.show(figsize=(5,5))
    
    图1 待分割图片

    使用lambda函数从图片文件名找到标签文件名,然后找到标签文件,用open_mask打开。这不太一样哦!一个是open_image、一个是open_mask

    get_y_fn = lambda x : path_lbl/f'{x.stem}_P{x.suffix}'
    
    mask = open_mask(get_y_fn(img_f))
    mask.show(figsize=(5,5), alpha=1)
    
    图2 分割图像标签

    使用np.loadtxt来读取codes.txt文件,这是分割像素的类别。

    codes = np.loadtxt(path/'codes.txt', dtype=str)
    

    类别是:

    array(['Animal', 'Archway', 'Bicyclist', 'Bridge', 'Building', 'Car', 'CartLuggagePram', 'Child', 'Column_Pole',
           'Fence', 'LaneMkgsDriv', 'LaneMkgsNonDriv', 'Misc_Text', 'MotorcycleScooter', 'OtherMoving', 'ParkingBlock',
           'Pedestrian', 'Road', 'RoadShoulder', 'Sidewalk', 'SignSymbol', 'Sky', 'SUVPickupTruck', 'TrafficCone',
           'TrafficLight', 'Train', 'Tree', 'Truck_Bus', 'Tunnel', 'VegetationMisc', 'Void', 'Wall'], dtype='<U17')
    

    下面开始载入数据。首先看下可怜的显存够不够用,如果显存够用的话,那么bs设置大一些,如果显存不够用的话,bs设置小一些。防止ran out of memory。

    size = src_size//2
    
    free = gpu_mem_get_free_no_cache()
    # 皮尺寸的大小依赖于还剩下多小显存
    if free > 8200: bs=8
    else:           bs=4
    print(f"using bs={bs}, have {free}MB of GPU RAM free")
    

    得到data list。

    • 载入数据
    • 分割数据
    • 关联数据和其标签
    src = (SegmentationItemList.from_folder(path_img)
           .split_by_fname_file('../valid.txt')
           .label_from_func(get_y_fn, classes=codes))
    

    由datalist得到databunch

    • 数据增强
    • 转换为databunch,设置批尺寸
    • 归一化(这里建议,如果使用什么数据集预训练,就用什么数据集进行归一化)
    data = (src.transform(get_transforms(), size=size, tfm_y=True)
            .databunch(bs=bs)
            .normalize(imagenet_stats))
    

    检查下训练数据和验证数据。


    图3 训练数据 图4 验证数据

    这里要注意的是要先把Void类去掉,然后才可以计算准确率。

    4 模型

    使用unet来训练数据

    learn = unet_learner(data, models.resnet34, metrics=metrics, wd=wd)
    

    这个wd可以在fit中设置。

    这里使用了技巧,先使用一半尺寸的数据进行训练,然后使用全尺寸的数据进行训练。

    5 训练

    • 先冻结backbone,只训练新加入的层。
    • 然后解冻,按照不同的layer group设置lr。
    • 如果freeze时的学习率是lr,则unfreeze时的学习率为slice(lr/400 or lr/1000, lr/4 or lr/10)

    增加图像尺寸,重复上面的步骤。
    注意:训练epoch,不能太小,也不能太大。这个靠自己的训练经验了。不同的数据集,训练轮数也是不一样的。

    相关文章

      网友评论

        本文标题:从零单排fastai脚本(1)

        本文链接:https://www.haomeiwen.com/subject/uwwnzqtx.html