实现分类的机器学习算法代码
时间: 2023-10-26 12:07:23 浏览: 88
不同的机器学习算法有不同的实现方式和代码,以下是几种常见的分类算法的实现示例:
1. K-近邻算法(K-Nearest Neighbors)
```
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
# 创建KNN分类器
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
# 预测测试集结果
y_pred = knn.predict(X_test)
# 输出准确率
print("Accuracy:", knn.score(X_test, y_test))
```
2. 决策树算法(Decision Tree)
```
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
# 创建决策树分类器
dt = DecisionTreeClassifier()
# 训练模型
dt.fit(X_train, y_train)
# 预测测试集结果
y_pred = dt.predict(X_test)
# 输出准确率
print("Accuracy:", dt.score(X_test, y_test))
```
3. 朴素贝叶斯算法(Naive Bayes)
```
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
# 创建朴素贝叶斯分类器
nb = GaussianNB()
# 训练模型
nb.fit(X_train, y_train)
# 预测测试集结果
y_pred = nb.predict(X_test)
# 输出准确率
print("Accuracy:", nb.score(X_test, y_test))
```
4. 支持向量机算法(Support Vector Machine)
```
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
# 创建支持向量机分类器
svm = SVC(kernel='linear')
# 训练模型
svm.fit(X_train, y_train)
# 预测测试集结果
y_pred = svm.predict(X_test)
# 输出准确率
print("Accuracy:", svm.score(X_test, y_test))
```
以上是几种常见的分类算法的代码实现,具体实现方式和参数设置可根据具体情况进行调整。
阅读全文