1.利用随机森林求出Titanic数据集的训练集及测试集预测准确率。 2.跑出影响因素的重要性排序图。 3.跑出随机森林收敛图。 4.将代码列出。
时间: 2024-02-29 15:52:40 浏览: 65
很抱歉,作为一名语言模型AI,我并不能直接使用代码运行程序。但是我可以告诉你如何用Python的scikit-learn库实现这些功能。
1. 利用随机森林求出Titanic数据集的训练集及测试集预测准确率:
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pandas as pd
# 读取数据集
titanic_data = pd.read_csv('titanic.csv')
# 数据预处理
titanic_data['Age'].fillna(titanic_data['Age'].mean(), inplace=True)
titanic_data.drop(['Cabin', 'Name', 'Ticket', 'PassengerId'], axis=1, inplace=True)
titanic_data = pd.get_dummies(titanic_data, columns=['Sex', 'Embarked'], drop_first=True)
# 分离特征和目标变量
X = titanic_data.drop('Survived', axis=1)
y = titanic_data['Survived']
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练随机森林模型
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
# 预测测试集
y_pred = rf.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
2. 跑出影响因素的重要性排序图:
```python
import matplotlib.pyplot as plt
# 得到特征重要性
importance = rf.feature_importances_
features = X.columns
# 将特征重要性排序
indices = importance.argsort()[::-1]
# 绘制重要性排序图
plt.title('Feature Importance')
plt.bar(range(X.shape[1]), importance[indices])
plt.xticks(range(X.shape[1]), features[indices], rotation=90)
plt.show()
```
3. 跑出随机森林收敛图:
```python
import numpy as np
# 记录训练集和测试集的误差
train_errors = []
test_errors = []
# 尝试多个树的数量
trees_range = range(10, 500, 10)
for trees in trees_range:
rf = RandomForestClassifier(n_estimators=trees, random_state=42)
rf.fit(X_train, y_train)
# 计算训练集误差
train_pred = rf.predict(X_train)
train_errors.append(1 - accuracy_score(y_train, train_pred))
# 计算测试集误差
test_pred = rf.predict(X_test)
test_errors.append(1 - accuracy_score(y_test, test_pred))
# 绘制误差随树的数量变化的图
plt.plot(trees_range, train_errors, label='Train Error')
plt.plot(trees_range, test_errors, label='Test Error')
plt.legend()
plt.xlabel('Number of Trees')
plt.ylabel('Error')
plt.show()
```
4. 代码列出:
```python
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
# 读取数据集
titanic_data = pd.read_csv('titanic.csv')
# 数据预处理
titanic_data['Age'].fillna(titanic_data['Age'].mean(), inplace=True)
titanic_data.drop(['Cabin', 'Name', 'Ticket', 'PassengerId'], axis=1, inplace=True)
titanic_data = pd.get_dummies(titanic_data, columns=['Sex', 'Embarked'], drop_first=True)
# 分离特征和目标变量
X = titanic_data.drop('Survived', axis=1)
y = titanic_data['Survived']
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练随机森林模型
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
# 预测测试集
y_pred = rf.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# 得到特征重要性
importance = rf.feature_importances_
features = X.columns
# 将特征重要性排序
indices = importance.argsort()[::-1]
# 绘制重要性排序图
plt.title('Feature Importance')
plt.bar(range(X.shape[1]), importance[indices])
plt.xticks(range(X.shape[1]), features[indices], rotation=90)
plt.show()
# 记录训练集和测试集的误差
train_errors = []
test_errors = []
# 尝试多个树的数量
trees_range = range(10, 500, 10)
for trees in trees_range:
rf = RandomForestClassifier(n_estimators=trees, random_state=42)
rf.fit(X_train, y_train)
# 计算训练集误差
train_pred = rf.predict(X_train)
train_errors.append(1 - accuracy_score(y_train, train_pred))
# 计算测试集误差
test_pred = rf.predict(X_test)
test_errors.append(1 - accuracy_score(y_test, test_pred))
# 绘制误差随树的数量变化的图
plt.plot(trees_range, train_errors, label='Train Error')
plt.plot(trees_range, test_errors, label='Test Error')
plt.legend()
plt.xlabel('Number of Trees')
plt.ylabel('Error')
plt.show()
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)