Python

Installation

Python3.6

For ubuntu 16.04

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6

Notice 特别注意点

数组相乘与点乘积的区别

A* B # element wise product

>>> import numpy as np
>>> A = np.array([[1, 2], [3, 4]])
>>> B = np.array([[3, 0], [0, 6]])
>>> A* B # element wise product
array([[ 3,  0],
       [ 0, 24]])
>>> np.dot(A, B)
array([[ 3, 12],
       [ 9, 24]])

How to

How to know PyTorch Version

import torch
print(torch.__version__)

How to add dimention to array

np.newaxis

怎样判断两个矩阵相等?

这个例子是判断一个矩阵是否为正交矩阵:

def check_orthogonal(M):
    # make sure the input is a matrix
    if len(np.shape(M)) !=2:
        print("error: input is not a matrix")
        return
    # make sure the input is not a square matrix
    dim = np.shape(M)[0]
    if dim != np.shape(M)[1]:
        print("error: input is not a square matrix")
        return
    A = np.dot(M, M.T)
    #  if np.array_equal(A, np.identity(dim)):
    [rows, cols] = A.shape
    I = np.identity(dim)
    for i in range(rows):
        for j in range(cols):
            if not (A[i, j] - I[i, j] <= 10e-3):
                print("matrix is not orthogonal")
                return
    print("matrix is orthogonal")

#  Verify check_orthogonal function
D = 1./3. * np.array(
    [[2, 2, -1],
     [2, -1, 2],
     [-1, 2, 2]])
check_orthogonal(D)

如何反序遍历

长空飞鸟 -CSDN

1 . for x in reversed(array):
           print x
2. for x in range(len(array)-1,-1,-1):
           print array[x]
3. for x in array[::-1]:
           print x

Example:
Input:
p: input list
U: the number to move
在这里插入图片描述

如何遍历数组

Refer How to loop with indexes in Python这篇文章详细讲解了如何 遍历单个数组与同时遍历多个数组

方法一:

var colors = ["red", "green", "blue", "purple"];
for (var i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}

方法二:while

colors = ["red", "green", "blue", "purple"]
i = 0
while i < len(colors):
    print(colors[i])
    i += 1

方法三: Range of length

colors = ["red", "green", "blue", "purple"]
for i in range(len(colors)):
    print(colors[i])

方法四: for in 最常用的方法

colors = ["red", "green", "blue", "purple"]
for color in colors:
    print(color)

方法五:enumerate
Python’s built-in enumerate function allows us to loop over a list and retrieve both the index and the value of each item in the list:

presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson"]
for num, name in enumerate(presidents, start=1):
    print("President {}: {}".format(num, name))

如何同时遍历多个数组

What if we need to loop over multiple things?
Often when we use list indexes, it’s to look something up in another list.

enumerate
For example, here we’re looping over two lists at the same time using indexes to look up corresponding elements:

colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for i, color in enumerate(colors):
    ratio = ratios[i]
    print("{}% {}".format(ratio * 100, color))

zip
We don’t actually care about the index when looping here. Our real goal is to loop over two lists at once. This need is common enough that there’s a special built-in function just for this.

Python’s zip function allows us to loop over multiple lists at the same time:

colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for color, ratio in zip(colors, ratios):
    print("{}% {}".format(ratio * 100, color))

Common used

Header template

#!/usr/bin/env python
import sys, os
sys.path.append(os.pardir)
import numpy as np
import matplotlib.pyplot as plt

main

if __name__ == '__main__' :

Notation

多行注释:
“”"
多行
“”"

Add import directory

import sys, os
sys.path.append(os.pardir)
sys.path.append('../include/color_pcl_generator')

argmax

    a = np.array([[1, 5, 5, 2],
              [9, 6, 2, 8],
              [3, 7, 9, 1]])
    print("axis = 0: ", np.argmax(a, axis=0))

    a = np.array([[1, 5, 5, 2],
              [9, 6, 2, 8],
              [3, 7, 9, 1]])
    print("axis=1: ", np.argmax(a, axis=1))

Result:

axis = 0: [1 2 2 1]
axis=1: [1 0 2]

arange

numpy.arange
numpy.arange([start, ]stop, [step, ]dtype=None) [start, stop)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.

>>> range (0, 5)
[0, 1, 2, 3, 4]
>>> range(5)
[0, 1, 2, 3, 4]
>>> c = [i for i in range(5)]
>>> c
[0, 1, 2, 3, 4]

numpy.linspace

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)[source]
Return evenly spaced numbers over a specified interval.

Returns num evenly spaced samples, calculated over the interval [start, stop].
The endpoint of the interval can optionally be excluded.

nditer

flags=[‘multi_index’]表示对a进行多重索引
“multi_index” causes a multi-index, or a tuple of indices with one per iteration dimension, to be tracked.

