如何从2d numpy数组中随机选择

时间:2017-10-19 02:20:12

标签: python numpy

我有一个列表清单(以及它真正的评级矩阵),ground_truth。我想制作20%的非零项目= 0.我最初的方法是:

var cookies;

phantom.create(['--ignore-ssl-errors=yes', '--load-images=no', '--ssl-
protocol=any']).then(function(ph) {
ph.createPage().then(function(page) {

page.property("onConsoleMessage", function(message) {
   console.log(message); 
});

page.property('onResourceReceived', function(response) {
        console.log(phantom.cookies); //Show the page cookies
        cookies = phantom.cookies;
       fs.write(CookieJar, JSON.stringify(phantom.cookies), "w"); //its not creating a file
}).then(function() {
      console.log('Cookies');
      console.log(phantom.cookies); //Equals to undefined
      console.log(cookies); //Equals to undefined
});;

page.open('https://stackoverflow.com').then(function(status) {
  if(status == 'success') {
     console.log('success');
  }  
});

});
});

然而,这会产生错误

ground_truth = [[0,99,98],[0,84,97], [55,0,0]]
ground_truth = np.array(ground_truth)
np.random.choice(ground_truth)

所以我的解决方案是将矩阵展平为1d数组,然后随机选取20%的非零项。

ValueError: a must be 1-dimensional

现在,我想将这些项目设置为0,并将更改反映在原始矩阵中。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

def get_average():
    ls = []
    user_input = 0
    while user_input != 'q':
        user_input = raw_input('Enter inter (q to quit):')
        if user_input != 'q':
            ls.append(int(user_input))
        elif user_input == 'q':
            break
    ls.pop()
    return sum(ls), ls

print get_average()

# ls.pop() will delete the last number of input