TensorFlow.js encountered a ValueError: Issue identified when validating the shape of dense_Dense1_input. It was expected to have a shape of [null,38], however, the array provided has a shape

I need assistance with resolving an error I encountered while training a model for a chat-bot. Any suggestions on troubleshooting this issue would be highly appreciated. Thank you.

Here is the code snippet:

Initializing the Neural Network:

var model = await tf.sequential();
        model.add(tf.layers.dense({
            units: 8,
            inputShape: training[0].length
        }));
        // console.log(model);
        model.add(tf.layers.dense({
            units: 8
        }));
        model.add(tf.layers.dense({
            units: 8
        }));
        model.add(tf.layers.dense({
            units: output[0].length,
            activation: 'softmax'
        }))
        model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

        await model.fit(tf.stack(training), tf.stack(output), {
            epochs: 1000,
            batchSize: 8
        }).then(printCall => {

            // Immediately Invoked Function Expression to solicit user input.
            (function () {
                console.log("(Type 'quit' to stop)");
                while (true) {
                    let inp = "Hi";
                    if (inp.toLowerCase() == "quit")
                        break;
                    var results = model.predict(tf.tensor(bagOfWords(inp, uniq_words)));
                    console.log(result);
                }
            })();
        })

Providing Data Details: training data in a 2d array format with dimensions of (23, 38) output data in a 2d array format with dimensions of (23, 6)

Bag of Words Methodology:

function bagOfWords(s, words) {
    var bag = [];
    for (var i = 0; i < uniq_words.length; i++) {
        bag.push(0);
    }
    var sWords = tokenizer.tokenize(s);
    var s_words = [];
    sWords.map(each => {
        s_words.push(natural.LancasterStemmer.stem(each));
    });

    for (var se in s_words) {
        for (var w in uniq_words) {
            if (uniq_words[w] == s_words[se])
                bag[w] = 1;
        }
    }
    return bag;
}

The bagOfWords function above generates a 1D array with dimensions of (38, 1).

If additional information or clarification is needed to better understand the problem, please feel free to ask. Appreciate your help.

Answer №1

The function bagOfWords mentioned above returns an array that is one-dimensional, with dimensions of (38, 1)

Contrary to what was stated, it is not a one-dimensional array but rather a two-dimensional tensor.

The expected shape for dense_Dense1_input was [null, 38] but the provided array had a shape of [38, 1]

This error occurred due to a mismatch in shapes. The tensor generated by

tf.tensor(bagOfWords(inp, uniq_words))
has a shape of [38, 1], whereas the model requires a shape of [null, 38]. To resolve this, the tensor can be reshaped to match the desired shape:

tf.tensor(bagOfWords(inp, uniq_words)).reshape([-1, 38])

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 $http data from a function that is external to it

Apologies if the title is confusing, it's hard to explain in a different way. The situation I have is... app.controller('viewProductController', ['$scope', 'dataFactory', '$routeParams', function($scope, dat ...

Having trouble retrieving data from the MongoDB database using Node.js

Having trouble with data retrieval from MongoDb Successfully connected to MongoDb, but when using the find command, it should return an empty collection, yet nothing is being returned. What could be causing this issue and how can it be monitored through ...

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...

What's the reason for the mousewheel functioning in Chrome but not in Firefox?

I am currently using CSS to enable scrolling up and down a popup page with just the mousewheel, but I'm facing an issue with it not working in FireFox. Surprisingly, it works fine in Chrome with the use of overflow-x:hidden; and overflow-y:auto; prope ...

Error in React-router: Unable to assign value to the 'props' property as it is undefined

Currently, I am working on setting up routing with Meteor using the react-router package. However, I have encountered a specific TypeError: Here is a link to an image that provides more context: This is the code snippet from my main.js file: import Reac ...

Slowly introduce a sequence of divs, then smoothly fade out the div that came before

After successfully using jQuery to create a smooth fade-in effect for a series of divs, I am now looking to incorporate a fade-out transition for the previous div. My plan is to include a fade out function as a callback within the existing fade in function ...

javascript utilize jquery to advance saved event

When it comes to hyperlinks, I am pausing some of my native click events to verify if the resulting page contains the desired content. After storing the jquery event object and performing some validations, my goal is to allow the event to continue as usua ...

Non-functioning Tooltips on Google Charts

Currently, I am working on integrating Google Chart with ASP.NET and linking it to a SQL Server database. I have encountered an issue while attempting to customize the tool tip. Below is the Header Code: <script src="js/jquery/jquery-1.10.2.js" type=" ...

Vue is removing a DOM node during the created lifecycle hook to set up a component

I am currently working on understanding the issue with this example that is not behaving as expected. My goal is to initialize my ContentView using the server-side rendered HTML in the DOM. I plan to check if init__main-content exists and then initialize t ...

Merge the date within every individual element

I am trying to combine two dates together. I thought my code was correct, as I first created the current year and then added 1 month to get to 2019. However, for some reason, the result is not displaying. function combineDates() { var currentDate = ...

Is it possible to retrieve data using a POST request?

An organization has assigned me an Angular task. They have given the following guidelines, however, the API URL is not functioning: Develop a single-page Angular application using the provided API to fetch sports results and organize them in a displayed ta ...

"Utilize the inline display property to keep elements hidden

I have created a template named 'aTemplate' using the following code: $.template('aTemplate', '<div id="someid" class="abc">' + .... '</div>' ); My goal is to make this div inline with other ele ...

Generating thick, shadowed lines in three.js to represent layers in a 3D printing visualization

I've been exploring ways to add depth to lines in Three.js that can cast shadows and appear as solid objects, but so far I've only achieved thicker lines that lack the 3D look I'm aiming for. This is for an online 3D printing platform where ...

Simulated static functions are invoked within the main function under evaluation

Looking to mock certain functions within a function I'm currently testing. In my code, there is a class with various static private functions that are called by the main function. Specifically, I want to verify the output of MyClass.functionD (which ...

Utilizing JavaScript and PHP to dynamically load HTML content on a webpage

Below is the code snippet I'm working with: <?php if ($x == 1){ ?> <b>Some html...</b> <?php } else if ($x==2){ ?> <b> Other html...</b> <?php } ?> Now, I want to create two links (a ...

Transferring items between different containers without using innerHTML

I've got an embedded <ul> within a (hidden) <aside id="idDetails">. How can I move the ul element from inside the aside and position it in a <div id="projectSide"> without using innerHTML? Any solutions in both plain JavaScript and j ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

Adding style to freshly generated content with class inclusion

Specifically speaking, when loading content from example.php, pay attention to the form with the class "aj-c-p" which is used for submitting user comments via Ajax (See code below). <form class="aj-c-p" action="set_comentario.php" method="post"> < ...

Disregard the views folder when using Express

I've configured a settings file to store important information like the application path and cookie secret for my express app. However, I'm facing an issue where it seems to be disregarding my specified view path directory. config.js: ... expor ...

Utilizing MeshPhongMaterial in THREE.js for Particle Material with Size Adjustment

My goal is to create particles that exhibit the characteristics of a Phong material, which means they react to light. I have been using the "createMultiMaterialObject" method to achieve this, and it has worked well for the most part. However, I have encoun ...