tf.add_weight 和 tf.Variable使用例子

这篇博客介绍了如何在Keras中自定义层,并通过两种不同的方法添加权重:传统方式和使用`add_weight()`方法。这两种方法都用于创建一个线性层,但后者简化了权重初始化和管理的过程。示例展示了如何定义和应用线性层,并输出其运算结果。

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

class Linear(keras.layers.Layer):
    def __init__(self, units=32, input_dim=32):
        super(Linear, self).__init__()
        w_init = tf.random_normal_initializer()
        self.w = tf.Variable(
            initial_value=w_init(shape=(input_dim, units), dtype="float32"),
            trainable=True,
        )
        b_init = tf.zeros_initializer()
        self.b = tf.Variable(
            initial_value=b_init(shape=(units,), dtype="float32"), trainable=True
        )

    def call(self, inputs):
        return tf.matmul(inputs, self.w) + self.b
        
x = tf.ones((2, 2))
linear_layer = Linear(4, 2)
y = linear_layer(x)
print(y)        

您还可以使用一种更加快捷的方式为层添加权重:add_weight() 方法:
区别在函数传参不同

class Linear(keras.layers.Layer):
    def __init__(self, units=32, input_dim=32):
        super(Linear, self).__init__()
        self.w = self.add_weight(
            shape=(input_dim, units), initializer="random_normal", trainable=True
        )
        self.b = self.add_weight(shape=(units,), initializer="zeros", trainable=True)

    def call(self, inputs):
        return tf.matmul(inputs, self.w) + self.b


