Git Product home page Git Product logo

tf_siren's Introduction

Tensorflow Sinusodial Representation Networks (SIREN)

Tensorflow 2.0 implementation of Sinusodial Representation networks (SIREN) from the paper Implicit Neural Representations with Periodic Activation Functions.

Installation

  • Pip install
$ pip install --upgrade tf_siren
  • Pip install (test support)
$ pip install --upgrade tf_siren[tests]

Usage

For general usage equivalent to the paper, import and use either SinusodialRepresentationDense or SIRENModel.

from tf_siren import SinusodialRepresentationDense
from tf_siren import SIRENModel

# You can use SinusodialRepresentationDense exactly like you ordinarily use Dense layers.
ip = tf.keras.layers.Input(shape=[2])
x = SinusodialRepresentationDense(32,
                                  activation='sine', # default activation function
                                  w0=1.0)(ip)        # w0 represents sin(w0 * x) where x is the input.
                                  
model = tf.keras.Model(inputs=ip, outputs=x)

# Or directly use the model class to build a multi layer SIREN
model = SIRENModel(units=256, final_units=3, final_activation='sigmoid',
                   num_layers=5, w0=1.0, w0_initial=30.0)

For the (experimental) kernel scaled variants, import and use either ScaledSinusodialRepresentationDense or ScaledSIRENModel.

from tf_siren import ScaledSinusodialRepresentationDense
from tf_siren import ScaledSIRENModel

# You can use SinusodialRepresentationDense exactly like you ordinarily use Dense layers.
ip = tf.keras.layers.Input(shape=[2])
x = ScaledSinusodialRepresentationDense(32,
                                        scale=1.0          # scale value should be carefully chosen in range [1, 2]
                                        activation='sine', # default activation function
                                        w0=1.0)(ip)        # w0 represents sin(w0 * x) where x is the input.
                                  
model = tf.keras.Model(inputs=ip, outputs=x)

# Or directly use the model class to build a multi layer Scaled SIREN
model = ScaledSIRENModel(units=256, final_units=3, final_activation='sigmoid', scale=1.0,
                         num_layers=5, w0=1.0, w0_initial=30.0)

Results on Image Inpainting task

A partial implementation of the image inpainting task is available as the train_inpainting_siren.py and eval_inpainting_siren.py scripts inside the scripts directory.

Weight files are made available in the repository under the Release tab of the project. Extract the weights and place the checkpoints folder at the scripts directory

These weights generates the following output after 5000 epochs of training with batch size 8192 while using only 10% of the available pixels in the image during training phase.


If we train for using only 20% of the available pixels in the image during training phase -


If we train for using only 30% of the available pixels in the image during training phase -

SIREN Hyper Network

We can use a Hyper Network in order to encode an entire dataset into the weights of a SIREN model. The weights for the SIREN model are generated by this hyper network, which computes these weights based on an encoded representation.

Support for the Hyper Network is available by using NeuralProcessHyperNet, which uses the SetEncoder from the paper as the encoder.

Training on the CIFAR 10 dataset is available inside the scripts directory - train_cifar_inpainting_siren.py and eval_cifar_inpainting_siren.py.

Pre-trained weights are available in the Release tab under assets.

On evaluating on the test set with 1000 context pixels, this model gets an average MSE of 0.009. Using 100 context pixels, the MSE increases to 0.019.

The following image is using 1000 context pixels on the test set :

(Experimental) Comparison of convergence between original and kernel scaled SIRENs

The kernel scaled variants of the model converge faster than the original SIREN under certain circumstances. All the models below are trained with Adam optimizer with constant learning rate of 5e-5 for 5000 epochs and batch size of 8192 on the same image pixels (10% of the celtic spiral image).

The tensorboard logs can be found here -

Citation

@inproceedings{sitzmann2019siren,
    author = {Sitzmann, Vincent
              and Martel, Julien N.P.
              and Bergman, Alexander W.
              and Lindell, David B.
              and Wetzstein, Gordon},
    title = {Implicit Neural Representations
              with Periodic Activation Functions},
    booktitle = {arXiv},
    year={2020}
}

Requirements

  • Tensorflow 2.0+
  • Matplotlib to visualize eval result

tf_siren's People

Contributors

jackietung1219 avatar justindujardin avatar titu1994 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

tf_siren's Issues

Loading models that use SIREN

Hi. I am unable to load my SIREN model with the Keras load_model function due to the following errors:

TypeError: __init__() missing 1 required positional argument: 'units'
ValueError: Unknown activation function: Sine

I had trained a CycleGAN model and want to load the saved weights but unable to do so.
Kindly look into it.

The Naming of "custom_objects"

Hi, about the source code of "siren.py",