对于这种迭代方式需要注意的是:所选择的顺序是和数组内存布局一致的,而不是使用标准C或者Fortran顺序。a和a.T的遍历顺序是一样的,也就是他们在内存中的存储顺序也是一样的.

>>> it = np.nditer(a, flags=['multi_index'])
>>> while not it.finished:
...     print "%d <%s>" % (it[0], it.multi_index),
...     it.iternext()
...
0 <(0, 0)> 1 <(0, 1)> 2 <(0, 2)> 3 <(1, 0)> 4 <(1, 1)> 5 <(1, 2)>

Matrix

array_equal

numpy.array_equal(a1, a2)
True if two arrays have the same shape and elements, False otherwise.
但是由于符点数的表示,元素不可能绝对相等,因此这个函数要慎用。

Plot

Pyplot tutorial for plot

Example

In the same python script write commands which plot the graph of the function
f in the interval [−2π, 2π]. Save the resulting plot as a PNG-file to your hard disk.

import matplotlib.pyplot as plt
def myfunc( x ):
   out = np.cos(x) * np.exp(x)
   return out
#plot function
# create vector for x
x = np.linspace(-2*np.pi, 2*np.pi, 100, endpoint=True);
print x
# call the function
y = myfunc(x);
#plot the data
plt.plot(x, y)
plt.grid()
plt.ylabel('cos(x) * exp(x)')
plt.title("f(x) = cos(x)exp(x)")
plt.legend()
plt.xlabel('x')
#store image
plt.savefig('myfunc.png')
plt.show()

Output:
在这里插入图片描述


Sampling

random.seed

fix random seed
np.random.seed(123)

randn

numpy.random.randn(d0, d1, ..., dn)
Return a sample (or samples) from the “standard normal” distribution.
For random samples from N ( μ , σ 2 ) N(\mu, \sigma^2) N(μ,σ2), use:

sigma * np.random.randn(...) + mu

normal distrubution

numpy.random.normal(loc=0.0, scale=1.0, size=None)

Example:
Create a vector with 100000 random variables which are normally distributed
with a mean of 5.0 and a standard deviation of 2.0.

mu, sigma = 5.0, 2.0
normal_vector = np.random.normal(mu, sigma, 100000)
plt.figure()
count, bins, ignored= plt.hist(normal_vector, 100, density=True)
plt.plot(bins, 1/(sigma*np.sqrt(2*np.pi))*
          np.exp(-(bins-mu)**2/(2*sigma**2) ),
          linewidth=2, color='r' )

plt.show()

uniform distribution

Create a vector with 100000 uniformly distributed random variables between
0 and 10.

numpy.random.uniform(low=0.0, high=1.0, size=None)

Example:

uniform_vector = np.random.uniform(0, 10, 100000)
plt.figure()
count, bins, ignored = plt.hist(uniform_vector, 100, density=True)
plt.plot(bins, np.ones_like(bins)*0.1, linewidth=2, color='r')

在这里插入图片描述
if Density=False:
在这里插入图片描述

rand

numpy.random.rand(d0, d1, ..., dn)
Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

mean and std. dev.

print np.mean(normal_vector), np.std(normal_vector)
print np.mean(uniform_vector), np.std(uniform_vector)

numpy.random.permutation

Randomly permute a sequence, or return a permuted range.

>>> import numpy as np
>>> np.random.permutation(10)
array([9, 1, 6, 2, 3, 7, 4, 0, 8, 5])
>>> np.random.permutation([1, 5, 9, 12, 12])
array([12,  5,  1,  9, 12])
>>> arr = np.arange(9).reshape(3, 3)
>>> np.random.permutation(arr)
array([[6, 7, 8],
       [0, 1, 2],
       [3, 4, 5]])
>>>


Python2

Compitable with Python3

from __future__ import print_function
from __future__ import division

Modules

Scipy

Scipy Lecture Notes
SciPy Tutorial-tutorialspoint
Python SciPy Tutorial: Learn with Example

scipy is composed of task-specific sub-modules:

scipy.cluster	Vector quantization / Kmeans
scipy.constants	Physical and mathematical constants
scipy.fftpack	Fourier transform
scipy.integrate	Integration routines
scipy.interpolate	Interpolation
scipy.io	Data input and output
scipy.linalg	Linear algebra routines
scipy.ndimage	n-dimensional image package
scipy.odr	Orthogonal distance regression
scipy.optimize	Optimization
scipy.signal	Signal processing
scipy.sparse	Sparse matrices
scipy.spatial	Spatial data structures and algorithms
scipy.special	Any special mathematical functions
scipy.stats	Statistics

glob.glob

import glob  

Reference

  1. Introduction to Mobile Robotics - SS 2017
  2. rand, randn
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值