Keras : history not accessible for loss or accuracy - machine-learning

I am training a CNN in Keras with Tensorflow backend,
mod1=gmodel.fit(images, train_labels,
batch_size=100,
epochs=2,
verbose=1,
validation_data=(test_images, test_labels))
and at every epoch I can see printed in the output the accuracy and loss (until here everything seems ok).
Epoch 1/10
1203/1203 [==============================] - 190s - loss: 0.7600 - acc: 0.5628
- val_loss: 0.5592 - val_acc: 0.6933
Epoch 2/10
1203/1203 [==============================] - 187s - loss: 0.5490 - acc: 0.6933
- val_loss: 0.4589 - val_acc: 0.7930
Epoch 3/10
....
At the end, I want to plot the validation loss so in previous projects I have accessed the validation loss via
mod1.history['val_loss']
but I am getting an error as if .history() was empty.
TypeError Traceback (most recent call last)
<ipython-input-23-ecdd306e9232> in <module>()
----> 1 modl.history()
TypeError: 'History' object is not callable
EDIT (after answer below): When I try to access the loss, for example:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-06fcc6efb374> in <module>()
----> 1 mod1.history['val_loss']
TypeError: 'History' object is not subscriptable
I haven't found anything like this problem before, so I am lost as to what could be happening or how to debug.
Any pointers or ideas are greatly appreciated.

model.fit(x_train, y_train,batch_size=128,validation_data=(x_test, y_test))
vy = model.history.history['val_loss']
ty = model.history.history['loss']
Please use the validation_data in model.fit statement for test data then the only "model.history.history" will come
Reference:
https://keras.io/callbacks/

Although you say you have called mod1.history['val_loss'], your error message tells a different story - most probably, as Daniel Moller has already commented, you have in fact used something like mod1.history() (i.e. with parentheses). Here is what I get (Python 3.5):
mod1.history()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-67bafe3187cc> in <module>()
----> 1 mod1.history()
TypeError: 'dict' object is not callable
mod1.history is not a function to be called with (), but a Python dictionary:
mod1.history
# result:
{'acc': [0.82374999999999998,
0.94294999999999995,
0.95861666666666667,
...],
'loss': [0.62551526172161098,
0.18810810926556587,
0.13734668906728426,
...],
'val_loss': [12.05395287322998,
11.584557554626464,
10.949809835815429,
...]}
mod1.history['val_loss']
# result:
[12.05395287322998,
11.584557554626464,
10.949809835815429,
...]

When model is fitted it will return a history object, you cannot call() or subscript it directly like history['loss'].
If you fitted it using model.fit() then you have to query as follows
model.history.history.keys() -> will give you ['acc','loss','val_acc','val_loss']
If you monitored loss and mentioned metrics as accuracy during compile process.
You can access all metrics using same format ,for ex :model.history.history['acc']
But if you fitted a model and assigned history object to a local variable like this history = model.fit(X, Y) then the mode of access would be
history.history['acc']
history.history['val_acc']
Here we don't need to mention model object as history object is now saved in a local variable.
And also don't forget to add validation data or use validation split parameter of fit to access the validation metrics.

Try this, it will definitely work.
Epoches = 30
Validation = (x_valid,y_valid)
model_clf.fit(x_train,y_train,epochs=Epoches, validation_data=Validation, batch_size=20 )
model_clf.history.params
model_clf.history.history
#### convert into datafarame
pd.DataFrame(model_clf.history.history)
#### if u want to draw the graph
pd.DataFrame(model_clf.history.history).plot(figsize=(15,7))
plt.grid(True)
plt.show()

Related

PyTorch Detecto Model: tensor incompatibiliy in predicition for a pretrained model

