当前位置:网站首页>Pytoch learning notes (I) installation and use of common functions
Pytoch learning notes (I) installation and use of common functions
2022-07-26 13:39:00 【Did Xiao Hu get stronger today】
List of articles
install Pytorch
stay Anaconda Create... In the environment pytorch Environmental Science
conda create -n pytorch python=3.6
Activate the environment
conda activate pytorch
View the package list
pip list
pytorch Official website :
https://pytorch.org/
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-wMEEx9Ga-1658802973736)(C:\Users\Husheng\Desktop\ Learning notes \image-20220721105827500.png)]](/img/ef/c15f4af71b02b2c566e404cf82fad5.png)
Installation command :
conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
appear True explain pytorch have access to GPU.
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-guSm5J4A-1658802973737)(C:\Users\Husheng\Desktop\ Learning notes \image-20220712220003299.png)]](/img/0c/57e8f43dcac3bf681b7f4935f3faed.png)
stay pytorch Install in jupyter
conda install nb_conda
start-up jupyter
jupyter notebook
shift + enter , Jump to another code block , And run the last code block .
Two common functions
(1)dir() There is something in the toolbox and the partition of the toolbox ;
(2)help() How each tool is used , How to use the tool .
Differences between the three coding methods
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-6HjdTzgI-1658802973737)(C:\Users\Husheng\Desktop\ Learning notes \image-20220721131337757.png)]](/img/40/b9087f6de8df6b3111626c4d09384f.png)
Dataset actual combat
from torch.utils.data import Dataset
from PIL import Image
import os
class MyData(Dataset):
def __init__(self, root_dir, label_dir):
self.root_dir = root_dir
self.label_dir = label_dir
self.path = os.path.join(self.root_dir, self.label_dir)
self.img_path = os.listdir(self.path)
def __getitem__(self, idx):
img_name = self.img_path[idx]
img_item_path = os.path.join(self.root_dir, self.label_dir, img_name)
img = Image.open(img_item_path)
label = self.label_dir
return img, label
def __len__(self):
return len(self.img_path)
root_dir = "dataset/train"
ants_label_dir = "ants"
bees_label_dir = "bees"
ants_dataset = MyData(root_dir, ants_label_dir)
bees_dataset = MyData(root_dir, bees_label_dir)
train_dataset = ants_dataset + bees_dataset
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-MiOH3EHJ-1658802973738)(C:\Users\Husheng\Desktop\ Learning notes \image-20220721170630153.png)]](/img/3a/3dcd63471b3fcbbf73e5b9b8622a66.png)
TensorBoard Use
install tensorboard
pip install tensorboard
Report errors :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-TVY5sptY-1658802973738)(C:\Users\Husheng\Desktop\ Learning notes \image-20220721172628638.png)]](/img/3f/aaad2046a1936e4b69314f2fe2dd14.png)
solve : Run as Administrator Anaconda Prompt, reinstall .
Installation and operation error :![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-maB8KXuL-1658802973738)(C:\Users\Husheng\Desktop\ Learning notes \image-20220721173651485.png)]](/img/5d/0d11edeb5933b710730703ac287d6d.png)
solve :setuptools There is a problem with the version , Unload and reload .
pip uninstall setuptools
pip install setuptools==59.5.0
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-uGXu9wRs-1658802973738)(C:\Users\Husheng\Desktop\ Learning notes \image-20220721174213013.png)]](/img/0a/7bc6decb7f61844e85f293d3e47c8d.png)
–logdir=logs No space in the middle
Designated port :
tensorboard --logdir=logs --port=6007
If you draw y = 2x, Draw again 3x, Will automatically fit the image , The solution is to delete logs All files under , Rerun code , Rerun tensorboard --logdir=logs --port=6007
display picture :
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image
writer = SummaryWriter("logs")
img_path = "data/train/ants_image/0013035.jpg"
img_PIL = Image.open(img_path)
img_array = np.array(img_PIL)
print(type(img_array))
print(img_array.shape)
writer.add_image("train", img_array, 1, dataformats='HWC')
# y = x
for i in range(100):
writer.add_scalar("y = 2x", 3*i, i)
writer.close()
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-cFyyh1MN-1658802973739)(C:\Users\Husheng\Desktop\ Learning notes \image-20220721225136606.png)]](/img/f3/b97661812068a688549a8f1d288910.png)
Transforms

