美文网首页
图像识别相关Python与Numpy学习备忘

图像识别相关Python与Numpy学习备忘

作者: Xtuphe | 来源:发表于2020-04-25 17:36 被阅读0次

    Colab真是学编程的好东西,不过需要科学上网,为了方便查询我把CS231n Python Tutorial With Google Colab上的东西搬来了

    基础数据类型

    Numbers

    x = 3
    print(x, type(x))
    

    3 <class 'int'>

    print(x + 1)   # Addition
    print(x - 1)   # Subtraction
    print(x * 2)   # Multiplication
    print(x ** 2)  # Exponentiation
    

    4
    2
    6
    9

    x += 1
    print(x)
    x *= 2
    print(x)
    

    9
    18

    y = 2.5
    print(type(y))
    print(y, y + 1, y * 2, y ** 2)
    

    <class 'float'>
    2.5 3.5 5.0 6.25

    ⚠️ Python不支持递增(x++)或递减(x--)

    Booleans

    t, f = True, False
    print(type(t))
    

    <class 'bool'>
    Python用英文单词来表示布尔运算符(and 表示&&, or 表示||)

    print(t and f) # Logical AND;
    print(t or f)  # Logical OR;
    print(not t)   # Logical NOT;
    print(t != f)  # Logical XOR;
    

    False
    True
    False
    True

    Strings

    hello = 'hello'   # String literals can use single quotes
    world = "world"   # or double quotes; it does not matter
    print(hello, len(hello))
    

    hello 5

    hw = hello + ' ' + world  # String concatenation
    print(hw)
    

    hello world

    hw12 = '{} {} {}'.format(hello, world, 12)  # string formatting
    print(hw12)
    

    hello world 12

    s = "hello"
    print(s.capitalize())  # Capitalize a string
    print(s.upper())       # Convert a string to uppercase; prints "HELLO"
    print(s.rjust(7))      # Right-justify a string, padding with spaces
    print(s.center(7))     # Center a string, padding with spaces
    print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another
    print('  world '.strip())  # Strip leading and trailing whitespace
    

    Hello
    HELLO
      hello
     hello
    he(ell)(ell)o
    world
    更多的方法在这儿 https://docs.python.org/3.7/library/stdtypes.html#string-methods

    Containers

    lists, dictionaries, sets. tuples

    Lists

    list等同于array,长度可变,可包含不同数据类型

    xs = [3, 1, 2]   # Create a list
    print(xs, xs[2])
    print(xs[-1])     # Negative indices count from the end of the list; prints "2"
    

    [3, 1, 2] 2
    2

    xs[2] = 'foo'    # Lists can contain elements of different types
    print(xs)
    

    [3, 1, 'foo']

    xs.append('bar') # Add a new element to the end of the list
    print(xs) 
    

    [3, 1, 'foo', 'bar']

    x = xs.pop()     # Remove and return the last element of the list
    print(x, xs)
    

    bar [3, 1, 'foo']
    list更多操作在这儿:https://docs.python.org/3.7/tutorial/datastructures.html#more-on-lists

    slicing

    nums = list(range(5))    # range is a built-in function that creates a list of integers
    print(nums)         # Prints "[0, 1, 2, 3, 4]"
    print(nums[2:4])    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
    print(nums[2:])     # Get a slice from index 2 to the end; prints "[2, 3, 4]"
    print(nums[:2])     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
    print(nums[:])      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
    print(nums[:-1])    # Slice indices can be negative; prints ["0, 1, 2, 3]"
    nums[2:4] = [8, 9] # Assign a new sublist to a slice
    print(nums)         # Prints "[0, 1, 8, 9, 4]"
    

    [0, 1, 2, 3, 4]
    [2, 3]
    [2, 3, 4]
    [0, 1]
    [0, 1, 2, 3, 4]
    [0, 1, 2, 3]
    [0, 1, 8, 9, 4]

    Loops

    animals = ['cat', 'dog', 'monkey']
    for animal in animals:
        print(animal)
    

    cat
    dog
    monkey

    animals = ['cat', 'dog', 'monkey']
    for idx, animal in enumerate(animals):
        print('#{}: {}'.format(idx + 1, animal))
    

    #1: cat
    #2: dog
    #3: monkey

    nums = [0, 1, 2, 3, 4]
    squares = []
    for x in nums:
        squares.append(x ** 2)
    print(squares)
    

    List comprehensions

    [0, 1, 4, 9, 16]
    等同于

    nums = [0, 1, 2, 3, 4]
    squares = [x ** 2 for x in nums]
    print(squares)
    

    [0, 1, 4, 9, 16]
    也可以加条件

    nums = [0, 1, 2, 3, 4]
    even_squares = [x ** 2 for x in nums if x % 2 == 0]
    print(even_squares)
    

    [0, 4, 16]

    Dictionaries

    d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
    print(d['cat'])       # Get an entry from a dictionary; prints "cute"
    print('cat' in d)     # Check if a dictionary has a given key; prints "True"
    

    cute
    True

    d['fish'] = 'wet'    # Set an entry in a dictionary
    print(d['fish'])      # Prints "wet"
    

    wet

    print(d['monkey'])  # KeyError: 'monkey' not a key of d
    

    monkey不是d的key,所以会报错

    print(d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
    print(d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"
    

    N/A
    wet

    del d['fish']        # Remove an element from a dictionary
    print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
    

    N/A
    更多关于dictionary:https://docs.python.org/2/library/stdtypes.html#dict
    字典遍历

    d = {'person': 2, 'cat': 4, 'spider': 8}
    for animal, legs in d.items():
        print('A {} has {} legs'.format(animal, legs))
    

    A person has 2 legs
    A cat has 4 legs
    A spider has 8 legs

    Dictionary comprehension

    nums = [0, 1, 2, 3, 4]
    even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
    print(even_num_to_square)
    

    {0: 0, 2: 4, 4: 16}

    Sets

    animals = {'cat', 'dog'}
    print('cat' in animals)   # Check if an element is in a set; prints "True"
    print('fish' in animals)  # prints "False"
    

    True
    False

    animals.add('fish')      # Add an element to a set
    print('fish' in animals)
    print(len(animals))       # Number of elements in a set;
    

    True
    3

    animals.add('cat')       # Adding an element that is already in the set does nothing
    print(len(animals))       
    animals.remove('cat')    # Remove an element from a set
    print(len(animals))  
    

    3
    2

    set与list类似,可以遍历,但由于set是无序的,所以不能指望每次打印的顺序一样

    animals = {'cat', 'dog', 'fish'}
    for idx, animal in enumerate(animals):
        print('#{}: {}'.format(idx + 1, animal))
    

    #1: dog
    #2: cat
    #3: fish

    Set comprehensions

    from math import sqrt
    print({int(sqrt(x)) for x in range(30)})
    

    {0, 1, 2, 3, 4, 5}

    Tuples

    tuple与list类似,不同的地方在于

    • tuple可以被用作dictionary的key,而list不能
    • tuple不能用下标取值,list可以
    d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
    t = (5, 6)       # Create a tuple
    print(type(t))
    print(d[t])       
    print(d[(1, 2)])
    

    <class 'tuple'>
    5
    1

    t[0] = 1
    

    会报错

    Functions

    Python用def定义函数

    def sign(x):
        if x > 0:
            return 'positive'
        elif x < 0:
            return 'negative'
        else:
            return 'zero'
    
    for x in [-1, 0, 1]:
        print(sign(x))
    

    negative
    zero
    positive

    常常定义函数来接收可空参数

    def hello(name, loud=False):
        if loud:
            print('HELLO, {}'.format(name.upper()))
        else:
            print('Hello, {}!'.format(name))
    
    hello('Bob')
    hello('Fred', loud=True)
    

    Hello, Bob!
    HELLO, FRED

    Classes

    class Greeter:
    
        # Constructor
        def __init__(self, name):
            self.name = name  # Create an instance variable
    
        # Instance method
        def greet(self, loud=False):
            if loud:
              print('HELLO, {}'.format(self.name.upper()))
            else:
              print('Hello, {}!'.format(self.name))
    
    g = Greeter('Fred')  # Construct an instance of the Greeter class
    g.greet()            # Call an instance method; prints "Hello, Fred"
    g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"
    

    Hello, Fred!
    HELLO, FRED

    Numpy

    (Numpy的部分有点抽象,自己上手去试会好理解很多。)
    Numpy是Python中科学计算的核心库,它提供了一个高性能的多维度数组对象,和处理这些对象的方法。
    要是用Numpy,首先得引入Numpy包:

    import numpy as np
    

    Arrays

    一个Numpy数组是一个相同类型的值的网格,并通过自然数(非负整数)构成的tuple索引。数据的维度(dimension)即为数组的(rank);数组的形状(shape)是一个tuple,此tuple的每个值是数据每个维度的大小。

    a = np.array([1, 2, 3])  # Create a rank 1 array
    print(type(a), a.shape, a[0], a[1], a[2])
    a[0] = 5                 # Change an element of the array
    print(a)                  
    

    <class 'numpy.ndarray'> (3,) 1 2 3
    [5 2 3]

    b = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array
    print(b)
    

    [[1 2 3]
    [4 5 6]]

    print(b.shape)
    print(b[0, 0], b[0, 1], b[1, 0])
    

    (2, 3)
    1 2 4

    Numpy也提供生成array的方法

    a = np.zeros((2,2))  # Create an array of all zeros
    print(a)
    

    [[0. 0.]
    [0. 0.]]

    b = np.ones((1,2))   # Create an array of all ones
    print(b)
    

    [[1. 1.]]

    c = np.full((4,6), 7) # Create a constant array
    print(c)
    

    创建一个shape为(4, 6),rank为2的array
    [[7 7 7 7 7 7]
    [7 7 7 7 7 7]
    [7 7 7 7 7 7]
    [7 7 7 7 7 7]]

    c = np.full((2,5,7), 9) # Create a constant array
    print(c)
    print(type(c))
    print(c.ndim)
    print(c.shape)
    

    [[[9 9 9 9 9 9 9]
    [9 9 9 9 9 9 9]
    [9 9 9 9 9 9 9]
    [9 9 9 9 9 9 9]
    [9 9 9 9 9 9 9]]

    [[9 9 9 9 9 9 9]
    [9 9 9 9 9 9 9]
    [9 9 9 9 9 9 9]
    [9 9 9 9 9 9 9]
    [9 9 9 9 9 9 9]]]
    <class 'numpy.ndarray'>
    3
    (2, 5, 7)
    创建一个rank为3,shape为(2,5,7)的array

    d = np.eye(2)        # Create a 2x2 identity matrix
    print(d)
    

    [[1. 0.]
    [0. 1.]]

    e = np.random.random((2,2)) # Create an array filled with random values
    print(e)
    

    [[0.8690054 0.57244319]
    [0.29647245 0.81464494]]

    Array indexing

    与Python的list类似,array可以被slice,由于array是多维度的,你必须指定每个维度的slice

    import numpy as np
    
    # 创建一个shape (3, 4)的2维array
    # [[ 1  2  3  4]
    #  [ 5  6  7  8]
    #  [ 9 10 11 12]]
    a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
    
    # 从a中切出前两行中间两列的一个shape为(2, 2)的subarray,a[0:2, 1:3]中的0可以省略
    # [[2 3]
    #  [6 7]]
    b = a[0:2, 1:3]
    print(b)
    

    [[2 3]
    [6 7]]

    slice切出的数据类似于指针,所以修改slice的数据会修改原array

    print(a[0, 1])
    b[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]
    print(a[0, 1]) 
    

    2
    77

    你也可以混合integer indexing和slice indexing,然而,这样会生成一个比原array维度低的新的array。

    # 创建一个rank为2,shape为 (3, 4)的array
    a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
    print(a)
    

    [[ 1 2 3 4]
    [ 5 6 7 8]
    [ 9 10 11 12]]

    获取中间一行数据的2种方法:

    • 混合integer indexing和slice并生成新的低维array
    • 只用slice生成一个与原array相同维度的array
    row_r1 = a[1, :]    # Rank 1 view of the second row of a  
    row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
    row_r3 = a[[1], :]  # Rank 2 view of the second row of a
    print(row_r1, row_r1.shape)
    print(row_r2, row_r2.shape)
    print(row_r3, row_r3.shape)
    

    [5 6 7 8] (4,)
    [[5 6 7 8]] (1, 4)
    [[5 6 7 8]] (1, 4)

    # 取array的某列数据时也会有类似的区别:
    col_r1 = a[:, 1]
    col_r2 = a[:, 1:2]
    print(col_r1, col_r1.shape)
    print()
    print(col_r2, col_r2.shape)
    

    [ 2 6 10] (3,)

    [[ 2]
    [ 6]
    [10]] (3, 1)

    相关文章

      网友评论

          本文标题:图像识别相关Python与Numpy学习备忘

          本文链接:https://www.haomeiwen.com/subject/suhfwhtx.html