[tensorflow]设置随机种子

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

设置全局随机种子

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

tf.random.set_seed(123)

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

train.py

import tensorflow as tf
from tensorflow import keras
import CSDNet18
tf.random.set_seed(123)
if __name__ == '__main__':
	cfg = 1
	CSDNet18_ = CSDNet18(cfg)
	layer = CSDNet18_(data)

CSDNet18.py

import FeatureNet
class CSDNet18(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

你可能感兴趣的:(Tensorflow学习,tensorflow,深度学习,python)