2012-02-01 25 views
12
  • Tengo una matriz numpy con forma de (4601, 58).
  • quiero dividir la matriz al azar de acuerdo con el 60%, 20%, 20% dividido en función del número de filas
  • Esto es para la tarea de aprendizaje automático que necesito
  • ¿Hay una función numpy que selecciona al azar filas?

Respuesta

17

puede utilizar numpy.random.shuffle

import numpy as np 

N = 4601 
data = np.arange(N*58).reshape(-1, 58) 
np.random.shuffle(data) 

a = data[:int(N*0.6)] 
b = data[int(N*0.6):int(N*0.8)] 
c = data[int(N*0.8):] 
3

Si desea seleccionar aleatoriamente filas, es posible que utilices random.sample de la biblioteca estándar de Python:

import random 

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

random.sample muestras sin reemplazo, por lo que no necesita preocuparse por filas repetidas terminando en choice. Dada una matriz numpy llamada matrix, puede seleccionar las filas cortando, como esta: matrix[choice].

Por supuesto, k puede ser igual al número de elementos totales en la población, y luego choice contendría un orden aleatorio de los índices para sus filas. Luego puede dividir choice como lo desee, si eso es todo lo que necesita.

7

Un complemento a la respuesta de Hyry si quiere mezclar constantemente varias matrices x, y, z con la misma primera dimensión: x.shape[0] == y.shape[0] == z.shape[0] == n_samples.

Usted puede hacer:

rng = np.random.RandomState(42) # reproducible results with a fixed seed 
indices = np.arange(n_samples) 
rng.shuffle(indices) 
x_shuffled = x[indices] 
y_shuffled = y[indices] 
z_shuffled = z[indices] 

Y a continuación, proceder a la división de cada matriz barajado como en la respuesta de Hyry.

1

Desde que lo necesite para el aprendizaje de máquina, que aquí es un método que escribí:

import numpy as np 

def split_random(matrix, percent_train=70, percent_test=15): 
    """ 
    Splits matrix data into randomly ordered sets 
    grouped by provided percentages. 

    Usage: 
    rows = 100 
    columns = 2 
    matrix = np.random.rand(rows, columns) 
    training, testing, validation = \ 
    split_random(matrix, percent_train=80, percent_test=10) 

    percent_validation 10 
    training (80, 2) 
    testing (10, 2) 
    validation (10, 2) 

    Returns: 
    - training_data: percentage_train e.g. 70% 
    - testing_data: percent_test e.g. 15% 
    - validation_data: reminder from 100% e.g. 15% 
    Created by Uki D. Lucas on Feb. 4, 2017 
    """ 

    percent_validation = 100 - percent_train - percent_test 

    if percent_validation < 0: 
     print("Make sure that the provided sum of " + \ 
     "training and testing percentages is equal, " + \ 
     "or less than 100%.") 
     percent_validation = 0 
    else: 
     print("percent_validation", percent_validation) 

    #print(matrix) 
    rows = matrix.shape[0] 
    np.random.shuffle(matrix) 

    end_training = int(rows*percent_train/100)  
    end_testing = end_training + int((rows * percent_test/100)) 

    training = matrix[:end_training] 
    testing = matrix[end_training:end_testing] 
    validation = matrix[end_testing:] 
    return training, testing, validation 

# TEST: 
rows = 100 
columns = 2 
matrix = np.random.rand(rows, columns) 
training, testing, validation = split_random(matrix, percent_train=80, percent_test=10) 

print("training",training.shape) 
print("testing",testing.shape) 
print("validation",validation.shape) 

print(split_random.__doc__) 
  • formación (80, 2)
  • de ensayo (10, 2)
  • validación (10, 2)
Cuestiones relacionadas