>  기사  >  백엔드 개발  >  Python에서 np.random.permutation 함수를 사용하는 방법

Python에서 np.random.permutation 함수를 사용하는 방법

PHPz
PHPz앞으로
2023-05-17 13:43:061814검색

    1: 함수 소개

    np.random.permutation() 일반적으로 입력 데이터를 무작위로 배열하는 임의 순열 함수입니다. 공식 문서에서는 이 함수를 사용할 수 있는 경우에만 사용할 수 있다고 명시하고 있습니다. 1차원 데이터는 무작위로 배열됩니다. 다차원 데이터의 경우 첫 번째 차원의 데이터만 무작위로 배열될 수 있습니다.

    간단히 말하면 np.random.permutation 함수의 기능은 주어진 목록에 따라 뒤섞인 무작위 목록을 생성하는 것입니다.

    데이터 세트를 처리할 때 일반적으로 이 기능을 사용하여 데이터 내부를 뒤섞을 수 있습니다. 순서를 설정하고 동일한 순서로 라벨 순서를 섞습니다.

    둘: 예

    2.1 배열 또는 목록 번호를 직접 처리

    import numpy as np
    
    data = np.array([1,2,3,4,5,6,7])
    a = np.random.permutation(data)
    b = np.random.permutation([5,0,9,0,1,1,1])
    print(a)
    print( "data:", data )
    print(b)

    Python에서 np.random.permutation 함수를 사용하는 방법

    2.2 간접 처리: 원본 데이터를 변경하지 않음(배열 첨자 처리)

    label = np.array([1,2,3,4,5,6,7])
    a = np.random.permutation(np.arange(len(label)))
    print("Label[a] :" ,label[a] )

    Python에서 np.random.permutation 함수를 사용하는 방법

    보충: 일반적으로 다음과 같이만 가능합니다. N 차원 배열에 사용되는 것은 정수 스칼라 배열을 스칼라 인덱스로만 변환할 수 있습니다

    왜?label1[a1] label1은 목록이고, a1은 목록 첨자의 무작위 순열이지만! 목록 구조에 스칼라 인덱스 label1[a1] 오류

    label1=[1,2,3,4,5,6,7]
    print(len(label1))
    
    a1 = np.random.permutation(np.arange(len(label1)))#有结果
    
    print(a1)
    
    print("Label1[a1] :" ,label1[a1] )#这列表结构没有标量索引 所以会报错

    Python에서 np.random.permutation 함수를 사용하는 방법

    2.3 예: 붓꽃 데이터에서 붓꽃 무작위 섞기(직접 사용할 수 있음)

    from sklearn import svm
    from sklearn import datasets #sklearn 的数据集
    iris = datasets.load_iris()
    iris_x = iris.data
    iris_y = iris.target
    indices = np.random.permutation(len(iris_x))
    
    #此时 打乱的是数组的下标的排序
    print(indices)
    print(indices[:-10])#到倒数第10个为止
    print(indices[-10:])#最后10个
    
    # print(type(iris_x))   <class &#39;numpy.ndarray&#39;>
    
    #9:1分类
    #iris_x_train = iris_x[indices[:-10]]#使用的数组打乱后的下标
    #iris_y_train = iris_y[indices[:-10]]
    #iris_x_test= iris_x[indices[-10:]]
    #iris_y_test= iris_y[indices[-10:]]

    배열 첨자 재배포, 즉 스칼라 인덱스: 다음 마크는 0

    Python에서 np.random.permutation 함수를 사용하는 방법부터 시작합니다.

    위 내용은 Python에서 np.random.permutation 함수를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제