diff --git "a/stackoverflow_DL-related_questions_data/data19.json" "b/stackoverflow_DL-related_questions_data/data19.json" new file mode 100644--- /dev/null +++ "b/stackoverflow_DL-related_questions_data/data19.json" @@ -0,0 +1,3000 @@ +{"QuestionId":55636740,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:00:20.313","AcceptedAnswerId":null,"OwnerUserId":7448090.0,"Title":"How to implement average reduction in caffe using Scale","Body":"

I want to implement Average-reduction in caffe<\/code> , not as part of the input layer. \nAlso I want it to be channel-wise, of some constant values (different from each other). I have tried with Scale<\/code> Layer and didn't find a way to subtract each channel individually.<\/p>\n\n

I will glad for some help<\/p>\n\n

EDIT<\/h2>\n\n

I was able to figure it out using bias<\/code> layer, which as i understand is used for implementing Scale<\/code> layer. <\/p>\n\n

I'm sharing my solution:<\/h3>\n\n

first create the prototxt:<\/p>\n\n

layer {\n    bottom: \"bottom_layer\"\n    top: \"top_layer\"\n    name: \"mean_reduction\"\n    type: \"Bias\"\n}\n<\/code><\/pre>\n\n

After it, injecting the data to the layer params<\/strong>, like this:<\/p>\n\n

net.params['mean_reduction'][0].data[...] = *the desired blob* \n<\/code><\/pre>\n","answers":[]}
+{"QuestionId":55636903,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:08:37.607","AcceptedAnswerId":null,"OwnerUserId":11347248.0,"Title":"Tensrflow \"Illegal Instruction\" error on session.run() line running on armv7l","Body":"

I'm trying to run Tensorflow on a PYNQ-Z2<\/code> board. I have installed it successfully using armv7l wheels for python3.5<\/code> and python3.6<\/code>. However, whenever I run any sample scripts that call session.run()<\/code> I get an \"Illegal Instruction\"<\/code> error. <\/p>\n\n

I have tried Tensorflow v1.5, v1.8, v1.9, v1.11, v1.12. <\/p>\n\n

Does anyone know anything I can try to fix this or know of where I can find a wheel that would work?<\/p>\n\n

Thank you!<\/p>\n","answers":[]} +{"QuestionId":55637271,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T16:30:32.100","AcceptedAnswerId":55637824.0,"OwnerUserId":4309985.0,"Title":"Preventing PyTorch Dataset iteration from exceeding length of dataset","Body":"

I am using a custom PyTorch Dataset with the following:<\/p>\n\n

class ImageDataset(Dataset):\n    def __init__(self, input_dir, input_num, input_format, transform=None):\n        self.input_num = input_num\n        # etc\n    def __len__ (self):\n        return self.input_num\n    def __getitem__(self,idx):\n        targetnum = idx % self.input_num\n        # etc\n<\/code><\/pre>\n\n

However, when I iterate over this dataset, iteration loops back to the start of the dataset instead of terminating at the end of the dataset. This effectively becomes an infinite loop in the iterator, with the epoch print statement never occurring for subsequent epochs.<\/p>\n\n

train_dataset=ImageDataset(input_dir = 'path\/to\/directory', \n                           input_num = 300, input_format = \"mask\") # Size 300\nnum_epochs = 10\nfor epoch in range(num_epochs):\n    print(\"EPOCH \" + str(epoch+1) + \"\\n\")\n    num = 0\n    for data in train_dataset:\n        print(num, end=\" \")\n        num += 1\n        # etc\n<\/code><\/pre>\n\n

Print output (... for values in between):<\/p>\n\n

EPOCH 1\n0 1 2 3 4 5 6 7 ... 298 299 300 301 302 303 304 305 ... 597 598 599 600 601 602 603 604 ...\n<\/code><\/pre>\n\n

Why is the basic iteration over the Dataset continuing past the defined __len__<\/code> of the DataSet, and how can I ensure that iteration over the dataset terminates after hitting the length of the dataset when using this method (or is manually iterating over the range of the dataset length the only solution)?<\/p>\n\n

Thank you.<\/p>\n","answers":[{"AnswerId":"55637824","CreationDate":"2019-04-11T17:06:19.253","ParentId":null,"OwnerUserId":"10749432","Title":null,"Body":"

Dataset<\/code> class doesn't have implemented StopIteration<\/code> signal.<\/p>\n\n

\n

The for<\/code> loop listens for StopIteration<\/code>. The purpose of the for statement is to loop over the sequence provided by an iterator and the exception is used to signal that the iterator is now done...<\/p>\n<\/blockquote>\n\n

More: Why does next raise a 'StopIteration', but 'for' do a normal return?<\/a> | The Iterator Protocol<\/a><\/p>\n"}]} +{"QuestionId":55637278,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:30:58.253","AcceptedAnswerId":null,"OwnerUserId":4462831.0,"Title":"Cannot run Tensorflow models from multiple threads","Body":"

I'm working on a project in which I need to load and run different neural networks at the same time.<\/p>\n\n

The models I am using for testing the code are taken from DeepLab Demo<\/a>, I basically encapsulated their code in a class (called DeepLabModel) and I instantiate it once for each different model they propose.<\/p>\n\n

Up to now I wrote a version of the code in which models are loaded (and used) sequentially from the same process, and everything works well<\/em>. <\/p>\n\n

Since I do some processing on the results and I need to simulate a distributed environment I need to parallelize each class containing the model.<\/p>\n\n

My first version was a class Agent<\/code> which got as parameter a previously loaded instance of DeepLabModel. Each Agent had a \"predict\" function which got executed in a different Process, but I noticed that the agents hanged on the session.run() function (inside the DeepLabModel.run()<\/code> function) without any output.<\/p>\n\n

Since I couldn't find the reason for this, I tried rewriting the code such that now each Agent<\/code> only gets the filename of each model, and I wrote a function run_agent()<\/code> in which I load the model, wait for an input image in a Queue and run the model on the input that is received.<\/p>\n\n

Here's some code from the last version (only relevant parts, DeepLabModel is just a wrapper of the code in the link provided above):<\/p>\n\n

import DeepLabModel\n\nclass Master():\n    def __init__(self, agents, timeout=10):\n        self.agents = agents # Reference to agents\n        # Message queues to communicate with the agents\n        self.output_queues = [Queue() for a in agents]\n        self.input_queues =  [Queue() for a in agents]\n        # Processes simulating remote agents    \n        self.agentpool = [Process(target=a.run_agent, \n                                  args=(self.output_queues[a_id], self.input_queues[a_id])) for a_id, a in enumerate(self.agents)]\n        for a in self.agentpool:\n            a.start()\n        print(\"Agents spawned\")\n\n\n\nclass Agent():\n    def __init__(self, agentname, model_name):\n        self.agentname=agentname\n        self.model_name = model_name\n        self.model = None\n\n    def load_model(self):\n        # .... basically the same code contained in DeepLab notebook\n        # ...here i use self.model_name and download the model...\n        self.model = DeepLabModel.DeepLabModel(download_path)\n\n\n    def run_agent(self, inqueue, outqueue):\n        self.inqueue = inqueue\n        self.outqueue = outqueue\n        self.load_model()\n        # The first element we expect is the task\n        image = self.inqueue.get()\n        result = self.model.run(image) # Here the program hangs\/crashes\n        # Asnwer back\n        self.outqueue.put(result)\n        # ...\n<\/code><\/pre>\n\n

The problem is that when the Processes try to execute tf.run()<\/code> each one fails with the error:\ntensorflow.python.framework.errors_impl.UnknownError: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.<\/code><\/p>\n\n

But no other warnings are printed. I tried running this both on gpu and cpu. I'm running a docker image (nvidia-docker), TF 1.12, everything works fine if I don't try to run tensorflow from different processes.<\/p>\n\n

I'm also wandering why the code hangs if the models are first loaded then passed to the processes (one to each process).<\/p>\n\n

Thank you in advance.<\/p>\n","answers":[]} +{"QuestionId":55637345,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T16:35:11.023","AcceptedAnswerId":55637346.0,"OwnerUserId":3623290.0,"Title":"Applying a permutation along one axis in TensorFlow","Body":"

How to permute \"dimensions\" along a single axis of a tensor?<\/p>\n\n

Something akin to tf.transpose<\/code>, but at the level of \"dimensions\" along an axis, instead of at the level of axes.<\/p>\n\n

To permute them randomly (along the first axis), there it tf.random.shuffle<\/code>, and to shift them, there is tf.roll<\/code>. But I can't find a more general function that would apply any given permutation.<\/p>\n","answers":[{"AnswerId":"55637346","CreationDate":"2019-04-11T16:35:11.023","ParentId":null,"OwnerUserId":"3623290","Title":null,"Body":"

tf.gather<\/code> can be used to that end. In fact, it is even more general, as the indices it takes as one of its inputs don't need to represent a permutation.<\/p>\n"}]} +{"QuestionId":55637407,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:38:15.783","AcceptedAnswerId":null,"OwnerUserId":11347415.0,"Title":"Dimension of the loss function and gradients for adversarial example","Body":"

I was working on some adversarial problem with mnist database. I was trying to find the gradient value for each pixel.For that, I calculated the categorical_crossentropy loss between mnist_model.input and target_number (target_number was first one hot encoded and then converted to a Keras variable) and the gradients. The dimension of my loss function is 28 by 28 by 10 and gradients are 28 by 28 by 1. I am not sure how the codes are working.\nHere is the following code, <\/p>\n\n

target = to_categorical(target_number)\nprint(target)\ntarget_variable = K.variable(target)\nloss = keras.metrics.categorical_crossentropy(mnist_model.input, target_variable)\ngradients = K.gradients(loss, mnist_model.input)\nget_grad_values = K.function([mnist_model.input], gradients)\n<\/code><\/pre>\n","answers":[]}
+{"QuestionId":55637564,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:49:32.147","AcceptedAnswerId":null,"OwnerUserId":10887556.0,"Title":"How do I use Pytorch's NLLLoss with count data?","Body":"

I have a model where I'm trying to predict with integer data, where an example of an expected output would be [40]. How do I use nn.PoissonNLLLoss to do this? Setting log_input=False slowly decreases my loss below 0.<\/p>\n","answers":[]} +{"QuestionId":55637648,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T16:54:51.717","AcceptedAnswerId":null,"OwnerUserId":9226396.0,"Title":"How to go about changing the kernel size in convolutional neural network","Body":"

I've got a discriminator and generator model in a GAN and I want to change the kernel sizes to be bigger. The input image is coming in at 64x64. At the moment the kernels are of size 4x4 (ks is set to 4):<\/p>\n\n

 self.main = nn.Sequential(\n        # input is (nc) x 64 x 64\n        nn.Conv2d(nc, self.ndf, ks, 2, 1, bias=False),\n        nn.LeakyReLU(0.2, inplace=True),\n        # state size. (self.ndf) x 32 x 32\n        nn.Conv2d(self.ndf, self.ndf * 2, ks, 2, 1, bias=False),\n        nn.BatchNorm2d(self.ndf * 2),\n        nn.LeakyReLU(0.2, inplace=True),\n        # state size. (self.ndf*2) x 16 x 16\n        nn.Conv2d(self.ndf * 2, self.ndf * 4, ks, 2, 1, bias=False),\n        nn.BatchNorm2d(self.ndf * 4),\n        nn.LeakyReLU(0.2, inplace=True),\n        # state size. (self.ndf*4) x 8 x 8\n        nn.Conv2d(self.ndf * 4, self.ndf * 8, ks, 2, 1, bias=False),\n        nn.BatchNorm2d(self.ndf * 8),\n        nn.LeakyReLU(0.2, inplace=True),\n        # state size. (self.ndf*8) x 4 x 4\n        nn.Conv2d(self.ndf * 8, 1, ks, 1, 0, bias=False),\n        nn.Sigmoid()\n    )\n<\/code><\/pre>\n\n

If I want to change it to 5 or 3, do I merely change ks to equal 5 or 3? Surely theres a problem because if you keep dividing the image size by two, the final layer has a size of 4x4 so It wouldnt fit on top of it properly. <\/p>\n","answers":[]} +{"QuestionId":55637807,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T17:05:26.633","AcceptedAnswerId":null,"OwnerUserId":7934786.0,"Title":"Attention layer on top of LSTM Autoencoder getting incompatibility error","Body":"

I am deploying a Bidirectional LSTM Autoencoder<\/code>, and am adding attention layer<\/code> on top of that.<\/p>\n\n

Before adding attention layer it is working fine. I got the idea from this post<\/a> for adding attention layer. \nAfter adding attention it complains about the dimension incompatibility.<\/p>\n\n

This is my code after adding attention:<\/p>\n\n

inputs = Input(shape=(SEQUENCE_LEN, EMBED_SIZE), name=\"input\")\nencoded = Bidirectional(LSTM(LATENT_SIZE, return_sequences=True), name=\"encoder_lstm\")(inputs)\nattention = Dense(SEQUENCE_LEN, activation='tanh')(encoded)\nattention = Flatten()(attention)\nattention = Activation('softmax')(attention)\nattention = RepeatVector(SEQUENCE_LEN)(attention)\nattention = Permute([2, 1])(attention)\nsent_representation = merge([encoded, attention], mode='mul')\nsent_representation = Lambda(lambda xin: K.sum(xin, axis=-2), output_shape=(units,))(sent_representation)\nautoencoder = Model(inputs, sent_representation)\nautoencoder.compile(optimizer=\"sgd\", loss='mse')\n<\/code><\/pre>\n\n

this is the error I got:<\/p>\n\n

Using TensorFlow backend.\n(?, 40, 50)\n(?, 40, 40)\nTraceback (most recent call last):\n(?, 40, 40)\n  File \"\/home\/sgnbx\/Downloads\/projects\/LSTM_autoencoder-master\/walkingaround.py\", line 131, in <module>\n    sent_representation = merge([activations, attention], mode='mul')\n  File \"\/home\/sgnbx\/anaconda3\/envs\/tf_gpu\/lib\/python3.4\/site-packages\/keras\/engine\/topology.py\", line 470, in __call__\n    self.assert_input_compatibility(x)\n  File \"\/home\/sgnbx\/anaconda3\/envs\/tf_gpu\/lib\/python3.4\/site-packages\/keras\/engine\/topology.py\", line 411, in assert_input_compatibility\n    str(K.ndim(x)))\nException: Input 0 is incompatible with layer dense_1: expected ndim=2, found ndim=3\n<\/code><\/pre>\n\n

I have read a couple of post regarding this error, namely: this<\/a> and this<\/a> and this<\/a>.\nbut they are not the same as my error. Also, Some suggested to make return_sequences=False, but I do not think this is the correct way. Later in the code, it again raises an error if we set it False!<\/p>\n\n

So, I feel like I am doing something wrong, otherwise, why the network should raise the error with the standard architecture.<\/p>\n\n

So my question is that:\nwhat is wrong with this network\nand how can I fix it.<\/p>\n\n

I appreciate it if you could explain in detail so I can grasp better or give me some links which talk about the conflict in my code.<\/p>\n\n

Thanks in advance!<\/p>\n","answers":[]} +{"QuestionId":55638143,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T17:26:13.323","AcceptedAnswerId":null,"OwnerUserId":11347571.0,"Title":"Failed to create a directory: logs\/fit","Body":"

With TensorFlow 1.13.1, I can save the logs with Tensorboard but when I upgrade to TensorFlow 2.0.0_alpha0 the same code gives me the error: <\/p>\n\n

\"Failed to create a directory: logs\/fit\/20190411-193710\\train; No such file or directory [Op:CreateSummaryFileWriter]\" \n<\/code><\/pre>\n\n

What can I do to correct this for TensorFlow 2.0.0_alpha0<\/p>\n\n

import tensorflow as tf\nimport datetime\nmnist = tf.keras.datasets.mnist\n\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train \/ 255.0, x_test \/ 255.0\n\ndef create_model():\nreturn tf.keras.models.Sequential([\ntf.keras.layers.Flatten(input_shape=(28, 28)),\ntf.keras.layers.Dense(512, activation='relu'),\ntf.keras.layers.Dropout(0.2),\ntf.keras.layers.Dense(10, activation='softmax')\n])\n\nmodel = create_model()\nmodel.compile(optimizer='adam',\n          loss='sparse_categorical_crossentropy',\n          metrics=['accuracy'])\n\nlog_dir=\"logs\/fit\/\"\ntensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, \nhistogram_freq=1)\n\nmodel.fit(x=x_train, \n          y=y_train, \n          epochs=5, \n          validation_data=(x_test, y_test), \n          callbacks=[tensorboard_callback])\n<\/code><\/pre>\n","answers":[]}
+{"QuestionId":55638192,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T17:29:20.320","AcceptedAnswerId":null,"OwnerUserId":3449567.0,"Title":"Solving a ML exercise with tensor flow","Body":"

First of all let me say than I'm a newcomer to machine\/deep lerning and tensorflow and after reading for a while i have some questions for an exercise i would like to solve.<\/p>\n\n

The exercise is the next one:<\/p>\n\n

Lets say that i have a training dataset which contains per each batch\/row a total of 50 questions of an undeterminated group of questions of two types:<\/p>\n\n

type 1. Questions with four posible answers. Only one answer per question is correct (single choise)<\/p>\n\n

type 2. Questions with four or five posible answers. Only two or tree posible correct answers. All correct answers have to be choosen (multiple choise)<\/p>\n\n

We can identify wheter if the question is type 1 or type 2.<\/p>\n\n

We can have x questions of type 1 and y questions of type 2 or x-2 questions of type 1 and y+2 of questions of type 2. (An undetermined amount of each type, changing each row)<\/p>\n\n

In the training dataset, each row contains 20 questions in total (and we can say how many of each type).<\/p>\n\n

We do also have the total percentil of success of the set of questions answered (total amount of correct answers in the set\/total amount of questions in the set * 100) BUT i can not tell if one particular question is right or wrong.<\/em><\/p>\n\n

Example of the batch\/each row:<\/p>\n\n

question 1: string\nanswer 1: string\na2: string\na3: string\nanswered: a1\nquestion type: 1\n(...)\nquestion 20: string\nanswer 20-1: string\na20-2: string\na20-3: string\na20-4: string\na20-5: string\nanswered: a20-3, a20-4, a20-5\nquestion type: 2\nsuccess percentil of all questions in the batch: 42%\n<\/code><\/pre>\n\n

goal:<\/p>\n\n

for a given question (type 1 or 2) that might or might not be in the training dataset (which could be expanded in each iteration\/epoch) give a percentil of succes for all posible answers. Example:<\/p>\n\n

q: qqqqqqqqqqqqq?\na1: 12.3%\na2: 50.8%\na3: 12.1%\na4: 34.5%\n<\/code><\/pre>\n\n

My questions:<\/p>\n\n

    \n
  1. Is this a problem that tensorflow (and the underling theory) can solve?<\/li>\n<\/ol>\n\n

    In case of no or maybe: alternatives?<\/p>\n\n

    In case yes:<\/p>\n\n

      \n
    1. Can you provide resources, examples.... on how to solve the problem?<\/li>\n<\/ol>\n\n

      Thank you!<\/p>\n","answers":[]} +{"QuestionId":55638347,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T17:41:11.640","AcceptedAnswerId":null,"OwnerUserId":3990607.0,"Title":"AttributeError: 'NoneType' object has no attribute '_inbound_nodes' in Keras while trying to do a resnet","Body":"

      I get the error AttributeError: 'NoneType' object has no attribute '_inbound_nodes'<\/code> while trying to create a Keras model using Keras'<\/p>\n\n

      model = Model(inputs=input, outputs=out)<\/code><\/p>\n\n

      From my understanding of other questions here on Stackoverflow (eg: Q1<\/a>, Q2<\/a>, Q3<\/a>, Q4<\/a>) about the same error, the trick should be to connect input<\/code> to out<\/code> using only Keras layer objects, even if it means using Lambda<\/code>. I am pretty sure that I did that.<\/p>\n\n

      My code is as follows:<\/p>\n\n

      from keras import backend as K\nimport keras\nfrom keras.layers import Layer, Activation, Conv1D, Lambda, Concatenate, Add\nfrom keras.layers.normalization import BatchNormalization\n\ndef create_resnet_model(input_shape, block_channels, repetitions, layer_class, batchnorm=False):\n    input = keras.Input(shape=input_shape)\n\n    x = K.identity(input)\n\n    resdim = sum(block_channels[-1]) if hasattr(block_channels[-1], \"__iter__\") else block_channels[-1]\n\n    def zero_pad_input(z):\n         pad_shape = K.concatenate([K.shape(z)[:2], [1 + resdim - input_shape[-1]]])\n         return K.concatenate([z, K.zeros(pad_shape)], axis=-1)\n\n    def add_mask_dim(z):\n        return K.concatenate([K.zeros_like(z[:, :, :1]), z], axis=-1)\n\n    padded_input = Lambda(zero_pad_input)(input)\n\n    def extract_features(z):\n        return z[:, :, 1:]\n\n    for block in range(repetitions):\n\n        for args in block_channels:\n            if not hasattr(args, \"__iter__\"):\n                args = (args, )\n            layer = layer_class(*args)\n            y = layer(x)\n            y_f = Lambda(extract_features)(y)\n            if batchnorm:\n                bn = BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None)\n                y_f = bn(y_f)\n            y_f = Activation(\"relu\")(y_f)\n            y = Lambda(add_mask_dim)(y_f)\n        if block == 0:\n            x = Add()([y, padded_input])\n        else:\n            x = Add()([x, y])\n\n    out = Conv1D(filters=1, kernel_size=1, activation=\"linear\", padding=\"same\")(x)\n\n    model = keras.Model(inputs=input, outputs=out)\n\n    return model\n<\/code><\/pre>\n\n

      Where layer_class<\/code> is a Keras layer module. So it seems to me that everything from the \u00ecnput<\/code> to out<\/code> is transformed using Keras layers. Even for the additions I use Add<\/code>.<\/p>\n","answers":[{"AnswerId":"55638388","CreationDate":"2019-04-11T17:43:06.700","ParentId":null,"OwnerUserId":"3990607","Title":null,"Body":"

      I found the problem. <\/p>\n\n

      x = K.identity(input)\n<\/code><\/pre>\n\n

      is not a Keras layer!<\/p>\n\n

      Changing that line for <\/p>\n\n

      def identity(z):\n    return z\n\nx = Lambda(identity)(input)\n<\/code><\/pre>\n\n

      solves the problem. <\/p>\n"}]} +{"QuestionId":55638989,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T18:26:20.353","AcceptedAnswerId":55639871.0,"OwnerUserId":8807447.0,"Title":"Eager tf.GradientTape() returns only Nones","Body":"

      I try to calculate the gradients with Tensorflow in the eager mode, but\ntf.GradientTape () returns only None values. I can not understand why.\nThe gradients are calculated in the update_policy () function.<\/p>\n\n

      The output of the line:<\/p>\n\n

      grads = tape.gradient(loss, self.model.trainable_variables)\n<\/code><\/pre>\n\n

      is<\/p>\n\n

      {list}<class 'list'>:[None, None, ... ,None]\n<\/code><\/pre>\n\n

      Here is the code.<\/p>\n\n

      import tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\n\nimport numpy as np\n\ntf.enable_eager_execution()\nprint(tf.executing_eagerly())\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsess = tf.Session(config=config)\nset_session(sess)\n\n\nclass PGEagerAtariNetwork:\n    def __init__(self, state_space, action_space, lr, gamma):\n        self.state_space = state_space\n        self.action_space = action_space\n        self.gamma = gamma\n\n        self.model = tf.keras.Sequential()\n        # Conv\n        self.model.add(\n            tf.keras.layers.Conv2D(filters=32, kernel_size=[8, 8], strides=[4, 4], activation='relu',\n                                   input_shape=(84, 84, 4,),\n                                   name='conv1'))\n        self.model.add(\n            tf.keras.layers.Conv2D(filters=64, kernel_size=[4, 4], strides=[2, 2], activation='relu', name='conv2'))\n        self.model.add(\n            tf.keras.layers.Conv2D(filters=128, kernel_size=[4, 4], strides=[2, 2], activation='relu', name='conv3'))\n        self.model.add(tf.keras.layers.Flatten(name='flatten'))\n\n        # Fully connected\n        self.model.add(tf.keras.layers.Dense(units=512, activation='relu', name='fc1'))\n        self.model.add(tf.keras.layers.Dropout(rate=0.4, name='dr1'))\n        self.model.add(tf.keras.layers.Dense(units=256, activation='relu', name='fc2'))\n        self.model.add(tf.keras.layers.Dropout(rate=0.3, name='dr2'))\n        self.model.add(tf.keras.layers.Dense(units=128, activation='relu', name='fc3'))\n        self.model.add(tf.keras.layers.Dropout(rate=0.1, name='dr3'))\n\n        # Logits\n        self.model.add(tf.keras.layers.Dense(units=self.action_space, activation=None, name='logits'))\n\n        self.model.summary()\n\n        # Optimizer\n        self.optimizer = tf.train.AdamOptimizer(learning_rate=lr)\n\n    def get_probs(self, s):\n        s = s[np.newaxis, :]\n        logits = self.model.predict(s)\n        probs = tf.nn.softmax(logits).numpy()\n        return probs\n\n    def update_policy(self, s, r, a):\n        with tf.GradientTape() as tape:\n            logits = self.model.predict(s)\n            policy_loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=a, logits=logits)\n            policy_loss = policy_loss * tf.stop_gradient(r)\n            loss = tf.reduce_mean(policy_loss)\n        grads = tape.gradient(loss, self.model.trainable_variables)\n        self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))\n<\/code><\/pre>\n","answers":[{"AnswerId":"55639871","CreationDate":"2019-04-11T19:29:24.610","ParentId":null,"OwnerUserId":"5154274","Title":null,"Body":"

      You don't have a forward pass in your model. The Model.predict()<\/code> method returns numpy()<\/code> array without taping the forward pass. Take a look at this example:<\/p>\n\n

      Given a following data and model:<\/p>\n\n

      import tensorflow as tf\nimport numpy as np\n\nx_train = tf.convert_to_tensor(np.ones((1, 2), np.float32), dtype=tf.float32)\ny_train = tf.convert_to_tensor([[0, 1]])\n\nmodel = tf.keras.models.Sequential([tf.keras.layers.Dense(2, input_shape=(2, ))])\n<\/code><\/pre>\n\n

      First we use predict()<\/code>:<\/p>\n\n

      with tf.GradientTape() as tape:\n    logits = model.predict(x_train)\n    print('`logits` has type {0}'.format(type(logits)))\n    # `logits` has type <class 'numpy.ndarray'>\n    xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_train, logits=logits)\n    reduced = tf.reduce_mean(xentropy)\n    grads = tape.gradient(reduced, model.trainable_variables)\n    print('grads are: {0}'.format(grads))\n    # grads are: [None, None]\n<\/code><\/pre>\n\n

      Now we use model's input:<\/p>\n\n

      with tf.GradientTape() as tape:\n    logits = model(x_train)\n    print('`logits` has type {0}'.format(type(logits)))\n    # `logits` has type <class 'tensorflow.python.framework.ops.EagerTensor'>\n    xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_train, logits=logits)\n    reduced = tf.reduce_mean(xentropy)\n    grads = tape.gradient(reduced, model.trainable_variables)\n    print('grads are: {0}'.format(grads))\n    # grads are: [<tf.Tensor: id=2044, shape=(2, 2), dtype=float32, numpy=\n    # array([[ 0.77717704, -0.777177  ],\n    #        [ 0.77717704, -0.777177  ]], dtype=float32)>, <tf.Tensor: id=2042, \n    # shape=(2,), dtype=float32, numpy=array([ 0.77717704, -0.777177  ], dtype=float32)>]\n\n<\/code><\/pre>\n\n

      So use model's __call__()<\/code> (i.e. model(x)<\/code>) for forward pass and not predict()<\/code>.<\/p>\n"}]} +{"QuestionId":55639151,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T18:37:12.190","AcceptedAnswerId":null,"OwnerUserId":11120877.0,"Title":"Mixing datasets in set ratio","Body":"

      In tensorlfow dataset, how do I mix 2 datasets, taking 75% of the set from my original data and 25% from the augmented data?<\/p>\n\n

      d = tf.data.Dataset.list_files(\"raw_data\/\")\\\n    .flat_map(tf.data.TFRecordDataset)\nad = tf.data.Dataset.list_files(\"augmented_data\/\")\\\n    .flat_map(tf.data.TFRecordDataset)\n<\/code><\/pre>\n","answers":[{"AnswerId":"55640140","CreationDate":"2019-04-11T19:47:37.970","ParentId":null,"OwnerUserId":"5786339","Title":null,"Body":"

      The problem is you can't use len()<\/code> on a dataset object, so it's sometimes hard to know exact number of examples until you iterate a full epoch. But you can approximate this with take<\/code> and skip<\/code> methods.<\/p>\n\n

      train_dataset = dataset.take(number_examples_for_train)\ntest_dataset = dataset.skip(number_examples_for_train)\n<\/code><\/pre>\n\n

      Those methods are a direct alternative to each other. \nhttps:\/\/www.tensorflow.org\/api_docs\/python\/tf\/data\/Dataset#take<\/a><\/p>\n"}]} +{"QuestionId":55639232,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T18:42:33.303","AcceptedAnswerId":null,"OwnerUserId":7803841.0,"Title":"OS Error: cannot identify the image file ","Body":"

      I am getting an error. I have tried all the previous solution on internet but it's not working. I guess the problem is with image = Image.open(myvar)<\/code> but not getting it.<\/p>\n\n

      def get_model():global model\n     model = load_model('Plant_Village.h5')\n     print(\" * Model loaded!\")\ndef preprocess_image(image,target_size):\n    image = image.resize(target_size)\n    image = img_to_array(image)\n    image = np.expand_dims(image,axis=0)\nreturn image\nprint(\" * Loading Keras model...\")\nget_model()\n@app.route(\"\/predict\",methods=['GET','POST'])\ndef predict():\n   message = request.get_json(force=True)\n   encoded = message['image']\n   decoded = base64.b64decode(encoded)\n   myvar=io.BytesIO(decoded)\n   print(myvar)\n   image = Image.open(myvar)\n   processed_image = preprocess_image(image, target_size=(256,256))\n   #print(\"image returned\")\n   prediction = model.predict(processed_image).tolist()\n   print(\"hello\")\n   respons={\n    'prediction':{\n        'Pepper__bell___Bacterial_spot':prediction[1][0][0][0][0][0][0][0][0][0][0][0][0][0][0],\n        'Pepper__bell___healthy':prediction[0][1][0][0][0][0][0][0][0][0][0][0][0][0][0],\n        'Potato___Early_blight':prediction[0][0][1][0][0][0][0][0][0][0][0][0][0][0][0],\n        'Potato___healthy':prediction[0][0][0][1][0][0][0][0][0][0][0][0][0][0][0],\n        'Potato___Late_blight':prediction[0][0][0][0][1][0][0][0][0][0][0][0][0][0][0],\n        'Tomato__Target_Spot':prediction[0][0][0][0][0][1][0][0][0][0][0][0][0][0][0],\n        'Tomato__Tomato_mosaic_virus':prediction[0][0][0][0][0][0][1][0][0][0][0][0][0][0][0],\n        'Tomato__Tomato_YellowLeaf__Curl_Virus':prediction[0][0][0][0][0][0][0][1][0][0][0][0][0][0][0],\n        'Tomato_Bacterial_spot':prediction[0][0][0][0][0][0][0][0][1][0][0][0][0][0][0],\n        'Tomato_Early_blight':prediction[0][0][0][0][0][0][0][0][0][1][0][0][0][0][0],\n        'Tomato_healthy':prediction[0][0][0][0][0][0][0][0][0][0][1][0][0][0][0],\n        'Tomato_Late_blight':prediction[0][0][0][0][0][0][0][0][0][0][0][1][0][0][0],\n        'Tomato_Leaf_Mold':prediction[0][0][0][0][0][0][0][0][0][0][0][0][1][0][0],\n        'Tomato_Septoria_leaf_spot':prediction[0][0][0][0][0][0][0][0][0][0][0][0][0][1][0],\n        'Tomato_Spider_mites_Two_spotted_spider_mite':prediction[0][0][0][0][0][0][0][0][0][0][0][0][0][0][1]\n    }\n}\nresponse=json.stringfy(respons)\nreturn jsonify(response)\n<\/code><\/pre>\n\n

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

      \"enter<\/a><\/p>\n","answers":[]} +{"QuestionId":55639955,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T19:35:24.457","AcceptedAnswerId":null,"OwnerUserId":10426463.0,"Title":"PyTorch Error The size of tensor a (128) must match the size of tensor b (9) at non-singleton dimension 0","Body":"

      I am running an CNN model of HAR using PyTorch 1.01 in Anaconda with GPU \nWhile doing the iteration it's giving me the error \nThe size of tensor a (128) must match the size of tensor b (9) at non-singleton dimension 0.\nI believe it's the datamodel while enumerate the train_model giving error. Anyone faced similar issues in PyTorch ? Need little support as new to PyTorch.<\/p>\n\n

      I have tried all the datamodel tricks found in google.<\/p>\n\n

      '''<\/p>\n\n

          def train(model, optimizer, train_loader, test_loader):\n    n_batch = len(train_loader.dataset) \/\/ BATCH_SIZE    \n    criterion = nn.CrossEntropyLoss()\n\n     for e in range(N_EPOCH):\n       model.train()\n       correct, total_loss = 0, 0\n        total = 0\n         for index, (sample, target) in enumerate(train_loader):\n        sample, target = sample.to(DEVICE).float(), target.to(DEVICE).long()            \n        sample = sample.view(-1, 9, 1, 128)\n        output = model(sample)\n        loss = criterion(output, target)\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        total_loss += loss.item()\n        _, predicted = torch.max(output.data, 1)\n        total += target.size(0)\n        correct += (predicted == target).sum()\n\n        if index % 20 == 0:\n            tqdm.tqdm.write('Epoch: [{}\/{}], Batch: [{}\/{}], loss:{:.4f}'.format(e + 1, N_EPOCH, index + 1, n_batch,\n                                                                                 loss.item()))\n    acc_train = float(correct) * 100.0 \/ (BATCH_SIZE * n_batch)\n    tqdm.tqdm.write(\n        'Epoch: [{}\/{}], loss: {:.4f}, train acc: {:.2f}%'.format(e + 1, N_EPOCH, total_loss * 1.0 \/ n_batch,\n                                                                  acc_train))\n\n    # Testing\n    model.train(False)\n    with torch.no_grad():\n        correct, total = 0, 0\n        for sample, target in test_loader:\n            sample, target = sample.to(DEVICE).float(), target.to(DEVICE).long()\n            sample = sample.view(-1, 9, 1, 128)\n            output = model(sample)\n            _, predicted = torch.max(output.data, 1)\n            total += target.size(0)\n            correct += (predicted == target).sum()\n    acc_test = float(correct) * 100 \/ total\n    tqdm.tqdm.write('Epoch: [{}\/{}], test acc: {:.2f}%'.format(e + 1, N_EPOCH, float(correct) * 100 \/ total))\n    result.append([acc_train, acc_test])\n    result_np = np.array(result, dtype=float)\n    np.savetxt('result.csv', result_np, fmt='%.2f', delimiter=',')   \n\n Error ----------------------------\n (7352, 1152)\n (7352, 128, 9)\n (2947, 1152)\n  (2947, 128, 9)\n   ----------------------------------------------------------------- \n    ----------\n RuntimeError                              Traceback (most recent \ncall last)\n <ipython-input-1-64c1adae4ee0> in <module>\n 86     model = net.Network().to(DEVICE)\n 87     optimizer = optim.SGD(params=model.parameters(), \n lr=LEARNING_RATE, momentum=0.9)\n---> 88     train(model, optimizer, train_loader, test_loader)\n 89     result = np.array(result, dtype=float)\n 90     np.savetxt('result.csv', result, fmt='%.2f', delimiter=',')\n\n <ipython-input-1-64c1adae4ee0> in train(model, optimizer, \n train_loader, test_loader)\n 29         correct, total_loss = 0, 0\n 30         total = 0\n ---> 31         for index, (sample, target) in \n enumerate(train_loader):\n 32             sample, target = sample.to(DEVICE).float(), \n target.to(DEVICE).long()\n 33             print('Sample',sample)\n\n ~\/anaconda3\/envs\/rnn_lstm_har_pytorch\/lib\/python3.6\/site- \n packages\/torch\/utils\/data\/dataloader.py in __next__(self)\n613         if self.num_workers == 0:  # same-process loading\n614             indices = next(self.sample_iter)  # may raise \nStopIteration\n--> 615             batch = self.collate_fn([self.dataset[i] for i \nin indices])\n616             if self.pin_memory:\n617                 batch = pin_memory_batch(batch)\n\n  ~\/anaconda3\/envs\/rnn_lstm_har_pytorch\/lib\/python3.6\/site- \n packages\/torch\/utils\/data\/dataloader.py in <listcomp>(.0)\n  613         if self.num_workers == 0:  # same-process loading\n  614             indices = next(self.sample_iter)  # may raise \n StopIteration\n --> 615             batch = self.collate_fn([self.dataset[i] for i \n in \n  indices])\n  616             if self.pin_memory:\n  617                 batch = pin_memory_batch(batch)\n\n ~\/anaconda3\/envs\/rnn_lstm_har_pytorch\/data_preprocess.py in \n __getitem__(self, index)\n  97     def __getitem__(self, index):\n  98         sample, target = self.samples[index], \n  self.labels[index]\n  ---> 99         return self.T(sample), target\n  100 \n  101     def __len__(self):\n\n ~\/anaconda3\/envs\/rnn_lstm_har_pytorch\/lib\/python3.6\/site- \n   packages\/torchvision\/transforms\/transforms.py in __call__(self, \n   img)\n   58     def __call__(self, img):\n   59         for t in self.transforms:\n   ---> 60             img = t(img)\n   61         return img\n   62 \n\n   ~\/anaconda3\/envs\/rnn_lstm_har_pytorch\/lib\/python3.6\/site- \n   packages\/torchvision\/transforms\/transforms.py in __call__(self, \n  tensor)\n   161             Tensor: Normalized Tensor image.\n   162         \"\"\"\n  --> 163         return F.normalize(tensor, self.mean, self.std, \n  self.inplace)\n   164 \n   165     def __repr__(self):\n\n  ~\/anaconda3\/envs\/rnn_lstm_har_pytorch\/lib\/python3.6\/site- \n  packages\/torchvision\/transforms\/functional.py in normalize(tensor, \n  mean, std, inplace)\n  206     mean = torch.tensor(mean, dtype=torch.float32)\n  207     std = torch.tensor(std, dtype=torch.float32)\n --> 208     tensor.sub_(mean[:, None, None]).div_(std[:, None, \n  None])\n  209     return tensor\n  210 \n\nRuntimeError: The size of tensor a (128) must match the size of \ntensor b (9) at non-singleton dimension 0\n\n   # This is for parsing the X data, you can ignore it if you do not \n   need preprocessing\n   def format_data_x(datafile):\n    x_data = None\n    for item in datafile:\n    item_data = np.loadtxt(item, dtype=np.float)\n    if x_data is None:\n        x_data = np.zeros((len(item_data), 1))\n    x_data = np.hstack((x_data, item_data))\n    x_data = x_data[:, 1:]\n    print(x_data.shape)\n    X = None\n    for i in range(len(x_data)):\n    row = np.asarray(x_data[i, :])\n    row = row.reshape(9, 128).T\n    if X is None:\n        X = np.zeros((len(x_data), 128, 9))\n    X[i] = row\n    print(X.shape)\n    return X\n\n\n    # This is for parsing the Y data, you can ignore it if you do not \n    need preprocessing\n    def format_data_y(datafile):\n    data = np.loadtxt(datafile, dtype=np.int) - 1\n    YY = np.eye(6)[data]\n    return YY\n\n\n    # Load data function, if there exists parsed data file, then use \n    it\n    # If not, parse the original dataset from scratch\n   def load_data():\n   import os\n\n    # This for processing the dataset from scratch\n    # After downloading the dataset, program put it in the DATA_PATH \n   folder\n\n    #str_folder = 'data\/' + 'UCI HAR Dataset\/'\n    DATA_PATH = 'data\/'\n    DATASET_PATH = DATA_PATH + 'UCI HAR Dataset\/'\n    TRAIN = 'train\/'\n    TEST = 'test\/'\n\n    INPUT_SIGNAL_TYPES = [\n        \"body_acc_x_\",\n        \"body_acc_y_\",\n        \"body_acc_z_\",\n        \"body_gyro_x_\",\n        \"body_gyro_y_\",\n        \"body_gyro_z_\",\n        \"total_acc_x_\",\n        \"total_acc_y_\",\n        \"total_acc_z_\"\n    ]\n\n    str_train_files = [DATASET_PATH + TRAIN + 'Inertial Signals\/' + \n    item + 'train.txt' for item in\n                       INPUT_SIGNAL_TYPES]\n    str_test_files = [DATASET_PATH + TEST + 'Inertial Signals\/' + item \n    + 'test.txt' for item in INPUT_SIGNAL_TYPES]\n    str_train_y = DATASET_PATH + TRAIN + 'y_train.txt'\n    str_test_y = DATASET_PATH + TEST + 'y_test.txt'\n\n    X_train = format_data_x(str_train_files)\n    X_test = format_data_x(str_test_files)\n    Y_train = format_data_y(str_train_y)\n    Y_test = format_data_y(str_test_y)\n\n   return X_train, onehot_to_label(Y_train), X_test, \n   onehot_to_label(Y_test)\n\n\n  def onehot_to_label(y_onehot):\n  a = np.argwhere(y_onehot == 1)\n  return a[:, -1]\n\n    class data_loader(Dataset):\n    def __init__(self, samples, labels, t):\n    self.samples = samples\n    self.labels = labels\n    self.T = t\n\n    def __getitem__(self, index):\n    sample, target = self.samples[index], self.labels[index]\n    return self.T(sample), target\n\n    def __len__(self):\n    return len(self.samples)\n\n\n   def load(batch_size=64):\n   x_train, y_train, x_test, y_test = load_data()\n   x_train, x_test = x_train.reshape((-1, 9, 1, 128)), \n   x_test.reshape((-1, 9, 1, 128))\n   transform = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize(mean=(0,0,0,0,0,0,0,0,0), std= \n    (1,1,1,1,1,1,1,1,1))\n    ])\n  train_set = data_loader(x_train, y_train, transform)\n  test_set = data_loader(x_test, y_test, transform)    \n  train_loader = DataLoader(train_set, batch_size=batch_size, \n  shuffle=True, drop_last=True)\n  test_loader = DataLoader(test_set, batch_size=batch_size, \n  shuffle=False)\n  return train_loader, test_loader\n<\/code><\/pre>\n\n

      '''<\/p>\n","answers":[{"AnswerId":"55641208","CreationDate":"2019-04-11T21:09:35.260","ParentId":null,"OwnerUserId":"3758174","Title":null,"Body":"

      The mean<\/code> in the normalize<\/code> transform must have the same size as the number of channels of the sample<\/code>. For example, if the sample is N x 9 x 5 x 7<\/code> mean<\/code> be size 9<\/code>. In this case, your sample has 128 channels but mean is of size 9<\/code>.<\/p>\n\n

      It looks like you try to reshape the sample using sample.view(-1, 9, 1, 128)<\/code> but that happens after the error in data loading.<\/p>\n\n

      You need to reshape the tensor before the normalize<\/code> transform. For example,<\/p>\n\n

      def reshape_tensor(x):\n    return x.reshape(9, 1, 128)\n\ntrain_dataset = datasets.ImageFolder(\n    traindir,\n    transforms.Compose([\n        ...,\n        reshape_tensor,\n        normalize,\n    ]))\n<\/code><\/pre>\n"}]}
      +{"QuestionId":55640149,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T19:48:36.350","AcceptedAnswerId":null,"OwnerUserId":3162360.0,"Title":"Error in Keras when I want to calculate the Sensitivity and Specificity","Body":"

      I am writing a code for classification between two types of images based on a CNN.\nI want to measure the accuracy, sensitivity, and specificity for my work but unfortunately, I have the following error. \nCould you please let me know what my problem is. <\/p>\n\n

      m = tf.keras.metrics.SensitivityAtSpecificity(0.5)\nmodel.compile(optimizer='adam', loss=keras.losses.binary_crossentropy, metrics=['accuracy',m])\n<\/code><\/pre>\n\n

      error:<\/p>\n\n

      Traceback (most recent call last):\n  File \"C:\/Users\/Hamed\/PycharmProjects\/Deep Learning\/CNN.py\", line 77, in <module>\n    validation_steps = 1600\/\/batch_size)\n  File \"C:\\Users\\Hamed\\Anaconda3\\envs\\tensorflowGPU\\lib\\site-packages\\keras\\legacy\\interfaces.py\", line 91, in wrapper\n    return func(*args, **kwargs)\n  File \"C:\\Users\\Hamed\\Anaconda3\\envs\\tensorflowGPU\\lib\\site-packages\\keras\\engine\\training.py\", line 1418, in fit_generator\n    initial_epoch=initial_epoch)\n  File \"C:\\Users\\Hamed\\Anaconda3\\envs\\tensorflowGPU\\lib\\site-packages\\keras\\engine\\training_generator.py\", line 217, in fit_generator\n    class_weight=class_weight)\n  File \"C:\\Users\\Hamed\\Anaconda3\\envs\\tensorflowGPU\\lib\\site-packages\\keras\\engine\\training.py\", line 1217, in train_on_batch\n    outputs = self.train_function(ins)\n  File \"C:\\Users\\Hamed\\Anaconda3\\envs\\tensorflowGPU\\lib\\site-packages\\keras\\backend\\tensorflow_backend.py\", line 2715, in __call__\n    return self._call(inputs)\n  File \"C:\\Users\\Hamed\\Anaconda3\\envs\\tensorflowGPU\\lib\\site-packages\\keras\\backend\\tensorflow_backend.py\", line 2675, in _call\n    fetched = self._callable_fn(*array_vals)\n  File \"C:\\Users\\Hamed\\Anaconda3\\envs\\tensorflowGPU\\lib\\site-packages\\tensorflow\\python\\client\\session.py\", line 1439, in __call__\n    run_metadata_ptr)\n  File \"C:\\Users\\Hamed\\Anaconda3\\envs\\tensorflowGPU\\lib\\site-packages\\tensorflow\\python\\framework\\errors_impl.py\", line 528, in __exit__\n    c_api.TF_GetCode(self.status.status))\ntensorflow.python.framework.errors_impl.NotFoundError: Resource localhost\/false_negatives\/class tensorflow::Var does not exist.\n     [[{{node metrics\/sensitivity_at_specificity\/AssignAddVariableOp_1}}]]\n     [[{{node metrics\/sensitivity_at_specificity\/Mean}}]]\n<\/code><\/pre>\n","answers":[{"AnswerId":"55688340","CreationDate":"2019-04-15T11:36:32.737","ParentId":null,"OwnerUserId":"4931156","Title":null,"Body":"

      The metric tf.keras.metrics.SensitivityAtSpecificity calculates sensitivity at a given specificity Click here<\/a>.<\/p>\n\n

      Unfortunately sensitivity and specificity metrics are not yet included in Keras, so you have to write your own custom metric as is specified here<\/a>.<\/p>\n\n

      The following is one simple way to calculate specificity found at this answer<\/a>.<\/p>\n\n

      def specificity(y_true, y_pred):\n    \"\"\"\n    param:\n    y_pred - Predicted labels\n    y_true - True labels \n    Returns:\n    Specificity score\n    \"\"\"\n    neg_y_true = 1 - y_true\n    neg_y_pred = 1 - y_pred\n    fp = K.sum(neg_y_true * y_pred)\n    tn = K.sum(neg_y_true * neg_y_pred)\n    specificity = tn \/ (tn + fp + K.epsilon())\n    return specificity\n<\/code><\/pre>\n\n

      You can get Keras implementations for specificity and sensitivity on this link<\/a>.<\/p>\n"}]} +{"QuestionId":55640342,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T20:04:55.003","AcceptedAnswerId":null,"OwnerUserId":9750363.0,"Title":"Proper hashing of categorical variables for RNN - Binary Classifcation","Body":"

      I'm currently working on a project that has all categorical data as input and a binary output (1=Yes 0=No).<\/p>\n\n

      A little bit about the data.\nThere are 3127854 rows. Each feature column is categorical in nature. \nThe following is how many unique values are in each column.<\/p>\n\n

      attribute_1 - 87<\/p>\n\n

      attribute_2 - 2<\/p>\n\n

      attribute_3 - 202<\/p>\n\n

      attribute_4 - 3<\/p>\n\n

      attribute_5 - 3<\/p>\n\n

      attribute_6 - 367<\/p>\n\n

      I keep on running into issues with how to hash\/embed the columns in a manner that allows me to input them into a RNN. Ideally what i'd like to do is hash the columns, embed, pass through LSTM layer, concat, flatten, dense layer, then output a binary prediction.<\/p>\n\n

      sorry if the code is a little sloppy\/repetitive as im tinkering around right now.<\/p>\n\n

      import numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\ndata = pd.read_csv(\".....\")\n\n\n#Creating hash buckets for categorical data\n\nattribute_1_hashed = tf.feature_column.categorical_column_with_hash_bucket(\"attribute_1\", len(auction_clean[\"attribute_1\"].unique()))\nattribute_2_hashed = tf.feature_column.categorical_column_with_hash_bucket(\"app_attribute_2\", len(auction_clean[\"app_attribute_2\"].unique()))\nattribute_3_hashed = tf.feature_column.categorical_column_with_hash_bucket(\"attribute_3\", len(auction_clean[\"attribute_3\"].unique()))\nattribute_4_hashed = tf.feature_column.categorical_column_with_hash_bucket(\"attribute_4\",len(auction_clean[\"attribute_4\"].unique()))\nattribute_5_hashed = tf.feature_column.categorical_column_with_hash_bucket(\"attribute_5\",len(auction_clean[\"attribute_5\"].unique()))\nattribute_6_hashed = tf.feature_column.categorical_column_with_hash_bucket(\"attribute_6\", len(auction_clean[\"attribute_6\"].unique()))\n\n\n#Input layer\nattribute_1_input = tf.keras.Input(shape=(1,), name='attribute_1')\nattribute_2_input = tf.keras.Input(shape=(1,), name='attribute_2')\nattribute_3_input = tf.keras.Input(shape=(1,), name='attribute_3')\nattribute_4_input = tf.keras.Input(shape=(1,), name='attribute_4')\nattribute_5_input = tf.keras.Input(shape=(1,), name='attribute_5')\nattribute_6_input = tf.keras.Input(shape=(1,), name='attribute_6')\n\n#Embedding Layer\nlongest_string = {}\nfor column in col_names:\n    longest_string[column] = auction_clean[column].map(lambda x: len(x)).max()\n\n\nembed_size = 10\nattribute_1_embedded = tf.keras.layers.Embedding(len(data.attribute_1)+1, embed_size,\n                                       input_length=1, name='attribute_1_embedding')(attribute_1_input)\n\nattribute_2_embedded = tf.keras.layers.Embedding(len(data.app_attribute_2)+1, embed_size, \n                                       input_length=1, name='attribute_2_embedding')(attribute_2_input)\n\nattribute_3_embedded = tf.keras.layers.Embedding(longest_string['attribute_3']+1, embed_size, \n                                       input_length=1, name='attribute_3_embedding')(attribute_3_input)\n\nattribute_4_embedded = tf.keras.layers.Embedding(longest_string['attribute_4']+1, embed_size, \n                                       input_length=1, name='attribute_4_embedding')(attribute_4_input)\n\nattribute_5_embedded = tf.keras.layers.Embedding(longest_string['attribute_5']+1, embed_size, \n                                       input_length=1, name='attribute_5_embedding')(attribute_5_input)  \n\nattribute_6_embedded = tf.keras.layers.Embedding(data.attribute_6.max()+1, embed_size, \n                                       input_length=1, name='attribute_6_embedding')(attribute_6_input)\n\n\n#LSTM Layer\nnum_units = 64\nattribute_1_lstm = tf.keras.layers.LSTM(units=num_units)(attribute_1_embedded)\nattribute_2_lstm = tf.keras.layers.LSTM(units=num_units)(attribute_2_embedded)\nattribute_3_lstm = tf.keras.layers.LSTM(units=num_units)(attribute_3_embedded)\nattribute_4_lstm = tf.keras.layers.LSTM(units=num_units)(attribute_4_embedded)\nattribute_5_lstm = tf.keras.layers.LSTM(units=num_units)(attribute_5_embedded)\nattribute_6_lstm = tf.keras.layers.LSTM(units=num_units)(attribute_6_embedded)\n\n\n#Concatenate LSTM's output\nconcatenated = tf.keras.layers.Concatenate()([attribute_1_lstm, \n                                           attribute_2_lstm,\n                                           attribute_3_lstm,\n                                           attribute_4_lstm,\n                                           attribute_5_lstm,\n                                           attribute_6_lstm])\n\nflatten = tf.keras.layers.Flatten()(concatenated)\n\n#Dense layer\ndense = tf.keras.layers.Dense(num_units, activation='relu')(concatenated)\n\n#Output Layer\nout = tf.keras.layers.Dense(1, activation=\"sigmoid\", name=\"main_output\")(dense)\n\nmodel = tf.keras.Model(\n    inputs = [attribute_1_input,attribute_2_input,attribute_3_input,attribute_4_input,attribute_5_input,attribute_6_input],\n    outputs = out,\n)\n\nmodel.compile(\n    tf.train.AdamOptimizer(0.1),\n    loss='categorical_crossentropy',\n    metrics=['accuracy'],\n)\n\n\nhistory = model.fit(\n    [attribute_1_hashed, attribute_2_hashed,attribute_3_hashed,attribute_4_hashed,attribute_5_hashed,attribute_6_hashed],\n    data.y,\n    batch_size=10,\n    epochs=1,\n    steps_per_epoch = 1,\n    verbose=0\n)\n\n<\/code><\/pre>\n\n

      What ends up happening at this point is the model.fit call doesnt end up working, saying<\/p>\n\n

      ValueError: Input arrays should have the same number of samples as target arrays. Found 3 input samples and 3127854 target samples.<\/p>\n\n

      Any input or guidance would be helpful, and as always please let me know if any clarification is needed.<\/p>\n\n

      Thanks in advance!<\/p>\n","answers":[]} +{"QuestionId":55640352,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T20:05:21.237","AcceptedAnswerId":null,"OwnerUserId":11014272.0,"Title":"Using Keras optimizers and models outside of the training process","Body":"

      I have a basic question. I want to know whether it is possible to use Keras (e.g. the functional API) to specify a neural network model, and then use the Keras optimization routines to train the network outside of the Keras training process. In other words, use Keras purely to specify a neural network, pull the weights out and put them into a loss function (outside the Keras APIs if necessary) then use one of the built-in optimization routines purely to minimize the loss function over a single batch of data (no multiple epochs etc. or anything beyond minimization of the loss function with regard to one set of data at this point).<\/p>\n\n

      My reason for wanting to do this is that I would like to use a dynamic optimization process that changes from batch iteration to batch iteration, which seems difficult to implement entirely within the Keras APIs.<\/p>\n","answers":[]} +{"QuestionId":55640538,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T20:21:08.750","AcceptedAnswerId":55640919.0,"OwnerUserId":11347242.0,"Title":"What does it mean \"The tensor's graph is different from the session's graph.\"","Body":"

      I'm trying to run this very simple tensorflow code I found on colab, but it seems I'm missing something basic about it.<\/p>\n\n

      I already tried to replace xy_sum.eval() with xy_sum.eval(session=sess) but the problem seems to persist.\nHere's \"my\" code:<\/p>\n\n

      from __future__ import print_function\nimport tensorflow as tf\ng=tf.Graph()\nwith g.as_default():\n    x=tf.constant(8,name=\"x_const\")\n    y=tf.constant(5,name=\"y_const\")\n    xy_sum=tf.add(x,y,name=\"x_y_sum\")\nwith tf.Session() as sess:\n    print(xy_sum.eval())\n<\/code><\/pre>\n\n

      I expect the output to be 13 as shown on https:\/\/colab.research.google.com\/notebooks\/mlcc\/tensorflow_programming_concepts.ipynb#scrollTo=Md8ze8e9geMi<\/a>,\nbut the ouput i get from spyder is<\/p>\n\n

      Traceback (most recent call last):\n\n  File \"<ipython-input-35-67314fd48aa4>\", line 1, in <module>\n    runfile('\/home\/***\/.config\/spyder-py3\/New Folder\/sommatf.py', wdir='\/home\/***\/.config\/spyder-py3\/New Folder')\n\n  File \"\/home\/***\/python3.7\/site-packages\/spyder_kernels\/customize\/spydercustomize.py\", line 786, in runfile\n    execfile(filename, namespace)\n\n  File \"\/home\/***\/python3.7\/site-packages\/spyder_kernels\/customize\/spydercustomize.py\", line 110, in execfile\n    exec(compile(f.read(), filename, 'exec'), namespace)\n\n  File \"\/home\/***\/.config\/spyder-py3\/New Folder\/sommatf.py\", line 15, in <module>\n    print(xy_sum.eval())\n\n  File \"\/home\/***\/python3.7\/site-packages\/tensorflow\/python\/framework\/ops.py\", line 695, in eval\n    return _eval_using_default_session(self, feed_dict, self.graph, session)\n\n  File \"\/home\/***\/python3.7\/site-packages\/tensorflow\/python\/framework\/ops.py\", line 5172, in _eval_using_default_session\n    raise ValueError(\"Cannot use the default session to evaluate tensor: \"\n\nValueError: Cannot use the default session to evaluate tensor: the tensor's graph is different from the session's graph. Pass an explicit session to `eval(session=sess)`.\n<\/code><\/pre>\n\n

      if I try, as suggested, to pass an explicit session I get:<\/p>\n\n

      raise ValueError(\"Cannot use the given session to evaluate tensor: \"\n\nValueError: Cannot use the given session to evaluate tensor: the tensor's graph is different from the session's graph.\n<\/code><\/pre>\n","answers":[{"AnswerId":"55640919","CreationDate":"2019-04-11T20:47:27.180","ParentId":null,"OwnerUserId":"5179463","Title":null,"Body":"

      The tf.Session<\/code> uses the default graph. So in order to use the graph g<\/code> you would either have to indent the session initialization into the with g.as_default():<\/code> block, or pass the graph to the session at initialization<\/a>.<\/p>\n"}]} +{"QuestionId":55640544,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T20:21:45.250","AcceptedAnswerId":null,"OwnerUserId":10952884.0,"Title":"model.fit_generator() fails with use_multiprocessing=True","Body":"

      In the code example below, I can train the model only when NOT using multiprocessing.<\/p>\n\n

      My generator is straight from the tensorflow.keras.utils.Sequence description https:\/\/www.tensorflow.org\/api_docs\/python\/tf\/keras\/utils\/Sequence<\/a><\/p>\n\n

      Any idea how to fix the generator to allow multiprocessing?<\/p>\n\n

      Running on Win 10, tensorflow 1.13.1, python 3.6.8<\/p>\n\n

      import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.utils import Sequence\n\n\n# Generator\nclass DataGenerator(Sequence):\n\n        def __init__(self, dim, batch_size, n_channels):\n\n            self.dim = dim            \n            self.batch_size = batch_size\n            self.n_channels = n_channels\n\n        def __len__(self):\n            return 100\n\n        def __getitem__(self, idx):\n\n            X = np.random.randn(self.batch_size, self.dim, self.n_channels)\n            Y = np.random.randn(self.batch_size, self.dim, 1)\n\n            return X, Y\n\n\ndim= 32\nbatch_size= 64\nn_channels= 3\n\n# Generators\ntraining_generator = DataGenerator(dim, batch_size, n_channels)\nvalidation_generator = DataGenerator(dim, batch_size, n_channels)\n\n\n# Model\nmodel = Sequential()\nmodel.add(layers.GRU(128, return_sequences=True, \n                     batch_input_shape=[None, training_generator.dim, training_generator.n_channels]))\nmodel.add(layers.Dense(1))\n\nmodel.compile(loss='mse', optimizer='adam')\n\n\n# This training procedure runs\nmodel.fit_generator(generator=training_generator,\n                    epochs = 2,\n                    steps_per_epoch = 100,\n                    max_queue_size = 32,\n                    validation_data=validation_generator,\n                    validation_steps = 20,\n                    verbose=1)\n\n# This training procedure fails (Only change is that I added the multiprocessing options)\nmodel.fit_generator(generator=training_generator,\n                    epochs = 2,\n                    steps_per_epoch = 100,\n                    max_queue_size = 32,\n                    validation_data=validation_generator,\n                    validation_steps = 20,\n                    verbose=1,\n                    use_multiprocessing=True,\n                    workers=4)\n<\/code><\/pre>\n\n

      I expected the second fit_generator() call to train the model like the first one. Instead, I get no output, not even an error message.<\/p>\n","answers":[{"AnswerId":"57022645","CreationDate":"2019-07-13T20:35:22.287","ParentId":null,"OwnerUserId":"11749543","Title":null,"Body":"

      I tried your code on Ubuntu 18.04.2 LTS machine with python 3.6.8 and tensorflow 1.13.1. It works in both cases as log shown below:<\/p>\n\n

      2019-07-13 12:56:17.003119: I tensorflow\/stream_executor\/dso_loader.cc:152] successfully opened CUDA library libcublas.so.10.0 locally\n100\/100 [==============================] - 3s 27ms\/step - loss: 0.9987\n100\/100 [==============================] - 10s 103ms\/step - loss: 0.9973 - val_loss: 0.9987\nEpoch 2\/2\n100\/100 [==============================] - 3s 26ms\/step - loss: 0.9955\n100\/100 [==============================] - 8s 83ms\/step - loss: 1.0028 - val_loss: 0.9955\nMultiprocessing=True ......\nEpoch 1\/2\n100\/100 [==============================] - 3s 32ms\/step - loss: 0.9952\n100\/100 [==============================] - 9s 89ms\/step - loss: 0.9962 - val_loss: 0.9952\nEpoch 2\/2\n100\/100 [==============================] - 3s 28ms\/step - loss: 0.9967\n100\/100 [==============================] - 9s 86ms\/step - loss: 0.9968 - val_loss: 0.9967\"\n<\/code><\/pre>\n\n

      My suggestion is to first try with CPU only mode, by putting BOTH the model and the fit_generator code under \"with tf.device('\/cpu:0'):\". If it works, it would be GPU related issue, such as proper driver, tensorflow with GPU support etc. Most likely, the issue was caused by GPU hanging.<\/p>\n"}]} +{"QuestionId":55640642,"AnswerCount":1,"Tags":"","CreationDate":"2019-04-11T20:27:52.087","AcceptedAnswerId":55657233.0,"OwnerUserId":11348106.0,"Title":"Error when attempting to change tensor shape in keras model","Body":"

      I want to change the shape and the content of the tensor in a keras model. Tensor is the output of a layer and has <\/p>\n\n

      shape1=(batch_size, max_sentences_in_doc, max_tokens_in_doc, embedding_size)<\/code> <\/p>\n\n

      and I want to convert to <\/p>\n\n

      shape2=(batch_size, max_documents_length, embedding_size)<\/code> <\/p>\n\n

      suitable as input of the next layer. Here sentences are made of tokens, and are zero-padded so every sentence has length=max_tokens_in_sentence<\/code>. \nIn detail:<\/p>\n\n

        \n
      1. I wanto to concatenate all the sentences of a batch taking only the nonzero part of the sentences;<\/li>\n
      2. then I zero-pad this concatenation to a length=max_document_length<\/code>.<\/li>\n<\/ol>\n\n

        So passing from shape1<\/code> to shape2<\/code> is not only a reshape as mathematical operations are involved.<\/p>\n\n

        I created the function embedding_to_docs(x)<\/code> that iterates on the tensor of shape1 to transform it into shape2. I call the function using a Lambda layer in the model, it works in debug with fictious data, but when I try to call it during the build of the model an error is raised: <\/p>\n\n

        Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn.<\/code><\/p>\n\n

        def embedding_to_docs(x):\n    new_output = []\n    for doc in x:\n        document = []\n        for sentence in doc:\n            non_zero_indexes = np.nonzero(sentence[:, 0])\n            max_index = max(non_zero_indexes[0])\n            if max_index > 0:\n                document.extend(sentence[0:max_index])\n        if MAX_DOCUMENT_LENGTH-len(document) > 0:\n            a = np.zeros((MAX_DOCUMENT_LENGTH-len(document), 1024))\n            document.extend(a)\n        else:\n            document = document[0:MAX_DOCUMENT_LENGTH]\n        new_output.append(document)\n\n    return np.asarray(new_output)\n\n...\n\n# in the model:\ntensor_of_shape2 = Lambda(embedding_to_docs)(tensor_of_shape1)\n\n<\/code><\/pre>\n\n

        How to fix this?<\/p>\n","answers":[{"AnswerId":"55657233","CreationDate":"2019-04-12T17:54:38.403","ParentId":null,"OwnerUserId":"2912797","Title":null,"Body":"

        You can use py_function<\/code><\/a>, which allows you to switch from the graph mode (used by Keras) to the eager mode (where it is possible to iterate over tensors like in your function).<\/p>\n\n

        def to_docs(x):\n  return tf.py_function(embedding_to_docs, [x], tf.float32)\n\ntensor_of_shape2 = Lambda(to_docs)(tensor_of_shape1)\n<\/code><\/pre>\n\n

        Note that the code run within your embedding_to_docs<\/code> must be written in tensorflow eager instead of numpy. This means that you'd need to replace some of the numpy calls with tensorflow. You'd surely need to replace the return line with:<\/p>\n\n

        return tf.convert_to_tensor(new_output)\n<\/code><\/pre>\n\n

        Using numpy arrays will stop the gradient computation, but you are likely not interested in gradient flowing through the input data anyway.<\/p>\n"}]} +{"QuestionId":55640836,"AnswerCount":2,"Tags":"","CreationDate":"2019-04-11T20:41:36.430","AcceptedAnswerId":null,"OwnerUserId":1601580.0,"Title":"How does one dynamically add new parameters to optimizers in Pytorch?","Body":"

        I was going through this post<\/a> in the pytorch forum, and I also wanted to do this. The original post removes and adds layers but I think my situation is not that different. I also want to add layers or more filters or word embeddings. My main motivation is that the AI agent does not know the whole vocabulary\/dictionary in advance because its large. I prefer strongly (for the moment) to not do character by character RNNs.<\/p>\n\n

        So what will happen for me is when the agent starts a forward pass it might find new words it has never seen and will need to add them to the embedding table (or perhaps add new filters before it starts the forward pass).<\/p>\n\n

        So what I want to make sure is:<\/p>\n\n

          \n
        1. embeddings are added correctly (at the right time, when a new computation graph is made) so that they are updatable by the optimizer<\/li>\n
        2. no issues with stored info of past parameters e.g. if its using some sort of momentum<\/li>\n<\/ol>\n\n

          How does one do this? Any sample code that works?<\/p>\n","answers":[{"AnswerId":"55776832","CreationDate":"2019-04-20T19:09:55.167","ParentId":null,"OwnerUserId":"5884955","Title":null,"Body":"

          Just to add an answer to the title of your question: \"How does one dynamically add new parameters to optimizers in Pytorch?\"<\/p>\n\n

          You can append params at any time to the optimizer:<\/p>\n\n

          import torch\nimport torch.optim as optim\n\nmodel = torch.nn.Linear(2, 2) \n\n# Initialize optimizer\noptimizer = optim.Adam(model.parameters(), lr=0.001, momentum=0.9)\n\nextra_params = torch.randn(2, 2)\noptimizer.param_groups.append({'params': extra_params })\n\n#then you can print your `extra_params`\nprint(\"extra params\", extra_params)\nprint(\"optimizer params\", optimizer.param_groups)\n<\/code><\/pre>\n"},{"AnswerId":"55766749","CreationDate":"2019-04-19T19:14:55.600","ParentId":null,"OwnerUserId":"4385912","Title":null,"Body":"

          \nThat is a tricky question, as I would argue that the answer is \"depends\", in particular on how you want to deal with the optimizer.<\/p>\n\n

          Let's start with your specific problem - an embedding. In particular, you are asking on how to add embeddings to allow for a larger vocabulary dynamically. My first advice is, that if you have a good sense of an upper boundary of your vocabulary size, make the embedding large enough to cope with it from the beginning, as this is more efficient, and as you will need the memory eventually anyway. But this is not what you asked. So - to dynamically change your embedding, you'll need to overwrite your old one with a new one, and inform your optimizer of the change. You can simply do that whenever you run into an exception with your old embedding, in a try ... except<\/code> block. This should roughly follow this idea:<\/p>\n\n

          # from within whichever module owns the embedding\n# remember the already trained weights\nold_embedding_weights = self.embedding.weight.data\n# create a new embedding of the new size\nself.embedding = nn.Embedding(new_vocab_size, embedding_dim)\n# initialize the values for the new embedding. this does random, but you might want to use something like GloVe\nnew_weights = torch.randn(new_vocab_size, embedding_dim)\n# as your old values may have been updated, you want to retrieve these updates values\nnew_weights[:old_vocab_size] = old_embedding_weights\nself.embedding.weights.data.copy_(new_weights)\n<\/code><\/pre>\n\n

          However, you should not do this for every single new word you receive, as this copying takes time (and a whole lot of memory, as the embedding exists twice for a short time - if you're nearly out memory, just make your embedding large enough from the start). So instead increase the size dynamically by a couple of hundred slots at a time.<\/p>\n\n

          Additionally, this first step already raises some questions:<\/p>\n\n

            \n
          1. How does my respective nn.Module<\/code> know about the new embedding parameter? \nThe __setattr__<\/code> method of nn.Module<\/code> takes care of that (see here<\/a>)<\/li>\n
          2. Second, why don't I simply change my parameter? That's already pointing towards some of the problems of changing the optimizer: pytorch internally keeps references by object ID. This means that if you change your object, all these references will point towards a potentially incompatible object, as its properties have changed. So we should simply create a new parameter instead.<\/li>\n
          3. What about other nn.Parameters<\/code> or nn.Modules<\/code> that are not embeddings? These you treat the same. You basically just instantiate them, and attach them to their parent module. The __setattr__<\/code> method will take care of the rest. So you can do so completely dyncamically ...<\/li>\n<\/ol>\n\n

            Except, of course, the optimizer. The optimizer is the only other thing that \"knows\" about your parameters except for your main model-module. So you need to let the optimizer know of any change. <\/p>\n\n

            And this is tricky, if you want to be sophisticated about it, and very easy if you don't care about keeping the optimizer state. However, even if you want to be sophisticated about it, there is a very good reason why you probably should not do this anyways. More about that below.<\/p>\n\n

            Anyways, if you don't care, a simple<\/p>\n\n

            # simply overwrite your old optimizer\noptimizer = optim.SGD(model.parameters(), lr=0.001)\n<\/code><\/pre>\n\n

            will do. If you care, however, you want to transfer your old state, you can do so the same way that you can store, and later load parameters and optimizer states from disk: using the .state_dict()<\/code> and .load_state_dict()<\/code> methods. This, however, does only work with a twist:<\/p>\n\n

            # extract the state dict from your old optimizer\nold_state_dict = optimizer.state_dict()\n# create a new optimizer\noptimizer = optim.SGD(model.parameters())\nnew_state_dict = optimizer.state_dict()\n# the old state dict will have references to the old parameters, in state_dict['param_groups'][xyz]['params'] and in state_dict['state']\n# you now need to find the parameter mismatches between the old and new statedicts\n# if your optimizer has multiple param groups, you need to loop over them, too (I use xyz as a placeholder here. mostly, you'll only have 1 anyways, so just replace xyz with 0\nnew_pars = [p for p in new_state_dict['param_groups'][xyz]['params'] if not p in old_state_dict['param_groups'][xyz]['params']]\nold_pars = [p for p in old_state_dict['param_groups'][xyz]['params'] if not p in new_state_dict['param_groups'][xyz]['params']]\n# then you remove all the outdated ones from the state dict\nfor pid in old_pars:\n    old_state_dict['state'].pop(pid)\n# and add a new state for each new parameter to the state:\nfor pid in new_pars:\n    old_state_dict['param_groups'][xyz]['params'].append(pid)\n    old_state_dict['state'][pid] = { ... }  # your new state def here, depending on your optimizer\n<\/code><\/pre>\n\n

            However, here's the reason why you should probably never<\/em> update your optimizer like this, but should instead re-initialize from scratch, and just accept the loss of state information: When you change your computation graph, you change forward and backward computation for all parameters along your computation path (if you do not have a branching architecture, this path will be your entire graph). This more specifically means, that the input to your functions (=layer\/nn.Module<\/code>) will be different if you change some function (=layer\/nn.Module<\/code>) applied earlier, and the gradients will change if you change some function (=layer\/nn.Module<\/code>) applied later. That in turn invalidates the entire state of your optimizer<\/strong>. So if you keep your optimizer's state around, it will be a state computed for a different computation graph, and will probably end up in catastrophic behavior on part of your optimizer, if you try to apply it to a new computation graph. (I've been there ...)<\/p>\n\n

            So - to sum it up: I'd really recommend to try to keep it simple, and to only change a parameter as conservatively as possible, and not to touch the optimizer.<\/p>\n"}]} +{"QuestionId":55640948,"AnswerCount":0,"Tags":"","CreationDate":"2019-04-11T20:49:32.697","AcceptedAnswerId":null,"OwnerUserId":11131827.0,"Title":"What is the difference between using HDF5Matrix + .fit vs .fit_generator in Keras?","Body":"

            I already know the difference between fit() and fit_generator() in Keras. The former is used when the training data is \"small\" enough to fit into memory, while the latter is used to generate data from a file residing on disk because the training data would be too large to load into memory.<\/p>\n\n

            But another way to handle the problem of large data (saved as .hdf5) is to import your training data using the keras HDF5Matrix as follows:<\/p>\n\n

            from keras.utils.io_utils import HDF5Matrix\n\nX_train = HDF5Matrix('input\/file.hdf5', 'x')\ny_train = HDF5Matrix('input\/file.hdf5', 'y')\n<\/code><\/pre>\n\n

            And then train your model using .fit()<\/p>\n\n

            model.fit(x = X_train, y = y_train)\n<\/code><\/pre>\n\n

            In that case, would there be an advantage for using a fit_generator over the simple .fit() function?<\/p>\n\n

            The only answer I found on the net was here:<\/p>\n\n

            https:\/\/github.com\/keras-team\/keras\/issues\/6298#issuecomment-294586859<\/a><\/p>\n\n

            Thank you<\/p>\n","answers":[]} +{"QuestionId":55641125,"AnswerCount":2,"Tags":"","CreationDate":"2019-04-11T21:02:19.503","AcceptedAnswerId":55757076.0,"OwnerUserId":10597829.0,"Title":"Minimum required hardware component to install tensorflow-gpu in python","Body":"

            I'm tried many PC with different hardware capability to install tensorflow on gpu, they are either un-compatible or compatible but stuck in some point. I would like to know the minimum hardware required to install tensorflow-gpu. And also I would like to ask about some hardware, Is they are allowed or not:\nCan I use core i5 instead of core i7 ??\nIs 4 GB gpu enough for training the dataset??\nIs 8 GB ram enough for training and evaluating the dataset ??\nI'm not good in hardware, can anyone please help me? Thanks.<\/p>\n","answers":[{"AnswerId":"55757076","CreationDate":"2019-04-19T05:34:09.457","ParentId":null,"OwnerUserId":"11127923","Title":null,"Body":"

            TensorFlow (TF) GPU 1.6 and above requires cuda compute capability (ccc) of 3.5 or higher and requires AVX instruction support.
            \n
            https:\/\/www.tensorflow.org\/install\/gpu#hardware_requirements<\/a>.\nhttps:\/\/www.tensorflow.org\/install\/pip#hardware-requirements<\/a>.<\/p>\n\n

            Therefore you would want to buy a graphics card that has ccc above 3.5.\nHere's a link that shows ccc for various nvidia graphic cards https:\/\/developer.nvidia.com\/cuda-gpus<\/a>.<\/p>\n\n

            However if your cuda compute capability is below 3.5 you have to compile TF from sources yourself. This procedure may or may not work depending on the build flags you choose while compiling and is not straightforward.\nIn my humble opinion, The simplest way is to use TF-GPU pre-built binaries to install TF GPU.<\/p>\n\n

            To answer your questions. Yes you can use TF comfortably on i5 with 4gb of graphics card and 8gb ram. The training time may take longer though, depending on task at hand.<\/p>\n\n

            In summary, the main hardware requirement to install TF GPU is getting a Nvidia graphics card with cuda compute capability more than 3.5, more the merrier.\nNote that TF officially supports only NVIDIA graphics card.<\/p>\n"},{"AnswerId":"55642174","CreationDate":"2019-04-11T22:43:32.673","ParentId":null,"OwnerUserId":"3443106","Title":null,"Body":"

            You should find your answers here:<\/p>\n\n

            https:\/\/www.nvidia.com\/en-gb\/data-center\/gpu-accelerated-applications\/tensorflow\/<\/a><\/p>\n\n

            From the link:<\/p>\n\n

            \n

            The GPU-enabled version of TensorFlow has the following requirements:<\/p>\n \n