Why is My TensorFlow.js Model for Predicting 2 Table Multiples Not Producing Accurate Results?

I have created a tensorflow.js model that predicts outputs in multiples of two. For example, if the input is 16, the prediction should be 32. However, even after providing the input data and labels accordingly, the output printed is [[1],] after prediction.print().

Code: -

const data = tf.tensor([2,4,6,8,10,12,14,16,18,20,22,24,26,28,30])
const label = tf.tensor([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])

const model = tf.sequential()
model.add(tf.layers.dense({inputShape : [1], units : 32, activation : 'relu'}))
model.add(tf.layers.dense({ units : 1, activation : 'softmax'}))   

model.compile({
    optimizer:'sgd',
    loss:'meanSquaredError',
    metrics:['accuracy']
})
function onBatchEnd (batch,logs){
   // console.log(logs.acc)
}
model.fit(data,label,{
epochs: 50,
batchSize : 4,
callbacks:{onBatchEnd}
}).then(info =>{
    console.log(info.history.acc);
    const prediction = model.predict(tf.tensor([16]))
    prediction.print() 
})

Output from Prediction.print(): [[1],]

Please explain the meaning of inputShape. How do I determine which inputShape to provide? For example, if my tensor is [[1,2],[3,4],[5,6]], what would the inputShape be for this? Also, could you provide some resources to study activation functions such as relu and softmax? Additionally, why does the output layer unit need to be one (1) only? If I specify any other value, it results in an error. (Explanation not clear)

Answer №1

The output layer cannot utilize the softmax activation function in this scenario. Typically, softmax is employed for classification tasks, which is not applicable here.

If you browse through the official TensorFlow website, you will find numerous examples. Upon reviewing your data and labels, it appears that they have been switched around. For instance, if you aim to predict 32 based on 16, then 32 would be considered as the feature (which represents the data) and 16 as the label. Refer to this link to understand the variance between features and labels.

In a predictive model involving 2 values, the inputShape should be defined as [2]. Simply put, the InputShape signifies the shape of the individual element being predicted. Here are examples:

  • [1, 2] indicates an inputShape of 2
  • [[2, 4, 5], [5, 6, 3]] calls for an inputShape of [2, 3]

and so forth ...

Model with inputShape [1]