x = tf.ones((2, 2))
linear_layer = Linear(4, 2)
y = linear_layer(x)
print(y)
按照TensorFlow2.11的写法修改这段代码:“class tgcnCell(RNN): """Temporal Graph Convolutional Network """ def call(self, inputs, **kwargs): pass def __init__(self, num_units, adj, num_nodes, input_size=None, act=tf.nn.tanh, reuse=None): super(tgcnCell, self).__init__(units=num_units,_reuse=reuse) self._act = act self._nodes = num_nodes self._units = num_units self._adj = [] self._adj.append(calculate_laplacian(adj)) @property def state_size(self): return self._nodes * self._units @property def output_size(self): return self._units def __call__(self, inputs, state, scope=None): with tf.variable_scope(scope or "tgcn"): with tf.variable_scope("gates"): value = tf.nn.sigmoid( self._gc(inputs, state, 2 * self._units, bias=1.0, scope=scope)) r, u = tf.split(value=value, num_or_size_splits=2, axis=1) with tf.variable_scope("candidate"): r_state = r * state c = self._act(self._gc(inputs, r_state, self._units, scope=scope)) new_h = u * state + (1 - u) * c return new_h, new_h def _gc(self, inputs, state, output_size, bias=0.0, scope=None): inputs = tf.expand_dims(inputs, 2) state = tf.reshape(state, (-1, self._nodes, self._units)) x_s = tf.concat([inputs, state], axis=2) input_size = x_s.get_shape()[2].value x0 = tf.transpose(x_s, perm=[1, 2, 0]) x0 = tf.reshape(x0, shape=[self._nodes, -1]) scope = tf.get_variable_scope() with tf.variable_scope(scope): for m in self._adj: x1 = tf.sparse_tensor_dense_matmul(m, x0) x = tf.reshape(x1, shape=[self._nodes, input_size,-1]) x = tf.transpose(x,perm=[2,0,1]) x = tf.reshape(x, shape=[-1, input_size]) weights = tf.get_variable( 'weights', [input_size, output_size], initializer=tf.contrib.layers.xavier_initializer()) x = tf.matmul(x, weights) # (batch_size * self._nodes, output_size) biases = tf.get_variable( "biases", [output_size], initializer=tf.constant_initializer(bias, dtype=tf.float32)) x = tf.nn.bias_add(x, biases) x = tf.reshape(x, shape=[-1, self._nodes, output_size]) x = tf.reshape(x, shape=[-1, self._nodes * output_size]) return x”
最新发布
04-05
将下列代码修改成tensorflow2.3.0兼容的模式:class BSplineLayer(Layer): """自定义B样条基函数层""" def __init__(self, num_basis, degree=3, **kwargs): super(BSplineLayer, self).__init__(**kwargs) self.num_basis = num_basis self.degree = degree def build(self, input_shape): # 初始化B样条节点系数 self.knots = self.add_weight( name='knots', shape=(self.num_basis + self.degree + 1,), initializer='glorot_uniform', trainable=True) self.coeffs = self.add_weight( name='coeffs', shape=(self.num_basis,), initializer='glorot_uniform', trainable=True) super(BSplineLayer, self).build(input_shape) def call(self, inputs): # B样条基函数计算 t = tf.linspace(-1.0, 1.0, self.num_basis + self.degree + 1) basis = tf.map_fn( lambda x: tf.math.bessel_j0( # 使用Bessel函数近似样条基 tf.reduce_sum(self.coeffs * tf.math.exp(-(x - self.knots)**2)) ), inputs) return basis class KANBlock(Layer): """KAN模块实现""" def __init__(self, num_basis, **kwargs): super(KANBlock, self).__init__(**kwargs) self.bspline_layer = BSplineLayer(num_basis=num_basis) def build(self, input_shape): self.bias = self.add_weight( name='bias', shape=(input_shape[-1],), initializer='zeros', trainable=True) super(KANBlock, self).build(input_shape) def call(self, inputs): # 分路径处理每个输入特征 spline_outputs = [] for i in range(inputs.shape[-1]): feature = inputs[..., i:i+1] spline_outputs.append(self.bspline_layer(feature)) # 合并并添加偏置 combined = tf.concat(spline_outputs, axis=-1) return combined + self.bias
04-01
帮我整段修改一下,改成TensorFlow2.11版本可用的:“ def TGCN(_X, _weights, _biases): ### cell_1 = tgcnCell(cell=custom_cell,gru_units=gru_units, adj=adj, num_nodes=num_nodes) cell = tf.nn.rnn_cell.MultiRNNCell([cell_1], state_is_tuple=True) _X = tf.unstack(_X, axis=1) outputs, states = tf.nn.static_rnn(cell, _X, dtype=tf.float32) m = [] for i in outputs: o = tf.reshape(i,shape=[-1,num_nodes,gru_units]) o = tf.reshape(o,shape=[-1,gru_units]) m.append(o) last_output = m[-1] output = tf.matmul(last_output, _weights['out']) + _biases['out'] output = tf.reshape(output,shape=[-1,num_nodes,pre_len]) output = tf.transpose(output, perm=[0,2,1]) output = tf.reshape(output, shape=[-1,num_nodes]) return output, m, states ###### placeholders ###### # 使用 tf.placeholder inputs = tf.compat.v1.placeholder(tf.float32, shape=[None, seq_len, num_nodes]) labels = tf.compat.v1.placeholder(tf.float32, shape=[None, pre_len, num_nodes]) # Graph weights weights = { 'out': tf.Variable(tf.random.normal([gru_units, pre_len], mean=1.0), name='weight_o')} biases = { 'out': tf.random.normal(shape=[pre_len],name='bias_o')} if model_name == 'tgcn': pred,ttts,ttto = TGCN(inputs, weights, biases) y_pred = pred ###### optimizer ###### lambda_loss = 0.0015 Lreg = lambda_loss * sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()) label = tf.reshape(labels, [-1,num_nodes]) ##loss loss = tf.reduce_mean(tf.nn.l2_loss(y_pred-label) + Lreg) ##rmse error = tf.sqrt(tf.reduce_mean(tf.square(y_pred-label))) optimizer = tf.train.AdamOptimizer(lr).minimize(loss) ###### Initialize session ###### variables = tf.global_variables() saver = tf.train.Saver(tf.global_variables()) #sess = tf.Session() gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) sess.run(tf.global_variables_initializer())”
04-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值