Python库[Pytorch,Numpy,]

目录

  • 注意
  • 基础
  • Python
  • 三方库
    • numpy: 科学计算
    • torch | PyTorch: 深度学习
    • torchvision: PyTorch的模型库
      • transforms:图像转换
    • huggingface/transformers: 自然语言处理库(TensorFlow2,PyTorch)
    • pycocotools: CocoApi
    • cv2:计算机视觉
    • matplotlib: 作图
    • shutil: 操作文件,os库的补充
    • sklearn:机器学习 & 数据集处理
    • tqdm:进度条
    • labelme:数据标注
    • PyMuPDF:PDF操作
    • resuests:网络请求(易用)
  • 官方库
    • collections:容器
    • argparse: 参数解析
    • json: json
    • glob: 文件通配
    • os: 文件,路径 操作
    • datetime: 时间
    • itertools: 工具类
    • operator: 操作函数
    • urllib:网络请求
  • 其它
    • pytorch下载
    • pytorch使用
    • CUDA&cuDNN 下载(pytorch需要)
    • cv2 | opencv-python

注意

疑难库可以直接下载whl,再pip install xx.whl。难以直接下到等情况
下载地址

基础

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)>=1

Python

`# 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())

三方库

numpy: 科学计算

import numpy as np
# np +-*/&| **
c = a+b # 同位置相加(shape不变,其它都差不多)

# np.shape: 获得对象的shape形状
a_np.shape() # (2,3)

# np.reshape(-1)
a_np.reshape(-1)

# 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)

torch | 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

torchvision: PyTorch的模型库

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]))

参考
transform
transforms.RandomRotation

huggingface/transformers: 自然语言处理库(TensorFlow2,PyTorch)

https://blog.csdn.net/sinat_28931055/article/details/119560054

import transformers

pycocotools: CocoApi

安装(需要vs)

  1. 使用pycocotools-windows
  • 参考:https://pypi.tuna.tsinghua.edu.cn/simple/pycocotools-windows/
  1. 安装
  • 参考:Microsoft Visual C++ Build Tools
    https://blog.csdn.net/colleges/article/details/123769410
    其他:可以考虑下载microsoft visual c 2015 2019 redistributable
  • 参考:https://download.visualstudio.microsoft.com/download/pr/b929b7fe-5c89-4553-9abe-6324631dcc3a/296F96CD102250636BCD23AB6E6CF70935337B1BBB3507FE8521D8D9CFAA932F/VC_redist.x64.exe
from pycocotools.coco import COCO

# 使用示例
annFile='data.json'
coco=COCO(annFile)
img = coco.loadImgs([1])[0]
annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None)
anns = coco.loadAnns(annIds )
coco.annToMask

# 输出示例
I = Image.open(img['file_name'])
plt.imshow(I); plt.axis('off')
annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None)
anns = coco.loadAnns(annIds)
coco.showAnns(anns)
plt.show()

CocoApi
COCO数据集

cv2:计算机视觉

pip install opencv-python

import cv2

# 提取轮廓
image,contours,hierarchy = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)


# 获得旋转框:((x_center,y_center),(height,width),angel)
rotatedbox = cv2.minAreaRect(points)

cv2.minAreaRect

matplotlib: 作图

import patplotlib.pyplot as plt

import matplotlib.pyplot as plt

#简单画图,折线图
plt.plot(x,y)
plt.slim(0.5,4.5)
plt.show()#显示

fig=plt.figure()
ax3=fig.add_subplot(234) # 2*3的第4个区域
ax.set( ) #xlim,ylim,title,ylabel,xlabel ;设置属性

fig,axes = plt.subplots(2,2) #nrows,ncols: 默认1;sharex,sharey:共享x,y
ax0,ax1,ax2,ax3=axes.flatten();
axes[0,1].set()

#可以用dict代替,然后传入相应的键和data=dict
ax3.plot(x,t  )#color,linewidth,markersize,marker,linesyle 画线
ax.fill_between(  ) # 填充中间的区域

ax.scater(  ) #散点图x,y
- s=area大小 #泡泡图

ax.bar(  )# 垂直柱状图
ax.axhline(0, ) #水平方向画线

ax.barh(  )# 横向柱状图(条形图)
ax.axhline(0, ) #垂直方向画线

> vert_bars = ax.bar(  ) #单独进行设置

#直方图histogram
ax.hist(x[,nbins]  ) #density, histtype, rwidth

#饼图
ax.pie(sizes  )#label, autopct, shadow, explode, pctdistance


# 箱形图

# 轮廓图
ax.contour(x, y, z)
ax.contourf(x, y, z) #填充轮廓线的颜色

> ax.set_xx( ) 设置
>ax.legend(  ) #控制图例的位置
>ax2.set(xticks=x, xticklabels=fruit) #修改x轴的表示方式
>fig.subplots_adjust(  ) #修改子图的间距等:wspace, hspace,left,right,top,bottom
>ax.spines[‘right’].set_visible(False) #轴设为不可见
>					set_position((‘data’,0))#把边界移到另一轴的0处
>					set_position((‘axes’,0))#把边界按百分比移动

shutil: 操作文件,os库的补充

import shutil

# move 移动
shutil.move(path_from,path_to)

# copy 复制
shutil.copy(path_from,path_to)



sklearn:机器学习 & 数据集处理


# 计算ROC,AUC
from sklearn.metrics import roc_curve,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)

# train_test_split:分成训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size, random_state)

# StratifiedShuffleSplit:数据分层抽样,K折交叉K-fold
a = list(range(0,10))
X = a*10
y = X
index_train, index_test=list(StratifiedShuffleSplit(n_splits=1, test_size=0.1).split(X,y))[0]
X_train = [ X[i] for i in index_train ]
X_test  = [ X[i] for i in index_test  ]

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)

labelme:数据标注

from labelme import utils as labelme_utils
img = labelme_utils.img_b64_to_arr(json_data['imageData'])

PyMuPDF:PDF操作

import fitz

# 新建pdf
pdf = fitz.open(path_pdf)

# 插入一页(取出[from_page,to_page],插入到pdf的start)
pdf.insert_pdf(pdf_temp,from_page=0,to_page=0,start=0)

# 获得所有链接,【页,to(x,y)】
links = pdf.get_links()

# 覆盖书签,每一条是[number,content,page,y]
pdf.set_toc(tocs)

# 保存
pdf.saveIncr() # 原位置,但修改次数+1
pdf.sasve(path_pdf_target) # 保存到目标位置


resuests:网络请求(易用)

import requests

# 构造请求,发送请求,获得响应
response = requests.post(url, cookies=cookies, data={'esId': 2}, timeout=30)

# 得到数据,response 包含所有请求的所有信息(状态码、data等)
data = r.json()['data']

官方库

collections:容器

https://blog.csdn.net/sinat_38682860/article/details/109291215


# Counter,计数
from collections import Counter
labels = [1,2,3,4,2,3,4,5]
counter = Counter(labels)
keys = list(counter.keys())
values = list(counter.values())

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) 
name_file = os.path.basename(path) 

datetime: 时间

import datetime

# 当前实际:年月日_时分秒
time_curr_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

itertools: 工具类


# chain: 多数组合并
from itertools import chain
lists = [[1,2,3],[2,3,4],[1,2]]
list_all = list(chain(*lists ))

# groupby: 按关键词分组(并且连续,所以需要排序)
from itertools import groupby
list_label = [1,2,3,2,3,4]
list_index_label = list(enumerate(index))
func_key = lambda i:i[1]
list_index_label_sorted = sorted(list_index_label,key=func_key)
group = groupby(list_index_label_sorted,key=lambda i:i[1])
for key,datas in group:
	print(list(datas))

operator: 操作函数


# itemgetter:取值函数,代替简单lambda表达式
from operator import itemgetter
data = [[1,2,3],[4,5,6]]
result = list(map(itemgetter(1,2),data)) # itemgetter(1),itemgetter('name')
for i in result:
    print(i)


urllib:网络请求

import urllib.request

# 构造请求
resuest = urllib.request.Request(
	url,
	headers=headers,
	data=bytes(urllib.parse.urlencode(jsondata),encoding="UTF-8"),
	method="POST")

# 发送并获得响应
response = urllib.request.urlopen(request,timeout=30)
# 得到数据,只包含data
result_str =response.read().decode("utf-8")
# 解析为json
result = json.loads(result_str)

其它

pytorch下载

  • 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
  • torch==1.8.2+cu111cu111是 这个torch的cuda版本(必须 <= 本机cuda版本)
    • 查看 [NVIDIA_GPU, CUDA]: nvidia-smi
  • 版本对应: torch,torchvision

pytorch使用

  • PyTorch孪生神经网络
  • torch.utils.data.DataLoader
  • torch.tnesor.scatter_
  • torch.module 获取中间层输出
    1. 手动forward,收集需要的
    2. IntermediateLayerGetter,仅限所有层都在model.named_children() 中的(`torchvision.models._utils.IntermediateLayerGetter(m,name_map)
    3. hook:module.register_forward_hook(hook=hook)
  • model.eval()
  • 使用官方Mask R-CNN
  • 自己的Mask R-CNN
  • torch.optim.lr_scheduler
  • [数据集划分 torch.utils.data.random_split]
  • [permute,transpose,view,reshape]

CUDA&cuDNN 下载(pytorch需要)

  1. 查看自己的cuda最低版本:执行nvidia-smi,看右上角
  2. CUDA【下载,运行安装】:https://developer.nvidia.com/cuda-toolkit-archive
  3. cuDNN【下载,将文件放到CUDA安装路径下】:https://developer.nvidia.com/rdp/cudnn-download
  4. 环境变量CUDA_HOME在第二步已经配好

cv2 | opencv-python

运行from .cv2 import * ,报错ImportError: libGL.so.1: cannot open shared object file:

https://blog.csdn.net/qq_50195602/article/details/124188467

apt-get install -y libgl1-mesa-dev

你可能感兴趣的:(python,pytorch,python,学习)