对于手写数字识别任务,我们可以使用不同的机器学习算法来实现,包括决策树、K最近邻(KNN)、支持向量机(SVM)和卷积神经网络(CNN)。下面我将为你提供每种算法的基本代码示例。
- 决策树算法:
python
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=42)
# 创建决策树模型
dt_model = DecisionTreeClassifier()
# 训练模型
dt_model.fit(X_train, y_train)
# 预测
y_pred = dt_model.predict(X_test)
# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("决策树算法准确率:", accuracy)
- K最近邻算法(KNN):
python
from sklearn.neighbors import KNeighborsClassifier
# 创建KNN模型
knn_model = KNeighborsClassifier()
# 训练模型
knn_model.fit(X_train, y_train)
# 预测
y_pred = knn_model.predict(X_test)
# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("KNN算法准确率:", accuracy)
- 支持向量机(SVM)算法:
python
from sklearn.svm import SVC
# 创建SVM模型
svm_model = SVC()
# 训练模型
svm_model.fit(X_train, y_train)
# 预测
y_pred = svm_model.predict(X_test)
# 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print("SVM算法准确率:", accuracy)
- 卷积神经网络(CNN)算法:这里给出一个简单的Keras示例,用于构建一个简单的卷积神经网络模型。
python
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
from keras.utils import to_categorical
# 加载数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = np.expand_dims(X_train, axis=-1)
X_test = np.expand_dims(X_test, axis=-1)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# 创建CNN模型
cnn_model = Sequential()
cnn_model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28,28,1)))
cnn_model.add(Flatten())
cnn_model.add(Dense(10, activation='softmax'))
# 编译模型
cnn_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
cnn_model.fit(X_train, y_train, epochs=5, batch_size=32, validation_data=(X_test, y_test))
# 评估模型
accuracy = cnn_model.evaluate(X_test, y_test)[1]
print("CNN算法准确率:", accuracy)
这些是每种算法的基本实现示例。对于CNN算法,我们使用了Keras来构建模型,因为Keras提供了更简单易用的API来构建神经网络。