TensorFlowJs | tf.loadLayersModel Not Working - tensorflow.js

Using sample code from the following link:
https://js.tensorflow.org/api/latest/#loadLayersModel
Checking the localstorage of Chrome I do see 'my-model-1' there, so it is getting saved but not loaded back into loadedModel. I have verified localstorage in Chrome and IE and 'my-model-1' is there in both browsers. IE doesn't throw an error, while Chrome does throw the error.
const model = tf.sequential({layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
model.predict(tf.ones([1, 3])).print();
const saveResults = model.save('localstorage://my-model-1');
const loadedModel = tf.loadLayersModel('localstorage://my-model-1');
loadedModel.predict(tf.ones([1, 3])).print();
Expected loadedModel.predict to work and instead getting loadedModel.predict is not a function error.

Problem
tf.loadLayersModel returns a Promise which resolves to the model. The same is also true for model.save.
Solution
You need to either use await or .then to wait until the Promise is resolved. Here is your code with the correct await statements:
(async () => {
const model = tf.sequential({layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
model.predict(tf.ones([1, 3])).print();
const saveResults = await model.save('localstorage://my-model-1');
const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');
loadedModel.predict(tf.ones([1, 3])).print();
})();
The code is executed in an async function as only here it is allowed to use the await keyword.

Related

SvelteKit form get request

I am trying to set up a simple endpoint in SvelteKit that reads the input given in a form and returns the result of an SQL query. In my first attempt I used the form actions and wrote the following code in the +page.server.js file:
export const actions = {
default: async (event) => {
let form_input = await event.request.formData();
let query = {
text: "select * from ux_return_shipments($1, $2, $3, $4)",
values: [form_input.get('beg-dep-date') || null, form_input.get('end-dep-date') || null, form_input.get('beg-arr-date') || null, form_input.get('end-arr-date') || null
}
try {
const result = await event.locals.pool.query(query);
return result.rows;
} catch (e) {
console.log(e);
}
}
};
I am now trying to set up the same process using a GET request instead of a POST one but I am having difficulties setting up the endpoint. I tried to replace the above code with this template but it looks like the endpoint is not getting activated since I see no activity server side:
export function GET({ url }) {
console.log(url);
return new Response("Test response");
};
What am I doing wrong? I see that using this code for an API endpoint (+server.js file) works correctly. I also checked the form element and the URL looks correct.
In case someone has the same problem I managed to solve it using this template:
export const load = async (event) => {
return ...
};
Using the load function I was able to set up a get endpoint and pass some data to the frontend using a return.

web3.js how can i save value in variable from function?

I am trying to get started with web3.js. There are two different examples for getBlockNumber or getBalance:
web3.eth.getBlockNumber(function (error, result) {
console.log(result);
});
or shorter
web3.eth.getBlockNumber()
.then(console.log);
But how do I save the output to process it further? No matter how I try, I only get "Promise { }".
I have read many posts on this but have not found a solution that works for me.
let result;
const blockNumber = async () => {
result = await web3.eth.getBlockNumber();
};
blockNumber();
Let me know if that solve your problem. Actually "everything" it's a promise in web3 that's why you need async/await
^ console.log the result variable ofc.

React: Method finishing before data loaded

I am trying to retrieve some data from Yahoo Finance using an XHTML Request, which works. However, I am trying to display the data retrieved on my app, but the method to retrieve the data is returning "undefined" before the data has been loaded.
async componentDidMount() {
var tempData = await this.fetchAsync();
console.log(tempData)
this.handleLoad(tempData)
}
handleLoad = (num) => {
this.setState(state => ({
price: num
}));
}
async fetchAsync () {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
const {params} = this.props.navigation.state;
var ticker = params.ticker;
var result;
var tempArray = [1];
var url = "https://yahoo-finance-low-latency.p.rapidapi.com/v8/finance/spark?symbols=" + ticker + "&range=2y&interval=1d"
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
result = JSON.parse(this.responseText);
tempArray = result[ticker]['close'];
testPrice = tempArray[tempArray.length-1]
console.log(testPrice)
var self = this;
return tempArray[tempArray.length-1]
}
});
xhr.open('get', url, true);
xhr.setRequestHeader("x-rapidapi-key", "my key");
xhr.setRequestHeader("x-rapidapi-host", "yahoo-finance-low-latency.p.rapidapi.com");
xhr.send();
}
I am using the componentDidMount() function to begin calling the methods to load the data, but when the app renders, the values are not displayed.
As you can see inside the fetchAsync() method, I return the value I need, but when I try and console.log the return from this method, I get undefined.
I have also tried moving this return to the end of the method, but when I use console.log here to ensure that tempArray has the data I need, it is empty.
I need to display tempArray[tempArray.length-1] on my screen, but the data is not loaded in time, and does not update even after it has loaded.
Your return tempArray[tempArray.length-1] inside the fetchAsync isn't actually returning from fetchAsync -- it's just returning from the callback function inside addEventListener. In fact, you don't actually have any code that is taking advantage of the async tag you have on that function.
One solution to this would be to call handleLoad directly from inside fetchAsync instead of return tempArray. (Of course, you'll want to make sure that you've bound this correctly to handleLoad).
Another solution would be to pass a callback function into fetchAsync that you could call instead of returning. Then, at your call site, it might look something like this:
this.fetchAsync((tempData) => {
console.log(tempData)
this.handleLoad(tempData)
});
Finally, a third solution would be to switch from XMLHTTPRequest to fetch, and then you could take advantage of async/await and actually make that fetchAsync method async (and be able to return a value from it).

How can I know if the save method worked in mongo

im new using mongo and when i save a new object in my db i use the save method, but when using it and then printing the result, if it was successful i get the object, not someting that i can use to handle any error in the front end
router.post("/post_recipe", async (request, response) => {
const {title, content, author} = request.body;
const new_post = new Posts({title, content, author});
new_post.save(sdfs).then((response) => {
response.json(response);
}).catch(error => response.json(error));
});
doing this on purpose i get the error in the console but its not sending it to the front end to handle it and tell the user that there was a problem
Posts its a scheme, dont know if it has something to do with
Problem is you are using same variable name for your router response and save method response.
Solution
router.post("/post_recipe", async (req, res) => {
const {title, content, author} = req.body;
const new_post = new Posts({title, content, author});
// Getting rid of .then and .catch method
new_post.save((err, savedPost) => {
// Your custom error message
if (err) return res.status(400).json('post not saved due to some problem! Please try again');
// Post that you just saved in db
return res.json(savedPost);
});
This happen due to scope of variable.
For more detail check this article from w3schools.com

getting a value from a field in firebase

I am trying to retrieve a specific value of a field and store it inside a variable named joiningScore. This makes joiningScore a object with a promise that has a value in it. How can I get that value. I tried tucking in a .then method after the .get("currentPos") but it throws an error saying docSnapshot.get().then is not a function.
var joiningScore = positionDoc.get().then((docSnapshot) => { return docSnapshot.get("currentPos"); })
const positionDoc = frebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
here positionDoc is a reference to the document in firestore.
This is because you are assigning to a variable a Promise chain.
You need to wait that the Promise returned by the get() method is fulfilled in order to get the value. See this doc for more details.
So something along these line should work:
const positionDoc = firebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
var joiningScore;
positionDoc.get().then((docSnapshot) => {
joiningScore = docSnapshot.get("currentPos");
})
You could also use an async function as follows:
async function getJoiningScore() {
const positionDoc = firebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
const docSnapshot = await positionDoc.get();
return docSnapshot.get("currentPos");
}
Note that this function is itself asynchronous.

Resources