跟我学算法- tensorflow VGG模型进行测试

我们使用的VGG模型是别人已经训练好的一个19层的参数所做的一个模型

第一步:定义卷积分部操作函数

mport scipy.io
import numpy as np
import os
import scipy.misc
import matplotlib.pyplot as plt
import tensorflow as tf

# 进行卷积操作
def _conv_layer(input, weights, bias):
    conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1),
                        padding='SAME')
    return tf.nn.bias_add(conv, bias)
# 进行池化操作
def _pool_layer(input):
    return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1),
                          padding='SAME')
# 进行去均值的操作
def preprocess(image, mean_pixel):
    return image - mean_pixel

def unprocess(image, mean_pixel):
    return image + mean_pixel

def imread(path):
    return scipy.misc.imread(path).astype(np.float)
def imsave(path, img):
    img = np.clip(img, 0, 255).astype(np.uint8)
    scipy.misc.imsave(path, img)

第二步:定义卷积操作函数

def net(data_path, input_image):
    layers = (
        'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
        'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
        'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',
        'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
        'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',
        'relu4_3', 'conv4_4', 'relu4_4', 'pool4',
        'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',
        'relu5_3', 'conv5_4', 'relu5_4'
    )
    # 载入数据
    data = scipy.io.loadmat(data_path)
    mean = data['normalization'][0][0][0]
    mean_pixel = np.mean(mean, axis=(0, 1))
    weights = data['layers'][0]
    net = {}
    current = input_image
    for i, name in enumerate(layers):
        kind = name[:4]
        if kind == 'conv':
            kernels, bias = weights[i][0][0][0][0]
            kernels = np.transpose(kernels, (1, 0, 2, 3))
            # 重构reshape
            bias = bias.reshape(-1)
            current = _conv_layer(current, kernels, bias)
        elif kind == 'relu':
            current = tf.nn.relu(current)
        elif kind == 'pool':
            current = _pool_layer(current)
        # 用来存放对应的处理结果
        net[name] = current

    assert len(net) == len(layers)

    return net, mean_pixel, layers

第三步: 构造文件路径

# 返回当前的路径
cwd = os.getcwd()
# 别人已经训练好的模型
VGG_PATH =cwd + '/data/imagenet-vgg-verydeep-19.mat'
IMG_PATH = cwd + '/data/cat.jpg'
input_image = imread(IMG_PATH)
shape = (1, input_image.shape[0], input_image.shape[1], input_image.shape[2])

第四步:训练模型,输出特征图像

with tf.Session as sess:
    image = tf.placeholder('float', shape=shape)
    #训练模型
    nets, mean_pixel, all_layers = net(VGG_PATH, image)
    # 去除均值
    input_image_pre = np.array([preprocess(input_image, mean_pixel)])
    layers = all_layers
    for i, layer in enumerate(layers):
        # 输出模型的单个特征
        features = nets[layer].eval(feed_dict={image:input_image})
        print(" Type of 'features' is ", type(features))
        print(" Shape of 'features' is %s" % (features.shape,))
    # 画卷积特征图
        if 1:
            plt.figure(i+1, figsize=(10, 5))
            plt.matshow(features[0, :, :, 0], cmap=plt.cm.gray, fignum=i+1)
            plt.title(""+layer)
            plt.colorbar()
            plt.show()

 

转载于:https://www.cnblogs.com/my-love-is-python/p/9571239.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TensorFlow VGG迁移学习微调是一种利用预先训练的VGG模型,并在其基础上进行微调的方法。VGG是一种深度卷积神经网络模型,已在大规模图像分类任务上证明了其有效性。 迁移学习是指将在一个任务上训练好的模型应用于另一个任务上的技术。而VGG迁移学习微调则是将预训练的VGG模型应用于特定任务,并对其进行微调以提高性能。 在迁移学习微调过程中,首先加载预训练的VGG模型权重。然后,将模型的最后几层替换为适应特定任务的新层。这些新层通常是全连接层,用于针对任务的特定类别进行预测。 在微调中,新层的权重被随机初始化,并与预训练模型的权重一起进行训练。这样做是为了使模型能够更好地适应新任务,因为预训练模型的权重已经学习到了许多通用特征。 训练时,可以使用较小的学习率来微调预训练模型的权重,以避免对这些权重的大幅度更新。同样,需要在训练过程中使用较大的数据集,并进行适当的数据增强来避免过拟合。 通过VGG迁移学习微调,可以利用预训练模型的优势,减少在现有数据集上进行训练所需的时间和计算资源。此外,由于预训练模型已在大规模数据集上进行了训练,所以它们通常会具备良好的特征提取能力,从而为微调任务提供更好的初始特征。 总的来说,TensorFlow VGG迁移学习微调是一种利用预训练模型进行迁移学习的方法,可以提高特定任务的性能,并减少训练所需的资源和时间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值