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.

HAO CHEN
  • 1,209
  • 3
  • 18
  • 32

2 Answers2

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.

Rob Bailey
  • 920
  • 1
  • 8
  • 23
  • 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. – HAO CHEN Dec 10 '20 at 16:11
  • You'd have to do `weights_1.map((arr) => arr.map((val) => Math.floor(Math.random() * 100) > 30 ? val : 0))` – Rob Bailey Dec 10 '20 at 16:48
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>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15