Trying to train a very simple model and do a
image-prediction with the following code
for pytorch detecto:
from detecto import core, utils, visualize
dataset = core.Dataset('images/')
model = core.Model(['rect'])
model.fit(dataset)
modelName = 'model_weights_simpleRect.pth'
model.save(modelName)
image = utils.read_image('simple_image_to_test.jpg')
predictions = model.predict(image)
This leads to the following output:
Epoch 1 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:12<00:00, 1.56it/s]
Epoch 2 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.80it/s]
Epoch 3 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.80it/s]
Epoch 4 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.79it/s]
Epoch 5 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.79it/s]
Epoch 6 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.80it/s]
Epoch 7 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.78it/s]
Epoch 8 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.80it/s]
Epoch 9 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.78it/s]
Epoch 10 of 10
Begin iterating over training dataset
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:11<00:00, 1.80it/s]
Traceback (most recent call last):
File "train_simpleRect_and_predict.py", line 15, in <module>
predictions = model.predict(image)
File "/home/std/anaconda3/envs/dri/lib/python3.7/site-packages/detecto/core.py", line 338, in predict
preds = self._get_raw_predictions(images)
File "/home/std/anaconda3/envs/dri/lib/python3.7/site-packages/detecto/core.py", line 294, in _get_raw_predictions
preds = self._model(images)
File "/home/std/anaconda3/envs/dri/lib/python3.7/site-packages/torch/nn/modules/module.py", line 541, in __call__
result = self.forward(*input, **kwargs)
File "/home/std/anaconda3/envs/dri/lib/python3.7/site-packages/torchvision/models/detection/generalized_rcnn.py", line 52, in forward
detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)
File "/home/std/anaconda3/envs/dri/lib/python3.7/site-packages/torch/nn/modules/module.py", line 541, in __call__
result = self.forward(*input, **kwargs)
File "/home/std/anaconda3/envs/dri/lib/python3.7/site-packages/torchvision/models/detection/roi_heads.py", line 550, in forward
boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals, image_shapes)
File "/home/std/anaconda3/envs/dri/lib/python3.7/site-packages/torchvision/models/detection/roi_heads.py", line 474, in postprocess_detections
pred_boxes = self.box_coder.decode(box_regression, proposals)
File "/home/std/anaconda3/envs/dri/lib/python3.7/site-packages/torchvision/models/detection/_utils.py", line 168, in decode
rel_codes.reshape(sum(boxes_per_image), -1), concat_boxes
RuntimeError: cannot reshape tensor of 0 elements into shape [0, -1] because the unspecified dimension size -1 can be any value and is ambiguous
How can I get more detailled information about the model dimension, where exactly
in the model the tensor incompatibilies occur and how to fix it?
Add. info: I used the same code with other data and it worked.
Thank you!
Another problem - which brought up a similar tensor-dimension error, was caused by this statement:
model = Model.load(modelName, ['rect'])
The correct version is:
model = Model()
model.load(modelName, ['rect'])
The problem were wrong image dimensions in the
xml-description files, which corresponded to each image.
I fixed the xml-files and the error did not occur again.

TypeError: __call__() takes 2 positional arguments but 3 were given. To train Raccoon prediction model using FastRCNN through Transfer Learning

from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from engine import train_one_epoch, evaluate
import utils
import torchvision.transforms as T
num_epochs = 10
for epoch in range(num_epochs):
train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)
lr_scheduler.step()
evaluate(model, data_loader_test, device=device)
I am using the same code as provided in this link Building Raccoon Model but mine is not working.
This is the error message I am getting
TypeError Traceback (most recent call last)
in ()
2 for epoch in range(num_epochs):
3 # train for one epoch, printing every 10 iterations
4 ----> train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)
5 # update the learning rate
6 lr_scheduler.step()
7 frames
in getitem(self, idx)
29 target["iscrowd"] = iscrowd
30 if self.transforms is not None:
31 ---> img, target = self.transforms(img, target)
32 return img, target
33
TypeError: call() takes 2 positional arguments but 3 were given
The above answer is incorrect, I accidentally upvoted before noticing. You are using the wrong Compose, note that it says
https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html#putting-everything-together
"In references/detection/, we have a number of helper functions to simplify training and evaluating detection models. Here, we will use references/detection/engine.py, references/detection/utils.py and references/detection/transforms.py. Just copy them to your folder and use them here."
there are helper scripts. They subclass the compose and flip methods
https://github.com/pytorch/vision/blob/6315358dd06e3a2bcbe9c1e8cdaa10898ac2b308/references/detection/transforms.py#L17
I did the same thing before noticing this. Do not use the compose method from torchvision.transforms, or else you will get the error above. Download their module and load it.
I am kind of a newbie at this and I was also having the same problem.
Upon doing more research, I found this where the accepted answer used:
img = self.transforms(img)
instead of:
img, target = self.transforms(img, target)
Removing "target" solved the error for me and should solve it for you as well. Not entirely sure why even the official PyTorch tutorial also has "target" included but it does not work for us.
I had the same issue, there is even an issue raised on Pytorch discussion forum using regarding the same T.Compose | TypeError: call() takes 2 positional arguments but 3 were given
I was able to overcome this issue by copy and pasting the files on the for a specific version v0.3.0 on the vision/reference/detection of the tutorial I am following building-your-own-object-detector-pytorch-vs-tensorflow-and-how-to-even-get-started
Just to fall into another issue I have raised here ValueError: All bounding boxes should have positive height and width. Found invaid box [500.728515625, 533.3333129882812, 231.10546875, 255.2083282470703] for target at index 0. #2740

no error while fitting the model over train data but NotFittedError while predicting over test set

Not fitted error coming up when using .predict,during fit there is no error
tried to convert dataframe into arrays still same error
Input:
rfg(n_estimators=500,random_state=42).fit(X=data_withoutnull1.iloc[:,1:8],y=data_withoutnull1['LotFrontage'])
rfg(n_estimators=500,random_state=42).predict(datawithnull1.iloc[:,1:8])
Output:
Traceback (most recent call last):
File "<ipython-input-477-10c6d72bcc12>", line 2, in <module>
rfg(n_estimators=500,random_state=42).predict(datawithnull1.iloc[:,1:8])
File "/home/sinikoibra/miniconda3/envs/pv36/lib/python3.6/site-packages/sklearn/ensemble/forest.py", line 691, in predict
check_is_fitted(self, 'estimators_')
File "/home/sinikoibra/miniconda3/envs/pv36/lib/python3.6/site-packages/sklearn/utils/validation.py", line 914, in check_is_fitted
raise NotFittedError(msg % {'name': type(estimator).__name__})
NotFittedError: This RandomForestRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
Try like this :
# Define X and y
X=data_withoutnull1.iloc[:,1:8].values
y=data_withoutnull1['LotFrontage']
You can use train test split to split the data into training set and testing set then pass the testing set into predict.
#pass X_train to fit -- training the model, fit(X_train)
#pass X_test to predict -- can be used for prediction, predict(X_test )
or Fitting Random Forest Regression to the dataset
from sklearn.ensemble import RandomForestRegressor
rfg= RandomForestRegressor(n_estimators = 500, random_state = 42)
rfg.fit(X, y)
# Predicting a new result
y_pred = rfg.predict([[some value here]] or testing set or dataset to be predicted)

