I am using softmax to get the probability vector from a CNN-MFCC based model. I've started to use the command
model(prediction_feature)
instead of
model.predict(prediction_feature)
as I kept getting warning messages while passing the model.predict command over a loop. However, now when I record the probability, the value gets returned in the form:
tf.Tensor(0.00087791355, shape=(), dtype=float32)
instead for just the number 0.00087791355 when I use the model.predict command.
Is there a way to extract just the number from the model(prediction_feature) approach?
You can convert a tensor to a NumPy array either using numpy.array(tensor) or the tensor.numpy() method.
For example:
import numpy
model(prediction_feature).numpy()
#Or
numpy.array(model(prediction_feature))
However, please let us know the warning messages you get while using model.predict(prediction_feature).
Related
I implemented a custom loss. I want to get the shape of input parameter, like y_true and y_pred. But
whatever I have tried, I can't get a valid shape. The methods I tried including y_true.shape, int_shape(shape), y_true.get_shape returned (None, None).
You know TensorFlow version <= 2.0 does not run eagerly. So when you run the graph you'll get a valid shape. Know the output shape and implement your loss function base on that. tf.shape(tensor) returns a valid shape.
I am trying to understand Pytorch autograd in depth; I would like to observe the gradient of a simple tensor after going through a sigmoid function as below:
import torch
from torch import autograd
D = torch.arange(-8, 8, 0.1, requires_grad=True)
with autograd.set_grad_enabled(True):
S = D.sigmoid()
S.backward()
My goal is to get D.grad() but even before calling it I get the runtime error:
RuntimeError: grad can be implicitly created only for scalar outputs
I see another post with similar question but the answer over there is not applied to my question. Thanks
The error means you can only run .backward (with no arguments) on a unitary/scalar tensor. I.e. a tensor with a single element.
For example, you could do
T = torch.sum(S)
T.backward()
since T would be a scalar output.
I posted some more information on using pytorch to compute derivatives of tensors in this answer.
I'm trying to apply federated learning to an existing keras model that takes two inputs. When I call tff.learning.from_compiled_keras_model and include a dummy batch, I get this error: ValueError: Layer model_1 expects 2 inputs, but it received 1 input tensors. Inputs received: [<tf.Tensor 'packed:0' shape=(2, 20) dtype=int64>].
The model accepts two numpy arrays as inputs, so I defined my dummy_batch as:
x = tf.constant(np.random.randint(1,100, size=[20]))
collections.OrderedDict([('x', [x, x]), ('y', x)])
I dug around a little bit and saw that eventually, tf.convert_to_tensor_or_sparse_tensor gets called on the input list (in the __init__ for _KerasModel), and that returns a single tensor of shape (2,20), instead of two separate arrays or tensors. Is there some other way I can represent the list of inputs to avoid this issue?
The TFF team just pushed a commit that should contain this bugfix; this commit should be what you want. See in particular the change in tensorflow_federated/python/learning/model_utils_test.py--the added test case should have been a repro of your issue, and it now passes.
You were right to call out our call to tf.convert_to_tensor_or_sparse_tensor; now we use tf.nest.map_structure to map this function call to the leaves of the passed-in data structure. Note that Keras does some extra input normalization as well; we decided not to duplicate that logic here.
This change won't be in the pip package until the next release, but if you build from source, it will be available now.
Thanks for this catch, and pointing to the right place!
I am trying to predict() the output for a single data point d, using my trained Keras model loaded from a file. But I get a ValueError If predicting from data tensors, you should specify the 'step' argument. What does that mean?
I tried setting step=1, but then I get a different error ValueError: Cannot feed value of shape () for Tensor u'input_1:0', which has shape '(?, 600)'.
Here is my code:
d = np.concatenate((hidden[p[i]], hidden[x[i]])).resize((1,600))
hidden[p[i]] = autoencoder.predict(d,steps=)
The model is expecting (?,600) as input. I have concatenated two numpy arrays of shape (300,) each to get (600,), which is resized to (1,600). This (1,600) is my input to predict().
In my case, the input to predict was None (because I had a bug in another part of the code).
In official doc, steps refer to the total number of steps before stopping. So steps=1 means make predictions on one batch instead of making prediction on one record (single data point).
https://keras.io/models/sequential/
-> Define value of steps argument,
d = np.concatenate((hidden[p[i]],
hidden[x[i]])).resize((1,600))
hidden[p[i]] = autoencoder.predict(d,steps=1)
If you are using a test data generator, it is good practice to define the steps, as mentioned in the documentation.
If you are predicting a single instance, no need to define the steps. Just make sure the argument (i.e. instance 'd') is not None, otherwise that error will show up. Some reshaping may also be necessary.
in my case i got the same error, i just reshaped the data to predict with numpy function reshape() to the shape of the data originally used to train the model.
XGBClassifier outputs probabilities if we use the method "predict_proba", however, when I train the model using xgboost.train, I cannot figure out how to get probabilities as output. Here is a chunk of my code:
dtrain=xgb.DMatrix(X_train, label=y)
param = {'max_depth':2, 'eta':1, 'silent':1, 'objective':'binary:logistic'}
modelXG=xgb.train(param,dtrain,xgb_model='xgbmodel')
xgboost.train() returns a xgb.Booster object. The xgb.Booster.predict() call returns probabilities in the case of a classification problem instead of the expected labels, if you are used to the .predict()methods of sklearn models. So modelXG.predict(dtest) call will give you want you need.