RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase.
最好加一个if语句:if __name__ == '__main__':
。# prepare dataset
class DiabetesDataset(Dataset):
def __init__(self, filepath):
xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32)#导入数据集
self.len = xy.shape[0] # shape(行,列)shape[0]:获取行数
self.x_data = torch.from_numpy(xy[:, :-1])#获取前8列数据x
self.y_data = torch.from_numpy(xy[:, [-1]])#获取最后一列数据y
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]#返回索引
def __len__(self):
return self.len#返回数据长度
dataset = DiabetesDataset('diabetes.csv')#读取数据
#加载数据
train_loader = DataLoader(dataset=dataset, batch_size=32, shuffle=True, num_workers=4) # num_workers 多线程
if __name__ == '__main__':
for epoch in range(100):
for i, data in enumerate(train_loader, 0): # train_loader 是先shuffle后mini_batch
inputs, labels = data
#每次获取一个(x[i],y[i]),然后拼接成一个矩阵X,Y,DataLoader会自动把数据转化为Tensor
y_pred = model(inputs)
loss = criterion(y_pred, labels)
print(epoch, i, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
同样是四步走:
请先尝试自己写!(其实就是第一步、第四步有所改动)
import torch
import numpy as np
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
# prepare dataset
class DiabetesDataset(Dataset):
def __init__(self, filepath):
xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32)#导入数据集
self.len = xy.shape[0] # shape(行,列)shape[0]:获取行数
self.x_data = torch.from_numpy(xy[:, :-1])#获取前8列数据x
self.y_data = torch.from_numpy(xy[:, [-1]])#获取最后一列数据y
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]#返回索引
def __len__(self):
return self.len#返回数据长度
dataset = DiabetesDataset('diabetes.csv')#读取数据
#加载数据
train_loader = DataLoader(dataset=dataset, batch_size=32, shuffle=True, num_workers=4) # num_workers 多线程
# design model using class
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()
# construct loss and optimizer
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# training cycle forward, backward, update
if __name__ == '__main__':
for epoch in range(100):
for i, data in enumerate(train_loader, 0): # train_loader 是先shuffle后mini_batch
inputs, labels = data
#每次获取一个(x[i],y[i]),然后拼接成一个矩阵X,Y,DataLoader会自动把数据转化为Tensor
y_pred = model(inputs)
loss = criterion(y_pred, labels)
print(epoch, i, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
请使用MNIST数据集构建一个线性模型分类器
MNIST数据集的使用
kaggle是一个数据竞赛网站,提供了很多数据集和解决方案,可以在上面提交代码。