ALEXNET如何直接调用
时间: 2023-10-07 14:12:40 浏览: 104
c4d颜值预测alexnet-opencv调用dnn
AlexNet是一种深度学习模型,通常需要使用深度学习框架来实现。以下是在Python中使用TensorFlow框架调用AlexNet的示例代码:
```
import tensorflow as tf
# 构建AlexNet模型
def alexnet(input_shape, num_classes):
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(96, (11, 11), strides=(4, 4), activation='relu', input_shape=input_shape),
tf.keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(2, 2)),
tf.keras.layers.Conv2D(256, (5, 5), strides=(1, 1), padding='same', activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(2, 2)),
tf.keras.layers.Conv2D(384, (3, 3), strides=(1, 1), padding='same', activation='relu'),
tf.keras.layers.Conv2D(384, (3, 3), strides=(1, 1), padding='same', activation='relu'),
tf.keras.layers.Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_classes, activation='softmax')
])
return model
# 调用AlexNet模型
input_shape = (227, 227, 3)
num_classes = 1000
model = alexnet(input_shape, num_classes)
# 加载预训练权重
weights_url = 'https://github.com/tensorflow/models/raw/master/research/slim/nets/alexnet/alexnet_ckpt.tar.gz'
weights_file = tf.keras.utils.get_file('alexnet_weights.tar.gz', weights_url, extract=True)
weights_dir = os.path.join(os.path.dirname(weights_file), 'checkpoints')
weights_path = os.path.join(weights_dir, 'alexnet_model.ckpt')
model.load_weights(weights_path)
# 使用AlexNet模型进行预测
image = tf.keras.preprocessing.image.load_img('image.jpg', target_size=(227, 227))
image_array = tf.keras.preprocessing.image.img_to_array(image)
image_array = tf.keras.applications.alexnet.preprocess_input(image_array)
image_array = tf.expand_dims(image_array, 0)
predictions = model.predict(image_array)
```
阅读全文