- PyTorch
- 安装
- 使用
- 二分类
- 基础
- Python
- 三方库
- numpy: 科学计算
- PyTorch: 深度学习
- torchvision: PyTorch的模型库
- transforms
- transformers: 自然语言处理库(TensorFlow2,PyTorch)
- matplotlib: 作图
- shutil: 操作文件,os库的补充
- sklearn: 机器学习
- tqdm: 进度条
- 官方库
- argparse: 参数解析
- json: json
- glob: 文件通配
- os: 文件,路径 操作
- 其它
PyTorch: Python的一个深度学习框架,不多介绍
安装-
cpu: pip install pytorch
-
gpu: pip3 install torch==1.8.2+cu111 torchvision==0.9.2+cu111 torchaudio===0.8.2 -f https://download.pytorch.org/whl/lts/1.8/torch_lts.html
-
conda: conda install pytorch torchvision cudatoolkit=10.1 -c pytorch
-
直接pip install torch==1.8.2+cu111不行的话,可以考虑[下载whl,pip install xxx.whl]
- torch/whl/官方
- torch/whl/清华镜像
- 区别:linux_x86_64,win_amd64
-
查看 [NVIDIA_GPU, CUDA]: nvidia-smi
-
版本对应: torch,torchvision
使用torch==1.8.2+cu111的cu111是 这个torch的cuda版本(必须<本机cuda版本)
当然在 .py / .ipynb 使用
# 导入 import torch
type( ) #返回;类型 isinstance(实例,类型) #实例是不是指定类型 torvh gather Pytorch 类型:Tensor IntTensor FloatTensor #默认类型 DoubleTensor 实例方法 size() #若有参数, 返回相应维度的大小 shape #返回以为的储存维度大小的,给下标可以看到对应维度的大小 type() Size( ) from_numpy( ) # 里边给多个参数,每个参数分别是各个维度的大小(参数的数量就是维度数量) tensor( ) #直接给要的张量 Tensor ...Tensor rand( ) #随机值, 单个值∈[0,1] rand_like() #随机值, 单个值∈N(0,1) ones( ) #全1 # one_like( a) zeros( ) #全0 eye( 大小) #单位矩阵 empty( ) randint( 最小值, 最大值, shape) #随机值, 单个值∈[最小值,最大值) normal( 均值张量 ,方差张量) #自定义两个同shape矩阵, 前一个矩阵为均值, 后一个矩阵为方差 full( shape, 值) # range( 起始值, 边界值[, 步长]) linspace( 起始值, 边界值, 步数) #数值平均分配 logspace( 起始值, 边界值, 步数) #↑,作为指数 randperm( ) # 切片二分类
# 模型(网络)
model = nn.Sequential(
nn.Linear(105,30),
nn.ReLU(),
nn.Linear(30,10),
nn.ReLU(),
nn.Linear(10,2),
nn.ReLU(),
nn.Softmax(),
)
# 训练一个epoch
def train(X,Y,model,batch_size,loss,optimizer,loss_s=[],accuracy_s=[]):
# index_True=np.where(Y==True)
# index_False=np.where(Y==False)
# np.random.shuffle(index_False)
# index_train=np.concatenate([index_True,index_False[:2*len(index_True)]],axis=1 )
# X_batch = X[index_train]
# Y_batch = Y[index_train]
# 随机打乱
index_s = np.arange(0,X.shape[0])
np.random.shuffle(index_s)
X = X[index_s]
Y = Y[index_s]
# 计算批次
batch_num = int(X.shape[0]/batch_size)
for step in range(batch_num):
X_batch=X[step*batch_size:(step+1)*batch_size]
Y_batch=Y[step*batch_size:(step+1)*batch_size]
# 计算预测值
Y_hat = model(X_batch)
# 计算loss
l = loss(Y_hat,Y_batch.reshape(-1)).sum()
# 梯度置为0
optimizer.zero_grad()
# 反向传播
l.backward()
# 梯度下降
optimizer.step()
# 更新loss
loss_s+=[ float(l) ]
# 更新accuracy
accuracy = (Y_hat.argmax(axis=1)==Y_batch.reshape(-1)).sum()/Y_batch.shape[0]
accuracy_s+=[ float(accuracy) ]
# 保存模型
if accuracy>0.93:
curr_time = datetime.datetime.now()
time_str = curr_time.strftime("%Y_%m_%d_%H_%M_%S")
torch.save(model.state_dict(), f'./9_output/model_{time_str}_'+str(int(accuracy*1000))+'.pth')
return (loss_s,accuracy_s)
# 优化器,loss函数
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
loss = nn.CrossEntropyLoss()
# 保存 loss,accuracy
loss_s,accuracy_s=[],[]
epoch_num = 1000
# 训练epochs
for i in range(epoch_num):
loss_s,accuracy_s = train(X,Y,model,1000,loss,optimizer,loss_s,accuracy_s)
# 模型保存,文件夹/model_时间_精度.pth
curr_time = datetime.datetime.now()
time_str = curr_time.strftime(r'%Y_%m_%d_%H_%M_%S_%f') # 精确到毫秒
model_path = f'./9_output/model_{time_str}_'+str(int(accuracy*1000))+'.pth'
torch.save(model.state_dict(), model_path) #, _use_new_zipfile_serialization=False
# 模型载入
model_param = torch.load(model_path)
model.load_state_dict(model_param)
基础
import numpy as np import torch # 定义 解释时使用的对象 a_list = [[0,1,2],[3,4,5]] # python对象 list,shape可以不同 a_np = np.array(a) # numpy对象 a_torch = torch.from_numpy(a_np) # torch对象 b = a_list objs = [0,1,2,3,4,5] # 迭代器(任意对象) X,Y # 类型:np/torch,len(shape)>=1Python
`# encoding: utf-8`
# py文件第一行,代表编码
# list.append: 数组拼接
a = [1,2]
b = [3,4]
c = a + b # c=[1,2,3,4]
a += b # a=[1,2,3,4]
c = a.append(b) # 显式调用
# len: 获取迭代器的长度
len(a_list) # 2,因为a_list是二维数组,第1位是2
# list|int|float 等: 类型转换。list可以把所有迭代器转为数组
list(range(5)) # [0,1,2,3,4] ,看下面的range
# range(<若干参数↓>): 获得 迭代器(数),以下等价
for i in range(20):
print(i)
for i in range(0,20):
print(i)
for i in range(0,20,1):
print(i)
# zip(<可变参数>): 压缩
a = a_list = [0,1,2,3,4,5]
b = b_list =[10,11,12,13,14,15]
for i,j in zip(a,b):
print(a,b)
for (i,j) in zip(a,b):
print(a,b)
# zip(*): 解压
(a2,b2)=zip(*zip(a,b))
# enumerate(<迭代器>): 带索引迭代
for i,obj in enumerate(objs):
print(i,obj)
# any
# all
# min
# max
# string r f
r'./data/0'
f'{dir}/{file}'
- string格式化
- .cpython-38-x86_64-linux-gnu.so
- .so的文件名 需要与版本匹配,查看该python接受 哪些后缀的文件,需使用python语言执行命令(import importlib.machinery ; print(importlib.machinery.all_suffixes()))
import numpy as np # np +-*/&| ** c = a+b # 同位置相加(shape不变,其它都差不多) # np.shape: 获得对象的shape形状 a_np.shape() # (2,3) # np.max: 返回同axis的最大值(shape的其他位置相同),原来的shape(axis)会消失,a_max=[2,5] # - 归一化时:X_max=np.max(X),X_min=np.min,X=(X-X_min)/(X_max-X_min) a_max = np.max(a.axis=1) # np.min: 返回同axis的最小值,和上面的相反,不解释 a_min = np.min(a.axis=1) # np.argmax: 返回同axis的最大值的下标,a_argmax=[2,2] a_argmax = np.argmax(a,axis=1) # np.sum a_sum = np.sum(a,axis=1) # 返回同axis的合 # np.all: np.& # np.any: np.| # np.where # - 返回 同一索引的下标的数组 的元组,比如满足条件的点为[(0,1),(2,3),(4,5)],则会返回([0,2,4],[1,3,5]) a_1 = np.where(a>3) # - a_2.shape==a.shape。若 a>3==True,则赋值第二个参数;否则,赋值第三个参数 a_2 = np.where(a>3,1,0) # - 与上一个不同的是,第二个参数为b_np (b_np.shape==a_np.shape), # 获取值时会获取相同位置的值(shape略不一样时,会广播),第三个参数也一样 a_3 = np.where(a>3,b_np,0) # np.concatenate: 合并,在shape(axis)会发生改变, # 例如 axis=0: shape=(2,6),shape(3,6) -> shape=(5,6) X = np.concatenate((X,X_add),axis=0)PyTorch: 深度学习
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset,DataLoader
# +=*/ : 许多函数类似于numpy
# torch.item # 转换为原始类型,只有size=1的才能转
# numpy -> torch.tensor
a_torch = torch.from_numpy(a_np) #将numpy 转换化为 tensor
a_torch = torch.tensor(a_np)
# torch.tensor -> numpy
a_np = a_torch.numpy()
# torch.clamp: 限制最大最小值
# 打乱 X,Y
index_s = np.arange(0,X.shape[0])
np.random.shuffle(index_s)
X = X[index_s]
Y = Y[index_s]
# torch.nn.functional.pairwise_distance() # n范数
# torch.scatter_: 转onehot
# a[b] b转onehot
# 转 onehot
def to_onehot(Y,label_num=4):
Y_onehot = np.zeros((Y.shape[0],label))
for i,y in zip(range(Y.shape[0]),Y):
Y_onehot[i,y[0]-1] = 1
return Y_onehot
# 指定device
device = torch.device('cpu')
device = torch.device('cuda',0)
a_torch = a_torch.to(device)
# cuda
# 看 [torch,cuda,cudnn] 版本,bash: nvcc -V | nvcc --version
print(torch.__version__)
print(torch.cuda.is_available()) # 查看CUDA是否可用
print(torch.cuda.device_count()) # 查看可用的CUDA数量
print(torch.version.cuda) # 查看CUDA的版本号
print(torch.backends.cudnn.version())
# cuda/cudnn 优化
# https://www.shuzhiduo.com/A/qVde1l6AdP/
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
- 学习
- PyTorch孪生神经网络
- torch.utils.data.DataLoader
- torch.tnesor.scatter_
- ↑↑↑ 2
- torch.module 获取中间层输出
- model.eval()
import torchvision # torchvision.models.模型名: 加载模型。参数: https://www.jianshu.com/p/07dd366d3d69 #pretrained (bool)-False表示随机初始化权重 #progress (bool)-Ture表示展示模型加载进度框 model = torchvision.models.模型名(pretrained=False, progress=True) # with torch.no_grad(): 不求梯度transforms
from torchvision import transforms t1 = transforms.Resize((64,64)) t2 = transforms.RandomHorizontalFlip() t3 = transforms.RandomVerticalFlip() t4 = transforms.RandomRotation((0,360),expand=True,fill=255) t5 = transforms.ToTensor() t6 = transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5, 0.5, 0.5])])) transform=transforms.Compose([t1,t5,t6]))
transformers: 自然语言处理库(TensorFlow2,PyTorch)参考
transform
transforms.RandomRotation
import transformersmatplotlib: 作图
import patplotlib.pyplot as plt # plt.plot: 折线图 plt.plot(xs,ys)shutil: 操作文件,os库的补充
import shutil # move 移动 shutil.move(path_from,path_to) # copy 复制 shutil.copy(path_from,path_to)sklearn: 机器学习
from sklearn.metrics import roc_curve,auc # 计算ROC,AUC # ROC # - y_true : 预测得到的标签,shape=(-1) # - y_score : 正标签的置信度,shape=(-1),!不是上面那个标签的 # - pos_label: 正标签数组 fpr,tpr,threshold=roc_curve(y_true,y_score,pos_label=[1]) # AUC roc_auc = auc(fpr, tpr) # 话 ROC 图 plt.plot(fpr,tpr)tqdm: 进度条
https://blog.csdn.net/winter2121/article/details/111356587
import tqdm from tqdm.notebook import tqdm # 在`jupyter notebook`中 # 使用 for i in tqdm(range(10)): print(i) time.sleep(1)官方库 argparse: 参数解析
import argparse
parser = argparse.ArgumentParser(description='染色体识别')
parser.add_argument('--model_number', type=str, help="模型名称,比如'model4']") # , default='model', required=True
parser.add_argument('--use_siamese' , action='store_true', default=False, help='使用孪生姊妹网络')
parser.add_argument('--sm' , type=int, default=10, help='save_margin_epoch : 每n个epoch保存一次 模型')
args = parser.parse_args()
print(args.__dict__)
model_number = args.model_number
use_siamese = args.use_siamese
json: json
import json # dict -> string json_str = json.dumps(json_dict) # string -> dict json_dict = json.loads(json_str) # dict -> file json.dump(json_dict,file) # file -> dict json_dict = json.load(file)glob: 文件通配
import glob
# 使用
path_s = glob.glob('model_one*.pth') # 获取所有匹配的路径
path_i = glob.iglob('model_one*.pth') # 获取第一个匹配的路径
os: 文件,路径 操作
import os # 列出文件夹下的文件 paths = os.path.listdir(path) # 该路径所在的文件夹(把最后的文件名去掉) path_dir = os.path.dirname(path)其它


![Python库[Pytorch,Numpy,] 学习笔记 Python库[Pytorch,Numpy,] 学习笔记](http://www.mshxw.com/aiimages/31/932209.png)
