1-CS231n

CS231nのPython

大致扫一眼笔记,这节主要是大致介绍一下python语言及其一些高效的库——numpy scipy matplotlib

python

python是一种高级的、动态类型的多范型编程语言
eg.python实现quicksort快速排序算法的简洁过程:

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) / 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)

关于快速排序,是对冒泡排序的一种改进算法:
1.在数组中选一个基准数
2.将数组中小于基准数的数据移到基准数左边,大于基准数的移到右边
3.对于基准数左右两边的数组,不断重复以上两个过程,直到每个子集只有一个元素,即为全部有序

基本数据类型

数字:整型和浮点型的使用与其他语言类似,但是需要注意的是,python中没有x++和x- -的操作符
布尔型:通过英语实现所有的布尔逻辑
字符串:类型多样,这里不再赘述

Containers 容器/复合数据类型

列表:即python 中数组,但列表长度可变,且能包含不同类型的元素
切片:可以一次性获取列表中的元素
循环:可以遍历列表中的每一个元素

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

运行结果
如果想要在循环体内访问每个元素的指针,可以使用内置的enumerate函数
列表推导List comprehensions:可以将一种数据类型转换为另一种

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

运行结果
字典:存储键、值,和Java中map差不多
集合sets:独立不同个体的无序集合
元组tuples:一个值的有序列表(不可改变),很多情况下与列表相似,但是不同之处在于元组可以在 字典中用作键,还可以作为集合的元素,而列表不行
函数:用def来定义函数
类:

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

主要与数组相关,每个numpy数组都是数据类似相同的元素组成的网格,提供了很多的数据类型用于创建数组及提供了很多计算数组的函数,其中最常用的是sum
需要注意的是,*是元素逐个相乘,dot用于矩阵乘法
总的来说,Numpy提供了高性能的多维数组,以及计算和操作数组的基本工具

Scipy

Scipy基于numpy,提供了大量的计算和操作数组的函数
eg.提供了一些操作图像的基本函数,还定义了一些有用的函数,可以计算集合中点之间的距离

matplotlib

一个功能强大的绘图工具,也可以用于显示图像

import numpy as np from scipy.misc import imread, imresize import
matplotlib.pyplot as plt

img = imread(‘assets/cat.jpg’) img_tinted = img * [1, 0.95, 0.9]

plt.subplot(1, 2, 1) plt.imshow(img)

plt.subplot(1, 2, 2)# A slight gotcha with imshow is that it might
give strange results# if presented with data that is not uint8. To
work around this, we# explicitly cast the image to uint8 before
displaying it. plt.imshow(np.uint8(img_tinted)) plt.show()

猜你喜欢

转载自blog.csdn.net/weixin_50291934/article/details/113756911