python:从excel中读取数据,分成训练集、验证集、测试集,使用svm进行预测的代码
时间: 2024-03-25 22:41:45 浏览: 19
以下是使用Python中的pandas和scikit-learn库从Excel中读取数据,并将其分为训练集、验证集、测试集,并使用SVM进行预测的示例代码:
```python
import pandas as pd
from sklearn import svm
from sklearn.model_selection import train_test_split
# 从Excel文件中读取数据
data = pd.read_excel('data.xlsx')
# 将数据分为特征和目标变量
X = data.drop('target', axis=1)
y = data['target']
# 将数据分为训练集、验证集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
# 训练SVM模型
clf = svm.SVC()
clf.fit(X_train, y_train)
# 在验证集上评估模型性能
val_accuracy = clf.score(X_val, y_val)
print("Validation accuracy:", val_accuracy)
# 在测试集上评估模型性能
test_accuracy = clf.score(X_test, y_test)
print("Test accuracy:", test_accuracy)
# 预测新数据
new_data = pd.read_excel('new_data.xlsx')
prediction = clf.predict(new_data)
print(prediction)
```
在此示例中,我们首先使用pandas库从Excel文件中读取数据。我们使用`data.drop()`方法将数据分为特征和目标变量。然后,我们使用scikit-learn库中的`train_test_split()`方法将数据分成训练集、验证集和测试集。我们使用`test_size`参数来指定测试集的大小,并使用`random_state`参数来确保我们每次运行代码时都得到相同的拆分。
接下来,我们使用`svm.SVC()`方法创建SVM模型,并使用`clf.fit()`方法将模型与训练数据拟合。然后,我们使用`clf.score()`方法评估模型在验证集和测试集上的性能。最后,我们使用`clf.predict()`方法对新数据进行预测,并输出预测结果。