有两个xlsx表格在桌面上,怎么通过python使用决策树、支持向量机、logistic回归、随机森林模型对两组数据进行分类
时间: 2024-01-30 08:04:01 浏览: 45
你可以使用Python中的pandas库来读取xlsx表格数据,并使用scikit-learn库中的机器学习算法来进行分类。下面是一个示例代码,展示如何使用决策树、支持向量机、logistic回归和随机森林模型对两组数据进行分类:
```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
# 读取xlsx表格数据
df1 = pd.read_excel('path_to_file1.xlsx')
df2 = pd.read_excel('path_to_file2.xlsx')
# 假设表格中的最后一列为目标变量,其他列为特征变量
X1 = df1.iloc[:, :-1]
y1 = df1.iloc[:, -1]
X2 = df2.iloc[:, :-1]
y2 = df2.iloc[:, -1]
# 划分训练集和测试集
X1_train, X1_test, y1_train, y1_test = train_test_split(X1, y1, test_size=0.2)
X2_train, X2_test, y2_train, y2_test = train_test_split(X2, y2, test_size=0.2)
# 创建并训练决策树模型
dt_model1 = DecisionTreeClassifier()
dt_model1.fit(X1_train, y1_train)
dt_model2 = DecisionTreeClassifier()
dt_model2.fit(X2_train, y2_train)
# 创建并训练支持向量机模型
svm_model1 = SVC()
svm_model1.fit(X1_train, y1_train)
svm_model2 = SVC()
svm_model2.fit(X2_train, y2_train)
# 创建并训练logistic回归模型
lr_model1 = LogisticRegression()
lr_model1.fit(X1_train, y1_train)
lr_model2 = LogisticRegression()
lr_model2.fit(X2_train, y2_train)
# 创建并训练随机森林模型
rf_model1 = RandomForestClassifier()
rf_model1.fit(X1_train, y1_train)
rf_model2 = RandomForestClassifier()
rf_model2.fit(X2_train, y2_train)
# 在测试集上进行预测
dt_pred1 = dt_model1.predict(X1_test)
dt_pred2 = dt_model2.predict(X2_test)
svm_pred1 = svm_model1.predict(X1_test)
svm_pred2 = svm_model2.predict(X2_test)
lr_pred1 = lr_model1.predict(X1_test)
lr_pred2 = lr_model2.predict(X2_test)
rf_pred1 = rf_model1.predict(X1_test)
rf_pred2 = rf_model2.predict(X2_test)
```
你可以根据自己的需求对示例代码进行修改,例如调整模型参数、特征工程等。这里只是一个简单的示例,供你参考。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)
![](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)