How can I deal with this code error which happens in my custom layer in Keras?












1















I want to make a custom layer in Keras.
In this example, I use a variable to multiply the tensor, but i get the error which is




in /keras/engine/training_arrays.py, line 304, in predict_loop
outs[i][batch_start:batch_end] = batch_out ValueError: could not broadcast input array from shape (36) into shape (2).




Actually i have check this file, but i get nothing. Is there some wrong in my custom layer?



#the definition of mylayer.


from keras import backend as K
import keras
from keras.engine.topology import Layer

class mylayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(mylayer, self).__init__(**kwargs)

def build(self, input_shape):
self.kernel = self.add_weight(name = 'kernel',
shape=(1,),dtype='float32',trainable=True,initializer='uniform')
super(mylayer, self).build(input_shape)

def call(self, inputs, **kwargs):
return self.kernel * inputs[0]
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[1])


#the test of mylayer.

from mylayer import mylayer
from tensorflow import keras as K
import numpy as np
from keras.layers import Input, Dense, Flatten
from keras.models import Model

x_train = np.random.random((2, 3, 4, 3))
y_train = np.random.random((2, 36))
print(x_train)

x = Input(shape=(3, 4, 3))
y = Flatten()(x)
output = mylayer((36, ))(y)

model = Model(inputs=x, outputs=output)

model.summary()

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(x_train, y_train, epochs=2)

hist = model.predict(x_train,batch_size=2)

print(hist)

print(model.get_layer(index=1).get_weights())


#So is there some wrong in my custom error?


Especially, when i train this net, it's ok,but when i try to use "prdict", it's wrong.










share|improve this question

























  • Show us the full error traceback as code-formatted text.

    – Klaus D.
    Jan 1 at 8:54
















1















I want to make a custom layer in Keras.
In this example, I use a variable to multiply the tensor, but i get the error which is




in /keras/engine/training_arrays.py, line 304, in predict_loop
outs[i][batch_start:batch_end] = batch_out ValueError: could not broadcast input array from shape (36) into shape (2).




Actually i have check this file, but i get nothing. Is there some wrong in my custom layer?



#the definition of mylayer.


from keras import backend as K
import keras
from keras.engine.topology import Layer

class mylayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(mylayer, self).__init__(**kwargs)

def build(self, input_shape):
self.kernel = self.add_weight(name = 'kernel',
shape=(1,),dtype='float32',trainable=True,initializer='uniform')
super(mylayer, self).build(input_shape)

def call(self, inputs, **kwargs):
return self.kernel * inputs[0]
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[1])


#the test of mylayer.

from mylayer import mylayer
from tensorflow import keras as K
import numpy as np
from keras.layers import Input, Dense, Flatten
from keras.models import Model

x_train = np.random.random((2, 3, 4, 3))
y_train = np.random.random((2, 36))
print(x_train)

x = Input(shape=(3, 4, 3))
y = Flatten()(x)
output = mylayer((36, ))(y)

model = Model(inputs=x, outputs=output)

model.summary()

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(x_train, y_train, epochs=2)

hist = model.predict(x_train,batch_size=2)

print(hist)

print(model.get_layer(index=1).get_weights())


#So is there some wrong in my custom error?


Especially, when i train this net, it's ok,but when i try to use "prdict", it's wrong.










share|improve this question

























  • Show us the full error traceback as code-formatted text.

    – Klaus D.
    Jan 1 at 8:54














1












1








1








I want to make a custom layer in Keras.
In this example, I use a variable to multiply the tensor, but i get the error which is




in /keras/engine/training_arrays.py, line 304, in predict_loop
outs[i][batch_start:batch_end] = batch_out ValueError: could not broadcast input array from shape (36) into shape (2).




Actually i have check this file, but i get nothing. Is there some wrong in my custom layer?



#the definition of mylayer.


from keras import backend as K
import keras
from keras.engine.topology import Layer

class mylayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(mylayer, self).__init__(**kwargs)

def build(self, input_shape):
self.kernel = self.add_weight(name = 'kernel',
shape=(1,),dtype='float32',trainable=True,initializer='uniform')
super(mylayer, self).build(input_shape)

def call(self, inputs, **kwargs):
return self.kernel * inputs[0]
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[1])


#the test of mylayer.

from mylayer import mylayer
from tensorflow import keras as K
import numpy as np
from keras.layers import Input, Dense, Flatten
from keras.models import Model

