详解tensorflow实现迁移学习实例

yizhihongxing

下面就详细讲解如何实现TensorFlow中的迁移学习以及两条相关的示例。

1. 初探迁移学习

1.1 什么是迁移学习?

迁移学习(Transfer Learning)是指在训练模型时,将预训练模型的一部分参数引入到新的模型中,以加快模型的训练速度及提高模型的准确率。稳定后的模型部分或全部的函数参数作为新模型的参数来使用。

1.2 迁移学习的优势

  1. 可以提高模型的准确率
  2. 可以加快模型的训练速度
  3. 可以减少数据量及时间投入

1.3 迁移学习的应用

迁移学习广泛应用于计算机视觉、自然语言处理、语音识别等领域,通过对已经训练好的模型进行微调,使得模型更加适应新的任务。

2. 实现迁移学习

下面介绍两个使用TensorFlow实现迁移学习的例子。

2.1 图像识别任务

2.1.1 安装TensorFlow

使用pip工具安装TensorFlow:

pip install tensorflow

2.1.2 下载预训练模型

  1. 下载Inception-v3模型:http://download.tensorflow.org/models/image/imagenet/inception-v3-2016-03-01.tar.gz
  2. 解压到指定目录下(假设目录为./models)

2.1.3 准备数据集

准备训练集和测试集,并且根据模型的要求将图片转换为相应大小(299*299)。

2.1.4 构建网络

import tensorflow as tf
from tensorflow.python.platform import gfile

with tf.Session() as sess:
    model_filename = './models/inception-v3.pb'
    with gfile.FastGFile(model_filename, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        sess.graph.as_default()
        tf.import_graph_def(graph_def, name='')
    # 获取输出层
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')

2.1.5 训练模型

# 转换数据格式,构建输入的Tensor
def read_file_list(file_list):
    images = []
    labels = []
    for file in file_list:
        image = cv2.imread(file)
        image = cv2.resize(image, (299, 299))
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        images.append(image)
        labels.append(int(file.split('/')[-2].split('_')[1]))
    return np.asarray(images, dtype=np.float32) / 255.0, np.asarray(labels, dtype=np.int32)

train_images, train_labels = read_file_list(train_list)
test_images, test_labels = read_file_list(test_list)
train_image_tensor = sess.graph.get_tensor_by_name('input:0')
train_label_tensor = sess.graph.get_tensor_by_name('output:0')

# 构造损失函数和优化器
cross_entropy = tf.losses.sparse_softmax_cross_entropy(train_label_tensor, logits_tensor)
train_step = tf.train.AdamOptimizer().minimize(cross_entropy)

# 训练模型
with tf.Session() as sess:
    # 初始化全局变量
    sess.run(tf.global_variables_initializer())
    for i in range(steps):
        _, loss = sess.run([train_step, cross_entropy], feed_dict={train_image_tensor: train_images, train_label_tensor: train_labels})
        if i % 100 == 0:
            print("Step: ", i, " Loss: ", loss)
    accuracy = sess.run(accuracy_tensor, feed_dict={train_image_tensor: test_images, train_label_tensor: test_labels})
    print("Accuracy: ", accuracy)

2.2 自然语言处理任务

2.2.1 安装TensorFlow

使用pip工具安装TensorFlow:

pip install tensorflow

2.2.2 下载预训练模型

  1. 下载GloVe预训练模型:http://nlp.stanford.edu/data/glove.6B.zip
  2. 解压到指定目录下(假设目录为./models)

2.2.3 准备数据集

准备训练集和测试集。本例中我们使用IMDB数据集。

2.2.4 构建网络

本例中我们使用LSTM来构建网络:

import tensorflow as tf
import numpy as np
from tensorflow.contrib.rnn import BasicLSTMCell

# 构建模型
class LSTM_Model(object):
    def __init__(self, num_classes, num_units):
        self.num_classes = num_classes
        self.num_units = num_units
        self.labels = tf.placeholder(tf.int32, [None])
        self.inputs = tf.placeholder(tf.float32, [None, None, self.num_units])
        self.seq_lens = tf.placeholder(tf.int32, [None])
        self.dropout_keep_prob = tf.placeholder(tf.float32)
        cell_fw = BasicLSTMCell(self.num_units)
        cell_bw = BasicLSTMCell(self.num_units)
        outputs, states = tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, self.inputs, sequence_length=self.seq_lens, dtype=tf.float32)
        output = tf.concat(outputs, 2)
        output = tf.layers.dropout(output, rate=self.dropout_keep_prob)
        output = tf.layers.dense(output, self.num_classes, activation=None)
        self.loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.labels, logits=output))
        self.train_op = tf.train.AdamOptimizer().minimize(self.loss)
        self.prediction = tf.argmax(output, 1)
        correct_pred = tf.equal(tf.cast(self.prediction, tf.int32), self.labels)
        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

    def train(self, sess, x, y, seq_lens, dropout_keep_prob):
        feed_dict = {self.inputs: x, self.labels: y, self.seq_lens: seq_lens, self.dropout_keep_prob:dropout_keep_prob}
        _, loss, accuracy = sess.run([self.train_op, self.loss, self.accuracy], feed_dict=feed_dict)
        return loss, accuracy

    def predict(self, sess, x, seq_lens):
        feed_dict = {self.inputs: x, self.seq_lens: seq_lens, self.dropout_keep_prob: 1.0}
        pred = sess.run(self.prediction, feed_dict=feed_dict)
        return pred

2.2.5 训练模型

import numpy as np
from keras.preprocessing import sequence
from keras.datasets import imdb
from keras.layers import Embedding

# 加载数据
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=10000, maxlen=100)
x_train = sequence.pad_sequences(x_train, maxlen=100, padding='post', truncating='post')
x_test = sequence.pad_sequences(x_test, maxlen=100, padding='post', truncating='post')

