Artificial Intelligence Getting --Numpy

A vector

Vector refers to a bunch number set formed

Multi-dimensional arrays, called Vector computing

Single number called a scalar

Two multi-dimensional arrays

  1. numpy definition of a multidimensional array:

With numpy.ndarray type (n representative of the number n, d Representative dimision dimension)

Ndarray itself is a class of this class is instantiated objects out, a multidimensional array is

Multidimensional array is an object

  1. Create a multidimensional array object:

    1> numpy.arange (start, end, step)

    He is accessed through numpy. Is a function in numpy

    It returns an array is an arithmetic sequence of one-dimensional arrays

    2> numpy.array()

    The array is not a class, is a function in numpy

    In () parentheses numpy.array function, the input may be interpreted as any array container (or a list of tuples)

    3> a method of obtaining the array element type:

    d = np.array([[1,2,3],[4,5,6]])
    方法一: type(d[0][0])  #==>python取类型的方法
    方法二: d.dtype  #==> numpy 取类型的方法

    4> int 32 represent four-byte integer

    Why is int32?

    Particular type is not specified in the definition, and now uses 4 bytes plastic just to save data d,

    Therefore default value is 4 bytes default ..

    Meaning 5> <U1 of

    g=np.array(['1','2','3'])
    print(g.dtype)    # <U1
    print(type(g[0]))  #<class 'numpy.str_'>
    • Unicode encoding each four bytes. By the high and low points. Into the little-endian and big-endian
    • 'U' is representative of unicode encoding
    • '<' Indicates little-endian
    • '1' represents only one character in each string

    6> 'numpy.str_' meaning

    • str represents a string
    • _ And python string as distinguished

    7> manually specify the type of the wording

    G=np.array(['1','2','3'],dtype=np.int32)
    print(G.dtype)  #int32
    H=G.astype(np.str_)
    print(H.dtype)  #<U11
    • 'As long as the manual setting of the specified type, the type of data to do it automatically converted. While the value is a string, but we are targeting Type Int32 plastic, so it is of type int 32'
    • Scene: To change back to string format, with astype function
    • <U11 explanation: when the type is changed back again, back to reserve some space in memory,

Note: All types of conversion and are not actually related to the type of conversion are copied, and then press the new type of copy, however, it is a constant source

dtype attribute is used to take the type of element

8> attribute on a dimension

d = np.array([[1,2,3],[4,5,6]])
print(d.shape)  #(2, 3)  2行 3列
  • shape attributes:

Shape attribute value is a tuple type, comprising a plurality of elements within a tuple, respectively, from high to low to indicate the number of each dimension .. latitude i.e. high to low latitudes

If you have page ranks

Page: Maximum dimensions

Line: second place

Column: Minimum

9> arrange and array can create an array, you can sometimes mixed with

i = np.array([[np.arange(1,5),np.arange(5,9),np.arange(9,13)],[np.arange(13,17),np.arange(17,21),np.arange(21,25)]])
print(i)
# [[[ 1  2  3  4]
#   [ 5  6  7  8]
#   [ 9 10 11 12]]
# 
#  [[13 14 15 16]
#   [17 18 19 20]
#   [21 22 23 24]]]

We can see the dimension with the shape attributes

Numpy in multi-dimensional arrays, three-dimensional rarely used

10> element index

元素索引是从 0  开始的

数组[索引]
数组[行索引][列索引]
数组[页索引][行索引][列索引]

a=np.array([[[ 1  ,2 , 3  ,4], [ 5  ,6 , 7 , 8], [ 9 ,10 ,11 ,12]]])
print(a[0])   #[[ 1  ,2 , 3  ,4], [ 5  ,6 , 7 , 8], [ 9 ,10 ,11 ,12]]
print(a[0][0])   # [1 2 3 4]
print(a[0][0][0])  # 1

for i in range(a.shape[0]):  # 0 是逐页
    for j in range(a.shape[1]): # 1 是逐行
        for k in range(a.shape[2]):   # 2 是逐列
            print(a[i][j][k])

