'Set half of tesor columns to zero

I have a tensor of size m x n (m rows and n columns).
For example:

[ 5 8 4 3
  1 3 5 4
  3 9 8 6 ]

I wish to randomly select half of the columns, and set all the values in this columns as zeros.
For our example, it will create something like this:

[ 5 0 4 0
  1 0 5 0
  3 0 8 0 ]

I'm aware how to set zero randomly half of all the elements,

torch.rand(x.shape) > 0.5

but done randomly without consideration in the columns, which is not helpfull for my case.

Thank you for any help,
Dave



Solution 1:[1]

import torch
x = torch.rand(3,4)
x
tensor([[0.0143, 0.1070, 0.9985, 0.0727],
        [0.4052, 0.8716, 0.7376, 0.5495],
        [0.2553, 0.2330, 0.9285, 0.6535]])
for i in [1,3] : # list has your columns which you want to make zero
    x[:,i] = 0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prajot Kuvalekar