用python写相关代码
时间: 2023-12-17 18:12:10 浏览: 23
以下是一个使用随机森林算法对肿瘤数据进行分类的示例代码。这里使用的数据集是UCI的乳腺癌数据集,包含30个特征和1个标签,标签为良性(benign)或恶性(malignant)。
```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
df = pd.read_csv('breast_cancer.csv')
# 分离特征和标签
X = df.iloc[:, 1:-1]
y = df.iloc[:, -1]
# 划分训练集和测试集
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)
```
在上面的代码中,`breast_cancer.csv`是数据集文件名,代码首先加载数据集,然后分离特征和标签。接着,使用 `train_test_split` 函数将数据集划分为训练集和测试集,其中 `test_size` 参数指定测试集所占比例。最后,使用随机森林算法进行建模和预测,并计算模型精度。