当前位置:网站首页>《PyTorch深度学习实践》第八课导入数据
《PyTorch深度学习实践》第八课导入数据
2022-07-19 22:31:00 【falldeep】
b站刘二视频,地址:
https://www.bilibili.com/video/BV1Y7411d7Ys?p=9&vd_source=79d752a233297190ff0b01ca81ccd878
代码(课中作业)
还是上节课的糖尿病的二元分类问题,四步法构造
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): #构造自己的类,继承自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, item): #获取某一行元素
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求均值
optimizer = torch.optim.SGD(model.parameters(), lr=0.0001) #要更新的是model中的参数, 学习率
#---------------------------------------step4 traning cycle------------------------------------------
if __name__ == '__main__': #要写这个
loss_lst = []
for epoch in range(1000):#外层epoch是所有数据集都遍历过的一次训练
sum = 0#
for i, data in enumerate(dataloader, 0):#一次是一个batch,从整个数据集中的一部分
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)
#可视化
num_lst = [i for i in range(len(loss_lst))]
plt.plot(num_lst, loss_lst)
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()
运行结果
MINIST数据导入
边栏推荐
- Makefile实现编译时间统计
- 应急响应 >> 基础技能与工具
- 132天...从电子厂流水线走到了高薪程序员
- 都说软件测试有手就行,但为何仍有这么多劝退的?
- 跳槽了...历经字节测试岗3轮面试,4个小时灵魂拷问,结局透心凉...
- In the computer mainframe, just press the power on button (on ()) of the host to call the startup methods of other hardware devices and software, such as memory self-test (check ()), CPU operation (ru
- How to use sublime text to open MD instead of typora
- Emergency response > > basic skills and tools
- 51单片机测量方波信号周期
- AIOps 还是 APM,企业用户应如何作出选择?
猜你喜欢
本轮牛市下半场的行情走势分析?2021-04-07
高数 | 【多元函数微分学 计算篇】链式求导法、隐函数求导法、全微分形式不变性、多元函数求极值
Request method ‘POST‘ not supported。 Failed to load resource: net::ERR_FAILED
趣店预制菜品牌战略发布会
DNS域名解析服务
Unity_同个材质多个颜色内存优化——使用MaterialPropertyBlock
费解的开关
Successfully solved @keyup Enter= "search()" problems that do not take effect in the El input component
226. 翻转二叉树-dfs法
教你使用CANN将照片一键转换成卡通风格
随机推荐
微服务架构 | 链路追踪 - [Sleuth]
对本轮行情发展的回顾和思考 2021-04-05
DNS域名解析服务
Digital transformation towards deep water: the banking industry continues to consolidate its scientific and technological foundation
异地在网上股票开户安全吗?
Do you really understand continuous integration (CI)?
ECCV 2022 | 重新思考Vision Transformers中用于数据增强的图像混合
函数入门
牛市当头,目前还能不能买入?2021-04-09
RPC如何实现超时重试
In the computer mainframe, just press the power on button (on ()) of the host to call the startup methods of other hardware devices and software, such as memory self-test (check ()), CPU operation (ru
Musk responded whether he would upload his brain to the cloud: already did it!
Take the first place in the International Olympic Games in mathematics, physics and chemistry, and win all the gold medals. Netizen: the Chinese team is too good
Communication project based on bio mode
JVM memory model
趣店预制菜品牌战略发布会
面试题 05.06. 整数转换
【C】「#define」
ECCV 2022 | 基于关系推理的语义新颖性检测
There is still a lot of room for innovation in defi, and high-quality projects will appear in the future 2021-04-13