What is the process for loading a model using tf.loadModel from firebase storage?

I'm currently working on an app using the ionic3 framework that recognizes hand-drawn characters. However, I am encountering difficulties with importing the model into my project. The model was initially imported from Keras and converted using tensorflowjs_converter. There are two methods through which I've tried to import the model into my ionic3 app:

  1. The model.json and weight files (shards) are stored in the directory /assets/models.
  2. The model.json and weight files (shards) are hosted in Firebase storage.

When I launch the app in a browser using the first method, the model and weights load correctly, allowing me to make predictions successfully. However, when I deploy the app on my Android device using

ionic cordova run android --device
, the model seems unable to fetch data from the weight files, resulting in the following error:

Based on the provided shape, [3, 3, 32, 64], the tensor should have 18432 values but has 917
.

To address this issue, I attempted hosting the files on Firebase storage. Despite fetching the model.json from storage, I encountered the same error as before, both in the browser and on the device.

My experience with storing shards and models locally led me to believe that the device does not recognize the shards in either method.

Furthermore, while using the Firebase storage approach on the device, attempting to fetch the model from the URL results in the error: Failed to fetch.

Below is the code snippet for retrieving the shards and model:

const modelURL: string = await this.db.getModel();
const shards: string[] = await this.db.getShards();

modelURL and shards contain download URLs from Firebase storage, with the model and shards located at the same level like so:

/* Firebase Storage hierarchy */

https://firebasestorage.googleapis.com/v0/b/project-foo.com/o/model%2Fmodel.json?alt=media&token=******
https://firebasestorage.googleapis.com/v0/b/project-foo.com/o/model%2Fgroup1-shard1of4?alt=media&token=******
https://firebasestorage.googleapis.com/v0/b/project-foo.com/o/model%2Fgroup1-shard2of4?alt=media&token=******
https://firebasestorage.googleapis.com/v0/b/project-foo.com/o/model%2Fgroup1-shard3of4?alt=media&token=******
https://firebasestorage.googleapis.com/v0/b/project-foo.com/o/model%2Fgroup1-shard4of4?alt=media&token=******

In order to fetch the model's download URL into tf.loadModel:

import * as tf from '@tensorflow/tfjs';    

await tf.loadModel(modelURL).then(model => {
    const output: any = model.predict(img);
});

Is there a way to pass the shards fetched from Firebase storage into tf.loadModel(), enabling me to retrieve all necessary data for making predictions in both the browser and on the device?

Thank you for your assistance.

Answer №1

When using the http loader for tf.loadModel(), it expects that model.json and its corresponding weight files (group1-shard1of1, etc.) share the same url path prefix. For instance: if the model file is located at: , the loader will try to retrieve weight files from: , ...

In your situation, const modelURL: string = await this.db.getModel(); const shards: string[] = await this.db.getShards();

If the modelUrl and shards have different paths, you may need to create your own BrowserHttp IOHandler for loading: const model = await tf.loadModel(new MyOwnHttpIOLoader(modelUrl, shards));

If they do share the same path, you can align them by manually editing the model.json file. This file contains an array of weight file paths.

Using firebase storage introduces another issue where the model file's URL is:

https://firebasestorage.googleapis.com/v0/b/project-foo.com/o/model%2Fmodel.json
with the path
firebasestorage.googleapis.com/v0/b/project-foo.com/o
The loader will use this path to attempt loading the weight file at
firebasestorage.googleapis.com/v0/b/project-foo.com/o/group1-shard1of4
. However, it does not match your weight URL
firebasestorage.googleapis.com/v0/b/project-foo.com/o/model%2Fgroup1-shard1of4
, as it lacks the model%2F prefix.

To resolve this, you can manually update the model.json file by adding the necessary prefix. Search for "weightsManifest" within the file, and adjust the "paths" array to resemble something like ["model%2Fgroup1-shard1of4", ...]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for assigning types from an interface object in TypeScript

Here is the code snippet I'm dealing with interface deviceInfo { Data: { model: string; year: number; }; } const gadget: deviceInfo.Data; I encountered a warning in vscode that indicates there ...

The best location for storing Typescript files within an ASP.NET Core project

My Typescript app is built on AngularJS 2 with ASP.NET Core, and currently I store my TS files in the wwwroot directory. While this setup works well during development, I am concerned about how it will function in production. I aim to deploy only minified ...

Deactivate the underscore and include the fiscal year in AngularJS

I am currently faced with a scenario where the back end is returning the value as follows: 123222_D1.123 However, I need to display the date from the database (12-Jun-2020) as 2020-D1.123 in a drop-down menu. Currently, I am displaying the above value i ...

Error: Unable to access _rawValidators property of null object

I'm currently facing an issue with formgroup and formcontrol in Angular. When I run ng serve, it's showing an error in the console. Does anyone have a solution for this? TypeError: Cannot read properties of null (reading '_rawValidators&a ...

Exploring TypeScript interfaces with optional properties and returning types

As a newcomer to TypeScript, I am currently exploring the documentation and came across an example in the "Optional Properties" section that caught my attention: interface SquareConfig { color?: string; width?: number; } function createSquare(config: ...

Navigating in Angular is made easy with the Angular routing feature, which allows you to redirect

I have been working through the Angular Tour of Heroes Guide and encountered the section on the "default route". I decided to experiment by removing the pathMatch attribute from the Route associated with an empty string. Below is the code snippet in quest ...

Higher order components enhance generic components

I'm facing an issue where I want to assign a generic type to my React component props, but the type information gets lost when I wrap it in a higher order component (material-ui). How can I ensure that the required information is passed along? type P ...

Distribute a TypeScript Project on NPM without exposing the source code

Issue: My library consists of numerous .ts files organized in structured folders. As I prepare to publish this library, I wish to withhold the source (typescript) files. Process: Executing the tsc command results in the creation of a corresponding .js fil ...

What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = [ { "amount": 270, "xlabel": "25-31/10", "datestatus": "past", "color": "#E74C3C", "y": 270, "date": "2020-10-31T00:00:00Z", "entityId": 1, "entityName": "Lenovo HK", "bankName": "BNP Paribas Bank", "b ...

Exploring Nuxt's Getters with vuex-class for seamless data retrieval

Currently, I am in the process of developing an application using Nuxt and experimenting with vuex for the first time. Despite following numerous tutorials to set it up, I'm encountering difficulties accessing the store and suspect that the issues may ...

Toggle the presence of a string in an array with a checkbox

Currently, I am working on a user creation form for my Next.js front end project using TypeScript. The main goal is to allow an administrator to create new users by filling out a simple form which will generate a basic user object. Here is the structure of ...

Next.js encountered an error when trying to locate the 'net' module while working with PostgreSQL

I'm facing a challenge in my Next.js project while attempting to retrieve all records from a table. The error message I'm encountering is "Module not found: Can't resolve 'net'" with an import trace pointing to multiple files withi ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

Error message: When using Vue CLI in conjunction with Axios, a TypeError occurs stating that XX

I recently started working with Vue.js and wanted to set up a Vue CLI project with Axios for handling HTTP requests. I came across this helpful guide which provided a good starting point, especially since I plan on creating a large project that can be reus ...

What is the best way to broaden the capabilities of function objects through the use of

Below is a code snippet that raises the question of how one should define certain types. In this scenario, it is required that Bar extends Foo and the return type of FooBar should be 'a'. interface Foo { (...args: any):any b: string } i ...

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...

RxJS - Only emit if another source does not emit within a specified time frame

Imagine having two observables. Whenever the first one emits, there should be a 2-second pause to check if the other observable emits something within that timeframe. If it does, then no emission should occur. However, if it doesn't emit anything, the ...

The compatibility of return value types between the constructor signature and the call signature interface is not maintained when they are used together

I'm new to TypeScript and I'm struggling to figure out why I'm getting a type error in the code below. Can someone help me identify what's wrong? interface CallOrConstruct { new (value: string): Person (value: number): number } cla ...

What is the best way to globally incorporate tether or any other feature in my Meteor 1.3 TypeScript project?

I've been working hard to get my ng2-prototype up and running in a meteor1.3 environment. Previously, I was using webpack to build the prototype and utilized a provide plugin to make jQuery and Tether available during module building: plugins: [ ne ...

Encountering a problem with Typescript and eslint while utilizing styled-components and Material UI: "Warning: React does not identify the `showText` prop on a DOM element."

While using a styled component to return a material ui Fab component, an error appears in the console: React does not recognize the `showText` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as low ...