117、TensorFlow变量共享

本文详细介绍了TensorFlow中变量共享的两种方式:显式传递tf.Variable对象和隐式包裹tf.Variable对象于tf.variable_scope内。通过创建卷积/ReLU层函数示例,展示了如何在不同场景下使用这些变量共享策略。

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

# sharing variables
# Tensorflow supports two ways of sharing variables
# 1、Explicitly passing tf.Variable objects around
# 2、Implicitly wrapping tf.Variable objects within tf.variable_scope objects
# For example , let's write a function to create a convolutional / relu layer
import tensorflow as tf
def conv_relu(input, kernel_shape, bias_shape):
    # Create variable named "weights"
    weights = tf.get_variable("weights", kernel_shape, initializer=tf.random_normal_initializer())
    # Create variable named "biases"
    biases = tf.get_variable("biases", bias_shape, initializer=tf.constant_initializer(0.0))
    # stride表示步长 , weight表示卷积核 , padding 表示卷积核是否可以停留在图像的边缘
    conv = tf.nn.conv2d(input, weights, strides=[1, 1, 1, 1], padding='SAME')
    return tf.nn.relu(conv + biases)


# 这个函数使用了简写的weights和biases 
# 在声明的时候是有帮助的,
# 但是在真实的模型中,我们更想要以下的卷积层,重复调用这个函数是不会起作用的
input1 = tf.random_normal([1, 10, 10, 32])
input2 = tf.random_normal([1, 20, 20, 32])
x = conv_relu(input1, kernel_shape=[5, 5, 32, 32], bias_shape=32)
# This fails 不支持重复调用 , 因为想要的行为还不清楚
# 是创建新的变量还是使用现有的变量
# x = conv_relu(x, kernel_shape=[5, 5, 32, 32], bias_shape=[32]) 

 

转载于:https://www.cnblogs.com/weizhen/p/8451478.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值