Get the value of some weights in a model trained by TensorFlow

前端 未结 3 486
温柔的废话
温柔的废话 2020-11-27 12:12

I have trained a ConvNet model with TensorFlow, and I want to get a particular weight in layer. For example in torch7 I would simply access model.modules[2].weights

3条回答
  •  悲哀的现实
    2020-11-27 12:56

    2.0 Compatible Answer: If we build a Model using Keras Sequential API, we can get the Weights of the Model using the code mentioned below:

    !pip install tensorflow==2.1
    
    from tf.keras import Sequential
    
    model = Sequential()
    
    model.add(Conv2D(filters=conv1_fmaps, kernel_size=conv1_ksize,
                             strides=conv1_stride, padding=conv1_pad,
                             activation=tf.nn.relu, input_shape=(height, width, channels),
                        data_format='channels_last'))
    
    model.add(MaxPool2D(pool_size = (2,2), strides= (2,2), padding="VALID"))
    
    model.add(Dropout(0.25))
    
    model.add(Flatten())
    
    model.add(Dense(units = 32, activation = 'relu'))
    
    model.add(Dense(units = 10, activation = 'softmax'))
    
    model.summary()
    
    print(model.trainable_variables) 
    

    The Last Statement, print(model.trainable_variables), will return the Weights of the Model as shown below:

        [,
     , , , , ]
    

提交回复
热议问题