What is the best method to convert data into the proper tensor format in Angular?

As I delve into my machine learning project, I find myself faced with the challenge of deploying my algorithm using Angular. While I have successfully uploaded the pretrained model and managed to import data from a CSV file, I am now struggling with properly transforming this data into the required tensor format. My LSTM Neural Network model relies on timewindows of 60 accelerometer data points (x-axis, y-axis, z-axis) to predict human activities, necessitating tensors in the format [any, 60,3]. Below is an excerpt of the code I have developed so far:

Loading the model here

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

Currently, I have set up a placeholder using the tf.ones() function for testing purposes to confirm the functionality of my predictions (which are accurate!)

 async predictProcess() {
   const output = this.model.predict([tf.ones([10, 60, 3])]) as any;    
   this.predictions = Array.from(output.dataSync());
   console.log(this.predictions);

This section of the code focuses on loading the data

getDataRecordsArrayFromCSVFile(csvRecordsArray: any, headerLength: any) {
let dataArr = [];

for (let i = 0; i < csvRecordsArray.length; i++) {
  let data = (<string>csvRecordsArray[i]).split(',');

  // FOR EACH ROW IN CSV FILE IF THE NUMBER OF COLUMNS
  // ARE SAME AS NUMBER OF HEADER COLUMNS THEN PARSE THE DATA
  if (data.length == headerLength) {

    let csvRecord: CSVRecord = new CSVRecord();

  //  csvRecord.timestep = Number(data[0].trim());
    csvRecord.xAxis = Number(data[1].trim());
    csvRecord.yAxis = Number(data[2].trim());
    csvRecord.zAxis = Number(data[3].trim());

    dataArr.push(csvRecord);
  }
}
return dataArr;
}

Here is the CSVRecord class

export class CSVRecord {
  public timestep: any;
  public xAxis: any;
  public yAxis: any;
  public zAxis: any;
}

Answer №1

It's more efficient to use an array instead of creating an object to populate dataArr

if (data.length == headerLength) {

    let csvRecord: number[] = [];

  //  csvRecord.timestep = Number(data[0].trim());
    csvRecord.push(Number(data[1].trim()));
    csvRecord.push(Number(data[2].trim()));
    csvRecord.push(Number(data[3].trim()));

    dataArr.push(csvRecord);
  }

To convert dataArr into a tensor, you can utilize

tf.tensor(dataArr)

By using tf.tensor, a tensor with the shape [dataArr.length, 3] will be created

If dataArr is a large array, directly creating a tensor from it may cause memory issues due to all the data being uploaded at once for computation. This answer provides insights on dealing with large data when creating tensors.

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

Having trouble with flash messages in Node.js?

Could anyone shed some light on why the flash messages are not displaying properly in my situation? Here is how I'm attempting to utilize them: This snippet is from my app.js file: var express = require('express'); var app = express ...

Error: Module not located - Unable to resolve 'crypto'

Upon running ng serve, I encountered a list of errors that need to be addressed. Here is my package JSON configuration: { "name": "ProName", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "tes ...

Using jQuery to track the status of checkboxes

Changing the checkbox status using the code: $(this).attr("checked", 'checked'); However, when trying to check the checkbox status afterwards, I received the following results: $(this).attr('checked'): "checked" $(this).is(':chec ...

Which TypeScript type must be used to define a class as a prop in the script setup of Vue 3?

Currently, I am working on a Vue 3 single file component that utilizes the script setup method. The challenge I am facing involves defining a prop that should accept values similar to those passed to the HTML class attribute. This means the prop could be a ...

Unexpected behavior observed with negated character: ? ^

I am looking to create a form where users can input their phone number and have the flexibility to choose how they want to separate the numbers. I have been using a regex pattern for validation: var regex = /[^0-9 \/-\\\(\)\+ ...

Tips for Angular: Eliminate extra white space in templates

My HTML template is supposed to simply translate a state: <ng-container [ngSwitch]="currentStatus"> <ng-container *ngSwitchCase="'DRAFT'" i18n="@@DraftStatus"> Draft </ng-container> <ng-container *ngSwitchCase= ...

What is the optimal method for defining a JSON serialization format for a TypeScript class?

Currently, I am in the process of developing a program using Angular and TypeScript. Within this program, there is a specific class named Signal that consists of various properties: export class Signal { id: number; obraId: number; obra: string ...

The Mongoose findOneAndUpdate method will only return the newly added document when using the $push

Provided here is a structured representation of my "profile" collection: { _id : ObjectId("2bb0fad110"), name : "Tommy", defaultrates : [ {_id : ObjectId("444cbcfd52"), rate : 35.0, raisedOn : "5/2/2009"}, {_ ...

PHP is adding unique characters like   into the database records

Description : Having an issue with adding a text to a content editable div. When clicking the button, I am trying to extract all the text from the div and send it to php successfully. However, when saving it to my database table, the text gets corrupted. A ...

Issue with React.js code not being detected in TSX file (Visual Studio 2015 Update 1 RC)

Currently, I am utilizing Visual Studio 2015 with update 1 release candidate. Interestingly, I have managed to successfully incorporate React.js code and syntax highlighting within a .JSX file. However, when it comes to a .TSX file, nothing seems to be wor ...

Generating a fresh document in MongoDB using Mongoose, complete with references and assigned ObjectIDs

I've been attempting to use the mongoose create function in order to generate a new document with references, but I'm encountering an error when trying to provide objectIds for those refs. Despite my efforts to find a solution, I have been unsucc ...

Enable the event listener for the newly created element

I am attempting to attach an event listener to this HTML element that is being created with an API call handleProducts() function handleProducts() { var display = document.getElementById("display") var url = "http://127.0.0.1:800 ...

The `tailwind.min.css` file takes precedence over `tailwind.css` in my Nuxt

Having trouble configuring Tailwind to use a custom font without it overriding the tailwind.css file and not displaying the changes? https://i.stack.imgur.com/ExDCL.png Check out my files below. // tailwind.config.js const defaultTheme = require('ta ...

The act of updating JQuery is causing my javascript code to malfunction completely

I've been attempting to update my jQuery library from version 1.3.2 (compressed) to jquery-1.10.2 (compressed) along with jquery-migrate-1.2.1 (compressed). However, after making this switch, none of the javascript pages on my website seem to be funct ...

React Router 4 - Optimizing Component Refresh by Remounting Instead of Re-Rendering

I am currently in the process of configuring a React project that utilizes React Router 4 ("react-router-dom": "^4.3.1"). Within this project, I have implemented a SideBar, a NavBar, and the main content section of the application which changes based on th ...

Reverse row changes in Angular Ag-Grid with the click of a button

Developed using Angular and JavaScript technologies. The AG-Grid consists of editable records with the first column being a checkbox. When changes are made to any selected records, clicking on a particular record's checkbox and then pressing a button ...

Angular JS page in its purest form

I have successfully developed a single-page application using AngularJs. However, when I visit the main page of my application hosted on the Heroku server, for a brief moment, all the images and text appear in a raw state at the top left corner of the bro ...

The hidden field in php is correctly configured, but when attempting to retrieve the value using jquery, it returns as 'undefined'

I am facing an issue with a javascript file that is sending data to php files to retrieve data from a mysql database and then populate fields with the retrieved data. The problem arises when I call the php function to store the field names in the database; ...

Revitalize and preserve the Kendo grid

One of my methods involves changing a variable from false to true in a grid. The challenge I am facing is how to save that variable and refresh the grid so that the changes are visible upon page reload. onClickBloquear(event: any) { if (event.dataIt ...

How can I optimize Javascript and CSS that are being used on my website but are not physically hosted on my website?

On my website, I have a plugin called "Contact Us" that was created and is being operated by Dropifi. Lately, I've been working on optimizing my site for SEO/Speed using Google's PageSpeed Insights tool. I enabled compression with GZip for all el ...