当前位置:网站首页>Exemple complet d'enregistrement du modèle pytoch + enregistrement du modèle pytoch seuls les paramètres d'entraînement sont - ils enregistrés? Oui (+ Solution)
Exemple complet d'enregistrement du modèle pytoch + enregistrement du modèle pytoch seuls les paramètres d'entraînement sont - ils enregistrés? Oui (+ Solution)
2022-07-02 19:55:00 【Fakeoccupational】
Le test utilise unliner model,Il y a d'autres questions.pytorch Enregistrer le modèle enregistrer seulement les paramètres d'entraînement?
saveModèle
# Importer des paquets
import glob
import os
import torch
import matplotlib.pyplot as plt
import random #Utilisé par l'Itérateur de données pour générer des données aléatoires
# Générer un ensemble de données x1Catégorie0,x2Catégorie1
n_data = torch.ones(50, 2) # Forme de base des données
x1 = torch.normal(2 * n_data, 1) # shape=(50, 2)
y1 = torch.zeros(50) # Type0 shape=(50, 1)
x2 = torch.normal(-2 * n_data, 1) # shape=(50, 2)
y2 = torch.ones(50) # Type1 shape=(50, 1)
# Attention! x, y Les données doivent être présentées sous la forme suivante(torch.catEst de fusionner les données)
x = torch.cat((x1, x2), 0).type(torch.FloatTensor) y = torch.cat((y1, y2), 0).type(torch.FloatTensor) # Visualisation des ensembles de données plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn') plt.show() # Lecture des données: def data_iter(batch_size, x, y): num_examples = len(x) indices = list(range(num_examples))
random.shuffle(indices) # L'ordre de lecture des échantillons est aléatoire
for i in range(0, num_examples, batch_size):
j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) #Peut - être moins d'une dernière foisbatch
yield x.index_select(0, j), y.index_select(0, j)
#############################################################################################################
def saver(model_state_dict, optimizer_state_dict, model_path, epoch, max_to_save=30):
total_models = glob.glob(model_path + '*')
if len(total_models) >= max_to_save:
total_models.sort()
os.remove(total_models[0])
state_dict = {
}
state_dict["model_state_dict"] = model_state_dict
state_dict["optimizer_state_dict"] = optimizer_state_dict
torch.save(state_dict, model_path + 'h' + str(epoch))
print('models {} save successfully!'.format(model_path + 'hahaha' + str(epoch)))
################################################################################################################
import torch.nn as nn
import torch.optim as optim
class net(nn.Module):
def __init__(self, **kwargs):
super(net, self).__init__(**kwargs)
self.net = nn.Sequential(nn.Linear(2, 1), nn.ReLU())
def forward(self, x):
return self.net(x)
def loss(y_hat, y):
return (y_hat - y.view(y_hat.size())) ** 2 / 2
def accuracy(y_hat, y): #@save
"""Calculer la quantité correcte prévue."""
cmp = y_hat.type(y.dtype) > 0.5 # Plus grand que0.5Catégorie1
result=cmp.type(y.dtype)
acc = 1-float(((result-y).sum())/ len(y))
return acc;
lr = 0.03
num_epochs = 3 # Nombre d'Itérations
batch_size = 10 # Taille du lot
model = net()
params = list(model.parameters())
optimizer = torch.optim.Adam(params, 1e-4)
for epoch in range(num_epochs):
for X, y_train in data_iter(batch_size, x, y):
optimizer.zero_grad()
l = loss(model(X), y_train).sum() # l Il s'agit de petits lots XEtyPerte de
l.backward(retain_graph=True)
optimizer.step()
print(l)
saver(model.state_dict(), optimizer.state_dict(), "./", epoch + 1, max_to_save=100)
loadModèle
# Importer des paquets
import glob
import os
import torch
import matplotlib.pyplot as plt
import random #Utilisé par l'Itérateur de données pour générer des données aléatoires
# Générer un ensemble de données x1Catégorie0,x2Catégorie1
n_data = torch.ones(50, 2) # Forme de base des données
x1 = torch.normal(2 * n_data, 1) # shape=(50, 2)
y1 = torch.zeros(50) # Type0 shape=(50, 1)
x2 = torch.normal(-2 * n_data, 1) # shape=(50, 2)
y2 = torch.ones(50) # Type1 shape=(50, 1)
# Attention! x, y Les données doivent être présentées sous la forme suivante(torch.catEst de fusionner les données)
x = torch.cat((x1, x2), 0).type(torch.FloatTensor) y = torch.cat((y1, y2), 0).type(torch.FloatTensor) # Visualisation des ensembles de données plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn') plt.show() # Lecture des données: def data_iter(batch_size, x, y): num_examples = len(x) indices = list(range(num_examples))
random.shuffle(indices) # L'ordre de lecture des échantillons est aléatoire
for i in range(0, num_examples, batch_size):
j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) #Peut - être moins d'une dernière foisbatch
yield x.index_select(0, j), y.index_select(0, j)
#############################################################################################################
def saver(model_state_dict, optimizer_state_dict, model_path, epoch, max_to_save=30):
total_models = glob.glob(model_path + '*')
if len(total_models) >= max_to_save:
total_models.sort()
os.remove(total_models[0])
state_dict = {
}
state_dict["model_state_dict"] = model_state_dict
state_dict["optimizer_state_dict"] = optimizer_state_dict
torch.save(state_dict, model_path + 'h' + str(epoch))
print('models {} save successfully!'.format(model_path + 'hahaha' + str(epoch)))
################################################################################################################
import torch.nn as nn
import torch.optim as optim
class net(nn.Module):
def __init__(self, **kwargs):
super(net, self).__init__(**kwargs)
self.net = nn.Sequential(nn.Linear(2, 1), nn.ReLU())
def forward(self, x):
return self.net(x)
def loss(y_hat, y):
return (y_hat - y.view(y_hat.size())) ** 2 / 2
def accuracy(y_hat, y): #@save
"""Calculer la quantité correcte prévue."""
cmp = y_hat.type(y.dtype) > 0.5 # Plus grand que0.5Catégorie1
result=cmp.type(y.dtype)
acc = 1-float(((result-y).sum())/ len(y))
return acc;
lr = 0.03
num_epochs = 3 # Nombre d'Itérations
batch_size = 10 # Taille du lot
model = net()
params = list(model.parameters())
optimizer = torch.optim.Adam(params, 1e-4)
# for epoch in range(num_epochs):
# for X, y_train in data_iter(batch_size, x, y):
# optimizer.zero_grad()
# l = loss(model(X), y_train).sum() # l Il s'agit de petits lots XEtyPerte de
# l.backward(retain_graph=True)
# optimizer.step()
# print(l)
# saver(model.state_dict(), optimizer.state_dict(), "./", epoch + 1, max_to_save=100)
def loader(model_path):
state_dict = torch.load(model_path)
model_state_dict = state_dict["model_state_dict"]
optimizer_state_dict = state_dict["optimizer_state_dict"]
return model_state_dict, optimizer_state_dict
model_state_dict, optimizer_state_dict = loader("h1")
model.load_state_dict(model_state_dict)
optimizer.load_state_dict(optimizer_state_dict)
print('pretrained models loaded!')
pytorch Enregistrer le modèle enregistrer seulement les paramètres d'entraînement?- Oui.
class net(nn.Module):
def __init__(self, **kwargs):
super(net, self).__init__(**kwargs)
self.net = nn.Sequential(nn.Linear(2, 1), nn.ReLU())
self.notrain= torch.rand((64, 64), dtype=torch.float)
def forward(self, x):
return self.net(x)

