python - 创建内存高效的神经网络
问题描述
我在 python 上创建了一个神经网络,我的问题是一个非常简单的分类问题,我使用的是 Leaky ReLu 网络,它的主要目标是过度拟合一组数据点。在我处理小数据点之前,如果我一次提供所有数据,我的网络会非常快。现在,我的电脑无法一次完成所有操作。所以我决定将整个数据集的小批量提供给它,现在它可以工作了。现在我有几个问题:
如果我以前使用过损失函数,我应该使用相同的吗?(就我而言,我正在使用
BCEWithLogitsLoss
)。我问这个是因为我在每批中都得到了非常奇怪的损失值。例如,在我进行批量更改之前,损失函数变得非常小,例如没有批量的模型中的 0.005。要真正的大。我的输入数据点大小
310000 x 3
或多或少。小批量是正确的方法吗?或者是否有另一个技巧来解决这个问题。既然我已经训练了数据,我是否已经以相同的方式评估了训练后的模型(即分批,这样我的 GPU 上的内存就不会用完)?
这是我的代码:
class CustomDataset(Dataset):
def __init__(self, x_tensor, y_tensor):
self.x = x_tensor
self.y = y_tensor
def __getitem__(self, index):
return (self.x[index], self.y[index])
def __len__(self):
return len(self.x)
class LabelData(Dataset):
def __init__(self, y_tensor):
self.y = y_tensor
def __getitem__(self, index):
return (self.y[index])
def __len__(self):
return len(self.y)
#X, order = common.loadplanes()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
Samples, Ocupancy = common.load_samples()
x_test = torch.from_numpy(Samples.astype(np.float32)).to(device)
y_test = torch.from_numpy(Ocupancy.astype(np.float32)).to(device)
train_data = CustomDataset(x_test, y_test)
train_loader = DataLoader(dataset=train_data, batch_size= 1000, shuffle=False) # Make bigger batches
phi = common.MLP(3, 1).to(device)
criterion = torch.nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(phi.parameters(), lr = 0.01)
epoch = 512
fit_start_time = time.time()
for epoch in range(epoch):
for x_batch, y_batch in train_loader:
optimizer.zero_grad()
x_batch = x_batch.to(device)
y_batch = y_batch.to(device)
y_pred = phi(x_batch)
# Compute Loss
loss = criterion(y_pred.squeeze(), y_batch.squeeze())
print('Epoch {}: train loss: {}'.format(epoch, loss.item())) # Backward pass
loss.backward()
optimizer.step()
fit_end_time = time.time()
print("Total time = %f" % (fit_end_time - fit_start_time))
X,Y,Z = np.mgrid[-3000:300:80,-3000:3000:80,-3000:3000:80]
xyz = torch.from_numpy(np.vstack([X.ravel(), Y.ravel(),Z.ravel()]).transpose().astype(np.float32))
# feed the network bit by bit?
xyz = LabelData(xyz)
labels = phi(xyz).to(device)
visualization_iso(X,Y,Z,labels)
我在写这篇文章时仍在运行我的代码,但我可以想象在模型训练后会出现错误,也就是说我的内存已经用完了(这就是为什么我我问第三个问题)或者我正在错误地评估我的网络,编辑它似乎我正在错误地评估模型,你可以在下面看到我的错误。如果我没有使用任何常见做法,或者您发现我的代码中有任何市长缺陷,请告诉我。
解决方案
推荐阅读
- c++ - 修改指针值
- sql - 如何在 BigQuery 中手动查询缓存表
- csv - 使用 Cassava 和 Attoparsec 解析自定义字段
- javascript - 问:常规垂直 ul 但 li 元素水平排序
- html - 使用 R Markdown 的 YAML 编写的代码添加徽标图像
- reactjs - 如何在不修改原始数据的情况下编辑 Gatsby GraphQL 数据
- javascript - Chrome 扩展开发:chrome.storage.local vs Indexeddb
- javascript - 如何访问对象的名称属性
- wordpress - wordpress 更新永久链接结构
- ruby-on-rails - Ruby on Rails:rails g 脚手架不生成任何视图