const data = tf.tensor([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
const label = tf.tensor([2,4,6,8,10,12,14,16,18,20,22,24,26,28,30])

const model = tf.sequential()
model.add(tf.layers.dense({inputShape : [1], units : 32, activation : 'relu'}))
model.add(tf.layers.dense({ units : 1}))   

model.compile({
    optimizer:'sgd',
    loss:'meanSquaredError',
    metrics:['accuracy']
})
function onBatchEnd (batch,logs){
   // console.log(logs.acc)
}
model.fit(data, label, {
epochs: 50,
callbacks:{onBatchEnd}
}).then(info =>{
    console.log(info.history.acc);
    const prediction = model.predict(tf.tensor([16]))
    prediction.print() 
})
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d4c6cad3e0908e91948e91">[email protected]</a>"> </script>
  </head>

  <body>
  </body>
</html>

Model with inputShape [2]

const data = tf.tensor([[1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[13,14]])

const label = tf.tensor([[2,4],[6,8],[10,12],[14,16],[18,20],[22,24],[26,28]])

const model = tf.sequential()
model.add(tf.layers.dense({inputShape : [2], units : 32, activation : 'relu'}))
model.add(tf.layers.dense({ units : 2}))   

model.compile({
    optimizer: tf.train.sgd(0.001),
    loss:'meanSquaredError',
    metrics:['accuracy']
})
function onBatchEnd (batch,logs){
   // console.log(logs.acc)
}
model.fit(data, label, {
epochs: 50,
callbacks:{onBatchEnd}
}).then(info =>{
    console.log(info.history.acc);
    const prediction = model.predict(tf.tensor([[12, 13]]))
    prediction.print() 
})
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
  </head>

  <body>
  </body>
</html>

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

Modifying input values in AngularJS/HTML

I'm encountering an issue with the ng-repeat function in AngularJS within my HTML code. The problem is that when I change the input with the ID 'add-price' in one cartproduct, it simultaneously changes in all other cartproducts as well. For ...

Error encountered in Typescript when attempting to invoke axios - the call lacks a suitable overload

When I make a call to axios, I include a config object like this: const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } } axios(req) An error in TypeScript is thrown stating that "No overload matc ...

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Adding external JavaScript files that rely on jQuery to a ReactJS project

As a beginner in web development, I have a question regarding importing external JavaScript files in ReactJS. I currently have the following imports: import $ from 'jquery'; window.jQuery = $; window.$ = $; global.jQuery = $; import './asse ...

Troubleshooting async/await issues in certain IDEs

I've been experimenting with aysnc and await in my project. While it worked perfectly in FiddleJS, I encountered an error when trying to implement it in my IDE (PHPSTORM 2017): async function test(url){ ^^^^^^^^ SyntaxError: Unexpected token f ...

Angular.js - organizing a list of items and preserving the outcome

Here is a compilation of randomly arranged items: <ul class="one" drag-drop="page.items"> <li ng-repeat='item in page.items|orderBy:page.random as result'> <img ng-src="http://placecage.com/{{item.id*100}}/{{item.id*100}}"& ...

What is the best way to modify the quantity property of a cart item object within the framework of this Angular 13 online shopping application?

I am currently developing an e-commerce app with a front-end built using Angular 13. The following code snippet is designed to calculate the total price of items in the shopping cart: import { Component, OnInit } from '@angular/core'; @Componen ...

The lookat() function in three.js isn't functioning according to my requirements

Here is the code snippet I am working with: http://codepen.io/usf/pen/pGscf This is the specific section of interest: function animate() { //sun.rotation.x = t/1000; sun.rotation.y += 0.01; t += 0.1; earth.position.x = Math.sin((2*Ma ...

"Enhance Your Form with Ajax Submission using NicEdit

Currently, I am utilizing nicEditor for a project and aiming to submit the content using jQuery from the plugin. Below is the code snippet: <script type="text/javascript"> bkLib.onDomLoaded(function() { new nicEditor().panelInstance('txt1' ...

What is the best way to move between websites or pages without having to reload the current page using a selector?

Have you ever wondered how to create a webpage where users can navigate to other websites or pages without seeing their address, simply by selecting from a drop-down menu? Take a look at this example. Another similar example can be found here. When visit ...

Utilizing ASCII art in React: A guide to incorporating textual designs into your

I'm having trouble displaying ASCII images correctly on my React app. I've tried various methods, but nothing seems to maintain the form when rendered in the browser. <Grid container id="terminal_banner"> <Grid item ...

Directly insert an image into your webpage by uploading it from the input field without the need to go through the server

Can an image be uploaded directly from <input type="file" /> into an HTML page, for example through the use of Javascript, without needing to first save the image to the server? I am aware that AJAX can accomplish this, but if there is a way to ...

Vue 3 gracefully handles errors by displaying an alternative component

I am currently developing a rendering library for my Vue 3 + Vite project. Essentially, I have a JSON array of products which I pass to a special <Render :products /> component. This Render component reads all the JSON products and converts them in ...

Is there a way for me to calculate the square of a number generated by a function?

Just starting out with Javascript and coding, I'm having trouble squaring a number that comes from a function. I've outlined below what I am trying to achieve. Thank you in advance for your help. // CONVERT BINARY TO DECIMAL // (100110)2 > ( ...

AngularJS: Controller isn't being triggered

I'm encountering a peculiar issue with AngularJS where MainCtrl is not functioning at all. When I visit localhost/, it automatically redirects to localhost/#/ but the page remains blank. There are no error messages in the console, and I can confirm th ...

Sending data to server with Backbone (using save() function and php script)

Wondering if you can assist me with an issue I'm facing. I am trying to utilize Backbone's save() method and send data to a php file. However, I encountered a problem right at the beginning. When I execute the following in the browser's co ...

Having trouble entering text into a textbox in Reactjs when the state is empty

I am currently working on integrating a newsletter submit form using Reactjs/nextjs. However, I am facing an issue where once I submit the form, I am unable to type anything in the textbox. I have tried making the "state" empty but it did not resolve the ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

Changing the background color using jQuery switch case statement

I am attempting to utilize jquery to dynamically change the background image of a webpage based on different cases in a JavaScript switch statement. I have completed three steps: 1) Included this script tag in my HTML document: <script src="http://co ...

Tips for Retrieving Information from Firebase in an Angular Application

I am facing an issue with my code where the ngFor directive is not working as expected when I use read_CheckOuts to return data from the database. Below are snippets of my code: crud.service.ts import { AngularFireDatabase} from '@angular/fire/datab ...