id
stringlengths
3
8
text
stringlengths
1
115k
st207500
Hi, When I run the following code, my tf parameter variables are not updated and the losses are Inf. Can anyone help here? Thanks! PS I believe that my mistake is in the steps: “# Initialize the parameters in the variational distribution” AND/ OR “#Variational model and surrogate posterior”: from sklearn.datasets import load_breast_cancer data = load_breast_cancer() num_fea = 30 df = pd.DataFrame(data["data"][:,:num_fea], columns=data["feature_names"][:num_fea]) X = np.array((dfX - dfX.mean())/dfX.std()) # Standardize num_datapoints, data_dim = X.shape holdout_portion = 0.2 n_holdout = int(holdout_portion * num_datapoints * data_dim) holdout_row = np.random.randint(num_datapoints, size=n_holdout) holdout_col = np.random.randint(data_dim, size=n_holdout) holdout_mask = (sparse.coo_matrix((np.ones(n_holdout), #The data (ones) in any order (holdout_row, holdout_col)), # Indices of which rows and columns the data needs to be placed shape = X.shape)).toarray() # the shape of the entire matrix in which the data needs to be placed and other entries left empty holdout_subjects = np.unique(holdout_row) #print(holdout_mask) holdout_mask = np.minimum(1, holdout_mask) # There were some repetitions, which also needs to be one x_train = np.multiply(1-holdout_mask, X) x_vad = np.multiply(holdout_mask, X) num_datapoints, data_dim = x_train.shape latent_dim = 5 def pmf_model(data_dim, latent_dim, num_datapoints, mask, gamma_prior = 0.1): w = yield tfd.Gamma(concentration = gamma_prior * tf.ones([latent_dim, data_dim]), rate = gamma_prior * tf.ones([latent_dim, data_dim]), name="w") # parameter z = yield tfd.Gamma(concentration = gamma_prior * tf.ones([num_datapoints, latent_dim]), rate = gamma_prior * tf.ones([num_datapoints, latent_dim]), name="z") # local latent variable / substitute confounder x = yield tfd.Poisson(rate = tf.multiply(tf.matmul(z, w), mask), name="x") # (modeled) data concrete_pmf_model = functools.partial(pmf_model, data_dim=data_dim, latent_dim=latent_dim, num_datapoints=num_datapoints, mask=mask) model = tfd.JointDistributionCoroutineAutoBatched(concrete_pmf_model) # Initialize w and z as a tensorflow variable w = tf.Variable(tf.random.gamma([latent_dim, data_dim], alpha = 0.1)) z = tf.Variable(tf.random.gamma([num_datapoints, latent_dim], alpha = 0.1)) # target log joint porbability target_log_prob_fn = lambda w, z: model.log_prob((w, z, x_train)) # Initialize the parameters in the variational distribution qw_conc = tf.random.uniform([latent_dim, data_dim], minval = 1e-5) qz_conc = tf.random.uniform([num_datapoints, latent_dim], minval = 1e-5) qw_rate = tf.maximum(tfp.util.TransformedVariable(tf.random.uniform([latent_dim, data_dim]), bijector=tfb.Softplus()), 1e-5) qz_rate = tf.maximum(tfp.util.TransformedVariable(tf.random.uniform([num_datapoints, latent_dim]), bijector=tfb.Softplus()), 1e-5) # Variational model and surrogate posterior: def factored_gamma_variational_model(): qw = yield tfd.TransformedDistribution(distribution = tfd.Normal(loc = qw_conc, scale = qw_rate), bijector = tfb.Exp(), name = "qw") qz = yield tfd.TransformedDistribution(distribution = tfd.Normal(loc = qz_conc, scale = qz_rate), bijector = tfb.Exp(), name = "qz") surrogate_posterior = tfd.JointDistributionCoroutineAutoBatched( factored_gamma_variational_model) losses = tfp.vi.fit_surrogate_posterior( target_log_prob_fn, surrogate_posterior=surrogate_posterior, optimizer=tf.optimizers.Adam(learning_rate=0.05), num_steps=500) losses
st207501
I am trying to read a TFRecord file like this: dataset = tf.data.TFRecordDataset("./tfrecords/train.record").map(_extract_fn).batch(3) However, when I run features, labels = iter(dataset).next() I get this error: tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [4], [batch]: [2] [Op:IteratorGetNext] This is the function that parses the TFRecord file: features = { 'image/height': tf.io.FixedLenFeature([],tf.int64), 'image/width': tf.io.FixedLenFeature([], tf.int64), 'image/filename': tf.io.VarLenFeature(tf.string), 'image/id': tf.io.FixedLenFeature([], tf.string), 'image/encoded': tf.io.FixedLenFeature([],tf.string), 'image/format': tf.io.FixedLenFeature([], tf.string), 'image/object/class/text': tf.io.VarLenFeature(tf.string), 'image/object/class/label': tf.io.VarLenFeature(tf.int64), 'image/object/bbox/xmin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/xmax': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.io.VarLenFeature(tf.float32), } sample = tf.io.parse_single_example(tfrecord, features) data = {} data["image/encoded"] = tf.image.decode_jpeg(sample["image/encoded"], channels=3) label = sample['image/object/class/label'].values return data,label If I write return data instead and only set features = iter(dataset).next() it works fine. What is the issue here? Thanks for any help!
st207502
The label has a variable length: TensorOverflow: 'image/object/class/label': tf.io.VarLenFeature(tf.int64), So when you try to .batch the dataset it can’t pack the different sized tensors together. You either want to use .padded_patch or .apply(tf.data.experimental.dense_to_ragged_batch(...))
st207503
Im trying to import to tensorflow an onnx saved model from a pytorch implementation of efficientdet-d0 and I get the following error when I try to run a prediction or export the model : ValueError: DepthwiseConv2D requires the stride attribute to contain 4 values, but got: 3 for ‘{{node depthwise}} = DepthwiseConv2dNative[T=DT_FLOAT, data_format=“NHWC”, dilations=[1, 1, 1, 1], explicit_paddings=[], padding=“VALID”, strides=[1, 1, 1]](transpose_4, Reshape_2)’ with input shapes: [?,?,?,?], [3,3,32,1]. code : onnx_model = onnx.load(PATH + ‘model.onnx’) onnx.checker.check_model(onnx_model) tf_rep = prepare(onnx_model) tf_rep.export_graph(“d0_s256_b32_ep400_TF.pb”) or onnx_model = onnx.load(PATH + ‘model.onnx’) onnx.checker.check_model(onnx_model) tf_rep = prepare(onnx_model) tf_rep.run(Variable(torch.randn(32,3,256,256, dtype=torch.float32)))
st207504
I suggest you to post this on the LinuxFoundation ONNX slack: https://onnx.ai/slack.html 6
st207505
If you only want the EfficientDet model, you can download from TensorFlow Hub: TensorFlow Hub 13
st207506
There has been some fine tuning on top of the original coco weights with another specific dataset so I need to keep the modifications for the new checkpoint
st207507
Able to get keras model h5 format for masked RCNN. I have tried 2 approaches: 1.While trying to convert keras model to tensorflow saved_model using GitHub - bendangnuksung/mrcnn_serving_ready: 🛠 Converting Mask R-CNN Keras model to Tensorflow 6 getting error as File “main.py”, line 113, in model.load_weights(H5_WEIGHT_PATH, by_name=True) File “/home/ubuntu/Downloads/Blaize/mrcnn_serving_ready-master/model.py”, line 2131, in load_weights saving.load_weights_from_hdf5_group_by_name(f, layers) File “/home/ubuntu/Downloads/venv/lib/python3.6/site-packages/keras/engine/saving.py”, line 1328, in load_weights_from_hdf5_group_by_name str(weight_values[i].shape) + ‘.’) ValueError: Layer #389 (named “mrcnn_bbox_fc”), weight <tf.Variable ‘mrcnn_bbox_fc/kernel:0’ shape=(1024, 24) dtype=float32, numpy= array([[-0.05486 , -0.03290214, 0.05897582, …, -0.05898178, -0.06868616, 0.05374715], [-0.06710163, -0.03682471, -0.03057443, …, -0.05611433, -0.04561458, 0.05178914], [-0.0041154 , -0.07344876, -0.06137543, …, 0.0011842 , 0.04365869, -0.05199062], …, [ 0.06231805, -0.02443966, -0.00532094, …, -0.01833269, -0.02245103, -0.01552512], [-0.04047406, -0.06753345, 0.02390008, …, 0.01883602, -0.04362615, -0.05265519], [ 0.00530255, 0.04341973, 0.03085093, …, -0.07011634, 0.01440722, 0.02777647]], dtype=float32)> has shape (1024, 24), but the saved weight has shape (1024, 324). 2.in the second method using https://github.com/amir-abdi/keras_to_tensorflow,got 1 error as ValueError('Unknown ’ + printable_module_name + ': ’ + class_name) ValueError: Unknown layer: BatchNorm
st207508
I’m not sure I understand your question correctly. Does the error occur when you are saving the keras model into .h5 file or loading it from it? If you are loading a model from a file and see messages about unknown layers, it mean that the original model contained some custom layers. You need to import them or initialize from scratch in your new code before loading the model.
st207509
There is a Mask-RCNN implementation in TF Model Garden as well 8. You can try that if you do not manage to resolve your issues with the code base you have been using. I have a sample for Model Garden’s RetinaNet training + saving here 4. It’s not Mask-RCNN but also a detection model so maybe the code can be useful to you to get through the Model Garden learning curve (the links below open in Colab and TPU training in Colab works in approx. 40 min): The main training + saving happens in 04ab_retinanet_arthropods_train.ipynb 3. You can reload the model to test it with https://04ac_retinanet_arthropods_predict.ipynb 1 and the last notebook contains the data conversion pipeline, which you can adapt for your own dataset: 04aa_retinanet_arthropods_dataprep.ipynb 1
st207510
Adding up some more information for the future: If you only need the model for inference, you can use it directly from TFHub: TensorFlow Hub 2 (among many other models) if you want to do fine tuning, there’re some good tutorial on Model Garden (as pointed by Martin), like these ones: list of colabs with code: models/research/object_detection/colab_tutorials at master · tensorflow/models · GitHub 4 Few shot code - models/eager_few_shot_od_training_tf2_colab.ipynb at master · tensorflow/models · GitHub 2
st207511
Thank You.Actually I wanted to convert mrcnn model to tf dialect .I downloaded model from TensorFlow Hub 2. and I tried adding signatures to model using import tensorflow.compat.v2 as tf loaded_model = tf.saved_model.load(’/maskedrcnn’) call = loaded_model.call.get_concrete_function( tf.TensorSpec(shape=(1, 1024, 1024, 3), dtype=tf.uint8)) signatures = {‘predict’: call} tf.saved_model.save(loaded_model,’/ex’, signatures=signatures) I got warning as Found untraced functions such as restored_function_body, restored_function_body, restored_function_body, restored_function_body, restored_function_body while saving (showing 5 of 125). These functions will not be directly callable after loading.
st207512
Aruna_Kote: oaded_model = tf.saved_model.load(’/maskedrcnn’) call = loaded_model.call.get_concrete_function( tf.TensorSpec(shape=(1, 1024, 1024, 3), dtype=tf.uint8)) signatures = {‘predict’: call} tf.saved_model.save(loaded_model,’/ex’, signatures=signatures) try this instead: import tensorflow as tf import tensorflow_hub as hub model_url = "https://tfhub.dev/tensorflow/mask_rcnn/inception_resnet_v2_1024x1024/1" loaded_model = hub.load(model_url) call = loaded_model.__call__.get_concrete_function( tf.TensorSpec(shape=(1, 1024, 1024, 3), dtype=tf.uint8)) signatures = {'predict': call} tf.saved_model.save(loaded_model,'./test', signatures=signatures) did it help?
st207513
I used :import tensorflow as tf from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 model_url = “TensorFlow Hub 1” imported = hub.load(model_url) concrete_func = imported.call.get_concrete_function( tf.TensorSpec(shape=(1, 1024, 1024, 3), dtype=tf.uint8)) #concrete_func = imported.signatures[’__saved_model_init_op’] frozen_func = convert_variables_to_constants_v2(concrete_func, lower_control_flow=False) graph_def = frozen_func.graph.as_graph_def(add_shapes=True) with tf.Graph().as_default() as inferred_graph: tf.import_graph_def(graph_def, name="") print(tf.mlir.experimental.convert_graph_def( graph_def, pass_pipeline=‘tf-standard-pipeline’ )) mlir file got generated .and then tensorflow/bazel-bin/tensorflow/compiler/mlir/tf-opt --tf-executor-to-functional-conversion --tf-shape-inference -xla-legalize-tf --print-ir-before-all --print-ir-after-all &>sample ex.mlir I got error as error: unknown TensorFlow type: uint8 %1106 = “tf.Placeholder”() {_output_shapes = [“tfshape$dim { size: 1 } dim { size: -1 } dim { size: -1 } dim { size: 3 }”], device = “”, dtype = “tfdtype$DT_UINT8”, name = “input_tensor”, shape = “tfshape$dim { size: 1 } dim { size: -1 } dim { size: -1 } dim { size: 3 }”} : () → tensor<1x?x?x3x!tf.uint8>
st207514
May I know where can I find the source code of the mrcnn model from TFHub. I tried converting model to to tflite using import tensorflow as tf import tensorflow_hub as hub inputs = tf.keras.Input(shape=(1024, 1024, 3),batch_size=1,dtype=tf.uint8) m_l = hub.KerasLayer(“TensorFlow Hub”) x = m_l(inputs) model = tf.keras.Model(inputs=inputs, outputs=x, name=“mrcnn”) converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() got error as 2021-08-27 12:49:16.478141: F tensorflow/lite/toco/tooling_util.cc:2277] Check failed: array.data_type == array.final_data_type Array “input_1” has mis-matching actual and final data types (data_type=uint8, final_data_type=float). Fatal Python error: Aborted
st207515
Hi Aruna, the source code is at the Model Garden repo here 4 One question, are you planning on using this model on a mobile device? I’m asking because it might be very slow! this model is very complex and has a big input (1024x1024). It’s not really a model for on-device inference. There’re many better options (good tutorial here 1).
st207516
Thank you sir. Sir actually I wanted convert the model to mlir that is HLO dialect and wanted to understand how the expression operators and conditional branching , dynamic sizes are looks when lowered to mlir. Sir is HLO files available for MRCNN?.Because I tried lowering the TF-HUB model But I am not able to lower it .I am getting error got error as 2021-08-27 12:49:16.478141: F tensorflow/lite/toco/tooling_util.cc:2277] Check failed: array.data_type == array.final_data_type Array “input_1” has mis-matching actual and final data types (data_type=uint8, final_data_type=float). Fatal Python error: Aborted
st207517
I think I understood. I don’t think there’s a MRCNN model converted to tflite (for the reasons mentioned earlier), sorry. Isn’t there any other model that you could use to understand the operations you want and that’s already converted to TFLite?
st207518
Sir is there a way to get rid of error 2021-08-27 12:49:16.478141: F tensorflow/lite/toco/tooling_util.cc:2277] Check failed: array.data_type == array.final_data_type Array “input_1” has mis-matching actual and final data types (data_type=uint8, final_data_type=float). Fatal Python error: Aborted. Thanks
st207519
Dear Tensorflow community, I am new to Tensorflow and have thus encountered problem when I try to implement Poisson Matrix factorization (on the Wisconsin Breast Cancer dataset). The problem is the following: I wish to build a gamma/poisson version of the PPCA model described here: TensorFlow Probabilistic PCA  |  TensorFlow Probability 1 I have defined my model with gamma and Poisson distributions for the posterior, i.e. the target log joint probability, as well as initialising the two latent variables in my model (u,v). Moreover, That is: N, M = x_train.shape L = 5 min_scale = 1e-5 mask = 1-holdout_mask # Number of data points = N, data dimension = M, latent dimension = L def pmf_model(M, L, N, gamma_prior = 0.1, mask = mask): v = yield tfd.Gamma(concentration = gamma_prior * tf.ones([L, M]), rate = gamma_prior * tf.ones([L, M]), name = "v") # parameter u = yield tfd.Gamma(concentration = gamma_prior * tf.ones([N, L]), rate = gamma_prior * tf.ones([N, L]), name = "u") # local latent variable x = yield tfd.Poisson(rate = tf.multiply(tf.matmul(u, v), mask), name="x") # (modeled) data pmf_model(M = M, L = L, N = N, mask = mask) concrete_pmf_model = functools.partial(pmf_model, M = M, L = L, N = N, mask = mask) model = tfd.JointDistributionCoroutineAutoBatched(concrete_pmf_model) # Initialize v and u as a tensorflow variable v = tf.Variable(tf.random.gamma([L, M], alpha = 0.1)) u = tf.Variable(tf.random.gamma([N, L], alpha = 0.1)) # target log joint porbability target_log_prob_fn = lambda v, u: model.log_prob((v, u, x_train)) # Initialize v and u as a tensorflow variable v = tf.Variable(tf.random.gamma([L, M], alpha = 0.1)) u = tf.Variable(tf.random.gamma([N, L], alpha = 0.1)) Then I need to state trainable variables/ parameters, which I do in the following (possibly wrong) way: qV_variable0 = tf.Variable(tf.random.uniform([L, M])) qU_variable0 = tf.Variable(tf.random.uniform([N, L])) qV_variable1 = tf.maximum(tfp.util.TransformedVariable(tf.random.uniform([L, M]), bijector=tfb.Softplus()), min_scale) qU_variable1 = tf.maximum(tfp.util.TransformedVariable(tf.random.uniform([N, L]), bijector=tfb.Softplus()), min_scale) Ultimately, I make my model for the surrogate posterior and estimate the losses and trainable parameters: def factored_pmf_variational_model(): qv = yield tfd.TransformedDistribution(distribution = tfd.Normal(loc = qV_variable0, scale = qV_variable1), bijector = tfb.Exp(), name = "qv") qu = yield tfd.TransformedDistribution(distribution = tfd.Normal(loc = qU_variable0, scale = qU_variable1), bijector = tfb.Exp(), name = "qu") surrogate_posterior = tfd.JointDistributionCoroutineAutoBatched( factored_pmf_variational_model) losses = tfp.vi.fit_surrogate_posterior( target_log_prob_fn, surrogate_posterior=surrogate_posterior, optimizer=tf.optimizers.Adam(learning_rate=0.05), num_steps=500) My code does NOT give an error however, my (after running the entire script stated here) trainable parameters are NaN for the qV_variable0 and qU_variable0. Is there a kind person, who can tell me why it goes wrong and it would be lovely to see a demonstration of how to use bijectors in the correct manner in tensorflow probability/ distributions with models estimated using Variational inference. Please also let me know if it is my target model or my surrogate posterior understanding that is wrong. Thank you so much in advance!
st207520
I want to use a pretrained TensorFlow model inside a custom loss function to train another model. Is it possible to do that? it seems that I cannot run a sess in a graph.
st207521
Hi Leonard, can you clarify a little bit. Do you want to use the pretrained TF model to be the ground truth and those values are compared to what your model is generating? If so, could you instead cache the pre trained model’s results and use that instead?
st207522
Hi ! thanks for your reply. Yes, I want to minimize the result between pretrained model and the training model. Since the data set is large and the data is randomly feed into model, I trying to load the pretrained model in training phase. Is it possible to do that?
st207523
leonard: Is it possible to do that? Yes. it seems that I cannot run a sess in a graph. That’s correct. But you shouldn’t need sessions or graphs at all. Everything will be a lot easier if you use TF2.
st207524
Thanks for your reply! I try to modify the training code of TF1. Are there other solution to do this?
st207525
It’s possible. You just have to build everything into a single graph and use a single session. That’s hard. Maybe not worth the effort at this point. But if you can make a saved_model from your TF1 model, you can easily load that in TF2 and everything should work.
st207526
Hi MoveNet developers, I’ve been following MoveNet for a while I love how you guys are creating really useful and performant model to be used in mobile applications. I have a use case where I would like to fine-tune/modify the model. (e.g. modify number of key point, provide more targeted training from custom dataset) Is there any plan to open source/enable fine tuning on MoveNet models? I’m relatively new to ML field (coming from SW) and looking at TFHub suggests that it’s not fine-tunable. (I did try to import/inspect the model on TF and yeah it looked pretty blackbox) I searched around open source implementation and there’s one written in PyTorch, github.com GitHub - lee-man/movenet: Un-official implementation of MoveNet from Google 20 Un-official implementation of MoveNet from Google. Contribute to lee-man/movenet development by creating an account on GitHub. I’ve no idea how accurate this implementation is, but I guess I have few options. Use PyTorch implementation as baseline Port this implementation/build in TF Ask original devs for generosity Let me know what you guys have planned, and any suggestions! Thanks, Daniel
st207527
Hello Daniel, Thanks a lot for your interest in using MoveNet! You are right the MoveNet releases are currently not fine-tunable. But the model implementation is actually based on the Tensorflow Object Detection API 7 so you should be able to access the model code and modify it for your own purpose. As mentioned in the documentation, the MoveNet model is based on CenterNet with some modifications in the postprocessing logics and ops re-write to boost the performance. The closest model architecture can be found here 25. You can also find some example training configs in the /models/research/object_detection/configs/tf2/ folder. I’d recommend you to start with the above codebase and modify from it. There are a few internal modifications which have not been released yet. We are still working on it and will let you know once it is there. Thanks.
st207528
Hi, Can someone from the Tensorflow Team please provide information on how to fine-tune a model from the Tensorflow 2 Model Zoo when training it for object detection? I have read that there is a freeze_variables parameter in the pipeline.config file, but is this still usable? Let’s say you want to freeze all the layers, expect the top 10, how can this be done when doing object detection? Thanks!
st207529
You could check Adding community contributed guides by sayakpaul · Pull Request #9271 · tensorflow/models · GitHub 20
st207530
On the OD repo there’s a lot of useful information that might help you: list of colabs with code: models/research/object_detection/colab_tutorials at master · tensorflow/models · GitHub 18 Few shot code - models/eager_few_shot_od_training_tf2_colab.ipynb at master · tensorflow/models · GitHub 8
st207531
Can someone comment on V5 downloading of TF-HUB models to TensorflowJS, I am not sure but things seem to have changed in the last year. I am most interested in fine-tuning which I thought needed to be uploaded using const model = await tf.loadLayersModel and frozen models converted from Tensorflow saved models could only be uploaded using const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true}); but V5 on TF-HUB seems to have fine-tunable Tensorflow Saved models, but the JS v1 and V3 versions only show the GraphModel load method which I thought was for frozen models. tf-hub link here 1 I guess my question is, how do I find fine-tunable Layers models from TF-HUB? Searching more I did find a JS(V5) here 1 but it is using the Graph Model Load which as far as I know is frozen const model = await tf.loadGraphModel( 'https://tfhub.dev/google/tfjs-model/imagenet/mobilenet_v3_large_100_224/feature_vector/5/default/1', { fromTFHub: true }); Any opinions? I want to search, find and load layers models from TF-HUB?
st207532
thanks Jason! Hi Jeremy, As of today we don’t have a search with this specific criteria (graph vs layered). These models you mention specifically, could not be converted to LayersModels. I believe LayersModels can only be made from Keras models, which was not the case here. They are fine tuneable on regular TF only. However, you can still “train” from any TFJS feature vector model using a KNN classifier. Tutorial: Transfer learning image classifier  |  TensorFlow.js 1 (go to colab step 7) does it makes sense?
st207533
Greetings everyone, I am a computer science student. For my graduation thesis, I want to work on a project that can detect exoplanets using machine learning. If you want to join me, want to support me, please do not hesitate to contact me.
st207534
We have done a blog post in 2019: blog.tensorflow.org Identifying Exoplanets with Neural Networks 4 What is an exoplanet? How do we find them? Most importantly, why do we want to find them? Exoplanets are planets outside of our Solar System - they orbit any star other than our Sun. We can find these exoplanets via a few methods: radial velocity,...
st207535
I will be using the EfficeintNet-D7 model through TensorFlow to count the number of objects in an image taken from the sky. I want to extract objects that only appear at 3ft or higher in an image (the object matches the ground so the model keeps incorrectly selecting it). How would I write this into the model?
st207536
Do you mean something like this? arXiv.org IM2HEIGHT: Height Estimation from Single Monocular Imagery via Fully Residual... 2 In this paper we tackle a very novel problem, namely height estimation from a single monocular remote sensing image, which is inherently ambiguous, and a technically ill-posed problem, with a large source of uncertainty coming from the overall scale....
st207537
I do not think this is the route I am wanting to go since I will be using orthomosaics and just want to make sure that I am only counting objects at a specific height since they sometimes blend into the background.
st207538
Do you want to solve this with a single aerial image like in: MDPI IMG2nDSM: Height Estimation from Single Airborne RGB Images with Deep Learning 1 Estimating the height of buildings and vegetation in single aerial images is a challenging problem. A task-focused Deep Learning (DL) model that combines architectural features from successful DL models (U-NET and Residual Networks) and learns the...
st207539
Hello I have a problem with this tutorial. TensorFlow Neural machine translation with attention  |  Text  | ... 2 I run it a couple of times before (even yesterday) and everything worked and when I tried running it today on Google Collab I get an error. Does anyone else have this problem? Can you please help. This is the error Convert the target sequence, and collect the “[START]” tokens example_output_tokens = output_text_processor(example_target_batch) start_index = output_text_processor._index_lookup_layer(’[START]’).numpy() first_token = tf.constant([[start_index]] * example_output_tokens.shape[0]) AttributeError Traceback (most recent call last) in () 2 example_output_tokens = output_text_processor(example_target_batch) 3 ----> 4 start_index = output_text_processor._index_lookup_layer(’[START]’).numpy() 5 first_token = tf.constant([[start_index]] * example_output_tokens.shape[0]) 2 frames /usr/local/lib/python3.7/dist-packages/keras/layers/preprocessing/index_lookup.py in _standardize_inputs(self, inputs, dtype) 734 if isinstance(inputs, (list, tuple, np.ndarray)): 735 inputs = tf.convert_to_tensor(inputs) → 736 if inputs.dtype != dtype: 737 inputs = tf.cast(inputs, dtype) 738 return inputs AttributeError: ‘str’ object has no attribute ‘dtype’
st207540
Hi there, i am working on a loudspeaker that can generate audible soundwaves in a special medium that is a fluid-gel. Since the equations for the signal processing part are not completely understood yet, i want to use a deep learning script to aid. It is not complicated the only problem is that i am very new to Tensorflow and have not really an idea how to implement it, although i have been working a week on it. So my problem is this: the loudspeaker has to generate ultrasonic modulated signals, the medium is nonlinear and therefore demodulates it, it becomes audible again in the medium. I can make many samples of some random signals and recorded samples, or hook the PC onto the loudpeaker and microfone, so that tensorflow can “learn” itself. I just have no clue how to do is, are there any sample projects you know? I am very thankful for any help
st207541
I don’t know if you could find this useful for your project: github.com magenta/ddsp 12 DDSP: Differentiable Digital Signal Processing. Contribute to magenta/ddsp development by creating an account on GitHub.
st207542
Hi @Georgschmied I’m not an expert but maybe this tutorial can give you some ideas to play with: Simple audio recognition: Recognizing keywords  |  TensorFlow Core 6 The main idea is, you get the sound waves from the medium, convert to a spectrogram, use a CNN to extract features and then to the classification.
st207543
For learning about waveform/signal processing, you could start with the Sound of AI channel that teaches signal processing with Python and deep learning for audio with TensorFlow and Librosa. Some hands-on examples (in separate playlists): 16- How to Implement a CNN for Music Genre Classification - YouTube 5 How to Implement Autoencoders in Python and Keras || The Encoder - YouTube 3 How to Extract Spectrograms from Audio with Python - YouTube 1 GitHub repos by the same person: GitHub - musikalkemist/DeepLearningForAudioWithPython: Code and slides for the "Deep Learning (For Audio) With Python" course on TheSoundOfAI Youtube channel. 1 ; GitHub - musikalkemist/generating-sound-with-neural-networks: Code and slides for the "Generating Sound with Neural Network" series on The Sound of AI Youtube channel. 2 ; GitHub - musikalkemist/AudioSignalProcessingForML: Code and slides of my YouTube series called "Audio Signal Proessing for Machine Learning" 1 Georgschmied: the loudspeaker has to generate ultrasonic modulated signals, To learn to generate sounds using the input from your loudspeaker, you might start with the second playlist mentioned above (generating sounds with neural networks). Georgschmied: can make many samples of some random signals and recorded samples If you’re interested in music source separation, for example, there’s an open sourced model called Spleeter - you can try it on your machine: GitHub - deezer/spleeter: Deezer source separation library including pretrained models. 2 (it was written in TensorFlow). (D3Net is one of the current state-of-the-art models: [2010.01733] D3Net: Densely connected multidilated DenseNet for music source separation 3 .) More material: DeepMind: WaveNet: A generative model for raw audio | DeepMind 2 (paper: WaveNet: A Generative Model for Raw Audio | DeepMind) DeepMind: The challenge of realistic music generation: modelling raw audio at scale | DeepMind 1 (Talk: Sander Dieleman: Generating music in the raw audio domain - YouTube) Google Brain Magenta: GANSynth: Adversarial Neural Audio Synthesis | OpenReview 1 (magenta/magenta/models/gansynth at master · magenta/magenta · GitHub) Magenta: Music Transformer: Generating Music with Long-Term Structure 2 Magenta’s repo: GitHub - magenta/magenta: Magenta: Music and Art Generation with Machine Intelligence 2 (and magenta/magenta/models at master · magenta/magenta · GitHub) Generating music in the waveform domain – Sander Dieleman 1 arXiv: [1911.13254] Music Source Separation in the Waveform Domain 1
st207544
I looked at this option. It seems like this solution is too complex for what I need to do with my project. I am sure that it has all the functionality I need, but I am just trying to process XY data for the number peaks and where they are. I could spend a week understanding all the details of the Magneta project, but the time would be wasted, if at the end, I cannot get what I need.
st207545
If you just need a peak detection on a simple audio signal probably you have easier off the shelf solution like: https://essentia.upf.edu/reference/streaming_PeakDetection.html 2
st207546
No, we need something better than that. I have developed our own modules that can detect the peaks and noisefloor features based on Principal Component Analysis. Actually that is the code that is being used to label the dataset. We need a DNN that can: Identify Harmonics, in the signal wave. Identify Non-Harmonics in the signal wave. Find Bessel functions in the signal wave. Identify carrier frequencies in the signal wave. Compare two signals to find differences. The biggest issue is that we can ID parts using simple signal processing in the laboratory, but this has to go out in production and ultimately customer environments, where there will be no hand-holding. A neural network is the best solution because of its’ ultimate reliability. So we need a DNN that is trained to find these features. I wanted to base this off of audio processing (since so much work has already been done). But it seems that ML for this kind of work only looks at a few solutions: XY data (none of the solutions I have seen look at signal data this way). Images of plots. (This appears more promising, but it is hard to see how we could train a network to “Look” at plots sucessifully). Spectrographs. All the audio processing examples I have seen look at audio files in this manner. I looked over Magneta and a few examples online. I don’t think we can turn our data into spectrograms. We have power v frequency plots (the data has already undergone an FFT). Is there a DNN effort that has looked at ways to process Power Vrs Frequency plots in radio emissions? Poking around the web I found this company in VA: https://www.deepsig.ai/ 1. Looks like we have competition.
st207547
There was a nice survey for radio signals at: arXiv.org Intelligent Radio Signal Processing: A Survey 6 Intelligent signal processing for wireless communications is a vital task in modern wireless systems, but it faces new challenges because of network heterogeneity, diverse service requirements, a massive number of connections, and various radio...
st207548
Hi, i wanted to build a deep learning model to color white blood cells and platelets, without actually staining them. For instance, i input a blood smear image without any colors added, and the model should output the WBCs and platelets colored as if it was stained by hand. What would be the best way to build such a model? Thanks!
st207549
You can start with: https://lup.lub.lu.se/student-papers/search/publication/8998594 4 But generally you can adapt and experiment many segmentation models. E.g. for U-NET style: http://www.worldascience.com/journals/index.php/wassn/article/view/24/14 2
st207550
Hello, I’m trying to implement a mechanistic model using TensorFlow which will be used as part of a GAN, based on the approach shown in this paper: [2009.08267] Integration of AI and mechanistic modeling in generative adversarial networks for stochastic inverse problems 1 The mechanistic model uses a TF Dormand-Prince solver to solve a set of differential equations which yield pressure waveforms for different regions of the cardiovascular system. I want to get gradients of the waveforms with respect to parameters of the mechanistic model for training the generator of the GAN. A couple of my differential equations incorporate a variable which is time-varying (piecewise but continuous, no “sharp corners”) and which is computed from a subset of the parameters to the mechanistic model. If I set this variable to a constant, I can get gradients of the waveforms wrt model parameters. However, if I keep this variable as time-varying, then I get a ZeroDivisionError when I try to compute the gradients. Any idea why this error might appear? I have included a stack trace below. Thanks a lot for your help! --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in ----> 1 dy6_dX = tape.gradient(y6, X) ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow/python/eager/backprop.py in gradient(self, target, sources, output_gradients, unconnected_gradients) 1078 output_gradients=output_gradients, 1079 sources_raw=flat_sources_raw, → 1080 unconnected_gradients=unconnected_gradients) 1081 1082 if not self._persistent: ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow/python/eager/imperative_grad.py in imperative_grad(tape, target, sources, output_gradients, sources_raw, unconnected_gradients) 75 output_gradients, 76 sources_raw, —> 77 compat.as_str(unconnected_gradients.value)) ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow/python/ops/custom_gradient.py in actual_grad_fn(*result_grads) 472 “@custom_gradient grad_fn.”) 473 else: → 474 input_grads = grad_fn(*result_grads) 475 variable_grads = [] 476 flat_grads = nest.flatten(input_grads) ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow_probability/python/math/ode/base.py in grad_fn(*dresults, **kwargs) 454 initial_time=result_time_array.read(initial_n), 455 initial_state=make_augmented_state(initial_n, → 456 terminal_augmented_state), 457 ) 458 ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow_probability/python/math/ode/dormand_prince.py in _initialize_solver_internal_state(self, ode_fn, initial_time, initial_state) 307 p = self._prepare_common_params(initial_state, initial_time) 308 → 309 initial_derivative = ode_fn(p.initial_time, p.initial_state) 310 initial_derivative = tf.nest.map_structure(tf.convert_to_tensor, 311 initial_derivative) ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow_probability/python/math/ode/base.py in augmented_ode_fn(backward_time, augmented_state) 388 adjoint_constants_ode) = tape.gradient( 389 adjoint_dot_derivatives, (state, tuple(variables), constants), → 390 unconnected_gradients=tf.UnconnectedGradients.ZERO) 391 return (negative_derivatives, adjoint_ode, adjoint_variables_ode, 392 adjoint_constants_ode) ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow/python/eager/backprop.py in gradient(self, target, sources, output_gradients, unconnected_gradients) 1078 output_gradients=output_gradients, 1079 sources_raw=flat_sources_raw, → 1080 unconnected_gradients=unconnected_gradients) 1081 1082 if not self._persistent: ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow/python/eager/imperative_grad.py in imperative_grad(tape, target, sources, output_gradients, sources_raw, unconnected_gradients) 75 output_gradients, 76 sources_raw, —> 77 compat.as_str(unconnected_gradients.value)) ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow/python/eager/backprop.py in _gradient_function(op_name, attr_tuple, num_inputs, inputs, outputs, out_grads, skip_input_indices, forward_pass_name_scope) 157 gradient_name_scope += forward_pass_name_scope + “/” 158 with ops.name_scope(gradient_name_scope): → 159 return grad_fn(mock_op, *out_grads) 160 else: 161 return grad_fn(mock_op, *out_grads) ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow/python/ops/array_grad.py in _ConcatGradV2(op, grad) 228 def _ConcatGradV2(op, grad): 229 return _ConcatGradHelper( → 230 op, grad, start_value_index=0, end_value_index=-1, dim_index=-1) 231 232 ~/.conda/envs/mpk/lib/python3.7/site-packages/tensorflow/python/ops/array_grad.py in _ConcatGradHelper(op, grad, start_value_index, end_value_index, dim_index) 117 # in concat implementation to be within the allowed [-rank, rank) range. 118 non_neg_concat_dim = ( → 119 concat_dim._numpy().item(0) % input_values[0]._rank()) # pylint: disable=protected-access 120 # All inputs are guaranteed to be EagerTensors in eager mode 121 sizes = pywrap_tfe.TFE_Py_TensorShapeSlice(input_values, ZeroDivisionError: integer division or modulo by zero
st207551
I was able to resolve this issue! I realized that the parameters which were giving me errors were passed into the function using them as 0-dimensional tensors rather than 1-d tensors; changing to pass them in as 1-d tensors alone solved the issue. Not sure why such a minor difference (0-d vs 1-d) would result in a ZeroDivisionError - if anyone has suggestions on why, I’d really appreciate it! Thank you so much!
st207552
The new TF Decision Forests library is really cool in Colab, and I’m trying to get it working in a Kaggle notebook. Please find below a link to a Kaggle notebook where I’ve successfully used the new Decision Forest library. However, there is an issue with the model_plotter (on bottom of the Kaggle Kernel). Any suggestion on what can be done to plot the model as it worked without a problem in Google Colab? Thank you! kaggle.com TF-DF Car Evaluation 2 Explore and run machine learning code with Kaggle Notebooks | Using data from [Private Datasource]
st207553
Hi NNCV, Thanks (for the positive feedback and alert). TF-DF uses D3 for plotting. And it seems (looking at the console of the web browser development tool) that Jupiter does not support the way TF-DF import D3. A solution, is to re-import D3 in a Jupyer notebook cell: %%javascript require.config({ paths: { d3: "https://d3js.org/d3.v7.min" } }); require(["d3"], function(d3) { window.d3 = d3; }); then, the following like should work fine tfdf.model_plotter.plot_model_in_colab(model, tree_idx=0, max_depth=3) Note that you might have to clear the cell output and reload the webpage. Alternatively, or if you don’t have a Jupiter or a Colab nodebook, the model plot can be exported to an html and visualized separably. For example: with open("/tmp/model.html", "w") as f: f.write(tfdf.model_plotter.plot_model(model, tree_idx=0, max_depth=3)) # Then, open "/tmp/model.html" in any web browser.
st207554
Mathieu: tfdf.model_plotter.plot_model_in_colab(model, tree_idx=0, max_depth=3) Thank you Mathieu! This solves the problem.
st207555
Hello, I recently try to start a project according to the excellent link below, I call it example project. Medium – 16 May 19 Human Activity Recognition using LSTMs on Android — TensorFlow for Hackers... 3 Ever wondered how your smartphone, smartwatch or wristband knows when you’re walking, running or sitting? Reading time: 8 min read In my new project, I plan to collect human activity movement data by some “expert” people to build a “expert” model and save it. So, for example, when I do some activities, the expert model can not only predict what activity I am doing, and tells me the “Similarity”. It means I can realize how much difference between me and the experts in the same activity movement. Can anyone tells me if my idea workable? or give me any hint? Are there any methods I can use in TensorFlow? Any suggestions will be appreciated. Thanks sincerely…
st207556
Hi Anthony, This is a very interesting idea. Some parts that might be hard: Have the comparison (pro vs user) be on the same perspective and position (rotation wise) You might need a model (or algorithm) to pair the movement execution and then compare the differences. There’s also some discussion on the topic here: https://discuss.tensorflow.org/t/what-model-s-for-a-sequence-of-human-poses
st207557
Hello! I’m using the efficientnet model and the 1280 vector output for image similarity. It’s working great and from testing is the best model I’ve found with the amount of data that is used. Sometimes it just does weird things though. Here are the image in question: Imgur: The magic of the Internet 27 The first image is the input, the 2nd which should be found and the third one which is actually found as closest. I’m using a compare script and these are the results of said images: input against image that should be found (img1 vs img2) features shape: (1280,) euclidean: 0.839167594909668 hamming: 1.0 chebyshev: 0.14557853 correlation: 0.36508870124816895 cosine: 0.35210108757019043 minkowski: 0.839167594909668 input against image that is incorrectly returned as closest (img1 vs img3 features shape: (1280,) euclidean: 0.7945413589477539 hamming: 1.0 chebyshev: 0.11684865 correlation: 0.32784974575042725 cosine: 0.3156479597091675 minkowski: 0.7945413589477539 I’m not understanding how img3 can be closer to the input than the other. It’s working most of the time and this is a weird outlier. Any ideas how this can be solved? Thanks!
st207558
No I’m using pre-trained weights. I would train it but I’m not sure what’s the correct course and the benefit. The image database is only filled with one class, namely stamps, so any classification goes out the window.
st207559
You can still use your dataset for metric learning or embedding finetuning. You can use the backbone that you want (also efficientnet). See: keras.io Keras documentation: Image similarity estimation using a Siamese Network with... 29 keras.io Keras documentation: Metric learning for image similarity search 26
st207560
Thank you very much for your suggestions! I’ve stumbled upon metric learning before but it went over my head how to implement it in my case. I’ve figured it out now, wasn’t too difficult once it clicked with the link you provided and the tests I’ve done show good results. The distance is much much closer now. Sometimes nearly 0 which is a big win! I’m still struggling to understand what’s really going on and how this works. From my understanding every layer has weights that can be tuned, in fine-tuning you freeze most of the pre-trained weights. I’m not freezing any right now and I wonder if that’s the best thing to do. From my intuition I’d freeze every weight but the last one I use, the avg_pool but this one and those before don’t have much weights. I fear I skew the weights too much with my limited data set. Any suggestions on this or do you think it’s alright? For reference, I build the model like this: model = tf.keras.applications.EfficientNetB0(include_top=False, weights=‘imagenet’, pooling=‘avg’) embeddings = tf.nn.l2_normalize(model.output, axis=-1) metric_model = EmbeddingModel(model.input, embeddings) model.summary()
st207561
If your dataset is really quite small you could be in a few shot domain. In that case you can take look at some tips in: arXiv.org How to fine-tune deep neural networks in few-shot learning? 11 Deep learning has been widely used in data-intensive applications. However, training a deep neural network often requires a large data set. When there is not enough data available for training, the performance of deep learning models is even worse...
st207562
Well it’s not really a small set. I’ll explain: The goal is to take a camera shot of a real stamp and find a correct lookup in a database that consists of 350k+ unique stamp images. Most of the results are pretty accurate and good, it could be better though, that’s why I’m looking to further train the model. For a lot of stamps I have real camera photos, 10-20 or more which I could compile but: With the metric learning I’m running into the problem that a label is expected and as I technically have over 350k labels I don’t know how to deal with that. In practice, I think metric learning is the right solution but I’m a little stuck right now.
st207563
If you need to retrieve the image from a real camera picture and you don’t have to much real camera images in the wild in your training dateset you will probably need to care about augmentations. E.g. See RandAugmentation in: keras.io Keras documentation: Consistency training with supervision 13
st207564
How should I handle 350k+ classifications? Overall I would need at least 1 million because that’s roughly the count of unique stamps that exist. If I try with 1 million labels I run into OOM errors. This conceptual problem keeps me from doing any meaningful training.
st207565
For the augmentation i was only talking about this: For a lot of stamps I have real camera photos, 10-20 If you are really going to have a large scale classification problem it is going to be quite similar to the large scale face recognition proposed solutions. E.g. Glint360K dataset has 360k identities so quite similar to your 350k+ but with other tricks you can scale also to 10M 20M 30M 100M. See: arXiv.org Partial FC: Training 10 Million Identities on a Single Machine 9 Face recognition has been an active and vital topic among computer vision community for a long time. Previous researches mainly focus on loss functions used for facial feature extraction network, among which the improvements of softmax-based loss... arXiv.org An Efficient Training Approach for Very Large Scale Face Recognition 4 Face recognition has achieved significant progress in deep-learning era due to the ultra-large-scale and well-labeled datasets. However, training on ultra-large-scale datasets is time-consuming and takes up a lot of hardware resource. Therefore,...
st207566
I see that you are using ImageNet Pre-Trained weights of EfficientNet for Feature Extraction. From what I see, either or both of the following issues may be contributing to the weird result: The Keras official implementation of EfficinetNet Expects Un-Normalized Inputs in the range of 0-255. So, in case you are normalizing the input images before feeding them into the network, it may lead to issues. Quote from Documentation: EfficientNet models expect their inputs to be float tensors of pixels with values in the [0-255] range. Source: Keras EfficientNet Documentation 5 The alternative issue (and most likely one) is since the network was pre-trained on ImageNet, which does not contain examples similar to your query and target image, it is possible that the feature map for both these images is the same and/or similar, which is leading to the error in distance calculations. A solution, in this case, would be to train/fine-tune your model on your relevant dataset to get a more relevant feature vector.
st207567
I am trying to build my own word2vec model using the code provided here Link: - Word2Vec  |  TensorFlow Core 3 So i have even tried to increase the data as well for training the word embedding and i am able to achieve a good model accuracy but when i plot the word vectors on the Embedding Projector the distance between words or the word similarity is really bad, if i even use the cosine distance formula between very similar words the result is bad. Whereas if the same data is used to train own embeddings using the Gensim library ( not pre-trained) the results of distance and similarity are way better, even on the Embedding Projector as well. Please can someone help me regarding this, i want to use the Word2Vec code only which is provided by TensorFlow but i am not able to get good results for word distance and word similarity.
st207568
Could there be a problem in how you are serializing the embedding vectors and the associated words? Also, can you confirm there is no difference in the hyperparameters that you are using in TensorFlow and Genism?
st207569
I am sure regarding the serializing of the vectors and associated word. But regarding the hyper-parameters, i have tried my best to use the same but gensim model is like a blackbox so with just one sentence of code i get the entire word vector array, surely there might be some changes in the code or the processing part but the Tensorflow model is giving no result at all.
st207570
Also there has been an issue raised before on the Github Repository of Tensorflow but it doesn’t seem to have been solved. Issue Raised: - The word vector obtained by the word2vec tutorial is very bad · Issue #50645 · tensorflow/tensorflow · GitHub 2
st207571
Hi @aiman_shivani . Sorry, that was posted by mistake. It was not related to the tutorial code.
st207572
Is keras_tuner also able to tune the hyperparameters of xgboost-based models? In particular, I am trying to use keras_tuner to tune the hyperparameters of the blender (an XGBRegressor ) of a stacking regressor. The hyperparameters of its lower-level regressors are already found, so I am only interested in the optimal values for max_depth and learning_rate of the blender. Here is my procedure to do so: import tensorflow as tf from sklearn.datasets import fetch_california_housing from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import StackingRegressor from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.tree import DecisionTreeRegressor import xgboost import keras_tuner as kt housing = fetch_california_housing() X_train_full, X_test, y_train_full, y_test = train_test_split(housing.data, housing.target, train_size=0.8, test_size=0.2) X_train, X_valid, y_train, y_valid = train_test_split(X_train_full, y_train_full, train_size=0.8, test_size=0.2) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.fit_transform(X_test) def build_dnn_reg_opt(): model = tf.keras.Sequential() model.add(tf.keras.layers.InputLayer(input_shape=X_train.shape[1:])) model.add(tf.keras.layers.BatchNormalization(momentum=0.999)) model.add(tf.keras.layers.Dense(42, tf.keras.activations.selu, kernel_initializer="lecun_normal")) model.add(tf.keras.layers.BatchNormalization(momentum=0.999)) model.add(tf.keras.layers.Dense(42, tf.keras.activations.selu, kernel_initializer="lecun_normal")) model.add(tf.keras.layers.BatchNormalization(momentum=0.999)) model.add(tf.keras.layers.Dense(1, kernel_initializer="lecun_normal")) optimizer = tf.keras.optimizers.Adam(learning_rate=0.05) model.compile(loss="mae", optimizer=optimizer, metrics=["mse"]) return model dnn_reg_opt = build_dnn_reg_opt() rnd_reg_opt = DecisionTreeRegressor(max_depth=8, min_samples_leaf=32, max_leaf_nodes=10) rf_reg_opt = RandomForestRegressor(n_estimators=76, max_leaf_nodes=20) def build_model_stack(hp): max_depth = hp.Int("max_depth", min_value=1, max_value=10, step=1) learning_rate = hp.Choice("learning_rate", values=[0.01,0.02,0.03,0.04,0.05,0.06,0.07]) model = StackingRegressor(estimators=[("rnd_reg_opt", rnd_reg_opt), ("rf_reg_opt", rf_reg_opt), ("dnn_reg_opt", dnn_reg_opt)], final_estimator=xgboost.XGBRegressor(max_depth=max_depth, learning_rate=learning_rate)) return model rnd_reg_opt.fit(X_train, y_train) def exponential_decay(lr0, s): def exponential_decay_fn(epoch): return lr0 * 0.1 ** (epoch / s) return exponential_decay_fn exponential_decay_fn = exponential_decay(lr0=0.01, s=20) lr_scheduler_cb = tf.keras.callbacks.LearningRateScheduler(exponential_decay_fn) early_stop_cb = tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=5) dnn_reg_opt.fit(X_train, y_train, validation_data = (X_valid, y_valid), epochs=50, callbacks =[early_stop_cb, lr_scheduler_cb]) rf_reg_opt.fit(X_train, y_train) tuner_BO = kt.BayesianOptimization(build_model_stack, objective=kt.Objective("val_loss", direction="min"), max_trials=10, seed=seed_value) tuner_BO.search(X_train, y_train, epochs=50, validation_data = (X_valid, y_valid), callbacks =[early_stop_cb, lr_scheduler_cb]) best_hps_BO = tuner_BO.get_best_hyperparameters(num_trials=1)[0] print("BO results:") print("max_depth: {0}".format(best_hps_BO.get("max_depth"))) print("learning_rate: {0}".format(best_hps_BO.get("learning_rate"))) But, the following error is thrown: RuntimeError: Model-building function did not return a valid Keras Model instance, found StackingRegressor(estimators=[('rnd_reg_opt', DecisionTreeRegressor(max_depth=8, max_leaf_nodes=10, min_samples_leaf=32)), ('rf_reg_opt', RandomForestRegressor(max_leaf_nodes=20, n_estimators=76)), ('dnn_reg_opt', <tensorflow.python.keras.engine.sequential.Sequential object at 0x0000012D308E0D30>)], final_estimator=XGBRegressor(base_score=None, booster=None, col... importance_type='gain', interaction_constraints=None, learning_rate=0.01, max_delta_step=None, max_depth=1, min_child_weight=None, missing=nan, monotone_constraints=None, n_estimators=100, n_jobs=None, num_parallel_tree=None, random_state=None, reg_alpha=None, reg_lambda=None, scale_pos_weight=None, subsample=None, tree_method=None, validate_parameters=None, verbosity=None)) Can one kindly share a work-around for this issue?
st207573
Is it possible to freeze specific layers when using Tensorflow Object Detection API? For example, I am using EfficientDet downloaded from the Tensorflow 2 Model Zoo. When I train the model, I am going to make it predict whether an object is car,plane or motorcycle. The model is already trained on these types of objects (COCO 2017 dataset), but I want to train it more on my specific use case . But, since it is already trained on these types of object I do not want it to “forget” what it has already learned. Hence, I need to freeze some of the layers. So, is this possible? And, if it is possible, how do I know which layers I actually need to freeze? I have found that I might can use the freeze_variables parameter in the pipeline.config file? Thanks for any help!
st207574
This might be what you’re after Transfer Learning example 10 Specifically these lines: base_model.trainable = True # Let's take a look to see how many layers are in the base model print("Number of layers in the base model: ", len(base_model.layers)) # Fine-tune from this layer onwards fine_tune_at = 100 # Freeze all the layers before the `fine_tune_at` layer for layer in base_model.layers[:fine_tune_at]: layer.trainable = False
st207575
The problem with this is that it is not a Keras model. So as far as I can see it cannot be done like this when models are from the Model Zoo.
st207576
I dont think that model will forget these classes if you have them in your training data.
st207577
After I trained it on some data the accuracy of the model dropped about 20% for the same classes that I want to make prediction on. I would expect it to be around 94% which was the case before training. So something is going on.
st207578
If your model are from the Model Zoo, you also can use Transfer Learning, i.e. to continue train process, but with very small learning_rate, such as 10-7 or 10-8 …based on your train set. In this case, you will improve an accuracy of model, but by a little steps.
st207579
So if I reduce the learning rate it should work to train it on my own data without losing all its “progress”?
st207580
Just getting into Tensorflow and i want to run the tensorflow recommender tutorials with my own data. However, the datastructures there (dict-like, tensors can be addressed by “keys”) do not fit with the datasets structures in the tf.data starters. Can pls someone point me somewhere there i can get a better overview over the dataset types (sub-classes) and best to work with recommenders?
st207581
I am not sure exactly what you want. You can get Tensor from csv file via pandas like this. df = pd.read_csv(‘movie.csv’) tf.data.Dataset.from_tensor_slices(dict(df))
st207582
Thanks, thats it already. I was before only stumbling over examples there the df transformed into an array was a tensor itself, no input using the dict transformation on the df, tensors defined with a name that did not show up if looking at the instances etc.
st207583
Dear all! Thank you for reading this far I was wondering if it is possible to make some kind of machine learning model that made an inference on each of the horizontal lines of an image. That is if I have a 1920x1080 image where each of the 1920 lines represents a spectra and outputs 1080 predictions. I belive that it could be beneficial for the training if I could input this prior knowledge into the model. I want to be able to do this to port it by high-level synthesis to an FPGA for effective edge computing and hoped to be able to generate one (1) TensorFlow model for effective edge computing. The idea was to use PYNQ. If anyone anywhere has anything to add to this idea, e.g. it is a bad idea, I would love to hear from you! Best, Sivert Bakken
st207584
I think that the first point to check Is the status of TF support on this board: PYNQ – 29 Sep 20 Apply Tensorflow model on pynq? 3 @nfmzl @rock Despite that this is a Pynq-Z2, is another option to leverage DPU-PYNQ in conjunction with TVM, assuming that nfmzl can port DPU-PYNQ to the Z2? You should also be able to consider use of the TVM runtime / compiler with no DPU. I... I also suggest to check this: github.com tanmay-ty/SpectralNET 4 Contribute to tanmay-ty/SpectralNET development by creating an account on GitHub.
st207585
I am trying to train a model with tf2 to find ambiguous objects such as small damages or small deformations in vehicles. I have tried several models but I have to lower the threshold to a lot so that it detects something … do you advise me some special model or some configuration for the pipeline.config? Thank you very much
st207586
From the my understanding, if the classes are very similar, you might need a very good dataset with lot’s of examples. How many images/boxes are you using?
st207587
about 8700 images and about 6000 boxes … but the problem is that it is very difficult for the models (I have tried several) to detect these (both damage and deformation) types of objects … I need to lower the threshold of .30 (by default ) to find something … any ideas? Thank you so much
st207588
do you think the resolution of the input image could be too low? to a point where the model wouldn’t have enough information to make a decision?
st207589
I don’t think so because the naked eye is visible … all the images are 800x600 and most of the boxes are visible to the naked eye … I don’t think the data set is the problem, I have tried efficient models (d2 and d3) to lower the learning rate because if I did not start training, it gave me a nan in losses … the truth is that I am a bit lost and I don’t know which parts of the pipeline to modify or if I should look for another model … many thanks for your interest and help.
st207590
Hi everyone, I’m trying to implement a part of this paper: https://people.kth.se/~ghe/pubs/pdf/szekely2019casting.pdf 18 This part specifically: Mel-spectrograms were extracted using the Librosa Python package with a window width of 20 ms and 2.5 ms hop length. The resulting spectrograms for two seconds of audio have 128×800 pixels. Zero crossing rates were calculated on the same windows. The neural network was implemented in Keras following the architecture in Figure 1. The first convolutional layer used 16 2D filters (size 3×3, stride 1×1) and ReLU nonlinearities, followed by batch normalisation and 5×4 max-pooling in both time and frequency. The second 2D convolutional layer used 8 filters in the frequency domain (4×1) and ReLU, followed by batch norm and 6×5 max pooling. Due to downsampling by the pooling layers, this produced 40 1×1 cells with 8 channels at a rate of 20 times per second. These were fed into a bidirectional LSTM layer of 8 hidden units in each direction, followed by a softmax output layer. The network was randomly initialised and trained for 40 epochs to minimise cross-entropy using Adadelta (with default parameters) batches of 16 two-second spectrogram excerpts. The softmax outputs can be interpreted as estimated per-frame class probabilities and used to automatically annotate the held-out episodes. Prior to further processing by either method, the temporal coherence of the automatic annotations was improved by merging mixed speech after a single-speaker segment into that speaker’s speech. This is what I have : import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential( [ keras.Input(shape=(128, 800, 2)), layers.Conv2D(16, (3, 3), activation='relu'), layers.BatchNormalization() layers.MaxPooling2D(pool_size=(5, 4)), layers.Conv2D(8, (4, 1), activation='relu'), layers.BatchNormalization() layers.MaxPooling2D(pool_size=(6, 5)), layers.Bidirectional(layers.LSTM(8)) layers.Dense(7), ] ) model.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer = keras.optimizers.Adadelta(), metrics = ["accuracy"], ) model.fit(x_train, y_train, epochs=40, batch_size=16) Can someone please help?
st207591
What do you need in particular? Do you need to prepare audio data? TensorFlow Audio Data Preparation and Augmentation  |  TensorFlow I/O 6
st207592
Thanks for the response @Bhack The code that I have shared above should implementat the model architecture specified in the block quotes. But my code clearly does not do that. I’d really be grateful if you could look at my code and suggest edits to it so that it represents the architecture described in the block quotes. Architecture of the model is also given as an image in the paper whose link I have shared above. I’m not able to attach images (because of permissions i guess) otherwise I would have added that also.
st207593
Capture21441×411 126 KB I am able to upload the image of the architecture now @Bhack
st207594
Some quick updates, I added a TimeDistributed layer now the code looks like this: import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential( [ keras.Input(shape=(128, 800, 2)), layers.Conv2D(16, (3, 3), activation='relu', padding='same'), layers.BatchNormalization(), layers.MaxPooling2D(pool_size=(5, 4)), layers.Conv2D(8, (1, 4), activation='relu', padding='same'), layers.BatchNormalization(), layers.MaxPooling2D(pool_size=(6, 5)), layers.TimeDistributed(layers.Flatten()), layers.Bidirectional(layers.LSTM(8)), layers.Dense(7), ] ) model.summary() model.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer = keras.optimizers.Adadelta(), metrics = ["accuracy"], ) This is some progress but far from what is described in the image and description above.
st207595
Maybe because you dont have stride in the MaxPooling layers. The paper does not specify this. Plus input in the paper is 128x800, yours 128x800x2.
st207596
@Kzyh I dont think so. They say However, we also investigated augmenting the frequency-domain spectra with timedomain information to improve classification. In particular, the zerocrossing rate (ZCR) has been shown to be an effective feature for differentiating breath events from unvoiced fricatives [25, 13] and have also been of interest for detecting overlapped speech [26]. It is defined as the number of times the audio waveform changes sign divided by the total number of samples in the window. and more importantly We added ZCR as another image channel to each spectrogram cell So the input shape is fine I think.
st207597
@Kzyh the paper does say however that The second 2D convolutional layer used 8 filters in the frequency domain and …this produced 40 1×1 cells with 8 channels at a rate of 20 times per second. These were fed into a bidirectional LSTM layer of 8 hidden units in each direction… I am unsure about these parts.
st207598
I think last pooling layers should output [x, 1, 40, 8], then after squeeze [x, 40, 8] you can feed this to LSTM. But with parameters used in paper last pooling ouptputs [x, 3, 39, 8].
st207599
@Kzyh when I set padding='valid' instead of padding=same then model.summary is: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 128, 800, 16) 304 _________________________________________________________________ batch_normalization (BatchNo (None, 128, 800, 16) 64 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 25, 200, 16) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 25, 200, 8) 520 _________________________________________________________________ batch_normalization_1 (Batch (None, 25, 200, 8) 32 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 4, 40, 8) 0 _________________________________________________________________ time_distributed (TimeDistri (None, 4, 320) 0 _________________________________________________________________ bidirectional (Bidirectional (None, 16) 21056 _________________________________________________________________ dense (Dense) (None, 7) 119 ================================================================= Total params: 22,095 Trainable params: 22,047 Non-trainable params: 48