install opencv Failure :![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-I5LKEQJT-1658802973743)(C:\Users\Husheng\Desktop\ Learning notes \image-20220721232654305.png)]](/img/2b/2257ea19f20b10a825cecda170aa90.png)
This error has also been solved for a long time , Several methods have been tried ( The last blog specifically solved this problem :https://blog.csdn.net/hshudoudou/article/details/125930549?spm=1001.2014.3001.5502), The final solution is to specify the version installation :
Code :
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
img_path = "dataset/train/ants/0013035.jpg"
img = Image.open(img_path)
# print(img)
writer = SummaryWriter("logs")
# 1. transforms How to use
tensor_trans = transforms.ToTensor()
tensor_img = tensor_trans(img)
writer.add_image("Tensor_img", tensor_img)
writer.close()
common Transforms

from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
writer = SummaryWriter("logs")
img = Image.open("imgages/blue.jpg")
print(img)
#ToTensor Use
trans_totensor = transforms.ToTensor()
img_tensor = trans_totensor(img)
writer.add_image("ToTensor", img_tensor)
#Normalize normalization
print(img_tensor[0][0][0])
trans_norm = transforms.Normalize([6, 3, 2], [9, 3, 5])
img_norm = trans_norm(img_tensor)
print(img_norm[0][0][0])
writer.add_image("Normalize", img_norm, 2)
#Resize
print(img.size)
trans_resize = transforms.Resize((512, 512))
# img PIL -> resize -> img_size PIL
img_resize = trans_resize(img)
# img_resize PIL -> totensor -> img_resize tensor
img_resize = trans_totensor(img_resize)
writer.add_image("Resize", img_resize, 0)
print(img_resize)
# Compose - resize - 2
trans_resize_2 = transforms.Resize(512)
# PIL -> PIL -> tensor
trans_compose = transforms.Compose([trans_resize_2, trans_totensor])
img_resize_2 = trans_compose(img)
writer.add_image("Resize", img_resize_2, 2)
# RandomCrop
trans_random = transforms.RandomCrop((500, 1000))
trans_compose_2 = transforms.Compose([trans_random, trans_totensor])
for i in range(10):
img_crop = trans_compose_2(img)
writer.add_image("RandomCropHW", img_crop, i)
writer.close()

Use transforms Points for attention :
Focus on input and output , Read more official documents , Pay attention to the parameters required by the method .
torchvision Use of data sets in

import torchvision
from torch.utils.tensorboard import SummaryWriter
dataset_transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor()
])
train_set = torchvision.datasets.CIFAR10(root="./dataset", train=True, transform=dataset_transform, download=True)
test_set = torchvision.datasets.CIFAR10(root="./dataset", train=False, transform=dataset_transform, download=True)
# print(test_set[0])
# print(test_set.classes)
# img, target = test_set[0]
# print(img)
# print(target)
# print(test_set.classes[target])
# img.show()
#
# print(test_set[0])
writer = SummaryWriter("p10")
for i in range(10):
img, target = test_set[i]
writer.add_image("test_set", img, i)
writer.close()
DataLoader Use
import torchvision
from torch.utils.data import DataLoader
# Prepared test data set
from torch.utils.tensorboard import SummaryWriter
test_data = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor())
test_loader = DataLoader(dataset=test_data, batch_size=64, shuffle=True, num_workers=0, drop_last=True)
# The first picture in the test data set and target
img, target = test_data[0]
print(img.shape)
print(target)
writer = SummaryWriter("dataloader")
# step = 0
# for data in test_loader:
# imgs, targets = data
# # print(imgs.shape)
# # print(targets)
# writer.add_images("test_data", imgs, step)
# step += 1
for epoch in range(2):
step = 0
for data in test_loader:
imgs, targets = data
# print(imgs.shape)
# print(targets)
writer.add_images("Epoch:{}".format(epoch), imgs, step)
step += 1
writer.close()
dataloader Equivalent to how to start from dataset Retrieve data from ,dataset: Data sets ,batch_size: The maximum number of each group ,shuffle: Whether to disturb ,num_workers: Number of threads ,drop_last: Whether to discard the last picture that is not divisible .
Reference material
边栏推荐
- Multi objective optimization series 1 --- explanation of non dominated sorting function of NSGA2
- Intercept the coordinate points (four point coordinates of the face frame) face image from the marked XML file and save it in the specified folder
- 历时15年、拥有5亿用户的飞信,彻底死了
- 消息的订阅和发布
- 力扣------字符串中的单词数
- Basic sentence structure of English ----- origin
- 周伟:寻找非共识性投资机会,陪伴延迟满足的创始团队
- SuperMap iclient for leaflet loads Gauss Kruger projection three-dimensional zonation CGCS2000 geodetic coordinate system WMTs service
- Parent class reference to child class (parent class reference points to child class object)
- 白帽子揭秘:互联网千亿黑产吓退马斯克
猜你喜欢