x_train = np.random.random((2, 3, 4, 3))
y_train = np.random.random((2, 36))
print(x_train)

x = Input(shape=(3, 4, 3))
y = Flatten()(x)
output = mylayer((36, ))(y)

model = Model(inputs=x, outputs=output)

model.summary()

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(x_train, y_train, epochs=2)

hist = model.predict(x_train,batch_size=2)

print(hist)

print(model.get_layer(index=1).get_weights())


#So is there some wrong in my custom error?


Especially, when i train this net, it's ok,but when i try to use "prdict", it's wrong.










share|improve this question
















I want to make a custom layer in Keras.
In this example, I use a variable to multiply the tensor, but i get the error which is




in /keras/engine/training_arrays.py, line 304, in predict_loop
outs[i][batch_start:batch_end] = batch_out ValueError: could not broadcast input array from shape (36) into shape (2).




Actually i have check this file, but i get nothing. Is there some wrong in my custom layer?



#the definition of mylayer.


from keras import backend as K
import keras
from keras.engine.topology import Layer

class mylayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(mylayer, self).__init__(**kwargs)

def build(self, input_shape):
self.kernel = self.add_weight(name = 'kernel',
shape=(1,),dtype='float32',trainable=True,initializer='uniform')
super(mylayer, self).build(input_shape)

def call(self, inputs, **kwargs):
return self.kernel * inputs[0]
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[1])


#the test of mylayer.

from mylayer import mylayer
from tensorflow import keras as K
import numpy as np
from keras.layers import Input, Dense, Flatten
from keras.models import Model

x_train = np.random.random((2, 3, 4, 3))
y_train = np.random.random((2, 36))
print(x_train)

x = Input(shape=(3, 4, 3))
y = Flatten()(x)
output = mylayer((36, ))(y)

model = Model(inputs=x, outputs=output)

model.summary()

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(x_train, y_train, epochs=2)

hist = model.predict(x_train,batch_size=2)

print(hist)

print(model.get_layer(index=1).get_weights())


#So is there some wrong in my custom error?


Especially, when i train this net, it's ok,but when i try to use "prdict", it's wrong.







python keras






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 1 at 9:10









Joey Mallone

2,15141731




2,15141731










asked Jan 1 at 8:51









cb zhangcb zhang

82




82













  • Show us the full error traceback as code-formatted text.

    – Klaus D.
    Jan 1 at 8:54



















  • Show us the full error traceback as code-formatted text.

    – Klaus D.
    Jan 1 at 8:54

















Show us the full error traceback as code-formatted text.

– Klaus D.
Jan 1 at 8:54





Show us the full error traceback as code-formatted text.

– Klaus D.
Jan 1 at 8:54












1 Answer
1






active

oldest

votes


















0














Your shape of self.kernel * inputs[0] is (36,), but your expectation is (?,36). Change it:



def call(self, inputs, **kwargs):
return self.kernel * inputs


If you want to output the weight of mylayer, you should set index=2.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994158%2fhow-can-i-deal-with-this-code-error-which-happens-in-my-custom-layer-in-keras%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Your shape of self.kernel * inputs[0] is (36,), but your expectation is (?,36). Change it:



    def call(self, inputs, **kwargs):
    return self.kernel * inputs


    If you want to output the weight of mylayer, you should set index=2.






    share|improve this answer




























      0














      Your shape of self.kernel * inputs[0] is (36,), but your expectation is (?,36). Change it:



      def call(self, inputs, **kwargs):
      return self.kernel * inputs


      If you want to output the weight of mylayer, you should set index=2.






      share|improve this answer


























        0












        0








        0







        Your shape of self.kernel * inputs[0] is (36,), but your expectation is (?,36). Change it:



        def call(self, inputs, **kwargs):
        return self.kernel * inputs


        If you want to output the weight of mylayer, you should set index=2.






        share|improve this answer













        Your shape of self.kernel * inputs[0] is (36,), but your expectation is (?,36). Change it:



        def call(self, inputs, **kwargs):
        return self.kernel * inputs


        If you want to output the weight of mylayer, you should set index=2.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 1 at 9:14









        giser_yuganggiser_yugang

        1,7701419




        1,7701419
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994158%2fhow-can-i-deal-with-this-code-error-which-happens-in-my-custom-layer-in-keras%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas