当前位置:网站首页>Station B, Master Liu Er - dataset and data loading
Station B, Master Liu Er - dataset and data loading
2022-07-06 05:42:00 【Ning Ranye】
Series articles :
y_pred = model(x_data) yes Use all the data
Want to batch , Learn a few concepts 
import torch
from torch.utils.data import Dataset #Dataset Abstract subclass , Need to inherit
from torch.utils.data import DataLoader #DataLoade Used to load data

def getitem(self, index):
def len(self): Return the data set length
dataset = DiabetesDataset() structure DiabetesDataset object
train_loader = DataLoader(dataset=dataset,
batch_size=32,
shuffle=True,
num_workers=2) Initialize parameters
import numpy as np
import torch
import matplotlib.pyplot as plt
# Dataset Abstract class
from torch.utils.data import Dataset
# DataLoader Abstract class
from torch.utils.data import DataLoader
class LogisticRegressionModel(torch.nn.Module):
def __init__(self):
super(LogisticRegressionModel, self).__init__()
# Input dimensions 8 Output dimension 6
self.lay1 = torch.nn.Linear(8,6)
self.lay2 = torch.nn.Linear(6,4)
self.lay3 = torch.nn.Linear(4,1)
self.sigmod = torch.nn.Sigmoid()
def forward(self,x):
x = self.sigmod(self.lay1(x))
x = self.sigmod(self.lay2(x))
x = self.sigmod(self.lay3(x))
return x
class DiabetesDataset(Dataset):
def __init__(self, filepath):
xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32)
self.len = xy.shape[0]
self.x_data = torch.from_numpy(xy[:,:-1])
self.y_data = torch.from_numpy(xy[:, [-1]])
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
def __len__(self):
return self.len
dataset = DiabetesDataset("./datasets/diabetes.csv.gz")
train_loader = DataLoader(dataset=dataset, batch_size=32, shuffle=True)
model = LogisticRegressionModel()
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=0.005)
epoch_list = []
loss_list = []
for epoch in range(100):
for i, data in enumerate(train_loader, 0):
# 1- Load data
inputs, label = data
# 2-forward
y_pred = model(inputs)
loss = criterion(y_pred, label)
epoch_list.append(epoch)
loss_list.append(loss.item())
optimizer.zero_grad()
# 3- Back propagation
loss.backward()
# Update
optimizer.step()
plt.plot(epoch_list, loss_list)
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()

MNIST Dataset import
import torch
from torch.utils.data import DataLoader,Dataset
from torchvision import datasets,transforms
train_dataset = datasets.MNIST(root='./datasets/mnist', train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = datasets.MNIST(root='./datasets/mnist', train=False,
transform=transforms.ToTensor(),
download=True)
train_loader = DataLoader(dataset=datasets, batch_size=32,
shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=32,
shuffle=False)
for batch_idx, (inouts, target) in enumerate(test_loader):
pass
边栏推荐
- 29io stream, byte output stream continue write line feed
- JS array list actual use summary
- 实践分享:如何安全快速地从 Centos迁移到openEuler
- How to use PHP string query function
- 自建DNS服务器,客户端打开网页慢,解决办法
- B站刘二大人-Softmx分类器及MNIST实现-Lecture 9
- AUTOSAR从入门到精通番外篇(十)-嵌入式S19文件解析
- B站刘二大人-多元逻辑回归 Lecture 7
- Vulhub vulnerability recurrence 71_ Unomi
- [experience] when ultralso makes a startup disk, there is an error: the disk / image capacity is too small
猜你喜欢

Analysis of grammar elements in turtle Library

嵌入式面试题(四、常见算法)

Download, install and use NVM of node, and related use of node and NRM

29io stream, byte output stream continue write line feed

Promise summary

What preparations should be made for website server migration?

初识CDN

Deep learning -yolov5 introduction to actual combat click data set training

28io stream, byte output stream writes multiple bytes

Questions d'examen écrit classiques du pointeur
随机推荐
[QNX hypervisor 2.2 user manual]6.3.3 using shared memory (shmem) virtual devices
ARTS Week 25
Deep learning -yolov5 introduction to actual combat click data set training
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Sequoiadb Lake warehouse integrated distributed database, June 2022 issue
What impact will frequent job hopping have on your career?
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
First knowledge database
Jvxetable implant j-popup with slot
Safe mode on Windows
js Array 列表 实战使用总结
Unity gets the width and height of Sprite
Easy to understand IIC protocol explanation
初识数据库
[force buckle]43 String multiplication
SQLite add index
Download, install and use NVM of node, and related use of node and NRM
Rustdesk builds its own remote desktop relay server
嵌入式面试题(四、常见算法)
Questions d'examen écrit classiques du pointeur