day1: python programming

1. Reasonable use of python console in Pycharm

The python console is called the python console. It is very convenient to debug while writing code. You can directly enter the code as shown in the figure below, and you can clearly see the changes of each variable in each step.

2.import us

Take advantage of the API 

A module for performing operations on files and folders in the python environment.

3. Dataset for Pytorch data reading

Dataset provides a way to get data and label

from torch.utils.data import Dataset
from PIL import Image  ## 读取图片的库,可以对图片进行可视化
import os  ## 关于系统操作的库,主要用来对文件路径操作
​
# dir_path='dataset/hymenoptera_data/train/ants'   # 获取数据相对路径/也可以是绝对路径
# import os          ## 对数据所在文件路径进行字符串操作
# img_path_list=os.listdir(dir_path)  ## 将地址传给os.listdir会吧所有数据地址汇成一个列表,我的数据地址是dir_path='dataset/hymenoptera_data/train/ants' 
​
# img_path_list[0]   #  这个列表存的就是每个数据的文件名,我们取出第一个看一下
# 输出:'0013035.jpg'  # 和列表操作一样可以逐个读取

Create a class class that reads data

class MyData(Dataset):
    '''
    读数据的类需要继承Dataset这个类
    '''
​
    def __init__(self, root_dir, label_dir):  # 初始化主要是为这个所建的类提供全局变量
        
        '''
        :param root_dir: 数据集根目录
        :param label_dir: 数据集标签的目录,这个只填标签目录即可,我们有函数可以合并这两个目录
​
        ####################################
        root_dir='dataset/hymenoptera_data/train'
        label_dir='ants'
        path=os.path.join(root_dir,label_dir)  os.path.join()这个函数可以拼接两个文件路径形成一个文件路径
        输出:'dataset/hymenoptera_data/train\\ants'       我的数据就是放在dataset/hymenoptera_data/train\\ants里面\\环境里需要用\\
        '''
        
        self.root_dir = root_dir  ## self 的作用就是把定义的变量设置成全局变量
        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):  # item原本是item,在这里我们使用idx
        
        # 取图片中的某一个
        '''
        img_name = img_path[idx]
        print(img_name)
        0013035.jpg
        '''
​
        img_name = self.img_path[idx]  ## 根据idx索引来提取索引所☞的图片的编号
        img_item_path = os.path.join(self.root_dir, self.label_dir,
                                     img_name)  # 每一个图片的位置'dataset/hymenoptera_data/train\\ants\\0013035.jpg'
        ## 读取图片
        img = Image.open(img_item_path)
        ## 标签
        label = self.label_dir
​
        return img, label
​
    def __len__(self):
        '''
        返回数据集长度,数据集的长度就是列表文件的长度
        :return:
        '''
​
        return len(self.img_path)
​

Guess you like

Origin blog.csdn.net/weixin_44198288/article/details/126956500