defforward(self, x): x = self.sigmoid(self.linear1(x)) x = self.sigmoid(self.linear2(x)) return x
defverify(self): val_correct, total = 0, 0 with torch.no_grad(): for i, data inenumerate(train_loader, 0): inputs, label = data predicted = model.predict(inputs) total += label.size(0) val_correct += (predicted == np.array(label)).sum() print('Accuracy: %d' %(val_correct / total * 100))
defpredict(self, x): ## 该函数用在测试集过程,因此只有前馈,没有什么 with torch.no_grad(): x = self.sigmoid(self.linear1(x)) x = self.sigmoid(self.linear2(x)) y = [] for result in x: if result > 0.5: y.append(1) else: y.append(0) return y
if __name__ == '__main__': for epoch inrange(100): for i, data inenumerate(train_loader, 0): inputs, label = data y_pred = model(inputs) y_pred = y_pred.squeeze(-1) ## 将维度降至1维并输出出来 loss = criterion(y_pred, label) ## 将预测的值与标签进行比较,并求解出误差值 print(epoch, i, loss.item())
defverify(self): val_correct, total = 0, 0 with torch.no_grad(): for i, data inenumerate(train_loader, 0): inputs, label = data predicted = model(inputs) total += label.size(0) val_correct += (predicted == label).sum().item() print('Accuracy: %d %%' %(val_correct / total * 100))
defpredict(self, x): ## 该函数用在测试集过程,因此只有前馈,没有什么 with torch.no_grad(): x = self.sigmoid(self.linear1(x)) x = self.sigmoid(self.linear2(x)) y = [] for result in x: if result > 0.5: y.append(1) else: y.append(0) return y
test_data = pd.read_csv(r'./titanic/test.csv') features = ["Pclass", "Sex", "SibSp", "Parch", "Fare"] test = torch.from_numpy(np.array(pd.get_dummies(test_data[features]), dtype=np.float32))
result = model.predict(test)
submission = pd.read_csv(r'./titanic/gender_submission.csv') submission['Survived'] = result submission.to_csv(r'./titanic/gender_submission_result_1.csv', index=False)