knn,决策树,逻辑回归,线性回归,支持向量机,卷积神经网络算法之间的区别用Python代码表示
时间: 2024-05-02 20:20:28 浏览: 80
KNN算法:
```python
from sklearn.neighbors import KNeighborsClassifier
# 创建KNN分类器对象
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
# 预测结果
y_pred = knn.predict(X_test)
```
决策树算法:
```python
from sklearn.tree import DecisionTreeClassifier
# 创建决策树分类器对象
dt = DecisionTreeClassifier(criterion='entropy')
# 训练模型
dt.fit(X_train, y_train)
# 预测结果
y_pred = dt.predict(X_test)
```
逻辑回归算法:
```python
from sklearn.linear_model import LogisticRegression
# 创建逻辑回归模型对象
lr = LogisticRegression()
# 训练模型
lr.fit(X_train, y_train)
# 预测结果
y_pred = lr.predict(X_test)
```
线性回归算法:
```python
from sklearn.linear_model import LinearRegression
# 创建线性回归模型对象
lr = LinearRegression()
# 训练模型
lr.fit(X_train, y_train)
# 预测结果
y_pred = lr.predict(X_test)
```
支持向量机算法:
```python
from sklearn.svm import SVC
# 创建SVM分类器对象
svc = SVC(kernel='linear')
# 训练模型
svc.fit(X_train, y_train)
# 预测结果
y_pred = svc.predict(X_test)
```
卷积神经网络算法:
```python
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten
# 创建卷积神经网络模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test))
# 预测结果
y_pred = model.predict(X_test)
```
阅读全文