user3472360
user3472360

Reputation: 2095

How to use a list of layers in tensorflow 2.0?

The below code throws me an error "AttributeError: can't set attribute". I think this is because I am trying to put TensorFlow layers into an ordinary list.

Does anyone know how I can get around this and be able to create a list of layers? I don't want to use Sequential because it is less flexible.

In PyTorch they have ModuleLists which you can use instead of a list, is there an equivalent in TensorFlow I can use?

!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

class MyModel(Model):
  def __init__(self):
    super(MyModel, self).__init__()
    self.layers = self.create_layers()

  def create_layers(self):    
    layers = [Conv2D(32, 3, activation='relu'), Flatten(), 
              Dense(128, activation='relu'), Dense(10, activation='softmax')]
    return layers

  def call(self, x):
    for layer in self.layers:
      x = layer(x)
    return x

model = MyModel()

full problem

Upvotes: 7

Views: 9612

Answers (2)

Theron
Theron

Reputation: 697

Just see this example in tf2.0's tutorial about how to make a list of layers https://www.tensorflow.org/tutorials/generative/pix2pix

Upvotes: 1

edkeveked
edkeveked

Reputation: 18401

layers is a reserved name for the layers of the model. Consider using another attribute for the model.

import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

class MyModel(Model):
  def __init__(self):
    super(MyModel, self).__init__()
    self.layers_custom = self.create_layers()

  def create_layers(self):    
    layers = [Conv2D(32, 3, activation='relu'), Flatten(), 
              Dense(128, activation='relu'), Dense(10, activation='softmax')]
    return layers

  def call(self, x):
    for layer in self.layers_custom:
      x = layer(x)
    return x

model = MyModel()
print(model.layers)
print(model.layers_custom)

Upvotes: 4

Related Questions