Notes on Python

基于CS231n的课程笔记

这是一个基于Stanford CS231n课程笔记的小总结,主要以简明的文字叙述和Python代码呈现。
鸣谢文章笔记来源 知乎

Containers 容器

这里侧重于看最简单的Lists列表,Dictionary字典,Set集等不在此处详述。
Slicing 切片

nums = 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]"

List comprehensions 列表推导

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print squares   # Prints [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  # Prints "[0, 4, 16]"
Functions 函数
def hello(name, loud=False):
    if loud:
        print 'HELLO, %s' % name.upper()
    else:
        print 'Hello, %s!' % name

hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True)  # Prints "HELLO, FRED!"
Classes 类
class Greeter(object):

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # Instance method
    def greet(self, loud=False):
        if loud:
            print 'HELLO, %s!' % self.name.upper()
        else:
            print 'Hello, %s' % 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!"
Numpy 数值计算扩展

本章节主要以Arrays 数组为主要介绍对象。

产生

p = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array
a = np.zeros((2,2))  # Create an array of all zeros
b = np.ones((1,2))   # Create an array of all ones
c = np.full((2,2), 7) # Create a constant array
d = np.eye(2)        # Create a 2x2 identity matrix
e = np.random.random((2,2)) # Create an array filled with random values
y = np.empty_like(x)   # Create an empty matrix with the same shape as x

Slicing 切片
(值得一提的是,切片往往边界范围是左闭右开的)

import numpy as np

# Create the following rank 2 array with shape (3, 4)
# [[ 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]])

# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
#  [6 7]]
b = a[:2, 1:3]

# A slice of an array is a view into the same data, so modifying it
# will modify the original array.
print a[0, 1]   # Prints "2"
b[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]
print a[0, 1]   # Prints "77"

访问
访问整型数组时可以使用整型访问或者切片访问,区别在产出的维度上,详见下例:

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
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
print row_r1, row_r1.shape  # Prints "[5 6 7 8] (4,)"
print row_r2, row_r2.shape  # Prints "[[5 6 7 8]] (1, 4)"

访问布尔型可以加条件,如下例:

a = np.array([[1,2], [3, 4], [5, 6]])

bool_idx = (a > 2) 
print bool_idx      # Prints "[[False False]
                    #          [ True  True]
                    #          [ True  True]]"
print a[bool_idx]  # Prints "[3 4 5 6]"
print a[a > 2]     # Prints "[3 4 5 6]"

计算
基本运算符只对相同规模的数组的对应元素进行四则运算。
矩阵乘法:在此需要使用点乘运算np.dot(A,B)
求和运算:np.sum(A) 指所有元素相加;np.sum(x,axis=id)指在id轴(即跨第id维度)求算结果,axis=0即为求各列的和,axis=1即为求各行的和。
转置运算:A.T

Broadcasting 广播机制
推荐在数值计算时使用能使得代码运行更迅速的广播机制。

x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using broadcasting
print y  # Prints "[[ 2  2  4]
         #          [ 5  5  7]
         #          [ 8  8 10]
         #          [11 11 13]]"

图像操作
基操和C++CV库的相似。
图像读入:imread(‘filepath/filename’)
图像通道值放缩变色:Python支持图片像素三通道数值直接按比例放缩,顺序与C++ OpenCV库的BGR不同,是比较普遍的RGB。
图像尺寸放缩:imresize(img,(row,col))
图像显示:imread(img)

Matplotlib
最常用的是matplotlib.pyplot模块。
2D绘图:plt.plot(x,y),可叠加画图,在最后面加一句plt.show()来显现。
横纵轴标签:plt.xlabel(‘x axis label’) plt.ylabel(‘y axis label’)
标题:plt.title(‘Sine and Cosine’)
系列标签:plt.legend([‘Sine’, ‘Cosine’])
多图输出:plt.subplot(width,height, id)

更于2019.7.30


听说贴Nabi的图片可以脱单?(逃~)
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值