‘nvidia-smi’ 不是内部或外部命令,也不是可运行的程序
参考博客
https://blog.csdn.net/shuiyixin/article/details/99897640
cd C:\Program Files\NVIDIA Corporation\NVSMI
nvidia-smi
cuda9.2只支持driver version396.26以上的 如果不够取升级驱动
pytorch的安装
conda activate pytorch #激活环境 环境名叫pytorch
conda activate pytorch
python
import torch
torch.cuda.is_available()#显示true 说明gpu可以被pytorch使用
04学习法宝(package)
dir 和help可以帮助你看看package里面有什么
创建项目时选择已有的环境 选择基于conda下的pytorch虚拟环境 而不是新建虚拟环境
05 pycharm和jupyter book的对比
这三个运行区域的理解
06加载数据 dataset和dataloader
dataset是从数据海洋中获取数据和其label
dataloader是把想要的数据打包
07dataset代码实战
如何获取图片:opencv获取图片的地址
from PIL import Image
或者 import cv2
将数据集放到pycharm的项目下 并复制图片的路径可以选择绝对还是相对路径 记得在windows下加\做完转义符
在python console中这样方便看img有什么属性
from PIL import Image
img_path='F:\\pythonProject1\\learn_pytorch\\dataset\\val\\ants\\800px-Meat_eater_ant_qeen_excavating_hole.jpg'
img=Image.open(img_path)
img.size
Out[5]: (800, 534)
img.show()#会弹窗展示图片
在python console控制台 通过文件夹获得文件夹下面所有的图片 先获得dir_path文件总路径 再os.listdir(dir_path)获得所有图片的名称
from PIL import Image
img_path='F:\\pythonProject1\\learn_pytorch\\dataset\\val\\ants\\800px-Meat_eater_ant_qeen_excavating_hole.jpg'
img=Image.open(img_path)
img.size
Out[5]: (800, 534)
img.show()
dir_path='dataset/val/ants'
import os
img_path_list=os.listdir(dir_path)#可以获得每张图片的名称
img_path_list[0]
Out[10]: '10308379_1b6c72e180.jpg'
python console
root_dir='dataset/train'
label_dir='ants'
path=os.path.join(root_dir,label_dir)#因为/在不同系统下有不同的含义 所以就根据不同的系统自动把路径用\\连接起来
path
Out[14]: 'dataset/train\\ants'
from torch.utils.data import Dataset
from PIL import Image#使用这个方法读取图片
import os
#self 相当于定义了全局变量
class MyData(Dataset):#继承Dataset类 一般要重写getitem和len函数
def __init__(self,root_dir,label_dir):#初始化 一般定义一些全局变量
self.root_dir=root_dir#相当指定一个全局变量
self.label=label_dir
self.path=os.path.join(self.root_dir,self.label)
self.img_path=os.listdir(self.path)
#读取每个图片
def __getitem__(self,idx):#想获得图片地址 通过索引idx去获取 就要先获取所有图片的一个list 所以通过idx就可以获得相应图片的地址 要用到os库
#img_path='dataset/val/ants/8124241_36b290d372.jpg'
img_name=self.img_path[idx]
img_item_path=os.path.join(self.root_dir,self.label,img_name)#每个图片的地址都是这样root_dir+label_dir+img_name
img=Image.open(img_item_path)
label=self.label_dir#label就是ants 里面放着都是蚂蚁的图片
return img,label
def __len__(self):
return len(self.img_path)
root_dir='dataset/train'
ants_label_dir='ants'
ants_dataset=MyData(root_dir,ants_label_dir)
https://my.oschina.net/u/4392911/blog/4480137
安装pytorch
#因为ants_dataset这个类返回的是两个参数
img,label=ants_dataset[0]
img.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210406110724653.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3N1ZW9uZw==,size_16,color_FFFFFF,t_70)
root_dir='dataset/train'
ants_label_dir='ants'
ants_dataset=MyData(root_dir,ants_label_dir)
#连接两个数据集的好处 有的数据集不足就可以仿造 可以和真实的数据集拼接在一起
bees_label_dir='bees'
bees_dataset=MyData(root_dir,bees_label_dir)
#整个数据集等于两个数据集直接相加
train_dataset=ants_dataset+bees_dataset
https://blog.csdn.net/ljlchrr/article/details/84000908
python在指定文件夹下新建txt
def text_create(name,msg):#创建文件名为name 内容为msg的文件夹
root_dir = 'dataset/train/ants_label/'#记得最后加上/
full_dir=root_dir+name+'.txt'
file=open(full_dir,'w')
file.write(msg)
findimg= re.compile(r"(.*?).jpg", re.S) # re.S让换行符包含在字符中 提取图片标题
for i in range(len(ants_dataset)):
img= re.findall(findimg, ants_dataset.img_path[i])[0]#因为是只有一个元素的列表 所以取第0个即可 如['0013035']
text_create(str(img), 'ants')
07tensorboard的使用1
transform 对图像数据进行统一的转换或者类的转化
SummaryWriter的使用 在pycharm按住ctrl 之后SummaryWriter变蓝色 点击即可
add_scalar用法 :
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
"""Add scalar data to summary. #添加一个标量数据到summary
Args:
tag (string): Data identifier#图标标题
scalar_value (float or string/blobname): Value to save#图标数值 y轴
global_step (int): Global step value to record#训练到多少步的时候 对应的数值是多少 x轴
walltime (float): Optional override default walltime (time.time())
with seconds after epoch of event
Examples::
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter()
x = range(100)
for i in x:
writer.add_scalar('y=2x', i * 2, i)
writer.close()
Expected result:
.. image:: _static/img/tensorboard/add_scalar.png
:scale: 50 %
"""
实例:
from torch.utils.tensorboard import SummaryWriter
writer=SummaryWriter('logs')#初始化实例 将创建的事件文件存在logs文件夹下
#writer.add_image()
for i in range(100):
writer.add_scalar('y=2x',2*i,i)#分别是tag标题 y轴 x轴
#在终端输入tensorboard --logdir=logs --port=6007 打开这个event 可以指定端口号port
writer.close()
当代码改成writer.add_scalar(‘y=2x’,3*i,i) 会在y=2x下面产生如下情形,解决方法:删除logs下的所有event重新执行
08tensorboard的使用2
add_image的使用:
def add_image(self, tag, img_tensor, global_step=None, walltime=None, dataformats='CHW'):
"""Add image data to summary.
Note that this requires the ``pillow`` package.
Args:
tag (string): Data identifier
img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data#注意这个类型是需要torch.Tensor, numpy.array, or string/blobname类型的
global_step (int): Global step value to record
walltime (float): Optional override default walltime (time.time())
seconds after epoch of event
将PIL 转换成numpy类型的image
image_path='dataset/train/ants/0013035.jpg'
from PIL import Image
img=Image.open(image_path)
print(type(img))
<class 'PIL.JpegImagePlugin.JpegImageFile'>
import numpy as np
img_array=np.array(img)
print(type(img_array))
<class 'numpy.ndarray'>
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image
writer=SummaryWriter('logs')#初始化实例 将创建的事件文件存在logs文件夹下
image_path='dataset/train/ants/0013035.jpg'
img_PIL=Image.open(image_path)
img_array=np.array(img_PIL)
#可以从控制台发现shape是512,768,3 是HWC 高度宽度通道
writer.add_image('test',img_array,1,dataformats='HWC')#默认是CHW所以要指定
效果如下
作用是训练的时候可以看给模型提供了哪些数据,或者可以看出每个阶段的训练结果
09transforms的使用
transforms的结构和用法
给定特定格式的图片经过一系列类转换成要的图片
ctrl+p可以看函数需要什么参数
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
#input
img_path='dataset/train/ants/5650366_e22b7e1065.jpg'
img=Image.open(img_path)
writer=SummaryWriter('logs')
#1transforms如何用
tensor_trans=transforms.ToTensor()#创建实例
tensor_img=tensor_trans(img)#PIL变tensor
writer.add_image('Tensor_img',tensor_img)
writer.close()
#2为什么需要tensor这个数据类型
效果
常见的transforms
transforms的compose类 每次经过中心的裁剪 最后再ToTensor
python中__call__()的用法
class Person:
def __call__(self,name):
print('__call__'+'hello'+name)
def hello(self,name):
print('hello'+name)
person= Person()
person('zhangshan')#因为有内置函数call 可以直接加参数 不用调用方法比较方便
person.hello('lisi')
'''
__call__hellozhangshan
hellolisi
'''
totensor的使用
1打开图片 2创建writer写入事件 3创建实例调用totensor 4add_image
Normalize的使用
class Normalize(torch.nn.Module):
"""Normalize a tensor image with mean and standard deviation.
Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n``
channels, this transform will normalize each channel of the input
``torch.*Tensor`` i.e.,
``output[channel] = (input[channel] - mean[channel]) / std[channel]``
.. note::
This transform acts out of place, i.e., it does not mutate the input tensor.
Args:
mean (sequence): Sequence of means for each channel.
std (sequence): Sequence of standard deviations for each channel.
inplace(bool,optional): Bool to make this operation in-place.
"""
def __init__(self, mean, std, inplace=False):
super().__init__()
self.mean = mean
self.std = std
self.inplace = inplace
totensor和normalize的效果
img_path='dataset/train/ants/5650366_e22b7e1065.jpg'
img=Image.open(img_path)
writer=SummaryWriter('logs')
#totensor的使用 1打开图片 2创建writer写入事件 3创建实例调用totensor 4add_image
tensor_trans=transforms.ToTensor()#创建实例
tensor_img=tensor_trans(img)
writer.add_image('Tensor_img',tensor_img)
# Normalize
print(tensor_img[0][0][0])
#output[channel] = (input[channel] - mean[channel]) / std[channel] 所以result=(input-0.5)/0.5
trans_norm=transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])#给出均值和标准差 因为是图片所以有三个通道
img_norm=trans_norm(tensor_img)#参数必须是img的tensor型
print(img_norm[0][0][0])
writer.add_image('Normalize',img_norm)
writer.close()
'''
tensor(0.3804)
tensor(-0.2392)
(0.38-0.5)/0.5 成立
'''
resize的使用
class Resize(torch.nn.Module):
"""Resize the input image to the given size.
The image can be a PIL Image or a torch Tensor, in which case it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
Args:
size (sequence or int): Desired output size. If size is a sequence like
(h, w), output size will be matched to this. If size is an int,
smaller edge of the image will be matched to this number.#如果只给一个数就是只有等比的缩放
i.e, if height > width, then image will be rescaled to
(size * height / width, size).
In torchscript mode padding as single int is not supported, use a tuple or
list of length 1: ``[size, ]``.
interpolation (int, optional): Desired interpolation enum defined by `filters`_.
Default is ``PIL.Image.BILINEAR``. If input is Tensor, only ``PIL.Image.NEAREST``, ``PIL.Image.BILINEAR``
and ``PIL.Image.BICUBIC`` are supported.
"""
#resize
print(img.size)
trans_reszie=transforms.Resize((512,512))
#img PIL ->resize ->img_resize PIL
img_resize=trans_reszie(img)
#img resize PIL ->totensor ->img_resize tensor
img_resize=tensor_trans(img_resize)
writer.add_image('Resize',img_resize,0)
print(img_resize)
compose用法
#randomcrop
trans_random=transforms.Resize((500,1000))#指定hw 裁剪成500*1000
trans_compose_2=transforms.Compose([trans_random,tensor_trans])
for i in range(10):
img_crop=trans_compose_2(img)
writer.add_image('RandomCropHW',img_crop,i)
#随机裁剪0-9张
方法总结
关注官方文档,输入输出类型,关注方法需要什么参数
不知道返回值的时候print/print(type())/debug