diff --git "a/stackoverflow_DL-related_questions_data/data24.json" "b/stackoverflow_DL-related_questions_data/data24.json" new file mode 100644--- /dev/null +++ "b/stackoverflow_DL-related_questions_data/data24.json" @@ -0,0 +1,1735 @@ +{"QuestionId":58790899,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T16:55:20.927","AcceptedAnswerId":null,"OwnerUserId":11509379.0,"Title":"Value for attr 'T' of float is not in the list of allowed values: int32, int64","Body":"
class BilinearUpsampling(Layer):\n\n    def __init__(self, upsampling=(2, 2), output_size=None, data_format=None, **kwargs):\n\n        super(BilinearUpsampling, self).__init__(**kwargs)\n\n        self.data_format = K.normalize_data_format(data_format)\n        self.input_spec = InputSpec(ndim=4)\n        if output_size:\n            self.output_size = conv_utils.normalize_tuple(\n                output_size, 2, 'output_size')\n            self.upsampling = None\n        else:\n            self.output_size = None\n            self.upsampling = conv_utils.normalize_tuple(\n                upsampling, 2, 'upsampling')\n\n    def compute_output_shape(self, input_shape):\n        if self.upsampling:\n            height = self.upsampling[0] * \\\n                input_shape[1] if input_shape[1] is not None else None\n            width = self.upsampling[1] * \\\n                input_shape[2] if input_shape[2] is not None else None\n        else:\n            height = self.output_size[0]\n            width = self.output_size[1]\n        return (input_shape[0],\n                height,\n                width,\n                input_shape[3])\n\n    def call(self, inputs):\n        if self.upsampling:\n            return tf.image.resize_bilinear(inputs, (int(inputs.shape[1] * self.upsampling[0]),\n                                                       int(inputs.shape[2] * self.upsampling[1])))\n                                              #align_corners=True)\n        else:\n            return tf.image.resize_bilinear(inputs, (self.output_size[0],\n                                                       self.output_size[1]))\n                                              #align_corners=True)\n\n    def get_config(self):\n        config = {'upsampling': self.upsampling,\n                  'output_size': self.output_size,\n                  'data_format': self.data_format}\n        base_config = super(BilinearUpsampling, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\nclass BatchNorm(BatchNormalization):\n    def call(self, inputs, training=None):\n          return super(self.__class__, self).call(inputs, training=True)\n\ndef BN(input_tensor,block_id):\n    bn = BatchNorm(name=block_id+'_BN')(input_tensor)\n    a = Activation('relu',name=block_id+'_relu')(bn)\n    return a\n\ndef l1_reg(weight_matrix):\n    return K.mean(weight_matrix)\n\nclass Repeat(Layer):\n    def __init__(self,repeat_list, **kwargs):\n        super(Repeat, self).__init__(**kwargs)\n        self.repeat_list = repeat_list\n\n    def call(self, inputs):\n        outputs = tf.tile(inputs, self.repeat_list)\n        return outputs\n    def get_config(self):\n        config = {\n            'repeat_list': self.repeat_list\n        }\n        base_config = super(Repeat, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n    def compute_output_shape(self, input_shape):\n        output_shape = [None]\n        for i in range(1,len(input_shape)):\n            output_shape.append(input_shape[i]*self.repeat_list[i])\n        return tuple(output_shape)\n\ndef SpatialAttention(inputs,name):\n    k = 9\n    H, W, C = map(int,inputs.get_shape()[1:])\n    attention1 = Conv2D(C \/ 2, (1, k), padding='same', name=name+'_1_conv1')(inputs)\n    attention1 = BN(attention1,'attention1_1')\n    attention1 = Conv2D(1, (k, 1), padding='same', name=name + '_1_conv2')(attention1)\n    attention1 = BN(attention1, 'attention1_2')\n    attention2 = Conv2D(C \/ 2, (k, 1), padding='same', name=name + '_2_conv1')(inputs)\n    attention2 = BN(attention2, 'attention2_1')\n    attention2 = Conv2D(1, (1, k), padding='same', name=name + '_2_conv2')(attention2)\n    attention2 = BN(attention2, 'attention2_2')\n    attention = Add(name=name+'_add')([attention1,attention2])\n    attention = Activation('sigmoid')(attention)\n    attention = Repeat(repeat_list=[1, 1, 1, C])(attention)\n    return attention\n\ndef ChannelWiseAttention(inputs,name):\n    H, W, C = map(int, inputs.get_shape()[1:])\n    attention = GlobalAveragePooling2D(name=name+'_GlobalAveragePooling2D')(inputs)\n    attention = Dense(int(C \/ 4), activation='relu')(attention)\n    attention = Dense(C, activation='sigmoid',activity_regularizer=l1_reg)(attention)\n    attention = Reshape((1, 1, C),name=name+'_reshape')(attention)\n    attention = Repeat(repeat_list=[1, H, W, 1],name=name+'_repeat')(attention)\n    attention = Multiply(name=name + '_multiply')([attention, inputs])\n    return attention\n\nclass BatchNorm(BatchNormalization):\n    def call(self, inputs, training=None):\n          return super(self.__class__, self).call(inputs, training=True)\n\nclass Copy(Layer):\n    def call(self, inputs, **kwargs):\n        copy = tf.identity(inputs)\n        return copy\n    def compute_output_shape(self, input_shape):\n        return input_shape\n\nclass layertile(Layer):\n    def call(self, inputs, **kwargs):\n        image = tf.reduce_mean(inputs, axis=-1)\n        image = tf.expand_dims(image, -1)\n        image = tf.tile(image, [1, 1, 1, 32])\n        return image\n\n    def compute_output_shape(self, input_shape):\n        output_shape = list(input_shape)[:-1] + [32]\n        return tuple(output_shape)\n\n\ndef BN(input_tensor,block_id):\n    bn = BatchNorm(name=block_id+'_BN')(input_tensor)\n    a = Activation('relu',name=block_id+'_relu')(bn)\n    return a\n\ndef AtrousBlock(input_tensor, filters, rate, block_id, stride=1):\n    x = Conv2D(filters, (3, 3), strides=(stride, stride), dilation_rate=(rate, rate),\n               padding='same', use_bias=False, name=block_id + '_dilation')(input_tensor)\n    return x\n\n\ndef CFE(input_tensor, filters, block_id):\n    rate = [3, 5, 7]\n    cfe0 = Conv2D(filters, (1, 1), padding='same', use_bias=False, name=block_id + '_cfe0')(\n        input_tensor)\n    cfe1 = AtrousBlock(input_tensor, filters, rate[0], block_id + '_cfe1')\n    cfe2 = AtrousBlock(input_tensor, filters, rate[1], block_id + '_cfe2')\n    cfe3 = AtrousBlock(input_tensor, filters, rate[2], block_id + '_cfe3')\n    cfe_concat = Concatenate(name=block_id + 'concatcfe', axis=-1)([cfe0, cfe1, cfe2, cfe3])\n    cfe_concat = BN(cfe_concat, block_id)\n    return cfe_concat\n\n\ndef VGG16(img_input, dropout=False, with_CPFE=False, with_CA=False, with_SA=False, droup_rate=0.3):\n    # Block 1\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    C1 = x\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n    if dropout:\n        x = Dropout(droup_rate)(x)\n    # Block 2\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n    C2 = x\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n    if dropout:\n        x = Dropout(droup_rate)(x)\n    # Block 3\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n    C3 = x\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n    if dropout:\n        x = Dropout(droup_rate)(x)\n    # Block 4\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n    C4 = x\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n    if dropout:\n        x = Dropout(droup_rate)(x)\n    # Block 5\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n    if dropout:\n        x = Dropout(droup_rate)(x)\n    C5 = x\n    C1 = Conv2D(64, (3, 3), padding='same', name='C1_conv')(C1)\n    C1 = BN(C1, 'C1_BN')\n    C2 = Conv2D(64, (3, 3), padding='same', name='C2_conv')(C2)\n    C2 = BN(C2, 'C2_BN')\n    if with_CPFE:\n        C3_cfe = CFE(C3, 32, 'C3_cfe')\n        C4_cfe = CFE(C4, 32, 'C4_cfe')\n        C5_cfe = CFE(C5, 32, 'C5_cfe')\n        C5_cfe = BilinearUpsampling(upsampling=(4, 4), name='C5_cfe_up4')(C5_cfe)\n        C4_cfe = BilinearUpsampling(upsampling=(2, 2), name='C4_cfe_up2')(C4_cfe)\n        C345 = Concatenate(name='C345_aspp_concat', axis=-1)([C3_cfe, C4_cfe, C5_cfe])\n        if with_CA:\n            C345 = ChannelWiseAttention(C345, name='C345_ChannelWiseAttention_withcpfe')\n    C345 = Conv2D(64, (1, 1), padding='same', name='C345_conv')(C345)\n    C345 = BN(C345,'C345')\n    C345 = BilinearUpsampling(upsampling=(4, 4), name='C345_up4')(C345)\n\n    if with_SA:\n        SA = SpatialAttention(C345, 'spatial_attention')\n        C2 = BilinearUpsampling(upsampling=(2, 2), name='C2_up2')(C2)\n        C12 = Concatenate(name='C12_concat', axis=-1)([C1, C2])\n        C12 = Conv2D(64, (3, 3), padding='same', name='C12_conv')(C12)\n        C12 = BN(C12, 'C12')\n        C12 = Multiply(name='C12_atten_mutiply')([SA, C12])\n    fea = Concatenate(name='fuse_concat',axis=-1)([C12, C345])\n    sa = Conv2D(1, (3, 3), padding='same', name='sa')(fea)\n\n    model = Model(inputs=img_input, outputs=sa, name=\"BaseModel\")\n    return model\n\ndef padding(x):\n    h,w,c = x.shape\n    size = max(h,w)\n    paddingh = (size-h)\/\/2\n    paddingw = (size-w)\/\/2\n    temp_x = np.zeros((size,size,c))\n    temp_x[paddingh:h+paddingh,paddingw:w+paddingw,:] = x\n    return temp_x\n\ndef load_image(path):\n    x = cv2.imread(path)\n    sh = x.shape\n    x = np.array(x, dtype=np.int32)\n    x = x[..., ::-1]\n    # Zero-center by mean pixel\n    x[..., 0] -= 103.939\n    x[..., 1] -= 116.779\n    x[..., 2] -= 123.68\n    x = padding(x)\n    x = cv2.resize(x, target_size, interpolation=cv2.INTER_LINEAR)\n    x = np.expand_dims(x,0)\n    return x,sh\n\ndef cut(pridict,shape):\n    h,w,c = shape\n    size = max(h, w)\n    pridict = cv2.resize(pridict, (size,size))\n    paddingh = (size - h) \/\/ 2\n    paddingw = (size - w) \/\/ 2\n    return pridict[paddingh:h + paddingh, paddingw:w + paddingw]\n\ndef sigmoid(x):\n    return 1\/(1 + np.exp(-x))\n\ndef getres(pridict,shape):\n    pridict = sigmoid(pridict)*255\n    pridict = np.array(pridict, dtype=np.uint8)\n    pridict = np.squeeze(pridict)\n    pridict = cut(pridict, shape)\n    return pridict\n\ndef laplace_edge(x):\n    laplace = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])\n    edge = cv2.filter2D(x\/255.,-1,laplace)\n    edge = np.maximum(np.tanh(edge),0)\n    edge = edge * 255\n    edge = np.array(edge, dtype=np.uint8)\n    return edge\n\nmodel_name = 'x.h5'\n\ntarget_size = (256,256)\n\ndropout = False\nwith_CPFE = True\nwith_CA = True\nwith_SA = True\n\nif target_size[0 ] % 32 != 0 or target_size[1] % 32 != 0:\n    raise ValueError('Image height and wight must be a multiple of 32')\n\nmodel_input = Input(shape=(target_size[0],target_size[1],3))\nmodel = VGG16(model_input,dropout=dropout, with_CPFE=with_CPFE, with_CA=with_CA, with_SA=with_SA)\nmodel.load_weights(model_name,by_name=True)\n\nfor layer in model.layers:\n    layer.trainable = False\n\nimage_path = 'x.jpg'\nimg, shape = load_image(image_path)\nimg = np.array(img, dtype=np.int32)\nsa = model.predict(img)\nsa = getres(sa, shape)\nplt.title('saliency')\nplt.subplot(131)\nplt.imshow(cv2.imread(image_path))\nplt.subplot(132)\nplt.imshow(sa,cmap='gray')\nplt.subplot(133)\nedge = laplace_edge(sa)\nplt.imshow(edge,cmap='gray')\nplt.show()\n<\/code><\/pre>\n\n

Error:\nValue for attr 'T' of float is not in the list of allowed values: int32, int64\n ; NodeDef: {{node RandomUniform}}; Op output:dtype; attr=seed:int,default=0; attr=seed2:int,default=0; attr=dtype:type,allowed=[DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE]; attr=T:type,allowed=[DT_INT32, DT_INT64]; is_stateful=true> [Op:RandomUniform]<\/p>\n\n

I've changed C into int... Really don't know what else... <\/p>\n","answers":[]} +{"QuestionId":58791016,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T17:09:51.063","AcceptedAnswerId":null,"OwnerUserId":11522935.0,"Title":"Is that a good idea to use transfer learning in real world projects?","Body":"

SCENARIO<\/h1>\n\n

What if my intention is to train for a dataset of medical images and I have chosen a coco pre-trained model. <\/p>\n\n

My Doubts<\/h1>\n\n

1 Since I have chosen medical images there is no point of train it on COCO dataset, right? if so what is a possible solution to do the same?<\/em><\/p>\n\n

2 Adding more layers to a pre-trained model will screw the entire model? with classes of around 10 plus and 10000's of training datasets?<\/em><\/p>\n\n

3 Without train from scratch what are the possible solutions , like fine-tuning the model?<\/em><\/p>\n\n

PS<\/strong> - let's assume this scenario is based on deploying the model for business purposes.<\/p>\n\n

Thanks-<\/p>\n","answers":[]} +{"QuestionId":58791097,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T17:18:31.940","AcceptedAnswerId":null,"OwnerUserId":12351740.0,"Title":"Tensorflow estimator exported model is too big, how can i reduce it","Body":"

I was able to successfully export the tf estimator model. Upon exporting, i got the following files as output. I am using colab, here is the link<\/a><\/p>\n\n

Exported files and folders image<\/a><\/p>\n\n

And I wanted to copy all the files and folders to my flask project where I could load the model and get predictions<\/p>\n\n

The problem is that the variables.data-00001-of-00002<\/code> file is 400mb<\/code> in size and I can not upload it Github.<\/p>\n\n

How can I solve this, or is there any other way of serving the model. Please help<\/p>\n","answers":[]} +{"QuestionId":58791435,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T17:56:21.040","AcceptedAnswerId":null,"OwnerUserId":3277468.0,"Title":"Preprocess Data for Tensorflow 2.0","Body":"

I have a .csv File that has hundreds of thousands of lines. The information was collected in order by the user. <\/p>\n\n

For example, one user's inputs may range 20-400 rows, and the corresponding target is a single row where the users first input row started.<\/p>\n\n

inputs | Targets<\/p>\n\n

0, 7<\/p>\n\n

1<\/p>\n\n

2<\/p>\n\n

3<\/p>\n\n

4<\/p>\n\n

So one set of targets per x amount of input rows.<\/p>\n\n

Some of my columns contain '-' I feel like this will mess up my model when trying to train, considering it isn't a float or int what I should do?<\/p>\n\n

Also, Should I shuffle my data if it is chunked like this?<\/p>\n","answers":[]} +{"QuestionId":58791808,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-10T18:40:26.723","AcceptedAnswerId":58794034.0,"OwnerUserId":12352004.0,"Title":"Hidden state tensors have a different order than the returned tensors","Body":"


\nAs part of GRU training, I want to retrieve the hidden state tensors.\n
<\/p>\n\n

I have defined a GRU with two layers:<\/p>\n\n

self.lstm = nn.GRU(params.vid_embedding_dim, params.hidden_dim , 2)\n<\/code><\/pre>\n\n

The forward function is defined as follows (the following is just a part of the implementation):<\/p>\n\n

    def forward(self, s, order, batch_size, where, anchor_is_phrase = False):\n    \"\"\"\n    Forward prop. \n    \"\"\"\n      # s is of shape [128 , 1 , 300] , 128 is batch size\n      output, (a,b) = self.lstm(s.cuda())\n      output.data.contiguous()\n<\/code><\/pre>\n\n

And out is of shape: [128 , 400] (128 is the number of samples which each one is embedded in 400 dimensional vector).<\/p>\n\n

I understand that out<\/code> is the output of the last hidden state and thus I expect it to be equal to b<\/code>. However, after I checked the values I saw that it's indeed equal but b<\/code> contains the tensor in a different order, that is for example output[0]<\/code> is b[49]<\/code>. Am I missing something here ?<\/p>\n\n

Thanks.<\/p>\n","answers":[{"AnswerId":"58794034","CreationDate":"2019-11-10T23:54:02.503","ParentId":null,"OwnerUserId":"3987085","Title":null,"Body":"

I understand your confusion. Have a look the example bellow and the comments:<\/p>\n\n

# [Batch size, Sequence length, Embedding size]\ninputs = torch.rand(128, 5, 300)\ngru = nn.GRU(input_size=300, hidden_size=400, num_layers=2, batch_first=True)\n\nwith torch.no_grad():\n    # output is all hidden states, for each element in the batch of the last layer in the RNN\n    # a is the last hidden state of the first layer\n    # b is the last hidden state of the second (last) layer\n    output, (a, b) = gru(inputs)\n<\/code><\/pre>\n\n

If we print out the shapes, they will confirm our understanding:<\/p>\n\n

print(output.shape) # torch.Size([128, 5, 400])\nprint(a.shape) # torch.Size([128, 400])\nprint(b.shape) # torch.Size([128, 400])\n<\/code><\/pre>\n\n

Also, we can test whether the last hidden state, for each element in the batch, of the last layer, obtained from output<\/code> is equal to b<\/code>:<\/p>\n\n

np.testing.assert_almost_equal(b.numpy(), output[:,:-1,:].numpy())\n<\/code><\/pre>\n\n

Finally, we can create an RNN with 3 layers, and run the same tests:<\/p>\n\n

gru = nn.GRU(input_size=300, hidden_size=400, num_layers=3, batch_first=True)\nwith torch.no_grad():\n    output, (a, b, c) = gru(inputs)\n\nnp.testing.assert_almost_equal(c.numpy(), output[:,-1,:].numpy())\n<\/code><\/pre>\n\n

Again, the assertion passes but only if we do it for c<\/code>, which is now the last layer of the RNN. Otherwise:<\/p>\n\n

np.testing.assert_almost_equal(b.numpy(), output[:,-1,:].numpy())\n<\/code><\/pre>\n\n

Raises an error:<\/p>\n\n

\n

AssertionError: Arrays are not almost equal to 7 decimals<\/p>\n<\/blockquote>\n\n

I hope that this makes things clear for you.<\/p>\n"}]} +{"QuestionId":58792361,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T19:52:21.673","AcceptedAnswerId":null,"OwnerUserId":8243797.0,"Title":"Loading ensemble keras model gives ValueError: Invalid input_shape argument (None, 224, 224, 3): model has 0 tensor inputs","Body":"

My model is an ensemble of 2 different keras models, the models are connected to same input layer and have 2 output layers when combined.\nBoth models are pretrained and I am trying to create a parallel architecture.\nMy architecture is :\n`<\/p>\n\n

model_input = Input(shape=(224,224,3), name=\"model_input\")\ngender_model_copy.layers.pop(0)\ncolor_model_copy.layers.pop(0)\ncolor_model_ens1 = color_model_copy(model_input)\ngender_model_ens1 = gender_model_copy(model_input)\nmodel_f = Model(input=[model_input], output=[color_model_ens1,gender_model_ens1])\nmodel_f.save('path')\n<\/code><\/pre>\n\n

`<\/p>\n\n

The model gets compiled and I can make predictions as well but when I save it and try to reload it I get, I get:<\/p>\n\n

ValueError: Invalid input_shape argument (None, 224, 224, 3): model has 0 tensor inputs.<\/code>\nFull trace : Github gist link<\/a>.<\/p>\n\n

I have a custom layer which I am adding by using custom_objects={'Scale':Scale()}<\/code>\n argument in keras.models.load_model<\/code>\nMy keras version is 2.2.5 and tensorflow version is 1.15<\/p>\n","answers":[]} +{"QuestionId":58792739,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-10T20:42:15.810","AcceptedAnswerId":null,"OwnerUserId":1179925.0,"Title":"Tensorflow: model wrapper that can release GPU resources","Body":"

Here is a wrapper for tensorflow .pb frozen model (imagenet classification):<\/p>\n\n

import tensorflow as tf\nimport numpy as np\nimport cv2\nfrom numba import cuda\n\n\nclass ModelWrapper():\n    def __init__(self, model_filepath):\n        self.graph_def = self.load_graph_def(model_filepath)\n        self.graph = self.load_graph(self.graph_def)\n        self.set_inputs_and_outputs()\n        self.sess = tf.Session(graph=self.graph)\n\n        print(self.__class__.__name__, 'call __init__')  #\n\n    def load_graph_def(self, model_filepath):\n        # Expects frozen graph in .pb format\n        with tf.gfile.GFile(model_filepath, \"rb\") as f:\n            graph_def = tf.GraphDef()\n            graph_def.ParseFromString(f.read())\n        return graph_def\n\n    def load_graph(self, graph_def):\n        with tf.Graph().as_default() as graph:\n            tf.import_graph_def(graph_def, name=\"\")\n        return graph\n\n    def set_inputs_and_outputs(self):\n        input_list = []\n        for op in self.graph.get_operations():  # tensorflow.python.framework.ops.Operation\n            if op.type == \"Placeholder\":\n                input_list.append(op.name)\n        print('Inputs:', input_list)\n\n        all_name_list = []\n        input_name_list = []\n        for node in self.graph_def.node:  # tensorflow.core.framework.node_def_pb2.NodeDef\n            all_name_list.append(node.name)\n            input_name_list.extend(node.input)\n        output_list = list(set(all_name_list) - set(input_name_list))\n        print('Outputs:', output_list)\n\n        self.inputs = []\n        self.input_tensor_names = [name + \":0\" for name in input_list]\n        for input_tensor_name in self.input_tensor_names:\n            self.inputs.append(self.graph.get_tensor_by_name(input_tensor_name))\n\n        self.outputs = []\n        self.output_tensor_names = [name + \":0\" for name in output_list]\n        for output_tensor_name in self.output_tensor_names:\n            self.outputs.append(self.graph.get_tensor_by_name(output_tensor_name))\n\n        input_dim_list = []\n        for op in self.graph.get_operations(): # tensorflow.python.framework.ops.Operation\n            if op.type == \"Placeholder\":\n                bs = op.get_attr('shape').dim[0].size\n                h = op.get_attr('shape').dim[1].size\n                w = op.get_attr('shape').dim[2].size\n                c = op.get_attr('shape').dim[3].size\n                input_dim_list.append([bs, h, w ,c])\n        assert len(input_dim_list) == 1\n        _, self.input_img_h, self.input_img_w, _ = input_dim_list[0]\n\n    def predict(self, img):\n        h, w, c = img.shape\n        if h != self.input_img_h or w != self.input_img_w:\n            img = cv2.resize(img, (self.input_img_w, self.input_img_h))\n\n        batch = img[np.newaxis, ...]\n        feed_dict = {self.inputs[0]: batch}\n        outputs = self.sess.run(self.outputs, feed_dict=feed_dict) # (1, 1001)\n        output = outputs[0]\n        return output\n\n    def __del__(self):\n        print(self.__class__.__name__, 'call __del__') #\n        import time #\n        time.sleep(3) #\n        cuda.close()\n<\/code><\/pre>\n\n

What I'm trying to do is to clean up GPU memory after I don't need model anymore, in this example I just create and delete model in the loop, but in real life it can be several different models.<\/p>\n\n

wget https:\/\/storage.googleapis.com\/download.tensorflow.org\/models\/inception_v3_2016_08_28_frozen.pb.tar.gz\ntar -xvzf inception_v3_2016_08_28_frozen.pb.tar.gz\nrm -f imagenet_slim_labels.txt\nrm -f inception_v3_2016_08_28_frozen.pb.tar.gz\n\nimport os\nimport time\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom model_wrapper import ModelWrapper\n\nMODEL_FILEPATH = '.\/inception_v3_2016_08_28_frozen.pb'\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\n\ndef create_and_delete_in_loop():\n    for i in range(10):\n        print('-'*60)\n        print('i:', i)\n        model = ModelWrapper(MODEL_FILEPATH)\n        input_batch = np.zeros((model.input_img_h, model.input_img_w, 3), np.uint8)\n        y_pred = model.predict(input_batch)\n        print('y_pred.shape', y_pred.shape)\n        print('np.argmax(y_pred)', np.argmax(y_pred))\n        del model\n\n\nif __name__ == \"__main__\":\n    create_and_delete_in_loop()\n\n    print('START WAITING')\n    time.sleep(10)\n    print('END OF THE PROGRAM!')\n<\/code><\/pre>\n\n

Output:<\/p>\n\n

------------------------------------------------------------\ni: 0\nInputs: ['input']\nOutputs: ['InceptionV3\/Predictions\/Reshape_1']\nModelWrapper call __init__\ny_pred.shape (1, 1001)\nnp.argmax(y_pred) 112\nModelWrapper call __del__\n------------------------------------------------------------\ni: 1\nInputs: ['input']\nOutputs: ['InceptionV3\/Predictions\/Reshape_1']\nModelWrapper call __init__\nSegmentation fault (core dumped)\n<\/code><\/pre>\n\n

What is the proper way of releasing GPU memory?<\/p>\n","answers":[{"AnswerId":"58944126","CreationDate":"2019-11-19T22:57:12.930","ParentId":null,"OwnerUserId":"3125070","Title":null,"Body":"

TL;DR<\/strong> Run your function as a new process+<\/sup> .<\/p>\n\n

tf.reset_default_graph()<\/code> is not guaranteed to release memory#<\/sup>. When a process dies, all the memory it was given (including your GPU Memory) will be released. Not only does this help keep things neatly organized, but also, you can analyze how much CPU, GPU, RAM, GPU Memory each process consumes. <\/p>\n\n

For example, if you had these functions,<\/p>\n\n

def train_model(x, y, params):\n  model = ModelWrapper(params.filepath)\n  model.fit(x, y, epochs=params.epochs)\n\n\ndef predict_model(x, params):\n  model = ModelWrapper(params.filepath)\n  y_pred = model.predict(x)\n  print(y_pred.shape)\n<\/code><\/pre>\n\n

You can use it like,<\/p>\n\n

import multiprocessing\n\nfor i in range(8):\n  print(f\"Training Model {i} from {params.filepath}\")\n  process_train = multiprocessing.Process(train_model, args=(x_train, y_train, params))\n  process_train.start()\n  process_train.join()\n\nprint(\"Predicting\")\nprocess_predict = multiprocessing.Process(predict_model, args=(x_train, params))\nprocess_predict.start()\nprocess_predict.join()\n<\/code><\/pre>\n\n

This way python fires a new process for your tasks, which can run with their own memory. <\/p>\n\n

Bonus Tip<\/strong>: You can also choose to run them in parallel if you have many CPUs and GPUs available: you just need to call process_train.join()<\/code> after the loop in that case. If you had eight GPUs, you can use this parent script to serve parameters, while each of the individual processes shall run on a different GPU. <\/p>\n\n


\n\n

#<\/sup> I tried a variety of things, separately and together<\/em>, before I started using processes,<\/p>\n\n

tf.reset_default_graph()\nK.clear_session()\ncuda.select_device(0); cuda.close()\nmodel = get_new_model() # overwrite\nmodel = None\ndel model\ngc.collect()\n<\/code><\/pre>\n\n

+<\/sup> I also considered using threads, subprocess.Popen, but I was satisfied with multiprocessing since it offered full decoupling that made it a lot easier to manage and allocate resources.<\/p>\n"}]} +{"QuestionId":58792860,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-10T20:57:36.360","AcceptedAnswerId":null,"OwnerUserId":12352427.0,"Title":"When I open Jupyter Notebook there is a Kernel Error appears","Body":"

I've been trying to work on a Python project about object detection with TensorFlow. Everything was okay until I run my Jupyter Notebook in my environment \"tensorflow1\". When Jupyter Notebook opens there is a red Kernel Error<\/code> appearing at the top righthand side of my window. When I click it gives a message like<\/p>\n\n

\n

Traceback (most recent call last):<\/p>\n \n

File\n \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\tornado\\web.py\",\n line 1699, in _execute\n result = await result File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\tornado\\gen.py\",\n line 742, in run\n yielded = self.gen.throw(*exc_info) # type: ignore File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\notebook\\services\\sessions\\handlers.py\",\n line 72, in post\n type=mtype)) File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\tornado\\gen.py\",\n line 735, in run\n value = future.result() File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\tornado\\gen.py\",\n line 742, in run\n yielded = self.gen.throw(*exc_info) # type: ignore File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\notebook\\services\\sessions\\sessionmanager.py\",\n line 88, in create_session\n kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name) File\n \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\tornado\\gen.py\",\n line 735, in run\n value = future.result() File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\tornado\\gen.py\",\n line 742, in run\n yielded = self.gen.throw(*exc_info) # type: ignore File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\notebook\\services\\sessions\\sessionmanager.py\",\n line 101, in start_kernel_for_session\n self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name) File\n \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\tornado\\gen.py\",\n line 735, in run\n value = future.result() File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\tornado\\gen.py\",\n line 209, in wrapper\n yielded = next(result) File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\notebook\\services\\kernels\\kernelmanager.py\",\n line 168, in start_kernel\n super(MappingKernelManager, self).start_kernel(**kwargs) File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\jupyter_client\\multikernelmanager.py\",\n line 110, in start_kernel\n km.start_kernel(**kwargs) File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\jupyter_client\\manager.py\",\n line 240, in start_kernel\n self.write_connection_file() File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\jupyter_client\\connect.py\",\n line 476, in write_connection_file\n kernel_name=self.kernel_name File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\jupyter_client\\connect.py\",\n line 141, in write_connection_file\n with secure_write(fname) as f: File \"D:\\Anaconda\\envs\\tensorflow1\\lib\\contextlib.py\", line 81, in\n enter<\/strong>\n return next(self.gen) File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\jupyter_core\\paths.py\",\n line 424, in secure_write\n win32_restrict_file_to_user(fname) File \"C:\\Users\\Yasin\\AppData\\Roaming\\Python\\Python36\\site-packages\\jupyter_core\\paths.py\",\n line 359, in win32_restrict_file_to_user\n import win32api<\/p>\n \n

ImportError: DLL load failed: The specified procedure could not be\n found.<\/p>\n<\/blockquote>\n\n

I tried to change the Kernel but I had only one Kernel called \"Python3\". I tried to remove it and created a new Kernel called \"Python tensorflow1\". I tried to run the codes with that Kernel and it still gives me that red error. <\/p>\n\n

It also says Failed to start the Kernel.<\/p>\n","answers":[{"AnswerId":"58801537","CreationDate":"2019-11-11T12:39:17.447","ParentId":null,"OwnerUserId":"10389198","Title":null,"Body":"

Please activate the environment tensorflow1 and install ipykernel in that environment uing below commands:<\/p>\n\n

conda activate tensorflow1\nconda install ipykernel\nipython kernel install --name tensorflow1 --user\n<\/code><\/pre>\n\n

Then try to use access jupyter notebook using the below command:<\/p>\n\n

jupyter notebook\n<\/code><\/pre>\n\n

If the above steps doesn't work please follow the below steps to create a new conda environment and access jupyter notebook from that environment:<\/p>\n\n

conda create -n env_tf -c intel python=3.6\n<\/code><\/pre>\n\n

Once the conda environment is created successfully, you can list the environment using the below command:<\/p>\n\n

conda env list\n<\/code><\/pre>\n\n

It should be listing :<\/p>\n\n

D:\\Anaconda\\envs\\env_tf<\/p>\n\n

Activate the environment using the below command:<\/p>\n\n

conda activate env_tf\n<\/code><\/pre>\n\n

Install ipykernel in the activated environment:<\/p>\n\n

conda install ipykernel\n\nipython kernel install --name env_tf --user \n<\/code><\/pre>\n\n

Access jupyter notebook using below command:<\/p>\n\n

jupyter notebook\n<\/code><\/pre>\n\n

Hope this helps.<\/p>\n"}]} +{"QuestionId":58792887,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-10T21:00:42.093","AcceptedAnswerId":58793236.0,"OwnerUserId":12352403.0,"Title":"codelab tutorial tensorflow errorxxx","Body":"

once I run the following code on windows 10 tensor flow version 1.7.1<\/strong><\/p>\n\n

python -m scripts.retrain \\\n  --bottleneck_dir=tf_files\/bottlenecks \\\n  --how_many_training_steps=500 \\\n  --model_dir=tf_files\/models\/ \\\n  --summaries_dir=tf_files\/training_summaries\/\"${ARCHITECTURE}\" \\\n  --output_graph=tf_files\/retrained_graph.pb \\\n  --output_labels=tf_files\/retrained_labels.txt \\\n  --architecture=\"${ARCHITECTURE}\" \\\n  --image_dir=tf_files\/flower_photos\n<\/code><\/pre>\n\n

I get the following error<\/strong><\/p>\n\n

line 1326, in <module>\n    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\nAttributeError: module 'tensorflow' has no attribute 'app'\n<\/code><\/pre>\n\n

Can somebody help me please:(<\/p>\n","answers":[{"AnswerId":"58793236","CreationDate":"2019-11-10T21:49:14.230","ParentId":null,"OwnerUserId":"3633891","Title":null,"Body":"

See here: tensorflow retrain.py app.run() got unexpected keyword argument 'argv'<\/a><\/p>\n\n

I think you need to update the version of your tensorflow.<\/p>\n"}]} +{"QuestionId":58792907,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T21:03:28.013","AcceptedAnswerId":null,"OwnerUserId":12352463.0,"Title":"No GPU Usage apparent in Google Cloud Vm with pytorch already installed and Cuda10","Body":"

I have been using in my machine a network, that is nothing really special. I wanted to do it faster so I started using google cloud. But I notice something weird that my machine with a GTX 1050 ti was faster than a V100 GPU. This didn't add up so I checked the usage and it seems that even though I put some stress by creating a big network and passing a lot of data to it the gpu by using a simple .cuda() in both the model and the data: there wasn't ussage shown in nvidia-smi command as shown in the image\nyou can check my code here:<\/p>\n\n

device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n    print(\"The device is:\",device,torch.cuda.get_device_name(0),\"and how many are they\",torch.cuda.device_count())\n\n    # # We load the training data \n    Samples , Ocupancy, num_samples, Samples_per_slice = common.load_samples(args.samples_filename)\n    Samples = Samples * args.scaling_todo\n\n    print(Samples_per_slice)\n    # Divide into Slices\n    Organize_Positions,Orginezed_Ocupancy, batch_size = common.organize_sample_data(Samples,Ocupancy,num_samples,Samples_per_slice,args.num_batches)\n\n    phi = common.MLP(3, 1).cuda()\n\n    x_test = torch.from_numpy(Organize_Positions.astype(np.float32)).cuda()\n    y_test = torch.from_numpy(Orginezed_Ocupancy.astype(np.float32)).cuda()\n\n    all_data = common.CustomDataset(x_test, y_test)\n\n\n    #Dive into Slices the data\n    Slice_data = DataLoader(dataset=all_data, batch_size = batch_size, shuffle=False) # only take batch_size = n\/b TODO Don't shuffle\n\n    #Chunky_data = DataLoader(dataset=Slice_data, batch_size =  chunch_size, shuffle=False)\n\n\n    criterion = torch.nn.BCEWithLogitsLoss()\n    optimizer = torch.optim.Adam(phi.parameters(), lr = 0.0001)\n    epoch = args.num_epochs\n\n    fit_start_time = time.time()\n\n    phi.train()\n    for epoch in range(epoch):\n        curr_epoch_loss = 0\n        batch = 0\n        for x_batch, y_batch in Slice_data:\n            optimizer.zero_grad()\n            x_train = x_batch\n            #print(x_train,batch_size)\n            y_train = y_batch\n\n            y_pred = phi(x_train)\n            #print(y_pred,x_train)\n\n            loss = criterion(y_pred.squeeze(), y_train.squeeze())\n\n            curr_epoch_loss += loss\n\n            print('Batch {}: train loss: {}'.format(batch, loss.item()))    # Backward pass\n\n            loss.backward()\n            optimizer.step() # Optimizes only phi parameters\n            batch+=1\n\n\n        print('Epoch {}: train loss: {}'.format(epoch, loss.item()))\n\n\n    fit_end_time = time.time()\n    print(\"Total time = %f\" % (fit_end_time - fit_start_time))\n\n    # Save Model\n    torch.save({'state_dict': phi.state_dict()}, args.model_filename)\n<\/code><\/pre>\n\n

and the model here:<\/p>\n\n

class MLP(nn.Module):\n    def __init__(self, in_dim: int, out_dim: int):\n        super().__init__()\n        self.in_dim = in_dim\n        self.out_dim = out_dim\n        self.fc1 = nn.Linear(in_dim, 128)\n        self.fc1_bn = nn.BatchNorm1d(128)\n        self.fc2 = nn.Linear(128, 256)\n        self.fc2_bn = nn.BatchNorm1d(256)\n        self.fc3 = nn.Linear(256, 512)\n        self.fc3_bn = nn.BatchNorm1d(512)\n        self.fc4 = nn.Linear(512, 512)\n        self.fc4_bn = nn.BatchNorm1d(512)\n        self.fc5 = nn.Linear(512, out_dim,bias=False)\n\n        self.relu = nn.LeakyReLU()\n\n\n    def forward(self, x):\n        x = self.relu(self.fc1_bn(self.fc1(x)))\n        x = self.relu(self.fc2_bn(self.fc2(x)))# leaky\n        x = self.relu(self.fc3_bn(self.fc3(x)))\n        x = self.relu(self.fc4_bn(self.fc4(x)))\n        x = self.fc5(x)\n        return x\n\nclass CustomDataset(Dataset):\n    def __init__(self, x_tensor, y_tensor):\n        self.x = x_tensor\n        self.y = y_tensor\n\n    def __getitem__(self, index):\n        return (self.x[index], self.y[index])\n\n    def __len__(self):\n        return len(self.x)\n\n<\/code><\/pre>\n","answers":[]}
+{"QuestionId":58793106,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T21:30:47.090","AcceptedAnswerId":null,"OwnerUserId":11065415.0,"Title":"Question about Training in Tensorflow 2.0 with @tf.function","Body":"

I'm looking at implementing a simple model in Tensorflow 2.0, while implementing the new @tf.function decorator function as well as the removal of tf.Session().<\/p>\n\n

As of right now I create my weights and biases with separate name scopes with feedforward():<\/p>\n\n

def feedforward(self, input, output, name_scope):\n\n    with tf.variable_scope(name_scope, reuse=tf.AUTO_REUSE) as scope:\n\n        self.W = tf.get_variable('weights',\n                                 shape=(input.shape[1], output),\n                                 initializer=tf.random_normal_initializer(0,0.01),\n                                 dtype=tf.float32)\n\n        self.b = tf.get_variable('biases',\n                                 shape=(output),\n                                 initializer=tf.constant_initializer(0,0.01),\n                                 dtype=tf.float32)\n\n        z = tf.matmul(self.W, input) + self.biases\n        activations = sigmoid(z)\n\n    return activations\n<\/code><\/pre>\n\n

I compile my layers using a define_layer function:<\/p>\n\n

@tf.function\ndef define_layers():\n    self.layer_1 = self.feedforward(self.features, self.l1_dim, 'layer_1')\n    self.layer_2 = self.feedforward(self.layer_1, self.l2_dim, 'layer_2')\n    self.final_layer = self.feedforward(self.layer_2, 1, 'final_layer')\n<\/code><\/pre>\n\n

And finally, I create my loss and optimizer with preamble():<\/p>\n\n

def preamble():\n    self.loss = \/\/\n    self.labels * -math.log(self.final_layer) + (1 - self.labels) \/\/\n        * -math.log(1 - self.final_layer)\n\n    self.optimizer = \/\/\n    tf.train.AdamOptimizer(learning_rate=0.01).minimize(self.loss)\n\n    return self.loss\n<\/code><\/pre>\n\n

So to my question: How do I go about implementing training with train() without using tf.Session()? For a simple example, I currently have:<\/p>\n\n

@tf.function\ndef train():\n    for epoch in range(100):\n        for (x, y) in (self.features, self.labels):\n            loss = preamble()\n\n        if epoch % 50 == 0:\n            print(\"Current Epoch is {:03d} with loss of {:.3f}\".format(epoch, self.loss))\n<\/code><\/pre>\n\n

For this application I do not want to use any tf.metrics or keras, as I want to develop it all using the low-level API. <\/p>\n\n

And an additional question, am I using the @tf.function() decorator properly? I am using it as per the Tensorflow Guide<\/a> to define my layers, but I'm not sure in what instances it is appropriate or not.<\/p>\n","answers":[]} +{"QuestionId":58793110,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-10T21:31:01.237","AcceptedAnswerId":58793702.0,"OwnerUserId":12127824.0,"Title":"Vectorizing multiplication of matrices with different shapes in numpy\/tensorflow","Body":"

I have a 4x4 input matrix and I want to multiply every 2x2 slice with a weight stored in a 3x3 weight matrix. Please see the attached image for an example:<\/p>\n\n

\"enter<\/a><\/p>\n\n

In the image, the colored section of the 4x4 input matrix is multiplied by the same colored section of the 3x3 weight matrix and stored in the 4x4 output matrix. When the slices overlap, the output takes the sum of the overlaps (e.g. the blue+red).<\/p>\n\n

I am trying to perform this operation in Tensorflow 2.0 using eager tensors (which can be treated as numpy arrays). This is what I've written to perform this operation and it produces the expected output.<\/p>\n\n

inputm = np.ones([4,4]) # initialize 4x4 input matrix\nweightm = np.ones([3,3]) # initialize 3x3 weight matrix\noutputm = np.zeros([4,4]) # initialize blank 4x4 output matrix\n\n# iterate through each weight\nfor i in range(weightm.shape[0]):\n    for j in range(weightm.shape[1]):\n        outputm[i:i+2, j:j+2] += weightm[i,j] * inputm[i:i+2, j:j+2]\n<\/code><\/pre>\n\n

However, I don't think this is efficient since I am iterating through the weight matrix one-by-one, and this will be extremely slow when I need to perform this on large matrices of 500x500. I am having a hard time identifying a way to vectorize this operation, maybe tiling the weight matrix to be the same shape as the input matrix and performing a single matrix multiplication. I have also thought about flattening the matrix but I'm still not able to see a way to do this more efficiently.<\/p>\n\n

Any advice will be much appreciated. Thanks in advance!<\/p>\n","answers":[{"AnswerId":"58793702","CreationDate":"2019-11-10T22:58:49.780","ParentId":null,"OwnerUserId":"1699075","Title":null,"Body":"

Alright, I think I have a solution but this involves using both numpy operations (e.g. np.repeat<\/code>) and TensorFlow 2.0 operations (i.e. tf.segment_sum<\/code>). And to warn you this is not the most clear elegant solution in the world, but it was the most elegant I could come up with. So here goes.<\/p>\n\n

The main culprit in your problem is this weight matrix. If you manipulate this weight matrix to be a 4x4 matrix (with correct sum of weight at each position) you have a nice weight matrix which you can do an element-wise multiplication with the input. And that's my solution. Note that this is designed for the 4x4 problem and you should be able to relatively easily extend this to the 500x500 matrix.<\/p>\n\n

import numpy as np\nimport tensorflow as tf\n\na = np.array([[1,2,3,4],[4,3,2,1],[1,2,3,4],[4,3,2,1]])\nw = np.array([[5,4,3],[3,4,5],[5,4,3]])\n\n# We make weights to a 6x6 matrix by repeating 2 times on both axis\nw_rep = np.repeat(w,2,axis=0)\nw_rep = np.repeat(w_rep,2,axis=1)\n\n# Let's now jump in to tensorflow\ntf_a = tf.constant(a)\ntf_w = tf.constant(w_rep)\ntf_segments = tf.constant([0,1,1,2,2,3])\n\n# This is the most tricky bit, here we use the segment_sum to achieve what we need\n# You can use segment_sum to get the sum of segments on the very first dimension of a matrix.\n# So you need to do that to the input matrix twice. One on the original and the other on the transpose.\n\ntf_w2 = tf.math.segment_sum(tf_w, tf_segments)\ntf_w2 = tf.transpose(tf_w2)\ntf_w2 = tf.math.segment_sum(tf_w2, tf_segments)\ntf_w2 = tf.transpose(tf_w2)\n\nprint(tf_w2*a)\n<\/code><\/pre>\n\n

PS: I will try to include an illustration of what's going on here in a future edit. But I reckon that will take some time.<\/p>\n"}]} +{"QuestionId":58793210,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T21:45:03.823","AcceptedAnswerId":null,"OwnerUserId":8087073.0,"Title":"Custom loss function works for regular NN but not for LSTM","Body":"

So I am building a custom loss function based on tfp.stats.covariance()<\/code>. It works perfectly when dealing with regular NN as below:<\/p>\n\n

import numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport tensorflow.keras.backend as K\n\nx = np.random.rand(100,1,180)\ny = np.random.rand(100,15,12)\n\ndef sharpe_loss(y_true, y_pred):  \n\n    cov = tf.cast(tfp.stats.covariance(y_true, sample_axis=1, event_axis=-1), tf.float32)\n\n    return K.mean(y_pred)\n\nmodel = tf.keras.models.Sequential([\n  tf.keras.layers.Dense(12, activation=tf.nn.sigmoid)\n])\n\nmodel.compile(optimizer= 'Adam',\n              loss=sharpe_loss)\n\nfit_ = model.fit(x, y, epochs=5, batch_size = 28) \n<\/code><\/pre>\n\n

But when building LSTM as below<\/p>\n\n

import numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport tensorflow.keras.backend as K\n\nx = np.random.rand(100,1,180)\ny = np.random.rand(100,15,12)\n\ndef sharpe_loss(y_true, y_pred):  \n\n    cov = tf.cast(tfp.stats.covariance(y_true, sample_axis=1, event_axis=-1), tf.float32)\n\n    return K.mean(y_pred)\n\nmodel = tf.keras.models.Sequential([\n  tf.keras.layers.LSTM(1),\n  tf.keras.layers.Dense(12, activation=tf.nn.sigmoid)\n])\n\nmodel.compile(optimizer= 'Adam',\n              loss=sharpe_loss)\n\nfit_ = model.fit(x, y, epochs=5, batch_size = 28) \n<\/code><\/pre>\n\n

I get ValueError: sample_axis ([1]) and event_axis ([1]) overlapped<\/code>. Which is weird as the shape that goes into the loss function for y_pred is [batch_size,15,12] and when running <\/p>\n\n

y_true = tf.constant(np.random.rand(28,15,12), tf.float32)\ntf.cast(tfp.stats.covariance(y_true, sample_axis=1, event_axis=-1), tf.float32)\n<\/code><\/pre>\n\n

No error occurs. Have I misunderstood something with the LSTM model, or what is wrong here?<\/p>\n\n

Note that my y_true data does not have anything to do with the shape of the output layer and this is far from the full loss function. <\/p>\n","answers":[]} +{"QuestionId":58793386,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T22:07:22.233","AcceptedAnswerId":null,"OwnerUserId":7697591.0,"Title":"How do i know my --output_arrays in tflite_convert","Body":"

I'm trying to convert my .pb to .tflite using tflite_convert <\/p>\n\n

How do i know my --output_arrays ? <\/p>\n\n

I'm using the ssd_mobilenet_v2_coco_2018_03_29<\/p>\n\n

this is my current code:<\/p>\n\n

tflite_convert --output_file=C:\/tensorflow1\/models\/research\/object_detection\/inference_graph\/detect.tflite --graph_def_file=C:\/tensorflow1\/models\/research\/object_detection\/inference_graph\/tflite_graph.pb --inference_type=FLOAT --inference_input_type=QUANTIZED_UINT8 --input_arrays=ImageTensor --input_shapes=1,513,513,3 --output_arrays=SemanticPredictions --mean_values=128 --std_dev_values=128 --allow_custom_ops\n\n<\/code><\/pre>\n\n

and it produce error:<\/p>\n\n

\n

Specified output array \"SemanticPredictions\" is not produced by any op in this graph. <\/p>\n<\/blockquote>\n\n

Following from\nhttps:\/\/www.tensorflow.org\/lite\/convert\/cmdline_examples#command-line_tools_<\/a><\/p>\n","answers":[]} +{"QuestionId":58793429,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-10T22:12:58.307","AcceptedAnswerId":null,"OwnerUserId":10018602.0,"Title":"Time Series Forecasting in Tensorflow 2.0 - How to predict using the last of the Validation Dataset?","Body":"

I'm (desperately) trying to figure out Tensorflow 2.0 without much luck so far, but I think I'm close with what I need right now.<\/p>\n\n

I've followed the doc here<\/a> to make a simple network to forecast stock data (not weather data), and what I'd like to do now is, forecast the future using the latest\/most recent section of the validation dataset. I'm hoping someone else has read through it already and can help me here.<\/p>\n\n

The code to predict the future using the validation dataset looks like this:<\/p>\n\n

for x, y in val_data_multi.take(3):\n  multi_step_plot(x[0], y[0], multi_step_model.predict(x)[0])\n<\/code><\/pre>\n\n

...where to the best of my knowledge, it takes a random chunk (3 separate times), and in my case is a 20 row x 9 column section, from the val_data_multi<\/code> \"Repeat dataset\" type, and then uses the model's multi_step_plot<\/code> function to spit out a plot that has the predicted values based on that random section of the validation dataset. But what if I don't want to just take a random validation section, I want to use the bottom of my actual dataset? So that if I have recent stock data at the bottom of my validation dataset, and I want to forecast for the future that hasn't happened yet, how can I take a 20x9 section from the bottom of that set, and not just have it \"take\" a random section to predict with?<\/p>\n\n

As a pseudo code attempt to explain what I'm trying to do, I was trying something like:<\/p>\n\n

for x, y in val_data_multi[-20:].take(1): #.take(3)\n<\/code><\/pre>\n\n

...to try and make it take one section 20 rows up from the bottom, and all columns. But of course this didn't work as TypeError: 'RepeatDataset' object is not subscriptable<\/code>.<\/p>\n\n

I hope that makes sense, and if it'll help for me to post my code, I can do that, but I'm just using what's already shown in that page, just made some modifications to use a stock dataset, that's all.<\/p>\n","answers":[{"AnswerId":"58805652","CreationDate":"2019-11-11T16:59:50.830","ParentId":null,"OwnerUserId":"10018602","Title":null,"Body":"

I was able to find a much better guide from this Github repo:<\/p>\n\n

https:\/\/github.com\/Hvass-Labs\/TensorFlow-Tutorials\/blob\/master\/23_Time-Series-Prediction.ipynb<\/a><\/p>\n\n

...which basically gets into better detail what I'm looking to do and made it very easy to understand. Thanks!<\/p>\n"}]} +{"QuestionId":58793565,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T22:38:13.843","AcceptedAnswerId":null,"OwnerUserId":3830871.0,"Title":"Use 2D Convolution like \"1D Convolution\" on images?","Body":"

I have 256\u00d7192 pixel images and search a small and fast cnn as a \"pre scanner\" to find interesting parts on a image (like 52x52, 32x32 chunks etc), which will be checked with a more complex cnn. The reason for this small cnn is the use within an embedded system with limited resources.<\/p>\n\n

Unfortunately I'm new at this topic, tensorflow and keras. My first idea was to create an net with only one 2D conv which works like an 1d conv. In this case the kernel should have a height of 192 and a width of 1 (maybe later 3).<\/p>\n\n

This is the model which I build on tensorflow 2:<\/p>\n\n

# Model\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(5, (1, 192), activation='relu', input_shape=(256, 192, 3)))\n\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n<\/code><\/pre>\n\n

The idea is to get one value per row which indicates if something \"interesting\" can be in this row. Based of this information and the neighbors a bigger part of the image will be cut out and feed into the more complex cnn.<\/p>\n\n

I have prepared normal images with 256x192px and for each image a text file with 256 values (0.0 or 1.0). Each 0\/1 represents one row and indicates if something interesting is in this row or not.<\/p>\n\n

This was my naive plan but the training crashes immediately with an error that I dont understand:<\/p>\n\n

ValueError: Dimensions must be equal, but are 32 and 256 for 'metrics\/accuracy\/Equal' (op: 'Equal') with input shapes: [32,256], [32,256,1].<\/code> <\/p>\n\n

I think I basic idea\/strategy is wrong. I dont unterstand where the 32 comes from. Can someone explain my mistake? And is my idea even feasible?<\/p>\n\n

Edit:<\/em><\/strong><\/p>\n\n

As requested the complete, dirty code. If there are some major flaws, please be forgiving. This is my first Python experiment.<\/p>\n\n

import tensorflow as tf\nimport os\nfrom tensorflow.keras import datasets, layers, models\nfrom PIL import Image\nfrom numpy import asarray\n\ntrain_images = []\ntrain_labels = []\ntest_images = []\ntest_labels = []\n\n# Prepare\ndir = os.listdir('images\/gt_image')\nsplit = len(dir)*0.2\n\nc = 0\n\nfor file in dir:\n    c = c + 1\n\n    im = Image.open('images\/gt_image\/' + file)\n\n    data = im.load()\n    image = []\n\n    for x in range(0, im.size[0]):\n        row = []\n        for y in range(0, im.size[1]):\n            row.append([x\/255 for x in data[x, y]])\n        image.append(row)\n    if c <= split:\n        test_images.append(image)\n    else:\n        train_images.append(image)\n\n    file = open('images\/gt_labels\/' + file + '.txt', 'r')\n    label = file.readlines()[0].split(', ')\n\n    if c <= split:\n        test_labels.append(label)\n    else:\n        train_labels.append(label)\nprint('prepare done')\n\n# Model\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(5, (1, 192), activation='relu', input_shape=(256, 192, 3)))\n\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\nmodel.summary()\n\nprint('compile done')\n\n# Learning\nhistory = model.fit(train_images, train_labels, epochs=10,\n                    validation_data=(test_images, test_labels))\n<\/code><\/pre>\n","answers":[]}
+{"QuestionId":58793577,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T22:40:50.813","AcceptedAnswerId":null,"OwnerUserId":11027569.0,"Title":"Pytorch Convolutional Autoencoder output is blurry. How to improve it?","Body":"

I created Convolutional Autoencoder using Pytorch and I'm trying to improve it. <\/p>\n\n

For the encoding layer I use first 4 layers of pre-trained ResNet 18 model<\/code> from torchvision.models.resnet<\/code>.<\/p>\n\n

I have mid-layer with just one Convolutional layer<\/code> with input and output channel sizes of 512. For the decoding layer I use Convolutional layers<\/code> following with BatchNorm<\/code> and ReLU<\/code> activation function.<\/p>\n\n

The decoding layer reduces the channel each layer: 512 -> 256 -> 128 -> 64 -> 32 -> 16 -> 3<\/code> and increases the resolution of the image with interpolation to match the dimension of the corresponding layer in the encoding part. For the last layer I use sigmoid<\/code> instead of ReLu<\/code>.<\/p>\n\n

All Convolutional layer<\/code>s are:<\/p>\n\n

self.up = nn.Sequential(\n                nn.Conv2d(input_channels, output_channels, \n                    kernel_size=5, stride=1,\n                    padding=2, bias=False),\n                nn.BatchNorm2d(output_channels),\n                nn.ReLU()\n            )\n<\/code><\/pre>\n\n

The input images are scaled to [0, 1]<\/code> range and have shapes 224x224x3<\/code>. Sample outputs are (First is from training set, the second from the test set):<\/p>\n\n

First image<\/a><\/p>\n\n

First image output<\/a><\/p>\n\n

Second image<\/a><\/p>\n\n

Second image output<\/a><\/p>\n\n

Any ideas why output is blurry? The provided model has been trained around 160 epochs<\/code> with ~16000<\/code> images using Adam<\/code> optimizer with lr=0.00005<\/code>. I'm thinking about adding one more Convolutional<\/code> layer in self.up<\/code> given above. This will increase complexity of the model, but I'm not sure if it is the right way to improve the model.<\/p>\n","answers":[]} +{"QuestionId":58793607,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-10T22:44:23.840","AcceptedAnswerId":58801230.0,"OwnerUserId":1423203.0,"Title":"AttributeError: module 'tensorflow' has no attribute 'placeholder' with keras 2.2.4 tensorflow 1.14","Body":"

I am getting this error AttributeError: module 'tensorflow' has no attribute 'placeholder'<\/code> when I'm using Keras 2.2.4(since it supports TensorFlow 1.x) \nTried TensorFlow 1.14 and also 2.0.0, but always same error<\/p>\n\n

Can someone help me resolve this <\/p>\n\n

This is complete log<\/p>\n\n

AttributeError                            Traceback (most recent call last)\n\n<ipython-input-65-dc4f74e64a0b> in <module>\n      7 \n      8 \n----> 9 inputExperiment = Input(shape=(1,),dtype='int8', name='inputExperiment')\n     10 x1 = Embedding(output_dim=4,input_dim=50,input_length=1)(inputExperiment)\n     11 x1 = Flatten()(x1)\n\n~\\Anaconda3\\envs\\Workspace\\lib\\site-packages\\keras\\engine\\input_layer.py in Input(shape, batch_shape, name, dtype, sparse, tensor)\n\n~\\Anaconda3\\envs\\Workspace\\lib\\site-packages\\keras\\legacy\\interfaces.py in wrapper(*args, **kwargs)\n\n~\\Anaconda3\\envs\\Workspace\\lib\\site-packages\\keras\\engine\\input_layer.py in __init__(self, input_shape, batch_size, batch_input_shape, dtype, input_tensor, sparse, name)\n\n~\\Anaconda3\\envs\\Workspace\\lib\\site-packages\\keras\\backend\\tensorflow_backend.py in placeholder(shape, ndim, dtype, sparse, name)\n\nAttributeError: module 'tensorflow' has no attribute 'placeholder'\n<\/code><\/pre>\n","answers":[{"AnswerId":"58801230","CreationDate":"2019-11-11T12:20:37.993","ParentId":null,"OwnerUserId":"2097240","Title":null,"Body":"

A placeholder is the initial tensor-like object you use to create a symbolic graph model. (Which is the standard Keras model and old Tensorflow model). <\/p>\n\n

If it can't be found, either your installation is bad or your tensorflow version is 2.0.0 (and thus uses eager mode by default - eager mode doesn't support placeholders). <\/p>\n\n

To use Tensorflow 2.0.0, it's probably better to use tensorflow.keras<\/code> instead of keras<\/code>. (But it may be an idea to test Keras 2.3 as proposed by Matias Valdenegro) <\/p>\n\n

To fix your installation, the safest way is to create a new environment.<\/p>\n\n

You should search the internet on how to create a new \"environment\" in Anaconda and in this environment you install the versions you need. This is the only safe way to install\/uninstall things without breaking your previous installations. After you created this environment and installed only the versions you need, then you run your code from this environment. Unfortunately these installation issues are not easy things to tackle. <\/p>\n"}]} +{"QuestionId":58793742,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-10T23:04:58.990","AcceptedAnswerId":null,"OwnerUserId":12230317.0,"Title":"LSTM input_shape in keras","Body":"

I am implementing a LSTM network in keras Spyder according to a Udemy tutorial. In the tutorial video the code is running but when I run it on my own, which step by step is precisely implemented the same as the tutorial video code, it gets an error which is:<\/p>\n\n

\n

Error when checking target: expected dense_26 to have 3 dimensions, but got array with shape (1198, 1)<\/p>\n<\/blockquote>\n\n

Does it relate to the version of Spyder? The size of x_train<\/code> is (1198,60,1)<\/code> and y_train<\/code> size is (1198,)<\/code> <\/p>\n\n

import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n#Importing the training set\ndataset_train = pd.read_csv('E:\\\\downloads_1\\\\Recurrent_Neural_Networks\\\\Google_Stock_Price_Train.csv')\ntraining_set = dataset_train.iloc[:,1:2].values\n#Feature Scaling \nfrom sklearn.preprocessing import MinMaxScaler\nsc = MinMaxScaler(feature_range=(0,1))\ntraining_set_scaled = sc.fit_transform(training_set)\n#Creating a Data Structure with 60 timesteps and 1 output\nx_train = []\ny_train = []\nfor i in range(60,1258):\n    x_train.append(training_set_scaled[i-60:i , 0])\n    y_train.append(training_set_scaled[i , 0])\nx_train , y_train = np.array(x_train) , np.array(y_train)\n\n#Reshaping\nx_train = np.reshape(x_train , (x_train.shape[0],x_train.shape[1], 1))\n\n\n\n#Part 2_Building the Rnn\n\n#importing te keras Libraries and Packages\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import LSTM\n\n\n#initializing the RNN\nregressor = Sequential()\n\n#Adding the first layer LSTM and some Dropout Regularisations\nregressor.add(LSTM(units = 50, return_sequences= True, input_shape = (x_train.shape[1], 1)))\nregressor.add(Dropout(0.2))\n\n#Adding the second layer LSTM and some Dropout Regularisations\nregressor.add(LSTM(units = 50, return_sequences= True))\nregressor.add(Dropout(0.2))\n\n#Adding the third layer LSTM and some Dropout Regularisations\nregressor.add(LSTM(units = 50, return_sequences= True))\nregressor.add(Dropout(0.2))\n\n#Adding the fourth layer LSTM and some Dropout Regularisations\nregressor.add(LSTM(units = 50, return_sequences= True))\nregressor.add(Dropout(0.2))\n\n#Adding the output layer\nregressor.add(Dense(units = 1))\n\n#compiling the RNN\nregressor.compile(optimizer= 'adam',  loss = 'mean_squared_error')\n\n#Fitting the RNN TO the training set`enter code here`\nregressor.fit(x_train, y_train, epochs = '100', batch_size = 32 )\n<\/code><\/pre>\n","answers":[{"AnswerId":"58794391","CreationDate":"2019-11-11T01:03:42.433","ParentId":null,"OwnerUserId":"1699075","Title":null,"Body":"

Your LSTM is returning a sequence (i.e. return_sequences=True<\/code>). Therefore, your last LSTM layer returns a (batch_size, timesteps, 50)<\/code> sized 3-D tensor. Then the dense layer returns a 3-D predictions (i.e. (batch_size, time steps, 1)<\/code>) array. <\/p>\n\n

But it appears you are feeding in a 2-D input as the outputs (i.e. 1192x1<\/code>). So this needs to be a (1192, 60, 1)<\/code> array for your model to use the labels.<\/p>\n\n

This really depends on your problem. The other alternative is, if you really have only 1 output value per data point, you need to use return_sequences=False<\/code> on the last LSTM.<\/p>\n\n

#initializing the RNN\nregressor = Sequential()\n\n#Adding the first layer LSTM and some Dropout Regularisations\nregressor.add(LSTM(units = 50, return_sequences= True, input_shape = (x_train.shape[1], 1)))\nregressor.add(Dropout(0.2))\n\n#Adding the second layer LSTM and some Dropout Regularisations\nregressor.add(LSTM(units = 50, return_sequences= True))\nregressor.add(Dropout(0.2))\n\n#Adding the third layer LSTM and some Dropout Regularisations\nregressor.add(LSTM(units = 50, return_sequences= True))\nregressor.add(Dropout(0.2))\n\n#Adding the fourth layer LSTM and some Dropout Regularisations\nregressor.add(LSTM(units = 50, return_sequences= False))\nregressor.add(Dropout(0.2))\n<\/code><\/pre>\n\n

PS: Also something you should be aware is that your Dense<\/code> layer is actually 3-D. This is fine if you were going for this. But the typical way of using a Dense<\/code> layer in a time-series model is to use a TimeDistributed<\/code> layer like follows.<\/p>\n\n

regressor.add(TimeDistirbuted(Dense(units = 1)))<\/code><\/p>\n"}]} +{"QuestionId":58794019,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-10T23:50:32.177","AcceptedAnswerId":null,"OwnerUserId":8388965.0,"Title":"Face alignment in pytorch","Body":"

I am trying to do face alignment on 300W dataset. I am using ResNet50 and L1 loss for training. My code looks like this. <\/p>\n\n

batch_size = 10\nimage_size = 128\n\nnet = torchvision.models.resnet50(pretrained=True)\nnum_ftrs = net.fc.in_features\nnet.fc = nn.Linear(num_ftrs, 136) # 136 because 68 points with 2 dim. so 136= 68*2\n\ndef train():\n    device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \n           \"cpu\")\n\n    optimiser = optim.Adam(net.parameters(), lr=0.001, \n            weight_decay=0.0005)\n\n    criterion = L1Loss(reduction='sum')\n\n    for epoch in range(int(0), 200000):\n        for batch, data in enumerate(trainloader, 0):\n            inputs, labels = data\n            inputs, labels = inputs.to(device), labels.to(device)\n\n            optimiser.zero_grad()\n\n            outputs = net(inputs).reshape(-1, 68, 2)\n\n            loss = criterion(outputs, labels)\n            loss.backward()\n            optimiser.step()\n            running_loss += loss.item()\n\n\n            sys.stdout.write(\n            '\\rTrain Epoch: {} Batch {} avg_Loss_per_batch: {:.2f} \n            '.format(epoch, batch, running_loss\/(batch+1)))\n            sys.stdout.flush()\n<\/code><\/pre>\n\n

The trainloader is with images and points. The ground-truths are shaped as (batch, 68, 2). We have 68 points on the face on 2 dimensional space. <\/p>\n\n

The papers suggests that the ResNet50 should get an error of 10 (metric: pixel) for a 256*256 image with L1 loss. I am getting error around 500-800 on validation set even after 5000 epoch. <\/p>\n\n

I am training images with 256*256 resolution with ground truth of 68 points such as ((x1,y1),(x2,y2)....(x68,y68)) and I have trained over 5000 epoch with many learning rates. My validation code looks like this,<\/p>\n\n

def validater(load_weights=False):\n    device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \n          \"cpu\")\n    net.eval()\n    net.to(device)\n\n    with torch.no_grad():\n        for batch, data in enumerate(testloader, 0):\n            inputs, labels = data\n            inputs, labels  = inputs.to(device), labels.to(device)\n\n            outputs = net(inputs).reshape(-1, 68, 2)\n\n            loss = criterion(outputs, labels)\n\n            loss2 = np.linalg.norm(labels.to('cpu') - outputs.to('cpu'))\n\n            sys.stdout.write('\\rTest Epoch: {} Batch {} total_L1_Loss: \n                {:.2f} avg_L1_Loss_per_img: {:.2f} total_norm_loss: \n                 {:.2f}'.format(\n                0, batch, avg_loss, avg_loss\/batch\/batch_size, \n                avg_loss2))\n            sys.stdout.flush()\n\n    print()\n<\/code><\/pre>\n\n

What is wrong with my code ? <\/p>\n\n

PS: I normalise the imgs with the following code<\/p>\n\n

    img = cv2.normalize(img, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n<\/code><\/pre>\n\n

After 4000 epoch I get outputs like this where yellow dots are ground truth and blue ones are predicted \"Yellow<\/a> <\/p>\n","answers":[]} +{"QuestionId":58794122,"AnswerCount":2,"Tags":"","CreationDate":"2019-11-11T00:10:36.960","AcceptedAnswerId":58801835.0,"OwnerUserId":7164581.0,"Title":"Keras CNN Classifier","Body":"

I do have a question regarding the CNN in Keras if you would like to help me I would really appreciate this.<\/p>\n\n

Disclaimer: I'm a noob in CNN and Keras, I'm just learning them right now.<\/p>\n\n


\n\n

My Data:<\/strong><\/p>\n\n

2 Classes (dogs and cats)<\/p>\n\n

Traing: 30 pics each category<\/p>\n\n

Test: 14 pics each category<\/p>\n\n

Valid: 30 pics each category<\/p>\n\n


\n\n

My code:<\/strong><\/p>\n\n

data_path = Path(\"..\/data\")\n\ntrain_path = data_path \/ \"train\"\ntest_path = data_path \/ \"test\"\nvalid_path = data_path \/ \"valid\"\n\ntrain_batch = ImageDataGenerator().flow_from_directory(directory=train_path,\n                                                       target_size=(200, 200),\n                                                       classes=animals,\n                                                       batch_size=10)\n\nvalid_batch = ImageDataGenerator().flow_from_directory(directory=valid_path,\n                                                       target_size=(200, 200),\n                                                       classes=animals,\n                                                       batch_size=10)\n\ntest_path = ImageDataGenerator().flow_from_directory(directory=test_path,\n                                                     target_size=(200, 200),\n                                                     classes=animals,\n                                                     batch_size=4)\n\nimgs, labels = next(train_batch)\n\nmodel = Sequential(\n    [Conv2D(32, (3, 3), activation=\"relu\", input_shape=(200, 200, 3)), Flatten(),\n     Dense(len(animals), activation='softmax')])\n\nmodel.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel.fit_generator(train_path, steps_per_epoch=4, validation_data=valid_batch, validation_steps=3, epochs=5, verbose=2)\n<\/code><\/pre>\n\n
\n\n

Here it's my error message:<\/strong><\/p>\n\n

I've replaced the paths with \"\"<\/p>\n\n

Traceback (most recent call last):\n  File \"\", line 191, in <module>\n    model.fit_generator(train_path, steps_per_epoch=4, validation_data=valid_batch, validation_steps=3, epochs=5, verbose=2)\n  File \"y\", line 91, in wrapper\n    return func(*args, **kwargs)\n  File \"\", line 1732, in fit_generator\n    initial_epoch=initial_epoch)\n  File \"\", line 185, in fit_generator\n    generator_output = next(output_generator)\n  File \"\", line 742, in get\n    six.reraise(*sys.exc_info())\n  File \"\", line 693, in reraise\n    raise value\n  File \"\", line 711, in get\n    inputs = future.get(timeout=30)\n  File \"\", line 657, in get\n    raise self._value\n  File \"\", line 121, in worker\n    result = (True, func(*args, **kwds))\n  File \"\", line 650, in next_sample\n    return six.next(_SHARED_SEQUENCES[uid])\nTypeError: 'PosixPath' object is not an iterator\n<\/code><\/pre>\n\n
\n\n

Could anyone explain to me what I'm doing wrong please? Also if this is an off-topic question just let me know where I can ask it.<\/p>\n","answers":[{"AnswerId":"58794786","CreationDate":"2019-11-11T02:17:07.300","ParentId":null,"OwnerUserId":"6031995","Title":null,"Body":"

This line isn't necessary<\/p>\n\n

imgs, labels = next(train_batch)<\/code><\/p>\n\n

from the docs <\/a> fit_generator first argument is a generator object no a string as you have supplied. Like this<\/p>\n\n

model.fit_generator(train_path, steps_per_epoch=4, validation_data=valid_batch, validation_steps=3, epochs=5, verbose=2)<\/code><\/p>\n"},{"AnswerId":"58801835","CreationDate":"2019-11-11T12:57:21.617","ParentId":null,"OwnerUserId":"11897007","Title":null,"Body":"

The issue you are having is that you are NOT passing the generator for the training, but the path for the files (you are using train_path<\/code><\/strong> instead of train_batch<\/code><\/strong>. <\/p>\n\n

Whereas you need to pass a generator for object when using .fit_generator()<\/code>:<\/p>\n\n

model.fit_generator(train_batch, steps_per_epoch=4, validation_data=valid_batch, validation_steps=3, epochs=5, verbose=2)\n<\/code><\/pre>\n"}]}
+{"QuestionId":58794263,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-11T00:38:40.343","AcceptedAnswerId":null,"OwnerUserId":3799454.0,"Title":"Custom back-propogation","Body":"

I am experimenting with Tensorflow, and have the following problem<\/p>\n\n

I want to use the iteration <\/p>\n\n

w_{t} := w_{t} - ag_{t-1}<\/code><\/p>\n\n

where t<\/code> is the time, a<\/code> is the learning rate, and g(0)<\/code> is pre-specified. Since the gradient is not a trainable weight, I am not able to simply initialize it. Any suggestions are appreciated. <\/p>\n\n

Thank you <\/p>\n","answers":[{"AnswerId":"58794470","CreationDate":"2019-11-11T01:17:43.667","ParentId":null,"OwnerUserId":"12105487","Title":null,"Body":"

I'm not sure whether I fully understand your question. Why not initialize your gradient (I call it G here) to a zero tensor of the same shape as w_t? Then if you want to implement SGD, you can accumulate the gradient of each sample from a random batch on G and finally update your w_t.<\/p>\n"}]} +{"QuestionId":58794626,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-11T01:50:52.170","AcceptedAnswerId":null,"OwnerUserId":2467772.0,"Title":"AttributeError: Attribut...parse'\",)","Body":"

AttributeError: Attribut...parse'\",) occurred during splitting text in tensor.\nThe error occurred in the following code.<\/p>\n\n

def read_data(batch_size, input_shape, file_src):\n  reader = tf.TextLineReader()\n  _, value = reader.read(file_src)\n  filename, label, boxes = tf.decode_csv(value, [[''], [''], ['']], ' ')\n  boxes=tf.strings.split(boxes,',')\n  height, width, channels_num = input_shape\n  rgb_image = tf.image.decode_jpeg(image_file, channels=channels_num)\n  rgb_image_float = tf.image.convert_image_dtype(rgb_image, tf.float32)\n  resized_images = tf.image.resize_images(rgb_image_float, [height, width])\n  resized_images.set_shape(input_shape)\n\n  min_after_dequeue = 30000\n  capacity = min_after_dequeue + 3 * batch_size\n  image_batch, label_batch, boxes_batch = tf.train.shuffle_batch([resized_images, label, boxes], batch_size=batch_size, capacity=capacity,\n                                                    min_after_dequeue=min_after_dequeue)\n\n  return image_batch, label_batch, boxes_batch \n<\/code><\/pre>\n\n

That is preparing all variable before sess run.\nBefore sess runs, there is no text inside boxes<\/code>.<\/p>\n\n

filename, label, boxes<\/code> are all variables read from a text file.\nboxes will read all text lines with ,<\/code> and supposed to split.<\/p>\n\n

But before the sess run, there is no text line inside and have error as <\/p>\n\n

boxes=tf.strings.split(boxes,',')\n(Pdb) p boxes\n<tf.Tensor 'DecodeCSV:2' shape=() dtype=string>\n(Pdb) n\nAttributeError: Attribut...parse'\",)\n<\/code><\/pre>\n","answers":[]}
+{"QuestionId":58794638,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-11T01:52:07.077","AcceptedAnswerId":null,"OwnerUserId":7020404.0,"Title":"How to detect only single custom object using Tensor Flow Object Detection API?","Body":"

I need to detect a red rectangle object only (I made a red rectangle using a tape on a desk). I have 30 pictures of it as the dataset. I follow the tutorial custom object detection using Tensor Flow Object Detection API on this page<\/a>. I use the ssd_inception_v2 model as shown in that page.<\/p>\n\n

I have tested the result and it can detect the red rectangle. But, the problem is when there are hands and the red rectangle, both of them will be detected as an object (see my picture below).<\/p>\n\n

\"Object<\/a><\/p>\n\n

I still do not understand why the model can detect a hand? It also can detect a person and a computer. Does this happen because I use the pre-trained model? How to make it to only detect my custom object (red rectangle)?<\/p>\n","answers":[]} +{"QuestionId":58794894,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-11T02:35:55.363","AcceptedAnswerId":null,"OwnerUserId":2467772.0,"Title":"TypeError: TypeErro...pected',)","Body":"

TypeError: TypeErro...pected',) in converting string type tensor to float32 and initialize to constant tensor.\nValue reading from a file is received as string type so need to convert to float32.<\/p>\n\n

How can I make it work?<\/p>\n\n

filename, label, box1, box2, box3, box4, box5, box6, box7, box8 = tf.decode_csv(value, [[''], [''], [''],[''],[''],[''],[''],[''],[''],['']], ' ')\nboxes = tf.constant([tf.dtypes.cast(box1, tf.float32),tf.dtypes.cast(box2, tf.float32),tf.dtypes.cast(box3, tf.float32),tf.dtypes.cast(box4, tf.float32),tf.dtypes.cast(box5, tf.float32),tf.dtypes.cast(box6, tf.float32),tf.dtypes.cast(box7, tf.float32),tf.dtypes.cast(box8, tf.float32)]) \n<\/code><\/pre>\n\n

Error is <\/p>\n\n

TypeError: TypeErro...pected',)\n<\/code><\/pre>\n","answers":[{"AnswerId":"58796416","CreationDate":"2019-11-11T06:19:59.077","ParentId":null,"OwnerUserId":"2467772","Title":null,"Body":"

Used tf.stack and solved.<\/p>\n\n

boxes = tf.transpose(tf.stack([tf.strings.to_number(box1,tf.dtypes.float32),tf.strings.to_number(box2,tf.dtypes.float32),tf.strings.to_number(box3,tf.dtypes.float32),tf.strings.to_number(box4,tf.dtypes.float32),tf.strings.to_number(box5,tf.dtypes.float32),tf.strings.to_number(box6,tf.dtypes.float32),tf.strings.to_number(box7,tf.dtypes.float32),tf.strings.to_number(box8,tf.dtypes.float32)]))\n<\/code><\/pre>\n"}]}
+{"QuestionId":58794981,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-11T02:52:15.123","AcceptedAnswerId":58807908.0,"OwnerUserId":5535024.0,"Title":"Is it possible to create multiple instances of the same CNN that take in multiple images and are concatenated into a dense layer? (keras)","Body":"

\"enter<\/a><\/p>\n\n

Is this possible with Keras or is it even possible to train a network from the ground-up with this architecture? <\/p>\n\n

I'm essentially looking to train a model that takes in a larger but fixed number of images per sample (i.e. 3+ image inputs with similar visual features), but not to explode the number of parameters by training several CNNs at once. The idea is to train only one CNN, that can be used for all the outputs. Having all images go into the same dense layers is important so the model can learn the associations across multiple images, which are always ordered based on their source.<\/p>\n","answers":[{"AnswerId":"58807908","CreationDate":"2019-11-11T19:58:26.910","ParentId":null,"OwnerUserId":"1699075","Title":null,"Body":"

You can easily achieve this using the Keras functional API the following way.<\/p>\n\n

from tensorflow.python.keras import layers, models, applications\n\n# Multiple inputs\nin1 = layers.Input(shape=(128,128,3))\nin2 = layers.Input(shape=(128,128,3))\nin3 = layers.Input(shape=(128,128,3))\n\n# CNN output\ncnn = applications.xception.Xception(include_top=False)\n\n\nout1 = cnn(in1)\nout2 = cnn(in2)\nout3 = cnn(in3)\n\n# Flattening the output for the dense layer\nfout1 = layers.Flatten()(out1)\nfout2 = layers.Flatten()(out2)\nfout3 = layers.Flatten()(out3)\n\n# Getting the dense output\ndense = layers.Dense(100, activation='softmax')\n\ndout1 = dense(fout1)\ndout2 = dense(fout2)\ndout3 = dense(fout3)\n\n# Concatenating the final output\nout = layers.Concatenate(axis=-1)([dout1, dout2, dout3])\n\n# Creating the model\nmodel = models.Model(inputs=[in1,in2,in3], outputs=out)\nmodel.summary()```\n<\/code><\/pre>\n"}]}
+{"QuestionId":58795032,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-11T02:59:52.113","AcceptedAnswerId":58797534.0,"OwnerUserId":1009508.0,"Title":"Custom loss is missing an operation for gradient","Body":"

I'm not too sure how to deal with this and why I am getting this error. <\/p>\n\n

    raise ValueError('An operation has `None` for gradient. '\n    ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.\n<\/code><\/pre>\n\n

So I am using a custom tripleloss for the loss function from this blog. https:\/\/omoindrot.github.io\/triplet-loss<\/a> and I am running it in keras which should not be an issue. But I cannot get it to work correctly with my model. <\/p>\n\n

So this is the loss function from them. The other code that it needs is a direct copy:<\/p>\n\n

def batch_hard_triplet_loss(embeddings, labels, margin = 0.3, squared=False):\n\n    # Get the pairwise distance matrix\n    pairwise_dist = pairwise_distances(embeddings, squared=squared)\n    mask_anchor_positive = _get_anchor_positive_triplet_mask(labels)\n    mask_anchor_positive = tf.to_float(mask_anchor_positive)\n    anchor_positive_dist = tf.multiply(mask_anchor_positive, pairwise_dist)\n    hardest_positive_dist = tf.reduce_max(anchor_positive_dist, axis=1, keepdims=True)\n    mask_anchor_negative = _get_anchor_negative_triplet_mask(labels)\n    mask_anchor_negative = tf.to_float(mask_anchor_negative)\n    max_anchor_negative_dist = tf.reduce_max(pairwise_dist, axis=1, keepdims=True)\n    anchor_negative_dist = pairwise_dist + max_anchor_negative_dist * (1.0 - mask_anchor_negative)\n    hardest_negative_dist = tf.reduce_min(anchor_negative_dist, axis=1, keepdims=True)\n    # Combine biggest d(a, p) and smallest d(a, n) into final triplet loss\n    triplet_loss = tf.maximum(hardest_positive_dist - hardest_negative_dist + margin, 0.0)\n    triplet_loss = tf.reduce_mean(triplet_loss)\n#triplet_loss = k.mean(triplet_loss) # use keras mean\n\n    return triplet_loss\n<\/code><\/pre>\n\n

Now this is my model that I am using. <\/p>\n\n

train_datagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\n    ....\n    validation_split=0.2) # set validation split\n\ntrain_generator = train_datagen.flow_from_directory(\n    IMAGE_DIR,\n    target_size=(224, 224),\n    batch_size=BATCHSIZE,\n    class_mode='categorical',\n    subset='training') # set as training data\n\nvalidation_generator = train_datagen.flow_from_directory(\n    IMAGE_DIR, # same directory as training data\n    target_size=(224, 224),\n    batch_size=BATCHSIZE,\n    class_mode='categorical',\n    subset='validation') # set as validation data\n\nprint(\"Initializing Model...\")\n# Get base model\ninput_layer = preloadmodel.get_layer('model_1').get_layer('input_1').input\nlayer_output = preloadmodel.get_layer('model_1').get_layer('glb_avg_pool').output\n# Make extractor\nbase_network = Model(inputs=input_layer, outputs=layer_output)\n\n# Define new model\ninput_images = Input(shape=(224, 224, 3), name='input_image')  # input layer for images\n#input_labels = Input(shape=(num_classes,), name='input_label')  # input layer for labels\nembeddings = base_network(input_images)  # output of network -> embeddings\noutput = Dense(1, activation='sigmoid')(embeddings)\nmodel = Model(inputs=input_images,  outputs=output)\n# Compile model\nmodel.compile(loss=batch_hard_triplet_loss, optimizer='adam')\n<\/code><\/pre>\n","answers":[{"AnswerId":"58797534","CreationDate":"2019-11-11T08:02:13.333","ParentId":null,"OwnerUserId":"1009508","Title":null,"Body":"

Ok I solved these issues with a lot of research. Now it didn't fix my problem as the code still does not work, but the issue of the loss function is fixed. Following this blog https:\/\/medium.com\/@Bloomore\/how-to-write-a-custom-loss-function-with-additional-arguments-in-keras-5f193929f7a0<\/a><\/p>\n\n

I changes the loss function to this: <\/p>\n\n

def batch_hard_triplet_loss(embeddings, labels, margin = 0.3, squared=False):\n    # Get the pairwise distance matrix\n    pairwise_dist = pairwise_distances(embeddings, squared=squared)\n    mask_anchor_positive = _get_anchor_positive_triplet_mask(labels)\n    mask_anchor_positive = tf.to_float(mask_anchor_positive)\n    anchor_positive_dist = tf.multiply(mask_anchor_positive, pairwise_dist)\n    hardest_positive_dist = tf.reduce_max(anchor_positive_dist, axis=1, keepdims=True)\n    mask_anchor_negative = _get_anchor_negative_triplet_mask(labels)\n    mask_anchor_negative = tf.to_float(mask_anchor_negative)\n    max_anchor_negative_dist = tf.reduce_max(pairwise_dist, axis=1, keepdims=True)\n    anchor_negative_dist = pairwise_dist + max_anchor_negative_dist * (1.0 - mask_anchor_negative)\n    hardest_negative_dist = tf.reduce_min(anchor_negative_dist, axis=1, keepdims=True)\n    def loss(y_true, y_pred):\n\n        # Combine biggest d(a, p) and smallest d(a, n) into final triplet loss\n        #triplet_loss = tf.maximum(hardest_positive_dist - hardest_negative_dist + margin, 0.0)\n        #triplet_loss = tf.reduce_mean(triplet_loss)\n        triplet_loss = k.maximum(hardest_positive_dist - hardest_negative_dist + margin, 0.0)\n        triplet_loss = k.mean(triplet_loss) # use keras mean\n        return triplet_loss\n\n    return loss\n<\/code><\/pre>\n\n

And then call it in the model like this:<\/p>\n\n

batch_loss = batch_hard_triplet_loss(embeddings, input_labels, 0.4, False)\nmodel = Model(inputs=input_images,  outputs=embeddings)\nmodel.compile(loss=batch_loss, optimizer='adam')\n<\/code><\/pre>\n\n

It now gives me these issues <\/p>\n\n

tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_label' with dtype float and shape [?,99]\n [[{{node input_label}}]]\n<\/code><\/pre>\n\n

But hey were moving on up.\nWhat the problem is keras only accepts loss with 2 parameters so you need to call the loss form another function like I did here. <\/p>\n"}]} +{"QuestionId":58795035,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-11T03:00:30.580","AcceptedAnswerId":null,"OwnerUserId":3259896.0,"Title":"Best way to handle negative sampling in Tensorflow 2.0 with Keras","Body":"

Tensorflow released an official guide to implementing word2vec in TF 2.0 Keras<\/p>\n\n

https:\/\/www.tensorflow.org\/tutorials\/text\/word_embeddings<\/a><\/p>\n\n

However, it's missing negative sampling, which is very important in word2vec, which is unfortunate, because the original tensorflow has some great candidate sampling functions. <\/p>\n\n

My best guess on what to do is augment the model,<\/p>\n\n

model = keras.Sequential([\n  layers.Embedding(encoder.vocab_size, embedding_dim),\n  layers.GlobalAveragePooling1D(),\n  layers.Dense(1, activation='sigmoid')\n])\n<\/code><\/pre>\n\n

Perhaps use the functional API instead of the sequential API. <\/p>\n\n

I see that the c++ TF 2.0 has candidate sampling ops https:\/\/www.tensorflow.org\/api_docs\/cc\/group\/candidate-sampling-ops<\/a><\/p>\n\n

Can these be incorporated into Keras? <\/p>\n","answers":[]} +{"QuestionId":58795164,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-11T03:22:53.363","AcceptedAnswerId":null,"OwnerUserId":9259385.0,"Title":"Installing Keras with Docker","Body":"

\r\n
\r\n
ResourceExhaustedErrorTraceback (most recent call last)\r\n<ipython-input-8-cb1025b61acf> in <module>()\r\n----> 1 history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=30,validation_data=validation_generator, validation_steps=50)\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/legacy\/interfaces.pyc in wrapper(*args, **kwargs)\r\n     89                 warnings.warn('Update your `' + object_name +\r\n     90                               '` call to the Keras 2 API: ' + signature, stacklevel=2)\r\n---> 91             return func(*args, **kwargs)\r\n     92         wrapper._original_function = func\r\n     93         return wrapper\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/models.pyc in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)\r\n   1251                                         use_multiprocessing=use_multiprocessing,\r\n   1252                                         shuffle=shuffle,\r\n-> 1253                                         initial_epoch=initial_epoch)\r\n   1254 \r\n   1255     @interfaces.legacy_generator_methods_support\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/legacy\/interfaces.pyc in wrapper(*args, **kwargs)\r\n     89                 warnings.warn('Update your `' + object_name +\r\n     90                               '` call to the Keras 2 API: ' + signature, stacklevel=2)\r\n---> 91             return func(*args, **kwargs)\r\n     92         wrapper._original_function = func\r\n     93         return wrapper\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/engine\/training.pyc in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)\r\n   2242                     outs = self.train_on_batch(x, y,\r\n   2243                                                sample_weight=sample_weight,\r\n-> 2244                                                class_weight=class_weight)\r\n   2245 \r\n   2246                     if not isinstance(outs, list):\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/engine\/training.pyc in train_on_batch(self, x, y, sample_weight, class_weight)\r\n   1888             ins = x + y + sample_weights\r\n   1889         self._make_train_function()\r\n-> 1890         outputs = self.train_function(ins)\r\n   1891         if len(outputs) == 1:\r\n   1892             return outputs[0]\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/backend\/tensorflow_backend.pyc in __call__(self, inputs)\r\n   2473         session = get_session()\r\n   2474         updated = session.run(fetches=fetches, feed_dict=feed_dict,\r\n-> 2475                               **self.session_kwargs)\r\n   2476         return updated[:len(self.outputs)]\r\n   2477 \r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/client\/session.pyc in run(self, fetches, feed_dict, options, run_metadata)\r\n    893     try:\r\n    894       result = self._run(None, fetches, feed_dict, options_ptr,\r\n--> 895                          run_metadata_ptr)\r\n    896       if run_metadata:\r\n    897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/client\/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)\r\n   1126     if final_fetches or final_targets or (handle and feed_dict_tensor):\r\n   1127       results = self._do_run(handle, final_targets, final_fetches,\r\n-> 1128                              feed_dict_tensor, options, run_metadata)\r\n   1129     else:\r\n   1130       results = []\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/client\/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)\r\n   1342     if handle is None:\r\n   1343       return self._do_call(_run_fn, self._session, feeds, fetches, targets,\r\n-> 1344                            options, run_metadata)\r\n   1345     else:\r\n   1346       return self._do_call(_prun_fn, self._session, handle, feeds, fetches)\r\n\r\n\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/client\/session.pyc in _do_call(self, fn, *args)\r\n   1361         except KeyError:\r\n   1362           pass\r\n-> 1363       raise type(e)(node_def, op, message)\r\n   1364 \r\n   1365   def _extend_graph(self):\r\n\r\nResourceExhaustedError: OOM when allocating tensor with shape[6272,512] and type float on \/job:localhost\/replica:0\/task:0\/device:GPU:0 by allocator GPU_0_bfc\r\n  [[Node: training\/RMSprop\/mul_24 = Mul[T=DT_FLOAT, _device=\"\/job:localhost\/replica:0\/task:0\/device:GPU:0\"](RMSprop\/rho\/read, training\/RMSprop\/Variable_8\/read)]]\r\nHint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.\r\n\r\n  [[Node: metrics\/acc\/Mean_1\/_109 = _Recv[client_terminated=false, recv_device=\"\/job:localhost\/replica:0\/task:0\/device:CPU:0\", send_device=\"\/job:localhost\/replica:0\/task:0\/device:GPU:0\", send_device_incarnation=1, tensor_name=\"edge_774_metrics\/acc\/Mean_1\", tensor_type=DT_FLOAT, _device=\"\/job:localhost\/replica:0\/task:0\/device:CPU:0\"]()]]\r\nHint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.\r\n\r\n\r\nCaused by op u'training\/RMSprop\/mul_24', defined at:\r\n  File \"\/usr\/lib\/python2.7\/runpy.py\", line 174, in _run_module_as_main\r\n    \"__main__\", fname, loader, pkg_name)\r\n  File \"\/usr\/lib\/python2.7\/runpy.py\", line 72, in _run_code\r\n    exec code in run_globals\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/ipykernel_launcher.py\", line 16, in <module>\r\n    app.launch_new_instance()\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/traitlets\/config\/application.py\", line 658, in launch_instance\r\n    app.start()\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/ipykernel\/kernelapp.py\", line 486, in start\r\n    self.io_loop.start()\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tornado\/ioloop.py\", line 888, in start\r\n    handler_func(fd_obj, events)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tornado\/stack_context.py\", line 277, in null_wrapper\r\n    return fn(*args, **kwargs)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/zmq\/eventloop\/zmqstream.py\", line 450, in _handle_events\r\n    self._handle_recv()\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/zmq\/eventloop\/zmqstream.py\", line 480, in _handle_recv\r\n    self._run_callback(callback, msg)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/zmq\/eventloop\/zmqstream.py\", line 432, in _run_callback\r\n    callback(*args, **kwargs)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tornado\/stack_context.py\", line 277, in null_wrapper\r\n    return fn(*args, **kwargs)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/ipykernel\/kernelbase.py\", line 283, in dispatcher\r\n    return self.dispatch_shell(stream, msg)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/ipykernel\/kernelbase.py\", line 233, in dispatch_shell\r\n    handler(stream, idents, msg)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/ipykernel\/kernelbase.py\", line 399, in execute_request\r\n    user_expressions, allow_stdin)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/ipykernel\/ipkernel.py\", line 208, in do_execute\r\n    res = shell.run_cell(code, store_history=store_history, silent=silent)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/ipykernel\/zmqshell.py\", line 537, in run_cell\r\n    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/IPython\/core\/interactiveshell.py\", line 2718, in run_cell\r\n    interactivity=interactivity, compiler=compiler, result=result)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/IPython\/core\/interactiveshell.py\", line 2822, in run_ast_nodes\r\n    if self.run_code(code, result):\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/IPython\/core\/interactiveshell.py\", line 2882, in run_code\r\n    exec(code_obj, self.user_global_ns, self.user_ns)\r\n  File \"<ipython-input-8-cb1025b61acf>\", line 1, in <module>\r\n    history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=30,validation_data=validation_generator, validation_steps=50)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/legacy\/interfaces.py\", line 91, in wrapper\r\n    return func(*args, **kwargs)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/models.py\", line 1253, in fit_generator\r\n    initial_epoch=initial_epoch)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/legacy\/interfaces.py\", line 91, in wrapper\r\n    return func(*args, **kwargs)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/engine\/training.py\", line 2088, in fit_generator\r\n    self._make_train_function()\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/engine\/training.py\", line 990, in _make_train_function\r\n    loss=self.total_loss)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/legacy\/interfaces.py\", line 91, in wrapper\r\n    return func(*args, **kwargs)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/keras\/optimizers.py\", line 251, in get_updates\r\n    new_a = self.rho * a + (1. - self.rho) * K.square(g)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/ops\/variables.py\", line 775, in _run_op\r\n    return getattr(ops.Tensor, operator)(a._AsTensor(), *args)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/ops\/math_ops.py\", line 907, in binary_op_wrapper\r\n    return func(x, y, name=name)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/ops\/math_ops.py\", line 1131, in _mul_dispatch\r\n    return gen_math_ops._mul(x, y, name=name)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/ops\/gen_math_ops.py\", line 2798, in _mul\r\n    \"Mul\", x=x, y=y, name=name)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/framework\/op_def_library.py\", line 787, in _apply_op_helper\r\n    op_def=op_def)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/framework\/ops.py\", line 3160, in create_op\r\n    op_def=op_def)\r\n  File \"\/usr\/local\/lib\/python2.7\/dist-packages\/tensorflow\/python\/framework\/ops.py\", line 1625, in __init__\r\n    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access\r\n\r\nResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[6272,512] and type float on \/job:localhost\/replica:0\/task:0\/device:GPU:0 by allocator GPU_0_bfc\r\n  [[Node: training\/RMSprop\/mul_24 = Mul[T=DT_FLOAT, _device=\"\/job:localhost\/replica:0\/task:0\/device:GPU:0\"](RMSprop\/rho\/read, training\/RMSprop\/Variable_8\/read)]]\r\nHint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.\r\n\r\n  [[Node: metrics\/acc\/Mean_1\/_109 = _Recv[client_terminated=false, recv_device=\"\/job:localhost\/replica:0\/task:0\/device:CPU:0\", send_device=\"\/job:localhost\/replica:0\/task:0\/device:GPU:0\", send_device_incarnation=1, tensor_name=\"edge_774_metrics\/acc\/Mean_1\", tensor_type=DT_FLOAT, _device=\"\/job:localhost\/replica:0\/task:0\/device:CPU:0\"]()]]\r\nHint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.<\/code><\/pre>\r\n<\/div>\r\n<\/div>\r\n<\/p>\n\n

I am trying to install Keras using Docker for deeplearning using a GPU. I am on the Keras github (https:\/\/github.com\/keras-team\/keras\/tree\/master\/docker<\/a>) and I cannot figure out how to do it. I am new with Docker and the docker images I have been able to acquire have all been with a 'docker pull' command. But I do not see a Docker pull command to get keras. I am not understanding the 'make' instructions provided.<\/p>\n\n

I have been having a heck of a time trying to get Keras running with my linux computer. I initially tried installing CUDA, TF and all of the files directly onto my computer but was having so many issues with version compatibility with all of the software that I gave up with that and have been trying to simplify it with docker, however this has not been easy either. I have tried several docker images including ermaker\/keras-jupyter and gw000\/keras-full and haven't been able to get them working either.<\/p>\n\n

Using gw000\/keras-full I've tried running simple neural networks with a cat classifier from the Deep learning with Keras book and I'm getting an error that memory has been completely filled up. I don't know why I would be getting that error, It's a simple classifier than I've been able to run on my old laptop and it's blowing up with my RTX 2080TI for some reason.<\/p>\n\n

Any help with trying to get a working version of keras thru docker would be much appreciated.<\/p>\n\n

This is code from using gw000\/keras-full. I use this to launch the docker with GPU:<\/p>\n\n

docker run -d $(ls \/dev\/nvidia* | xargs -I{} echo '--device={}') $(ls \/usr\/lib\/*-linux-gnu\/{libcuda,libnvidia}* | xargs -I{} echo '-v {}:{}:ro') -p 8888:8888 -v \/home\/name\/Desktop:\/srv gw000\/keras-full\n<\/code><\/pre>\n\n
\n\n

When I try to run the training of the model, this happens on the first epoch. I see in the error that it's trying to run python 2 which might be an issue because it was probably written with python 3 but I don't know if that's the issue and how to change it to use python 3 instead. As mentioned before, the code is verbatim from the Deep Learning with Keras book and worked perfect on my old laptop. I cannot for the life of me figure out why i can't get anything running on my PC.<\/p>\n\n

Epoch 1\/30<\/p>\n\n

*SEE THE ATTACHED CODE SNIP FOR THE ERROR I GET*\n<\/code><\/pre>\n","answers":[{"AnswerId":"58797999","CreationDate":"2019-11-11T08:40:07.617","ParentId":null,"OwnerUserId":"2993180","Title":null,"Body":"
\n

But I do not see a Docker pull command to get keras. I am not\n understanding the 'make' instructions provided<\/p>\n<\/blockquote>\n\n

The make instruction runs all the bash commands required for building docker image. The image is build according to configurations mentioned in the Dockerfile<\/code>. Once the image is built, it is stored in your local machine. Therefore, you don't need to pull it.<\/p>\n\n

You can choose the way you want to use Keras. For example, if you want to run Keras in interactive mode, then run make bash<\/code>. This will build the docker image and instantiate a container for that image. You can use Keras through a new command line prompt. However, if you want to use GPU as well (assuming you have installed the NVIDIA drivers successfully), run make bash GPU=0<\/code>. This will run nvidia-docker<\/code> command for you. This resulting container will have gpu support.<\/p>\n\n

\n

I have tried several docker images including ermaker\/keras-jupyter and\n gw000\/keras-full and haven't been able to get them working either<\/p>\n<\/blockquote>\n\n

The images ermaker\/keras-jupyter<\/code> and gw000\/keras-full<\/code> are pre-built docker images. However, the ermaker\/keras-jupyter<\/code> does not come with gpu version of keras. It seems your program is memory intensive. Without gpu support it will show memory error. If you have installed the drivers properly, a good alternative could be using python virtual environment. <\/p>\n\n

However, if you are getting memory error even after running the Keras docker container with gpu support, then try to reduce the batch size for your training. <\/p>\n"}]} +{"QuestionId":58795272,"AnswerCount":0,"Tags":"","CreationDate":"2019-11-11T03:39:32.633","AcceptedAnswerId":null,"OwnerUserId":12353326.0,"Title":"How can I read a CSV file in TensorFlow when multiple rows represent one data element?","Body":"

I'm trying to learn some chemical structures. The data set is CSV file in which 132 rows represent 132 possible atoms of one molecule, and there are 5000+ molecules in total. I know how to read single row data, but how can I read this data and combine the 132 rows as one element?<\/p>\n","answers":[]} +{"QuestionId":58795601,"AnswerCount":1,"Tags":"","CreationDate":"2019-11-11T04:34:48.720","AcceptedAnswerId":58801221.0,"OwnerUserId":6651938.0,"Title":"Pytorch: Understand how nn.Module class internally work","Body":"

Generally, a nn.Module<\/code> can be inherited by a subclass as below. <\/p>\n\n

def init_weights(m):\n    if type(m) == nn.Linear:\n        torch.nn.init.xavier_uniform(m.weight)  # \n\nclass LinearRegression(nn.Module):\n    def __init__(self):\n        super(LinearRegression, self).__init__()\n        self.fc1 = nn.Linear(20, 1)\n        self.apply(init_weights)\n\n    def forward(self, x):\n        x = self.fc1(x)\n        return x\n<\/code><\/pre>\n\n

My 1st question is, why I can simply run the code below even my __init__<\/code> doesn't have any positinoal arguments for training_signals<\/code> and it looks like that training_signals<\/code> is passed to forward()<\/code> method. How does it work?<\/p>\n\n

model = LinearRegression()\ntraining_signals = torch.rand(1000,20)\nmodel(training_signals)\n<\/code><\/pre>\n\n

The second question is that how does self.apply(init_weights)<\/code> internally work? Is it executed before calling forward<\/code> method?<\/p>\n","answers":[{"AnswerId":"58801221","CreationDate":"2019-11-11T12:19:52.433","ParentId":null,"OwnerUserId":"4228275","Title":null,"Body":"

\n

Q1: Why I can simply run the code below even my __init__<\/code> doesn't have any positional arguments for training_signals<\/code> and it looks like that training_signals<\/code> is passed to forward()<\/code> method. How does it work?<\/p>\n<\/blockquote>\n\n

First, the __init__<\/code> is called when you run this line:<\/p>\n\n

model = LinearRegression()\n<\/code><\/pre>\n\n

As you can see, you pass no parameters, and you shouldn't. The signature of your __init__<\/code> is the same as the one of the base class (which you call when you run super(LinearRegression, self).__init__()<\/code>). As you can see here<\/a>, nn.Module<\/code>'s init signature is simply def __init__(self)<\/code> (just like yours).<\/p>\n\n

Second, model<\/code> is now an object. When you run the line below:<\/p>\n\n

model(training_signals)\n<\/code><\/pre>\n\n

You are actually calling the __call__<\/code> method and passing training_signals<\/code> as a positional parameter. As you can see here<\/a>, among many other things, the __call__<\/code> method calls the forward<\/code> method:<\/p>\n\n

result = self.forward(*input, **kwargs)\n<\/code><\/pre>\n\n

passing all parameters (positional and named) of the __call__<\/code> to the forward<\/code>.<\/p>\n\n

\n

Q2: How does self.apply(init_weights)<\/code> internally work? Is it executed before calling forward method?<\/p>\n<\/blockquote>\n\n

PyTorch is Open Source, so you can simply go to the source-code and check it. As you can see here<\/a>, the implementation is quite simple:<\/p>\n\n

def apply(self, fn):\n    for module in self.children():\n        module.apply(fn)\n    fn(self)\n    return self\n<\/code><\/pre>\n\n

Quoting the documentation of the function: it \"applies fn<\/code> recursively to every submodule (as returned by .children()<\/code>) as well as self<\/code><\/em>\". Based on the implementation, you can also understand the requirements:<\/p>\n\n

Similar to this question<\/a>, I'm looking to have several image input layers that go through one larger CNN (e.g. XCeption minus dense layers), and then have the output of the one CNN across all images be concatenated into a dense layer.<\/p>\n\n