Pytorch基本训练

1、dataframe转化成numpy数组
data = np.array(df.iloc[:100, :])
2、numpy数据格式转化

由于torch进行训练时需要数据类型为torch.float32,所以需要对numpy进行格式转化

X = np.linspace(-2, 2, 200).astype(np.float32)
np.random.shuffle(X)  #numpy打乱数据顺序
X = X.reshape(200, 1)
y = 3.5*X + np.random.normal(0, 0.05, (200, 1)).astype(np.float32)
3、手写数据迭代器
dataset = Data.TensorDataset(X_t, y_t)
data_iter = Data.DataLoader(dataset, batch_size = 10, shuffle = True)
4、训练基本步骤
  • 1、回归
import torch
import torch.nn as nn
import torch.utils.data as Data
from torch.nn import init
from sklearn.model_selection import train_test_split

X = np.linspace(-2, 2, 200).astype(np.float32)
np.random.shuffle(X)
X = X.reshape(200, 1)
y = 3.5*X + np.random.normal(0, 0.05, (200, 1)).astype(np.float32)

X_t, y_t = torch.from_numpy(X), torch.from_numpy(y)

dataset = Data.TensorDataset(X_t, y_t)
data_iter = Data.DataLoader(dataset, batch_size = 10, shuffle = True)

#定义网络结构,损失函数,优化器
class LinearNet(nn.Module):
    def __init__(self, inputs, outputs):
        super(LinearNet, self).__init__()
        self.linear = nn.Linear(inputs, outputs)
    def forward(self, x):
        y = self.linear(x)
        return y

model = LinearNet(1, 1)

criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.03)

#随机初始化参数
for params in model.parameters():
	init.normal_(params, mean = 0 , std = 0.01

#模型训练
for i in range(20):  
    for x_train, y_train in data_iter:
        y_hat = model(x_train)
        loss = criterion(y_hat, y_train)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    
    print("epochs :{}, loss :{}".format(i+1, loss.item()))
  • 分类
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

# Hyper-parameters 
input_size = 28 * 28    # 784
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001

# MNIST dataset (images and labels)
train_dataset = torchvision.datasets.MNIST(root='../../data', 
                                           train=True, 
                                           transform=transforms.ToTensor(),
                                           download=False)

test_dataset = torchvision.datasets.MNIST(root='../../data', 
                                          train=False, 
                                          transform=transforms.ToTensor())

# Data loader (input pipeline)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, 
                                           batch_size=batch_size, 
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset = test_dataset, 
                                          batch_size=batch_size, 
                                          shuffle=False)
                                          
model = LinearNet(input_size, num_classes)

# Loss and optimizer
# nn.CrossEntropyLoss() computes softmax internall
#交叉熵损失函数和softmax回归集合到一起了
#使用交叉熵的时候将标签转化成独热编码
criterion = nn.CrossEntropyLoss()  
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)  

#随机初始化参数
for params in model.parameters():
	init.normal_(params, mean = 0 , std = 0.01)

#模型训练
# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        # Reshape images to (batch_size, input_size)
        images = images.reshape(-1, input_size)
        
        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

#loss.item()去除loss函数的值        
        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, input_size)

        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum()

    print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))

PyTorch中,.data 仍保留,但建议使用 .detach(), 区别在于 :
.data 返回和 x 的相同数据 tensor, 但不会加入到x的计算历史里,且require s_grad = False, 这样有些时候是不安全的, 因为 x.data 不能被 autograd 追踪求微分 。
.detach() 返回相同数据的 tensor ,且 requires_grad=False ,但能通过 in-place 操作报告给 autograd 在进行反向传播的时候.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值