ANN预测泰坦尼克号生存分类代码
时间: 2023-08-15 17:03:19 浏览: 115
以下是使用Python和Keras库实现的ANN预测泰坦尼克号生存分类的代码示例:
```python
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv('train.csv')
# 数据预处理和特征工程
data.drop(['PassengerId','Name','Ticket','Cabin'], axis=1, inplace=True)
data['Age'].fillna(data['Age'].median(), inplace=True)
data['Embarked'].fillna(data['Embarked'].mode()[0], inplace=True)
data = pd.get_dummies(data, columns=['Sex','Embarked'])
X = data.drop('Survived', axis=1)
y = data['Survived']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 构建ANN模型
model = Sequential()
model.add(Dense(12, input_dim=X_train.shape[1], activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=150, batch_size=10, verbose=0)
# 评估模型
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
```
注:以上代码仅为示例,实际应用中还需要进行更多的数据处理和模型调参。
阅读全文