Numpy three built-in types and custom types

  1. Built-in type

    a) Pros:
    You can specify how much memory occupied by data type
    can be flexible and change
    b) Disadvantages:
    Because the flexible variability, so at the expense of performance, (need to leave enough space)
    can not use a fixed memory address calculation method can only be done dynamically, since the operation of the address would be spent running time
    Note: providing a fixed size for each type numpy, the calculation of the address can therefore be determined by the type defined numpy own independent set of data types with a data type system .. fixed length, the number of bytes is fixed ..
    Example: Numpy.bool a Boolean one byte
    signed version (positive and negative numbers):
    Int8 signed 1 byte type
    Int16 2-byte signed type
    Int32 4-byte signed type
    unsigned version (only positive):
    Uint8 1 byte unsigned
    Uint16 2 byte unsigned type
    Uint32 4 byte unsigned type
    float type:
    float16 2-byte floating-point signed
    Float32 signed 4-byte floating-point
    Float64 8-byte floating-point signed
    type complex (real and imaginary Portions are represented by two 4-byte floating point):
    complex64. 8-byte type complex
    Complex128 16 bytes complex types
    Note: 1 = a plurality of combinations of two floating-point
    string type:
    Str_ string is not a predetermined number of bytes, because the length of the string depending on the type of string of unicode
    string length based on the character string contains decision
    NOTE: lunicode = 4 bytes
    can be set dtype type conversion and astype

  2. Custom Types

    1. Direct use of the original name of the built-in type

    2. Format using the compact type (encoded string type)
      simplifies the operation: string can be represented with fewer

      Full name Simplified format
      Numpy.int8 i1
      Int16 i2
      Uint32 U4
      Float64 F8
      Complex128 Cl6
    3. Multi-byte integers endian size of
      multi-byte integers can add a prefix byte order
      prefix type:
      '<' low-bit little-endian lower address
      '=' default, not artificially designated
      '>' big endian low tree bits of address

      Note: To prevent compatibility problems sometimes due to a function of the code on different processors transplant brought forcibly added so '<' and '>'

      import numpy as np
      
      a=np.array([('ABC',[1,2,3])],dtype={'names':['name','scores'],'formats':['U3','3i4']})
      print(a)  #[('ABC', [1, 2, 3])]
      print(a[0]['name'])   #ABC
      print(a[0]['scores'][0])  #1
      print(a[0]['scores'][1])    #2
      print(a[0]['scores'][2])    #3
      

