Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm using Socket.IO to send some numbers and string to an array. However, it keeps converting everything to a String so I get an error message.

Additionally I'm using ml.js for the models, the model logic is based of their random forest alorithm

Here is the code I'm working with:
JavaScript
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3019;
const rf =  require('ml-random-forest');

const options = {
    seed: 3,
    maxFeatures: 0.9, //number of features
    replacement: true,
    nEstimators: 25 //number of trees
  };

  var RF = new rf.RandomForestClassifier(options);
  let seperationSize;
  let data = require('./myData.json');
  let X = [], y = [];
  let trainingSetX = [], trainingSetY = [], testSetX = [], testSetY = [];
  
  seperationSize = 0.9 * data.length; //
  data = shuffleArray(data); //shuffle the data
  dressData();
  
  function dressData() {
  
      data.forEach((row) => {
          let rowArray, typeNumber;
          rowArray = Object.keys(row).map(key => parseFloat(row[key])).slice(1,14); 
          typeNumber = typesArray.indexOf(row.type); // Convert type(String) to type(Number)
          console.log(typeNumber);
  
          X.push(rowArray);
          y.push(typeNumber);
      });
  
      // split into training and test sets
      trainingSetX = X.slice(0, seperationSize);
      trainingSetY = y.slice(0, seperationSize);
      testSetX = X.slice(seperationSize);
      testSetY = y.slice(seperationSize);
  
      train();
  }
  
  function train() {  // train model on the training sets
      RF.train(trainingSetX, trainingSetY);
      test();
  }
  
  function test() {  //predict test set outcomes
      const result = RF.predict(testSetX);
      const testSetLength = testSetX.length
      const predictionError = error(result, testSetY);
      console.log(`Test Set Size = ${testSetLength} and number of Misclassifications = ${predictionError}`);
  }
  
  function error(predicted, expected) { //calculate errors in prediction
      let misclassifications = 0;
      for (var index = 0; index < predicted.length; index++) {
          console.log(`truth : ${expected[index]} and prediction : ${predicted[index]}`);
          if (predicted[index] !== expected[index]) {
              misclassifications++;
          }
      }
      return misclassifications;
  }
  
  
  function shuffleArray(array) {
      typesArray = ['0','1'];
      for (var i = array.length - 1; i > 0; i--) {
          var j = Math.floor(Math.random() * (i + 1));
          var temp = array[i];
          array[i] = array[j];
          array[j] = temp;
      }
      return array;
  }
  

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('send data', function(msg){
      msg = [[msg]];
      console.log(msg);
      console.log(RF.predict(msg));
      
    io.emit('send data',
    msg
    );
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});


and the html:
HTML
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(){
          socket.emit('send data', $('#m').val());
          $('#m').val('');
          return false;
        });
        socket.on('send data', function(msg){
          $('#messages').append($('<li>').text(msg));
          window.scrollTo(0, document.body.scrollHeight);
        });
      });
    </script>
  </body>
</html>

Thanks so much!

What I have tried:

I tried sending the data like:
46 , 183 , 46 , 89.51666666666667 , 3109.1353107344635 ,55.75962079080581 , 46 , 5371 , 0.7339762336495166 ,  -1.2148916670171341 , '4:45', '12/07/2020'

into a double array msg = [[msg]] but it keeps converting it to
[
  ['46 , 183 , 46 , 89.51666666666667 , ' +
    '3109.1353107344635 ,55.75962079080581 , 46 , 5371 , ' +
    "0.7339762336495166 ,  -1.2148916670171341 , '4:45', " +
    "'12/07/2020'"
  ]
]


instead of:
[
  [
    46,
    183,
    46,
    89.51666666666667,
    3109.1353107344635,
    55.75962079080581,
    46,
    5371,
    0.7339762336495166,
    -1.2148916670171341,
    '4:45',
    '12/07/2020'
  ]
]
Posted
Updated 5-Jan-21 10:57am
v3
Comments
Richard MacCutchan 5-Jan-21 11:11am    
"but it keeps converting it to"
What or who is it?
ynjay 5-Jan-21 12:35pm    
socket.io, when I send from client to server the data gets converted to a String
Richard MacCutchan 5-Jan-21 12:39pm    
And how does it do that? Socket transfers do nothing to the data, they just move it across the network. Your software must be doing something to store it as a string. But since you have not shown any of your code it is impossible to guess where or how.
ynjay 5-Jan-21 12:41pm    
I will add my code
Dave Kreskowiak 5-Jan-21 12:48pm    
Socket.Io is a namespace. Namespaces don't do anything.

We need to see the code you're using to send the data.

1 solution

Quote:
Array keeps returning as string

I suspect that you have wrong assumption about how things works.
Quote:
into a double array msg = [[msg]] but it keeps converting it to

I suspect that msg is a string and you embed it in a double array, which result in a string in a double array.
The problem is that you expect a magic conversion to another data structure.
I fear you need to tell to do the conversion, somewhere.
Try:
JavaScript
console.log(msg);
msg = [[msg]];
console.log(msg);

and see in log file what was msg before you embed it in a double array.
Lay be you search the wrong problem in the wrong place.
 
Share this answer
 
Comments
ynjay 5-Jan-21 17:13pm    
Thanks for your answer! So I tried logging msg and I got
46 , 183 , 46 , 89.51666666666667 , 3109.1353107344635 ,55.75962079080581 , 46 , 5371 , 0.7339762336495166 ,  -1.2148916670171341 , '4:45', '12/07/2020'


I just tried console.log(typeof msg) and I got string
Patrice T 5-Jan-21 17:24pm    
This confirms what I said.
you need to find how to convert the string the way you want.
I am not a JS user.
ynjay 5-Jan-21 22:07pm    
Thanks so much for your help. Somebody suggested to use the split method, seems to work.
Patrice T 5-Jan-21 22:11pm    
Beware, the split method works as long a you don't have a string with a comma inside.
You still need to know when to convert to numbers.
ynjay 6-Jan-21 9:57am    
Thanks so much!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900