torch FashionMNIST数据集导出图片

import numpy as np
import struct
 
from PIL import Image
import os

path_home='./data/FashionMNIST/raw/'
data_file = path_home+'train-images-idx3-ubyte'
# It's 47040016B, but we should set to 47040000B
data_file_size = 47040016
data_file_size = str(data_file_size - 16) + 'B'
 
data_buf = open(data_file, 'rb').read()
 
magic, numImages, numRows, numColumns = struct.unpack_from(
    '>IIII', data_buf, 0)
datas = struct.unpack_from(
    '>' + data_file_size, data_buf, struct.calcsize('>IIII'))
datas = np.array(datas).astype(np.uint8).reshape(
    numImages, 1, numRows, numColumns)
 
label_file = path_home+'train-labels-idx1-ubyte'
 
# It's 60008B, but we should set to 60000B
label_file_size = 60008
label_file_size = str(label_file_size - 8) + 'B'
 
label_buf = open(label_file, 'rb').read()
 
magic, numLabels = struct.unpack_from('>II', label_buf, 0)
labels = struct.unpack_from(
    '>' + label_file_size, label_buf, struct.calcsize('>II'))
labels = np.array(labels).astype(np.int64)
 
datas_root = 'mnist_train'
if not os.path.exists(datas_root):
    os.mkdir(datas_root)
 
for i in range(10):
    file_name = datas_root + os.sep + str(i)
    if not os.path.exists(file_name):
        os.mkdir(file_name)
 
for ii in range(numLabels):
    img = Image.fromarray(datas[ii, 0, 0:28, 0:28])
    label = labels[ii]
    file_name = datas_root + os.sep + str(label) + os.sep + \
        'mnist_train_' + str(ii) + '.png'
    img.save(file_name)

torch自定义数据集模型训练demo

import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from torch import nn
import os
import pandas as pd
from torchvision.io import decode_image


device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
#  独热数据逆转化 ,本例独热化非必须
def arc_one_hot(x,list=torch.tensor([0,1,2,3,4,5,6,7,8,9],dtype=torch.float).to(device)):
    return x@list
#  1.创建自定义数据集
class CustomImageDataset(Dataset):
    def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
        self.img_labels = pd.read_csv(annotations_file, header=None) # 注意首行默认会被作为标题行忽略,或者设置header=None 
        self.img_dir = img_dir
        self.transform = transform
        self.target_transform = target_transform

    def __len__(self):
        return len(self.img_labels)

    def __getitem__(self, idx):
        img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
        #print(img_path)
        image = decode_image(img_path).float().div(255) #需要转成float类型,否则无法训练
        #print(image.shape)
        label = self.img_labels.iloc[idx, 1]
        #print(label)
        if self.transform:
            image = self.transform(image)
        if self.target_transform:
            label = self.target_transform(label)
        #独热化
        # print(label)
        new_transform = Lambda(lambda y: torch.zeros(10, dtype=torch.float).scatter_(dim=0, index=torch.tensor(y), value=1))
        label = new_transform(label)
        # print("------fuck")
        # print(label)
        return image, label
    

# csv注意是否有标题行
csv_path='/Users/mnist_test_cus_data/imglist_train.csv'
img_dir='/Users/mnist_test_cus_data/imgs_train/'
batch_size = 64
# 创建自定义数据集实例
mydataset = CustomImageDataset(annotations_file=csv_path, img_dir=img_dir, transform=None, target_transform=None)

# 使用 DataLoader 加载数据
mydataloader = DataLoader(mydataset, batch_size, shuffle=True, num_workers=0) #, num_workers=4 macos报错
print(len(mydataloader))
print(len(mydataloader.dataset))
# print(mydataset[59999])
# print(mydataset[0][0])
# print(mydataset[0][1])
# exit()

# Download test data from open datasets.
test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor(),
    target_transform = Lambda(lambda y: torch.zeros(10,dtype=torch.float).scatter_(dim=0, index=torch.tensor(y), value=1))
)
test_dataloader = DataLoader(test_data, batch_size=batch_size)

# 遍历 DataLoader
#for batch in mydataloader:
#    images, labels = batch
    #print(images.size(), labels.size())
    #print(images)
    #print(labels)

for X, y in test_dataloader:
    print(f"Shape of X [N, C, H, W]: {X.shape}")
    print(f"Shape of y: {y.shape} {y.dtype}")

    # print(X)
    # print(y)
    # print(arc_one_hot(y.to(device)))

    break
print(len(mydataloader))
# exit()


