当前位置:网站首页>Pytorch deep learning practice lesson 8 importing data
Pytorch deep learning practice lesson 8 importing data
2022-07-25 03:29:00 【falldeep】
b Station Liu Er video , Address :
https://www.bilibili.com/video/BV1Y7411d7Ys?p=9&vd_source=79d752a233297190ff0b01ca81ccd878
Code ( Homework in class )
Or the binary classification of diabetes in last class , Four step construction
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
#-------------------------------------------step1 prepare data----------------------------------------
class Data(Dataset): # Construct your own class , Inherited from Dataset class
def __init__(self, filepath):
xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32)
# File path The separator in the data data type
self.len = xy.shape[0] # Return several rows and columns ( matrix )
self.x_data = torch.from_numpy(xy[:, :-1])# Take each line , Get to the last column
self.y_data = torch.from_numpy(xy[:, [-1]])# Take each line , Take the last column
def __getitem__(self, item): # Get a line of elements
return self.x_data[item], self.y_data[item]
def __len__(self):
return self.len
dataset = Data('diabetes.csv')
dataloader = DataLoader(dataset=dataset, batch_size=32, shuffle=True)
#------------------------------------------setp2 design model--------------------------------------------
class Modle(torch.nn.Module):
def __init__(self):
super(Modle, self).__init__()
self.linear1 = torch.nn.Linear(8, 6)
self.linear2 = torch.nn.Linear(6, 4)
self.linear3 = torch.nn.Linear(4, 1)
self.sigmoid = torch.nn.Sigmoid()
def forward(self, x):
x = self.sigmoid(self.linear1(x))
x = self.sigmoid(self.linear2(x))
x = self.sigmoid(self.linear3(x))
return x
model = Modle()
#---------------------------------------step3 constuct loss and optimizer-----------------------------
criteration = torch.nn.BCELoss(reduction='mean')#mean Calculating mean
optimizer = torch.optim.SGD(model.parameters(), lr=0.0001) # To update is model Parameters in , Learning rate
#---------------------------------------step4 traning cycle------------------------------------------
if __name__ == '__main__': # I want to write this
loss_lst = []
for epoch in range(1000):# Outer layer epoch It is a training that all data sets have been traversed
sum = 0#
for i, data in enumerate(dataloader, 0):# One at a time batch, From a part of the whole data set
inputs, lables = data#x y
y_pred = model(inputs)
loss = criteration(y_pred, lables)
sum += loss.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_lst.append(sum / dataloader.batch_size)
# visualization
num_lst = [i for i in range(len(loss_lst))]
plt.plot(num_lst, loss_lst)
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()
Running results
MINIST Data import
边栏推荐
- NVM installation and use
- Common methods of array
- Take a note: Oracle conditional statement
- Why does the legend of superstar (Jay Chou) not constitute pyramid selling? What is the difference between distribution and pyramid selling?
- Acwing 870. approximate number
- Detailed explanation of three factory modes
- Experience sharing of system architecture designers in preparing for the exam: how to prepare for the exam effectively
- Machine learning exercise 8 - anomaly detection and recommendation system (collaborative filtering)
- "Introduction to interface testing" punch in to learn day04: how to abstract the procedural test script into a test framework?
- Solve mysql5.6 database specified key was too long; Max key length is 767 bytes
猜你喜欢

Li Kou 343 integer partition dynamic programming

Machine learning exercise 8 - anomaly detection and recommendation system (collaborative filtering)

Message queue (MQ)

Stm32cubemx quadrature encoder

Day 10: BGP border gateway protocol
![[file upload] parse text files and store them in batches through JDBC connection (dynamic table creation and dynamic storage)](/img/9c/0305f7256ab6037d586c8940b9dc76.png)
[file upload] parse text files and store them in batches through JDBC connection (dynamic table creation and dynamic storage)

Hw2021 attack and defense drill experience - Insights

Force deduction problem 238. product of arrays other than itself

Import and export using poi

Use of stm32cubemonitor Part II - historical data storage and network access
随机推荐
[golang] golang realizes sending wechat service number template messages
How to use two stacks to simulate the implementation of a queue
Time complexity and space complexity
Moveit2 - 10.urdf and SRDF
Flowlayout in compose
Node queries the path of all files (files or folders) named filename under the target directory
Acwing 870. approximate number
Select sort / cardinality sort
Skywalking distributed link tracking, related graphics, DLJD, cat
Secondary vocational network security skills competition P100 dcore (light CMS system) SQL injection
Database transactions (often asked)
How is the virtual DOM different from the actual DOM?
Function method encapsulation -- mutual conversion of image types qpixmap, qimage and mat
Message queue (MQ)
Detailed explanation of three factory modes
Network security - comprehensive penetration test -cve-2018-10933-libssh maintain access
Chrome process architecture
Flink1.15 source code reading - Flink annotations
Why does the legend of superstar (Jay Chou) not constitute pyramid selling? What is the difference between distribution and pyramid selling?
Function of each layer of data warehouse
