学习机器学习——练习训练模型(2)(图像分割细胞图片)

图像分割——细胞图片
基于Pytorch,UNET模型
模型学习来自:(很感谢这么详细的文章)
https://github.com/Jack-Cherish/Deep-Learning
其他网址:
(1)pytorch新手教程
https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html
(2)UNET论文
https://arxiv.org/pdf/1505.04597.pdf
(因为第一次使用云服务器运行,也没有配置环境等,还不是root用户,出现了一些问题,因为原网址写的模型训练等很详细,这里主要记录一下自己遇到的问题和训练过程)

(一)项目背景

在这里插入图片描述

  • 医学图像分割,基于UNET模型,给出细胞结构图,将每个细胞相互分割开。
  • 训练数据:30张果蝇电镜图,分辨率:512*512

(二)模型训练

1.上传数据集

没有通过linux命令上传文件,下载软件FileZillia,通过SSH登录,输入主机、用户名、密码,点击快速连接即可登录,将文件进行拖拽即可上传。FileZillia下载网址:

 https://filezilla-project.org/

软件界面展示:
在这里插入图片描述

2.上传项目代码

和上传数据集一样,通过软件Filezillia将项目文件夹及相关代码上传至对应位置。(之前在github上已经下载好了项目文件,没有用git下载的原因是安装git出现了问题,还没有解决)

项目目录:
在这里插入图片描述

(1)代码1——加载数据(dataset.py)

使用一些数据增强方法,来扩大我们的数据集。


#导入包
import torch
import cv2
import os
import glob
from torch.utils.data import Dataset
import random

class ISBI_Loader(Dataset):
    def __init__(self, data_path):
        # 初始化函数,读取所有data_path下的图片
        self.data_path = data_path
        self.imgs_path = glob.glob(os.path.join(data_path, 'image/*.png'))

    def augment(self, image, flipCode):
        # 使用cv2.flip进行数据增强,filpCode为1水平翻转,0垂直翻转,-1水平+垂直翻转
        flip = cv2.flip(image, flipCode)
        return flip

    def __getitem__(self, index):
        # 根据index读取图片
        image_path = self.imgs_path[index]
        # 根据image_path生成label_path
        label_path = image_path.replace('image', 'label')
        # 读取训练图片和标签图片
        image = cv2.imread(image_path)
        label = cv2.imread(label_path)
        # 将数据转为单通道的图片
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        label = cv2.cvtColor(label, cv2.COLOR_BGR2GRAY)
        image = image.reshape(1, image.shape[0], image.shape[1])
        label = label.reshape(1, label.shape[0], label.shape[1])
        # 处理标签,将像素值为255的改为1
        if label.max() > 1:
            label = label / 255
        # 随机进行数据增强,为2时不做处理
        flipCode = random.choice([-1, 0, 1, 2])
        if flipCode != 2:
            image = self.augment(image, flipCode)
            label = self.augment(label, flipCode)
        return image, label

    def __len__(self):
        # 返回训练集大小
        return len(self.imgs_path)


if __name__ == "__main__":
    isbi_dataset = ISBI_Loader("data/train/")
    print("数据个数:", len(isbi_dataset))
    train_loader = torch.utils.data.DataLoader(dataset=isbi_dataset,
                                               batch_size=2, 
                                               shuffle=True)
    for image, label in train_loader:
        #打印训练集图片的大小
        print(image.shape)

__init__函数是这个类的初始化函数,根据指定的图片路径,读取所有图片数据,存放到self.imgs_path列表中。

__len__函数可以返回数据的多少,这个类实例化后,通过len()函数调用。

__getitem__函数是数据获取函数,在这个函数里你可以写数据怎么读,怎么处理,并且可以一些数据预处理、数据增强都可以在这里进行。我这里的处理很简单,只是将图片读取,并处理成单通道图片。同时,因为 label 的图片像素点是0和255,因此需要除以255,变成0和1。同时,随机进行了数据增强。

augment函数是定义的数据增强函数,怎么处理都行,我这里只是进行了简单的旋转操作。

在这个类中,你不用进行一些打乱数据集的操作,也不用管怎么按照 batchsize 读取数据。因为实例化这个类后,我们可以用 torch.utils.data.DataLoader 方法指定 batchsize 的大小,决定是否打乱数据。

Pytorch 提供给给我们的 DataLoader 很强大,我们甚至可以指定使用多少个进程加载数据,数据是否加载到 CUDA 内存中等高级用法,本文不涉及,就不再展开讲解了。

运行结果:
bug1
在这里插入图片描述
想到了是路径的问题,但是以为是代码的问题,原来是运行所在目录的问题,出现bug运行时所在目录为:**/DL_exercises/cell_segmentation/utils$ python3 dataset.py

解决方法
回到目录:**/DL_exercises/cell_segmentation,然后运行:python3 utils/dataset.py
在这里插入图片描述

(2)代码2——模型各层详细内容(unet_parts.py)

修改网络,使网络的输出尺寸正好等于图片的输入尺寸。
UNet是一个对称的网络结构,左侧为下采样,右侧为上采样。