AI theory knowledge map 1 Foundation

The last time I heard about eBay, or the last time

如何构建以客户为中心的产品蓝图:来自首席技术官的建议

Learn about Pinia state getters actions plugins

We were tossed all night by a Kong performance bug
![[oauth2] VIII. Configuration logic of oauth2 login -oauth2loginconfigurer and oauth2clientconfigurer](/img/7e/4f652c4d3d72ad563ddbc1c1f1f50b.png)
[oauth2] VIII. Configuration logic of oauth2 login -oauth2loginconfigurer and oauth2clientconfigurer
![[flower carving hands-on] fun music visualization series small project (12) -- meter tube fast rhythm light](/img/99/6581b8a576e59a13aa4e977e3a1b70.jpg)
[flower carving hands-on] fun music visualization series small project (12) -- meter tube fast rhythm light

【黑马早报】字节旗下多款APP下架;三只松鼠脱氧剂泄露致孕妇误食;CBA公司向B站索赔4.06亿;马斯克否认与谷歌创始人妻子有婚外情...

【OAuth2】八、OAuth2登录的配置逻辑-OAuth2LoginConfigurer和OAuth2ClientConfigurer

【着色器实现Overlay重新覆盖变装效果_Shader效果第九篇】
随机推荐
Uncover the secret of white hat: 100 billion black products on the Internet scare musk away
JSON data transfer parameters & date type parameter transfer
重押海外:阿里、京东、顺丰再拼“内力”
时间复杂度和空间复杂度
Activity.onStop() 延迟10秒?精彩绝伦的排查历程
云智技术论坛工业专场 明天见!
JUC summary
我们被一个 kong 的性能 bug 折腾了一个通宵
Thoughts on the compilation of Dr. Shuo's opening report
2022年,我们只用一个月就“送走”了这么多互联网产品
JSON数据传递参数&日期型参数传递
Brief introduction of reflection mechanism
[oauth2] VIII. Configuration logic of oauth2 login -oauth2loginconfigurer and oauth2clientconfigurer
终极套娃 2.0 | 云原生交付的封装
421. Maximum XOR value of two numbers in the array
带你熟悉云网络的“电话簿”:DNS
上一次听到易趣,还是上一次
Huawei computer test ~ offset realizes string encryption
Familiarize you with the "phone book" of cloud network: DNS
Activity. Onstop() delay 10 seconds? Wonderful investigation process