id
stringlengths
3
8
text
stringlengths
1
115k
st206100
Thanks. For our project we need a zero-install solution and don’t want to maintain our own server. So browser-only solutions work for us. But we can live with long loading times and slower sentence encoding, hence our interest in higher accuracy USE models.
st206101
As others have also suggested, if you get the above error detailing currently unsupported ops you have 2 options: Contribute the missing op to the TensorFlow.js project - we are open source and welcome pull requests to help gain parity with TF Python - there are thousands of ops out there so we have tried to convert over common ones initially but we are a younger team so may be some time before parity is achieved. Na Li wrote a nice document on contributing ops here: tfjs/CONTRIBUTING_MISSING_OP.md at master · tensorflow/tfjs · GitHub 2 Change the Python model not to use the unsupported op(s) so it uses ones we do support. However this can be hard as it is not immediately obvious what command in the high level code caused that op to be used unless you know the model very well and how the functions used translate to lower level operations. As you mentioned, we do have a Universal Sentence Encoder already converted available as a premade model: tfjs-models/universal-sentence-encoder at master · tensorflow/tfjs-models · GitHub 3 if this is good enough for your needs.
st206102
I have no idea how to fix it. Here is my code and error: from keras import backend as K target_image = K.constant(preprocess_image(target_image_path)) style_reference_image = K.constant(preprocess_image(style_reference_image_path)) combination_image = K.placeholder((1, img_height, img_width, 3)) input_tensor = K.concatenate([target_image, style_reference_image, combination_image], axis=0) model = vgg19.VGG19(input_tensor=input_tensor, weights='imagenet', include_top=False) print('model loaded') AttributeError Traceback (most recent call last) <ipython-input-17-709cfab4486a> in <module> 6 combination_image = K.placeholder((1, img_height, img_width, 3)) 7 input_tensor = K.concatenate([target_image, style_reference_image, combination_image], axis=0) ----> 8 model = vgg19.VGG19(input_tensor=input_tensor, weights='imagenet', include_top=False) 9 print('model loaded') ~/anaconda3/envs/tf_gpu/lib/python3.7/site-packages/keras/applications/__init__.py in wrapper(*args, **kwargs) 18 kwargs['models'] = models 19 kwargs['utils'] = utils ---> 20 return base_fun(*args, **kwargs) 21 22 return wrapper ~/anaconda3/envs/tf_gpu/lib/python3.7/site-packages/keras/applications/vgg19.py in VGG19(*args, **kwargs) 9 @keras_modules_injection 10 def VGG19(*args, **kwargs): ---> 11 return vgg19.VGG19(*args, **kwargs) 12 13 ~/anaconda3/envs/tf_gpu/lib/python3.7/site-packages/keras_applications/vgg19.py in VGG19(include_top, weights, input_tensor, input_shape, pooling, classes, **kwargs) 102 img_input = layers.Input(shape=input_shape) 103 else: --> 104 if not backend.is_keras_tensor(input_tensor): 105 img_input = layers.Input(tensor=input_tensor, shape=input_shape) 106 else: ~/anaconda3/envs/tf_gpu/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in is_keras_tensor(x) 693 ``` 694 """ --> 695 if not is_tensor(x): 696 raise ValueError('Unexpectedly found an instance of type `' + 697 str(type(x)) + '`. ' ~/anaconda3/envs/tf_gpu/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in is_tensor(x) 701 702 def is_tensor(x): --> 703 return isinstance(x, tf_ops._TensorLike) or tf_ops.is_dense_tensor_like(x) 704 705 AttributeError: module 'tensorflow.python.framework.ops' has no attribute '_TensorLike'
st206103
Can you share more of your code and the TensorFlow version/environment you’re using? Also, try using the latest TensorFlow version (e.g. with PiPI 4 or conda) and then call/use tf.keras.applications.vgg19(). Example/walkthrough with VGG19: TensorFlow Neural style transfer  |  TensorFlow Core API docs: TensorFlow tf.keras.applications.VGG19  |  TensorFlow Core v2.5.0 3 Instantiates the VGG19 architecture. More examples with VGG19: TensorFlow The Functional API  |  TensorFlow Core keras.io Keras documentation: Keras Applications 2 This may also help - implementations of VGG-11/13/19 with TF 2.0 (last updated June 2020, not tested): github.com Bao-Jiarong/VGG/blob/master/vgg.py ''' Author : Bao Jiarong Creation Date: 2020-06-13 email : [email protected] Task : VGG11, VGG13, VGG16, VGG19 Implementation Dataset : MNIST Digits (0,1,...,9) ''' import tensorflow as tf class Block(tf.keras.models.Sequential): def __init__(self,n,m): super().__init__() for i in range(m): self.add(tf.keras.layers.Conv2D(filters = n, kernel_size=(3,3),strides=(1,1),padding = 'same',activation = "relu")) self.add(tf.keras.layers.MaxPool2D(pool_size = (2, 2))) class Dense(tf.keras.models.Sequential): def __init__(self,n,m=2): super().__init__() for i in range(m): This file has been truncated. show original
st206104
Thanks, it is because of version in tensorflow that when I change from 2.0 to 1.11 it works for me.
st206105
In many cases, it’s useful to train different layer groups with different learning rates. How do we achieve this with the stand keras.optimizers?
st206106
I don’t think that we have an off the shelf solution. Probably you could use a custom function with gradient_transformers 5
st206107
I am doing TensorFlow’s text generation tutorial and it says that a way to improve the model is to add another RNN layer. The model in the tutorial is this: class MyModel(tf.keras.Model): def __init__(self, vocab_size, embedding_dim, rnn_units): super().__init__(self) self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim) self.gru = tf.keras.layers.GRU(rnn_units, return_sequences=True, return_state=True) self.dense = tf.keras.layers.Dense(vocab_size) def call(self, inputs, states=None, return_state=False, training=False): x = inputs x = self.embedding(x, training=training) if states is None: states = self.gru.get_initial_state(x) x, states = self.gru(x, initial_state=states, training=training) x = self.dense(x, training=training) if return_state: return x, states else: return x And I tried adding a layer doing this: class MyModel(tf.keras.Model): def init(self, vocab_size, embedding_dim, rnn_units): super().init(self) self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim) self.gru = tf.keras.layers.GRU(rnn_units, return_sequences=True, return_state=True) self.gru2 = tf.keras.layers.GRU(rnn_units, return_sequences=True, return_state=True) self.dense = tf.keras.layers.Dense(vocab_size) def call(self, inputs, states=None, return_state=False, training=False): x = inputs x = self.embedding(x, training=training) if states is None: states = self.gru.get_initial_state(x) x, states = self.gru(x, initial_state=states, training=training) x, states = self.gru2(x, initial_state=states, training=training) x = self.dense(x, training=training) if return_state: return x, states else: return x The accuracy during training is above 90% but the text that it generates is nonsensical. What am I doing wrong? How should I add that new layer? Edit: This is an example of the text generated: Y gué el chme th ¡G : i uit: R dud d RR dududut ded,d!D! ties, is: y ui: iu,: ¡RRAShad wy…Ze…Zlegh Fither k.#É…WIkk.DR… t: W: R: IXII?IllawfGh…ZEWThedWe td y: W,Y,!:Z Edit 2: this is the tutorial I am following: TensorFlow Text generation with an RNN  |  TensorFlow 1 my code is essentially the same except for the new GRU layer
st206108
dsr: The accuracy during training is above 90% but the text that it generates is nonsensical. RNN/LSTMs are not the current state-of-the-art for natural language generation. For example, in the Google AI Blog: Reformer: The Efficient Transformer 8 post it says that: In the language domain, long short-term memory 1 (LSTM) neural networks cover enough context to translate sentence-by-sentence 7. In this case, the context window (i.e., the span of data taken into consideration in the translation) covers from dozens to about a hundred words. The more recent Transformer model 1 not only improved performance in sentence-by-sentence translation, but could be used to generate entire Wikipedia articles through multi-document summarization. This is possible because the context window used by Transformer extends to thousands of words. Have you tried any of the pre-trained Transformer-based models or trained one of your own? You may find the following posts and research papers useful: A Transformer Chatbot Tutorial with TensorFlow 2.0 — The TensorFlow Blog 2 T5: Google AI Blog: Exploring Transfer Learning with T5: the Text-To-Text Transfer Transformer (Colab - “Fine-Tuning the Text-To-Text Transfer Transformer (T5) for Closed-Book Question Answering”: Google Colaboratory). arXiv - [1910.10683] Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer (2019) Reformer: Google AI Blog: Reformer: The Efficient Transformer 8 ALBERT: Google AI Blog: ALBERT: A Lite BERT for Self-Supervised Learning of Language Representations BERT: Google AI Blog: Open Sourcing BERT: State-of-the-Art Pre-training for Natural Language Processing Fundamentals of Text Generation. This is an introductory tutorial on… | by Murat Karakaya | Deep Learning Tutorials with Keras | May, 2021 | Medium 1 (includes a lot of reference links).
st206109
Thank you for the links, I will look into them when I am more versed, right now I’m too noob for them. Nonetheless more than with the result of the text itself I’m interested in knowing what I’m doing wrong. Probably I didn’t explain it well but the text it gives seem more like a random series of letters than the result it should give. It’s not like random phrases it’s just random letters.
st206110
Have you already tried to reproduce a very minimal char-level text generation with your data? For a good step by step example see: keras.io Keras documentation: Character-level text generation with LSTM 3
st206111
Yes, I have done simpler text-generator. Using just one GRU or LSTM it works fine with the Shakespeare dataset, but I added more data and the model needed more complexity to learn so I added another layer and there is where my problem started. I insist, is with the two GRU where my problem is. I just want to know how it is supposed to be implemented the new GRU layer.
st206112
dsr: if states is None: states = self.gru.get_initial_state(x) x, states = self.gru(x, initial_state=states, training=training) x, states = self.gru2(x, initial_state=states, training=training) x = self.dense(x, training=training) if return_state: return x, states You treat GRU states as an intermediate output processed sequentially (you create some states, pass them to the first layer, get back new states, pass them to the second layer, then retrieve the final states…). But that’s not what RNN states are! They’re parallel, not sequential! The state of GRU2 is completely independent from the state of GRU1. If you want to do stateful processing, then you should be loading both states independently at the start of each batch (and also returning both states at the end). The good news is, a GRU has only has state vector, so the code will be a bit easier than if you were dealing with a LSTM, which has multiple state vectors. You’d do something like: if states is None: state1 = self.gru1.get_initial_state(x) state2 = self.gru2.get_initial_state(x) else: state1, state2 = states x, state1 = self.gru1(x, initial_state=state1, training=training) x, state2 = self.gru2(x, initial_state=state2, training=training) x = self.dense(x, training=training) if return_state: return x, [state1, state2]
st206113
I have done that and another problem emerged now, I dont know if you could help me with that. Apparently now the shapes are incompatible: ValueError: Shapes (64, 100) and (64, 100, 78) are incompatible I don’t know where that disonance comes from. If it helps my dataset is like this: <BatchDataset shapes: ((64, 100), (64, 100)), types: (tf.int64, tf.int64)> How could I fix this?
st206114
Hard to say since I don’t know what shapes these are. I recommend switching your entire model to the Functional API, you’ll find it much easier to debug. There’s no justification for using Model subclassing here. Basic version: inputs = Input(shape=...) x = layers.Embedding(vocab_size, embedding_dim)(inputs) x = layers.GRU(rnn_units, return_sequences=True)(x) x = layers.GRU(rnn_units, return_sequences=True)(x) outputs = layers.Dense(vocab_size)(x) model = Model(inputs, outputs) Version that allows state reinjection: inputs = Input(shape=...) initial_gru1_state = Input(shape=...) initial_gru2_state = Input(shape=...) x = layers.Embedding(vocab_size, embedding_dim)(inputs) x, state1 = layers.GRU(rnn_units, return_sequences=True, return_state=True)(x, initial_state=initial_gru1_state) x, state2 = layers.GRU(rnn_units, return_sequences=True, return_state=True)(x, initial_state=initial_gru2_state) outputs = layers.Dense(vocab_size)(x) model = Model(inputs, [outputs, state1, state2]) Untested code obviously, but going this route (the standard route) will make your life much easier.
st206115
It keeps giving me the same error: ValueError: Shapes (64, 100) and (64, 100, 78) are incompatible The 78 is the vocabulary size of the Embedding layer, 64 is the batch size and 100 is the sequence length.
st206116
Will you be able to share your code here, so it’d be easier to debug? Maybe via GitHub or a Colab notebook.
st206117
I redid my dataset from the beginning and now works. I don’t know what I previously did in the dataset but probably I reshape it or change something I shouldn’t. But now it works fine. Thank you
st206118
There seems to no support available for LSTM layer quantization. If one has to do Quantization of LSTM layers, what will be starting point ?
st206119
Hi, I think you can starts from Post training quantization : Post-training quantization  |  TensorFlow Lite 4 Unfortunately, Quantization aware training is not supports LSTM/RNN layers yet. (It just in the plan.) For your information, There’s known issue related to LSTM quantization: Can LSTM be fully quantized for inference? · Issue #25563 · tensorflow/tensorflow · GitHub 14
st206120
You can also check github.com google/qkeras 10 QKeras: a quantization deep learning library for Tensorflow Keras
st206121
How to extract last layers from SSD resnet Object Detection model after fine -tunning?
st206122
I’m following the tutorial here 1 to create a custom train_step. I’m trying to save some intermediate results (which are Tensor objects) inside a custom Model class with eager execution enabled. When I try something like tf.keras.backend.get_value(some_tensor), some_tensor.numpy() inside the train_step, I get an error that Tensor object has no attribute numpy. I’ve also tried some_tensor.eval(session = tf.compat.v1.Session()) and also got an error. I’m wondering if there’s any way to extract the value of tensors computed inside the train_step.
st206123
I’ve been using Tensorflow 2.4 and recently upgraded to 2.5 and got this warning, I know it’s only a warning but it’s rather odd as the rename just put it all on lowercase? Hoping someone has insight on the warning. WARNING - Function `_wrapped_model` contains input name(s) BP, BPA, CF, CP, CRS, Class, D, DIST, DLR, FU, JA, JT, LSC, LSD, LSL, LSP, LST, LSW, NR, P, Race, SP, SU, TA, TIM, TU, UP, WT with unsupported characters which will be renamed to bp, bpa, cf, cp, crs, class, d, dist, dlr, fu, ja, jt, lsc, lsd, lsl, lsp, lst, lsw, nr, p, race, sp, su, ta, tim, tu, up, wt in the SavedModel.
st206124
It was introduced with github.com/tensorflow/tensorflow Log info message if input name in function signature changes in SavedModel, which get converted here: https://github.com/tensorflow/tensorflow/blob/7e3a0d6be0e1c5f2c87d8552c092055d6340f596/tensorflow/core/framework/graph_to_functiondef.cc#L82-L93 34 committed Nov 5, 2020 +63 -3 Also clean up signature_serialization.canonicalize_signatures PiperOrigin-RevI…d: 340680532 Change-Id: Ia5794e5ead1171531ebd08a8234538add68d45d4 Just to inform the user when an input name Is normalized.
st206125
Hi folks. When using mixed precision to perform transfer learning with any hub model I run into the following error: ValueError: Could not find matching function to call loaded from the SavedModel. Got: Positional arguments (2 total): * Tensor("x:0", shape=(None, 224, 224, 3), dtype=float16) * False Keyword arguments: {} Expected these arguments to match one of the following 4 option(s): Option 1: Positional arguments (2 total): * TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='input_1') * True Keyword arguments: {} Option 2: Positional arguments (2 total): * TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='x') * False Keyword arguments: {} Option 3: Positional arguments (2 total): * TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='input_1') * False Keyword arguments: {} Option 4: Positional arguments (2 total): * TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='x') * True Keyword arguments: {} Is it a known issue? To reproduce this, just take this official example: Transfer learning with TensorFlow Hub 1 and add the following lines of code in the library imports: from tensorflow.keras import mixed_precision policy = mixed_precision.Policy('mixed_float16') mixed_precision.set_global_policy(policy) The data type of the last layer of the classifier should be float32. This is to prevent numeric instabilities, though. Also, to perform mixed-precision the compute capability of your GPU should be at least 7 or higher. V100 is a good example of this. Cc: @lgusm @kempy @markdaoust
st206126
Hi Sayak, This is expected behaviour as you cannot change number types that are saved on the SavedModel. The model publisher could publish a version with mixed precision and allow you to do what you want but I don’t know if anyone did that yet. From the docs 4: “Note: The data types used by a saved model have been fixed at saving time. Using tf.keras.mixed_precision etc. has no effect on the saved model that gets loaded by a hub.KerasLayer.”
st206127
I don’t know if a workaround like this one 7 could be used internally also for float32 to mixed_float16
st206128
Thanks, @Bhack. But the workaround needs us to first train the model with mixed-precision which in this case (TF-Hub) not supported it seems.
st206129
Yes I know that the example is the inverted case. What I meant is that if TFHUB knows internally how to rebuild the model I was guessing if that workaround f32_model.set_weights(model.get_weights()) could work also in this case. I’ve not tested this, It was just an hypotesis but if It works It could be similar to the cast in Mxnet: You can also fine-tune a model, which was originally trained in float32, to use float16 mxnet.apache.org Mixed precision training using float16 1 Mixed precision training using float16
st206130
Hey Sayak, I think if you want to see this supported in general, your best bet would be to file a GitHub issue against TensorFlow for a feature request to enable loading SavedModels with different precision than they were saved in.
st206131
A workaround is to temporarily change the global policy to float32 when loading, then change it back to mixed precision. For example: tf.keras.mixed_precision.set_global_policy('float32') # change policy *TRANSFER_MODEL = tf.keras.Sequential([ * hub.KerasLayer("https://tfhub.dev/tensorflow/efficientnet/b0/classification/1") * ]) *tf.keras.mixed_precision.set_global_policy('mixed_bfloat16') # change policy back
st206132
Hello, everyone! I am currently trying to use the TensorFlow model optimization library to reduce the memory footprint of the models my workplace is running in our production environment. Specifically, I am testing the tfmot.sparsity.keras.prune_low_magnitude API to prune model weights and get the model to a certain percentage of sparsity. I am very new to this topic and have so far had mixed results and so wanted to reach out to people who would know more about it and perhaps have actively used this tool before. So far I am trying to prune a very basic autoencoder-like model. I am not sure how to paste the code here, but here is a link to the same question I posted on SO stackoverflow.com Why is my pruned model larger than my base model when using Tensorflow's Model Optimization library to prune weights 1 python-3.x, keras, tensorflow2.0 asked by djvaroli on 02:16PM - 10 Jun 21 UTC The goal of this project I am working on is to reduce the file size of the model.pb protobuf file so that when that model is loaded in a Tensorflow Serving container, said container requires less memory to load and run the model and as a result, the cost associated with that container running in the cloud is also lower ( my logic is less RAM needed → smaller bill at the end). One thing I want to confirm is that I am correct in expecting that a pruned model with say 95% sparsity should have a lower file size when saved in SavedModel format as a protobuf file. If that is indeed correct, then I am not sure why if I run the same code (as can be seen in the link) but change the code dimension of the autoencoder, for lower values the protobuf file for the pruned model is indeed small, whereas for larger values of the code dimension the protobuf file for the pruned model actually stays the same or in some cases even takes up more space. I can sort of understand staying the same since the number weights actually remains same, however taking up more space makes no sense to me. It seems to me that something must be wrong, but each time the script is run I fully reset the environment. However, it is very possible I am just misunderstanding what weights pruning is meant to achieve and/or missing some very important implementation detail which is resulting in this sort of behavior. I have unfortunately not been able to find much online about optimizing production models meant for TF Serving outside of quantization and storing models as tflite. However, since, as I understand, TF Serving does not work with tflite models, that is not very useful to me. I have been banging my head on the table with this problem for a while now so any help would be much much appreciated.
st206133
While converting a model using tflite, I want to understand the internal block diagram of it. How the conversion is taking place. Is there internal pruning happening in it ?? If yes, then does it make sense to prune a network beforehand ??
st206134
Generally I suggest you to select tags and category from the menu on a new thread cause specialized technical team members could be subscribed only to a tag subset (e.g. in this case I suggest tflite and docs)
st206135
Completely agree with @Bhack on this. TensorFlow Lite and TensorFlow Model Optimization Toolkit have very well documentation and tutorials. They are the first-hand resource.
st206136
The pruning is not happening during the tf-lite conversion. To add sparsity, your model need to be updated by following a specific procedure - Please refer the official guide. Pruning in Keras example  |  TensorFlow Model Optimization 3
st206137
If you are interested about pruning for latency on TFLite you can follow or ask an update at: github.com/tensorflow/model-optimization Sparsity Runtime Integration with TF/TFLite for Latency Improvements 11 opened Dec 6, 2019 alanchiao feature request technique:pruning As suggested [here](https://www.tensorflow.org/model_optimization/guide/pruning)…, model pruning currently only provides benefits in model compression/size reduction. Further framework support is necessary to provide latency improvements in TF/TFLite.
st206138
We are a group of 4 people from Padova University, studying computer engineering. The University assigned us a project that concern the analysis an open source code, and we choose your project. We have some quick questions about the project, and we wonder if some of the original developers were available to answer them. If this is the wrong place to ask, please give us the right contact
st206139
The purpose of our project is to do an analysis of the production process and an analysis of the evolution of the code according to the CK LOC and CC metrics. What we would like to ask you is if you could answer some questions written by us.
st206140
@Toma , I would suggest you to post all your questions here with the numbers and whoever may have worked on specific part for particular question can answer it.
st206141
Questions: How was your approach to the project? ● How much time did you spend on developing the first working version of your project? ● How many people worked on the project in the beginning? Has this number changed over time? ● Have the roles of developers in general always been the same or have they changed over time? (ex. frontend/backend) ● Has the project’s strategy changed over time? 1. Was everything decided at the beginning and then you implemented the project? 2. Have you moved step by step, thinking of one feature at a time? 3. have you all worked on the same feature or have you divided the features into subgroups? ● Did any problems arise during development? If so, how were they solved? Did you build the project based on other existing projects, or was it a new idea? ● If it was new, what prompted you to create it? Necessity/Utility… How did you test the code? ● Have you used special testing software? And if so, which ones? ● How often did you test the code? (ex.after each class/method/feature) ● Did you ask developers outside the project to test the code or did you do it? Code management: ● Did you rather make the code less optimized but more “readable” or did you focus on maximum efficiency while ignoring readability? ● Did you prefer to release as soon as possible or did you go quietly to have a code as perfect as possible? As an open source project, have you taken advice from other people? (curiosity) How do you manage the costs? Have you received financial help(like crowd-funding or something else) from other people? Thank you for your time, Marco, Andrea, Andrea, Riccardo
st206142
We already have @ewilderj @thea in the thread. I also add @yarri-oss. I hope they could give you a feedback soon.
st206143
I think many of these answers can be found quite easily, and others aren’t really as applicable to a project like TensorFlow. I think you might have a better time studying a more typical open source project such as curl. I’m really sorry but I just don’t have time to go through the questions in detail, we tend to receive questionnaires like this on a relatively frequent basis. If anyone wanted to work on a “History of TensorFlow” doc, I would definitely be up for contributing and getting answers for that, so we would be able to have something definitive.
st206144
@ewilderj , I would love to work on that doc and also want to know in depth. Can you please point me to the starting point? I would just require a starting point (Doc, code, email thread, google group thread, discussion anything would work). Please point me to anything that you know of and I will get started.
st206145
Google AI Blog TensorFlow - Google’s latest machine learning system, open sourced for everyone 3 Posted by Jeff Dean, Senior Google Fellow, and Rajat Monga, Technical Lead Deep Learning has had a huge impact on computer science, making... But you really need to start from the origin of DistBelief
st206146
I am Lamar Van Dusen from Alberta and Kindly tell me what is the purpose of this Tensorflow website. What is tensor flow used for, kind regards
st206147
#help_request #tfdf I can’t seem to be able to make prediction using a tfdf model, I’m working in colab and I obtain an “assertion error” anytime I try using something like model(Xtest) or model.predict(Xtest) while everything seems to go smooth up to that point. Any idea of what goes wrong ? Thanks, Cristelle.
st206148
Hi Cristelle, can you post the code you used? Using the beginner colab 5, after the cell with model_1.save(…) (in the section Prepare this model for TensorFlow Serving) I’ve tried this: for r in test_ds.take(1): print(model_1(r[0])) And I got the expected predictions
st206149
indeed it works this way! thanks a lot! I guess I was feeding in the wrong data types… Here’s my code, and there are probably a lot of more than awkward things… If anyone has the time to comment on that, that would be much helpful. I was trying to use the iris dataset: import tensorflow_decision_forests as tfdf import pandas as pd from sklearn.datasets import load_iris data2 = load_iris(as_frame=True) df = pd.DataFrame(data = data2.data) allcol = df.columns i = 0 for cn in allcol: df =df.rename(columns={cn:str(i)}) i +=1 df_class = pd.DataFrame(data = data2.target) complete_df = pd.concat([df, df_class], axis=1) complete_df = complete_df.sample(frac=1) train_df = complete_df[:100] test_df = complete_df[100:] train_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_df, label="target") test_ds = tfdf.keras.pd_dataframe_to_tf_dataset(test_df, label="target") model = tfdf.keras.RandomForestModel() model.fit(train_ds) Xtest = test_df.iloc[:,:4] ytest = test_df.iloc[:,4] y_hats = model.predict(Xtest) Thanks a lot Cristelle
st206150
Great to hear that it works . Thanks for the code snippet. Some of the error messages are certainly not explicit enough. We will improve that in the next TF-DF release. Regarding your example, the issue is that Xtest is a Pandas dataframe, while predict expects a TensorFlow dataset, a Numpy array or a Tensor (or one of the more exotique formats such as DatasetCreator). Your code could be re-written as follow: import tensorflow_decision_forests as tfdf import pandas as pd from sklearn.datasets import load_iris iris_frame = load_iris(as_frame=True) iris_dataframe = pd.DataFrame(data = iris_frame.data) iris_dataframe["species"] = iris_frame.target # Replace the spaces by "_" in the feature names. iris_dataframe = iris_dataframe.rename(columns=lambda x: x.replace(" ","_")) # Shuffle the dataset iris_dataframe = iris_dataframe.sample(frac=1) # Train/Test split. train_dataframe = iris_dataframe[:100] test_dataframe = iris_dataframe[100:] # Converts from Pandas dataframes to TensorFlow datasets. train_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(train_dataframe, label="species") test_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(test_dataframe, label="species") # Train the model. model = tfdf.keras.RandomForestModel() model.fit(train_dataset) # Generate the predictions. model.predict(test_dataset) Keras also directly supports the consumption of Numpy arrays. This option is less powerful than Pandas Dataframes, but in your case, it leads to a more compact code: import tensorflow_decision_forests as tfdf import pandas as pd from sklearn.datasets import load_iris iris_frame = load_iris() features = iris_frame.data labels = iris_frame.target # Shuffle the examples. permutations = np.random.permutation(features.shape[0]) features = features[permutations] labels = labels[permutations] train_features = features[:100] train_labels = labels[:100] test_features = features[100:] test_labels = labels[100:] model = tfdf.keras.RandomForestModel() model.fit(x=train_features, y=train_labels) model.predict(test_features) Cheers, Edit: Shuffle the examples before the train/test split.
st206151
Happy to help. The Iris examples returned by sklearn are grouped by classes. Therefore, the :100 vs 100: split would be of poor quality for a train/test evaluation. Shuffling the examples before the split solves the issue. The example above was edited accordingly.
st206152
Hello everyone, I’m learning about GAN and I like to know more about how to create multiple images from a different set of assets like Bored Ape Yacht Club Marketplace on OpenSea: Buy, sell, and explore digital assets 2 thanks
st206153
I encountered error while working on tensorflow ValueError: Items of feature_columns must be a _FeatureColumn. Given (type <class ‘tensorflow_hub.feature_column_v2._TextEmbeddingColumnV2’>): _TextEmbeddingColumnV2(key=‘sentence’, module_path=‘TensorFlow Hub 1’, output_key=None, trainable=False), can anyone help me?
st206154
Possible to provide the code? Otherwise, it’s difficult to get a sense of what’s going wrong.
st206155
Ideally please provide a small python script that demonstrates the bug. This shouldn’t be your whole program, instead it should be an example script that reproduces the issue in as little code as possible. That makes it easier to debug. If it’s under, say, 100 lines, it might be reasonable to post that directly here in the forum. If it’s longer, consider sharing a public GitHub repo or a Colab. It would also help to include which versions of Tensorflow and TF Hub you are using.
st206156
Hello Everyone Hi, so i have been building a Django project in python for the last two months and have got everything ready from user registration to file upload. Now my LAST part left is the following. A User clicks an image on site which then drops down and shows similar results of that image. How can i achieve that ? I want to fetch the results from the Database back-end of python (Will use the async Fetch function for that ) and the add Event listener for clicking an Image. Will Really Need Your Help. Thanks Will TensorFlow.js be suitable? I am a newbie at this. So far I know the Following: i have got the concept, that is extract the features and then compare histograms and display similar results. is there an example in java script. i tried finding it. just could not get it any where mostly i found is image resizing Will it be better to do it in the back end or use JavaScript ? Sorry for Noob Question
st206157
You’re in the right direction regarding the features. My first try would be to extract the image feature vector and use it (instead of the text embeddings) shown in this tutorial: Semantic Search with Approximate Nearest Neighbors and Text Embeddings 2
st206158
hi thanks you so much for the reply. I will check that link out, Hey do you have any experience with opencv? SO far i have got the edges of the two images using canny method, but now what next should i do to compare my images ? Here is the code, Can you Please Help Out: import cv2 import os import numpy as np import matplotlib.pyplot as plt img1 = cv2.imread("1-Flip-flops.jpg",0) img2 = cv2.imread("29-Leather mules.jpg",0) edges1 = cv2.Canny(img1, threshold1=30, threshold2=100) edges2 = cv2.Canny(img2, threshold1=30, threshold2=100) print(edges1) plt.imshow(edges1, cmap = "gray") plt.show() plt.imshow(edges2, cmap = "gray") plt.show()
st206159
Try to give pass to TensorFlow How to match images using DELF and TensorFlow Hub 2 It is not clear what is your specific context so this tutorial is about image retrieval with landmarks and it could be a good baseline. See also on the same TFHub model: https://www.dlology.com/blog/easy-landmark-image-recognition-with-tensorflow-hub-delf-module/ 1
st206160
Hi thanks for the recommended article, the nearest neighbor i have to find for similar images. Can you also check my opencv code above ? I am trying to match or find similar images of shoeswear that I scrapped from Shoe retailers online. I have detected the edges but now what? Sorry if wrong forum,
st206161
You need to follow and understand some basic examples e.g. with MNIST and then reproduce it for your dataset. For a complete basic example see: PyImageSearch – 30 Mar 20 Autoencoders for Content-based Image Retrieval with Keras and TensorFlow -... 1 Learn how to use convolutional autoencoders to create a Content-based Image Retrieval system (i.e., image search engine) using Keras and TensorFlow. Est. reading time: 25 minutes
st206162
BERT is available in TFJS for question answering but can also it be used as a sentence encoder? USE is getting pretty old and my impression is that BERT is better for the same task. Is it?
st206163
I don’t know if you need exactly BERT for your project but if you want something ready we have many USE models available in TensorFlow Hub 25 Here you can find conversion commands for TFjs: TensorFlow Importing a TensorFlow GraphDef based Models into TensorFlow.js 5
st206164
Thanks. Do you know how those USE models compare to the one in the tfjs-models on TensorFlow GitHub that has already been converted?
st206165
Here are some resources: Towards DataScience Blog 19 universal-sentence-encoder for tfjs on github 10 Directly usable model on tfhub as mentioned by @Bhack 9 NPM package for using in JS app directly 9
st206166
If you click the TFHub link in that Readme you can see that it is the USE light on TFHub
st206167
I’m getting the idea that I should stay with USE (and forget about BERT) but in deciding which TFHub USE version, instead of finding any performance comparisons, I find the sentence “We apply this model to the STS benchmark for semantic similarity, and the results can be seen in the example notebook made available.” So, if I want to use benchmarks to decide if it is worth trying different sizes of USE do I need to run this notebook to generate my own benchmarks? The paper by Cer et al lists some benchmarks but not for different sizes of USE. I don’t even find a table listing the number of parameters for each of the USE variants.
st206168
This is a great repo for comparison between different embeddings, language models, techniques, etc. for sentence embeddings: github.com TharinduDR/Simple-Sentence-Similarity 119 Exploring the simple sentence similarity measurements using word embeddings They also have a notebook for USE metrics so you can compare that with the rest of that metrics table.
st206169
Hi guys, i’m trying to use my GPU(Nvidia GeForce 540M) with Tensorflow. I’ve installed CUDA 6.5 but it seems not be supported by tensorflow. I’ve seen that is mandatory to have cuDNN Can anyone help me?
st206170
Hello @Luca_Zanetti You may need to create an NVIDIA Developer Account, if you don’t have one already, before downloading cuDNN. (Requirements: GPU support  |  TensorFlow 8 This tutorial showing how to install CUDA, cuDNN, etc by a TensorFlow user seems to be getting some good feedback, you may find this useful: https://youtu.be/hHWkvEcDBO0?t=144 7 Keep us posted and good luck!
st206171
One more thing @Luca_Zanetti - for TensorFlow 2.5 with GPU support, you’ll need: CUDA 11.2 cuDNN SDK 8.10 NVIDIA drivers 450.80.02 or higher [UPDATED - see GPU support  |  TensorFlow 8 for the latest info] (The docs are being updated.) Thanks for the writing a blog post about this, @ashutosh1919. Can you check the link you shared?
st206172
Tensorflow 2.5 with GPU device (Python 3.9, Cuda 11.2.2 , Cudnn 8.1.1) Conda environment - Windows 10 General Discussion I want to share the procedure to work with your GPU with the new stable version of tensorflow 2.5 in case someone is having problems with the update. I have noticed an improvement in training time. According to official information https://github.com/tensorflow/tensorflow/releases Procedure: Install Anaconda with Python 3.9 source: https://docs.conda.io/en/latest/miniconda.html Install the latest version of your GPU driver. Install Cuda Toolkit 11.2.2 source: https://developer.nvi… (TF 2.5 with conda on Windows 10 - by @Ricardo)
st206173
It seems the problem is with the GPU CUDA compute capability. My GPU have a compute capability of 2.1 but probably tensorflow need at least 3.0 can anyone confirm this?
st206174
Hi @Luca_Zanetti - here are the requirements: GPU support  |  TensorFlow 1 Luca_Zanetti: My GPU have a compute capability of 2.1 Is your GPU listed here? CUDA GPUs | NVIDIA Developer 7
st206175
Based on this information, it looks like it’s not supported @Luca_Zanetti Have you considered Google Colab (free) or Colab Pro 3 (more details: Google Colaboratory 3)? Luca_Zanetti: GeForce GT 540M Great graphics card 540m on Alienware-M11x | Dell 1
st206176
Yes, i’m using Google Colab now. I was trying to set up also my pc with GPU in order to not depend only on network connection and run locally sometimes. Thank you
st206177
This is based on: tensorflow-mnist-vae/mnist_vae.ipynb at master · CharlesD1ng/tensorflow-mnist-vae · GitHub In my model.py, I have: class model(): def __init__(self): self.X = tf.placeholder(dtype=tf.float32, shape=[None, 28, 28], name='X') self.keep_prob = tf.placeholder(dtype=tf.float32, shape=(), name='keep_prob') def encoder(self): #I'm using self.X here to find z ... return self.X, self.keep_prob, z, mn, sd def decoder(self, z): #I'm using z (generated in encoder) to find image ... return image def loss(self, image, sd, mn):#I'm using image generated by decoder and the original image self.X ... return loss def optimizer(self, loss, lr): #Call optimizer by using loss and learning rate. ... return optimizer In my training.py, I want to train the model that I defined in model.py. Therefore I have: mnist = input_data.read_data_sets('MNIST_data') lr = 0.005 model = model() X, keep_prob, z, mn, sd = model.encoder() decoder = model.decoder(z) loss = model.loss(decoder, sd, mn) optimizer = model.optimizer(loss, lr) sess = tf.Session() sess.run(tf.global_variables_initializer()) for epoch in range(epoch_number): batch = [np.reshape(b, [28, 28]) for b in mnist.train.next_batch(batch_size=batch_size)[0]] loss_, _ = sess.run([loss, train_optimizer], feed_dict={X: batch, keep_prob: 0.8}) print("iteration: {}, overall_loss: {}".format(epoch, loss_)) Actually my question is related to that point: model = model() X, keep_prob, z, mn, sd = model.encoder() decoder = model.decoder(z) loss = model.loss(decoder, sd, mn) optimizer = model.optimizer(loss, lr) I’m new on tensorflow and not sure if it is the right way to train a model in tensorflow 1. I saw something scope, variable, get_collection things and a little bit confused. Is it the right way of training a model? Because, if it is the case. After saving my model, to generate new images using this decoder that I trained, I have some difficulties. In a similar way, to test my model that I saved, in test.py, I do: model = model() X, keep_prob, z, mn, sd = model.encoder() decoder = model.decoder(z) saver = tf.train.Saver() sess = tf.Session() saver.restore(sess, 'model.pk') randoms = [np.random.normal(0, 1, intermediate_dim) for _ in range(100)] images = sess.run(dec, feed_dict = {z: randoms, keep_prob: 1.0}) k = [np.reshape(imgs[i], [28, 28]) for i in range(len(images ))] In this writing style, to use decoder I need to call encoder. If I do not call it, it will not know the variable z. See: X, keep_prob, z, mn, sd = model.encoder() decoder = model.decoder(z) Do you have any idea about what is the right way to use different .py files while training a deep learning network using tensorflow 1. Thank you in advance.
st206178
I suggest you to start with TF 2 directly. Take a look at TensorFlow Convolutional Variational Autoencoder  |  TensorFlow Core 2
st206179
thank you for your suggestion but I need to solve this problem by using tensorflow 1. It is some how obligatory for me.
st206180
I strongly suggest you to use TF 2 cause it will be quite hard to receive support on TF 1.x. In any case this was an old TF1 tutorial on VAE/MNIST. https://danijar.com/building-variational-auto-encoders-in-tensorflow/ 1
st206181
Hi @john123 Do you have the full project maybe stored in a public repo or can you post it all here? Maybe we could try to provide feedback / debug it for you if we can replicate fully. Thanks!
st206182
hi @8bitmp3, actually I’m trying to separate this ipynb file (https://github.com/CharlesD1ng/tensorflow-mnist-vae/blob/master/mnist_vae.ipynb. ) into model.py, train.py and test.py.
st206183
john123: tensorflow-mnist-vae/mnist_vae.ipynb at master · CharlesD1ng/tensorflow-mnist-vae · GitHub. For TF 1, maybe you can adapt this code: VAE-Tensorflow/src at master · ChengBinJin/VAE-Tensorflow · GitHub 2 And, in comparison, this TF 2 code circa December 2019 is quite clean: Deep-Learning-with-TensorFlow-2-and-Keras/VAE.ipynb at master · sujitpal/Deep-Learning-with-TensorFlow-2-and-Keras · GitHub 4
st206184
I’m trying to test out hash embeddings ([1709.03933] Hash Embeddings for Efficient Word Representations 2) on skipgrams and while I’m searching for parameters it seems like my data pipeline is my biggest bottleneck. I’ve tried computing skipgrams on the fly which is quite slow, and also writing positive pairs to TFRecords, computing NCE negative samples on the fly but this is very storage-intensive and requires a lot of preprocessing. What’s the current state of the art for producing skipgrams to keep up with an embedding training?
st206185
Hi, I’m trying to implement an RoI pooling layer in Keras. I have a reference implementation based on multiple nested tf.map_fn calls that works correctly but is incredibly slow (I can’t stop TF from re-tracing each time, apparently). I tried a more naive and simpler approach using a for-loop directly. But I don’t understand how Keras executes this. When I build a simple single-layer test model to unit test my layer, it works just fine: input_map = Input(shape = (9,8,num_channels)) # input map size input_rois = Input(shape = (num_rois,4), dtype = tf.int32) # N RoIs, each of length 4 (y,x,h,w) output_roi_pool = RoIPoolingLayer(pool_size = pool_size)([input_map, input_rois]) roi_model = Model([input_map, input_rois], output_roi_pool) ... x = [ x_maps, x_rois ] y = roi_model.predict(x = x) During training, where I have a more complex model (FasterRCNN) and I have to call train_on_batch(), something is not right. I’ve tried a few different ways to print out the outputs of the layer but it’s not clear what is happening. Sometimes I get values, sometimes I get 0’s. Here is my code: class RoIPoolingLayer(Layer): """ Input shape: Two tensors [x_maps, x_rois] each with shape: x_maps: (samples, height, width, channels), representing the feature maps for this batch, of type tf.float32 x_rois: (samples, num_rois, 4), where RoIs have the ordering (y, x, height, width), all tf.int32 Output shape: (samples, num_rois, pool_size, pool_size, channels) """ def __init__(self, pool_size, **kwargs): self.pool_size = pool_size super().__init__(**kwargs) def get_config(self): config = { "pool_size": self.pool_size, } base_config = super(RoIPoolingLayer, self).get_config() return dict(list(base_config.items()) + list(config.items())) def compute_output_shape(self, input_shape): map_shape, rois_shape = input_shape assert len(map_shape) == 4 and len(rois_shape) == 3 and rois_shape[2] == 4 assert map_shape[0] == rois_shape[0] # same number of samples num_samples = map_shape[0] num_channels = map_shape[3] num_rois = rois_shape[1] return (num_samples, num_rois, self.pool_size, self.pool_size, num_channels) def call(self, inputs): return tf.map_fn( fn = lambda input_pair: _RoIPoolingLayer._compute_pooled_rois(feature_map = input_pair[0], rois = input_pair[1], pool_size = self.pool_size), elems = inputs, fn_output_signature = tf.float32 # this is absolutely required else the fn type inference seems to fail spectacularly ) def _compute_pooled_rois(feature_map, rois, pool_size): num_channels = feature_map.shape[2] num_rois = rois.shape[0] if num_rois == None: return tf.zeros(shape=(tf.shape(rois)[0],pool_size, pool_size, num_channels)) pools = [] for roi_idx in range(num_rois): region_y = rois[roi_idx, 0] region_x = rois[roi_idx, 1] region_height = rois[roi_idx, 2] region_width = rois[roi_idx, 3] region_of_interest = tf.slice(feature_map, [region_y, region_x, 0], [region_height, region_width, num_channels]) x_step = tf.cast(region_width, dtype = tf.float32) / tf.cast(pool_size, dtype = tf.float32) y_step = tf.cast(region_height, dtype = tf.float32) / tf.cast(pool_size, dtype = tf.float32) for y in range(pool_size): for x in range(pool_size): pool_y_start = y pool_x_start = x pool_y_start_int = tf.cast(pool_y_start, dtype = tf.int32) pool_x_start_int = tf.cast(pool_x_start, dtype = tf.int32) y_start = tf.cast(pool_y_start * y_step, dtype = tf.int32) x_start = tf.cast(pool_x_start * x_step, dtype = tf.int32) y_end = tf.cond((pool_y_start_int + 1) < pool_size, lambda: tf.cast((pool_y_start + 1) * y_step, dtype = tf.int32), lambda: region_height ) x_end = tf.cond((pool_x_start_int + 1) < pool_size, lambda: tf.cast((pool_x_start + 1) * x_step, dtype = tf.int32), lambda: region_width ) x_size = tf.math.maximum(x_end - x_start, 1) pool_cell = tf.slice(region_of_interest, [y_start, x_start, 0], [y_size, x_size, num_channels]) pooled = tf.math.reduce_max(pool_cell, axis=(1,0)) # keep channels independent print(pooled) pools.append(pooled) return tf.reshape(tf.stack(pools, axis = 0), shape = (num_rois, pool_size, pool_size, num_channels)) Note the print statement. During execution, it sometimes returns a numeric tensor but most of the time returns unevaluated tensors: Tensor("model_3/roi_pool/map/while/Max:0", shape=(512,), dtype=float32) Tensor("model_3/roi_pool/map/while/Max_1:0", shape=(512,), dtype=float32) Tensor("model_3/roi_pool/map/while/Max_2:0", shape=(512,), dtype=float32) Tensor("model_3/roi_pool/map/while/Max_3:0", shape=(512,), dtype=float32) Tensor("model_3/roi_pool/map/while/Max_4:0", shape=(512,), dtype=float32) Tensor("model_3/roi_pool/map/while/Max_5:0", shape=(512,), dtype=float32) ... No idea what is going on. I thought TF2 would use eager execution for this sort of code but I guess not. It appears to be building a graph sometimes (but not on every step) but then the graph does not seem to be executed correctly. I’m happy to share more code. I’m at a complete loss as to how to get this to work. I would expect that if no error is thrown, this should execute correctly, but instead it is doing something difficult for me to comprehend. Inspecting the layer at run-time seems to disturb the result. As far as I know, it requires a function evaluation, which I believe forces execution of the graph (?) and gives me what appears to be the right result. However, that is clearly not what is actually happening during training. Any ideas how I can make this work? All the examples of RoI pooling in Keras online are either painfully slow (multiple layers of tf.map_fn) or don’t work (there are other old for-loop-based examples similar to this one).
st206186
@Bhack could you provide a minimal example of tfa.image.compose_transforms()? TensorFlow tfa.image.compose_transforms  |  TensorFlow Addons 14 Composes the transforms tensors.
st206187
Here you have rotation + translation github.com tensorflow/addons/blob/master/tensorflow_addons/image/tests/transform_ops_test.py#L41-L55 11 def test_compose(dtype): image = tf.constant( [[1, 1, 1, 0], [1, 0, 0, 0], [1, 1, 1, 0], [0, 0, 0, 0]], dtype=dtype ) # Rotate counter-clockwise by pi / 2. rotation = transform_ops.angles_to_projective_transforms(np.pi / 2, 4, 4) # Translate right by 1 (the transformation matrix is always inverted, # hence the -1). translation = tf.constant([1, 0, -1, 0, 1, 0, 0, 0], dtype=tf.dtypes.float32) composed = transform_ops.compose_transforms([rotation, translation]) image_transformed = transform_ops.transform(image, composed) np.testing.assert_equal( [[0, 0, 0, 0], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 1, 1]], image_transformed.numpy(), )
st206188
Thanks but in practice what are we supposed to be providing to compose_transforms()? Something like the following? compose_transforms([tf.image.rot90, tf.image.random_flip_left_right]) If so, how it’s supposed to be applied to an image or a batch of images? From the documentation and also the test-case shared above, these questions are not clear.
st206189
Internally it is just a matmul loop over single projective tranfroms matrix in the list (or batched): github.com tensorflow/addons/blob/master/tensorflow_addons/image/transform_ops.py#L177:L179 12 name: The name for the op. Returns: A composed transform tensor. When passed to `transform` op, equivalent to applying each of the given transforms to the image in order. """ assert transforms, "transforms cannot be empty" with tf.name_scope(name or "compose_transforms"): composed = flat_transforms_to_matrices(transforms[0]) for tr in transforms[1:]: # Multiply batches of matrices. composed = tf.matmul(composed, flat_transforms_to_matrices(tr)) return matrices_to_flat_transforms(composed) def flat_transforms_to_matrices( transforms: TensorLike, name: Optional[str] = None ) -> tf.Tensor: """Converts projective transforms to affine matrices.
st206190
Sadly, I am still not clear as to how to use it with a dataset or even a single image having a leading batch dimension.
st206191
That method is just going to compose projective transformations. The real transformation is in transform that is still quite duplicated in addons cause the transform in TF is still a private API (but the transform Matrix format is the same). See the thread starting at Cannot run model.fit locally (help) General Discussion And it looks like, similar to the keras.preprocessing implementation, all those layers.experimental.preprocessing layers use this transform function which just takes a projection matrix: So I think you’d just need to work out the right range of matrices there. Maybe there’s something you can copy from the keras.preprocessing version. Or maybe someone’s already done all that work.
st206192
Here’s a shot example applying the composition on a standard image: colab.research.google.com Google Colaboratory 16
st206193
This is the same with internals from tensorflow.python.keras.layers.preprocessing.image_preprocessing import transform .... image_transformed = transform(tf.expand_dims(image, axis=0),composed)
st206194
E.g. the internal one was used in transformations that support models in model gardens SIG. github.com tensorflow/models/blob/master/official/vision/beta/ops/augment.py 11 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # 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. """AutoAugment and RandAugment policies for enhanced image/video preprocessing. AutoAugment Reference: https://arxiv.org/abs/1805.09501 RandAugment Reference: https://arxiv.org/abs/1909.13719 """ import math This file has been truncated. show original These transformations are available for users in PyPI tf-models-official 9 TensorFlow Official Models Most of the transformations available in Addons I think that are duplicated now.
st206195
Cool. But I think we both could agree that the documentation does not clearly reflect on these points. I guess we cannot expect the majority of users to dig into the source code and figure their way out into using these.
st206196
Yes probably some documentation is missing but I think that we can build a clear path and better documentation or tutorials when we will unify a little bit the image processing API that currently it is quite duplicated or sparse in the ecosystem (also generally we cannot promote private API to the end users like from tensorflow.python). The modern history of this in Addons/Ecosystem it is already quite old: github.com/tensorflow/addons Migrate AutoAugment and RandAugment to TensorFlow Addons. 7 opened Mar 5, 2020 closed May 28, 2020 dynamicwebpaige Feature Request help wanted image **Describe the feature and the current behavior/state.** RandAugment and AutoAu…gment are both policies for enhanced image preprocessing that are included in EfficientNet, but are still using `tf.contrib`. https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py The only `tf.contrib` image operations that they use, however, are [rotate](https://www.tensorflow.org/addons/api_docs/python/tfa/image/rotate), [translate](https://www.tensorflow.org/addons/api_docs/python/tfa/image/translate) and [transform](https://www.tensorflow.org/addons/api_docs/python/tfa/image/transform) - all of which have been included in TensorFlow Addons. **Relevant information** - Are you willing to contribute it (yes/no): No, but am hoping that someone from the community will pick it up (potentially a Google Summer of Code student)? - Are you willing to maintain it going forward? (yes/no): Yes - Is there a relevant academic paper? (if so, where): AutoAugment Reference: https://arxiv.org/abs/1805.09501 RandAugment Reference: https://arxiv.org/abs/1909.13719 - Is there already an implementation in another framework? (if so, where): See link above; this would be a standard migration from `tf.contrib`. - Was it part of tf.contrib? (if so, where): Yes **Which API type would this fall under (layer, metric, optimizer, etc.)** Image **Who will benefit with this feature?** Anyone doing image preprocessing, especially for EfficientNet. github.com/tensorflow/addons [1/2] Add Image Ops for Data Augmentation 5 opened Mar 18, 2020 closed May 28, 2020 abhichou4 Feature Request good first issue help wanted image Part 2: https://github.com/tensorflow/addons/issues/1353 As part of #1226, re…levant image ops need to be added to `tfa.image`. List of ops tracked in this issue (tick the op only once the corresponding PR is *merged*): - [x] Blend - [x] CutOut - [ ] Identity - [x] Translate X, Y - [x] Shear X, Y - [ ] Solarize Ops - [ ] Posterize - [ ] AutoContrast - [x] Equalize - [ ] Invert - [ ] Color - [ ] Brightness - [x] Sharpness Reference: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py
st206197
Hello, I’m unable to install tensorflowjs for node on raspberry pi. When I install tfjs-node, and run it: Welcome to Node.js v14.16.0. Type ".help" for more information. > const tf = require('@tensorflow/tfjs'); undefined > require('@tensorflow/tfjs-node') node-pre-gyp info This Node instance does not support builds for Node-API version 8 node-pre-gyp info This Node instance does not support builds for Node-API version 8 Uncaught: Error: /home/pi/program/nanocptscenariorunner/node_modules/@tensorflow/tfjs-node/lib/napi-v7/tfjs_binding.node: wrong ELF class: ELFCLASS64 at Object.Module._extensions..node (internal/modules/cjs/loader.js:1122:18) at Module.load (internal/modules/cjs/loader.js:928:32) at Function.Module._load (internal/modules/cjs/loader.js:769:14) at Module.require (internal/modules/cjs/loader.js:952:19) at require (internal/modules/cjs/helpers.js:88:18) > When doing npm rebuild @tensorflow/tfjs-node .... gyp verb node dev dir /home/pi/.cache/node-gyp/14.16.0 gyp verb `which` succeeded for `make` /usr/bin/make gyp info spawn make gyp info spawn args [ 'V=1', 'BUILDTYPE=Release', '-C', 'build' ] ../binding/tfjs_backend.cc: In function ‘TFE_TensorHandle* tfnodejs::CreateTFE_TensorHandleFromStringArray(napi_env, int64_t*, uint32_t, TF_DataType, napi_value)’: ../binding/tfjs_backend.cc:196:64: error: ‘TF_TString’ was not declared in this scope array_length * sizeof(TF_TString))); ^~~~~~~~~~ ../binding/tfjs_backend.cc:198:15: error: ‘t’ was not declared in this scope .... Nodejs: 14.13 Raspbian lite strech Raspberry 3 armv7l ==> 32 bits
st206198
Hey! I have just recently started with TF and ML in general and wanted to use random forest on our dataset. I was pretty excited when I saw that there was finally something out for the newer version (compared to having to run TF 1.15) and a great guide to it, however I am already struggling at the first steps (I am rather new to docker and linux as well). My issue is: when I use the tensorflow/tensorflow:latest-jupyter, I get an error when trying the “pip install -q tensorflow_decision_forests” WARNING: The candidate selected for download or install is a yanked version: ‘tensorflow-decision-forests’ candidate (version 0.0.0 at https://files.pythonhosted.org/packages/9b/c2/5b5d8796ea5cb8c19457cd9b563c71b536ffc3d14936049fa9cf49b31dcf/tensorflow_decision_forests-0.0.0-py3-none-any.whl#sha256=18ed810f415437ef8e8a4848d3cbf2cff51e3ea2b66224b75f9d9c0f689629a7 2 (from Links for tensorflow-decision-forests)) Reason for being yanked: and then when trying to import it, it obviously says cannot find decision-forests module. I looked at the newer versions of the decision forests module, but they only seem to be python 3.7 or higher, the container however runs 3.6? When I tried upgrading python it kinda broke everything else in it, so I am not sure what to do. It would be great if anyone has a solution to this!
st206199
I am trying to update also the jupyter (devel) image with this PR Update TF official devel images to Ubuntu 20.04 and precommit hooks by bhack · Pull Request #48371 · tensorflow/tensorflow · GitHub 1 Problably we could also upgrade the non devel Docker image if this will be merged.