用tensorflow写一段代码:卷积神经网络进行特征提取,支持向量机进行十分类
时间: 2024-05-09 07:21:59 浏览: 101
以下是用tensorflow写的卷积神经网络进行特征提取,支持向量机进行十分类的代码:
```python
import tensorflow as tf
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 构建卷积神经网络
def cnn_model(X):
# 输入层
input_layer = tf.keras.layers.Input(shape=X.shape[1:])
# 卷积层
conv_layer = tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu')(input_layer)
# 池化层
pool_layer = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(conv_layer)
# 扁平化层
flatten_layer = tf.keras.layers.Flatten()(pool_layer)
# 全连接层
dense_layer = tf.keras.layers.Dense(units=128, activation='relu')(flatten_layer)
# 输出层
output_layer = tf.keras.layers.Dense(units=10, activation='softmax')(dense_layer)
# 定义模型
model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer)
return model
# 加载数据集
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
# 数据预处理
X_train = X_train / 255.
X_test = X_test / 255.
X_train = X_train.reshape((-1, 28, 28, 1))
X_test = X_test.reshape((-1, 28, 28, 1))
# 构建模型
model = cnn_model(X_train)
# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=5, batch_size=64, validation_data=(X_test, y_test))
# 提取特征
feature_extractor = tf.keras.models.Model(inputs=model.inputs, outputs=model.layers[-2].output)
train_features = feature_extractor.predict(X_train)
test_features = feature_extractor.predict(X_test)
# 支持向量机进行分类
svm_model = SVC(kernel='linear')
svm_model.fit(train_features, y_train)
svm_pred = svm_model.predict(test_features)
# 计算准确率
accuracy = accuracy_score(y_test, svm_pred)
print("Accuracy:", accuracy)
```
这段代码实现了对 MNIST 数据集的特征提取和分类,其中卷积神经网络用于特征提取,支持向量机用于十分类。最终输出分类准确率。
阅读全文