# -*- coding: utf-8 -*-
"""
主要記錄代碼,相關說明采用注釋形勢,供日常總結、查閱使用,不定時更新。
Created on Fri Aug 24 19:57:53 2018
@author: Dev
"""
import numpy as np
import random
# 常用函數
arr = np.arange(10)
print(np.sqrt(arr)) # 求平方根
print(np.exp(arr)) # 求e的次方
random.seed(200) # 設置隨機種子
x = np.random.normal(size=(8, 8))
y = np.random.normal(size=(8, 8))
np.maximum(x, y) # 每一位上的最大值
arr = np.random.normal(size=(2, 4)) * 5
print(arr)
print(np.modf(arr)) # 將小數部分與整數部分分成兩個單獨的數組
# 向量化操作
# meshgrid的基本用法
points1 = np.arange(-5, 5, 1) # [-5, 5]閉區間步長為1的10個點
points2 = np.arange(-4, 4, 1)
xs, ys = np.meshgrid(points1, points2) # 返回一個由xs, ys構成的坐標矩陣
print(xs) # points1作為行向量的len(points1) * len(points2)的矩陣
print(ys) # points2作為列向量的len(points1) * len(points2)的矩陣
# 將坐標矩陣經過計算后生成灰度圖
import matplotlib.pyplot as plt
points = np.arange(-5, 5, 0.01) # 生成1000個點的數組
xs, ys = np.meshgrid(points, points)
z = np.sqrt(xs ** 2 + ys ** 2) # 計算矩陣的平方和開根
print(z)
plt.imshow(z, cmap=plt.cm.gray)
plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
plt.show()

# 將條件邏輯表達為數組運算
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])
# 純Python,用列表解析式做判斷
result = [x if c else y for x, y, c in zip(xarr, yarr, cond)]
# zip()基本用法
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
for tupple_a in zip(a, b, c): # python 3.x為了減少內存占用,每次zip()調用只返回一個元組對象
print(tupple_a)
# np.where()
result = np.where(cond, xarr, yarr)
# np.where()的用法:

#np.where()的幾個例子
# condition, x, y均指定
np.where([[False, True], [True, False]],
[[1, 2], [3, 4]],
[[9, 8], [7, 6]])
# 只指定condition時,返回np.nonzero(),即非零元素的索引
x = np.arange(9.).reshape(3, 3)
np.where( x > 5 )
x[np.where( x > 3.0 )] # 將索引值帶入原數組,得到滿足大於3條件的元素
arr = np.random.normal(size=(4,4))
print(arr)
np.where(arr > 0, 2, -2)
np.where(arr > 0, 2, arr) # 只將大於0的元素設置為2
# 用np.where()進行多條件判斷
# 例子: 對0~100范圍內的數進行判斷
# 純python
sum1 = 0
for i in range(0, 100):
if np.sqrt(i) > 3 and np.sqrt(i) < 5: # 平方根在(3, 5)之間
sum1 += 3
elif np.sqrt(i) > 3: # 平方根在[5, 10)之間
sum1 += 2
elif np.sqrt(i) < 5: # 平方根在(0, 3]之間
sum1 += 1
else:
sum1 -= 1
print(sum1)
注: 這個例子其實用的不好,最后一個sum -= 1實際上沒有用到,只是用這個例子說明多條件判斷。
# 使用np.where()
num_list = np.arange(0, 100)
cond1 = np.sqrt(num_list) > 3
cond2 = np.sqrt(num_list) < 5
result = np.where(cond1 & cond2, 3, np.where(cond1, 2, np.where(cond2 < 5, 1, -1)))
print(sum(result))
# 數學與統計方法
arr = np.random.normal(size=(5, 4))
arr.mean() # 平均值
np.mean(arr)
arr.sum() # 求和
arr.mean(axis=1) # 對行求平均值
arr.sum(0) # 對每列求和
arr.sum(axis=0)
arr = np.arange(9).reshape(3, 3)
arr.cumsum(0) # 每列的累計和
arr.cumprod(1) # 每行的累計積
注: 關於numpy中axis的問題
axis=1可理解為跨列操作
axis=0可理解為跨行操作
# 布爾型數組
arr = np.random.normal(size=(10, 10))
(arr > 0).sum() # 正值的數量
bools = np.array([False, False, True, False])
bools.any() # 有一個為True,則結果為True
bools.all() # 必須全為True,結果才為True
# 排序
arr = np.random.normal(size=(4, 4))
print(arr)
arr.sort() # 對每行元素進行排序
arr = np.random.normal(size=(5, 3))
print(arr)
arr.sort(0) # 對每列元素進行排序
# 求25%分位數(排序后根據索引位置求得)
num_arr = np.random.normal(size=(1000, 1000))
num_arr.sort()
print(num_arr[0, int(0.25 * len(num_arr))])
# 求唯一值
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
print(np.unique(names))
# 純Python
print(sorted(set(names)))
# 判斷values中的列表元素是否在數組list_a中
arr_a = np.array([6, 0, 0, 3, 2, 5, 6])
values = [2, 3, 6]
np.in1d(arr_a, values)
# 線性代數相關的函數
x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
x.dot(y) # 矩陣的乘法
np.dot(x, y)
np.dot(x, np.ones(3))
np.random.seed(12345)
from numpy.linalg import inv, qr
X = np.random.normal(size=(5, 5))
mat = X.T.dot(X) # 矩陣X轉置后再與原X相乘
inv(mat) # 求逆矩陣
mat.dot(inv(mat)) # 與逆矩陣相乘
# 隨機數
samples = np.random.normal(size=(4, 4))
samples
from random import normalvariate
# normalvariate(mu,sigma)
# mu: 均值
# sigma: 標准差
# mu = 0, sigma=1: 標准正態分布
# 比較純Python與numpy生成指定數量的隨機數的速度
N = 1000000 # 設置隨機數的數量
get_ipython().magic(u'timeit samples = [normalvariate(0, 1) for _ in range(N)]')
get_ipython().magic(u'timeit np.random.normal(size=N)')
結果:
818 ms ± 9.87 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
34.5 ms ± 164 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 范例:隨機漫步
import random
# 純Python
position = 0
walk = [position]
steps = 1000
for i in range(steps):
step = 1 if random.randint(0, 1) else -1
position += step
walk.append(position)
# np
np.random.seed(12345)
nsteps = 1000
draws = np.random.randint(0, 2, size=nsteps) # 取不到2
steps = np.where(draws > 0, 1, -1)
walk = steps.cumsum() # 求累計和
walk.min()
walk.max()
(np.abs(walk) >= 10).argmax() # 首次到達10的索引數
# 一次模擬多個隨機漫步
nwalks = 5000 # 一次生成5000組漫步數據
nsteps = 1000
draws = np.random.randint(0, 2, size=(nwalks, nsteps))
steps = np.where(draws > 0, 1, -1)
walks = steps.cumsum(1) # 將5000個樣本中每一步的值進行累積求和
print(walks)
# 計算首次到達30
hits30 = (np.abs(walks) >= 30).any(1) # 在列方向上進行對比
print(hits30)
print(hits30.sum()) # 到達+/-30的個數
# 查看每一步中首次到達30的步數
crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)
# 求到達30的平均步數
crossing_times.mean()
# 標准正態分布
steps = np.random.normal(loc=0, scale=0.25, size=(nwalks, nsteps))