[python]代码库
### 先安装的依赖:
#TensorFlow
#Keras
#Matplotlib
#Scikit-Learn
# 导入所需的库
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
# 加载和准备数据集
X = np.load("animals.npy")
y = np.load("labels.npy")
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建卷积模型
model = Sequential()
model.add(Conv2D(32, (3, 3), strides=(1, 1), activation="relu", input_shape=X.shape[1:]))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(32, (3, 3), strides=(1, 1), activation="relu"))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(256, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(3, activation="softmax"))
# 编译模型
opt = Adam(lr=0.001)
model.compile(optimizer=opt,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
epochs = 10
history = model.fit(X_train, y_train, epochs=epochs,
validation_data=(X_test, y_test))
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test accuracy:', score[1])
# 绘制训练和验证准确度
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()