alexnet代码python
时间: 2023-09-04 09:16:14 浏览: 102
以下是使用Python实现的AlexNet代码示例:
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Define the AlexNet model
def alexnet(input_shape, num_classes):
model = keras.Sequential([
layers.Conv2D(filters=96, kernel_size=(11,11), strides=(4,4), activation='relu', input_shape=input_shape),
layers.MaxPooling2D(pool_size=(3,3), strides=(2,2)),
layers.BatchNormalization(),
layers.Conv2D(filters=256, kernel_size=(5,5), strides=(1,1), activation='relu', padding="same"),
layers.MaxPooling2D(pool_size=(3,3), strides=(2,2)),
layers.BatchNormalization(),
layers.Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), activation='relu', padding="same"),
layers.BatchNormalization(),
layers.Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), activation='relu', padding="same"),
layers.BatchNormalization(),
layers.Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), activation='relu', padding="same"),
layers.MaxPooling2D(pool_size=(3,3), strides=(2,2)),
layers.BatchNormalization(),
layers.Flatten(),
layers.Dense(4096, activation='relu'),
layers.Dropout(0.5),
layers.BatchNormalization(),
layers.Dense(4096, activation='relu'),
layers.Dropout(0.5),
layers.BatchNormalization(),
layers.Dense(num_classes, activation='softmax')
])
return model
# Instantiate the model
input_shape = (227, 227, 3)
num_classes = 1000
model = alexnet(input_shape, num_classes)
# Compile the model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, batch_size=128, epochs=10, validation_split=0.2)
# Evaluate the model
score = model.evaluate(x_test, y_test)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
阅读全文