【Tensorflow练习】: tf.variable_scope、tf.get_variable、tf.get_variable_scope、arg_scope的简单使用示例

本文介绍了TensorFlow中变量管理的关键概念,包括`tf.variable_scope`, `tf.get_variable`, `tf.get_variable_scope`以及`arg_scope`的使用。通过示例展示了如何创建、重用和安全地管理变量,以及`arg_scope`在控制变量共享方面的作用。" 8806931,1403176,Apache Tez:优化Hadoop处理的DAG框架,"['Hadoop生态', '大数据处理', 'MapReduce优化', 'DAG框架', 'Apache组件']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先导入库:

#coding=utf-8
#如果出现编码上的问题,可能需要先写上面这行,保存一下文件,再写下面的部分
import tensorflow  as tf

创建新变量的一个实例:

#对应的参数(name_or_scope, default_name, values=None, ...,reuse=None,...,auxiliary_name_scope=True)
#其中,default_name: name_or_scope若为None,则用它,否则它将无用
with tf.variable_scope("foo"):
    with tf.variable_scope("bar"):
        v = tf.get_variable("v", [1])  #获取具有此名称"v"的现有变量(如果已有)或创建一个新变量(还没有该名称的变量); 参数(name, shape, dtype, initializer, ...)
        print(v.name)  #output: foo/bar/v:0
        s = tf.get_variable_scope()  #返回当前变量scopereuse=None
        print(s.name)  #output: foo/bar
        assert v.name == "foo/bar/v:0" 

若name_or_scope=None, 且default_name='fcy':(default_name: name_or_scope若为None,则用它,否则它将无用)

#若name_or_scope=None, 且default_name='fcy':
with tf.variable_scope(name_or_scope=None, default_name='fcy'):
    with tf.variable_scope("bar"):
        v = tf.get_variable("v", [1])  
        print(v.name)  #output: fcy/bar/v:0
        s = tf.get_variable_scope()  #返回当前变量scopereuse=None
        print(s.name)  #output: fcy/bar
        assert v.name == "fcy/bar/v:0"  

代码分析如下: ```python def cnn_model(features, target): # 对target进行one-hot编码 target = tf.one_hot(target, 15, 1, 0) # 对features中的词进行embedding,得到词向量 word_vectors = tf.contrib.layers.embed_sequence(features, vocab_size=n_words, embed_dim=EMBEDDING_SIZE, scope='words') # 在词向量上增加一个维度,用于卷积 word_vectors = tf.expand_dims(word_vectors, 3) with tf.variable_scope('CNN_Layer1'): # 添加卷积层 conv1 = tf.contrib.layers.convolution2d(word_vectors, N_FILTERS, FILTER_SHAPE1, padding='VALID') # 对卷积结果进行ReLU非线性变换 conv1 = tf.nn.relu(conv1) # 对卷积结果进行最大池化 pool1 = tf.nn.max_pool(conv1, ksize=[1, POOLING_WINDOW, 1, 1], strides=[1, POOLING_STRIDE, 1, 1], padding='SAME') # 对池化结果进行转置,以满足形状要求 pool1 = tf.transpose(pool1, [0, 1, 3, 2]) with tf.variable_scope('CNN_Layer2'): # 添加卷积层 conv2 = tf.contrib.layers.convolution2d(pool1, N_FILTERS, FILTER_SHAPE2, padding='VALID') # 对卷积结果进行ReLU非线性变换 conv2 = tf.nn.relu(conv2) # 对卷积结果进行最大池化 pool2 = tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1]) # 将池化结果送入全连接层,输出最终的分类结果 logits = tf.contrib.layers.fully_connected(pool2, 15, activation_fn=None) loss = tf.losses.softmax_cross_entropy(target, logits) train_op = tf.contrib.layers.optimize_loss(loss, tf.contrib.framework.get_global_step(), optimizer='Adam', learning_rate=LEARNING_RATE) return ({ 'class': tf.argmax(logits, 1), 'prob': tf.nn.softmax(logits) }, loss, train_op) ``` 1. `tf.one_hot(target, 15, 1, 0)`:对target进行one-hot编码,将每个词转化为一个长度为15的向量,其中对应的位置为1,其余为0。 2. `tf.contrib.layers.embed_sequence(features, vocab_size=n_words, embed_dim=EMBEDDING_SIZE, scope='words')`:对features(即输入的词)进行embedding,将每个词转化为一个EMBEDDING_SIZE维的向量。 3. `tf.expand_dims(word_vectors, 3)`:在词向量上增加一个维度,用于卷积。 4. `tf.contrib.layers.convolution2d(word_vectors, N_FILTERS, FILTER_SHAPE1, padding='VALID')`:添加卷积层,使用N_FILTERS个大小为FILTER_SHAPE1的滤波器进行卷积操作。 5. `tf.nn.relu(conv1)`:对卷积结果进行ReLU非线性变换。 6. `tf.nn.max_pool(conv1, ksize=[1, POOLING_WINDOW, 1, 1], strides=[1, POOLING_STRIDE, 1, 1], padding='SAME')`:对卷积结果进行最大池化,使用大小为POOLING_WINDOW的池化窗口,步长为POOLING_STRIDE。 7. `tf.transpose(pool1, [0, 1, 3, 2])`:对池化结果进行转置,将第3维和第4维交换,以满足后续卷积层的输入要求。 8. `tf.contrib.layers.convolution2d(pool1, N_FILTERS, FILTER_SHAPE2, padding='VALID')`:添加卷积层,使用N_FILTERS个大小为FILTER_SHAPE2的滤波器进行卷积操作。 9. `tf.nn.relu(conv2)`:对卷积结果进行ReLU非线性变换。 10. `tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1])`:对卷积结果进行最大池化,并去除不必要的维度。 11. `tf.contrib.layers.fully_connected(pool2, 15, activation_fn=None)`:将池化结果送入全连接层,输出最终的分类结果。 12. `tf.losses.softmax_cross_entropy(target, logits)`:计算损失函数,使用softmax交叉熵作为损失函数。 13. `tf.contrib.layers.optimize_loss(loss, tf.contrib.framework.get_global_step(), optimizer='Adam', learning_rate=LEARNING_RATE)`:使用Adam优化器最小化损失函数,更新模型参数。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值