id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st206200 | I see! I got it to work in Colab now which works for now, I am not sure how to add a validation set to it though (so have train, validation and test), any ideas?
Thanks a bunch! |
st206201 | You can use the selfvalidation or validation in fit for metrics. See decision-forests/beginner_colab.ipynb at main · tensorflow/decision-forests · GitHub 8 |
st206202 | The error was caused by the absence of the TF-DF pip package for py3.6. This is now solved 8. Thanks for the alert :).
Others might see the same error if they try to install TF-DF via pip on Windows or MacOS – we’re working on releasing those soon, and will update our Known Issues 6 docs when we do! |
st206203 | Thanks Bhack for the answer. Following are some more details:
Tl;dr: A validation set is not required for training (see rationale 2), and if you use one, you shouldn’t pass it to fit(); rather to evaluate().
Splitting your data into train/validation/test is a generally good practice for ML. The reason most people do this is to tune their training algorithm on held-out data to have better results without skewing their final test eval.
Decision forests generally deal with relatively small datasets, and TF-DF always internally holds out some parts of the training set to do something similar (stop training early if it looks like it will overfit). Because the datasets are small, it can be helpful to just train on all the examples from train + validation (concatenate them in the call to fit()).
You can use the model self-evaluation 3 (e.g. out-of-bag for random forest) to get the held-out evaluation that is done during training.
If you want to evaluate your model on the validation split for another reason (e.g. hyperparameter tuning), you should call model.evaluate(validation_ds) manually. TF-DF always trains for exactly one epoch, so the evaluation you might expect from fit() while using a different TF Keras model won’t be what you get here.
Hope this helps! |
st206204 | Thank you Arvind for the extra details. So what will happen when you will pass the validation_data arg to fit() in this case?
I think that users have habits to naturally use validation_data arg in fit so it could be nice to have some disclaimer on the unexpected effects of this arg in the example/notebook or docs. |
st206205 | For now, nothing, unfortunately – which is different than what would happen in the usual Keras model: in the usual Keras model one would get a history of evaluations on the return.
For now we briefly documented the difference (see fit method returns) 3, but we are already working on fixing this – it should be coming in the next few days (now I notice we should have documented on validation_data argument, as well as on the various models).
The simple work around is for now call model.evaluate() on your validation data. Notice that DF only train on one epoch, so one will only get one evaluation on the validation dataset anyway. |
st206206 | Jan:
so one will only get one evaluation on the validation dataset anyway
So how will It interact with validation_steps arg? |
st206207 | So I’m assuming you are asking in the model.fit() method, right ?
If yes, it does, as usual (see keras.Model.fit API doc 2)
But the evaluation will return empty (for now) for TF-DF … until we fix this. |
st206208 | I was able to fit my RandomForest model, however when I try to convert it into tflite format it throws error.
The error is : InvalidArgumentError: Cannot convert a Tensor of dtype resource to a NumPy array. |
st206209 | hi Krishnava, thanks for bringing that up.
Unfortunately TFLite does not yet implement TF-DF models. We definitely would like to implement that, if we see more need. Pls, if you don’t mind, create an “issue” in our github repository 10 for that, so we can track others that may be interested in a TFLite version.
In the short term, for a very fast/cheap inference for a purely decision forest models, consider doing inference using the TF-DF C++ library called Yggdrasil 5. There is an example 4 that you can use to get started – it will read the TF-DF saved model that you trained in TensorFlow directly.
The Decision Forest models served in this fashion are often incredibly low-latency / low-cost. You can measure the serving speed without writing code using the benchmark inference tool 5.
G’luck! |
st206210 | Just as an update, as of release 0.1.4 passing validation_data (or other forms of validation input) to Model.fit() should lead to an evaluation at the end of the epoch, that is returned back on the History object returned by Model.fit. |
st206211 | okay I’ll try again with better formatting this time:
Hey, it’s me again! Your input really helped and I just quickly wanted to run this by to see whether what I’m doing is as it is intended: I have one .csv that i split into training and testing, and another .csv that i want to use purely as testing set to compare with the first. I started out as per your beginner tutorial with this
model_1 = tfdf.keras.RandomForestModel(
compute_oob_variable_importances=True,
max_depth = 20,
num_trees = 250
)
model_1.compile(
metrics=["accuracy", tf.keras.metrics.Recall(), tf.keras.metrics.Precision(), tf.keras.metrics.FalseNegatives(), tf.keras.metrics.FalsePositives()])
with sys_pipes():
model_1.fit(x=train_ds)
and for the second pure test set did this:
test_ds_pd2 = dataset_df1
train_ds2 = tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=label)
test_ds2 = tfdf.keras.pd_dataframe_to_tf_dataset(test_ds_pd2, label=label)
model_2 = tfdf.keras.RandomForestModel(
compute_oob_variable_importances=True,
max_depth = 20,
num_trees = 250
)
model_2.compile(
metrics=["accuracy", tf.keras.metrics.Recall(), tf.keras.metrics.Precision(), tf.keras.metrics.FalseNegatives(), tf.keras.metrics.FalsePositives()])
with sys_pipes():
model_2.fit(x=train_ds)
does that make sense? I apologize for this very basic question, just want to ensure I got it correct |
st206212 | It makes sense. There are situations where having multiple test datasets, each with a different distribution is useful :).
In your current formulation, two independent models are trained (model_1 and model_2), but none of them are evaluated on a test dataset. Here is something closer to what you describe:
# We assume the setup from the beginner colab (https://www.tensorflow.org/decision_forests/tutorials/beginner_colab)
train_ds_pd, test_ds_pd = split_dataset(...)
# In addition, here is the second dataset you mentioned: The "purely testing" set.
# Note: "test_ds_pd" is also a pure testing set.
pure_test_ds_pd = ...
# Train the model on the train split.
model = tfdf.keras.RandomForestModel()
model.fit(tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=label))
# Add some metrics for the model evaluation.
model.compile(metrics=["accuracy", tf.keras.metrics.Recall(), tf.keras.metrics.Precision(), tf.keras.metrics.FalseNegatives(), tf.keras.metrics.FalsePositives()])
# Evaluate the model on the test split of the first dataset.
evaluation_on_test = model.evaluate(tfdf.keras.pd_dataframe_to_tf_dataset(test_ds_pd, label=label))
# Evaluate the model on the second dataset i.e. "the pure test" one.
evaluation_on_pure_test = model.evaluate(tfdf.keras.pd_dataframe_to_tf_dataset(pure_test_ds_pd, label=label)) |
st206213 | Right, for some reason I trained 2 models witht the same parameters to then evaluate each set on one instead of both on the same model… Thanks a bunch for your fast reply! |
st206214 | Sorry for the many basic questions, but my dataset contains some numerical values but also a lot of booleans (shown as 0 and 1), which are used as numeric features by default, is that an issue? If yes, how do I fix it? And if not, does it have any other implications (e.g. for loss)? |
st206215 | As you correctly noted, TF-DF detects boolean features as numerical ones.
There is no impact (good or bad) on the quality or inference speed of the model.
However, this will impact slightly the training speed of the model.
Yggdrasil Decision Forests 4 (the core library behind TF-DF) supports boolean features natively, so they should be made available in TF-DF soon . |
st206216 | Ah thanks, hopefully last one: how do I know which of my classes is my positive and negative class in binary classification? and can I change this or specify this somehow (other than switchingthe labels in the dataset)? |
st206217 | Hi, i wanna know if you had use some programs to analyze CK,LOC,CC metrics of TensorFlow code.
Thanks to the availability, Andrea. |
st206218 | Hi @Andrea , Can you please describe your question in brief please? I didn’t get the context of what you want to say. If you are searching for documentation on metrics that tensorflow supports and here 10 it is. |
st206219 | I wanna know if there is a way to get (with some programs maybe) or the CK metrics like:
WMC weighted sum of the number of methods of a class.
DIT the longest path from the class to the most remote ancestor.
In case of multiple inheritance, DIT is thelargest number among the various most remote ancestors.
NOC the count of all the direct children of a class.
CBO a measure of the dependencies that an object has with other objects.
RFC the number of methods of a class than can beinvoked in response to a call to a method of a
class. |
st206220 | I don’t know a single open source tool that extract all these metrics for python and c++.
One of the few opensoruce multilanguage tools is:
github.com
terryyin/lizard 5
A simple code complexity analyser without caring about the C/C++ header files or Java imports, supports most of the popular languages.
But it will not cover all the CK metrics that are you looking for. |
st206221 | There is a way to analize some of the metrics that i wrote up?? because on the net i can’t find anything |
st206222 | For c/c++ you can still try to check the old cccc
github.com
sarnold/cccc 2
Source code counter and metrics tool for C++, C, and Java
For python you need to check for individual GitHub projects, if maintained and popular enought to trust the implementation. |
st206223 | i wanna do the metrics for python on TensorFlow code, if you have any suggest is very accepet!!
Thanks in advice |
st206224 | For python
github.com
sed-inf-u-szeged/OpenStaticAnalyzer 1
OpenStaticAnalyzer is a source code analyzer tool, which can perform deep static analysis of the source code of complex systems.
But I don’t think it is maintained anymore |
st206225 | I am not that good with RNNs and want to understand it in depth. Also, not just how to create RNN based models and which models are good, I also want to understand how tensorflow has implemented LSTM and GRU like layers.
Any materials (Books, Blogs, Videos etc.) would be appreciated for learning RNNs.
Please, also suggest the part of the code which can be starting point to understand implementation of RNN based layers in tf. |
st206226 | Personally, in TF/Keras I suggest you to make a first pass on
keras.io
Keras documentation: Working with RNNs 9 |
st206227 | Dive into Deep Learning (http://d2l.ai/ 6)
When you’re starting out, just the mathematics could be intimidating and just the code could be too shallow to learn. In my case, this book was the perfect mixture of code and maths and it has all of its code available as colab notebook.
Andrew Ng Deep Learning Specialization
It is probably the best beginners course in Deep Learning and if you can’t pay for coursera, you could watch the videos on youtube.
‘Learn ML’ section of tensorflow has a very good set of educational resources which can also act as a roadmap for you
TensorFlow
Machine learning education | TensorFlow 3
Start your TensorFlow training by building a foundation in four learning areas: coding, math, ML theory, and how to build an ML project from start to finish. |
st206228 | @sangam Thanks for resources. Dive to deeplearning is something that I wanted. I already have gone through andrew ng courses and it is not that I am complete beginner. I just take time working with RNNs and want to understand by looking at some real life implementations for learning. |
st206229 | The “Understanding LSTM Networks” by Chris Olah is an excellent resource on LSTM internals. For applications and code samples I found tutorials at Machine Learning Mastery very useful. I suspect some of the code might not follow the TF 2 APIs, something to keep in mind. |
st206230 | @manik_galkissa , Thanks so much for the resource. Can you please provide a link as well? |
st206231 | Sorry , seems like I’m not allowed to post links just yet. But the top results with the above keywords should point you in the right direction. |
st206232 | I suggest also to take a look at this cheatsheet
https://stanford.edu/~shervine/teaching/cs-230/cheatsheet-recurrent-neural-networks 2 |
st206233 | For high-level theory and more practical implementation of RNN & LSTM with TensorFlow, two books:
Hands on Machine Learning with Scikit-Learn, Keras, and TensorFlow (Aurelion Geron) 8, its repo is also code-rich, Chapter 15 5, Chapter 16 8
AI and Machine Learning for Coders (Laurence Moroney) 10, Chapter 7
or Course 3 of TensorFlow Developer Program - DeepLearning.AI 1 |
st206234 | I forgot to add this - Lecture 2 Intro to Deep Learning MIT - Deep Sequence Modeling. 2 - As you wanted to understand RNN &LSTMs in-depth, and implement them with TF, this would most likely be a quick (but still theoretical & practical ) option |
st206235 | Hi,
I am not very familiar with RNN (LSTM, GRU) models and I wanted to check how I can construct a model where the output of one RNN Cell is the input to the other using Keras.
Do I have to construct my own model using LSTMCell for example?
Thanks
Fadi Badine |
st206236 | hello, I am new here in the forum. I am a retired analyst who tinkers with Python, Tensorflow, PyTorch etc. I have an older Dell Optiplex 760 desktop which I use for some of my ML exercises. Running TF and TF2 on the Ubuntu 20.04 desktop there was non problems, how when I upgraded from Ubuntu 20.04 to Ubuntu 21.04, none of my Python scripts with TF2 would work. as soon as the script tried to run “Import Tensorflow as tf” , I would get the message “the kernel appears to have died, it will restart automatically”.
While its an older computer with 4 megs of ram, the same scripts ran very well on a Ubuntu 20.04 machine with the same specs. I thought that I would ask the question here in case anyone had similar experiences.
I look forward to any responses
Clive DaSilva |
st206237 | You could try to use one of the official docker tensorflow images to see if it solves your problem. |
st206238 | Can you post the full error message please? Also, maybe a minimal code that reproduces the problem? |
st206239 | Hi @Clive_Dasilva Welcome to the forum.
mihaimaruseac:
Can you post the full error message please? Also, maybe a minimal code that reproduces the problem?
+1. What @mihaimaruseac suggested can help reproduce the error and potentially find a solution. A list of steps with conda/pip commands you took to install TensorFlow and other packages could help.
In addition, as you’re probably aware, Python packages can be tricky. Some users appear to have experienced a similar issue - e.g. Kernel Restarting The kernel appears to have died. It will restart automatically (Jupyter-Tensorflow) · Issue #9829 · tensorflow/tensorflow · GitHub 13 - and some have come up with possible solutions, such as updating a certain package 6.
Since you’re on Linux, you could try Docker 1 (as @Aure suggested) or venv (a virtual environment) to isolate TensorFlow from the rest of the Python packages, then install tensorflow and maybe jupyterlab and see if that fixes your issue.
Let us know how it goes.
( from xkcd: Python Environment) |
st206240 | Thanks, I’ll try the venv route as suggested. set up a venv just for tf and see how it works. Damn thing is I have an older laptop running Ubuntu 20.04 with Tensorflow 2.2.9 and it works without this issue |
st206241 | What is the best way to extract the y_test and X_test data once we have it converted into the tf_dataset?
I could get the y_test with y_tfdf = np.concatenate([y for x, y in test_ds], axis=0)
I was hoping to compare with other GBMs using plot_roc_curve() from sklearn |
st206242 | @Erin , There is an entire guide here 5 in documentation on splitting slicing data when using tensorflow_datasets. |
st206243 | I’m following the instructions for tf.keras.layers.RNN to define a custom RNN layer and When I call the layer the initial_state passed in as an argument, the initial state is over-written by the output of my get_initial_state() method (which randomly initializes the initial state) when stateful = True. The custom RNN cell is defined below:
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras import backend
import numpy as np
np.random.seed(42)
class MinimalRNNCell(keras.layers.Layer):
def __init__(self, units, **kwargs):
self.units = units
self.state_size = units
super(MinimalRNNCell, self).__init__(**kwargs)
def build(self, input_shape):
#weights initialized as zero
self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
initializer=tf.keras.initializers.Constant(value=0),
name='kernel')
#constant weights for testing
self.recurrent_kernel = self.add_weight(
shape=(self.units, self.units),
initializer=tf.keras.initializers.Constant(value=1),
name='recurrent_kernel')
self.built = True
def call(self, inputs, states):
prev_output = states[0]
h = backend.dot(inputs, self.kernel)
output = h + backend.dot(prev_output, self.recurrent_kernel)
return output, [output]
#randomly initialized initial state
def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
initializer = tf.keras.initializers.RandomNormal(mean=0., stddev=1., seed=None)
return initializer((batch_size, self.units))
batch_size = 8
input_dim = 4
state_size = 3
timestep = 2
input = tf.zeros((batch_size, timestep, input_dim)) #input initialized to zero
init = ( tf.random.stateless_normal([batch_size, state_size], seed = (1,2) ))
min_rnn = MinimalRNNCell(state_size)
layer = keras.layers.RNN(min_rnn, return_sequences=True, stateful=True)
out =layer(input , training = True , initial_state = init)
out[:,0,:] == backend.dot(init, min_rnn.recurrent_kernel)
Regarding the last four lines, when layer is defined such that stateful = False, the last line generates a boolean array of all True indicating that the initial_state is being passed in properly. However, when stateful = True, that’s no longer the case. I’m wondering how to fix this such that the user input initial state always over-rides the random initialization from my get_initial_state() method. |
st206244 | Not sure if it will fit your solution but the following tutorial gives you an idea of setting the initial LSTM states of a decoder in an NMT setting:
TensorFlow
Neural machine translation with attention | Text | ... 5 |
st206245 | The above behaviour was observed on Tensorflow version 2.5.0. I just tested my exact same code on Tensorflow version 2.3.0 and get the desired behaviour (user passed in initial state in the call method over-rides get_initial_state() of the custom RNN cell whether Stateful is True or False), which seems to be consistent with the documentation:
A get_initial_state(inputs=None, batch_size=None, dtype=None) method that creates a tensor meant to be fed to call() as the initial state, if the user didn’t specify any initial state via other means.
However, in Tensorflow 2.3.0, if Stateful = True, it is ignoring the get_initial_state() method even if a user initial_state is not passed in (leading to initializing initial state as all zeroes). |
st206246 | On the iOS version of our app we are using the Apple Word Tagger Model 20 so that it can assist us with parsing some complex sentences and that way we can extract the parts that we actually want. It is working fairly well.
I need something similar on Android.
Basically I would feed it a large sample of sentences and a classification for every word in the sentence and once it learns those I can pass it some new sentences and it’ll tell me the classification of each of the words.
A similar example to what we want would be an address parser. Imagine that the training data looks like:
123, house_number
E., direction_short
Main, street_name
Av., avenue
17123, house_number
W. direction_short
West, direction_long
Ct., court
10th, street_name
etc, etc
And then we pass it “87 W. Central St.”, then the word tagger would tell us 87 is house_number, W. is direction_short, etc.
I tried using the Bert Classifier and the NLClassifier with my own model but when I get the classifier results back it is analyzing the entire “87 W. Central St.” and telling me the score for each possible label, at least I think that is what is doing.
I need a model that will tell me the category (label) of each word in my sentence. Is there such a thing for Android?
Hope that makes sense.
Thanks. |
st206247 | If you are looking for something canned like Apple WTM you can take a look at MLKIT:
Google Developers
Extract Entities with ML Kit on Android | Google Developers 26 |
st206248 | This looks super close to what I need but my data is pretty custom data. Normal words but I need to categorize them in a way specific to my app. Is there something like this but that can be trained with my own data and categories?
Thanks. |
st206249 | If you want something near production ready with your custom data you can try to explore:
github.com
legacyai/tf-transformers/blob/main/src/tf_transformers/notebooks/tutorials/ner_albert.ipynb 34
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MTy_I5RsT3to"
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RE1LHLVeU3qR"
},
"outputs": [],
"source": [
"# Install tf-transformers from github"
This file has been truncated. show original |
st206250 | The good thing about training a tagger model based on ALBERT is it will likely be supported in TFLite. TensorFlow Hub also provides MobileBERT checkpoints, another model supported in TFLite.
Tagging @lgusm for more details. |
st206251 | Hi everybody,
despite searching on google and the forum, I wasn’t able to find a good explanation on how to initialize an agent with a custom policy. How do I do that? Does anybody have a hint?
Greetings,
Stefan |
st206252 | Have you already seen this tutorial?
TensorFlow
Policies | TensorFlow Agents |
st206253 | Yes - I tried to follow “Example 3: Q Policy”, which works so far. But where in this tutorial is the agent located?
[Thank you very much for your time and sorry for such maybe dumb questions] |
st206254 | Policies can be created independently of agents. E.g. see the random_policy in DQN tutorial
colab.research.google.com
Google Colaboratory
If you are going to create your custom Agent policy and collect_policy are constructor args:
TensorFlow
tf_agents.agents.TFAgent | TensorFlow Agents 1
Abstract base class for TF-based RL and Bandits agents. |
st206255 | Stefan_Haerter:
But where in this tutorial is the agent located?
[Thank you very much for your time and sorry for such maybe dumb questions]
No problem. Deep RL is not easy.
Your agent [an abstract term, so it’s just your program] would try to learn to do X by interacting with an environment (e.g. the game of Pong via Gym or an Android app via AndroidEnv using a policy (approximated by a neural net - hence “deep” RL) to gain experience. The policy (your neural net) “belongs” to your agent - it maps the agent’s observations (inputs, could be image pixels or sequential data directly via an API) to its actions/action log probabilities (outputs).
In addition, you may find this post - Deep Reinforcement Learning With TensorFlow 2.1 | Roman Ring 1 - helpful. It was written by an engineer who now works at DeepMind. In addition, there’s a YouTube channel that teaches well-known "basic deep RL methods - such as DQN, policy gradients, and actor-critic methods - with core TensorFlow 2. Check out Everything You Need To Master Actor Critic Methods | Tensorflow 2 Tutorial - YouTube 1 (actor-critic methods) or Deep Q Learning With Tensorflow 2 - YouTube 1 (DQN). |
st206256 | Thank you, the second one seems to be what I am looking for. I tried to code with the dqn_agent and wondered why there was no policy arg. |
st206257 | Thank you for the explanation and the links. I already wrote a custom environment and now I want to write a custom policy as well. Let’s say I have a use case like the following:
There are a number of boxes and a number of pieces. The task of the agent is to choose a piece and sort it into a box so that the load of the fullest box is minimized. I will have a look at the links. |
st206258 | Stefan_Haerter:
and now I want to write a custom policy as well.
You could also write an “MVP” using, for example, an SAC 3 (by BAIR) algorithm with just TF Probability and TF as a start.
Here’s a “clean” example:
github.com
philtabor/Youtube-Code-Repository/blob/master/ReinforcementLearning/PolicyGradient/SAC/tf2/networks.py 3
import os
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow_probability as tfp
from tensorflow.keras.layers import Dense
class CriticNetwork(keras.Model):
def __init__(self, n_actions, fc1_dims=256, fc2_dims=256,
name='critic', chkpt_dir='tmp/sac'):
super(CriticNetwork, self).__init__()
self.fc1_dims = fc1_dims
self.fc2_dims = fc2_dims
self.n_actions = n_actions
self.model_name = name
self.checkpoint_dir = chkpt_dir
self.checkpoint_file = os.path.join(self.checkpoint_dir, name+'_sac')
self.fc1 = Dense(self.fc1_dims, activation='relu')
self.fc2 = Dense(self.fc2_dims, activation='relu')
This file has been truncated. show original
(Another example with code: Deep Reinforcement Learning: Playing CartPole through Asynchronous Advantage Actor Critic (A3C) with tf.keras and eager execution — The TensorFlow Blog 3) |
st206259 | In fact, I attempt to solve a Flexible Job Shop Scheduling Problem. I try to model it in a way that the machines are the “boxes” and the tasks of the jobs are the pieces which are to be sorted in the boxes. I want to test if that works. |
st206260 | You can take a look at
arXiv.org
Towards Standardizing Reinforcement Learning Approaches for Stochastic... 1
Recent years have seen a rise in interest in terms of using machine learning,
particularly reinforcement learning (RL), for production scheduling problems of
varying degrees of complexity. The general approach is to break down the
scheduling problem... |
st206261 | Dear All
I try to perform a simple multiplication using the first element of the output layer. My code looks like the following:
from tensorflow.keras.layers import *
import tensorflow as tf
scale_, mean_ = 2., 4.
a = Input(shape=(128,128), name=‘Input_vec’)
m_num = Input(shape=(4,), name=‘Input_num’)
output = Lambda(lambda x: tf.multiply(x[0], x[1]))((a, m_num[1]))
But I get the following error:
ValueError: Dimensions must be equal, but are 128 and 4 for '{{node lambda_18/Mul}} = Mul[T=DT_FLOAT](Placeholder, Placeholder_1)' with input shapes: [?,128,128], [4]. |
st206262 | Check tf.multply doc
If x.shape is not the same as y.shape, they will be broadcast to a compatible shape.
TensorFlow
tf.math.multiply | TensorFlow Core v2.5.0 2
Returns an element-wise x * y. |
st206263 | @mohammad_gharaee , The shape of a in your code snippet would be [None, 128, 128] and shape of m_num would be [None, 4].
IMO, I don’t think they are multiplication compatible. I mean you can still multiply by broadcasting as @Bhack mentioned above but it doesn’t make sense to me in this case.
Can you mention a specific use case that you are trying to achieve here. May be then someone can help. |
st206264 | thanks @ashutosh1919, @Bhack
I already checked the doc and I know about broadcasting.
Actually here is my idea. I try to get some some parameters from image and using them create a matrix for next layer. In the image below you may see my rough idea. So I want to multiply each set of params to image.
I really appreciate your help. |
st206265 | I tried to do so but I got the error “Sorry, you can’t embed media items in a post.” |
st206266 | @ashutosh1919
Here is the image. Just replace - with .
drive-google-com/file/d/1U6oEAuTGscujR6HGtlpe976ssjZZr14q/view?usp=sharing |
st206267 | I want to compare the recognition rate before and after quantization.
First, i want to save the weights of the trained model as a csv file,
quantize them through an external program, and then input the csv file
as the weights of the model again
but, i don’t know how…
thx for reading my Question. |
st206268 | tf.keras.Model has explicit methods get_weights and load_weights with which you can store weights in any type of file and load them from any type of file.
Please take a look at this stackoverflow answer 13 |
st206269 | I appreciate your reply.
I was able to solve this problem.
Thank you very much. ashutosh. |
st206270 | I am running Google Colab locally on my Macbook Air running the M1 chip. I have installed the pre-released TensorFlow and am trying to run a ConvNet model, but get an error saying ‘ImportError: Image transformations require SciPy. Install SciPy’. I have read the readme on the GitHub for the pre-released TF and it says SciPy is currently not available. I tried installing SciPy on the virtual environment that TF was installed in but still no luck, does not import when running an interactive python session on my terminal and also when running the model again. Has anyone gotten around this? I cannot stand waiting 15+ minutes per epoch on 30 epochs when training my model when using Colabs hosted server. |
st206271 | It Is a temp known limit but there are workarounds:
E.g. See Installing TensorFlow and JupyterLab on Mac with M1 28 |
st206272 | Thank you. I managed to install SciPy into my virtual env using some commands that were written by a user in of the websites in the link you gave me, but I still ran into the same issue: ‘ImportError: Image transformations require SciPy. Install SciPy’ after doing that. Seems like I will probably just have to buy a new pc in order to train my model much faster than what I am getting now. Had to scale down my steps_per_epoch by 10, and the speed at which its training is still appalling! |
st206273 | You can also try to read/interact with this ticket:
github.com/apple/tensorflow_macos
Instructions to install TensorFlow in a Conda Environment 27
opened
Feb 3, 2021
mwidjaja1
This is not so much an issue as opposed to a 'How To' if you'd like to install t…his version of Tensorflow in Conda.
## Prerequisites: You must be on macOS Big Sur
If you have an Apple Silicon Mac, this is a freebie, you're already on Big Sur. If you're on an Intel Mac, the Intel versions of TensorFlow are Big Sur only.
**Sanity Check before Proceeding**: To ensure you're on the right version of macOS, run `sw_vers -productVersion` in your terminal. If it's not version 11.##, you're not on Big Sur and must upgrade to it from the macOS App Store.
## Prerequisites: Install XCode Command Line Tools
Install Xcode Command Line tools if you haven't. To do so, run this in your terminal: `xcode-select --install`
**Sanity Check before Proceeding**: To ensure installation worked, run `which xcrun` in your terminal and you should get a path like `/usr/bin/xcrun`. If you haven't, you did not install it correctly.
## Prerequisites: Install Miniforge
**Where to download Miniforge from**
Miniforge, is a 'lightweight' Python interpreter that has full access to the Conda ecosystem. You can download Miniforge from https://github.com/conda-forge/miniforge#miniforge3. You can use Anaconda if you're on Intel, but note that this guide will be written from the perspective of using miniforge.
**Sanity Check before Proceeding**:
- Run `file $(which python)` in your terminal (thanks to @lebigot for this shortcut!). Please make sure that you got:
- This path implies you're running your `miniforge` version of Python. It'll probably be `<your home dir>/miniforge3/bin/python`.
- If you have an Apple Silicon Mac, it should also say `Mach-O 64-bit executable arm64`. If you have an Intel Mac, it should also say `Mach-O 64-bit executable x86_64`.
- Run `which pip` in your terminal and it too should resolve to some path that implies you're using miniforge3.
If any of those sanity checks failed, you must redo this section. Please ensure that you downloaded the correct Miniforge for your system architecture and installed it. If you did all that, set your environment paths to Miniforge's Python Installation. To do that, you need to figure out where conda was installed to (it's probably `~/miniforge3/condabin/conda`) and then run `~/miniforge3/condabin/conda init` in your terminal.
## Apple Silicon Only Warning: You CANNOT use Anaconda
This warning only applies to Apple Silicon Macs. Anaconda comes with many Python packages included, some of which are not Apple Silicon (i.e. ARM) compatible and thus Anaconda is not ARM compatible. You can use Anaconda if you're using an Intel Mac though.
If you were planning to use Anaconda on ARM, please scroll back up and install Miniforge. Miniforge has Conda, which means you can install many of the packages you want such as Pandas, Scipy, and Numpy -- unlike Anaconda, you just have to do the install manually by running `conda install mypackagenamehere`.
## Intel Only Warning: Python Bugs in Big Sur
This warning only apply to Intel Macs. For Intel, both Anaconda and MiniForge have a [Python Bug](https://www.python.org/downloads/release/python-387/) which prevents you from running Python correctly in some instances on macOS Big Sur. Until the Python community fixes this, each time prior to loading Python, you must run `export SYSTEM_VERSION_COMPAT=0`. You could also add this to your `.bash_profile` or other shell environment file if you have one, to do this automatically for you.
## Installing TensorFlow
Attached to this Issue is a YAML file which will help you create a Conda Environment with TensorFlow, along with all the prerequisites you need from the ARM conda-forge channel.
1. Download [environment.yml](https://raw.githubusercontent.com/mwidjaja1/DSOnMacARM/main/environment.yml), which contains the instructions to create a Python environment with the dependencies you need -- we'll install TensorFlow afterwards. Some browsers insist on adding `.txt` to the end of the file -- do not let your browser do that. [thanks to @isuruf for streamlining this file to be all Conda]
2. In your terminal run this command, replacing the uppercase variables with the path to your environment.yml file and your desired name for this environment: `conda env create --file=PATH_TO_ENVIRONMENT.YML --name=YOUR_ENV_NAME_HERE`.
3. Activate that environment by running this command, replacing the uppercase variable with your environment's name: `conda activate YOUR_ENV_NAME_HERE`
4. Pip install the TensorFlow wheels by running the commands below. By the way, the URLs for the TensorFlow wheel files came from the [Releases](https://github.com/apple/tensorflow_macos/releases) page, so you can swap these wheel files out with a prior version of TensorFlow as needed.
**For X86 as of 03/11/2021:**
Thanks to @edwin-yan for the updated commands
```
pip install --upgrade --force --no-dependencies https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_x86_64.whl https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_x86_64.whl
```
**For Apple Silicon as of 03/11/2021:**
```
pip install --upgrade --force --no-dependencies https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl
```
5. Finally, give it a spin. Run `python` and try importing `tensorflow`.
### Example Commands
In this below example, I'm installing & running the ARM version of tensorflow from an environment I've named `test`. The yml file is placed in the same directory I'm running this command from, which is my home directory (i.e. `~`)
```
conda env create --file=environment.yml --name=test
conda activate test
pip install --upgrade --force --no-dependencies https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha2/tensorflow_addons_macos-0.1a2-cp38-cp38-macosx_11_0_arm64.whl https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha2/tensorflow_macos-0.1a2-cp38-cp38-macosx_11_0_arm64.whl
python
import tensorflow
```
<img width="873" alt="Screen Shot 2021-02-02 at 10 19 26 PM" src="https://user-images.githubusercontent.com/7283317/106693560-bc1d2280-65a4-11eb-8555-ff2d1d9b8caa.png">
### Troubleshooting for importing TensorFlow
- Type in `which python` and then `which pip` in your terminal. Both paths should point to a Python that is **inside the environment** you created in Step 2. If it doesn't, you may not have installed Miniforge correctly, ran Step 2 correctly, and/or may not have ran Step 3.
- Run `python --version` and it should be version 3.8. If it isn't, you most likely did not create or activate your environment correctly, as per Steps 2 & 3. Do those again.
- If python is correctly pointed to the right environment but you cannot import tensorflow, consider running step 5 again just to make sure you installed Tensorflow in the appropriate environment.
- If you are using Intel and got a `not a supported wheel on this platform` error, run `export SYSTEM_VERSION_COMPAT=0` in your terminal and try again. If this works, you'll need to do this everytime you use Python until a [Python Bug](https://www.python.org/downloads/release/python-387/) is resolved.
- **Please verify that you did ALL of the Sanity Checks from the previous section and that they resolve appropriately before posting your issue here.** If you do post your issue, please provide the terminal outputs from those steps and bonus points if you share the results of your Sanity Check and run `pip` with a `-v` flag for additional logging. Remember I'm just a volunteer -- I'll try to help but there's only so much I can help with.
### Troubleshooting for setting up TensorFlow
- For those having issues with tf.keras.models.load_model about a `failed to decode` error: Try downgrading to h5py to the 2.10.0 wheel file that was [packaged with this alpha release](https://github.com/apple/tensorflow_macos/releases/download/) (`pip install ~/path to h5py.whl`). Thanks to @ramicaza.
And subscribe/upvote this:
github.com/apple/tensorflow_macos
SciPy for image transformations 35
opened
Dec 22, 2020
MintStudios
I'm trying to train a model which works on kaggle, but won't work on my M1 macbo…ok pro. It says:
`ImportError: Image transformations require SciPy. Install SciPy`
I just built a model to identify plants and diseases, but the problem is that it isn't working when it's fitting. Compiling is fine, but it stops and gives me errors when the model tries to fit. |
st206274 | Followed the instructions on the first GitHub ticket, ended up working, model finally runs locally, averaging around 2s / step, as opposed to to the ~40s / step I was getting before when not running it locally. Thank you for your help, very much appreciated! |
st206275 | It looks like you’re hitting the error in this file:
github.com
keras-team/keras-preprocessing/blob/master/keras_preprocessing/image/affine_transformations.py 15
"""Utilities for performing affine transformations on image data.
"""
import numpy as np
from .utils import array_to_img, img_to_array
try:
import scipy
# scipy.ndimage cannot be accessed until explicitly imported
from scipy import ndimage
except ImportError:
scipy = None
try:
from PIL import Image as pil_image
from PIL import ImageEnhance
except ImportError:
pil_image = None
ImageEnhance = None
This file has been truncated. show original
samiesaheb:
I managed to install SciPy into my virtual env using some commands that were written by a user in of the websites in the link you gave me, but I still ran into the same issue: ‘ImportError: Image transformations require SciPy. Install SciPy’ after doing that
From the code I linked, that doesn’t sound possible. The error is only triggered is import scipy; import scipy.ndimage fails.
Anyway, one good workaround for this is to not use keras.preprocessing since these run in python/numpy/scipy not in tensorflow. keras.layers.experimental.preprocessing contains pure-tensorflow layers that implemnent common image transformations.
TensorFlow
tf.keras.layers.experimental.preprocessing.RandomRotation 7
Randomly rotate each image.
We have several examples that use these. |
st206276 | Interesting. I was trying to do data augmentation and was using ImageDataGenerator, the keras.layers.experimental.preprocessing I think has everything I need apart from shear_range which is in ImageDataGenerator, how would I go about applying a shear_range in that ? I tried searching for it and was not able to find it. |
st206277 | I think we have TF native shear in the model garden package
PyPI
tf-models-official 6
TensorFlow Official Models |
st206278 | 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:
github.com
tensorflow/tensorflow/blob/master/tensorflow/python/keras/layers/preprocessing/image_preprocessing.py#L621 3
array_ops.zeros((num_translations, 1), dtypes.float32),
-translations[:, 0, None],
array_ops.zeros((num_translations, 1), dtypes.float32),
array_ops.ones((num_translations, 1), dtypes.float32),
-translations[:, 1, None],
array_ops.zeros((num_translations, 2), dtypes.float32),
],
axis=1)
def transform(images,
transforms,
fill_mode='reflect',
fill_value=0.0,
interpolation='bilinear',
output_shape=None,
name=None):
"""Applies the given transform(s) to the image(s).
Args:
images: A tensor of shape (num_images, num_rows, num_columns, num_channels)
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.
Bhack:
I think we have TF native shear in the model garden package
Or maybe someone’s already done all that work. |
st206279 | More than one I hope we could unify the image processing API one of this days:
TensorFlow
tfa.image.shear_x | TensorFlow Addons 4
Perform shear operation on an image (x-axis). |
st206280 | markdaoust:
layers.experimental.preprocessing layers use this transform function which just takes a projection matrix:
It is a “private” API. We have tried to expose this but the evaluation was to keep this private. See
github.com/tensorflow/tensorflow
Expose transform 4
tensorflow:master ← bhack:patch-11
opened
Dec 16, 2020
bhack
+9
-0
See https://github.com/tensorflow/addons/pull/2293 |
st206281 | Hi
When I load grayscale, I use cv2.imread and give cv2.IMREAD_GRAYSCALE as the flag.
I just wondered what will happen if I train the model by color image from gray scale.
I Tried, and the training ended successfully.
Now, I’ve got something to ask.
What difference is between training with original grayscale image and color image converted to grayscale?
Is it better to train grayscale model with original grayscale images than to train color model with color images converted to grayscale? |
st206282 | If the conversion to grayscale produces the same output as the grayscale image then the output of the training should be identical (modulo randomness).
If the conversion is different, then it depends on how big the difference is. But this is unikely, as conversion to grayscale is usually done using the same formula. |
st206283 | Hello,
I have found the following code as alternative to the torch.select_index function, but the loop makes the process very slow. Do you have any suggestion ?
def tf_index_select(self, input_, dim, indices):
"""
input_(tensor): input tensor
dim(int): dimension
indices(list): selected indices list
"""
start = time.time()
shape = input_.get_shape().as_list()
if dim == -1:
dim = len(shape)-1
shape[dim] = 1
tmp = []
for idx in indices:
begin = [0]*len(shape)
begin[dim] = tf.dtypes.cast(idx, tf.int64)
tmp.append(tf.slice(input_, begin, shape))
res = tf.concat(tmp, axis=dim)
return res
Thank you |
st206284 | Is tf.gather enought for your use case?
TensorFlow
tf.gather | TensorFlow Core v2.5.0 2
Gather slices from params axis axis according to indices. (deprecated arguments)
Then we have also tf.gather_nd:
TensorFlow
tf.gather_nd | TensorFlow Core v2.5.0 2
Gather slices from params into a Tensor with shape specified by indices. |
st206285 | Hello,
I hope everyone is having a good day. I have been experimenting on TFX and running pipelines in Kubeflow trying to build an end-to-end solution.
After the model deployment phase, I have been wondering if there is a supported tool for model monitoring in the production environment to check whether a model is performing as expected/ what are the responses to the inference requests and if they are true in nature… I’m looking for a deployment solution… keeping eye on the running model especially in the kubeflow context.
I would love to hear from the team.
Thank You. |
st206286 | Hi Muhammad,
It depends on where you’re deploying to. For TFlite and TFJS deployments model monitoring is very different. For TensorFlow Serving it would mostly be a matter of logging and then analyzing the log data for drift and skew. To detect concept drift you will need labeling of samples of prediction requests. For Vertex AI there is a preview release of model monitoring support 5.
thanks,
Robert |
st206287 | Thank you for the reply.
In the TensorFlow Serving context, besides the GCP Vertex AI solution. Is there any open-source on-premise solution available for logging and analyzing the model in production?
and what are the other methods to drive model metrics besides labelling and is there any open-source solution available for that as well?
Waiting for your reply.
Thank you. |
st206288 | Need to run a sign language video classification model(i3d) on android, that takes 5 dimension ( 1 3 64 224 224),examples/lite/examples/image_classification/android at master · tensorflow/examples · GitHub 2 , but failes. But runs on PC with python3.7.
java1574×237 58 KB
This is the error. I think it is due to the input size. In opencv we can concat frames and convert it to a numpy array to get the size as (1 64 224 224 3) then transpose it to (1 3 64 224 224). No idea on how it can be done with Java.
input1400×925 35.1 KB
output747×923 31.9 KB |
st206289 | What is the exact type of the input tensor buffer that you’re using in the Java code?
Based on the error message, your Java buffer size is 576 bytes, which suggests that your buffer type / size doesn’t match what’s expected by your model. |
st206290 | Adding on what YYoon said, the example from TensorFlow/Examples is not meant to run with whatever tflite file you insert into the project. You have to do a lot of changes, but it is a good start without the need to write all the boilerplate code for the camera for example.
First of all I have not seen a 5th dimension. If you had input of [1,224,224,3] or [1,3,224,224] for the image your job would have been more easy. So what is this 5th dimension? You have to provide more info and a notebook to check. If this is a 3D dimension I have not found a camera that can provide this type of information. What are the inputs at the notebook? Are they 3D images? |
st206291 | I’m developing a Machine Learning “fortune teller” that completes sentences from seeds, but my trained algorithm seems very poor or even not usable.
It’s my first time training with tokenized words, and I’ve tried several approaches but non results in a good trained model.
Example of my dataset
This July money will be by your side.
The next days love will come at your door.
Be careful with your friend and money.
Love is going to be hard this year.
A lot of friends will come at your door.
Be powerful at your job it will result good this month.
... etc, etc.
I have:
21,885 unique sentences
1,523 unique words
How have I prepared my data?
I’ve sorted the unique words in alphabetic order and saved them into a 1,523-length array.
For example:
[a, at, be, by, come, door, good, job, lot, ....]
With this built array, I assign to every word of my data a numbered value.
For example:
Hello, my name is Carlos will be equal to [54, 504, 492, 394, 100, 150]
Supposing that in my dictionary Hello=54 ,=504 my=492 name=394 is=100 Carlos=150
Why not using a pre-trained model that completes sentences? Because I have special words that don’t exist in the dictionary and weird names.
Creating my inputs and outputs
Having tokenized my words, I’ve come up with a way to make same-length inputs for my model by grouping array of words into N-length entries.
I’ve decided to split my sentences in arrays of 4-items with an array of 2-items as output, for example:
Hello, my name is {Name} and I like apples.
Will result into:
Input Output
["Hello", ",", "name", "is"] ["{Name}", "and"]
[",", "name", "is", "{Name}"] ["and", "I"]
["name", "is", "{Name}", "and"] ["I", "like"]
["is", "{Name}", "and", "I"] ["like", "apples"]
["{Name}", "and", "I", "like"] ["apples", "."]
["and", "I", "like", "apples"] [".", "."]
Note: I start appending “.” at the end of output when the sentence has finished so the algorithm has a good knowledge of when a sentence ends.
Then I repeat these steps for all the 21,885 sentences I have.
And finally I substitute the word with the index of where it’s my word list, so real input/output looks like this.
Input Output
[400,500,390,293] [303, 442]
Training
My data on this example is constructed by Inputs of 4-length arrays and outputs of 2-length arrays.
Idea is to train an algorithm that given 4 words it can predict the next 2 words. (Used 4-length array for input for this example but I’ve tried multiple array lengths for the input)
Layers and model used so far
const model = tf.sequential();
model.add(tf.layers.dense({units: 100, inputShape: [4]}));
model.add(tf.layers.activation({activation: 'softmax'}));
model.add(tf.layers.dense({units: 2}));
model.compile({loss: 'categoricalCrossentropy', optimizer: tf.train.sgd(0.001) ,metrics: ['accuracy']});
//70% of the data used for trainning
const xs = tf.tensor2d(inputs, [inputs.length, inputs[0].length]);
const ys = tf.tensor2d(outputs, [outputs.length, outputs[0].length]);
//20% of the data used for validation
const xsVal = tf.tensor2d(inputsVal, [inputsVal.length, inputsVal[0].length]);
const ysVal = tf.tensor2d(outputsVal, [outputsVal.length, outputsVal[0].length]);
model.fit(xs, ys,{epochs: 100,batchSize:64, validationData: [xsVal, ysVal]}).then(async () => {
const saveResult = await model.save('file://modelo2');
});
But I cannot get it train correctly, it loops in a step giving all the time the same loss= value.
I’ve also tried by changing the training learning rate, but I keep getting the same loop. Which makes me thing I’m not preparing my data correctly or I’m using a bad technique.
I’ve also tried to change the model of training to meanSquaredError, but same problem.
Second approach
Instead of converting the output as a tokenized value of the index of my word list. E.g. Hello=54, I’ve made a another approach to only predict the next word by making a 1,523-length array of [0,0,0,...1,0] with a 1 in the index of my word list.
For example, if I want to tokenize the output of the word website of my list ["car", "apple", "website", "orange", "red"] the output will be a [0, 0, 1, 0, 0] array
So now my data looks like:
Input Output
[400,500,390,293] [0,0,0,0,0,0,0,0,0,0,1]
But this also leads to a failed training.
What am I missing or doing wrong?
I think I have to achieve something like LSTM, but I haven’t trained one as such and I’m lost about how to prepare the data for the problem I need to solve and how to prepare the layers and model.
Can anyone suggest a better approach for this?
Thanks in advance.
Note: All data and tokens for this example have been made up to explain the problem. |
st206292 | @cabada , I don’t know if your model architecture might get good results.
I’d suggest you look into this tutorial: Text generation with an RNN | TensorFlow 19
The tutorial uses charprediction but I think you can adapt it to word prediction. |
st206293 | You’re on the right track with your sequences. I try to think of sequence training as “Given the last n elements, tell me what the n+1 element should be”. I’m not sure how having two outputs would affect the training, but I don’t see any problems with it, you’re just predicting the next two elements instead of the next one.
You’re right about wanting to try an LSTM layer (or GRU, they both seem to perform similar functions) which will consider not just the current input but also the ones before it. The problem with using dense layers for this is that they don’t consider ordering, so they’re just taking the collection of words rather than taking them in order. |
st206294 | While my code runs without any problems with Keras Tuner and standard loss functions like ‘mse’ I am trying to figure out how to write a custom loss function that accept an external argument in addition to true and forecasted y to use inside Keras Tuner for LSTM model selection. I am looking for the easiest and less painful way and I didn’t find a working solution in old posts.
One approach I follewed is this one. Let’s say I have these variables
# external vector needed in custom loss function
ex_loss= np.logical_not(klines_backtest.loc[i_sel,['d']].to_numpy(dtype=np.float32)[:sample_start])
# create data sequences for x and vector to forecasy y
x_train, y_train = lstm_data_sequence(dataset[:sample_start,:-1], dataset[:sample_start,-1], lstm_sequence)
# concatenate external vector to y so y shape is Nx2
y_train = np.vstack((y_train, ex_loss[lstm_sequence:,0])).T
I have defined the following loss function
def bande_loss(y_true, y_pred):
mse = K.square(y_pred - y_true[:,0])
i_loss = K.equal(y_true[:,1], 1) and K.greater_equal(y_pred, y_true[:,0])
i_loss = K.cast(~i_loss, 'float32')
return K.mean(mse*i_loss)
Basically I tryied to avoid the loss function override passing the additional variable (of the same size of y_true) I need in the loss function inside y_train where I expext to have y_true and the corresponding external variable correctly sized for the batch.
The LSTM for model selection is
def lstm_model(hp):
model = Sequential()
model.add(InputLayer(input_shape=(48*3, 13)))
num_layers = hp.Int('num_layers', min_value=4, max_value=8, step=2)
num_units = hp.Choice('units', values=[50, 100, 250, 500])
n_dropout = hp.Choice('n_dropout', values=[float(0), 0.10, 0.20])
n_rec_dropout = hp.Choice('n_rec_dropout', values=[float(0), 0.10, 0.20])
learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4, 1e-5, 1e-6])
for i in range(num_layers):
if i < num_layers - 1:
r_sequence = True
else:
r_sequence = False
model.add(LSTM(
units=num_units,
dropout=n_dropout,
recurrent_dropout=n_rec_dropout,
return_sequences=r_sequence))
model.add(Dense(1))
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
loss=bande_loss,
metrics=[bande_loss])
return model
Executing this code
tuner = Hyperband(
hypermodel=lstm_model,
objective=Objective("bande_loss", direction="min"),
max_epochs=50,
hyperband_iterations=2,
executions_per_trial=1,
overwrite=True,
project_name='hyperband_tuner')
stop_early = tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=3, verbose=1)
tuner.search(x_train, y_train, epochs=30, validation_split=p_train, callbacks=[stop_early],
shuffle=False, verbose=1)
I get this error
The second input must be a scalar, but it has shape [32]
[[{{node bande_loss/cond/switch_pred/_2736}}]] [Op:__inference_train_function_45266]
Function call stack:
train_function
Note that 32 is the (default) batch size.
Also running the same code with
def bande_loss(y_true, y_pred):
mse = K.square(y_pred - y_true[:,0])
return K.mean(mse)
seems to work fine while running with
def bande_loss(y_true, y_pred):
mse = K.square(y_pred - y_true[:,1])
return K.mean(mse)
gives me the same error and I cannot understand why.
I also tried the loss function override in this way
def lstm_model(hp):
model = Sequential()
model.add(InputLayer(input_shape=(48*3, 13)))
num_layers = hp.Int('num_layers', min_value=4, max_value=8, step=2)
num_units = hp.Choice('units', values=[50, 100, 250, 500])
n_dropout = hp.Choice('n_dropout', values=[float(0), 0.10, 0.20])
n_rec_dropout = hp.Choice('n_rec_dropout', values=[float(0), 0.10, 0.20])
learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4, 1e-5, 1e-6])
for i in range(num_layers):
if i < num_layers - 1:
r_sequence = True
else:
r_sequence = False
model.add(LSTM(
units=num_units,
dropout=n_dropout,
recurrent_dropout=n_rec_dropout,
return_sequences=r_sequence))
model.add(Dense(1))
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
loss=bande_loss(ex_loss),
metrics=[bande_loss(ex_loss)])
return model
def bande_loss(ex_loss):
def loss(y_true, y_pred):
mse = K.square(y_pred - y_true)
i_loss = K.equal(ex_loss, True) and K.greater_equal(y_pred, y_true)
i_loss = K.cast(~i_loss, 'float32')
return K.mean(mse*i_loss)
return loss
...
# external vector needed in custom loss function
ex_loss= np.logical_not(klines_backtest.loc[i_sel,['d']].to_numpy(dtype=np.float32)[:sample_start])
# create data sequences for x and vector to forecasy y
x_train, y_train = lstm_data_sequence(dataset[:sample_start,:-1], dataset[:sample_start,-1], lstm_sequence)
ex_loss = K.variable(ex_loss[lstm_sequence:], dtype=bool)
tuner = Hyperband(
hypermodel=lstm_model,
objective=Objective("bande_loss(ex_loss)", direction="min"),
max_epochs=50,
hyperband_iterations=2,
executions_per_trial=1,
overwrite=True,
project_name='hyperband_tuner')
stop_early = tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=3, verbose=1)
tuner.search(x_train, y_train, epochs=30, validation_split=p_train, callbacks=[stop_early],
shuffle=False, verbose=1)
But I get this error
tensorflow.python.framework.errors_impl.InvalidArgumentError: The second input must be a scalar, but it has shape [4176]
[[{{node cond/switch_pred/_12}}]] [Op:__inference_train_function_34471]
Function call stack:
train_function
Can anyone provide me help or a simpler and effective way to implement custom loss functions with external parameters inside Keras Tuner? |
st206295 | Can anyone please help me to visualize the inner features of the SSD model at the time of inference, like the feature map of each layer? |
st206296 | BTW I have no clue on how to get access to the last layer of the model. You know class prediction, bbox prediction, etc. |
st206297 | You can have access to the inner layers such as the backbone in Keras fashion. First you must run the object detection model similar as the notebook eager_few_shot_od_training_tf2_colab.ipynb, to get the backbone should detection_model.feature_extractor.classifaction_backbone, with that you can extract features. |
st206298 | Thanks for the help, but I did know how to do feature extraction from backbone layers like VGG16, Mobilenet, etc. But I want to do the extraction from the object detection layers. |
st206299 | You’re welcome, and I’m also looking at how to extract the object detector layers. If you get an answer, please share it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.