朴素贝叶斯算法、决策树与随机森林、支持向量机算法、KNN算法简易代码
时间: 2023-12-01 13:00:57 浏览: 41
朴素贝叶斯算法:
```python
from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load the iris dataset
iris = load_iris()
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
# Create a Gaussian Naive Bayes classifier
gnb = GaussianNB()
# Train the classifier using the training data
gnb.fit(X_train, y_train)
# Use the classifier to make predictions on the testing data
y_pred = gnb.predict(X_test)
```
决策树与随机森林:
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load the iris dataset
iris = load_iris()
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
# Create a decision tree classifier
dtc = DecisionTreeClassifier()
# Train the classifier using the training data
dtc.fit(X_train, y_train)
# Use the classifier to make predictions on the testing data
y_pred = dtc.predict(X_test)
# Create a random forest classifier
rfc = RandomForestClassifier(n_estimators=100)
# Train the classifier using the training data
rfc.fit(X_train, y_train)
# Use the classifier to make predictions on the testing data
y_pred = rfc.predict(X_test)
```
支持向量机算法:
```python
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load the iris dataset
iris = load_iris()
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
# Create a Support Vector Machine classifier
svm = SVC()
# Train the classifier using the training data
svm.fit(X_train, y_train)
# Use the classifier to make predictions on the testing data
y_pred = svm.predict(X_test)
```
KNN算法:
```python
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load the iris dataset
iris = load_iris()
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
# Create a K-Nearest Neighbors classifier
knn = KNeighborsClassifier(n_neighbors=5)
# Train the classifier using the training data
knn.fit(X_train, y_train)
# Use the classifier to make predictions on the testing data
y_pred = knn.predict(X_test)
```