# 加载GloVe预训练模型
glove_file = "./models/glove.6B.100d.txt"
word2idx = imdb.get_word_index()
idx2word = {k: (v + 3) for k, v in word2idx.items()}
idx2word[0] = "<PAD/>"
idx2word[1] = "<START/>"
idx2word[2] = "<UNK/>"
idx2word[3] = "<UNUSED/>"

embedding_matrix = []
with open(glove_file, 'r') as f:
    for line in f:
        line = line.strip().split()
        word = line[0]
        if word in idx2word:
            embedding = np.asarray(line[1:], dtype=np.float32)
            embedding_matrix.append(embedding)
embedding_matrix = np.asarray(embedding_matrix, dtype=np.float32)
embedding_layer = Embedding(input_dim=x_train.shape[0], output_dim=100, input_length=100, weights=[embedding_matrix])

with tf.Session() as sess:
    lstm_model = LSTM_Model(num_classes=2, num_units=100)
    sess.run(tf.global_variables_initializer())
    for i in range(steps):
        idxs = np.random.permutation(np.arange(0,len(y_train)))
        batch_loss = []
        batch_acc = []
        for j in range(0, len(y_train), batch_size):
            batch_idx = idxs[j:j+batch_size]
            batch_seq_lens = np.sum(np.sign(x_train[batch_idx]),axis=1)
            batch_loss_j, batch_acc_j = lstm_model.train(sess, x_train[batch_idx], y_train[batch_idx], batch_seq_lens, dropout_keep_prob=0.7)
            batch_loss.append(batch_loss_j)
            batch_acc.append(batch_acc_j)
        if i % 10 == 0:
            print("Step: ", i, " Loss: ", np.mean(batch_loss), " Accuracy: ", np.mean(batch_acc))
    test_seq_lens = np.sum(np.sign(x_test),axis=1)
    test_accuracy = lstm_model.predict(sess, x_test, test_seq_lens)
    print("Test Accuracy: ", test_accuracy)

以上两个例子分别是图像识别任务和自然语言处理任务中使用迁移学习的例子,本文档已经详细讲解完成。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解tensorflow实现迁移学习实例 - Python技术站

(0)
上一篇 2023年5月15日
下一篇 2023年5月15日

相关文章

  • 卷积神经网络的卷积核大小、个数,卷积层数如何确定呢?

    转载TonySure 最后发布于2019-07-08 09:47:19 阅读数 7521  收藏   https://yq.aliyun.com/articles/610509   卷积神经网络的卷积核大小、卷积层数、每层map个数都是如何确定下来的呢?看到有些答案是刚开始随机初始化卷积核大小,卷积层数和map个数是根据经验来设定的,但这个里面应该是有深层次…

    2023年4月6日
    00
  • 卷积神经网络之卷积的物理意义

      图像中的卷积,是离散的,这不同于我们数学中的卷积公式,数学中的卷积公式大部分都是连续的,但是也有离散的卷积公式,学过数字信号处理的应该都知道。这一点是我之前不明白的地方。      正如上图所示,大的方框表示原图像的像素,中间小的3*3的方框为卷积模板,最右边的方框是做完卷积之后的输出图像。   那么,为什么要对图像做卷积呢?卷积的物理意义是什么呢?经过…

    2023年4月6日
    00
  • Tensorflow 2.4加载处理图片的三种方式详解

    那么首先我会创建一个标题来概括这篇文章的主要内容。 Tensorflow 2.4 加载处理图片的三种方式详解 接下来,我会介绍加载和处理图片的三种方式,分别是:使用Keras的ImageDataGenerator、使用TensorFlow Dataset API和使用TensorFlow的DataLoader API。 1. 使用Keras的ImageDat…

    卷积神经网络 2023年5月15日
    00
  • 深度学习(卷积神经网络)一些问题总结(转)

        涉及问题: 1.每个图如何卷积:   (1)一个图如何变成几个?   (2)卷积核如何选择? 2.节点之间如何连接? 3.S2-C3如何进行分配? 4.16-120全连接如何连接? 5.最后output输出什么形式? ①各个层解释:    我们先要明确一点:每个层有多个Feature Map,每个Feature Map通过一种卷积滤波器提取输入的一种…

    2023年4月7日
    00
  • 集合并卷积

    因为小星星那题才知道有这么个东西。。 下面这段从uoj复制的:http://liu-runda.blog.uoj.ac/blog/2360 题目 给出h[0…(2n)−1],满足h[x]=sigma{f[i]*g[j],1<=i<=n,1<=j<=n,i|j==x} 我们记F[i]=sigma(f[j],j&i==j),G[i…

    卷积神经网络 2023年4月6日
    00
  • 吴裕雄 python 神经网络——TensorFlow 使用卷积神经网络训练和预测MNIST手写数据集

    import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data #设置输入参数 batch_size = 128 test_size = 256 # 初始化权值与定义网络结构,建构一个3个卷积层和3个池化层,一个全连接层…

    2023年4月8日
    00
  • 卷积神经网络基础_转载

    网上看到的关于卷积神经网络总结比较好的文章 链接如下:https://blog.csdn.net/sinat_34328764/article/details/84192303

    卷积神经网络 2023年4月6日
    00
  • [ 1 x 1 ] Convolution-1*1卷积的作用

    一、卷积神经网络中的卷积(Convolution in a convoluted neural network)     具体内容亲参考《深度学习》。 二、1*1卷积(one by one convolution)的作用 1*1卷积过滤器 ,它的大小是1*1,没有考虑在前一层局部信息之间的关系。最早出现在 Network In Network的论文中 ,使用…

    2023年4月5日
    00
合作推广
合作推广
分享本页
返回顶部