当前位置:网站首页>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
边栏推荐
- 【华为机试真题详解】统计射击比赛成绩
- 【torch】|torch.nn.utils.clip_grad_norm_
- How to download GB files from Google cloud hard disk
- 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
- Vulhub vulnerability recurrence 72_ uWSGI
- 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
- 类和对象(一)this指针详解
- Pytorch代码注意的细节,容易敲错的地方
- 29io stream, byte output stream continue write line feed
- Zoom and pan image in Photoshop 2022
猜你喜欢
进程和线程
Text classification still stays at Bert? The dual contrast learning framework is too strong
[SQL Server fast track] - authentication and establishment and management of user accounts
Safe mode on Windows
Installation de la Bibliothèque de processus PDK - csmc
Vulhub vulnerability recurrence 71_ Unomi
59. Spiral matrix
Sword finger offer II 039 Maximum rectangular area of histogram
数字经济破浪而来 ,LTD是权益独立的Web3.0网站?
- [email protected]树莓派"/>
[email protected]树莓派
随机推荐
P2802 回家
UCF(暑期团队赛二)
Vulhub vulnerability recurrence 72_ uWSGI
AUTOSAR从入门到精通番外篇(十)-嵌入式S19文件解析
Jushan database appears again in the gold fair to jointly build a new era of digital economy
Download, install and use NVM of node, and related use of node and NRM
Note the various data set acquisition methods of jvxetable
Check the useful photo lossless magnification software on Apple computer
[JVM] [Chapter 17] [garbage collector]
[machine learning notes] univariate linear regression principle, formula and code implementation
Summary of deep learning tuning tricks
Vulhub vulnerability recurrence 69_ Tiki Wiki
Game push: image / table /cv/nlp, multi-threaded start!
[Jiudu OJ 08] simple search x
初识CDN
How to get list length
Node 之 nvm 下载、安装、使用,以及node 、nrm 的相关使用
Installation de la Bibliothèque de processus PDK - csmc
[detailed explanation of Huawei machine test] check whether there is a digital combination that meets the conditions
The digital economy has broken through the waves. Is Ltd a Web3.0 website with independent rights and interests?