[tensorflow]设置随机种子

本文介绍了如何在多文件的TensorFlow项目中统一设置随机种子,如在train.py中通过调用优快云et18.py和FeatureNet.py时,通过tf.random.set_seed(123)确保模型权重的可重复性。这个技巧对于需要模型复现的研究和开发至关重要。

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

这篇文章讲的非常详细.文章链接
根据复杂网络总结提炼一下:

设置全局随机种子

在定义网络结构的py文件上,加入下面的代码

tf.random.set_seed(123)

例如
我们的网络可能横跨很多个py文件,例如在train.py中,我们需要调用优快云et18.py中的网络结构.而优快云et18又要使用FeatureNet.我们只需要在:train.py中加入tf.random.set_seed(123)就可以了.
所有train.py中的网络模型权重都会设置种子为123

train.py

import tensorflow as tf
from tensorflow import keras
import 优快云et18
tf.random.set_seed(123)
if __name__ == '__main__':
	cfg = 1
	优快云et18_ = 优快云et18(cfg)
	layer = 优快云et18_(data)

优快云et18.py

import FeatureNet
class 优快云et18(Model):
    def __init__(self, cfg):
    	self.output_layer = keras.Sequential([
            layers.Dense(units=256, activation='relu',name='dense_1'),
            layers.Dense(units=128, activation='relu',name='dense_2'),
            layers.Dense(units=64, activation='relu',name='dense_3')])
        self.FeatureNet = FeatureNet(cfg)
    def call(self,data):
        # ==1.FeatureNet process==
        x = self.FeatureNet(data)
        # ==2.输出层==
        out = self.output_layer(x, training=training)  
        return out

FeatureNet.py

class FeatureNet(Model):
    def __init__(self, cfg):
        self.output_layer = keras.Sequential([
            layers.Dense(units=256, activation='relu',name='dense_1'),
            layers.Dense(units=128, activation='relu',name='dense_2'),
            layers.Dense(units=64, activation='relu',name='dense_3')])
    	
    def call(self,data):
        # ==1.输出层==
        out = self.output_layer(x, training=training) 
        return out
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值