#  2. 可视化数据
def showdata():
    labels_map = {
        0: "T-Shirt",
        1: "Trouser",
        2: "Pullover",
        3: "Dress",
        4: "Coat",
        5: "Sandal",
        6: "Shirt",
        7: "Sneaker",
        8: "Bag",
        9: "Ankle Boot",
    }
    figure = plt.figure(figsize=(8, 8))
    cols, rows = 3, 3
    xxx=''
    for i in range(1, cols * rows + 1):
        sample_idx = torch.randint(len(mydataset), size=(1,)).item()
        img, label = mydataset[sample_idx]
        figure.add_subplot(rows, cols, i)
        # 独热逆转化
        label=arc_one_hot(label.to(device)).item()
        plt.title(labels_map[label])
        plt.axis("off")
        xxx=img
        plt.imshow(img.squeeze(), cmap="gray")
    plt.show()
    print(xxx.shape)
    print('------')
    print(xxx.squeeze().shape)

    # Display image and label.
    train_features, train_labels = next(iter(mydataloader))
    print(f"Feature batch shape: {train_features.size()}")
    print(f"Labels batch shape: {train_labels.size()}")
    img = train_features[0].squeeze()
    label = train_labels[0]
    plt.imshow(img, cmap="gray")
    plt.show()
    print(f"Label: {label}")
    # exit()


# 3.定义模型

print(f"Using {device} device")

# Define model
class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten() #维度展平
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10)
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

model = NeuralNetwork().to(device)
print(model)

# 4. 定义损失函数和优化器
loss_fn = nn.CrossEntropyLoss() #交叉熵
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)

# 5. 训练
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    print("size="+str(size))
    model.train() # 启用 Batch Normalization 和 Dropout,归一化,随机丢弃神经元防止过拟合,测试时不丢弃
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)
        # Compute prediction error
        pred = model(X)
        # print("---------->pred=")
        # print(pred)
        # print(y)
        # print("-----------------------<")
        # 不需要独热逆转化,交叉熵计算过程包含了独热编码,但是不仍然可以使用独热参数
        # y=arc_one_hot(y)
        loss = loss_fn(pred, y)

        # Backpropagation
        loss.backward() # 计算梯度
        optimizer.step() # 根据梯度优化参数
        optimizer.zero_grad() # 梯度归零

        if batch % 100 == 0: # 每100个batch打印一次
            loss, current = loss.item(), (batch + 1) * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")
        # exit()
# 6. 测试
def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            #print(y)
            #不需要独热逆编码
            #y=arc_one_hot(y)
            #print(y)
            pred = model(X)
            #print(pred)
            test_loss += loss_fn(pred, y).item()
            #统计个数
            # >>> xx==zz
            # tensor([ True, False, False,  True, False,  True, False,  True, False, False,
            #          True, False, False,  True, False, False,  True, False,  True, False,
            #          True, False, False, False, False,  True,  True, False,  True, False,
            #         False,  True, False, False, False, False, False, False,  True,  True,
            #         False, False, False,  True, False, False,  True, False, False,  True,
            #         False,  True, False,  True,  True, False, False, False, False,  True,
            #         False,  True,  True,  True])
            # >>> (xx==zz).type(torch.float)
            # tensor([1., 0., 0., 1., 0., 1., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0.,
            #         1., 0., 1., 0., 0., 0., 0., 1., 1., 0., 1., 0., 0., 1., 0., 0., 0., 0.,
            #         0., 0., 1., 1., 0., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 1., 0., 1.,
            #         1., 0., 0., 0., 0., 1., 0., 1., 1., 1.])
            # >>> (xx==zz).type(torch.float).sum()
            # tensor(25.)
            # >>> (xx==zz).type(torch.float).sum().item()
            # 25.0
            yy=arc_one_hot(y)
            correct += (pred.argmax(1) == yy).type(torch.float).sum().item()
    test_loss /= num_batches
    correct /= size
    print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")

#  7. 训练和测试
def do_train():
    epochs = 5
    for t in range(epochs):
        print(f"Epoch {t+1}\n-------------------------------")
        train(mydataloader, model, loss_fn, optimizer)
        test(test_dataloader, model, loss_fn)
    print("Done!")
    __save_model__()

# for var_name in model.state_dict():
#     print(var_name, "\t", model.state_dict()[var_name])

# for var_name in optimizer.state_dict():
#     print(var_name, "\t", optimizer.state_dict()[var_name])

#  8. 保存模型
def __save_model__():
    path="model.pth"
    torch.save(model.state_dict(), path)
    print("Saved PyTorch Model State to "+path)