tf.keras.utils.get_custom_objects().update({
    'sine': Sine,
    'siren_uniform': SIRENInitializer,
    'siren_first_uniform': SIRENFirstLayerInitializer,
    'SinusodialRepresentationDense': SinusodialRepresentationDense,
    'ScaledSinusodialRepresentationDense': ScaledSinusodialRepresentationDense,
})

I think the purpose of the code is to make custom object available by calling "tf.keras.utils.get_custom_objects()".

Therefore I would like to ask why the name declared be like
"sine" but not "Sine";
"siren_uniform" but not "SIRENInitializer";
"siren_first_uniform" but not "SIRENFirstLayerInitializer"?

I think it should be like

tf.keras.utils.get_custom_objects().update({
    'Sine': Sine,
    'SIRENInitializer': SIRENInitializer,
    'SIRENFirstLayerInitializer': SIRENFirstLayerInitializer,
    'SinusodialRepresentationDense': SinusodialRepresentationDense,
    'ScaledSinusodialRepresentationDense': ScaledSinusodialRepresentationDense,
})

And loading model can be achieved by utilizing

load_model =
keras.models.load_model('./weight_model.h5',custom_objects=tf.keras.utils.get_custom_objects())

Cuz the native name of the class usually be like: Sine.__name__ = "Sine"

Is there other purpose intended to be done, so that we cannot use the origin class name directly?
Thank you!

can it be used in tensorflow=1.1x

my original coda is in tensorflow=1.13,and i tried tranforming it in tf2.0.But it is a big work,i just want to use it as a activation,coule give me a simple way to address it?thx

Why Sine activation function as a network layer in use?

Thank you for your contribution!

I saw in the SinusodialRepresentationDense layer that the Sine activation function was passed as a network layer? Is there any benefit to doing this?

And what happens if I change it to normal function?

Thank you very much!

How to use SIREN activation with ResNet?

Thank you for this interesting project but I was interested to know how can we use the siren activation with any other deep model such as ResNet, DenseNet, etc?

Currently, I guess the implementation is for MLP kind networks only.

Can you also provide a python file or some hints for say doing inpainting using Resnet-18 with ReLU non-linearity replaced with SIREN.

Thank you

TypeError reported when running with tensorflow2.0.0

Hi,

I was trying to run the example code train_cifar_inpainting_siren.py with tensorflow 2.0.0, however, it reported the following error:

Traceback (most recent call last):
  File "train_cifar_inpainting_siren.py", line 62, in <module>
    _ = model(dummy_input)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py", line 891, in __call__
    outputs = self.call(cast_inputs, *args, **kwargs)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py", line 457, in __call__
    result = self._call(*args, **kwds)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py", line 503, in _call
    self._initialize(args, kwds, add_initializers_to=initializer_map)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py", line 408, in _initialize
    *args, **kwds))
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1848, in _get_concrete_function_internal_garbage_collected
    graph_function, _, _ = self._maybe_define_function(args, kwargs)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 2150, in _maybe_define_function
    graph_function = self._create_graph_function(args, kwargs)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 2041, in _create_graph_function
    capture_by_value=self._capture_by_value),
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py", line 915, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py", line 358, in wrapped_fn
    return weak_wrapped_fn().__wrapped__(*args, **kwds)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 2658, in bound_method_wrapper
    return wrapped_fn(*args, **kwargs)
  File "/home/lynne/.local/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py", line 905, in wrapper
    raise e.ag_error_metadata.to_exception(e)
TypeError: in converted code:
    relative to /home/lynne:

    Downloads/tf_SIREN-master_new/tf_SIREN-master/tf_siren/hypernet.py:95 call  *
        param_list = self.hyper_net(embeddings)
    .local/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py:847 __call__
        outputs = call_fn(cast_inputs, *args, **kwargs)
    Downloads/tf_SIREN-master_new/tf_SIREN-master/tf_siren/meta/meta_siren_mlp.py:99 call  *
        params = layer(context=context)

    TypeError: __call__() missing 1 required positional argument: 'inputs'

Any way to solve this problem? Thanks a lot.

different results from "SinusodialRepresentationDense" and "SIRENModel"

Thanks for the great work, Somshubra!
I tried to use both the Layer class and the Model Class to build the same model structure with exactly the same parameters, and I found that the Model Class (SIRENModel) is consistently better than the model created using the Layer Class "SinusodialRepresentationDense", for at least 10 repeated tests. this makes me realize there must be some difference between my implementation using Layer class and your SIRENModel. However, after reading through your code, I could not figure it out. Please advise if you have time. Thanks!

Here is the code scripts for the three model implementation. the MODEL 3 is consistently better than the other two.

Model 1 using the Layer Class:


