Numpy: How to randomly split/select an matrix into n-different matrices

前端 未结 4 796
攒了一身酷
攒了一身酷 2021-02-05 16:00
  • I have a numpy matrix with shape of (4601, 58).
  • I want to split the matrix randomly as per 60%, 20%, 20% split based on number of rows
  • This is for Machin
4条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 16:20

    If you want to randomly select rows, you could just use random.sample from the standard Python library:

    import random
    
    population = range(4601) # Your number of rows
    choice = random.sample(population, k) # k being the number of samples you require
    

    random.sample samples without replacement, so you don't need to worry about repeated rows ending up in choice. Given a numpy array called matrix, you can select the rows by slicing, like this: matrix[choice].

    Of, course, k can be equal to the number of total elements in the population, and then choice would contain a random ordering of the indices for your rows. Then you can partition choice as you please, if that's all you need.

提交回复
热议问题