#  9. 加载模型
def load_model():
    model = NeuralNetwork().to(device)
    model.load_state_dict(torch.load("model.pth", weights_only=True))
    return model
#  10. 测试模型
def  test_model():
    model = load_model()
    classes = [
        "T-shirt/top",
        "Trouser",
        "Pullover",
        "Dress",
        "Coat",
        "Sandal",
        "Shirt",
        "Sneaker",
        "Bag",
        "Ankle boot",
    ]

    model.eval()
    x, y = test_data[0][0], test_data[0][1]
    with torch.no_grad():
        x = x.to(device)
        pred = model(x)
        # 独热转化,同device才能计算
        y=arc_one_hot(y.to(device)).int()
        print(y)

        print(f"Predicted: {pred[0].argmax(0)}, Actual: {y}")
        predicted, actual = classes[pred[0].argmax(0)], classes[y]
        print(f'Predicted: "{predicted}", Actual: "{actual}"')

def  do_test_model():
    load_model()
    test_model()
def do_train_model():
    showdata()
    do_train()
    test_model()
def main():
    do_train_model()
    #do_test_model()
    

if __name__ == '__main__':
    main()

ipynb转markdown

在vs code中Jupyter Notebook ipynb文件不能复制内容,不方便分享,而自带的导出功能非常鸡肋,需要安装XETEX,官网显示全部安装需要7个多G“By default, everything is installed (7+GB)”,直接劝退了。

既然ipynb就是markdown写出来的,直接转markdown岂不是更好?

网上很多使用下面的命令,但是我遇到了错误 Jupyter command `jupyter-nbconvert` not found. 有可能是我环境变量问题。

jupyter nbconvert –to markdown ‘abc.ipynb’

推荐使用下面的代码,不依赖环境

python3 -m nbconvert –to markdown ‘abc.ipynb’

torch 张量

张量是一种特殊的数据结构,与数组和矩阵非常相似。在 PyTorch 中,我们使用张量来编码模型的输入和输出,以及模型的参数。

张量类似于 NumPy 的 ndarray,不同之处在于张量可以在 GPU 或其他硬件加速器上运行。实际上,张量和 NumPy 数组通常可以共享底层内存,从而无需复制数据(详见与 NumPy 的桥接)。张量还针对自动微分进行了优化(我们将在后面的 Autograd 部分详细介绍)。如果您熟悉 ndarrays,您会很快适应 Tensor API。如果不熟悉,请继续阅读!

import torch
import numpy as np

初始化张量

张量可以通过多种方式进行初始化。请看以下示例

直接从数据创建

张量可以直接从数据创建。数据类型会自动推断。

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

从 NumPy 数组创建

张量可以从 NumPy 数组创建(反之亦然 – 详见与 NumPy 的桥接)。

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

继续阅读“torch 张量”

torch 快速入门

Quickstart

This section runs through the API for common tasks in machine learning. Refer to the links in each section to dive deeper.

Working with data

PyTorch has two primitives to work with datatorch.utils.data.DataLoaderand torch.utils.data.DatasetDataset stores the samples and their corresponding labels, and DataLoader wraps an iterable around the Dataset.

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor

PyTorch offers domain-specific libraries such as TorchTextTorchVision, andTorchAudio, all of which include datasets. For this tutorial, we will be using a TorchVision dataset.

The torchvision.datasets module contains Dataset objects for many real-world vision data like CIFAR, COCO (full list here). In this tutorial, we use the FashionMNIST dataset. Every TorchVision Dataset includes two arguments:transform and target_transform to modify the samples and labels respectively.

# Download training data from open datasets.
training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor(),
)

# Download test data from open datasets.
test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor(),
)
print(len(training_data))
60000
继续阅读“torch 快速入门”

Python中r’ ‘, b’ ‘, u’ ‘, f’ ‘的含义及用法详解

在Python中,字符串是一种常见的数据类型,用于表示文本信息。除了普通的字符串,Python还提供了一些特殊的字符串前缀和格式化字符串,包括r’ ‘,b’ ‘,u’ ‘,f’ ‘。本文将详细解释这些前缀的含义以及它们的用法,以帮助大家更好地理解和应用它们。

更多Python学习内容:http://ipengtao.com

r’ ‘: 原始字符串

r前缀表示原始字符串(raw string),它会取消字符串中的转义字符(如\n、\t)的特殊含义。原始字符串适用于需要保留转义字符原始形式的情况,如正则表达式、文件路径等。

1 基本用法

