The sinking of the Titanic is one of the most infamous shipwrecks in history. On April 15, 1912, during her maiden voyage, the widely considered “unsinkable” RMS Titanic sank after colliding with an iceberg. Unfortunately, there weren’t enough lifeboats for everyone onboard, resulting in the death of 1502 out of 2224 passengers and crew.While there was some element of luck involved in surviving, it seems some groups of people were more likely to survive than others.
if __name__ == '__main__': testdata_preprocessed() data_preprocessed()
''' 采用pandas和numpy对数据集进行预处理,将其分别保存在对应的csv文件中。 '''
对数据进行预处理后,开始编写主程序构建预测模型。
导入相应模块
1 2 3 4
import numpy as np import pandas as pd import torch import matplotlib.pyplot as plt
编写神经网络模型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classNet(torch.nn.Module): def__init__(self, n_feature, n_hidden, n_hidden2, n_hidden3, n_output): super().__init__() self.feature = torch.nn.Linear(n_feature, n_hidden) self.layer = torch.nn.Linear(n_hidden, n_hidden2) self.layer2 = torch.nn.Linear(n_hidden2, n_hidden3) self.predict = torch.nn.Linear(n_hidden3, n_output) defforward(self, x): x = torch.sigmoid(self.feature(x)) x = torch.sigmoid(self.layer(x)) x = torch.sigmoid(self.layer2(x)) x = torch.sigmoid(self.predict(x)) return x ''' 构建一层输入层,两层隐含层,一层输出层。全部采用sigmoid激活函数连接层。 '''
加载数据集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defdata_handling(): data_preprocessed() data = np.loadtxt('train.csv', delimiter=',', dtype=np.float32) x = torch.from_numpy(data[:, :-1]) y = torch.from_numpy(data[:, [-1]])