Unsupervised loss function in Keras

Is there any way in Keras to specify a loss function which does not need to be passed target data?
I attempted to specify a loss function which omitted the y_true parameter like so:
def custom_loss(y_pred):
But I got the following error:
Traceback (most recent call last):
File "siamese.py", line 234, in <module>
model.compile(loss=custom_loss,optimizer=Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0))
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 911, in compile
sample_weight, mask)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 436, in weighted
score_array = fn(y_true, y_pred)
TypeError: custom_loss() takes exactly 1 argument (2 given)
I then tried to call fit() without specifying any target data:
model.fit(x=[x_train,x_train_warped, affines], batch_size = bs, epochs=1)
But it looks like not passing any target data causes an error:
Traceback (most recent call last):
File "siamese.py", line 264, in <module>
model.fit(x=[x_train,x_train_warped, affines], batch_size = bs, epochs=1)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1435, in fit
batch_size=batch_size)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1322, in _standardize_user_data
in zip(y, sample_weights, class_weights, self._feed_sample_weight_modes)]
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 577, in _standardize_weights
return np.ones((y.shape[0],), dtype=K.floatx())
AttributeError: 'NoneType' object has no attribute 'shape'
I could manually create dummy data in the same shape as my neural net's output but this seems extremely messy. Is there a simple way to specify an unsupervised loss function in Keras that I am missing?
I think the best solution is customizing the training instead of using the model.fit method.
The complete walkthrough is published in the Tensorflow tutorials page.
Write your loss function as if it had two arguments:
y_true
y_pred
If you don't have y_true, that's fine, you don't need to use it inside to compute the loss, but leave a placeholder in your function prototype, so keras wouldn't complain.
def custom_loss(y_true, y_pred):
# do things with y_pred
return loss
Adding custom arguments
You may also need to use another parameter like margin inside your loss function, even then your custom function should only take in those two arguments. But there is a workaround, use lambda functions
def custom_loss(y_pred, margin):
# do things with y_pred
return loss
but use it like
model.compile(loss=lambda y_true, y_pred: custom_loss(y_pred, margin), ...)

Difference between Tensorflow and Scikitlearn log_loss function implementation

Hi I am trying to get into tensorflow and feeling a bit dumb.
Does log_loss in TF differ from sklearn's one?
Here are some lines from my code, how I am calculating:
from sklearn.metrics import log_loss
tmp = np.array(y_test)
y_test_t = np.array([tmp, -(tmp-1)]).T[0]
tf_log_loss = tf.losses.log_loss(predictions=tf.nn.softmax(logits), labels=tf_y)
with tf.Session() as sess:
# training
a = sess.run(tf.nn.softmax(logits), feed_dict={tf_x: xtest, keep_prob: 1.})
print(" sk.log_loss: ", log_loss(y_test, a,eps=1e-7 ))
print(" tf.log_loss: ", sess.run(tf_log_loss, feed_dict={tf_x: xtest, tf_y: y_test_t, keep_prob: 1.}))
Output I get
Epoch 7, Loss: 0.4875 Validation Accuracy: 0.818981
sk.log_loss: 1.76533018874
tf.log_loss: 0.396557
Epoch 8, Loss: 0.4850 Validation Accuracy: 0.820738
sk.log_loss: 1.77217639627
tf.log_loss: 0.393351
Epoch 9, Loss: 0.4835 Validation Accuracy: 0.823374
sk.log_loss: 1.78479079656
tf.log_loss: 0.390572
Seems like while tf.log_loss converges sk.log_loss diverges.
I had the same problem. After looking up the source code of tf.losses.log_loss, its key lines show wat is going on:
losses = - math_ops.multiply(labels, math_ops.log(predictions + epsilon))
- math_ops.multiply((1 - labels), math_ops.log(1 - predictions + epsilon))
It is binary log-loss (i.e. every class is considered non-exclusive) rather than multi-class log-loss.
As I worked with probabilities (rather than logits), I couldn't use tf.nn.softmax_cross_entropy_with_logits (though, I could have applied logarithm).
My solution was to implement log-loss by hand:
loss = tf.reduce_sum(tf.multiply(- labels, tf.log(probs))) / len(probs)
See also:
https://github.com/tensorflow/tensorflow/issues/2462
difference between tensorflow tf.nn.softmax and tf.nn.softmax_cross_entropy_with_logits

Resources