search
HomeBackend DevelopmentPython TutorialHow to use the np.random.permutation function in python

    1: Function introduction

    np.random.permutation() Generally speaking, it is a random permutation function, which is to The input data is randomly arranged. The official document states that this function can only randomly arrange one-dimensional data, and for multi-dimensional data, it can only randomly arrange the data in the first dimension.

    In short: the function of np.random.permutation function is to generate a scrambled random list according to the given list

    When processing the data When setting up a data set, you can usually use this function to shuffle the internal order of the data set and shuffle the label sequence in the same order.

    2: Example

    2.1 Directly process array or list numbers

    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)

    How to use the np.random.permutation function in python

    2.2 Indirect processing: do not change the original data (for arrays Index processing)

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

    How to use the np.random.permutation function in python

    ##Supplement: Generally it can only be used for N-dimensional arrays and can only convert integer scalar arrays to scalar indexes

    why?label1[a1] label1 is a list, a1 is a random arrangement of list subscripts but! The list structure does not have a scalar index label1[a1] error

    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] )#这列表结构没有标量索引 所以会报错

    How to use the np.random.permutation function in python

    2.3 Example: random shuffling of iris flowers in iris data (can be used directly)

    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:]]

    The array subscript is the redistribution of scalar index: The subscript starts from 0

    How to use the np.random.permutation function in python

    The above is the detailed content of How to use the np.random.permutation function in python. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

    Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

    Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

    ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

    Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

    In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

    Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

    ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

    How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

    ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

    Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

    Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

    How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

    Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

    What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

    Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.