Solutions
class net(nn.Module):
def __init__(self, **kwargs):
super(net, self).__init__(**kwargs)
self.net = nn.Sequential(nn.Linear(2, 1), nn.ReLU())
# self.notrain = torch.rand((64, 64), dtype=torch.float)
self.notrain = torch.nn.Parameter(torch.ones(64, 64))
def forward(self, x):
return self.net(x)
for epoch in range(num_epochs):
for X, y_train in data_iter(batch_size, x, y):
optimizer.zero_grad()
l = loss(model(X), y_train).sum() # l Il s'agit de petits lots XEtyPerte de
l.backward(retain_graph=True)
optimizer.step()
print(l)
model.notrain.data = model.notrain.data+2
saver(model.state_dict(), optimizer.state_dict(), "./", epoch + 1, max_to_save=100)
Référence et plus
PyTorch DataLoaderDebug :Aléatoiremask Ou une sélection aléatoire des données bug
边栏推荐
- Think about the huge changes caused by variables
- [daily question] 241 Design priorities for operational expressions
- Shardingsphere jdbc5.1.2 about select last_ INSERT_ ID () I found that there was still a routing problem
- Embedded (PLD) series, epf10k50rc240-3n programmable logic device
- One side is volume, the other side is layoff. There are a lot of layoffs in byte commercialization department. What do you think of this wave?
- R语言使用econocharts包创建微观经济或宏观经济图、indifference函数可视化无差异曲线(indifference curve)
- Esp32c3 crash analysis
- GCC: Graph Contrastive Coding for Graph Neural NetworkPre-Training
- Google Earth Engine(GEE)——Landsat 9影像全波段影像下载(北京市为例)
- upload-labs
猜你喜欢

CS5268完美代替AG9321MCQ Typec多合一扩展坞方案

攻防世界pwn题:Recho

API文档工具knife4j使用详解

AcWing 1126. Minimum cost solution (shortest path Dijkstra)

Istio1.12:安装和快速入门

RPD出品:Superpower Squad 保姆级攻略

嵌入式(PLD) 系列,EPF10K50RC240-3N 可编程逻辑器件

励志!大凉山小伙全奖直博!论文致谢看哭网友

KT148A语音芯片使用说明、硬件、以及协议、以及常见问题,和参考代码

Py's interpret: a detailed introduction to interpret, installation, and case application
随机推荐
CRM客户关系管理系统
Kt148a voice chip instructions, hardware, protocols, common problems, and reference codes
[JS] get the search parameters of URL in hash mode
Data Lake (XII): integration of spark3.1.2 and iceberg0.12.1
Kt148a voice chip IC software reference code c language, first-line serial port
高并发下如何避免产生重复数据?
450 Shenxin Mianjing 1
Conscience summary! Jupyter notebook from Xiaobai to master, the nanny tutorial is coming!
at编译环境搭建-win
功能、作用、效能、功用、效用、功效
励志!大凉山小伙全奖直博!论文致谢看哭网友
Istio部署:快速上手微服务,
NMF-matlab
从20s优化到500ms,我用了这三招
[NLP] a detailed generative text Abstract classic paper pointer generator
How to avoid duplicate data in gaobingfa?
八年测开经验,面试28K公司后,吐血整理出高频面试题和答案
What is the Bluetooth chip ble, how to select it, and what is the path of subsequent technology development
What are the benefits of multi terminal applet development? Covering Baidu applet, Tiktok applet, wechat applet development, and seizing the multi platform traffic dividend
Solution: vs2017 cannot open the source file stdio h main. H header document [easy to understand]