id
stringlengths
3
8
text
stringlengths
1
115k
st205900
tf.contrib Is not supported anymore. Please use: TensorFlow tf.keras.layers.Flatten  |  TensorFlow Core v2.5.0 Flattens the input. Does not affect the batch size.
st205901
Hi everyone! I woul like to run a Mobile Net on an embedded system (Coral USB Accelerator) to analyze audio recordings that I convert into spectrograms. I have implemented the model according to the Mobile Net paper 16 in Tensorflow. def SeparableConv(x, num_filters, strides, alpha=1.0): x = tf.keras.layers.DepthwiseConv2D(kernel_size=3, padding='same')(x) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(np.floor( num_filters * alpha), kernel_size=(1, 1), strides=strides, use_bias=False, padding='same')(x) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.ReLU()(x) return x def Conv(x, num_filters, kernel_size, strides=1, alpha=1.0): x = tf.keras.layers.Conv2D((np.floor( num_filters * alpha)), kernel_size=kernel_size, strides=strides, use_bias=False , padding='same')(x) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation('relu')(x) x = tf.keras.layers.ReLU()(x) return x inputs = tf.keras.layers.Input(shape=(64, 64, 1)) x = Conv(inputs, num_filters=16, kernel_size=3 , strides=2) x = SeparableConv(x, num_filters=32, strides=1) x = SeparableConv(x, num_filters=64, strides=2) x = SeparableConv(x, num_filters=64, strides=1) x = SeparableConv(x, num_filters=128, strides=2) x = SeparableConv(x, num_filters=128, strides=1) x = SeparableConv(x, num_filters=256, strides=1) x = SeparableConv(x, num_filters=256, strides=2) x = SeparableConv(x, num_filters=256, strides=1) x = SeparableConv(x, num_filters=256, strides=1) x = SeparableConv(x, num_filters=256, strides=1) x = SeparableConv(x, num_filters=256, strides=1) x = SeparableConv(x, num_filters=512, strides=2) x = SeparableConv(x, num_filters=512, strides=1) x = tf.keras.layers.GlobalAveragePooling2D()(x) x = tf.keras.layers.Dense(512)(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dropout(0.001)(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(2)(x) outputs = tf.keras.layers.ReLU()(x) model = tf.keras.models.Model(inputs, outputs) To run it on the Coral USB Accelerator I need to quantize it and convert it to a TensorFlow Lite model (and then compile it again with the Edge TPU compiler). But the prediction is massively worse after quantizing from 32bit float to 8bit int. The problem seems to be the batch normalization keras.layers.BatchNormalization() 2. This is not an instruction that is allowed in TensorFlow lite. But since Mobile Net was designed specifically for embedded systems and Batch Normalization is a fundamental part of it I can’t imagine that this is not possible on the Edge TPU. So I wanted to ask if anyone knows a workaround to get Mobile Net, specifically Batch Normalization working on the Coral USB Accelerator? Many thanks for your help and advice in advance!
st205902
Hi @Olivier_Staehli Why do you say that the problem is with Batch normalization? Have you tried without it? Have you tried the model without integer quantization to check it?
st205903
Hi @George_Soloupis, Thanks for your questions. I have tried without it but the results did not made sense since Batch normalization seems to be a crucial part of mobile net. However, I have built a network with only a few layers and checked each part of mobile net separately. There, I figured out that batch normalization is the issue (also GlobalAveragePooling() causes the result to be less accurate but it is not very significant and can be replaced by MaxPooling). The results of the non-quantized TensorFlow Lite model are the same as the TensorFlow model. Therefore, I concluded that it must be BatchNormalization in the integer quantization step.
st205904
Nice!! It seems that you have tried a lot! I will search myself for this particular issue when BatchNormalization is used during full integer quantization. In the meantime I will tag also @Sayak_Paul and hope that he has done full integer quantization to models that contain BatchNormalization to shed some light. I think though that for this particular issue you have to provide a notebook to check the structure and the representative dataset that is used.
st205905
I would try with an increased representative dataset. Also, when you are using the integer quantized model, it’s important to account for the scale and offset as shown here: TensorFlow Post-training integer quantization  |  TensorFlow Lite 8 BatchNormalization should not be an issue here. Olivier_Staehli: To run it on the Coral USB Accelerator I need to quantize it and convert it to a TensorFlow Lite model (and then compile it again with the Edge TPU compiler). But the prediction is massively worse after quantizing from 32bit float to 8bit int. The problem seems to be the batch normalization keras.layers.BatchNormalization(). Batch Normalization is well-supported actually. Refer here: TensorFlow TensorFlow Lite and TensorFlow operator compatibility 10 Also, please try with the most stable version of the libraries that you are using.
st205906
Thanks a lot for your support! Here is a link to the Jupyter Notebook (This is my first ML project, so it might be possible that I made a beginner mistake somewhere) This is the training and validation data set
st205907
Many thanks @Sayak_Paul ! The representative dataset seems to be the issue! I just use this method: def representative_data_gen(): for input_value in tf.data.Dataset.from_tensor_slices(test_audio).batch(1).take(250): yield [input_value] When I change the values e.g. from 100 to 250 the predictions change drastically (for the worse). Is there any method or formula to figure out how large the representative dataset should be? I also tried quantization-aware training and could not get a better result. Therefore I thought it cannot be something in the actual quantization process. But I was wrong with that assumption.
st205908
If quantization-aware is giving you worse results then I suspect there’s something definitely wrong in your data input pipeline. I would investigate the data preprocessing functions really carefully and would also investigate their descriptive statistics. Is test_audio preprocessed 'cause the TFLiteConverter would expect it is. It’s a different story if your model consists the preprocessing layers inside of it already. Olivier_Staehli: Is there any method or formula to figure out how large the representative dataset should be? It is really dependent on the dataset and the problem you are using. Also, how much quality you can afford to lose. In my experience, a sample size of 100 - 1000 usually works. Therefore, I would recommend plotting a graph of Representative Dataset Size vs. Model Performance and pick one from there. Lastly, I would come back to this suggestion: Sayak_Paul: Also, when you are using the integer quantized model, it’s important to account for the scale and offset as shown here:
st205909
Hey everyone! i’ve majorly worked with PyTorch and lately I’ve found myself working with libraries based on Tensorflow. I wish to ask how can i convert saved TF model to pytorch models?
st205910
Hello folks, I have got an AMD GPU on my system and I want to use it for model training. After several efforts I have not been able to do so. Since CUDA is only supported on NVIDIA GPU, it doesn’t work for me. Any suggestions? Thank you.
st205911
Rohan_Raj: I have got an AMD GPU on my system and I want to use it for model training. After several efforts I have not been able to do so. Since CUDA is only supported on NVIDIA GPU, it doesn’t work for me. Any suggestions? Thank you. CUDA is Nvidia proprietary technology, for AMD GPUs you have OpenCL
st205912
@Remy_Wehrung Is OpenGL supported with Tensorflow. If I sit for the TensorFlow certification exam then would it cause any issue?
st205913
you are confusing OpenGL, 3D display technology created by the late Silicon Graphics and OpenCL, open source data processing middleware, it has nothing to do with it, see the sites talking about OpenCL
st205914
@Remy_Wehrung sorry there was typo with openGL. Can OPEN CL be used while giving the Tensorflow certification exam?
st205915
Rohan_Raj: Can OPEN CL be used while giving the Tensorflow certification exam? No, for this certification you need to know the Tensorflow API, Python basics and Linux administration basics, that’s all. Open CL is only useful if you are familiar with C ++. but it is irrelevant for the certification
st205916
You need to use TF AMD ROCm github.com ROCmSoftwarePlatform/tensorflow-upstream - Tensorflow ROCm port 241 TensorFlow ROCm port. Contribute to ROCmSoftwarePlatform/tensorflow-upstream development by creating an account on GitHub.
st205917
Tensorflow-directml for windows github / microsoft / tensorflow-directml (cannot include links) can be used with any DirectX 12 compatible video card. In my tests on 2080Ti it is only ~68% slower than cuda version
st205918
Directx has nothing to do with ML, so that the Microsoft fork (by the way?) Is slower does not surprise me. We are talking about libraries written in python, it is universal as a language.
st205919
DirectML is young tech. GPU vendors should optimize their drivers for DirectML . But at least you can run tf graph models on amd gpu right now. Also inference on tensorflow-DirectML is only ~30% slower.
st205920
For Directml the RFC is still in WIP see the last messages in github.com/tensorflow/community RFC: TensorFlow on DirectML 18 tensorflow:master ← wchao1115:master opened May 12, 2020 wchao1115 +105 -0 This RFC will be open for comment until Monday, May 25th, 2020. | Status … | Proposed | :-------------- |:---------------------------------------------------- | | **RFC #** | [243](https://github.com/tensorflow/community/pull/243) | | **Author(s)** | Chai Chaoweeraprasit ([email protected]), Justin Stoecker ([email protected]), Adrian Tsai ([email protected]), Patrice Vignola ([email protected]) | | **Sponsor** | Penporn Koanantakool ([email protected]) | | **Updated** | 2020-06-08 | ## Objective Implement a new TensorFlow device type and a new set of kernels based on [DirectML](https://docs.microsoft.com/en-us/windows/win32/direct3d12/dml-intro), a hardware-accelerated machine learning library on the DirectX 12 Compute platform. This change broadens the reach of TensorFlow beyond its existing GPU footprint and enables high-performance training and inferencing on Windows devices with any DirectX12-capable GPU. /Cc @penporn Currently I still suggest to use the mentioned ROCM wheel on AMD GPUS
st205921
Bhack: For Directml the RFC is still in WIP see the last messages in I already use tf-directml in production. DeepFaceLab has DX12 build to train deepfakes on amd gpus. All works like a charm .
st205922
TF 1.x is practically EOL and TF directml is still waiting for: github.com/microsoft/tensorflow-directml Tensorflow 2 support (?) 11 opened Nov 25, 2020 masc-it Are you planning to support tensorflow 2 in the near future? It would be aweso…me, in particular for unlucky AMD GPU owners (like me..)
st205923
LMAO Who did say that? if you have no skill to make a graph model, it is your problem, not tf 1.15 version.
st205924
TF 1.x it Is not actively supported in TF as It is EOL. Tensorflow Directml is still a fork of TF 1.x. so you can find third party support there.
st205925
Deepfakescovery: currently tf-dml is the best solution to train and inference on AMD cards for windows. I am waiting for better options. rocm is option for linux only , and amd has no plan to release it on windows. Also I think TF 2.x is EOL, because it tries to mimic pytorch, but a lot of bugs and performance degradation in result. If you want pytorch, it is better to use pytorch, than pathetic parody of it. Or more simply Keras? Maybe I’ll be nerdy, but where’s the “ease” of doing machine learning on windows compared to linux? TF, Keras, scikit learn, pytorch are primarily intended for Linux and this OS has evolved a lot in ergonomics
st205926
On Windows I still suggest to use WSL2 when It will be ready (hopefully quite soon): github.com/RadeonOpenCompute/ROCm WSL 2 Clarification 2 opened May 14, 2019 iamkucuk As you may know, Microsoft is about to publish a new WSL version. My question is…: How can we benefit from WSL 2.0 which will provide a full linux kernel? On native Windows with Directml when the RFC is finalized and we will have TF2.x support. Today I don’t suggest to start a new project with TF 1.x
st205927
Bhack: On Windows I still suggest to use WSL2 when It will be ready (hopefully quite soon): ROCm is not supported on WSL2 and AMD has no plan to support drivers on windows. currently tf-dml is the best solution to train and inference on AMD cards for windows.
st205928
@Remy_Wehrung couldn’t agree more! The power you get with “sudo” is like Thanos with infinity stones.
st205929
Bhack: Today I don’t suggest to start a new project with TF 1.x same for TF 2.x For an experienced programmer, the ML framework does not matter. In my experience 95% of time I spent to datasets, researching and UI/app. Models can be easily ported to any ML framework.
st205930
/usr/local/lib/python3.7/dist-packages/matplotlib/image.py:452: UserWarning: Warning: converting a masked element to nan. dv = np.float64(self.norm.vmax) - np.float64(self.norm.vmin) /usr/local/lib/python3.7/dist-packages/matplotlib/image.py:459: UserWarning: Warning: converting a masked element to nan. a_min = np.float64(newmin) /usr/local/lib/python3.7/dist-packages/matplotlib/image.py:464: UserWarning: Warning: converting a masked element to nan. a_max = np.float64(newmax) :6: UserWarning: Warning: converting a masked element to nan. /usr/local/lib/python3.7/dist-packages/numpy/core/_asarray.py:83: UserWarning: Warning: converting a masked element to nan. return array(a, dtype, copy=False, order=order) The above given is the warning when I tried using keras’ make_gradcam_heatmap method in Google Colab. The heatmap is not getting plotted. Please help me in solving it.
st205931
I have the log mel spectrograms of a few audio clips and I am trying to augment the spectrograms using tfa.image.sparse_image_warp so that time warping can be achieved as done in Google’s SpecAugment But I am confused on how to do achieve time warping as the documentation does not specify how to initialize arguments to sparse_image_warp. The method declaration is like this: tfa.image.sparse_image_warp( image: tfa.types.TensorLike, source_control_point_locations: tfa.types.TensorLike, dest_control_point_locations: tfa.types.TensorLike, interpolation_order: int = 2, regularization_weight: tfa.types.FloatTensorLike = 0.0, num_boundary_points: int = 0, name: str = ‘sparse_image_warp’) → tf.Tensor Can someone point out how to initialize source_control_point_locations, dest_control_point_locations and num_boundary_points?
st205932
I suppose you need to use the Deepspeech fork of this See this thread: github.com/tensorflow/io Audio Processing API and tfio.audio 3 opened Mar 6, 2020 yongtang This is about API design of the audio processing in tfio. Comments and discussio…ns are welcomed. When we started to get into reading audio for tfio, we start with a feature request from the community of 24bit WAV file which was not possible in tf core repo. Since then, we also supported `Dataset` types of access that essentially is a sequential read, and random access (AudioIOTensor) which allows python `__getitem__()` and `__len__()` styles access in tensorflow graph. Later, we added additional audio format support such as `Flac`, `Ogg`, `MP3` and `MP4`, in addition to the already supported `WAV` file. Note `WAV`, `Flac`, `Ogg`, `MP3` does not requires external .so dependency. For `MP4`, we use AVFoundation on macOS, but needs FFmpeg's .so files on Linux. We also added the `resample` as a basic ops (not a python class) recently upon request from community. Recently, new requests to add supports for decoding memory input audio into tensors comes in play (See PR #815). So the APIs for audio processing in tfio will expand even further. Initially we have not truly come up with a good audio api design as those features are added over gradually, span across more than a year. Now as the features are gradually in shape, I think it is point to start lay out tfio.audio to revisit APIs so that: 1. Capture the usage from community for different use cases. 2. Allow expansion in the future (our focus was on decoding but encoding will be added soon). The audio processing in tf repo, is pretty much limited and is really not a good template for us to follow. I also look into pytorch's audio package as well. While pytorch's APIs are typically very clean, the audio related apis are not as clean as some other parts. pytorch also relies on sox which could be an issue (sometimes could be a benefit depending on the scenario.). We can summarize the use case that has been covered: 1. AudioIODataset which is a subclass of tf.data.Dataset and could be passed to tf.keras. Dataset is a sequential access (not random accessed) that allows iteration from the beginning to the end. The shape and dtype are probed automatically in eager mode. dtype has to be provided by user in graph mode. It is normally file based (or callback-based) and will not load the whole clip into memory (lazy-loaded). 2. AudioIOTensor which exposes `__getitem__`, `__len__`, `shape`, `dtype`, and `rate` API in python and could be used in graph mode (certain restriction apply). IOTensor is a random access that allows reading data at any index (`__getitem__`). This is very useful in situations where user want to access just a small clip of the audio. The `shape` API allows user to get the number of channels and samples. `shape = [samples, channels]`. The shape and dtype are probed automatically in eager mode. dtype has to be provided by user in graph mode. It is file based (or callback-based) and will not load the whole clip into memory (lazy-loaded). 3. `decode`/`decode_mp3`/`decode_mp4`/etc (see discussion in #815) where the API could be used to decode a string (memory) into tensor. This is useful in situations where we already load the small clip of audio files into memory and we just want to do a decoding. On a separate discussion, we may want to expose `metainfo()` API in audio to return back user the shape, dtype, and rate of the audio clip in kernel ops. 4. `encode`/`encode_mp3`/`encode_mp4`/etc which is the counterpart of 3. We haven't add any ops yet though I the need is obvious. 5. `resample` is an audio processing API we recently added. We may want to expand more in the future. Given the above I think the layout could be: ``` tfio.audio - AudioIODataset - AudioIOTensor - decode - decode_mp3 - decode_mp4 - decode_wav - encode - encode_mp3 - encode_mp4 - encode_wav - resample ``` The list could be easy though details could be challenging. For example in tf: ``` tf.audio.decode_wav( contents, desired_channels=-1, desired_samples=-1, name=None ) ``` Do we really want to provide the option of `desired_channels` and `desired_samples`? My understanding is that we already provided AudioIODataset and AudioIOTensor which already allows lazy-loaded partial access (either sequentially or completely random). I don't see we want to manipulate further. Any additional manipulation could be done after a tensor has been returned. For example, to reduce the stereo to mono is just to drop one dim in tensor (after the tensor is returned from decode_wav). Another thing is the dtype. In order for a custom op to work in graph mode, Shape is not needed because shape could be pass as unknown dimension. But, at the minimum a dtype has to be provided (unless it is known before hand). For example, even in `decode_wav` case, the above will not work for 24bit wav file. We do have to provide an API with minimal input: ``` tfio.audio.decode_wav(input, dtype, name=None) ``` There might be some other details to sort out. /cc @jjedele @terrytangyuan @BryanCutler, also cc @faroit @lieff in case you are interested.
st205933
Hello good people. So, I would want to do predictions using image data of goats. My independent variable was continuous data that I divided into 3 classes to make it categorical: group 1= <30%, group 2= 30% to 70%, and group 3= >70%. However, my worry is that prediction accuracy may be compromised by images from goats with output values close to the border, eg 31%. To address this issue, I would want to use multiple label classification but only for images from goats with percentages within +/- 5% from the border ie 25% to 35% and 65%-75%. I would not want to maintain 3 groups. My question is that, is this possible. if so, how do I group my training and testing data set, which Multi-label classification method would best fit my problem and how do I go about it
st205934
What are the outputs of your model going to look like? From your description, it sounds like you’re going to have one output, and use it’s value between 0 and 1 to determine which group it falls into. Are your classes along a continuous spectrum, or are they distinct and mutually exclusive?
st205935
I have one output factor with values from 0 to 1. Like you rightfully said, I will use the output values from each goat to classify the images into 3 distinct classes, i.e. class A for values less than 0.30, class B from 0.30 to 0.70 and class C greater than 0.70. However, because I have grouped my data into 3 distinct and mutually exclusive classes, I’m likely going to have biases for images from goats with percentages such as 0.28, 0.32, 0.69 or 0.73 as they are close to my delineating points and may give predictions belonging to another group. Therefore, I would want to use Multi-label classification for such figures (ie +/- 0.05 from 0.3 and from 0.7). Would this work, if not what other deep learning method would work for such a prediction analysis
st205936
Okay. For multi-class classification, you’ll usually have the same number of units in your output layer as you have classes. This means that each output represents the probability that the image falls into a given category. You can then use a softmax activation function to scale your outputs so that they add up to 1. An example of the output that you’d get would be [0.01, 0.01, 0.98] meaning that your model is 98% confident that the image is in class 3. When training, set up a list of your classes (like [“class1”, “class2”, “class3”]) and have your training labels be the index in that list where the goat should be classified. Set your model up as I described above and use ‘sparse_categorical_crossentropy’ as your loss function. After training, you can use the argmax function in numpy to get the index of the largest value from your prediction list and use the list of class names to give it a text label.
st205937
thank you so much Jeff. What are the advantages of using sparse categorical cross-entropy over categorical cross entropy?
st205938
categorical_crossentropy lets you use the actual label values. It’s good for when you have a single category, or you have an input that can fit into multiple classes so one-hot encoding your label won’t help (for example, an image with multiple goats). sparse_categorical_crossentropy lets you use the index of your class as the label and creates the one-hot array for you. This helps when you have lots of classes and don’t want to have your label be a huge array of 0s with one 1 for the class that you’re looking for.
st205939
For sparse categorical cross-entropy, you don’t need to one-hot encode 11 your class labels. It’s handled by the library itself. But for categorical cross-entropy the loss function expects the predictions and the true class labels to be in one-hot encoded form. It is beneficial when you would want to use something like label-smoothing 10 or any other method that modifies the marginal distributions.
st205940
Hello sir , i have trained my 10 classes with CNN but the model is predicting anything outside my classes , is there a way to fix this so that the model predicts only my 10 classes
st205941
What do the results that you’re getting look like? You may want to check that you have a 10-unit dense layer at the end of your network, and that the labels for your results match the 10 classes that you’re looking for.
st205942
yeah i have a dense layer of 10 classes the problem am experiencing is that , it is a tomato leaf disease detection model but it is predicting even my face as one of the classes am having .Is there a way to control prediction so that it only predicts tomato leaf disease only and ignore other things
st205943
Your model will only know how to classify based on the images that you’ve trained it with. It’s trying to decide which of the classes it recognizes that your input image is most similar to. To fix this, you might try setting a minimum threshold when handling the model’s output. If your highest class value is below a certain level, then it’s probably safe to say that your model doesn’t recognize any disease in the image.
st205944
thank you so much , do you a code snippets for doing that since am using tensorflow to train the model and inferences on android application. I will appreciate
st205945
Sorry, this would be a post-processing step and I haven’t done much coding around TF Lite yet.
st205946
If you are working on your first examples you could experiment with the TFlite task library. E.g. for the image classifier like in your use case there is an easy available score field: TensorFlow Integrate image classifiers  |  TensorFlow Lite 18
st205947
Hello, Is there any method that allows us to feed images to a pre-trained Image Classification CNN (saved_model.pb) and have it perform predictions on those images? Similar to the ‘.predict()’ method that exists for Keras models. Thanks, Ahmad
st205948
The predict method still works on TF2.x : Basic classification: Classify images of clothing  |  TensorFlow Core 4 There are some examples here: Image Classification with TensorFlow Hub 5
st205949
Hey Community i hope you’re doing fine, i have data frame with more than 7000 rows and a 4 columns, and the label column with categorical labels and i want to convert them to numerical labels, and i don’t know how to do it! is there any tensorflow function that can do this? any help please.
st205950
You’d have a couple of options here. Since you’re working in a dataframe, there’s a function in Pandas called get_dummies 5 that will one-hot encode for you. There’s also a function in Keras called to_categorical 5, though that seems like it’s limited to taking integer values as your classes. Those integers could be the indexes for a list of class name strings if you want to convert back to meaningful names. Here are some links to the documentation pages for those functions. https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html 5 https://www.tensorflow.org/api_docs/python/tf/keras/utils/to_categorical 5
st205951
Hey @Jeff_Corpac thank you for your reply, but the function to_categorical does not accept categorical classes like (red, green, blue…) that’s my case!
st205952
Do you want something like this? Medium – 31 Oct 20 Demonstration of TensorFlow Feature Columns (tf.feature_column) 6 Understand tensorflow feature columns Reading time: 12 min read
st205953
You might want to try the Pandas function instead. You mentioned using a DataFrame in your original post so I figured you were using Pandas. You can also set up a list of class names like ['red', 'green', 'blue'] and use the index (0 = red, 1 = green, etc) as categories for the to_categorical function. Since the categorical column is your label, you could also try using sparse_categorical_crossentropy as your loss function and use the index values as your labels to skip the to_categorical function altogether.
st205954
Thank you so much, you guys really saved my life! I read the article shared by @Bhack, and i just applied the advice given by @Jeff_Corpac and it worked yaaay
st205955
Hi, I want to use TFLite Model Maker to train custom object detection models. When I try to change the hparam image_size. spec = EfficientDetModelSpec( model_name="efficientdet-lite0", uri="https://tfhub.dev/tensorflow/efficientdet/lite0/feature-vector/1", hparams={ "image_size": "420x420" } ) train_data, validation_data, test_data = object_detector.DataLoader.from_csv("...") model = object_detector.create( train_data, validation_data=validation_data, model_spec=spec, epochs=1, batch_size=4, train_whole_model=True) The following error occurs: Error --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-4ed9b6a821a2> in <module> ----> 1 model = object_detector.create( train_data, 2 validation_data=validation_data, 3 model_spec=spec, 4 epochs=1, 5 batch_size=4, c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow_examples\lite\model_maker\core\task\object_detector.py in create(cls, train_data, model_spec, validation_data, epochs, batch_size, train_whole_model, do_train) 285 if do_train: 286 tf.compat.v1.logging.info('Retraining the models...') --> 287 object_detector.train(train_data, validation_data, epochs, batch_size) 288 else: 289 object_detector.create_model() c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow_examples\lite\model_maker\core\task\object_detector.py in train(self, train_data, validation_data, epochs, batch_size) 154 validation_ds, validation_steps, val_json_file = self._get_dataset_and_steps( 155 validation_data, batch_size, is_training=False) --> 156 return self.model_spec.train(self.model, train_ds, steps_per_epoch, 157 validation_ds, validation_steps, epochs, 158 batch_size, val_json_file) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow_examples\lite\model_maker\core\task\model_spec\object_detector_spec.py in train(self, model, train_dataset, steps_per_epoch, val_dataset, validation_steps, epochs, batch_size, val_json_file) 262 val_json_file=val_json_file, 263 batch_size=batch_size)) --> 264 train.setup_model(model, config) 265 train.init_experimental(config) 266 model.fit( c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow_examples\lite\model_maker\third_party\efficientdet\keras\train.py in setup_model(model, config) 111 def setup_model(model, config): 112 """Build and compile model.""" --> 113 model.build((None, *config.image_size, 3)) 114 model.compile( 115 steps_per_execution=config.steps_per_execution, c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\keras\engine\training.py in build(self, input_shape) 417 'method accepts an `inputs` argument.') 418 try: --> 419 self.call(x, **kwargs) 420 except (errors.InvalidArgumentError, TypeError): 421 raise ValueError('You cannot build your model by calling `build` ' c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow_examples\lite\model_maker\third_party\efficientdet\keras\train_lib.py in call(self, inputs, training) 883 884 def call(self, inputs, training): --> 885 cls_outputs, box_outputs = self.base_model(inputs, training=training) 886 for i in range(self.config.max_level - self.config.min_level + 1): 887 cls_outputs[i] = self.classes(cls_outputs[i]) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\keras\engine\base_layer.py in __call__(self, *args, **kwargs) 1010 with autocast_variable.enable_auto_cast_variables( 1011 self._compute_dtype_object): -> 1012 outputs = call_fn(inputs, *args, **kwargs) 1013 1014 if self._activity_regularizer: c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\autograph\impl\api.py in wrapper(*args, **kwargs) 668 except Exception as e: # pylint:disable=broad-except 669 if hasattr(e, 'ag_error_metadata'): --> 670 raise e.ag_error_metadata.to_exception(e) 671 else: 672 raise ValueError: in user code: c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow_hub\keras_layer.py:243 call * result = smart_cond.smart_cond(training, c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\saved_model\load.py:668 _call_attribute ** return instance.__call__(*args, **kwargs) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\eager\def_function.py:828 __call__ result = self._call(*args, **kwds) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\eager\def_function.py:871 _call self._initialize(args, kwds, add_initializers_to=initializers) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\eager\def_function.py:725 _initialize self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\eager\function.py:2969 _get_concrete_function_internal_garbage_collected graph_function, _ = self._maybe_define_function(args, kwargs) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\eager\function.py:3361 _maybe_define_function graph_function = self._create_graph_function(args, kwargs) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\eager\function.py:3196 _create_graph_function func_graph_module.func_graph_from_py_func( c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\framework\func_graph.py:990 func_graph_from_py_func func_outputs = python_func(*func_args, **func_kwargs) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\eager\def_function.py:634 wrapped_fn out = weak_wrapped_fn().__wrapped__(*args, **kwds) c:\users\felix\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\saved_model\function_deserialization.py:267 restored_function_body raise ValueError( ValueError: Could not find matching function to call loaded from the SavedModel. Got: Positional arguments (2 total): * Tensor("inputs:0", shape=(None, 420, 420, 3), dtype=float32) * False Keyword arguments: {} Expected these arguments to match one of the following 4 option(s): Option 1: Positional arguments (2 total): * TensorSpec(shape=(None, 320, 320, 3), dtype=tf.float32, name='inputs') * True Keyword arguments: {} Option 2: Positional arguments (2 total): * TensorSpec(shape=(None, 320, 320, 3), dtype=tf.float32, name='input_1') * False Keyword arguments: {} Option 3: Positional arguments (2 total): * TensorSpec(shape=(None, 320, 320, 3), dtype=tf.float32, name='input_1') * True Keyword arguments: {} Option 4: Positional arguments (2 total): * TensorSpec(shape=(None, 320, 320, 3), dtype=tf.float32, name='inputs') * False Keyword arguments: {} Does this mean, that custom input shape is not supported?
st205956
felithium: spec = EfficientDetModelSpec( model_name="efficientdet-lite0", uri="https://tfhub.dev/tensorflow/efficientdet/lite0/feature-vector/1", hparams={ "image_size": "420x420" } ) Hi @felithium Please where did you find this code snippet? Place here the link to check it. I read the documentation here 7 and I cannot find EfficientDetModelSpec…and the dictionary for the hparams
st205957
here there’re some documentation that can help: Object Detection with TensorFlow Lite Model Maker 10 If you want to change the input image size, you might need to change the base model spec to one that has a bigger input from here: TensorFlow Hub 13 hope it helps
st205958
George_Soloupis: documentation here and I I stepped into the source and found out that … from tflite_model_maker import model_spec # ... this is the same as ... spec = model_spec.get('efficientdet_lite0') # # ... this or ... # efficientdet_lite0_spec = functools.partial( # EfficientDetModelSpec, # model_name='efficientdet-lite0', # uri='https://tfhub.dev/tensorflow/efficientdet/lite0/feature-vector/1', #) # # ... this. # spec = EfficientDetModelSpec( # model_name="efficientdet-lite0", # uri="https://tfhub.dev/tensorflow/efficientdet/lite0/feature-vector/1", # hparams={...} # here I can add hparams which I think is convinient # ) Sadly I am not allowed to post links. But you can find the documentation to EfficientDetModelSpec exported as EfficientDetSpec if you search for tflite_model_maker.object_detector.EfficientDetSpec on your link and press on it. @mm_export('object_detector.EfficientDetSpec') class EfficientDetModelSpec(object):
st205959
I read the documentation you linked. And it says that I can change hparams which contains image_size but doing so results in the error I posted. Sadly changing the model won’t fix my problem, because I need a special aspect ratio like 1.67, because all my images have this aspect ratio, while every model in the hub has an aspect ration of 1.
st205960
@felithium Yes, unfortunately, custom input shape is not supported in TFLite Model Maker for now. If you’d like to use a custom input shape, you need to to use automl/efficientdet at master · google/automl · GitHub 33 repo.
st205961
Typically we think of Convolutional Neural Networks as accepting fixed size inputs (i.e., 224×224, 227×227, 299×299, etc.). But what if you wanted to: Utilize a pre-trained network for transfer learning… …and then update the input shape dimensions to accept images with different dimensions than what the original network was trained on? Why might you want to utilize different image dimensions? There are two common reasons: Your input image dimensions are considerably smaller than what the CNN was trained on and increasing their size introduces too many artifacts and dramatically hurts loss/accuracy. Your images are high resolution and contain small objects that are hard to detect. Resizing to the original input dimensions of the CNN hurts accuracy and you postulate increasing resolution will help improve your model. In these scenarios, you would wish to update the input shape dimensions of the CNN and then be able to perform transfer learning. The question then becomes, is such an update possible? Yes, in fact, it is. For more visit: https://reviewscot.com/ web blog.
st205962
Here is my attempt to curate a content which explains how TensorFlow works internally. I have spent good amount of time (2 months) curating content, structuring it, creating visuals and animations for this one. I hope it will help many. [https://youtu.be/OmSLter9lyE 49](YouTube URL)
st205963
Do you think that Tensorflow could plan to introduce in 2021 Rust in the codebase like in other Google projects (Chromium, Android, Linux Kernel etc.) or do you think that we will have some specific issues for our library? E.g. For Rust/C++ interop in Chromium see: chromium.org Rust and C++ interoperability - The Chromium Projects 6 Home of the Chromium Open Source Project /cc @mihaimaruseac
st205964
See also GitHub - google/autocxx: Tool for safe ergonomic Rust/C++ interop driven from existing C++ headers 3
st205965
Another related link: How CrowdStrike Combines TensorFlow and Rust for Performance 2 It would be nice to have parts of TF written in Rust instead of C++ for better safety, but I am unsure this is possible at the moment, unfortunately. We will need a large refactoring and modularization to allow this to happen.
st205966
I think it could be interesting, as a prototipe, if we could consume the new WIP TF runtime c++ API (e.g. with autoccx) to write the simple kernel example in Rust: github.com tensorflow/runtime/blob/master/lib/test_kernels/simple_kernels.cc 6 // Copyright 2020 The TensorFlow Runtime Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This file implements a few simple classes of synchronous kernels for testing. #include <fstream> #include <iterator> #include <random> #include <string> This file has been truncated. show original
st205967
It could be really nice to have an analysis like this one for TF Google Online Security Blog Rust/C++ interop in the Android Platform 4 Posted by Joel Galenson and Matthew Maurer, Android Team One of the main challenges of evaluating Rust for use within the Android platform...
st205968
Wish to use Universal Sentence Embeddings from Tf hub, retrain with own corpus for a classification task. So layers are: UnivSentEmb pretrained from tf hub with trainable ON Dense 300, relu Dense num_classes, softmax Once the model is trained on own corpus, during the prediction time it behaves as a classifier. predicted_class = model.predict(test_sentence) Here, wish to query middle layer values, which is a 300 long embedding vector, for the test_sentence. Possible? How? Is this approach correct? Can we say that this 300 long vector of that test_sentence is its USE embedding?
st205969
Hi @Yogesh_Kulkarni one way of doing what you want is to have your custom model have 2 outputs: the dense layer with num_classes and the dense layer with the 300 embeddings for that you might need to use the Functional API: The Functional API  |  TensorFlow Core 3
st205970
Hi! Every time I run a code more than once with tensorflow_probability imported I get the following error: import tensorflow_probability Traceback (most recent call last): File “”, line 1, in import tensorflow_probability File “/home/slevy/Desktop/probability/tensorflow_probability/init.py”, line 23, in from tensorflow_probability.python import * # pylint: disable=wildcard-import File “/home/slevy/Desktop/probability/tensorflow_probability/python/init.py”, line 142, in dir(globals()[pkg_name]) # Forces loading the package from its lazy loader. File “/home/slevy/Desktop/probability/tensorflow_probability/python/internal/lazy_loader.py”, line 61, in dir module = self._load() File “/home/slevy/Desktop/probability/tensorflow_probability/python/internal/lazy_loader.py”, line 44, in _load module = importlib.import_module(self.name) File “/home/slevy/anaconda3/lib/python3.7/importlib/init.py”, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File “/home/slevy/Desktop/probability/tensorflow_probability/python/experimental/init.py”, line 35, in from tensorflow_probability.python.experimental import bijectors File “/home/slevy/Desktop/probability/tensorflow_probability/python/experimental/bijectors/init.py”, line 19, in from tensorflow_probability.python.experimental.bijectors.distribution_bijectors import make_distribution_bijector File “/home/slevy/Desktop/probability/tensorflow_probability/python/experimental/bijectors/distribution_bijectors.py”, line 25, in from tensorflow_probability.python.distributions import deterministic File “/home/slevy/Desktop/probability/tensorflow_probability/python/distributions/init.py”, line 23, in from tensorflow_probability.python.distributions.autoregressive import Autoregressive File “/home/slevy/Desktop/probability/tensorflow_probability/python/distributions/autoregressive.py”, line 30, in from tensorflow_probability.python.util.seed_stream import SeedStream File “/home/slevy/Desktop/probability/tensorflow_probability/python/util/init.py”, line 23, in from tensorflow_probability.python.util.deferred_tensor import DeferredTensor File “/home/slevy/Desktop/probability/tensorflow_probability/python/util/deferred_tensor.py”, line 738, in class _DeferredTensorSpec(_DeferredTensorSpecBase, type_spec.BatchableTypeSpec): File “/home/slevy/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/type_spec.py”, line 713, in decorator_fn _NAME_TO_TYPE_SPEC[name].name)) ValueError: Name tfp.util.DeferredTensorSpec has already been registered for class tensorflow_probability.python.util.deferred_tensor._DeferredTensorSpec. I couldn’t find any discussions on this error anywhere, what can I do to fix it? It’s really annoying to restart the kernel each time to run my code. Thanks in advance!
st205971
Hi, can you provide a bit more context? If you can provide a link to a colab that reproduces this problem we’ll have an easier time helping out.
st205972
Hi again – I think we found the issue, so this should be fixed in tomorrow’s tfp-nightly. (Please let us know if not!)
st205973
Ok so this error appears when I import first tensorflow.compat.v1 and than import also tensorflow_probability. It only appear when I run this twice (even if there is not other code involved). I can’t reproduce this error in colab so I guess this error has to do with some clash in packages on my laptop.
st205974
Hi shi_le, thanks for the additional info. It’s important to make sure your tensorflow and TFP versions are in alignment, and that there is only one version of each installed. There are two release patterns for TF and TFP: nightly and stable, which I think you’ve noticed given your latest comment. You should avoid ever having both tensorflow and tf-nightly installed side by side, and similarly with TFP. If you want to use tf-nightly, you should also use tfp-nightly. Every once in a while one of these fails to be pushed out on a given day, but usually they should both be there and even if they’re off by one or two days they should be compatible. If you are using tensorflow==1.15, you will need to install an older TFP version, since we stopped supporting the 1.x line in new stable releases when TF stopped incrementing the stable 1.x versions. The last TFP version that should work with TF 1.15 was tensorflow_probability==0.8 (see the release notes here 1). In general, when TFP publishes a new release, we note the compatible TF version in the release notes (see all of them here 3). Generally speaking we release stables in lock-step with TF. When they push a new stable, we do, too. So, final advice: uninstall all the TF’s TFP’s and TF nightly’s and TFP nightly’s you have and then just install exactly the ones you want to use. Then things should work! Please let us know if not, or if I can clarify any of the above.
st205975
Sorry I just realized that this error comes from the tensorflow_probability package I took from the tensorflow/probability github repository (unless it is the same as TFP). But I still don’t understand why I get the error when importing this package (after I already imported it one time) without doing anything else. I get the error ValueError: Name tfp.util.DeferredTensorSpec has already been registered for class tensorflow_probability.python.util.deferred_tensor._DeferredTensorSpec. or more specifically from this part of type_spec.py in the package : def register(name): “”"Decorator used to register a globally unique name for a TypeSpec subclass. Args: name: The name of the type spec. Must be globally unique. Must have the form "{project_name}.{type_name}". E.g. "my_project.MyTypeSpec". Returns: A class decorator that registers the decorated class with the given name. “”" if not isinstance(name, str): raise TypeError(“Expected name to be a string; got %r” % (name,)) if not _REGISTERED_NAME_RE.match(name): raise ValueError( "Registered name must have the form ‘{project_name}.{type_name}’ " “(e.g. ‘my_project.MyTypeSpec’); got %r.” % name) def decorator_fn(cls): if not (isinstance(cls, type) and issubclass(cls, TypeSpec)): raise TypeError(“Expected cls to be a TypeSpec; got %r” % (cls,)) if cls in _TYPE_SPEC_TO_NAME: raise ValueError(“Class %s.%s has already been registered with name %s.” % (cls.module, cls.name, _TYPE_SPEC_TO_NAME[cls])) if name in _NAME_TO_TYPE_SPEC: raise ValueError(“Name %s has already been registered for class %s.%s.” % (name, _NAME_TO_TYPE_SPEC[name].module, _NAME_TO_TYPE_SPEC[name].name)) _TYPE_SPEC_TO_NAME[cls] = name _NAME_TO_TYPE_SPEC[name] = cls return cls return decorator_fn Any idea why would importing this package twice leads to this error? Sorry again for the confusion!
st205976
Hi shi_le, the TFP github repo code should generally be the same as tfp-nightly, modulo changes within the last day. It’s possible you had a few days old snapshot of the TFP repo, since I believe Emily’s recent changes fixed this (real!) bug. If you can, please try with tfp-nightly from pip, and/or rebuilt .whl from the github repo, synced to the most recent HEAD, and see if this alleviates your issue. Let us know if not! Thanks for catching this error and discussing it with us, helping us to improve TFP. Sorry for the confusing bug!
st205977
I am using TF 1.15.0 and Keras with an LSTM to analyse a large set of (mainly jazz related) midi files. It is important that I can monitor the progress during the training stage. I want to output metrics and from these create a series of graphs. I can now do this for loss, val_loss, accuracy, val_accuracy. I have also now been able to call (in model.compile…) metrics for recall and precision. These are included in a log. I want to use these, in turn, to calculate an f1-score. I am having difficulty using the values for precision and recall as within the log they are named as “precision_3” and “recall_4”. Can anyone tell me what the number after precision and recall refer to? If I knew I could use this to access these values during training.
st205978
I am trying to convert EfficientNetD1 model from Tensorflow Model Zoo to TensorRT using this script: import tensorflow as tf import numpy as np from tensorflow.python.compiler.tensorrt import trt_convert as trt input_saved_model_dir = './saved_model/' output_saved_model_dir = './test/' num_runs = 2 conversion_params = trt.DEFAULT_TRT_CONVERSION_PARAMS conversion_params = conversion_params._replace(max_workspace_size_bytes=(1<<32)) conversion_params = conversion_params._replace(precision_mode="FP16") conversion_params = conversion_params._replace( maximum_cached_engines=100) converter = trt.TrtGraphConverterV2(input_saved_model_dir=input_saved_model_dir,conversion_params=conversion_params) converter.convert() def my_input_fn(): inp1 = np.random.normal(size=(1,640,640,3)).astype(np.float32) yield inp1 converter.build(input_fn=my_input_fn) converter.save(output_saved_model_dir) But I only get this error: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2) File "/usr/local/lib/python3.8/dist-packages/tensorflow/python/eager/execute.py", line 59, in quick_execute tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, tensorflow.python.framework.errors_impl.InvalidArgumentError: cannot compute __inference_pruned_174167 as input #0(zero-based) was expected to be a uint8 tensor but is a float tensor [Op:__inference_pruned_174167] Any suggestion on this issue?
st205979
#help_request #tflite I am working on this project: TensorFlow Lite image classification Android example application I run this project on my own phone (xiaomi redmi note 8) on Android Studio (not emulator) When I run this project on Android Studio, TFL Classify applications gives the following error: application keep stopping. Then Android Studio gives this error: E/AndroidRuntime: FATAL EXCEPTION: main Process: org.tensorflow.lite.examples.classification, PID: 7599 java.lang.RuntimeException: Unable to start activity ComponentInfo{org.tensorflow.lite.examples.classification/org.tensorflow.lite.examples.classification.ClassifierActivity}: java.lang.IllegalArgumentException: No enum constant org.tensorflow.lite.examples.classification.tflite.Classifier.Model.QUANTİZED_EFFİCİENTNET at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:201) at android.app.ActivityThread.main(ActivityThread.java:6864) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) Caused by: java.lang.IllegalArgumentException: No enum constant org.tensorflow.lite.examples.classification.tflite.Classifier.Model.QUANTİZED_EFFİCİENTNET at java.lang.Enum.valueOf(Enum.java:258) at org.tensorflow.lite.examples.classification.tflite.Classifier$Model.valueOf(Classifier.java:47) at org.tensorflow.lite.examples.classification.CameraActivity.onCreate(CameraActivity.java:195) at android.app.Activity.performCreate(Activity.java:7232) at android.app.Activity.performCreate(Activity.java:7221) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2964) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:201) at android.app.ActivityThread.main(ActivityThread.java:6864) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) I updated SDK version 28 to 29.0.2 but it didn’t work
st205980
@Ugur_Ercelik Please give us a link of the project that it has a problem to take a look.
st205981
I wanted to put the link, but I got an error “Sorry, you can’t include links in your posts.” So i put like this Project link : github.com.tensorflow.examples.tree.master.lite.examples.image_classification.android
st205982
Hi @Ugur_Ercelik it seems that the project builds OK to my AS. Download again the projects from here 7 go to the image_classification/android folder and build it again. Also check that inside Classifier.java file there is: /** The model type used for classification. */ public enum Model { FLOAT_MOBILENET, QUANTIZED_MOBILENET, FLOAT_EFFICIENTNET, QUANTIZED_EFFICIENTNET } Best
st205983
Yes thats right.The error is caused by UI string.I looked app->res->values->strings.xml And there,like this Quantized_Efficientnet Float_Efficientnet Quantized_MobileNet Float_Mobilenet Then,i changed like this QUANTIZED_EFFICIENTNET FLOAT_EFFICIENTNET QUANTIZED_MOBILENET FLOAT_MOBILENET And problem is solved.Thanks for your opinion
st205984
Hello, i recently trained a ssd_resnet model for some custom classification. In general everything worked out as i was able to run inference on the data which was produced by the training process. What i want to do is to convert the model to a tflite model and compile it for a coral TPU. What does not work atm: I cannot find any information on how to convert my model into a tflite model. The training process was done using the script model_main_tf2.py from the object detection API. This produces files as follows: checkpoint ckpt-XXX.data-00000-of-00001 ckpt-XXX.index (which is as far as i can tell everything) I am aware that there are a lot of sites talking about converting modesl to tflite but none that work from the kind of checkpoints i have. (it always refers to model.ckpt files with some kind of meta file given which i guess is a tf1 format?) What i tried: using the export scripts provided by the opject detection API (export_tflide_ssd_graph.py, export_tflite_graph_tf2.py) - both did not work as it says: “your model is not built”. loading and building the model and then manually exporting it: # load model configs = config_util.get_configs_from_pipeline_file(PATH_TO_CFG) model_config = configs['model'] detection_model = model_builder.build(model_config=model_config, is_training=False) # Restore checkpoint ckpt = tf.compat.v2.train.Checkpoint(model=detection_model) ckpt.restore(os.path.join(PATH_TO_CKPT, 'ckpt-63')).expect_partial() detection_model.build((614,514)) converter = tf.lite.TFLiteConverter.from_keras_model(detection_model) tflite_model = converter.convert()``` which results in the same problem telling me that the input is not set and that i could solve this by “building” the model. (which i thought i did…?) So if anyone can shed some light on how this could work or where i can find any documentation on how to convert these checkpoints to a .tflite model i’d be really grateful. Let me know if i forgot to provide any information. Cheers.
st205985
so i was finally able to figure this out. Posting my own answer in a hope that it might help someone else: the model gained from the learning process apparently is not a standard tensorflow or keras model and first must be exported using the script called “exporter_main_v2.py”. This is relatively selfexplainatory as it takes the arguments --trained_checkpoint_dir, --pipeline_config_path and --output_directory when this step is done a folder is created at the output location which should be called “saved_model” The following python script can be used to transform this into a TF-Lite model: MODEL_PATH = "your/abs/path/to/folder/saved_model" MODEL_SAVE_PATH = "your/target/save/location" converter = tf.lite.TFLiteConverter.from_saved_model(MODEL_PATH ,signature_keys=['serving_default']) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.experimental_new_converter = True converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] tflite_model = converter.convert() with tf.io.gfile.GFile(MODEL_SAVE_PATH, 'wb') as f: f.write(tflite_model) Hope this helps someone.
st205986
@georg_laage It seems that with the latest version of TensorFlow 2.5.0 you do not need the below lines of code: converter.experimental_new_converter = True converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] You can make the conversion like this 8 code snippet. Can you confirm if you have time?
st205987
Hey @George_Soloupis, just tested your code suggestion and it indeed leads to the same result. Sadly i had to learn over the last days that a successful (or rather non-error) conversion of a model does not necessarily mean that one can actually use the result for anything. If i use the model as followed: interpreter = tf.lite.Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() print("Validation finished successfully.") then i never get to the final print. The command interpreter.invoke() just randomly exits without any further message or error. I added a verification step to my model before the conversion and can thus confirm that the original model is correctly working. I also had to learn that since i want to compile the tflite model for a coral-ai TPU i need to add full integer quantization to the tflite-conversion which completly breaks the process. I’ll probably open a new discussion for that since this question as itself is answered.
st205988
@georg_laage I am really interested in both problems! That you never get a result of the interpreter and that you cannot do a full quantization. Please tag me whenever you need help.
st205989
Hey George, thank you for your interest in my issue. I was able to get a bit further with the help of a discussion in a github issue here: github<dot>com/tensorflow/models/issues/9371 (“link” to issue, apparently i am not allowed to include links in my post) My original error was to take the wrong script to export my checkpoints into saved_model format. I was using exporter_main_v2.py instead of export_tflite_graph_tf2.py. Since then the conversion and inference step actually works (in some manner as it terminates without error) The resulting tflite is too small though as it only reaches 440 bytes. Apparently this is an issue when using wrong tensorflow versions but even after a fresh install of tensorflow in a virtual env the problem remains the same. This so far is without integer quantization.
st205990
It’s been a while TensorFlow Addons released an easy-to-use wrapper for Cyclical Learning Rates. Today, we are pleased to release its accompanying tutorial guide: TensorFlow TensorFlow Addons Optimizers: CyclicalLearningRate 3 Usage is straightforward: steps_per_epoch = len(x_train) // BATCH_SIZE clr = tfa.optimizers.CyclicalLearningRate(initial_learning_rate=INIT_LR, maximal_learning_rate=MAX_LR, scale_fn=lambda x: 1/(2.**(x-1)), step_size=2 * steps_per_epoch ) optimizer = tf.keras.optimizers.SGD(clr)
st205991
Hi all. Looking for resources/materials that build on TensorFlow/Keras (preferably) for doing scalable image similarity searches.
st205992
With Keras you can take a look at: Investigating the Vision Transformer Model for Image Retrieval Tasks 18 *DELF tutorial 10 More in general I suggest you an overview: arXiv.org Deep Image Retrieval: A Survey 7 In recent years a vast amount of visual content has been generated and shared from various fields, such as social media platforms, medical images, and robotics. This abundance of content creation and sharing has introduced new challenges. In...
st205993
Thanks @Bhack. I am aware of the DELF model but I don’t want to go that route, I would rather prefer good old embeddings (within a reduced space with something like random projections), and then applying approximate nearest neighbors. Thanks for the survey paper, will look into it. Maybe a TFX example on this might be very helpful given the practical relevancy. Cc: @Robert_Crowe
st205994
Sayak_Paul: good old embeddings When you have created your more or less efficient embedding e.g.: keras.io Keras documentation: Metric learning for image similarity search 10 keras.io Keras documentation: Natural language image search with a Dual Encoder 2 keras.io Keras documentation: Image similarity estimation using a Siamese Network with... 5 Then, you can use almost the same pipeline as in text: Google Cloud Building a real-time embeddings similarity matching system 8
st205995
Thanks. I am quite familiar with the Keras examples that you shared. In fact, I myself have one: github.com sayakpaul/A-Barebones-Image-Retrieval-System 8 This project presents a simple framework to retrieve images similar to a query image. All of them demonstrate workflows which is why I wanted to know about solutions that focus on scalability and depth. Thanks for the GCP one.
st205996
Is that also this domain Is quite large and It has evolved a little bit over the time. As you can see from the mentioned survey and also in: arXiv.org A Decade Survey of Content Based Image Retrieval using Deep Learning 1 The content based image retrieval aims to find the similar images from a large scale dataset against a query image. Generally, the similarity between the representative features of the query image and dataset images is used to rank the images for...
st205997
Well if Tensorflow/keras isn’t a necessity you can try CLIP model by OpenAI. It is quite robust and has good generalizability. You can pre calculate all the images embeddings and calculate cosine similarity with your query image. For huge number of images at large scale you can use Approximate Nearest Neighbor with Hnswlib: github.com nmslib/hnswlib 4 Header-only C++/python library for fast approximate nearest neighbors or Faiss: github.com facebookresearch/faiss 4 A library for efficient similarity search and clustering of dense vectors. or Annoy: github.com spotify/annoy 4 Approximate Nearest Neighbors in C++/Python optimized for memory usage and loading/saving to disk CLIP is usually used by encoding the text to same embedding domain as images, but it should work within images itself too since they are in same domain.
st205998
Thanks for your suggestions. Using ANN has been on my mind from the beginning. After looking for a few other options I also saw NGT which seems to be producing the best results too. For within image domain pre-training, I would rather prefer the recent self-supervised methods like DINO because they are well formulated and we’ll established. DINO is also particularly good at this task. Just as an FYI, one of the Keras links above (shared by @Bhack) actually shows you how to implement a CLIP like model minimally. If you haven’t, definitely check that out
st205999
I am trying to use a model from Tensorflow Model Zoo on a Jetson Nano computer. First I convert the model (.pb -file) to ONNX-format. But when I try to convert it to TensorRT format after the ONNX-step) I only get an error saying: [8] Assertion failed: convertDtype(onnxDtype.elem_type(), &trtDtype) I then run a script in order to turn the data type to float32 since uint8 is not supported by TensorRT. I then try to convert the model to TensorRT format once again, but now I get the error: [8] Assertion failed: cond.is_weights() && cond.weights().count() == 1 && "If condition must be a initializer!" And at this point I am stuck. It seems to me that Jetson/Nvidia does not actually support object detection using models from the Tensorflow Model Zoo? At least I get the impression that most of the layers that the models in the Model Zoo are built on is not supported by TensorRT or ONNX, which therefor creates all sort of problems? Note that I am using the tf.experimental.tensorrt.Converter but the actual tensorrt library provided by Nvidia in order to convert the model. Thanks for any help!