优化这段代码
时间: 2023-08-11 14:17:10 浏览: 47
好的,这里给出一个优化后的代码,主要针对特征选择、模型调参和结果输出进行了改进。
```python
# 导入所需库和数据
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import accuracy_score, classification_report
data = pd.read_csv('titanic.csv')
# 数据预处理
data['Age'].fillna(data['Age'].mean(), inplace=True)
data['Sex'] = (data['Sex'] == 'male').astype(int)
# 特征选择
X = data[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']]
y = data['Survived']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
# 模型训练和调参
param_grid = {
'max_depth': [3, 5, 7, 9],
'min_samples_split': [2, 4, 6, 8],
'min_samples_leaf': [1, 2, 3, 4]
}
clf = DecisionTreeClassifier(random_state=1)
grid_search = GridSearchCV(clf, param_grid, cv=5, n_jobs=-1, scoring='accuracy')
grid_search.fit(X_train, y_train)
# 预测测试集
y_pred = grid_search.predict(X_test)
# 评估模型
acc = accuracy_score(y_test, y_pred)
print('Accuracy:', acc)
print('Best parameters:', grid_search.best_params_)
print('Classification report:')
print(classification_report(y_test, y_pred))
```
改进的内容如下:
1. 特征选择增加了3个特征:SibSp(同行兄弟/配偶数)、Parch(同行父母/子女数)和Fare(票价)。
2. 模型训练和调参使用了`GridSearchCV`进行交叉验证和网格搜索,以寻找最优参数。
3. 评估模型使用了`classification_report`输出更详细的分类指标,包括准确率、召回率、F1分数和支持度等。
通过这些改进,可以提高模型的预测准确度,并且更全面地评估模型的性能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)