id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st205400 | This works, but I don’t know if it’s the preferred way in TF 1:
import tensorflow as tf
from tensorflow.keras import backend as K
tf.compat.v1.disable_eager_execution()
with tf.compat.v1.Session() as sess:
example = tf.random.normal([4, 4, 2, 2], mean=1, stddev=4, seed = 1)
print_example = tf.compat.v1.print(example)
# Print absolute maximum value (shape: ())
abs_max = K.max(example, axis=None)
print_abs_max = tf.compat.v1.print(abs_max)
sess.run([print_example, print_abs_max]) |
st205401 | Hey there,
maybe some of you can help me to drop me off from misunderstanding list of input_shape.
I am using dataset to gen data.
The window is 10, and I divide x with size 5 and y with size 5.
Then the dataset will go ahead to the model, I just work with a simple Sequential one and give input_shape (3,1) to to first layer, fe. lstm.
I can fit the model.
I predict random values from (1, 1) as input_shape to (10, 1) as input_shape.
So what does input_shape mean actually? I lost it so deeply…
Full code:
import numpy as np
import tensorflow as tf
data = np.random.randn(5000)
data = data[...,np.newaxis]
sp = int(len(data) * .5)
train_data = data[:sp]
valid_data = data[sp:]
def windowed_set(data):
win_sz=10
ds = tf.data.Dataset.from_tensor_slices(data)
ds = ds.window(size=win_sz, shift=1, drop_remainder=True).flat_map(lambda w: w.batch(win_sz))
ds = ds.shuffle(win_sz).map(lambda w: (w[:int(win_sz*0.5)], w[int(win_sz*0.5):]))
ds = ds.batch(32).prefetch(1)
return ds
train_set = windowed_set(train_data)
valid_set = windowed_set(valid_data)
#Model definition
model = tf.keras.models.Sequential([
tf.keras.layers.LSTM(32,
input_shape=[3, 1],
return_sequences=True),
tf.keras.layers.Dense(1)
])
model.summary()
model.compile(loss=tf.keras.losses.Huber(),
optimizer=tf.keras.optimizers.Adam())
#Training
model.fit(train_set,
validation_data=valid_set,
epochs=50,
verbose=0)
#Prediction
for i in range(1, 11):
print(f"prediction {i} bit:")
pred_input = np.random.rand(i)
pred_input = np.expand_dims(pred_input, axis=-1)
print(pred_input.shape)
pred = model.predict(np.reshape(pred_input, (1,) + pred_input.shape))
print(pred)
print() |
st205402 | Input shape is the dimension of the input data, for example in case you have image data a Keras model needs an input_shape of (height, width, num_channels) , if you are feeding a model with an input of (3, 1) the model will learn dependences of three consecutive elements. larger the window more information the model considers about the temporal dependences of observations in the sequence.
Sometimes you can have dynamic input shapes ex, images with variable height/width. You can check more details here tf.keras.Input | TensorFlow Core v2.5.0 2 |
st205403 | miguelalba96:
Input shape is the dimension of the input data, for example in case you have image data a Keras model needs an input_shape of (height, width, num_channels) , if you are feeding a model with an input of (3, 1) the model will learn dependences of three consecutive elements. larger the window more information the model considers about the temporal dependences of observations in the sequence.
thx @miguelalba96 .
According to your statement, the training will be performed by the dependencies of input_shape instead of the shape of the batch’s input samples, right? correct me if I am wrong.
So, what I mean here, for example, the samples are with window 100, the training will still be performed with 3 and ignore the rest of 97?
Btw, the compiler doesn’t give any warnings there… |
st205404 | You have the following architecture:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm (LSTM) (None, 3, 32) 4352
_________________________________________________________________
dense (Dense) (None, 3, 1) 33
=================================================================
Total params: 4,385
Trainable params: 4,385
Non-trainable params: 0
_________________________________________________________________
If I feed one tensor created with your code in the model:
train_set = iter(train_set)
batch = next(train_set)
out = model(batch[0])
you will get the warning:
WARNING:tensorflow:Model was constructed with shape (None, 3, 1) for input KerasTensor(type_spec=TensorSpec(shape=(None, 3, 1), dtype=tf.float32, name='lstm_1_input'), name='lstm_1_input', description="created by layer 'lstm_1_input'"), but it was called on an input with incompatible shape (32, 5, 1)
therefore your model is only considering 3 time steps from the 5 you are feeding, have a look here:How to Reshape Input Data for Long Short-Term Memory Networks in Keras 3 , this this could help you to understand the input logic in LSTM models |
st205405 | Hey all!
I think I’m struggling with a core concept here so bare with me! I’ve created a simple model to test my deployment infrastructure. I am using structured data and have followed this guide from the TF site. One of the key steps in model training is converting the data into tensors using tf.data.Dataset.from_tensor_slices. I understand why this is done but when I have deployed my model and I make a request to the endpoint I have to send my data in the JSON format, not as a tensor. This appears to cause a data type issue.
Do I have to create a preprocessing layer in my model that converts JSON or a dataframe into a Tensor using the above function? I have struggled to find examples of this so any help would be greatly appreciated!
Thanks |
st205406 | Hi,
I’m following Custom operators | TensorFlow Lite 3 to create a custom operator (to use it on a micocontroller) which can be supported by Tensorflow Lite. For the sine operator the tutorial uses
converter = tf.lite.TFLiteConverter.from_concrete_functions([sin.get_concrete_function(x)])
converter.allow_custom_ops = True
tflite_model = converter.convert()
Does this snippet of code allow you to convert the entire model which uses sine op, right? |
st205407 | Hello.
I want to use Tensor Flow to classify parts using a camera.
So to create my dataset, to teach the CNN, I want to use 3D image.
I use a 3D generator to create image of all parts in many position. Taking pictures of all the parts in many position, that I want to classify is not possible because I have lot of differents parts.
My problem is when I use my CNN with real image, it did classify my parts.
What is the best way to classify real image with “virtual” image ?
I found lot of article, that explain the theory. I look for article about real exemple, and / or sample code.
Thanks for help. |
st205408 | To explore more in depth all the domain adaptation issues I suggest to take a look at:
arXiv.org
Synthetic Data for Deep Learning 2
Synthetic data is an increasingly popular tool for training deep learning
models, especially in computer vision but also in other areas. In this work, we
attempt to provide a comprehensive survey of the various directions in the
development and...
arXiv.org
Unsupervised Domain Adaptation of Object Detectors: A Survey 1
Recent advances in deep learning have led to the development of accurate and
efficient models for various computer vision applications such as
classification, segmentation, and detection. However, learning highly accurate
models relies on the...
Also if It Is a little bit old, if you want some reference implementations, check the sim2real challenge leaderboard:
paperswithcode.com
Papers with Code - Syn2Real-C Benchmark (Synthetic-to-Real Translation) 1
The current state-of-the-art on Syn2Real-C is DADA. See a full comparison of 6 papers with code. |
st205409 | Trying to read the tfrecord file and use it to train the model with .fit call but getting this error:
TypeError("dataset length is unknown.")
Here’s my tfrecord code:
FEATURE_DESCRIPTION = {
'lr': tf.io.FixedLenFeature([], tf.string),
'hr': tf.io.FixedLenFeature([], tf.string),
}
def parser(example_proto):
parsed_example = tf.io.parse_single_example(example_proto, FEATURE_DESCRIPTION)
lr = tf.io.decode_jpeg(parsed_example['lr'])
hr = tf.io.decode_jpeg(parsed_example['hr'])
return lr, hr
train_data = tf.data.TFRecordDataset(TFRECORD_PATH)\
.map(parser)\
.batch(BATCH_SIZE, drop_remainder = True)\
.prefetch(tf.data.AUTOTUNE)
And len(train_data) is giving error TypeError("dataset length is unknown.") because the cardinality is -2, or in other words the train_data is unable to capture the total number of samples because the dataset source is a file.
Is there any way we can tell the train_data how many samples/batches are there? |
st205410 | Check this thread:
https://discuss.tensorflow.org/t/typeerror-dataset-length-is-unknown-tensorflow/ |
st205411 | The solution is to manually set the cardinality as below:
# print(len(train_data)) gives error
train_data = train_data.apply(tf.data.experimental.assert_cardinality(NUM_BATCHES))
print(len(train_data)) # NUM_BATCHES |
st205412 | Disclosure: Self Taught
I am trying to use recall on 2 of 3 classes as a metric, so class B and C from classes A,B,C.
(The original nature of this is that my model is highly imbalanced in the classes [~90% is class A], such that when I use accuracy I get results of ~90% for prediciting class A everytime)
model.compile(
loss='sparse_categorical_crossentropy', #or categorical_crossentropy
optimizer=opt,
metrics=[tf.keras.metrics.Recall(class_id=1, name='recall_1'),tf.keras.metrics.Recall(class_id=2, name='recall_2')]
)
history = model.fit(train_x, train_y, batch_size=BATCH, epochs=EPOCHS, validation_data=(validation_x, validation_y), callbacks=[tensorboard, checkpoint])
This spits out an error:
raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (None, 3) and (None, 1) are incompatible
Model summary is:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm (LSTM) (None, 120, 32) 19328
_________________________________________________________________
dropout (Dropout) (None, 120, 32) 0
_________________________________________________________________
batch_normalization (BatchNo (None, 120, 32) 128
_________________________________________________________________
lstm_1 (LSTM) (None, 120, 32) 8320
_________________________________________________________________
dropout_1 (Dropout) (None, 120, 32) 0
_________________________________________________________________
batch_normalization_1 (Batch (None, 120, 32) 128
_________________________________________________________________
lstm_2 (LSTM) (None, 32) 8320
_________________________________________________________________
dropout_2 (Dropout) (None, 32) 0
_________________________________________________________________
batch_normalization_2 (Batch (None, 32) 128
_________________________________________________________________
dense (Dense) (None, 32) 1056
_________________________________________________________________
dropout_3 (Dropout) (None, 32) 0
_________________________________________________________________
dense_1 (Dense) (None, 3) 99
=================================================================
Total params: 37,507
Trainable params: 37,315
Non-trainable params: 192
Note that the model works fine without the errors if using:
metrics=['accuracy']
but this and this made me think something has not been implemented along the lines of tf.metrics.SparseCategoricalRecall()
from
tf.metrics.SparseCategoricalAccuracy()
So I diverted to a custom metric which decended into a rabbit hole of other issues as I am highly illeterate when it comes to classes and decorators.
I botched this together from an custom metric example (I have no idea how to use the sample_weight so I commented it out to come back to later):
class RelevantRecall(tf.keras.metrics.Metric):
def __init__(self, name="Relevant_Recall", **kwargs):
super(RelevantRecall, self).__init__(name=name, **kwargs)
self.joined_recall = self.add_weight(name="B/C Recall", initializer="zeros")
def update_state(self, y_true, y_pred, sample_weight=None):
y_pred = tf.argmax(y_pred, axis=1)
report_dictionary = classification_report(y_true, y_pred, output_dict = True)
# if sample_weight is not None:
# sample_weight = tf.cast(sample_weight, "float32")
# values = tf.multiply(values, sample_weight)
# self.joined_recall.assign_add(tf.reduce_sum(values))
self.joined_recall.assign_add((float(report_dictionary['1.0']['recall'])+float(report_dictionary['2.0']['recall']))/2)
def result(self):
return self.joined_recall
def reset_states(self):
# The state of the metric will be reset at the start of each epoch.
self.joined_recall.assign(0.0)
model.compile(
loss='sparse_categorical_crossentropy', #or categorical_crossentropy
optimizer=opt,
metrics=[RelevantRecall()]
)
history = model.fit(train_x, train_y, batch_size=BATCH, epochs=EPOCHS, validation_data=(validation_x, validation_y), callbacks=[tensorboard, checkpoint])
This aim is to return a metric of [recall(b)+recall(c)/2]. I’d imagine returning both recalls seperately like metrics=[recall(b),recall(c)] would be better but I can’t get the former to work anyway.
I got a tensor bool error: OperatorNotAllowedInGraphError: using a 'tf.Tensor' as a Python 'bool' is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature. which googling led me to add: @tf.function above my custom metric class.
This led to a old vs new class type error:
super(RelevantRecall, self).__init__(name=name, **kwargs)
TypeError: super() argument 1 must be type, not Function
which I didn’t see how I had achieved since the class has an object?
As I said I’m quite new to all aspects of this so any help on how to achieve (and how best to achieve) using a metric of only a selection of prediciton classes would be really appreciated.
OR
if I am going about this entirely wrong let me know/guide me to the correct resource please
Ideally I’d like to go with the former method of using tf.keras.metrics.Recall(class_id=1.... as it seems the neatest way if it worked.
I am able to get the recall for each class when using a similar function in the callbacks part of the model, but this seems more intensive as I have to do a model.predict on val/test data at the end of each epoch.
Also unclear if this even tells the model to focus on improving the selected class (i.e difference in implementing it in metric vs callback) |
st205413 | Hey there!
I want to achieve human pose estimation inside a react Native App but I can’t find any docs or resources on how to do it.
I know from this blog TensorFlow.js for React Native is here! — The TensorFlow Blog 38 that Tensorflow.js integration with React Native is possible and blog explains how to add " tensorflow-models/mobilenet" in a React Native app but I want to utilize tensorflow’s posenet model.
I was able to install the necessary dependencies for Tensorflow.js, following the same blog and set up the development environment successfully.
I want to achieve something similar to what is showcased in the beginning of this blog.
I also found some example of posenet with React that run on browser but nothing related to building an android app using React Native.
I am new to both Tensorflow and React native so I was hoping if anyone could provide my some docs or instructions specific to the integration of posenet model and tensorflow.js into a React Native app. |
st205414 | You may find this tutorial/write up useful:
Medium – 13 May 20
Image Classification on React Native with TensorFlow.js and MobileNet 111
Real-time, on-device image classification in a React Native app.
Reading time: 7 min read |
st205415 | I’m using tensorflow 2.3.0 but I disable v2 behaviour. I’m struglling to find way to differentiate the loss with respect to input and update the input instead of model weight.I use input as tf.Variable but it always has error : zip argument #2 must support iteration. Can anyone give me an example of how to apply gradient descent wrt input (Not change network at this step)? Or please helpe me fix this code:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
x = tf.Variable(name =“x”,initial_value = np.array([[3.0,3.0],[2.0,2.0]]).astype(np.float32),dtype = tf.float32)
y = tf.Variable(name =“y”,initial_value = np.array([[3.0],[4.0]]).astype(np.float32),dtype = tf.float32)
w1 = tf.Variable(tf.ones([2,3]))
w2 = tf.Variable(tf.ones([3,1]))
hidden = tf.matmul(tf.transpose(x),w1)
output = tf.matmul(hidden,w2)
loss = output - y
optimizer = tf.train.GradientDescentOptimizer(1)
gradient = optimizer.compute_gradients(loss,y)
minimize =optimizer.apply_gradients(zip(gradient, x))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(“before gradient descent”)
print(“x—\n”,x.eval(),"\n",“y—\n”,y.eval())
print(“w1—\n”,w1.eval(),"\n",“w2—\n”,w2.eval())
x_,y_,w1_,w2_,hidden_,output_,loss_,gradient_ = sess.run([x,y,w1,w2,hidden,output,loss,gradient])
print("*****after gradient descent*****")
print("w1---\n",w1_,"\n","w2---\n",w2_)
print("x---\n",x_,"\n","y_---\n",y_)
print("output_---\n",output_)
print("hidden_---\n",hidden_)
print("loss_---\n",loss_,"\n")
print("gradient_---\n",gradient_,"\n") |
st205416 | I found that stringtohashbucketop and stringtokeyedhashbucketop only deal with value override without hash collision handling. Why?
//tensorflow/tensorflow/core/kernels/string_to_hash_bucket_fast_op.h
typedef decltype(input_flat.size()) Index;
for (Index i = 0; i < input_flat.size(); ++i) {
const uint64 input_hash = hash(input_flat(i));
const uint64 bucket_id = input_hash % num_buckets_;
// value override without hash collision handling
output_flat(i) = static_cast<int64>(bucket_id);
}
//tensorflow/tensorflow/core/kernels/string_to_hash_bucket_op.h
typedef decltype(input_flat.size()) Index;
for (Index i = 0; i < input_flat.size(); ++i) {
const uint64 input_hash = hash(input_flat(i));
const uint64 bucket_id = input_hash % num_buckets_;
// value override without hash collision handling
output_flat(i) = static_cast<int64>(bucket_id);
} |
st205417 | I don’t quite understand why these two models defined with functional API:
inp = layers.Input((10,2))
x = layers.Flatten()(inp)
x = layers.Dense(5)(x)
m1 = keras.models.Model(inputs=inp, outputs=x)
and OO way:
class MyModel(tf.keras.Model):
def __init__(self, inp_shape, out_size = 5):
super(MyModel, self).__init__()
self.inp = layers.InputLayer(input_shape=inp_shape)
self.flatten = layers.Flatten()
self.dense = layers.Dense(out_size)
def call(self, a):
x = self.inp(a)
x = self.flatten(x)
x = self.dense(x)
return x
m2 = MyModel((10,2))
m2.build(input_shape = (10,2))
give different results:
> m1.summary()
Model: "functional_3"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_17 (InputLayer) [(None, 10, 2)] 0
_________________________________________________________________
flatten_19 (Flatten) (None, 20) 0
_________________________________________________________________
dense_18 (Dense) (None, 5) 105
=================================================================
Total params: 105
Trainable params: 105
Non-trainable params: 0
> m2.summary()
Model: "my_model_9"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_18 (InputLayer) [(None, 10, 2)] 0
_________________________________________________________________
flatten_20 (Flatten) multiple 0
_________________________________________________________________
dense_19 (Dense) multiple 15
=================================================================
Total params: 15
Trainable params: 15
Non-trainable params: 0
When I test it with on some toy tensor, I get:
> tsta = np.random.randn(3,10,2)
> m1(tsta) # correct
> m2(tsta)
InvalidArgumentError: Matrix size-incompatible: In[0]: [3,20], In[1]: [2,5] [Op:MatMul]
What I want to achieve is to have exactly the same model as m1 but with subclassed API. |
st205418 | You could try my example:
import tensorflow as tf
tsta = tf.random.uniform([3,10,2])
tf.random.set_seed(111111)
inp = tf.keras.layers.Input((10,2))
x = tf.keras.layers.Flatten()(inp)
x = tf.keras.layers.Dense(5)(x)
m1 = tf.keras.Model(inputs=inp, outputs=x)
m1.build(input_shape = (3, 10, 2))
m1.summary()
print(m1(tsta))
tf.random.set_seed(111111)
class MyModel(tf.keras.Model):
def __init__(self, out_size = 5):
super(MyModel, self).__init__()
self.flatten = tf.keras.layers.Flatten()
self.dense = tf.keras.layers.Dense(out_size)
def call(self, x):
x = self.flatten(x)
x = self.dense(x)
return x
m2 = MyModel()
m2.build(input_shape = (3, 10, 2))
m2.summary()
print(m2(tsta)) |
st205419 | Thanks, and why the summary of m2 gives:
Model: "my_model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
flatten_4 (Flatten) multiple 0
_________________________________________________________________
dense_4 (Dense) multiple 105
=================================================================
so you see how there’s multiple in the output? The whole reason why I’m struggling with this is because I want to check the output sizes of my model objects (slightly more complicated than that), but what I’m getting so far is mulitple. Any remedy for this? |
st205420 | Subclass model doesn’t record any shape info about layers such as layer.output_shape.
So it prints multiple. |
st205421 | Hey there,
I’ve created a simple model on teachablemachine. Could you please tell me how I can now loop this model so that I can upload a catalog of images into it and, at the exit, get a file for a spreadsheet where the results for each image will be.
teachablemachine.withgoogle.com
Teachable Machine 2
Train a computer to recognize your own images, sounds, & poses.
A fast, easy way to create machine learning models for your sites, apps, and more – no expertise or coding required.
Thank you! |
st205422 | Hi @Yan_Mednis
Since you have it on a TFJS format, I think you might be able to do the loop using Javascript.
Do you want to just upload this batch of images from the catalogue or is it a service you are building?
for the output, I’d focus on generating a CSV with the data and then import it on Sheets, might be easier than using the Sheets api (if you don’t know that yet)
@Jason might have some much better insights than mine on this. |
st205423 | If you look at the example code that Teachable Machine provides it shows you how to call the model classification function. You simply would call this many times (remember each time to wait for the previous classification to complete else you may overload the machine). In case you didnt see it, after you trained a model with Teachable Machine there is an “export model” button at the top right of the screen. Click that, download the model files and host them on your web server, and then check the sample HTML + JS code for how to use your downloaded model (remember to change the path to where you hosted the model files):
<div>Teachable Machine Image Model</div>
<button type="button" onclick="init()">Start</button>
<div id="webcam-container"></div>
<div id="label-container"></div>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@teachablemachine/[email protected]/dist/teachablemachine-image.min.js"></script>
<script type="text/javascript">
// More API functions here:
// https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/image
// the link to your model provided by Teachable Machine export panel
const URL = "./my_model/";
let model, webcam, labelContainer, maxPredictions;
// Load the image model and setup the webcam
async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
// Convenience function to setup a webcam
const flip = true; // whether to flip the webcam
webcam = new tmImage.Webcam(200, 200, flip); // width, height, flip
await webcam.setup(); // request access to the webcam
await webcam.play();
window.requestAnimationFrame(loop);
// append elements to the DOM
document.getElementById("webcam-container").appendChild(webcam.canvas);
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
}
async function loop() {
webcam.update(); // update the webcam frame
await predict();
window.requestAnimationFrame(loop);
}
// run the webcam image through the image model
async function predict() {
// predict can take in an image, video or canvas html element
const prediction = await model.predict(webcam.canvas);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
}
}
</script> |
st205424 | Data : Lists of ordered sequences, some of which may contain nested sequences.(As in the example below)
I have input sequences that contain not just single elements, but also lists.
Eg : i1 = [2, 5, 10, [1, 7 ,9 , 20], 11, 32].
If it were just a sequence like [2,4,6,7] that does not contain a nested sequence, I would just directly pass them to the embedding layer. But, in my case, that’s not possible.
The elements in my sequences are ordered by their date/time of occurrence.
So, for each ID, I have a sequence of ordered events.
Sometimes, multiple events occur on the same day, which leads to nested lists.
For example, consider the sequence [A, B, [D, C, I, K], M]
This means, Event A has occurred on day 1, event B on day two, and events[D,C,I,K] on day 3 etc.
So, given a sequence of events for each unique ID, my goal is to predict what will be the next event/sequence of events via an LSTM model.
I have just converted these events represented by text into integer tokens, and subsequently got their count vectors/one-hot vector representation.
But, I’m facing troubles getting embeddings from such an input representation.
Embedding layers in TF/Keras would only accept integer tokens and not one-hot vectors as input.
So could someone please tell me how to get embeddings for such input representation?
Could someone please provide a simple working example for some sample sequences like this?
[A, B, [D, C, E], L]
[[S,T,B], M]
[M, N, [L,U]]
[A, B, L]
Where A, B, C,… etc are events represented by text and lets say I want to represent those events by embedding vectors of size 50 or 100. With padding length = 4. In that case, my Input dim should be (None, 4) and the output via embedding layer should be (None, 4, 50) or (None, 4, 100) depending on the vector size. [None - batch size]
With Integer tokens :
A - 1, B-2, C-3, D-4, E-5, L-6, M-7, N-8, P-9, S-10, T-11, U-12
The padded sequences would look like this :
1. [1, 2, [4,3,5], 6, 0]
2. [[10, 11, 2], 7, 0, 0]
3. [7, 8, [6, 12], 0]
4. [1, 2, 6, 0]
Now, could someone please help me get outputs from embedding layer of the shape (Batch_size, seq_len, dim_len)?
Or, are there better suggestions to represent my LSTM input which contains nested sequences ? |
st205425 | This will give you a good overview of the topic in different domains:
arXiv.org
Generalizing from a Few Examples: A Survey on Few-Shot Learning 10
Machine learning has been highly successful in data-intensive applications
but is often hampered when the data set is small. Recently, Few-Shot Learning
(FSL) is proposed to tackle this problem. Using prior knowledge, FSL can
rapidly generalize to...
Then probably you could find something more specific for your application target. |
st205426 | Given that Siamese networks can work for one-shot learning (such as image recognition (Koch, Zemel & Salakhutdinov (2015) 3, Jadon (2020) 2), maybe you could try adapting these Siamese net examples from the Keras community @fchollet:
Image similarity estimation using a Siamese Network with a triplet loss 7
Image similarity estimation using a Siamese Network with a contrastive loss 4
Perhaps, @Sayak_Paul knows more about this. |
st205427 | In case you’re interested in few-shot learning examples, which are somewhat related:
MAML (model-agnostic meta-learning): tensorflow-maml/maml.ipynb at master · hereismari/tensorflow-maml · GitHub 7
image831×429 148 KB
(from the MAML paper by Finn, Abbeel & Levine (2017) 2)
The Keras community created an implementation of a MAML-inspired method called Reptile here: Few-Shot learning with Reptile 1 (cc @fchollet )
image832×429 106 KB
(from the Reptile paper by Nichol, Achiam & Schulman (2018)). |
st205428 | I don’t know your domain but e.g. if you want an high level API example for the object detection API in model garden we have:
github.com
tensorflow/models/blob/master/research/object_detection/colab_tutorials/eager_few_shot_od_training_tf2_colab.ipynb 7
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "rOvvWAVTkMR7"
},
"source": [
"# Eager Few Shot Object Detection Colab\n",
"\n",
"Welcome to the Eager Few Shot Object Detection Colab --- in this colab we demonstrate fine tuning of a (TF2 friendly) RetinaNet architecture on very few examples of a novel class after initializing from a pre-trained COCO checkpoint.\n",
"Training runs in eager mode.\n",
"\n",
"Estimated time to run through this colab (with GPU): \u003c 5 minutes."
]
},
{
"cell_type": "markdown",
"metadata": {
This file has been truncated. show original
For TFLite
github.com
tensorflow/models/blob/master/research/object_detection/colab_tutorials/eager_few_shot_od_training_tflite.ipynb 4
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "rOvvWAVTkMR7"
},
"source": [
"# Introduction\n",
"\n",
"Welcome to the **Few Shot Object Detection for TensorFlow Lite** Colab. Here, we demonstrate fine tuning of a SSD architecture (pre-trained on COCO) on very few examples of a *novel* class. We will then generate a (downloadable) TensorFlow Lite model for on-device inference.\n",
"\n",
"**NOTE:** This Colab is meant for the few-shot detection use-case. To train a model on a large dataset, please follow the [TF2 training](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_training_and_evaluation.md#training) documentation and then [convert](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_on_mobile_tf2.md) the model to TensorFlow Lite."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3U2sv0upw04O"
},
This file has been truncated. show original |
st205429 | When convert FP TF models to TFlite models, how can I specify the precision of each operations? I understand how to specify the integer precision of weights and activations, but how can I get information (and set) how each operation is computed? For example, if I have an element-wise addition, how do I know if the addition is computed in 8, 16, or 32bits?
As a practical example, say I need to compute z=x+y for a residual connection. x and y are both 8 bits tensors from previous conv layers. How can I compute x+y in 16 bits? It seems to me that TFlite hasn’t offered such flexibility? |
st205430 | I’m working with tflite on Android, and I have a model architecture that’s a MobilenetV2 backbone, and a GRU RNN, trained with CTC loss. I want to use ctc beam search decoding at inference time.
I’ve successfully made a .tflite model and tested that I can load it up and get the expected behaviour on my local machine.
BUT, it doesn’t work on my Android project as I get this error:
Could not build model from the provided pre-loaded flatbuffer: Unsupported custom op: FlexCTCBeamSearchDecoder, version: 1
The error is raised when I try to instantiate this class:
package com.stampfree.validation.tflite;
import android.app.Activity;
import java.io.IOException;
/** This TensorFlowLite classifier works with the float MobileNet model. */
public class DigicodeMobileNet extends Classifier {
/**
* Initializes a {@code ClassifierFloatMobileNet}.
*
* @param device a {@link Device} object to configure the hardware accelerator
* @param numThreads the number of threads during the inference
* @throws IOException if the model is not loaded correctly
*/
public DigicodeMobileNet(Activity activity, Device device, int numThreads)
throws IOException {
super(activity, device, numThreads);
}
@Override
protected String getModelPath() {
return "tf_mobilenetv2_128x768_ctc_post_epoch08.tflite";
}
}
I have tried this using the default dependencies:
dependencies {
implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly-SNAPSHOT'
implementation 'org.tensorflow:tensorflow-lite-select-tf-ops:0.0.0-nightly-SNAPSHOT'
}
and by building the AAR in a docker container.
Both approaches gave the same result.
Any tips? Happy to share more context on request. |
st205431 | Hi @Alexander_Soare
I have used a FlexCTCGreedyDecoder operator before at this 8 project. It seems that adding the
implementation 'org.tensorflow:tensorflow-lite-select-tf-ops:0.0.0-nightly dependency worked fine and to drop 70MB of the final .apk I have used also the building the AAR in a docker container. It is strange that it does not work for you.
First try with the above dependency and not the SNAPSHOT one. If you need explicitly the SNAPSHOT dependency check again the documentation here 2.
Ping me again if neither worked.
Thanks |
st205432 | 微信截图_202107122034342560×1238 304 KB
微信截图_202107122034482560×1238 293 KB
TensorFlow
Get started with microcontrollers | TensorFlow Lite 2
I can’t open the links to these examples |
st205433 | The fix is on the way, thanks for flagging this.
Meanwhile, if you’re looking for the links, here they are:
Hello, World - repo: tflite-micro/tensorflow/lite/micro/examples/hello_world at main · tensorflow/tflite-micro · GitHub 6
Hello, World - README: tflite-micro/README.md at main · tensorflow/tflite-micro · GitHub 5
Training - README: https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/examples/hello_world/train/README.md 1
Training - Colab: tflite-micro/train_hello_world_model.ipynb at main · tensorflow/tflite-micro · GitHub 1
cc @Advait_Jain |
st205434 | I am following the tutorial about Time Series from the official documentation of Tensorflow (Time series forecasting | TensorFlow Core 6)
Very early in the tutorial they transform the datetime to Sine and Cosine signals to help train the model. This signals are created using the number of seconds in a day and year. They then explain that it can be checked using a FFT function. In the graph that is generated there are clear peaks on “1/year” and “1/day”. I guess this is the reason they used this timelapses to create the Sine and Cosine columns.
In a classic FFT, the Y axis usually represents the amplitude of a sound, for instance. My question relies on what this stands for in terms of time and why the peaks are the values chosen for the sine and cosine columns. |
st205435 | Yes. I wrote this.
I’m no meterologist. But we all naturally expect the weather to act differently depending on the time of day, and the time of year.
The sine and cos signals I pass to the model are just a convenient and smooth way to tell it the time of day and time of year.
But even more simply, we also expect there to be some periodicity at 1/day and 1/year (the sun is important). A linear model with just those two sine and cos features will be able to account for that periodicity.
One way to think of the FFT is as the linear model weights for the sine and cos across every frequency. In this special case (orthonormal functions) the weights are the portion of the variance contained in the signal at each frequency.
You could use any sin/cos frequencies as input, but those two frequencies are good choices since that’s where a lot of the variance is. |
st205436 | Thank you for your explanation, I know understand the meaning behind the FFT shown in the tutorial.
I have one further question related to the tutorial. On all the single shot models this layer is added to the model:
tf.keras.layers.Dense(OUT_STEPS*num_features, kernel_initializer=tf.initializers.zeros()) ,
My question is about the reasoning behind “OUT_STEPS*num_features” as the way to set the number of units for the layer. Is it necessary to set a number equal to product between the label width and the number of features, is it a good practice or is it just an example? I am currently trying to edit and play around with the layers and I don’t know if that has to be mantained or I can put the number of units I want.
Thank you |
st205437 | Juan:
OUT_STEPS*num_features
IIRC that’s just there is case you want to generate more than one output time, like the 3 next steps or something. |
st205438 | Thanks. I am currently using your tutorial as part of my end of university project. It has been really helpful and I would like to reference the tutorial in the written part of the project. Should I write your name as author of the tutorial or should I leave it as “Tensorflow Team”? I am currently using APA format for references and bibliography. |
st205439 | I leave it as “Tensorflow Team”?
Yes. I added the FFT part, but many people have contributed to this file over the years. |
st205440 | I am using tensorflow==1.15.5.
And I load my model like this
modelBlstm = tf.keras.models.load_model(modelPath,
custom_objects={
'elmo': hub.Module("https://tfhub.dev/google/elmo/2", trainable=False),
'tf': tf
})
My model needs elmo variable to be declared, so I passed the elmo variable in custom objects, but with this it does not predict correctly, now I declare the elmo as different variable
and just use
modelBlstm = tf.keras.models.load_model(modelPath)
it works well with the same user query.
But this works only if i am running the same code in single file.
But now if integrate the same code in my project it shows elmo variable is undefined.
Tried declaring elmo outside the class, creating elmo variable inside the class but it does not work, even with in the project, i removed the class and just cerated the functions like this…
dirName = os.path.dirname(__file__)
modelPath = os.path.join(dirName, "models/elmo-strat-bilstm-dense-2.h5")
modelBlstm = tf.keras.models.load_model(modelPath)
labelModelPath = os.path.join(dirName, "..\config\labels_mapping.pkl")
modelLabel = joblib.load(labelModelPath)
stopwords = ['i', 'am', 'a',
'to', 'is', 'do', 'in', 'of']
elmo = hub.Module("https://tfhub.dev/google/elmo/2", trainable=False)
print("************elmo",elmo)
with tf.Session() as session:
K.set_session(session)
session.run(tf.global_variables_initializer())
session.run(tf.tables_initializer())
modelBlstm = tf.keras.models.load_model(modelPath, )
def process(query: str) -> Intent:
Logger.log("Processing query : " + query)
query = __textPreprocess(query)
print("query", query)
intent = __predict(query)
print(query)
return intent
but even this does not work,
all other details i have mentioned in this SO question.
Any help?
stackoverflow.com
model is not predicting correct results keras tensorflow python
python, tensorflow, keras, data-science
asked by
Sunil Garg
on 10:09AM - 09 Jul 21 UTC |
st205441 | Sorry, I’m replying but I don’t have an answer to you.
What I’d suggest to maybe help you is, if you want to use TF 2.x and with another text embedding, you can try this tutorial: Classify text with BERT | Text | TensorFlow |
st205442 | @dmelt, can you give more information about the problem?
That would make it easier for the community to help you. |
st205443 | Given text the ai can respond in a narrators voice(a voice that the user chooses) back to the user. So I am not sure if I can post a link but something along the lines of this uberduck.ai. |
st205444 | Got it,
So, this is a complex problem to solve and that’s kind of what Google Assistant does.
suppose you have already the answer you want to be narrated back by some voice, you need to use a text to speech model, which is a specialization of audio generation.
I’d start looking into the GCP solution for this: Text-to-Speech: Lifelike Speech Synthesis | Google Cloud 5 |
st205445 | It is something like QA:
TensorFlow
BERT Question Answer with TensorFlow Lite Model Maker 8
Plus custom voice TTS on the answer:
github.com
as-ideas/TransformerTTS 11
🤖💬 Transformer TTS: Implementation of a non-autoregressive Transformer based neural network for text to speech. |
st205446 | How to train and save the model in google colab or GCP & AWS then import into pycharm.
I tried the pickle h5 model save method. is the h5 file enough for grading or do I need to buy Computing VM at GCP. I really don’t have GPU to train my model and can’t afford cloud GPU’s it’s expensive. please explain any other method.
Thank you for your time. |
st205447 | This answer can help you: I have a question to Exam(TF certification) - #5 by Laurence_Moroney 13
and to pass model around, don’t use pickle, try saving to a saved model (maybe compress it if necessary): Using the SavedModel format | TensorFlow Core 2 |
st205448 | Hi all ,
Is there are any method for clustering techniques using TensorFlow like KMeans , Meanshift , BRICH algorithms ? |
st205449 | We don’t have this implemented in the library but If are looking for an unsupervised solution you can take a look at:
TensorFlow
TensorFlow Decision Forests 4
A collection of state-of-the-art Decision Forest algorithms for regression, classification, and ranking applications. |
st205450 | Also, more in general, please consider all the modern Deep learning approaches to learn embeddings:
Google Developers
Embeddings | Machine Learning Crash Course | Google... 4 |
st205451 | Hi
I have results trained with tensorflow.contrib.slim.fully_connected layer and the training results are stored as “fully_connected/weights”. When I migrate to TF2.3, the contrib package was not supported anymore. Instead, I am using tf.compat.v1.layers.dense(…, name=‘fully_connected’). But dense layer’s kernal is named as “kernel” while in tensorflow.contrib.slim.fully_connected, it was named as “weights”.
When load my trained results, it complain it cannot find “fully_connected/kernel” in my checkpoints. (it was saved as “fully_connected/weights”.
How can I resolve this kernel name difference?
Thanks for your help |
st205452 | Liang:
When load my trained results, it complain it cannot find “fully_connected/kernel” in my checkpoints. (it was saved as “fully_connected/weights”.
Can you paste the error? |
st205453 | Here is the error message:
2021-07-12 09:49:20.004761: W tensorflow/core/framework/op_kernel.cc:1502] OP_REQUIRES failed at save_restore_v2_ops.cc:184 : Not found: Key Agent_0/fully_connected/kernel not found in checkpoint
Traceback (most recent call last):
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py”, line 1356, in _do_call
return fn(*args)
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py”, line 1341, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py”, line 1429, in _call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.NotFoundError: Key Agent_0/fully_connected/kernel not found in checkpoint
[[{{node save/RestoreV2}}]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 1286, in restore
{self.saver_def.filename_tensor_name: save_path})
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py”, line 950, in run
run_metadata_ptr)
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py”, line 1173, in _run
feed_dict_tensor, options, run_metadata)
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py”, line 1350, in _do_run
run_metadata)
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py”, line 1370, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Key Agent_0/fully_connected/kernel not found in checkpoint
[[node save/RestoreV2 (defined at \Documents\PortfolioOptConvert\a3c\server.py:44) ]]
Original stack trace for ‘save/RestoreV2’:
File “\Documents\PortfolioOptConvert\a3c.py”, line 90, in
r = Server().main()
File “\Documents\PortfolioOptConvert\a3c\server.py”, line 44, in init
self.saver = tf.compat.v1.train.Saver(max_to_keep=Config.MAX_SAVE_RESULT)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 825, in init
self.build()
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 837, in build
self._build(self._filename, build_save=True, build_restore=True)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 875, in _build
build_restore=build_restore)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 508, in _build_internal
restore_sequentially, reshape)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 328, in _AddRestoreOps
restore_sequentially)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 575, in bulk_restore
return io_ops.restore_v2(filename_tensor, names, slices, dtypes)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_io_ops.py”, line 1779, in restore_v2
name=name)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py”, line 788, in _apply_op_helper
op_def=op_def)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\util\deprecation.py”, line 507, in new_func
return func(*args, **kwargs)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py”, line 3616, in create_op
op_def=op_def)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py”, line 2005, in init
self._traceback = tf_stack.extract_stack()
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 1296, in restore
names_to_keys = object_graph_key_mapping(save_path)
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 1614, in object_graph_key_mapping
object_graph_string = reader.get_tensor(trackable.OBJECT_GRAPH_PROTO_KEY)
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py”, line 678, in get_tensor
return CheckpointReader_GetTensor(self, compat.as_bytes(tensor_str))
tensorflow.python.framework.errors_impl.NotFoundError: Key _CHECKPOINTABLE_OBJECT_GRAPH not found in checkpoint
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “C:\Users\zhuli\Documents\PortfolioOptConvert\a3c.py”, line 90, in
r = Server().main()
File “C:\Users\zhuli\Documents\PortfolioOptConvert\a3c\server.py”, line 115, in main
self.saver.restore(sess, ckpt.all_model_checkpoint_paths[Config.WHICH_CHECKPOINT])
File “C:\Users\zhuli\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 1302, in restore
err, “a Variable name or other graph key that is missing”)
tensorflow.python.framework.errors_impl.NotFoundError: Restoring from checkpoint failed. This is most likely due to a Variable name or other graph key that is missing from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error:
Key Agent_0/fully_connected/kernel not found in checkpoint
[[node save/RestoreV2 (defined at \Documents\PortfolioOptConvert\a3c\server.py:44) ]]
Original stack trace for ‘save/RestoreV2’:
File “\Documents\PortfolioOptConvert\a3c.py”, line 90, in
r = Server().main()
File “\Documents\PortfolioOptConvert\a3c\server.py”, line 44, in init
self.saver = tf.compat.v1.train.Saver(max_to_keep=Config.MAX_SAVE_RESULT)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 825, in init
self.build()
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 837, in build
self._build(self._filename, build_save=True, build_restore=True)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 875, in _build
build_restore=build_restore)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 508, in _build_internal
restore_sequentially, reshape)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 328, in _AddRestoreOps
restore_sequentially)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 575, in bulk_restore
return io_ops.restore_v2(filename_tensor, names, slices, dtypes)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_io_ops.py”, line 1779, in restore_v2
name=name)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py”, line 788, in _apply_op_helper
op_def=op_def)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\util\deprecation.py”, line 507, in new_func
return func(*args, **kwargs)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py”, line 3616, in create_op
op_def=op_def)
File “\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py”, line 2005, in init
self._traceback = tf_stack.extract_stack() |
st205454 | I suppose you can simple rename the variable in the checkpoint.
Check if this script is still working correctly:
gist.github.com
https://gist.github.com/fvisin/578089ae098424590d3f25567b6ee255 3
tensorflow_rename_variables.py
# Adapted from https://gist.github.com/batzner/7c24802dd9c5e15870b4b56e22135c96
import getopt
import sys
import tensorflow as tf
usage_str = ('python tensorflow_rename_variables.py '
'--checkpoint_dir=path/to/dir/ --replace_from=substr '
'--replace_to=substr --add_prefix=abc --dry_run')
find_usage_str = ('python tensorflow_rename_variables.py '
This file has been truncated. show original |
st205455 | Can anyone help me with this:
I am following the Tensorflow notebook for Few shot learning ( Google Colaboratory 3 )
In it, I saw that they were annotating the images using colab_utils.annotate(). I can’t understand the annotation format they are using (like YOLO or COCO format). Another problem is that we can’t specify the classes at the time when we are drawing the bounding boxes and I have to remember the order in which I annotate the different images and classes so I can add them by code later on.
If someone can tell me what’s that format so I can annotate the images on my PC locally rather than on COLAB which will save a lot of time.
Any help would be appreciated.
Regards
Original Question Credits: tensorflow - colab_utils.annotate(), annotation format - Stack Overflow 5 |
st205456 | The annotation format is in a docstring in the source code:
github.com
tensorflow/models/blob/master/research/object_detection/utils/colab_utils.py#L436-L459 6
The input of the call back function is a list of list of objects
corresponding to the annotations. The format of annotations is shown
below
[
// stuff for image 1
[
// stuff for rect 1
{x, y, w, h},
// stuff for rect 2
{x, y, w, h},
...
],
// stuff for image 2
[
// stuff for rect 1
{x, y, w, h},
// stuff for rect 2
{x, y, w, h},
...
This file has been truncated. show original |
st205457 | I was going to post the exact same thing as @Bhack !
another resource that I found that might help is this notebook about the annotation function: Google Colaboratory 14 |
st205458 | How to convert tfdf.keras.GradientBoostedTreesModel into tensorflow lite format? |
st205459 | Hi,
TF-DF is not yet compatible with TF Lite. Here is 6 the feature request. You can ping on the issue to help prioritize it .
Cheers,
M. |
st205460 | May also be worth noting, that in the meantime if you need to serve the model with C++, in a very light-fashion way, you can also do that straight forward with the underlying C++ library Yggdrasil Decision Forests 4.
Ideally though, it should be integrated with TF Lite. |
st205461 | Hello all. Hope you would be doing good. I am a newbie, I just want to ask that finding an HCF of 2 numbers, by teaching the ANN giving the data of 2 numbers with their HCF. Is this problem achievable? |
st205462 | You can take a look at:
github.com
deepmind/mathematics_dataset 3
This dataset code generates mathematical question and answer pairs, from a range of question types at roughly school-level difficulty. |
st205463 | Hi, I need to implement a custom convolution layer which is not supported by Tensorflow and TF Lite, so I tried to define it by using the tutorial to have a TF operator for a custom op and the guide to have a custom op supported by TF Lite. However, when I try to convert the operator with TF Lite converter, I get this error:
Traceback (most recent call last):
File "es.py", line 39, in <module>
converter =
tf.lite.TFLiteConverter.from_concrete_functions([tf.function(convol1d).get_concrete_function(inp)])
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py",
line 1299, in get_concrete_function
concrete = self._get_concrete_function_garbage_collected(*args, **kwargs)
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py",
line 1205, in _get_concrete_function_garbage_collected
self._initialize(args, kwargs, add_initializers_to=initializers)
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py",
line 725, in _initialize
self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-
access
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line
2969, in _get_concrete_function_internal_garbage_collected
graph_function, _ = self._maybe_define_function(args, kwargs)
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line
3314, in _maybe_define_function
self._function_spec.canonicalize_function_inputs(*args, **kwargs)
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line
2697, in canonicalize_function_inputs
inputs, flat_inputs, filtered_flat_inputs = _convert_numpy_inputs(inputs)
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line
2753, in _convert_numpy_inputs
a = _as_ndarray(value)
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line
2711, in _as_ndarray
return value.__array__()
File "/home/em/venv/lib/python3.8/site-packages/tensorflow/python/keras/engine
/keras_tensor.py", line 273, in __array__
raise TypeError(
TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may
indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or,
you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register
dispatching, preventing Keras from automatically converting the API call to a lambda layer in the
Functional Model.
The code is like this:
import tensorflow as tf
tf.config.run_functions_eagerly(True)
from keras.datasets import mnist
from keras.models import Model
from keras.layers import add,Input,Activation,Flatten,Dense
def convol(inp):
conv_module = tf.load_op_library('./conv.so')
x = conv_module.conv(inp, name="Conv")
return x
def read_mnist(path):
(train_x,train_y), (test_x,test_y)=mnist.load_data()
return train_x,train_y,test_x,test_y
def tcn(train_x,train_y,test_x,test_y):
inp=Input(shape=(28,28))
x = convol(inp)
x=Flatten()(x)
x=Dense(10,activation='softmax')(x)
model=Model(inputs=inp,outputs=x)
model.summary()
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])
model.fit(train_x,train_y,batch_size=100,epochs=10,validation_data=(test_x,test_y))
pred=model.evaluate(test_x,test_y,batch_size=100)
print('test_loss:',pred[0],'- test_acc:',pred[1])
train_x,train_y,test_x,test_y=read_mnist('MNIST_data')
tcn(train_x,train_y,test_x,test_y)
tflite_model_name = 'net'
inp=Input(shape=(28,28))
converter =
tf.lite.TFLiteConverter.from_concrete_functions([tf.function(convol).get_concrete_function(inp)])
converter.allow_custom_ops = True
tflite_model = converter.convert()
open(tflite_model_name + '.tflite', 'wb').write(tflite_model) |
st205464 | Hi @Gianni_Rossi
So does the model train properly but not converted? Is there a colab notebook to reproduce? |
st205465 | Hi, thanks for your reply. I can train the model, but I can’t convert it. Unfortunately I have problems using the .so file obtained from the TF custom conv operator on Google Colab. |
st205466 | @George_Soloupis
Since I need to have a dilated and causal convolutional 1D op which can be supported by TF Lite (and we have a Conv1D supported by TF), I think I might as well not use my custom TF conv op above, and instead use the class Conv1D. Following the tutorial Custom operators | TensorFlow Lite I tried to implement this very simple conv1D:
#include "tensorflow/lite/kernels/conv_1d.h"
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <vector>
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/tensor.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
namespace tflite {
namespace ops {
namespace custom {
namespace conv_1d {
const int dim = 5;
int dim_in;
int dim_out;
int dim_k = 3;
float copy[dim];
constexpr float kernel[3] = {1.2,2.0,4.2};
constexpr int dilation = 2;
TfLiteStatus Conv1dPrepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
int num_dims = NumDimensions(input);
TfLiteIntArray* output_size = TfLiteIntArrayCreate(num_dims);
for (int i=0; i<num_dims; ++i) {
output_size->data[i] = input->dims->data[i];
}
return context->ResizeTensor(context, output, output_size);
}
TfLiteStatus Conv1dEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node,0);
TfLiteTensor* output = GetOutput(context, node,0);
float* input_data = input->data.f;
float* output_data = output->data.f;
if (output->dims->data[0] > 1)
dim_out = output->dims->data[0];
else dim_out = output->dims->data[1];
if (input->dims->data[0] > 1)
dim_in = input->dims->data[0];
else dim_in = input->dims->data[1];
float copy0[4+dim_in];
for (int i=0; i<4; i++) {
copy0[i] = 0;
}
for (int i=0; i<dim_in; i++) {
copy0[i+4] = input_data[i];
}
for (int i=0; i<dim_out; i++) {
for (int m=0; m<dim; m++) {
copy[m] = copy0[m+i];
}
for (int j=0; j<dim_k; j++) {
output_data[i] = output_data[i] + copy[j*dilation]*kernel[j];
}
}
return kTfLiteOk;
}
} // namespace conv_1d
TfLiteRegistration* Register_CONV_1D() {
static TfLiteRegistration r = {nullptr, nullptr, conv_1d::Conv1dPrepare, conv_1d::Conv1dEval};
return &r;
}
} // namespace custom
} // namespace ops
} // namespace tflite
However, I always use a fixed kernel which is not trainable. In order to access weights created by the Class Conv1D and other inputs, how can I do? Then I’d like to use this code in Python to register the op:
import tensorflow as tf
tf.config.run_functions_eagerly(True)
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Conv1D,Activation,Input,Flatten,Dense
num_filters = 32
kern_size = 3
@tf.function
def convol(inp, num_filters, kern_size):
r = Conv1D(filters = num_filters, kernel_size = kern_size, name="cd1")(inp)
return x
def read_mnist(path):
(train_x,train_y), (test_x,test_y)=mnist.load_data()
return train_x,train_y,test_x,test_y
def tcn(train_x,train_y,test_x,test_y):
inp=Input(shape=(28,28))
x = convol(inp,num_filters,kern_size)
x=Flatten()(x)
x=Dense(10,activation='softmax')(x)
model=Model(inputs=inp,outputs=x)
model.summary()
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])
model.fit(train_x,train_y,batch_size=100,epochs=10,validation_data=(test_x,test_y))
pred=model.evaluate(test_x,test_y,batch_size=100)
print('test_loss:',pred[0],'- test_acc:',pred[1])
train_x,train_y,test_x,test_y=read_mnist('MNIST_data')
tcn(train_x,train_y,test_x,test_y)
tflite_model_name = 'net'
inp=Input(shape=(28,28))
converter = tf.lite.TFLiteConverter.from_concrete_functions([convol.get_concrete_function(inp,num_filters,kern_size)])
converter.allow_custom_ops = True
tflite_model = converter.convert()
open(tflite_model_name + '.tflite', 'wb').write(tflite_model) |
st205467 | Hi,
I am trying to expand the model from tflite object detector with OCR, I have exported the underlying serving model and I have some trouble understanding the output I’m getting from the keras model. The output I’m getting is 2 arrays with pyramid like outputs.
EfficientDet architecture2264×820 207 KB
I’m trying to understand how I can get bboxes and predictions (scores and class) out of it. I’ve been looking for clues here but I can’t wrap my head around it.
I’d like to stay with tflite implementation of the model as it provides me with very convenient training and the results with just some augmentation added on top of what tflite already provides is getting me satisfying results and just use the underlying model to combine it with OCR and later export it back to tflite for mobile use. |
st205468 | Can you try something like this?
interpreter = tf.lite.Interpreter(model_content=tflite_model_path)
interpreter.allocate_tensors()
fn = interpreter.get_signature_runner()
output = fn(images=image)
print(output) |
st205469 | I do have a working inference with the model both in python and on android. The problem is I want to use the underlying keras model and combine it with OCR to build a single model that detects objects and reads text out of them (necessary for my use case). The idea is to use a Keras sequential model with efficiientdet model as first layer, data processing as a second layer and OCR as the third one. My issue is that the keras model output is different from the tflite model so I’m trying to replicate the output postprocessing. |
st205470 | The difference is probably nms in tflite model.
Maybe use this after your keras model?
github.com
google/automl/blob/9c58b0b487995d5e6b95ba366cb56cff8f17cd26/efficientdet/keras/postprocess.py#L528 2
nms_boxes_bs[:, :, 1],
nms_boxes_bs[:, :, 0],
nms_boxes_bs[:, :, 3],
nms_boxes_bs[:, :, 2],
nms_scores_bs,
nms_classes_bs,
]
return tf.stack(detections_bs, axis=-1, name='detections')
def generate_detections(params,
cls_outputs,
box_outputs,
image_scales,
image_ids,
flip=False,
pre_class_nms=True):
"""A legacy interface for generating [id, x, y, w, h, score, class]."""
_, width = utils.parse_image_size(params['image_size'])
original_image_widths = tf.expand_dims(image_scales, -1) * width |
st205471 | Passing the output from the model into generate_detections with params being a dict from EfficientDetLite0Spec config and scales [0.25] (single image input for now), I get
InvalidArgumentError: indices[0,19206] = 19206 is not in [0, 19206) [Op:GatherV2]
in line 146 of automl/efficientdet/keras/postprocess.py (I can’t post git links yet)
Not sure what I’m doing wrong at this point.
For reference snippets of my code
keras_model = model.create_serving_model()
res = keras_model(np.expand_dims(npimages[0], 0))
detections = generate_detections(params, res[0], res[1], [0.25], [1]) |
st205472 | I seem to have fixed the issue, I need to add 1 to the number of classes in the parameters to accommodate the background class. Thank you @Kzyh for help! |
st205473 | I have just installed Tensorflow 2.2.0 from a source on my Raspberry Pi 4B running Raspbian 32-bit (armv7l) OS, but when I try to run python code, it gives me the following error, I don’t know if it is something about the version as it doesn’t say anything specifically about the version of TF.
importError: cannot import name ‘L2’ from ‘tensorflow.keras.regularizers’ (/usr/local/lib/python3.7/dist-packages/tensorflow/keras/regularizers/init.py) |
st205474 | Check 2.2 api docs. Changing L2 to l2 should work. tf.keras.regularizers.l2 | TensorFlow Core v2.2.0 11 |
st205475 | Do I have to replace all L2 with L1 throughout in the following the code.
This file is MACHINE GENERATED! Do not edit.
Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
“”"Built-in regularizers.
“”"
from future import print_function as _print_function
import sys as _sys
from tensorflow.python.keras.regularizers import L1L2
from tensorflow.python.keras.regularizers import Regularizer
from tensorflow.python.keras.regularizers import deserialize
from tensorflow.python.keras.regularizers import get
from tensorflow.python.keras.regularizers import l1
from tensorflow.python.keras.regularizers import l1_l2
from tensorflow.python.keras.regularizers import l2
from tensorflow.python.keras.regularizers import serialize
del _print_function |
st205476 | Whenever I try to make changes it says, you cannot edit this file as it is a machine generated file. |
st205477 | No, you change it in your training code. You can also switch to tf 2.3 or higher and dont change anything. |
st205478 | Yes, I was thinking about shifting to tf 2.5.0 but I didn’t find any article or anything to install tf 2.5.0 on RPi 4B running Raspbian 32-bit (armv7l). |
st205479 | Just an update: Just in case anyone runs into the same issue in the future, I had to install Raspbian 64-bit (aarch64) which is the latest version of the Raspbian OS for Raspberry Pi’s having a 64-bit architecture support, then installed Tensorflow 2.5.0 and Opencv 4.5.2 both from a source. I never recommend installing Tensorflow and OpenCV using the pip commands. Always go for sources. |
st205480 | I followed the exact instructions here Tensorflow Plugin - Metal - Apple Developer 8
but when I try to fit any model I get this error and model does not train…
Screenshot 2021-07-09 at 5.09.24 PM1952×216 124 KB
I upgraded MacOS to 11.4 and now the model fits but I get the same error |
st205481 | Hello everybody.
I was trying to run the Tensorflow BERT tutorial for text classification ( Classify text with BERT | Text | TensorFlow 5 ), but it does non want to run on my GPU. Does anyone faced the same issue?
Thank you. |
st205482 | Hi @Stefano_Di_Pietro , I am training the model with GPU enabled in Colab (in the cloud) without issues (notebook: Google Colaboratory 2 → Edit > Notebook settings > GPU).
So, this may be specific to your setup. Have you had issues with training other TensorFlow 2.x models on your GPU? Can you share your OS, GPU model, cuDNN/CUDA versions?
Hardware requirements: GPU support | TensorFlow 2
Software requirements: GPU support | TensorFlow 2
GPU support: GPU support | TensorFlow |
st205483 | Thank you @8bitmp3 for the reply. I already run plenty of tensorflow models on my computer
This model is running on a Ubuntu 20.10
The Graphic card is a GeForce GTX1060, driver Version: 460.80
CUDA Version: 11.2
cuDNN: 7.6.5 |
st205484 | What is the value of this in your setup:
TensorFlow
tf.test.is_gpu_available | TensorFlow Core v2.5.0 3
Returns whether TensorFlow can access a GPU. (deprecated) |
st205485 | Oh my god … it says False.
But I see a Python process under Anaconda (I’m using Anaconda, I forgot to mention it):
±----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| 0 N/A N/A 909 G /usr/lib/xorg/Xorg 456MiB |
| 0 N/A N/A 1505 G /usr/bin/kded5 24MiB |
| 0 N/A N/A 1510 G /usr/bin/kwin_x11 45MiB |
| 0 N/A N/A 1558 G /usr/bin/plasmashell 24MiB |
| 0 N/A N/A 1622 G /usr/lib/firefox/firefox 11MiB |
| 0 N/A N/A 2066 G …AAAAAAAAA= --shared-files 128MiB |
| 0 N/A N/A 75968 G …AAAAAAAAA= --shared-files 30MiB |
| 0 N/A N/A 242507 C …conda3/envs/tf/bin/python 61MiB |
±----------------------------------------------------------------------------+ |
st205486 | Stefano_Di_Pietro:
This model is running on a Ubuntu 20.10
The Graphic card is a GeForce GTX1060, driver Version: 460.80
CUDA Version: 11.2
cuDNN: 7.6.5
For TF v2.5 the minimum cuDNN version appears to be 8.1
GPU support | TensorFlow 4 - do you think this may be causing the issue or are you running your setup with TF v2.4 or lower?
Alternatively, maybe trying v2.5 in a Docker container (as @bhack might recommend) - Docker | TensorFlow 1 - can help resolve this issue. |
st205487 | Actually, in some way, my Anaconda environment was broken. I tried with a new created one it it works fine.
I will try to figure it out.
Thank you for the help. |
st205488 | Please make sure that this is a bug. As per our
GitHub Policy 1,
we only address code/doc bugs, performance issues, feature requests and
build/installation issues on GitHub. tag:bug_template
System information
Have I written custom code (as opposed to using a stock example script provided in TensorFlow.js): Yes
OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Windows 10
Mobile device (e.g. iPhone 8, Pixel 2, Samsung Galaxy) if the issue happens on mobile device: N/A
TensorFlow.js installed from (npm or script link): npm install @tensorflow/tfjs
TensorFlow.js version (use command below): 3.6.0
Browser version: Chrome 90 on Windows 10
Tensorflow.js Converter Version: 3.6.0
Hyperlinks are capitalized to prevent confusion(because the color settings(and blue filter) on my monitor make it hard to see the difference between them)
Describe the current behavior
I used transfer learning using a pretrained model from the Tensorflow Object Detection API, which i converted to tensorflow-js using the tensorflow-converter API in python. View the ipynb notebook HERE 3. I then followed @hugozanini’s REPO 5 which had a template for using your tensorflow object detection models in javascript; I copied the index.json file and put it into a sandbox, replacing his model.json file with mine. The repo which contains it can be found here 2
Describe the expected behavior
I was expecting the model to work and the program to run normally, like it did in this DEMO. Instead, I got
index.js:1437 TypeError: Cannot read property 'children' of undefined
at operation_mapper.js:409
at Array.forEach (<anonymous>)
at operation_mapper.js:403
at Array.forEach (<anonymous>)
at OperationMapper.mapFunction (operation_mapper.js:401)
at operation_mapper.js:163
at Array.reduce (<anonymous>)
at OperationMapper.transformGraph (operation_mapper.js:162)
at GraphModel.loadSync (graph_model.js:159)
at GraphModel._callee$ (graph_model.js:119)
at tryCatch (runtime.js:62)
at Generator.invoke [as _invoke] (runtime.js:288)
at Generator.prototype.<computed> [as next] (runtime.js:114)
at asyncGeneratorStep (asyncToGenerator.js:3)
at _next (asyncToGenerator.js:25)
Standalone code to reproduce the issue
Provide a reproducible test case that is the bare minimum necessary to generate
the problem. If possible, please share a link to Colab/CodePen/any notebook.
HERE 3 is the colab notebook I used to train my model
HERE 4 is the sandbox where I tried to use the tensorflow.js model
Other info / logs Include any logs or source code that would be helpful to
diagnose the problem. If including tracebacks, please include the full
traceback. Large logs and files should be attached.
Error Message:
index.js:1437 TypeError: Cannot read property 'children' of undefined
at operation_mapper.js:409
at Array.forEach (<anonymous>)
at operation_mapper.js:403
at Array.forEach (<anonymous>)
at OperationMapper.mapFunction (operation_mapper.js:401)
at operation_mapper.js:163
at Array.reduce (<anonymous>)
at OperationMapper.transformGraph (operation_mapper.js:162)
at GraphModel.loadSync (graph_model.js:159)
at GraphModel._callee$ (graph_model.js:119)
at tryCatch (runtime.js:62)
at Generator.invoke [as _invoke] (runtime.js:288)
at Generator.prototype.<computed> [as next] (runtime.js:114)
at asyncGeneratorStep (asyncToGenerator.js:3)
at _next (asyncToGenerator.js:25) |
st205489 | Generally I suggest you to select tags from the menu on a new thread cause specialized technical team members could be subscribed only to a tag subset (e.g. in this case I suggest tfjs and help_request) |
st205490 | Unfortunately, I don’t have the ability to set tags. I can only set the title, description, and category. |
st205491 | Did you ever get this resolved? I’m running into the same error running tfjs-node v3.7.0 or v 3.0.0-rc.1
v3.7.0
TypeError: Cannot read property ‘output’ of undefined
v3.0.0-rc1
TypeError: Cannot read property ‘children’ of undefined |
st205492 | Hello everyone,
I am new to TensorFlow and I want to use reinforce agent codes. Before that, I need to install the followings:
sudo apt-get update
sudo apt-get install -y xvfb ffmpeg
pip install ‘imageio==2.4.0’
I tried to install them in a Jupyter cell, Anaconda prompt and Command prompt but it was unsuccessful. I get syntax error as “Invalid syntax”. Could you please help me and let me know how to fix this problem?
Thank you. |
st205493 | Hi F_J,
I’ve just tried on colab and it works like this (I tried one line per cell):
!apt-get update
!apt-get install -y xvfb ffmpeg
!pip install imageio==2.4.0 |
st205494 | The REINFORCE tutorial 4 is for Google Colab, which runs on the Cloud. You are recommended to use it to utilize the free GPU acceleration (for a number of hours) and the setup simplicity, since deep RL can be compute intensive and sample-inefficient (see Reinforcement learning, fast and slow by DeepMind’s Matthew Botvinick et al., 2019).
If you’re running the notebook locally:
On a Linux machine, you might also need to add x11-utils:
!apt-get install -y xvfb x11-utils
!apt-get install -y ffmpeg
On a macOS machine, to install xvfb you may need to check the answer on StackOverflow: linux - xvfb-run on OS X - Stack Overflow which may have a good answer. To install ffmpeg, check out Which ffmpeg package I should download for macOS? - Super User - you might want to choose Homebrew (brew install ffmpeg).
The xvfb and ffmpeg dependencies are needed for video playback to watch the replays of your RL agent. “Xvfb (X virtual framebuffer) is a display server implementing the X11 display server protocol. It runs in memory and does not require a physical display. Only a network layer is necessary.” (source). (For more information, you can read about X virtual frame buffer/xvfb and FFmpeg. You can also read about X11.)
Regarding this step:
F_J:
pip install ‘imageio==2.4.0’
If you use back ticks, make sure you use ' and not ‘ or ’. No back ticks should work, as @lgusm mentioned here:
lgusm:
!pip install imageio==2.4.0
You may find this post useful: Rendering OpenAi Gym in Google Colaboratory. – StarAi – StarAi Applied Research Blog |
st205495 | Thank you. !pip install imageio==2.4.0 worked. But, the first two lines are not still run. |
st205496 | Hi all,
I’d like to define a custom convolutional op by following this: Create an op | TensorFlow Core. I’d ask you: how can I access filter weights in the Compute method? In the call to the REGISTER_OP macro, should I define filter dimensions? Where the weights are updated? |
st205497 | I’m wondering why all Keras layers use Glorot initialization as default. Since Relu is the most popular activation function, shouldn’t He be the default initialization?
The prebuilt application models such as ResNet50, also use Glorot initialization as default and there is no parameter to pass and modify it. |
st205498 | Are you talking about this:
Medium – 6 Jul 19
Why default CNN are broken in Keras and how to fix them 15
A deep dive into CNN initialization…
Reading time: 6 min read |
st205499 | Exactly! In my case I’m using the default ResNet50, trained from scratch and the network is training and converging. My inputs have an arbitrary number of channels that’s why I cannot use ImageNet weights. However, I’m wondering if initialization with He method would improve the results. I noticed a big difference in overfitting rom run to run depending on the initials weights from each run. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.