当前位置:网站首页>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
边栏推荐
- 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
- Processes and threads
- Selective parameters in MATLAB functions
- [email protected]树莓派
- 初识CDN
- Installation de la Bibliothèque de processus PDK - csmc
- Vulhub vulnerability recurrence 67_ Supervisor
- What preparations should be made for website server migration?
- Algorithm -- climbing stairs (kotlin)
- Promise summary
猜你喜欢

Codeforces Round #804 (Div. 2) Editorial(A-B)

02. 开发博客项目之数据存储
![[experience] install Visio on win11](/img/f5/42bd597340d0aed9bfd13620bb0885.png)
[experience] install Visio on win11

自建DNS服务器,客户端打开网页慢,解决办法
![[Jiudu OJ 07] folding basket](/img/a7/e394f32cf7f02468988addad67674b.jpg)
[Jiudu OJ 07] folding basket

Node 之 nvm 下载、安装、使用,以及node 、nrm 的相关使用

【经验】win11上安装visio

29io stream, byte output stream continue write line feed

A master in the field of software architecture -- Reading Notes of the beauty of Architecture

Garbage collector with serial, throughput priority and response time priority
随机推荐
Cuda11.1 online installation
什么是独立IP,独立IP主机怎么样?
MySQL advanced learning summary 9: create index, delete index, descending index, and hide index
Selective parameters in MATLAB functions
First knowledge database
[detailed explanation of Huawei machine test] check whether there is a digital combination that meets the conditions
2022 half year summary
Codeforces Round #804 (Div. 2) Editorial(A-B)
27io stream, byte output stream, OutputStream writes data to file
Zoom and pan image in Photoshop 2022
HAC cluster modifying administrator user password
Vulhub vulnerability recurrence 73_ Webmin
Application Security Series 37: log injection
B站刘二大人-数据集及数据加载 Lecture 8
B站刘二大人-线性回归及梯度下降
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
How to download GB files from Google cloud hard disk
Pytorch代码注意的细节,容易敲错的地方
[string] palindrome string of codeup
Pointer classic written test questions