# 使用r前缀创建原始字符串
path = r’C:\Users\Username\Documents’
print(path)

在上述示例中,r前缀将字符串中的反斜杠\视为普通字符,而不是转义字符。

2 与转义字符的比较

# 普通字符串与原始字符串的比较
normal_str = ‘C:\\Users\\Username\\Documents’
raw_str = r’C:\Users\Username\Documents’

print(normal_str == raw_str)  # 输出 True

原始字符串与普通字符串在表示相同的文本时是相等的,但原始字符串更容易阅读和维护。

b’ ‘: 字节字符串

b前缀表示字节字符串(bytes string),它用于处理二进制数据,而不是文本数据。字节字符串是不可变的,通常用于处理图像、音频、网络协议等二进制数据。

1 基本用法

# 使用b前缀创建字节字符串
binary_data = b’\x48\x65\x6c\x6c\x6f’  # 字母 ‘Hello’ 的字节表示
print(binary_data)

在上述示例中,b前缀表示字节字符串,每个\x后面跟着两个十六进制数字,表示一个字节。

2 字符串与字节字符串的区别

# 字符串与字节字符串的区别
text = ‘Hello’
binary_data = b’Hello’

print(type(text))  # 输出 <class ‘str’>
print(type(binary_data))  # 输出 <class ‘bytes’>

字符串和字节字符串是不同的数据类型,字符串用于文本,字节字符串用于二进制数据。

u’ ‘: Unicode字符串

u前缀表示Unicode字符串,它用于处理Unicode编码的文本数据。在Python 3中,所有的字符串都是Unicode字符串,因此很少需要使用u前缀。在Python 2中,u前缀用于表示Unicode字符串。

1 基本用法

# 使用u前缀创建Unicode字符串(Python 2示例)
unicode_text = u’你好,世界!’
print(unicode_text)

在Python 3中,无需使用u前缀,普通字符串即为Unicode字符串。

2 Unicode字符串与普通字符串的区别

# Unicode字符串与普通字符串的区别(Python 2示例)
text = ‘Hello’
unicode_text = u’Hello’

print(type(text))  # 输出 <type ‘str’>
print(type(unicode_text))  # 输出 <type ‘unicode’>

在Python 2中,Unicode字符串与普通字符串是不同的数据类型,用于区分文本编码。

f’ ‘: 格式化字符串

f前缀表示格式化字符串(formatted string),它用于在字符串中嵌入表达式的值。在格式化字符串中,可以使用大括号{}来引用变量或表达式,并将其值插入字符串中。

1 基本用法

# 使用f前缀创建格式化字符串
name = ‘Alice’
age = 30
greeting = f’Hello, my name is {name} and I am {age} years old.’
print(greeting)

在上述示例中,f前缀表示格式化字符串,大括号{}内的表达式会被计算并插入到字符串中。

2 表达式和变量

# 在格式化字符串中使用表达式和变量
x = 10
y = 20
result = f’The sum of {x} and {y} is {x + y}’
print(result)

格式化字符串允许嵌入表达式和变量,并将它们的值动态插入到字符串中。

总结

在Python中,r’ ‘,b’ ‘,u’ ‘,f’ ‘等前缀和格式化字符串是用于处理不同类型文本和数据的工具。r前缀表示原始字符串,b前缀表示字节字符串,u前缀表示Unicode字符串,f前缀表示格式化字符串。了解这些前缀的含义和用法有助于更好地处理不同类型的字符串和数据。

python from .xxx import yyy 与 from xxx import yyy区别

相对导入只能用于同一个package里,并且包内的文件不能单独运行,只能在包的外部来调用



|--testmodule.py
|
|--testpy
   |
   |-- __init__.py 模块标志文件
   |
   |-- hello.py    模块1
   |
   |-- test.py             模块2,导入模块1,不可以单独运行
   |
   |-- test2.py    可以单独运行




hello.py
print('hello.py')
class hhh():
    print('hhhh')



test.py
from .hello import hhh
print('test.py')



testmodule.py
from testpy import test
print('OK')


python3 testmodule.py
hello.py
hhhh
test.py
OK




test2.py
from hello import hhh
print('test2.py')


cd testpy 

ls
__init__.py	__pycache__	hello.py	test.py		test2.py

python3 test.py  不可以单独运行

Traceback (most recent call last):
  File "/Users/yourname/Documents/testpy/test.py", line 1, in <module>
    from .hello import hhh
ImportError: attempted relative import with no known parent package

python3 test2.py  可以单独运行
hello.py
hhhh
test2.py