Questions tagged [tf.keras]
[tf.keras] is TensorFlow's implementation of the Keras API specification. Use the tag for questions specific to this TensorFlow module. You might also add the tag [keras] to your question since it has the same API.
tf.keras
2,189
questions
8
votes
3
answers
7k
views
Keras Model AttributeError: 'str' object has no attribute 'call'
I'm trying to convert my Keras hdf5 file into a TensorFlow Lite file with the following code:
import tensorflow as tf
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model("/...
8
votes
2
answers
9k
views
How to correctly use the Tensorflow MeanIOU metric?
I want to use the MeanIoU metric in keras (doc link). But I don't really understand how it could be integrated with the keras api. In the example, the prediction and the ground truth are given as ...
8
votes
2
answers
23k
views
TensorFlow 2.0 How to get trainable variables from tf.keras.layers layers, like Conv2D or Dense
I have been trying to get the trainable variables from my layers and can't figure out a way to make it work. So here is what I have tried:
I have tried accessing the kernel and bias attribute of the ...
8
votes
2
answers
10k
views
Unable to import Keras(from TensorFlow 2.0) in PyCharm 2019.2
I have just installed the stable version of TensorFlow 2.0 (released on October 1st 2019) in PyCharm.
The problem is that the keras package is unavailable.
The actual error is :
"cannot import ...
8
votes
1
answer
11k
views
SHAP DeepExplainer with TensorFlow 2.4+ error
I'm trying to compute shap values using DeepExplainer, but I get the following error:
keras is no longer supported, please use tf.keras instead
Even though i'm using tf.keras?
KeyError ...
8
votes
1
answer
3k
views
Can SigmoidFocalCrossEntropy in Tensorflow (tf-addons) be used in Multiclass Classification? ( What is the right way)?
Focal Loss given in Tensorflow is used for class imbalance. For Binary class classification, there are a lots of codes available but for Multiclass classification, a very little help is there. I ran ...
8
votes
1
answer
16k
views
Tensorflow model.fit() using a Dataset generator
I am using the Dataset API to generate training data and sort it into batches for a NN.
Here is a minimum working example of my code:
import tensorflow as tf
import numpy as np
import random
def ...
8
votes
1
answer
6k
views
Tensorflow Keras RMSE metric returns different results than my own built RMSE loss function
This is a regression problem
My custom RMSE loss:
def root_mean_squared_error_loss(y_true, y_pred):
return tf.keras.backend.sqrt(tf.keras.losses.MSE(y_true, y_pred))
Training code sample, ...
8
votes
2
answers
4k
views
What is the difference between conv1d with kernel_size=1 and dense layer?
I am building a CNN with Conv1D layers, and it trains pretty well. I'm now looking into how to reduce the number of features before feeding it into a Dense layer at the end of the model, so I've been ...
8
votes
3
answers
23k
views
Cannot use keras models on Mac M1 with BigSur
I am trying to use Sequential model from keras of tensorflow. When I am executing following statement:
model.fit(x_train, y_train, epochs=20, verbose=True, validation_data=(x_dev, y_dev), batch_size=...
8
votes
1
answer
9k
views
Dictionary of tensors input for Keras Functional API TensorFlow 2.0
I have a dataset of dictionary of tensors, and the following model defined using the subclassing API:
class Model(tf.keras.Model):
def __init__(self):
super().__init__()
self....
8
votes
1
answer
15k
views
AttributeError: The layer has never been called and thus has no defined input shape
I'm tring to build an autoencoder in TensorFlow 2.0 by creating three classes: Encoder, Decoder and AutoEncoder.
Since I don't want to manually set input shapes I'm trying to infer the output shape of ...
8
votes
1
answer
3k
views
Should I use the standalone Keras library or tf.keras?
As Keras becomes an API for TensorFlow, there are lots of old versions of Keras code, such as https://github.com/keiserlab/keras-neural-graph-fingerprint/blob/master/examples.py
from keras import ...
8
votes
2
answers
5k
views
Does tf.keras.metrics.AUC work on multi-class problems?
I have a multi-class classification problem and I want to measure AUC on training and test data.
tf.keras has implemented AUC metric (tf.keras.metrics.AUC), but I'm not be able to see whether this ...
8
votes
1
answer
2k
views
Saving and loading multiple models with the same graph in TensorFlow Functional API
In the TensorFlow Functional API guide, there's an example shown where multiple models are created using the same graph of layers. (https://www.tensorflow.org/beta/guide/keras/functional#...
8
votes
1
answer
744
views
TF2.1: SegNet model architecture problem. Bug with metric calculation, keeps constant and converge to determined value
I'm building a custom model (SegNet) in Tensorflow 2.1.0.
The first problem I'm facing is the reutilization of the indices of the max pooling operation needed as described in the paper.
Basically, ...
8
votes
0
answers
788
views
Call Model.fit with tensors / Executing op on CPU not GPU / Tensorflow 2.1
I am experimenting with reinforcement learning in python. I am using Tensorflow 2.1 and my machine has muyliple GPUs (with CUDA 10.2 driver 440.59). I am allocating the operations on my GPUs using tf....
7
votes
1
answer
17k
views
ValueError: No gradients provided for any variable - Tensorflow 2.0/Keras
I am trying to implement a simple sequence-to-sequence model using Keras. However, I keep seeing the following ValueError:
ValueError: No gradients provided for any variable: ['simple_model/...
7
votes
4
answers
3k
views
Keras - no good way to stop and resume training?
After a lot of research, it seems like there is no good way to properly stop and resume training using a Tensorflow 2 / Keras model. This is true whether you are using model.fit() or using a custom ...
7
votes
4
answers
7k
views
The clear_session() method of keras.backend does not clean up the fitting data
I am working on a comparison of the fitting accuracy results for the different types of data quality. A "good data" is the data without any NA in the feature values. A "bad data" is the data with NA ...
7
votes
1
answer
5k
views
tf.nn.relu vs tf.keras.activations.relu [closed]
I see both tf.nn.relu and tf.keras.activations.relu computes only the ReLU function (no additional fully connected layer or something, as described here), so what's the difference between them? Does ...
7
votes
1
answer
8k
views
What is the difference between input_shape and input_dim in keras?
Currently i am learning deep learning and stumbled upon these confusion:
when to use input_shape and input_dim parameter.
shape of my data is (798,9) and these has 8 input variable and 1 output ...
7
votes
2
answers
7k
views
Keras callback AttributeError: 'ModelCheckpoint' object has no attribute '_implements_train_batch_hooks'
I'm using Keras (with TensorFlow back-end) to implement a neural network and want to only save the model that minimises loss on the validation set during training. To do this, I instantiated a ...
7
votes
3
answers
7k
views
Using tf.keras.utils.Sequence with model.fit_generator with use_multiprocessing=True generated warning
This is the warning I got:
WARNING:tensorflow:multiprocessing can interact badly with TensorFlow, causing nondeterministic deadlocks. For high performance data pipelines tf.data is recommended.
The ...
7
votes
1
answer
1k
views
Redundancies in tf.keras.backend and tensorflow libraries
I have been working in TensorFlow for about a year now, and I am transitioning from TF 1.x to TF 2.0, and I am looking for some guidance on how to use the tf.keras.backend library in TF 2.0. I ...
7
votes
1
answer
1k
views
Do the number of units in a layer need to be defined within a conditional scope when using keras tuner to setup a model?
According to the Keras Tuner examples here and here, if you want to define the number of layers and each layer's units in a deep learning model using hyper parameters you do something like this:
for i ...
7
votes
6
answers
2k
views
pipenv - Pipfile.lock is not being generated due to the 'Could not find a version that matches keras-nightly~=2.5.0.dev' error
As the title clearly describes the issue I've been experiencing, no Pipfile.lock is being generated as I get the following error when I execute the recommended command pipenv lock --clear:
ERROR: ...
7
votes
2
answers
1k
views
In Keras, is there any function similar to the zero_grad() in Pytorch?
In Pytorch, we can call zero_grad() to clear the gradients. In Keras, do we have a similar function so that we can achieve the same thing? For example, I want to accumulate gradients among some ...
7
votes
2
answers
3k
views
Weighting samples in multiclass image segmentation using keras
I am using a Unet based model to perform image segmentation on a biomedical image. Each image is 224x224 and I have four classes including the background class. Each mask is sized as (224x224x4) and ...
7
votes
1
answer
21k
views
Unable to train my keras model : (Data cardinality is ambiguous:)
I am using the bert-for-tf2 library to do a Multi-Class Classification problem. I created the model but training throws the following error:
-----------------------------------------------------------...
7
votes
1
answer
3k
views
How to fit and evaluate tf.data.dataset with tf.keras at the end of every epoch?
When x is tf.data dataset, a tuple of (inputs, targets) and inputs is a dict of features like {"fea_1": val_1, "fea_2": val_2…}, model.fit function in tensorflow/python/keras/engine/training.py doesn'...
7
votes
1
answer
1k
views
Loading file from path contained in tf.Tensor
I build a simple model using tf.keras and a tf.data.Dataset for efficient loading as the dataset is a couple of GBs big.
The images are in tiff format and therefore need to be loaded directly as numpy....
7
votes
1
answer
2k
views
How do sessions and parallelism work in TF2.0?
I am trying to run two tensorflow models in parallel in the same process.
In Tensorflow 1.x we could do e.g. Keras Tensorflow - Exception while predicting from multiple threads
graph = tf.Graph()
...
7
votes
0
answers
1k
views
Entity Embedding of Categorical within Time Series Data and LSTM
I'm trying to solve a time series problem. In short, for each customer and material (SKU code), I have different orders placed in the past. I need to build a model that predict the number of days ...
7
votes
0
answers
3k
views
Tensorflow Keras model.summary() shows 0 trainable parameters on a layer
I'm training a LSTM variant, PhasedLSTM, for regression. I'm using tensorflow.contrib.rnn.PhasedLSTMCell which expects a vector of timestamps in addition to the features. Here's my model definition :
...
6
votes
3
answers
17k
views
ValueError: Expect x to be a non-empty array or dataset (Tensor Flow lite model maker on Collab)
I am following this tutorial on creating a custom Model using TensorFlow lite Model Maker on Collab.
import pathlib
path = pathlib.Path('/content/employee_pics')
count = len(list(path.glob('*/*.jpg'))...
6
votes
1
answer
6k
views
keras.load_model() can't recognize Tensorflow's activation functions
I saved a tf.keras model using tf.keras.save_model functions.
why tf.keras.load_model throws an exception?
code example:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras ...
6
votes
1
answer
7k
views
How to set dynamic memory growth on TF 2.1?
With previous versions of tensorflow+keras I was able to set an 'allow_growth' option and view realtime memory usage with nvidia-smi. Otherwise it will all gett allocated immediately by the process. ...
6
votes
2
answers
17k
views
tf.keras.preprocessing.image_dataset_from_directory Value Error: No images found
belos is my code to ensure that the folder has images, but tf.keras.preprocessing.image_dataset_from_directory returns no images found. What did I do wrong? Thanks.
DATASET_PATH = pathlib.Path('C:\\...
6
votes
3
answers
5k
views
Keras-tuner search function throws Failed to create a NewWriteableFile error
The relatively new keras-tuner module for tensorflow-2 is causing the error 'Failed to create a NewWriteableFile'. The tuner.search function is working, it is only after the trial completes that the ...
6
votes
2
answers
6k
views
Why am I receive AlreadyExistsError?
When I train my binary classification via keras I received this error:
AlreadyExistsError: Resource __per_step_16/training_4/Adam/gradients/lstm_10/while/ReadVariableOp_8/Enter_grad/...
6
votes
6
answers
5k
views
Reload Keras-Tuner Trials from the directory
I'm trying to reload or access the Keras-Tuner Trials after the Tuner's search has completed for inspecting the results. I'm not able to find any documentation or answers related to this issue.
For ...
6
votes
2
answers
3k
views
tf.keras.metrics.MeanIoU with sigmoid layer
I have a network for semantic segmentation and the last layer of my model applies a sigmoid activation, so all predictions are scaled between 0-1. There is this validation metric tf.keras.metrics....
6
votes
2
answers
7k
views
CancelledError: [_Derived_]RecvAsync is cancelled
I am having an issue. I run the same code on my local machine with CPU and Tensorflow 1.14.0. It works fine. However, when I run it on GPU with Tensorflow 2.0, I get
CancelledError: [_Derived_]...
6
votes
2
answers
1k
views
How to skip problematic hyperparameter combinations when tuning models using Keras Tuner?
When using Keras Tuner, there doesn't seem to be a way to allow the skipping of a problematic combination of hyperparams. For example, the number of filters in a Conv1D layer may not be compatible ...
6
votes
2
answers
9k
views
List of metrics that can be passed to tf.keras.model.compile
Based on the tensorflow documentation, when compiling a model, I can specify one or more metrics to use, such as 'accuracy' and 'mse'. However, the documentation doesn't say what metrics are ...
6
votes
1
answer
7k
views
How to substitute `keras.layers.merge._Merge` in `tensorflow.keras`
I want to create a custom Merge layer using the tf.keras API. However, the new API hides the keras.layers.merge._Merge class that I want to inherit from.
The purpose of this is to create a Layer that ...
6
votes
1
answer
7k
views
Why does Keras gives me different results between model.evaluate, model.predicts & model.fit?
I'm working on a project with a resnet50 based dual output model. One output is for the regression task and the second output is for a classification task.
My main question is about the model ...
6
votes
2
answers
6k
views
'NoneType' object is not subscriptable - error at Keras custom callback class
I am getting this error when I am defining a custom callback function.
'NoneType' object is not subscriptable
Code sample
class Metrics(tf.keras.callbacks.Callback):
def on_train_begin(self, ...
6
votes
1
answer
2k
views
WARNING:tensorflow:`write_grads` will be ignored in TensorFlow 2.0 for the `TensorBoard` Callback
I am using the following lines of codes to visualise the gradients of an ANN model using tensorboard
tensorboard_callback = tf.compat.v1.keras.callbacks.TensorBoard(log_dir='./Graph', histogram_freq=...