0

I have a javascript matrix class with constructor

    class Matrix {
  constructor(rows, cols) {
    this.rows = rows;
    this.cols = cols;
    this.data = Array(this.rows).fill().map(() => Array(this.cols).fill(0));
  }

Now I have a matrix namely weights_1 which the size is 32 * 64

How to randomly selects some elements in weights_1 and make them to zero? for example, I want to make 30% of elements in the weights_1 to zero.

1
  • Array.from({length: 100}, _ => Math.random() < 0.3 ? 0 : 666); Commented Dec 10, 2020 at 16:04

2 Answers 2

1

How about

this.data = Array(this.rows).fill().map(() => Array(this.cols).fill(Math.floor(Math.random() * 100) > 30 ? 1 : 0));

This would randomly set (roughly) 30% of the values to 0 and the others to 1.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, is there any way just change weights_1? because I have already generated a matrix named weights_1, and it already has values in this matrix, and I would like to change some of them to zero, and other elements will keep the same.
You'd have to do weights_1.map((arr) => arr.map((val) => Math.floor(Math.random() * 100) > 30 ? val : 0))
0

Here's a solution that'll make sure the result is 30% instead of just "probably around 30%." The variable naming should make everything self-explanatory. I used randojs for the shuffling, but you can refer to this post about shuffling in javascript if you prefer to do that part yourself.

class Matrix {
  constructor(rows, cols) {
    this.rows = rows;
    this.cols = cols;
    this.data = Array(this.rows).fill().map(() => Array(this.cols).fill(999));
  }

  zeroOutPercentage(percentage) {
    var totalWeigths = this.rows * this.cols;
    var numberOfWeightsToZeroOut = Math.floor(totalWeigths * (percentage / 100));
    var weightsToZeroOut = randoSequence(totalWeigths).slice(0, numberOfWeightsToZeroOut);

    for (var i = 0; i < weightsToZeroOut.length; i++) {
      var row = Math.floor(weightsToZeroOut[i] / this.rows);
      var col = weightsToZeroOut[i] % this.rows;
      this.data[row][col] = 0;
    }
  }
}

var weights_1 = new Matrix(20, 20);
weights_1.zeroOutPercentage(30);
console.log(weights_1.data);
<script src="https://randojs.com/2.0.0.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.