数据的读取方式
1、如果数据量比较小,直接读入内存,通过data[i]获取
2、如果数据量很大,我们不能直接读入内存,比如数据有很多文件,我们可以将文件名存储到一个文件,通过names[i]获取文件名,然后再去读取数据
dataloader加载器
多线程的错误问题
在linux多线程是通过fork创建的,但是在windows是通过spawn创建的,所以会出现运行时错误。
解决方法是将代码写入if-else语句,而不是直接写在for循环
即下面这种形式
点击查看代码
import torch
import numpy as np
from torch.utils.data import Dataset, DataLoader
class DiabetesDataset(Dataset):
def __init__(self, filePath):
xy = np.loadtxt(filePath, delimiter=',', dtype=np.float32)
self.x_data = torch.from_numpy(xy[:, :-1])
self.y_data = torch.from_numpy(xy[:, [-1]])
self.len = xy.shape[0]
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
def __len__(self):
return self.len
dataset = DiabetesDataset('diabetes.csv.gz') # 创建dataset
train_loader = DataLoader(dataset=dataset, batch_size=32, shuffle=True, num_workers=2)
class Model(torch.nn.Module):
def __init__(self):
super(Model, 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 = Model()
criterion = torch.nn.BCELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
if __name__ == '__main__':
for epoch in range(100):
for i, data in enumerate(train_loader, 0):
inputs, labels = data
y_pred = model(inputs)
loss = criterion(y_pred, labels)
print('epoch: ', epoch, 'i: ', i, 'loss: ', loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()