b = np.array ([0x1234], dtype = ( 'u2', { 'low bit' :( 'u1', 0), 'high number of bits' :( 'u1', 1)})) # Big endian
print ( '{: x}' format (b [0]).) # B hexadecimal output element in the No. 0
print ( '{: x}, {: x}'. Format (b [ 'low order bits'] [0], b [ ' high digit'] [0]))
`

  1. About byte order:

    Without adding endian data types: one-byte integer, Boolean, complex types, floating point

    Other cases: Numpy.str_ => U + number of characters

    Unicode itself is multi-byte integers, a can be regarded as a unicode UInt32, there is also the size of the endian

    ​ Numpy.bool => b

    Note: numpy python package is provided, a method of using custom type element may be a complete different types of access; or an element with a different type to be combined to make up the array elements where numpy homogeneous ..

Four sections

And similar python

Array [Start: End: step]

You can slice for multidimensional arrays

Default start: the first element (in steps of n), the last element (negative step) -> Reverse

Default termination: tail (positive steps), the first former (negative steps)

Default Step: 1

a = np.arange(1,10)
print(a)  #[1 2 3 4 5 6 7 8 9]
print(a[:3])   #[1 2 3]
print(a[3:6])  #[4 5 6]
print(a[6:])   #[7 8 9]
print(a[:-4:-1])  #[9 8 7]
print(a[...])    #[1 2 3 4 5 6 7 8 9]
print(a[:])    #[1 2 3 4 5 6 7 8 9]
print(a[1::3])  #[2 5 8]

b=np.arange(1,25).reshape(2,3,4)
print(b)
# print(b[:,0,0])  # [ 1 13]
# print(b[0,:,:])
# print(b[0,1,::2])  #[5 7]
# print(b[-1,1:,2:])
# print(b[:,1:,1])
print(b[1,1,::2])  #[17 19]

One or more defaults sections:

​ a[...] a[ : ]

Five dimensions of change

It divided 4 ways

  1. View Variable Dimension:

    Get different dimensions for an array object view

    Method: Array .reshape (New Dimension) -> Array view New Dimension

    Array .ravel () -> one-dimensional array of view

    import numpy as np
    
    a=np.array([np.arange(1,9)])
    print(a)   #[[1 2 3 4 5 6 7 8]]
    
    b=a.reshape(2,4)
    print(b)   #[[1 2 3 4] [5 6 7 8]]
    
    c=b.ravel()
    print(c)   #[1 2 3 4 5 6 7 8]
  2. Copy the variance dimension (different dimensions of copies):
    get different dimensions for a copy of the array object
    method: flatten () -> that copy of the array of
    functions: to obtain a copy of the original data while gaining an example, which is a copy

    d=b.flatten()
    print(d)   #[1 2 3 4 5 6 7 8]  复制成一维
    
    e=b.reshape(2,2,2).copy()
    print(e)
  3. Situ variable dimension
    array. Shape = (new dimension)
    equivalent to the
    array. Resize (New Dimension)

    a=np.array([np.arange(1,9)])
    a.shape = (2,2,2)
    # a.resize =(2,2,2) 
    print(a)  #变成一个新的2页2行2列的三维数组
  4. View transpose (the concept of linear algebra)
    understood as interchanging rows
    array transpose () -.> View transposed array
    equivalent to

    Array T -.> Transpose View Properties

    a=np.array([np.arange(1,9)])
    a.shape = (4,2)  #a是4行2列
    g = a.transpose()
    print(g)
    # [[1 3 5 7]
    #  [2 4 6 8]]
    
    print(np.array([a]).T)  #先转成多维数组,再转置
    print(a.reshape(-1,1))   # -1 无效值

    Note: The device must be two-dimensional array can

    Six and a combination of split

    • Vertical composition:

    numpy.vstack ((vertically)) the stack

    • Vertical Split:

    numpy.vsplit (array, the number of copies)

    ​ 列: a,b=np.vsplit( c , 2 )

    C is a variable representative of the split is split into 2 represents 2 parts

    import numpy as np
    
    a=np.arange(11,20).reshape(3,3)
    print(a)
    b=np.arange(21,30).reshape(3,3)
    print(b)
    c=np.vstack((a,b))
    print(c)
    
    l,h=np.vsplit(c,2)
    print(l,h,sep='\n')  #把c 拆分成 l 和 h 两个
    • Level combinations:

    numpy.hstack ((left)) stack

    • Split level:

    numpy.hsplit (array, the number of copies)

    ​ 列: a,b=np.vsplit( c , 2 )

    C is a variable representative of the split is split into 2 represents 2 parts

    import numpy as np
    
    a=np.arange(11,20).reshape(3,3)
    print(a)
    b=np.arange(21,30).reshape(3,3)
    print(b)
    c=np.hstack((a,b))
    print(c)
    l,h=np.hsplit(c,2)
    print(l,h,sep='\n')
    • A combination of depth and depth resolution

      numpy.dstack ((front and rear)) stack

      numpy.dsplit (array, the number of copies)

    c=np.dstack((a,b))
    print(c)
    l,h=np.dsplit(c,2)
    print(l,h,sep='\n')

    Depth combinations:

    1. Before and layout, to the plane of the line to cut, to cut this part are combined to form an array with a third vertical, constituting a three-digit group
    2. These three sections is three pages, each page has a two-dimensional array from the corresponding row, also made transposed, to cut the rows into columns

    Depth Split:

    1. a, b = np.dsplit( c , 2)

    2. print (aT [0]. T, bT [0]. T, sep = '\ n') #T [0]. T transposition takes No. 0 sub-set of elements

      NOTE: To return to the depth resolution two-dimensional array pattern, to be hand operated

      Row / column combination

    3. Features: Only the combination can not be split

      numpy.row_stack ((vertical)) is equivalent to numpy.vstack

      numpy.column_stack ((approximately)) is equivalent to numpy.hstack

      numpy.column_stack ((approximately)) shorthand np.c_ [about]

Review ndarray seven properties

  • dtype element type
  • shape array dimensions
  • T transpose view
  • ndim number of dimensions
  • size number of elements. equivalent to a one-dimensional array of python len ()
  • Total number of bytes npytes element
  • len () will never get in shape first element *** size ** get is in the shape of the product
  • itemize the number of bytes element that is an element accounted for how many bytes
  • flat flat obtained iterator is an iterator object may be iterating
  • tolist array change list
  • imag imaginary part of the array
  • real real part of the array

***** numpyThere append function method, but must have a return value

import numpy as np

a=np.array([
    [1+1j,2+4j,3+6j],
    [1+1j,2+4j,3+6j],
    [1+1j,2+4j,3+6j]
])
print(a.dtype)  #complex128 16个字节 8位是实部 8位是虚部
print(a.shape)   #3行3列
print(a.ndim)    #2维
print(a.size,len(a))   # 9个元素  3 列
print(a.itemsize)  # 每个元素占16个字节
print(a.nbytes)  # 144个字节  16* 9
print(a.T)
print(a.real,a.imag,sep='\n')   # 取实部和虚部
for i in a.flat:   #flat 扁平迭代器
    print(i)
# ----------------------------------------------------------
#列 :
def fun(z,zz):
    z.append(zz)
    return z
x=np.array([1,2,3])
y=40
# x=fun(x,y) #会报错 因为数组没有append方法
x=fun(x.tolist(),y)
print(x)  #[1, 2, 3, 40]

y=np.append(x,50)
print(y)    #[ 1  2  3 40 50]

Guess you like

Origin www.cnblogs.com/clove7/p/11536347.html