ip = tf.keras.layers.Input(shape=[1])
xp = SinusodialRepresentationDense(units = 12,
activation='sine', # default activation function
w0=0.2)(ip) # w0 represents sin(w0 * x) where x is the input.
xp = SinusodialRepresentationDense(units = 12,
activation='sine',
w0 = 1.0)(xp)
xp = SinusodialRepresentationDense(units = 12,
activation='sine',
w0 = 1.0)(xp)
xp = SinusodialRepresentationDense(units = 1,
activation='linear')(xp)
model = tf.keras.Model(inputs=ip, outputs=xp)


Model 2 using the Layer Class:


w0=1.0
w0_initial=0.2
model = keras.Sequential([
SinusodialRepresentationDense(units=12, w0= w0_initial),
SinusodialRepresentationDense(units=12, w0=w0),
SinusodialRepresentationDense(units=12, w0=w0),
SinusodialRepresentationDense(units =1, activation='linear')])


Model 3 using the MODEL Class (always better results):


model = SIRENModel(units=12, final_units=1, final_activation='linear',
num_layers=3, w0=1.0, w0_initial=0.2)


Would it be possible to use SIREN on 2D CNN?

Hi, I like SIREN and implemented it on my network. However, the number of network parameters would be huge if use original image without sampling (I flattened the image directly, then use dense layers to construct the network). I am wondering if it is possible to use SIREN on 2D CNN? Thanks a lot.

Can it be used on tensorflow>= 2.2.0?

Hi, I watched the video and really like your excellent work. When I try to install it, the version error was shown. Is it possible to use it in a higher tensorflow version? Or I have to change my tensorflow version?

Collecting tensorflow>=2.2.0 (from tf-siren)
  Could not find a version that satisfies the requirement tensorflow>=2.2.0 (from tf-siren) (from versions: 0.12.1, 1.0.0, 1.0.1, 1.1.0rc0, 1.1.0rc1, 1.1.0rc2, 1.1.0, 1.2.0rc0, 1.2.0rc1, 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.4.1, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.5.1, 1.6.0rc0, 1.6.0rc1, 1.6.0, 1.7.0rc0, 1.7.0rc1, 1.7.0, 1.7.1, 1.8.0rc0, 1.8.0rc1, 1.8.0, 1.9.0rc0, 1.9.0rc1, 1.9.0rc2, 1.9.0, 1.10.0rc0, 1.10.0rc1, 1.10.0, 1.10.1, 1.11.0rc0, 1.11.0rc1, 1.11.0rc2, 1.11.0, 1.12.0rc0, 1.12.0rc1, 1.12.0rc2, 1.12.0, 1.12.2, 1.12.3, 1.13.0rc0, 1.13.0rc1, 1.13.0rc2, 1.13.1, 1.13.2, 1.14.0rc0, 1.14.0rc1, 1.14.0, 2.0.0a0, 2.0.0b0, 2.0.0b1)
No matching distribution found for tensorflow>=2.2.0 (from tf-siren)

why no validation?

I am wondering why you haven't implemented any validation code for the cifar hypernetwork experiment? Is there no danger of overfitting, or is overfitting something you want to do?

Thank you for your code!

Problem when loading a model

Hey, that's a really nice implementation =)
I'm using tf2.3.1 and training works perfectly but when I save and load a model I get this error message:

File "D:\virtualenv\tensorflow2\lib\site-packages\tensorflow\python\ops\init_ops_v2.py", line 90, in from_config
return cls(**config)
TypeError: init() got an unexpected keyword argument 'scale'

Before loading the model I'm already setting up the custom objects with:
tf.keras.utils.get_custom_objects().update({
'Sine': Sine,
'SIRENInitializer': SIRENInitializer,
'SIRENFirstLayerInitializer': SIRENFirstLayerInitializer,
'SinusodialRepresentationDense': SinusodialRepresentationDense,
'ScaledSinusodialRepresentationDense': ScaledSinusodialRepresentationDense,
})
model = tf.keras.models.load_model(str(modelPath))

I'm only using SinusodialRepresentationDense in my model and there is indeed a scale variable passed to tf.keras.initializers.VarianceScaling in the SIRENInitializer, but I'm not sure where the problem is =(

I hoped you could help me out here.
Cheers,
Flo

duplicate multiplication of w0 ?

First of all: Thanks for providing an implementation of SIREN for tensorflow so quickly after the release of the paper!

I did notice that there are 2 places where w0 multiplication is applied:

  1. directly inside the dense layer call:

https://github.com/titu1994/tf_SIREN/blob/master/tf_siren/siren.py#L124 (along with the other if-cases)

  1. after the call, within the activation layer: https://github.com/titu1994/tf_SIREN/blob/master/tf_siren/siren.py#L25

Is this intended?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.