目录
4.Python Numpy教程(Python Numpy Tutorial)
1.查询网站
Anaconda的中文网:Anaconda 中文网
Anaconda 的英文网:Anaconda Documentation — Anaconda documentation
2.MKL Optimizations(MKL优化)
英特尔™ 数学内核库 (MKL) 专为科学、工程和金融计算而开发,是一组线程化和矢量化的数学例程,可用于加速各种数学函数和应用程序。Anaconda 已将一些最流行的数值/科学 Python 库的 MKL 驱动的二进制版本打包到 MKL 优化中,以提高性能。
MKL 优化包括:
- 速度提升的 NumPy、SciPy、scikit-learn 和 NumExpr
- MKL 与 Anaconda 中的可再发行二进制文件的打包,以便于访问 MKL 运行时库(runtime library)。
- Python 绑定到低级 MKL 服务函数,允许修改运行时使用的线程数(the number of threads)
Anaconda 版本从2.5开始,就默认自带MKL优化。可通过更新anaconda来获得支持。
conda update conda
conda update anaconda
MKL优化功能也可选择不使用。
3.创建虚拟环境
一般来说,下载pycharm以后,将pycharm与anaconda相结合可以很方便的创建虚拟环境。
下载python工程所需要的库:
# again, ensure your virtual env (either conda or venv)
# has been activated before running the commands below
cd assignment1 # cd to the assignment directory
# install assignment dependencies.
# since the virtual env is activated,
# this pip is associated with the
# python binary of the environment
pip install -r requirements.txt
4.Python Numpy教程(Python Numpy Tutorial)
① 数据类型
与大多数语言一样,Python有许多基本类型,包括整数、浮点、布尔和字符串。这些数据类型的行为方式与其他编程语言相似。
②布尔运算
在python中,逻辑运算(与、或、非)不再是符号表示。而是换成了英语表达:
t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
print(t and f) # Logical AND; prints "False"
print(t or f) # Logical OR; prints "True"
print(not t) # Logical NOT; prints "False"
print(t != f) # Logical XOR; prints "True"
③ container types
python 中包含许多内置容器类型,包括列表,字典,集合,元组;
Ⅰ列表
其中对于列表的访问以及列表赋值都是用‘[ ]’进行操作的。
其中无法改变的量有数字、字符、元组等
可以改变的量有列表、集合等
xs = [3, 1, 2] # Create a list
print(xs, xs[2]) # Prints "[3, 1, 2] 2"
print(xs[-1]) # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo' # Lists can contain elements of different types
print(xs) # Prints "[3, 1, 'foo']"
xs.append('bar') # Add a new element to the end of the list
print(xs) # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop() # Remove and return the last element of the list
print(x, xs) # Prints "bar [3, 1, 'foo']"
列表的创建
1.直接创建列表
listname = [element1 , element2 , element3 , ... , elementn]
2.创建空列表
emptylist = [ ]
3.list函数创建列表
Python 提供了一个内置的函数 list(),使用它可以将其它数据类型转换为列表类型
#将字符串转换成列表
list1 = list("hello")
print(list1)
#将元组转换成列表
tuple1 = ('Python', 'Java', 'C++', 'JavaScript')
list2 = list(tuple1)
print(list2)
#将字典转换成列表
dict1 = {'a':100, 'b':42, 'c':9}
list3 = list(dict1)
print(list3)
#将区间转换成列表
range1 = range(1, 6)
list4 = list(range1)
print(list4)
#创建空列表
print(list())
学习:列表推导式——
[expression for iter_val in iterable if cond_expr]
[expression if... else... for iter_val in iterable]
采用列表推导式时,列表甚至不用初始化。列表推导式的应用场景很多,一开始是用来对列表(list)来进行操作,后来开始对字典、集合等进行操作,出现了的字典推导式或集合推导式。
对列表进行操作
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
参考:List comprehension - 知乎 (zhihu.com)
Ⅱ 字典
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"
d['fish'] = 'wet' # Set an entry in a dictionary
print(d['fish']) # Prints "wet"
# print(d['monkey']) # KeyError: 'monkey' not a key of d
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"
del d['fish'] # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
对字典进行操作一般都是通过关键字来访问。字典的表达用的是大括号‘{ }’
对字典进行操作也有像列表一样的方法。
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
字典推导式(不熟)
将这
三个方法放在一起介绍,是因为它们都用来获取字典中的特定数据:
- keys() 方法用于返回字典中的所有键(key);
- values() 方法用于返回字典中所有键对应的值(value);
- items() 用于返回字典中所有的键值对(key-value)。
scores = {'数学': 95, '语文': 89, '英语': 90}
print(scores.keys())
print(scores.values())
print(scores.items())
输出:
dict_keys(['数学', '语文', '英语'])
dict_values([95, 89, 90])
dict_items([('数学', 95), ('语文', 89), ('英语', 90)])
参考:Python dict字典方法完全攻略(全) (biancheng.net)
Ⅲ 集合
集合是不同元素的无序集合
集合的创建:
Python 提供了 2 种创建 set 集合的方法,分别是使用 {} 创建和使用 set() 函数将列表、元组等类型数据转换为集合。
1.使用{}来创建
setname = {element1,element2,...,elementn}
2.set函数创建
set() 函数为 Python 的内置函数,其功能是将字符串、列表、元组、range 对象等可迭代对象转换成集合。
该函数的语法格式如下:
setname = set(iteration)
其中,iteration 就表示字符串、列表、元组、range 对象等数据。
set1 = set("c.biancheng.net")
set2 = set([1,2,3,4,5])
set3 = set((1,2,3,4,5))
print("set1:",set1)
print("set2:",set2)
print("set3:",set3)
Ⅳ 元组
元组是一个(不可变的)有序值列表。 元组在很多方面类似于列表; 最重要的区别之一是元组可以用作字典中的键和集合的元素,而列表则不能。
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)) # Prints "<class 'tuple'>"
print(d[t]) # Prints "5"
print(d[(1, 2)]) # Prints "1"
元组和列表(list)的不同之处在于:
- 列表的元素是可以更改的,包括修改元素值,删除和插入元素,所以列表是可变序列;
- 而元组一旦被创建,它的元素就不可更改了,所以元组是不可变序列。
列表(list)和元组(tuple)比较相似,它们都按顺序保存元素,所有的元素占用一块连续的内存,每个元素都有自己的索引,因此列表和元组的元素都可以通过索引(index)来访问
元组也可以看做是不可变的列表,通常情况下,元组用于保存无需修改的内容。
字典(dict)和集合(set)存储的数据都是无序的,每份元素占用不同的内存,其中字典元素以 key-value
的形式保存。
④ Class 类
Python 中定义一个类使用 class 关键字实现,其基本语法格式如下:
class 类名:
多个(≥0)类属性...
多个(≥0)类方法...
注意,无论是类属性还是类方法,对于类来说,它们都不是必需的,可以有也可以没有。另外,Python 类中属性和方法所在的位置是任意的,即它们之间并没有固定的前后次序。
其实,类属性指的就是包含在类中的变量;而类方法指的是包含类中的函数。换句话说,类属性和类方法其实分别是包含类中的变量和函数的别称。需要注意的一点是,同属一个类的所有类属性和类方法,要保持统一的缩进格式,通常统一缩进 4 个空格。
类方法也可以进行更细致的划分,具体可分为类方法、实例方法和静态方法。通常情况下,在类中定义的方法默认都是实例方法。实例方法最大的特点就是,它最少也要包含一个 self 参数,用于绑定调用此方法的实例对象(Python 会自动完成绑定)。实例方法通常会用类对象直接调用
class CLanguage:
#类构造方法,也属于实例方法
def __init__(self):
self.name = "C语言中文网"
self.add = "http://c.biancheng.net"
# 下面定义了一个say实例方法
def say(self):
print("正在调用 say() 实例方法")
clang = CLanguage()
clang.say()
在上面代码中,clang 变成了类对象,因此可以用类对象直接调用实例方法
clang = CLanguage()
CLanguage.say(clang)
当然,Python 也支持使用类名调用实例方法,但此方式需要手动给 self 参数传值。如上述代码所示。
参考:Python class:定义类(入门必读) (biancheng.net)
⑥ Numpy(数组)
Numpy 是 Python 科学计算的核心库。 它提供了一个高性能的多维数组对象,以及用于处理这些数组的工具。
Numpy 数组是值的网格,所有类型都相同,并由非负整数元组索引。 维数是数组的秩; 数组的形状是一个整数元组,给出了沿每个维度的数组大小。
我们可以从嵌套的 Python 列表初始化 numpy 数组,并使用方括号访问元素。(在实际操作中特别需要注意列表与数组之间的差异)。
xs = [3, 1, 2] # Create a list
import numpy as np
a = np.array([1, 2, 3]) # Create a rank 1 array
(仔细观察数组和列表之间的区别)
import numpy as np
a = np.array([1, 2, 3]) # Create a rank 1 array
print(type(a)) # Prints "<class 'numpy.ndarray'>"
print(a.shape) # Prints "(3,)"
print(a[0], a[1], a[2]) # Prints "1 2 3"
a[0] = 5 # Change an element of the array
print(a) # Prints "[5, 2, 3]"
b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
print(b.shape) # Prints "(2, 3)"
print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"
import numpy as np
a = np.zeros((2,2)) # Create an array of all zeros
print(a) # Prints "[[ 0. 0.]
# [ 0. 0.]]"
b = np.ones((1,2)) # Create an array of all ones
print(b) # Prints "[[ 1. 1.]]"
c = np.full((2,2), 7) # Create a constant array
print(c) # Prints "[[ 7. 7.]
# [ 7. 7.]]"
d = np.eye(2) # Create a 2x2 identity matrix
print(d) # Prints "[[ 1. 0.]
# [ 0. 1.]]"
e = np.random.random((2,2)) # Create an array filled with random values
print(e) # Might print "[[ 0.91940167 0.08143941]
# [ 0.68744134 0.87236687]]"
观察上述代码,二维数组的创建和访问是如何实现的。
python也提供了很多方法去实现数组索引
对二维数组进行取值
import numpy as np
HJL = np.array([
[1,2,3,4],
[4,5,6,7],
[7,8,9,10]
])
"""获取二维数组形状"""
print(HJL.shape) #(3, 4) ,3行4列
直接标明行索引和列索引,在一个方括号内,中间用逗号分隔。(先行索引再列索引,数组索引从0开始)
"""获取其中某一个值"""
print(HJL[1,0]) #4
"""获取其中某一行"""
print(HJL[1,:]) #[4 5 6 7]
"""获取某一行的其中几个"""
print(HJL[1,0:2]) #[4 5]
"""获取其中某几行"""
print(HJL[0:2,:]) #[[1 2 3 4],[4 5 6 7]]
参考:(34条消息) Python序列中元素的访问方式(三)Python.numpy数组元素的访问、切片与索引_THEAQING-CSDN博客
整数数组索引的一个有用技巧是从矩阵的每一行中选择或改变一个元素:
import numpy as np
a = np.array([[1,2], [3, 4], [5, 6]])
# An example of integer array indexing.
# The returned array will have shape (3,) and
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
# The above example of integer array indexing is equivalent to this:
print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]"
# When using integer array indexing, you can reuse the same
# element from the source array:
print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
# Equivalent to the previous integer array indexing example
print(np.array([a[0, 1], a[0, 1]])) # Prints "[2 2]"
import numpy as np
# Create a new array from which we will select elements
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(a) # prints "array([[ 1, 2, 3],
# [ 4, 5, 6],
# [ 7, 8, 9],
# [10, 11, 12]])"
# Create an array of indices
b = np.array([0, 2, 0, 1])
# Select one element from each row of a using the indices in b
print(a[np.arange(4), b]) # Prints "[ 1 6 7 11]"
# Mutate one element from each row of a using the indices in b
a[np.arange(4), b] += 10
print(a) # prints "array([[11, 2, 3],
# [ 4, 5, 16],
# [17, 8, 9],
# [10, 21, 12]])
我们使用布尔数组索引来构造一个秩为 1 的数组,该数组由与 bool_idx 的 True 值对应的 a 的元素组成:
import numpy as np
a = np.array([[1,2], [3, 4], [5, 6]])
bool_idx = (a > 2) # Find the elements of a that are bigger than 2;
# this returns a numpy array of Booleans of the same
# shape as a, where each slot of bool_idx tells
# whether that element of a is > 2.
print(bool_idx) # Prints "[[False False]
# [ True True]
# [ True True]]"
# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
print(a[bool_idx]) # Prints "[3 4 5 6]"
# We can do all of the above in a single concise statement:
print(a[a > 2]) # Prints "[3 4 5 6]"
每个 numpy 数组都是相同类型元素的网格。 Numpy 提供了大量可用于构造数组的数值数据类型。 Numpy 在创建数组时会尝试猜测数据类型,但构造数组的函数通常还包含一个可选参数来显式指定数据类型。
import numpy as np
x = np.array([1, 2]) # Let numpy choose the datatype
print(x.dtype) # Prints "int64"
x = np.array([1.0, 2.0]) # Let numpy choose the datatype
print(x.dtype) # Prints "float64"
x = np.array([1, 2], dtype=np.int64) # Force a particular datatype
print(x.dtype)
矩阵元素计算
import numpy as np
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
# Elementwise sum; both produce the array
# [[ 6.0 8.0]
# [10.0 12.0]]
print(x + y)
print(np.add(x, y))
# Elementwise difference; both produce the array
# [[-4.0 -4.0]
# [-4.0 -4.0]]
print(x - y)
print(np.subtract(x, y))
# Elementwise product; both produce the array
# [[ 5.0 12.0]
# [21.0 32.0]]
print(x * y)
print(np.multiply(x, y))
# Elementwise division; both produce the array
# [[ 0.2 0.33333333]
# [ 0.42857143 0.5 ]]
print(x / y)
print(np.divide(x, y))
# Elementwise square root; produces the array
# [[ 1. 1.41421356]
# [ 1.73205081 2. ]]
print(np.sqrt(x))
矩阵求解向量积
请注意,与 MATLAB 不同的是,* 是元素乘法,而不是矩阵乘法。 我们改为使用 dot 函数来计算向量的内积,将向量乘以矩阵,以及将矩阵相乘。
import numpy as np
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11, 12])
# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))
# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
# [43 50]]
print(x.dot(y))
print(np.dot(x, y))
Broadcasting(广播)
小数组和大数组进行运算
import numpy as np
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
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]]"
⑦ SciPy说明
Image operations
from scipy.misc import imread, imsave, imresize
# Read an JPEG image into a numpy array
img = imread('assets/cat.jpg')
print(img.dtype, img.shape) # Prints "uint8 (400, 248, 3)"
# We can tint the image by scaling each of the color channels
# by a different scalar constant. The image has shape (400, 248, 3);
# we multiply it by the array [1, 0.95, 0.9] of shape (3,);
# numpy broadcasting means that this leaves the red channel unchanged,
# and multiplies the green and blue channels by 0.95 and 0.9
# respectively.
img_tinted = img * [1, 0.95, 0.9]
# Resize the tinted image to be 300 by 300 pixels.
img_tinted = imresize(img_tinted, (300, 300))
# Write the tinted image back to disk
imsave('assets/cat_tinted.jpg', img_tinted)
Distance between points
Scipy定义了一些函数用来计算点集之间的距离。
函数scipy.spatial.distance.pdist计算给定集中所有点对之间的距离。
import numpy as np
from scipy.spatial.distance import pdist, squareform
# Create the following array where each row is a point in 2D space:
# [[0 1]
# [1 0]
# [2 0]]
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)
# Compute the Euclidean distance between all rows of x.
# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],
# and d is the following array:
# [[ 0. 1.41421356 2.23606798]
# [ 1.41421356 0. 1. ]
# [ 2.23606798 1. 0. ]]
d = squareform(pdist(x, 'euclidean'))
print(d)
⑧ Matplotlib
Matplotlib是一个打印库。本节简要介绍matplotlib.pyplot模块,该模块提供了一个类似于MATLAB的绘图系统。
import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
# Plot the points using matplotlib
plt.plot(x, y)
plt.show() # You must call plt.show() to make graphics appear.
您可以使用subplot函数在同一图形中绘制不同的内容。以下是一个例子:
import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)
# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')
# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')
# Show the figure.
plt.show()
您可以使用imshow功能显示图像。以下是一个例子:
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]
# Show the original image
plt.subplot(1, 2, 1)
plt.imshow(img)
# Show the tinted image
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()