Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conolutional Neural Network: float() argument must be a string or a number? #7421

Closed
malamo opened this issue Jul 25, 2017 · 9 comments
Closed

Comments

@malamo
Copy link

malamo commented Jul 25, 2017

I want to train my data with a conventional neural network (CNN),I start with reshaping my data than creating my model:

model = Sequential()
input_traces = Input(shape=(3253,))

model.add(Convolution1D(nb_filter=32, filter_length=3, border_mode='same', 
activation='relu',input_dim=input_traces))                      
model.add(MaxPooling1D(pool_length=2))
model.add(Flatten())
model.add(Dense(250, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=
['accuracy'])
print(model.summary())
model.fit(x_train, y_train, batch_size=15, nb_epoch=30, show_accuracy=True, 
validation_data=(x_test, y_test))

But this code gives me this error:

CNN_Based_Attack.py:139: UserWarning: Update your `Conv1D` call to the Keras 2 API: `Conv1D(activation="relu", input_shape=(None, /in..., padding="same", filters=32, kernel_size=3)`
  model.add(Convolution1D(nb_filter=32, filter_length=3, border_mode='same', activation='relu',input_dim=input_traces))
Traceback (most recent call last):
  File "CNN_Based_Attack.py", line 139, in <module>
    model.add(Convolution1D(nb_filter=32, filter_length=3, border_mode='same', activation='relu',input_dim=input_traces))
  File "/home/.local/lib/python2.7/site-packages/keras/models.py", line 430, in add
    layer(x)
  File "/home/.local/lib/python2.7/site-packages/keras/engine/topology.py", line 557, in __call__
    self.build(input_shapes[0])
  File "/home/.local/lib/python2.7/site-packages/keras/layers/convolutional.py", line 134, in build
    constraint=self.kernel_constraint)
  File "/home/.local/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)
  File "/home/.local/lib/python2.7/site-packages/keras/engine/topology.py", line 390, in add_weight
    weight = K.variable(initializer(shape), dtype=dtype, name=name)
  File "/home/.local/lib/python2.7/site-packages/keras/initializers.py", line 200, in __call__
    scale /= max(1., float(fan_in + fan_out) / 2)
TypeError: float() argument must be a string or a number.

I really don't understand this error. Could you please help me.

@Dref360
Copy link
Contributor

Dref360 commented Jul 25, 2017

You're trying to mix the Functional API and the Sequential API.
If you want to use the Sequential API, do not use an Input layer. Please see the documentation
https://keras.io/getting-started/sequential-model-guide/

@stale
Copy link

stale bot commented Oct 23, 2017

This issue has been automatically marked as stale because it has not had recent activity. It will be closed after 30 days if no further activity occurs, but feel free to re-open a closed issue if needed.

@stale stale bot added the stale label Oct 23, 2017
@stale stale bot closed this as completed Nov 22, 2017
@soufianesabiri
Copy link

Hello,

I am facing same issue, though I AM not mixing APIs, I am using functional API. Please help!

@MSA8D8
Copy link

MSA8D8 commented Jun 12, 2019

Hello

I also have the same problem.
And, I also use functional API only.

Traceback (most recent call last): File "/Volumes/disk2s1/experiment/Script/Python/Behavior_analysis/DNN.py", line 158, in <module> main() File "/Volumes/disk2s1/experiment/Script/Python/Behavior_analysis/DNN.py", line 155, in main eval.calculate_DNN() File "/Volumes/disk2s1/experiment/Script/Python/Behavior_analysis/DNN.py", line 149, in calculate_DNN self.CNN_with_Keras(mel,chr) File "/Volumes/disk2s1/experiment/Script/Python/Behavior_analysis/DNN.py", line 117, in CNN_with_Keras x = GRU(200, return_sequences=True, dropout=0.5)(x) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/layers/recurrent.py", line 532, in __call__ return super(RNN, self).__call__(inputs, **kwargs) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/engine/base_layer.py", line 431, in __call__ self.build(unpack_singleton(input_shapes)) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/layers/recurrent.py", line 493, in build self.cell.build(step_input_shape) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/layers/recurrent.py", line 1273, in build constraint=self.kernel_constraint) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper return func(*args, **kwargs) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/engine/base_layer.py", line 249, in add_weight weight = K.variable(initializer(shape), File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/initializers.py", line 209, in __call__ scale /= max(1., float(fan_in + fan_out) / 2) TypeError: float() argument must be a string or a number, not 'Dimension'

@Lanme
Copy link

Lanme commented Aug 1, 2019

Hello

I also have the same problem.
And, I also use functional API only.