""" Parts of the U-Net model """
"""https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_parts.py"""

import torch
import torch.nn as nn
import torch.nn.functional as F

class DoubleConv(nn.Module):
    """(convolution => [BN] => ReLU) * 2"""

    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.double_conv = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        return self.double_conv(x)

class Down(nn.Module):
    """Downscaling with maxpool then double conv"""

    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.maxpool_conv = nn.Sequential(
            nn.MaxPool2d(2),
            DoubleConv(in_channels, out_channels)
        )

    def forward(self, x):
        return self.maxpool_conv(x)

class Up(nn.Module):
    """Upscaling then double conv"""

    def __init__(self, in_channels, out_channels, bilinear=True):
        super().__init__()

        # if bilinear, use the normal convolutions to reduce the number of channels
        if bilinear:
            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
        else:
            self.up = nn.ConvTranspose2d(in_channels // 2, in_channels // 2, kernel_size=2, stride=2)

        self.conv = DoubleConv(in_channels, out_channels)

    def forward(self, x1, x2):
        x1 = self.up(x1)
        # input is CHW
        diffY = torch.tensor([x2.size()[2] - x1.size()[2]])
        diffX = torch.tensor([x2.size()[3] - x1.size()[3]])

        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
                        diffY // 2, diffY - diffY // 2])

        x = torch.cat([x2, x1], dim=1)
        return self.conv(x)


class OutConv(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(OutConv, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)

    def forward(self, x):
        return self.conv(x)
(3)代码3——模型结构(unet_model.py)

""" Full assembly of the parts to form the complete network """
"""Refer https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_model.py"""

import torch.nn.functional as F

from .unet_parts import *

class UNet(nn.Module):
    def __init__(self, n_channels, n_classes, bilinear=True):
        super(UNet, self).__init__()
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.bilinear = bilinear

        self.inc = DoubleConv(n_channels, 64)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        self.down4 = Down(512, 512)
        self.up1 = Up(1024, 256, bilinear)
        self.up2 = Up(512, 128, bilinear)
        self.up3 = Up(256, 64, bilinear)
        self.up4 = Up(128, 64, bilinear)
        self.outc = OutConv(64, n_classes)

    def forward(self, x):
        x1 = self.inc(x)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        logits = self.outc(x)
        return logits

if __name__ == '__main__':
    net = UNet(n_channels=3, n_classes=1)
    print(net)

3.模型训练——包括设置损失函数、优化器、指标等(train.py)


from model.unet_model import UNet
from utils.dataset import ISBI_Loader
from torch import optim
import torch.nn as nn
import torch

def train_net(net, device, data_path, epochs=40, batch_size=1, lr=0.00001):
    # 加载训练集
    isbi_dataset = ISBI_Loader(data_path)
    train_loader = torch.utils.data.DataLoader(dataset=isbi_dataset,
                                               batch_size=batch_size, 
                                               shuffle=True)
    # 定义RMSprop算法
    optimizer = optim.RMSprop(net.parameters(), lr=lr, weight_decay=1e-8, momentum=0.9)
    # 定义Loss算法
    criterion = nn.BCEWithLogitsLoss()
    # best_loss统计,初始化为正无穷
    best_loss = float('inf')
    # 训练epochs次
    for epoch in range(epochs):
        # 训练模式
        net.train()
        # 按照batch_size开始训练
        for image, label in train_loader:
            optimizer.zero_grad()
            # 将数据拷贝到device中
            image = image.to(device=device, dtype=torch.float32)
            label = label.to(device=device, dtype=torch.float32)
            # 使用网络参数,输出预测结果
            pred = net(image)
            # 计算loss
            loss = criterion(pred, label)
            print('Loss/train', loss.item())
            # 保存loss值最小的网络参数
            if loss < best_loss:
                best_loss = loss
                torch.save(net.state_dict(), 'best_model.pth')
            # 更新参数
            loss.backward()
            optimizer.step()

if __name__ == "__main__":
    # 选择设备,有cuda用cuda,没有就用cpu
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    # 加载网络,图片单通道1,分类为1。
    net = UNet(n_channels=1, n_classes=1)
    # 将网络拷贝到deivce中
    net.to(device=device)
    # 指定训练集地址,开始训练
    data_path = "data/train/"
    train_net(net, device, data_path)

运行结果:
在这里插入图片描述
在这里插入图片描述

4.模型测试——(predict.py)


import glob
import numpy as np
import torch
import os
import cv2
from model.unet_model import UNet

if __name__ == "__main__":
    # 选择设备,有cuda用cuda,没有就用cpu
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    # 加载网络,图片单通道,分类为1。
    net = UNet(n_channels=1, n_classes=1)
    # 将网络拷贝到deivce中
    net.to(device=device)
    # 加载模型参数
    net.load_state_dict(torch.load('best_model.pth', map_location=device))
    # 测试模式
    net.eval()
    # 读取所有图片路径
    tests_path = glob.glob('data/test/*.png')
    # 遍历所有图片
    for test_path in tests_path:
        # 保存结果地址
        save_res_path = test_path.split('.')[0] + '_res.png'
        # 读取图片
        img = cv2.imread(test_path)
        # 转为灰度图
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        # 转为batch为1,通道为1,大小为512*512的数组
        img = img.reshape(1, 1, img.shape[0], img.shape[1])
        # 转为tensor
        img_tensor = torch.from_numpy(img)
        # 将tensor拷贝到device中,只用cpu就是拷贝到cpu中,用cuda就是拷贝到cuda中。
        img_tensor = img_tensor.to(device=device, dtype=torch.float32)
        # 预测
        pred = net(img_tensor)
        # 提取结果
        pred = np.array(pred.data.cpu()[0])[0]
        # 处理结果
        pred[pred >= 0.5] = 255
        pred[pred < 0.5] = 0
        # 保存图片
        cv2.imwrite(save_res_path, pred)

下载data/test下的文件,看见预测结果
在这里插入图片描述

(三)一些问题

1.一些linux服务器命令

  • 查看压缩包的大小:du -hs 文件名
  • 解压文夹:tar 文件目录
  • 删除文件:
    (1)删除文件夹:rm -rf 文件夹目录,例:rm -rf /usr/python
    (2)删除文件:rm -f 文件目录,例:rm -f /usr/server.xml
  • 修改文件的名字:mv name1 name2
    把当前目录下的name1文件名改成name2,如果该目录下有name2,则覆盖以前的name2文件。
  • 查看服务器cuda版本(前提安装了cuda):cat /usr/local/cuda/version.txt

2.环境下载

在命令后加上-i 镜像地址,会加快速度,例:
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple

解决pip install慢的问题,转载自:https://blog.csdn.net/yang5915/article/details/83175804
新版ubuntu要求使用https源,要注意。

清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/ 中国科技大学
https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/

临时使用:
可以在使用pip的时候加参数-i https://pypi.tuna.tsinghua.edu.cn/simple
例如:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple gevent,这样就会从清华这边的镜像去安装gevent库。

永久修改,一劳永逸:
linux下,修改 ~/.pip/pip.conf (没有就创建一个), 修改 index-url至tuna,内容如下: index-url = https://pypi.tuna.tsinghua.edu.cn/simple

windows下,直接在user目录中创建一个pip目录,如:C:\Users\xx\pip,新建文件pip.ini,内容如下:index-url = https://pypi.tuna.tsinghua.edu.cn/simple

(1)非root用户安装python

转载自:https://blog.csdn.net/JohinieLi/article/details/103710021

1)源码安装python
从官网选择需要的版本下载 https://www.python.org/downloads/ ,这里选用V3.6.8,安装时通过–prefix指定安装路径,安装到自己的home目录下

cd /home/username/
wget https://www.python.org/ftp/python/3.6.8/Python-3.6.8.tgz
tar -xzf Python-3.6.8.tgz
cd Python-3.6.8
#使用隐藏目录,避免误删
mkdir -p /home/username/.python3.6.8/
./configure --prefix="/home/username/.python3.6.8/"
make
make install

2)配置普通用户的环境变量
安装好之后可以配置下环境变量,这样每次执行时就不需要指定python目录了

cd ~
vim ~/.bashrc
 
#新增下面一行,指定python安装目录下的bin路径
export PATH=/home/username/.python3.6.8/bin:$PATH
#使环境变量立即生效
source ~/.bashrc 

配置好之后即可以在当前用户下任意路径中使用python3和pip3
3)如果需要自己安装pip使用以下方法

wget https://bootstrap.pypa.io/get-pip.py
#如果配置了环境变量,可以不用指定python3.exe的路径,直接用pyton3来执行
/home/username/.python3.6.8/bin/python3 get-pip.py

(2)安装pytorch

转载自:https://blog.csdn.net/weixin_43499979/article/details/106671985

1)输入

pip install torch==1.3.1 -f https://download.pytorch.org/whl/torch_stable.html

结果如图所示:
在这里插入图片描述
2)成功调用如图所示
在这里插入图片描述
可能会出现的bug:
在这里插入图片描述
按上面安装解决即可。

(3)安装opencv
安装命令:

pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple

安装结果:
在这里插入图片描述
遇到的bug:
在这里插入图片描述
【原因】猜测是因为下载速度太慢
命令后加上-i 镜像源地址就解决了,如安装结果图示。

3.运行bug

(1)tar解压出错:gzip:stdin:unexpected end of file
在这里插入图片描述

参考博文:https://blog.csdn.net/qq_29350001/article/details/51954801
【错误原因1】:压缩包不完整,解决方法:删除重新下载
【错误原因2】:gzip -d后面跟文件名但是不要跟后缀.gz

(2)SyntaxError: Non-ASCII character ‘\xe5’ in file…
参考博文:https://blog.csdn.net/liuchunming033/article/details/39696679
【原因】
python的默认编码文件是用的ASCLL码,而python文件中使用了中文等非英语字符。(python2会出现这个问题,python3不会)
【解决方法】
在Python源文件的最开始一行,加入一句:
#coding=UTF-8(等号换为”:“也可以)或者 #-- coding:UTF-8 -

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值