tf.random_uniform函数和tf.zeros函数具体用法

本文详细介绍了TensorFlow中tf.random_uniform与tf.zeros函数的使用方法,包括参数解释及如何生成指定形状的随机张量和全零张量,适用于深度学习模型初始化。

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

tf.random_uniform用法:
random_uniform(
    shape,          一维整数张量或 Python 数组。输出张量的形状。
    minval=0,         dtype 类型的 0-D 张量或 Python 值;生成的随机值范围的下限;默认为0
    maxval=None,         dtype 类型的 0-D 张量或 Python 值。要生成的随机值范围的上限。如果 dtype 是浮点,则默认为1 。
    dtype=tf.float32,       输出的类型:float16、float32、float64、int32、orint64。
    seed=None,              一个 Python 整数。用于为分布创建一个随机种子。查看 tf.set_random_seed 行为。
    name=None           操作的名称(可选)
)
tf.zeros用法:
tf.zeros(
    shape,
    dtype=tf.float32,
    name=None
)

将下列代码修改成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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值