Traceback (most recent call last): File "/Volumes/disk2s1/experiment/Script/Python/Behavior_analysis/DNN.py", line 158, in <module> main() File "/Volumes/disk2s1/experiment/Script/Python/Behavior_analysis/DNN.py", line 155, in main eval.calculate_DNN() File "/Volumes/disk2s1/experiment/Script/Python/Behavior_analysis/DNN.py", line 149, in calculate_DNN self.CNN_with_Keras(mel,chr) File "/Volumes/disk2s1/experiment/Script/Python/Behavior_analysis/DNN.py", line 117, in CNN_with_Keras x = GRU(200, return_sequences=True, dropout=0.5)(x) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/layers/recurrent.py", line 532, in __call__ return super(RNN, self).__call__(inputs, **kwargs) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/engine/base_layer.py", line 431, in __call__ self.build(unpack_singleton(input_shapes)) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/layers/recurrent.py", line 493, in build self.cell.build(step_input_shape) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/layers/recurrent.py", line 1273, in build constraint=self.kernel_constraint) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper return func(*args, **kwargs) File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/engine/base_layer.py", line 249, in add_weight weight = K.variable(initializer(shape), File "/Users/masaru/.pyenv/versions/3.7.2/lib/python3.7/site-packages/keras/initializers.py", line 209, in __call__ scale /= max(1., float(fan_in + fan_out) / 2) TypeError: float() argument must be a string or a number, not 'Dimension'

Have you solved?

@aramhamidi
Copy link

I am having the same problem.
self.encoded2 = Dense(nodes, activation=act)(self.encoded2)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/base_layer.py", line 431, in call
self.build(unpack_singleton(input_shapes))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/layers/core.py", line 866, in build
constraint=self.kernel_constraint)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/base_layer.py", line 249, in add_weight
weight = K.variable(initializer(shape),
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/initializers.py", line 209, in call
scale /= max(1., float(fan_in + fan_out) / 2)
TypeError: float() argument must be a string or a number, not 'Dimension'

Any advice?

@kevinco27
Copy link

kevinco27 commented Oct 12, 2019

I encountered this issue while stacking GRU layer in a functional API fashion and solved the problem by making a minor change to the Keras source code.
The problem of this issue is that the type of a tensor shape isn't properly cast to int type recognized by float function.

In my case, I add a line of code, which transform Dimension type of a shape to int type, below the build function of recurrent.py at line 440. The code is as follow, and my Keras version is 2.1.5.

def build(self, input_shape):
        # Note input_shape will be list of shapes of initial states and
        # constants if these are passed in __call__.
	input_shape = tuple([i if (isinstance(i, int) or i is None else i.value for i in input_shape)]) # casting "Dimension" type of input_shape's elements to "int" type
				
	if self._num_constants is not None:
            constants_shape = input_shape[-self._num_constants:]
        else:
            constants_shape = None

        if isinstance(input_shape, list):
            input_shape = input_shape[0]

If you encountered the issue when building another layer, you may find the build function in related file and modify the code like above.

@kevinco27
Copy link

I encountered this issue while stacking GRU layer in a functional API fashion and solved the problem by making a minor change to the Keras source code.
The problem of this issue is that the type of a tensor shape isn't properly cast to int type recognized by float function.

In my case, I add a line of code, which transform Dimension type of a shape to int type, below the build function of recurrent.py at line 440. The code is as follow, and my Keras version is 2.1.5.

def build(self, input_shape):
        # Note input_shape will be list of shapes of initial states and
        # constants if these are passed in __call__.
	input_shape = tuple([i if (isinstance(i, int) or i is None else i.value for i in input_shape)]) # casting "Dimension" type of input_shape's elements to "int" type
				
	if self._num_constants is not None:
            constants_shape = input_shape[-self._num_constants:]
        else:
            constants_shape = None

        if isinstance(input_shape, list):
            input_shape = input_shape[0]

If you encountered the issue when building another layer, you may find the build function in related file and modify the code like above.

Or if you use Reshape layer with tensor shape as argument, like tensor.shape[1], you can just change tensor.shape[1] to tensor.shape[1].value that is int instead of 'tensorflow.python.framework.tensor_shape.Dimension'

@TomMeowMeow
Copy link

I encountered this issue while stacking GRU layer in a functional API fashion and solved the problem by making a minor change to the Keras source code.
The problem of this issue is that the type of a tensor shape isn't properly cast to int type recognized by float function.
In my case, I add a line of code, which transform Dimension type of a shape to int type, below the build function of recurrent.py at line 440. The code is as follow, and my Keras version is 2.1.5.

def build(self, input_shape):
        # Note input_shape will be list of shapes of initial states and
        # constants if these are passed in __call__.
	input_shape = tuple([i if (isinstance(i, int) or i is None else i.value for i in input_shape)]) # casting "Dimension" type of input_shape's elements to "int" type
				
	if self._num_constants is not None:
            constants_shape = input_shape[-self._num_constants:]
        else:
            constants_shape = None

        if isinstance(input_shape, list):
            input_shape = input_shape[0]

If you encountered the issue when building another layer, you may find the build function in related file and modify the code like above.

Or if you use Reshape layer with tensor shape as argument, like tensor.shape[1], you can just change tensor.shape[1] to tensor.shape[1].value that is int instead of 'tensorflow.python.framework.tensor_shape.Dimension'

Thanks, change tensor.shape[1] to tensor.shape[1].value work for me, thanks !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants