Guide on successfully importing a pretrained model in Angular using TensorFlow.js

I need help with uploading a pretrained Keras model to my existing tensorflow.js model and then making simple predictions by passing tensors in the correct format. The model is stored locally within the project, in the assets folder.

export class MotionAnalysisComponent implements OnInit {

  model: tf.LayersModel;

  ngOnInit() {
        this.loadModel()
    };

  async loadModel() {
      this.model = await 
tf.loadLayersModel('C:/Users/..path to folder../assets/tfjs_model/model.json');
      console.log('Prediction from loaded model:');
      this.model.predict(tf.ones([60,60,60]));
    }

I've added a button in my HTML code that should trigger the prediction process and display the results in the console. However, I am encountering the following errors:

  • Fetching API cannot load file:///C:/Users/..path to folder../assets/tfjs_model/model.json. The URL scheme must be "http" or "https" for CORS request.

  • ERROR Error: Uncaught (in promise): TypeError: Failed to fetch TypeError: Failed to fetch

Answer №1

If you are using this application in a web browser, accessing local file resources is not possible. The solution is to place your model.json file in a specific folder (such as "assets") within your Angular project and then load the model using the http(s) protocol from that location.

You can achieve this by following these steps:

async loadModel() {
  this.model = await tf.loadModel('/assets/tfjs_model/model.json');
}

Answer №2

Here are a few key points to keep in mind:

Similar to how model.save() works, the loadLayersModel function requires a URL-like string as an argument, starting with a scheme that specifies where we are loading the model from.

The scheme (e.g., http:// or https://) is then followed by a path.

Instead of a URL-like string, you can use an object that adheres to the IOHandler interface.

It's important to note that the tf.loadLayersModel() function operates asynchronously.

Upon completion, tf.loadLayersModel returns a tf.Model object.

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

Retrieve the rowid from the first column of a jqGrid row

I want the first column of my jqGrid to display the rowid number number | name | class 1 | A | acceptable 2 | B | good 3 | C | bad Alternatively, I would like to add a column like this (image) https://docs.google.com/file/d/0Bxi6bFcYZ_MgYTI1dUJCMWEtd0E/ ...

How can I retrieve the length of an array in vuejs?

This snippet includes a script tag <script> export default { data() { return { blogs: [], }; }, created() { this.paginate_total = this.blogs.length / this.paginate; }, }; </script> Displayed below is the respo ...

AWS: Grant access to designated clients for users

My AWS Cognito setup includes: AWS Cognito User Pool: UserPool_1 The User Pool contains 3 users: Mike, Sarah, John I have configured 3 App Clients under this user pool: WebClient_1 WebClient_2 WebClient_3 I need Mike to be able to access: WebClient_ ...

Is there a way to recursively convert property types from one to another in an object that contains optional properties?

The scenario: I am currently working with MongoDB and a REST API that communicates using JSON. MongoDB uses objects instead of identifiers for documents, but when these objects are stringified (such as in a response body), they get converted into strings. ...

Can conditional content projection (transclusion) be achieved in Angular 2+?

How can I set default content that will only display if content is not transcluded? Consider the following component template: <article> <header> <ng-content select="[header]"></ng-content> </header> < ...

Animate the Bootstrap carousel from top to bottom instead of the traditional left to right movement

Is there an option available in the bootstrap carousel to animate it from top to bottom and bottom to top, rather than from right to left and left to right? jsFiddle link <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval=" ...

Utilizing the power of jQuery within three.js

Thank you once again for your previous assistance, but I find myself in need of your expertise once more. I have successfully added markers to my map as desired. However, these markers now require functionality to be clickable. Specifically, when clicked, ...

Using AJAX to send a POST request with the PHP $_FILES superglobal while preventing the default form submission with the onclick

Seeking to implement a photo upload form using an AJAX script that is currently in place. Currently, I have the html form with a file input field. Upon submission, there is an onclick event triggering "PostForm(); return false;" This action directs to a ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

The process of implementing web-based online diagramming software involves a strategic approach to designing and integrating various

I'm really interested in learning how web-based online diagramming software works. If anyone could provide guidance or point me to example resources, I would greatly appreciate it. Here are some of the web-based online tools that I have been explorin ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

text within the table is overlapping when being created dynamically in the <table> using javascript and jquery.quickflip.js

Hello everyone, I am currently working on dynamically generating a table using tabs created with jquery.quickflip.js. However, I have run into an issue where the text from one tab may overwrite values in another tab when switching between them. Below is ...

Troubleshooting the malfunctioning save() method in Angular's hero tutorial

Currently working through the Angular Hero Tutorial version 7.3.4 while integrating Angular with a Django backend. Struggling to update a hero's name: Within the hero-detail.component.ts, there is a save() method designed to update the hero object us ...

Issue with Alignment of Border in PDF [Example Included]

I am currently developing a straightforward react application with very minimal content. index.js: <div className="App"> <div id="printable-div"> <h1>Generate PDF</h1> <p>Capture a screenshot of ...

Ways to update the color of the mat-dialog-title using the material theme

Currently, I am utilizing the Angular Material Dialog and have been attempting to dynamically change the title color of the dialog based on the material theme. <h1 mat-dialog-title color="primary">{{ title }}</h1> Even though setting ...

a user-friendly database solution for storing data in HTML 5 and Google Drive

Greetings, I am currently faced with the following dilemma: As I work on my angular 2 application, I find myself needing to save certain data. Personally, I have a preference for saving data in JSON format. Here is the scenario: Imagine a todo list where ...

How to identify a button click on an HTML page within an Android WebView

When using my Android app, I encounter an issue with a webview that contains a form and a submit button. The button code snippet is as follows: <button role="button" class="btn ng-binding" ng-click="actions.collect()" tooltip="default" title="Check f ...

Leveraging the boolean values of attributes within JSX statements

I have been working on a React.js project where I am trying to incorporate a data-picker plugin that requires a specific style of input-attributes: <input data-enable-time=true /> However, I have encountered an issue where webpack fails to compile t ...

What is the best way to retrieve the number of clients in a room using socket.io?

I am using socket.io version 1.3.5 My objective is to retrieve the number of clients in a specific room. This is the code implementation I have: socket.on('create or join', function (numClients, room) { socket.join(room); }); ...

Modifying text size using JavaScript string manipulation

I'm currently experimenting with a countdown script, but I'm struggling to change the size of the numbers displayed. Can anyone help me find where I can adjust the font and font size in this script? var eventdate = new Date("February 20, 2014 11 ...