生成数组和矩阵
数组和矩阵 切片方法
reshape
类型转换
等差数列
等比数列
分布数组
画图方法
线图
柱状图
函数图 心形图 等
绘制三维图
插值方法
scipy 求极值函数
a = np.arange(0, 60, 10).reshape((-1, 1)) + np.arange(6)
print (a)
[[ 0 1 2 3 4 5]
[10 11 12 13 14 15]
[20 21 22 23 24 25]
[30 31 32 33 34 35]
L = [1, 2, 3, 4, 5, 6]
print ("L = ", L)
L = [1, 2, 3, 4, 5, 6]
# 通过array函数传递list对象
L = [1, 2, 3, 4, 5, 6]
# print ("L = ", L)
a = np.array(L)
print ("a = ", a)
print (type(a))
# # # 若传递的是多层嵌套的list,将创建多维数组
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print (b)
# # #
# # # # 数组大小可以通过其shape属性获得
print (a.shape)
print (b.shape)
a = [1 2 3 4 5 6]
<class 'numpy.ndarray'>
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(6,)
(3, 4)
# b.shape = 4, 3# b.shape = 2,-1行 多列
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print (b)
c = b.reshape((4, -1))
print ("b = \n", b)
print ('c = \n', c)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
b =
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
c =
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
print (b.dtype)
d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.float)
f = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.complex)
print (d)
print (f)
[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
[[ 1.+0.j 2.+0.j 3.+0.j 4.+0.j]
[ 5.+0.j 6.+0.j 7.+0.j 8.+0.j]
[ 9.+0.j 10.+0.j 11.+0.j 12.+0.j]]
转换类型
f = d.astype(np.int)
b=np.arange(1,10,0.5)
print (b)
# 如果生成一定规则的数据,可以使用NumPy提供的专门函数
# arange函数类似于python的range函数:指定起始值、终止值和步长来创建数组
# 和Python的range类似,arange同样不包括终值;但arange可以生成浮点类型,而range只能是整数类型
a = np.arange(1, 10, 0.5)
print (a)
[1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. 5.5 6. 6.5 7. 7.5 8. 8.5 9. 9.5]
# # # linspace函数通过指定起始值、终止值和元素个数来创建数组,缺省包括终止值
# b = np.linspace(1, 10, 10)
b = [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
# # 可以通过endpoint关键字指定是否包括终值
# c = np.linspace(1, 10, 10, endpoint=False)
logspace可以创建等比数列
# # 下面函数创建起始值为10^1,终止值为10^2,有20个数的等比数列
# d = np.logspace(1, 2, 10, endpoint=True)
# print d
# # # 下面创建起始值为2^0,终止值为2^10(包括),有10个数的等比数列
# f = np.logspace(0, 10, 11, endpoint=True, base=2)
# print f
[python] view plain copy
- <code class="language-python"> # # # 使用 frombuffer, fromstring, fromfile等函数可以从字节序列创建数组
- # s = 'abcd'
- # g = np.fromstring(s, dtype=np.int8)
- # print g</code>
[ 97 98 99 100]
数组取值
# a = np.arange(10)
# print a
# # # 获取某个元素
# print a[3]
# # # # 切片[3,6),左闭右开
# print a[3:6]
# # # # 省略开始下标,表示从0开始
# print a[:5]
# # # # 下标为负表示从后向前数
# print a[3:]
# # # # 步长为2
# print a[1:9:2]
# # # # 步长为-1,即翻转
# print a[::-1]
# # # # 切片数据是原数组的一个视图,与原数组共享内容空间,可以直接修改元素值
# a[1:4] = 10, 20, 30
# print a
# # # # 因此,在实践中,切实注意原始数据是否被破坏,如:
# b = a[2:5]
# b[0] = 200
# print a
更改了a的值
a = np.logspace(0, 9, 10, base=2)
print (a)
i = np.arange(0, 10, 2)
print (i)
# # # # 利用i取a中的元素
b = a
print (b)
# # # b的元素更改,a中元素不受影响
b[2] = 1.6
print (b)
print (a)
等比 [ 1. 2. 4. 8. 16. 32. 64. 128. 256. 512.]
等差
[0 2 4 6 8] 提取数组
[ 1. 4. 16. 64. 256.] 更改
[ 1. 4. 1.6 64. 256. ]
[ 1. 2. 4. 8. 16. 32. 64. 128. 256. 512.]
# 使用布尔数组i作为下标存取数组a中的元素:返回数组a中所有在数组b中对应下标为True的元素
# # 生成10个满足[0,1)中均匀分布的随机数
a = np.random.rand(10)
print (a)
# # # 大于0.5的元素索引
print (a > 0.5)
# # # # 大于0.5的元素
b = a[a > 0.5]
print (b)
# # # # 将原数组中大于0.5的元素截取成0.5
a[a > 0.5] = 0.5
print (a)
# # # # b不受影响
print (b)
大于0.5 赋给新值
[0.58580625 0.95061009 0.82539452 0.01199016 0.30635077 0.11879863
0.94065007 0.51743287 0.96030271 0.88039496]
[ True True True False False False True True True True]
[0.58580625 0.95061009 0.82539452 0.94065007 0.51743287 0.96030271
0.88039496]
[0.5 0.5 0.5 0.01199016 0.30635077 0.11879863
0.5 0.5 0.5 0.5 ]
[0.58580625 0.95061009 0.82539452 0.94065007 0.51743287 0.96030271
0.88039496]
数组切片
# # 合并上述代码:
a = np.arange(0, 60, 10).reshape((-1, 1)) + np.arange(6)
print (a)
# # 二维数组的切片
print (a[(0,1,2,3), (2,3,4,5)])
print (a[3:, [0, 2, 5]])
i = np.array([True, False, True, False, False, True])
print (a)
print (a[i, 3])
[[ 0 1 2 3 4 5]
[10 11 12 13 14 15]
[20 21 22 23 24 25]
[30 31 32 33 34 35]
[40 41 42 43 44 45]
[50 51 52 53 54 55]]
[ 2 13 24 35]
[[30 32 35]
[40 42 45]
[50 52 55]]
0 2 5 行
[[ 0 1 2 3 4 5]
[20 21 22 23 24 25]
[50 51 52 53 54 55]] 3列
[ 3 23 53]
matplotlib.rcParams['font.sans-serif'] = [u'SimHei'] #FangSong/黑体 FangSong/KaiTimatplotlib.rcParams['axes.unicode_minus'] = False # 不处理负号mu = 0sigma = 1x = np.linspace(mu - 3 * sigma, mu + 3 * sigma, 50)y = np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / (math.sqrt(2 * math.pi) * sigma)# print x.shape# print 'x = \n', x# print y.shape# print 'y = \n', yplt.plot(x, y, 'ro-', linewidth=2)plt.plot(x, y, 'r-', x, y, 'go', linewidth=2, markersize=8)plt.grid(True)plt.title(u'Guass分布')plt.show()画图 guass 分布
matplotlib.rcParams['font.sans-serif'] = [u'SimHei'] #FangSong/黑体 FangSong/KaiTi
matplotlib.rcParams['axes.unicode_minus'] = False # 不处理负号
mu = 0
sigma = 1
x = np.linspace(mu - 3 * sigma, mu + 3 * sigma, 50)
y = np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / (math.sqrt(2 * math.pi) * sigma)
# print x.shape
# print 'x = \n', x
# print y.shape
# print 'y = \n', y
plt.plot(x, y, 'ro-', linewidth=2)
plt.plot(x, y, 'r-', x, y, 'go', linewidth=2, markersize=8)
plt.grid(True)
plt.title(u'Guass分布')
plt.show()
# 5.2 损失函数:Logistic损失(-1,1)/SVM Hinge损失/ 0/1损失
x = np.array(np.linspace(start=-2, stop=3, num=1001, dtype=np.float))
y_logit = np.log(1 + np.exp(-x)) / math.log(2)
y_boost = np.exp(-x)
y_01 = x < 0
y_hinge = 1.0 - x
y_hinge[y_hinge < 0] = 0
plt.plot(x, y_logit, 'r-', label='Logistic Loss', linewidth=2)
plt.plot(x, y_01, 'g-', label='0/1 Loss', linewidth=2)
plt.plot(x, y_hinge, 'b-', label='Hinge Loss', linewidth=2)
plt.plot(x, y_boost, 'm--', label='Adaboost Loss', linewidth=2)
plt.grid()
plt.legend(loc='upper right')
# plt.savefig('1.png')
plt.show()
# x ** x x > 0
# (-x) ** (-x) x < 0def f(x): y = np.ones_like(x) i = x > 0 y = np.power(x, x) i = x < 0 y = np.power(-x, -x) return y
x = np.linspace(-1.3, 1.3, 101)
y = f(x)
plt.plot(x, y, 'g-', label='x^x', linewidth=2)
plt.grid()
plt.legend(loc='upper left')
plt.show()
# # 5.4 胸型线
x = np.arange(1, 0, -0.001)
y = (-3 * x * np.log(x) + np.exp(-(40 * (x - 1 / np.e)) ** 4) / 25) / 2
plt.figure(figsize=(5,7))
plt.plot(y, x, 'r-', linewidth=2)
plt.grid(True)
plt.show()
# 5.5 心形线
t = np.linspace(0, 7, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)
plt.plot(x, y, 'r-', linewidth=2)
plt.grid(True)
plt.show()
# # 5.6 渐开线
t = np.linspace(0, 50, num=1000)
x = t*np.sin(t) + np.cos(t)
y = np.sin(t) - t*np.cos(t)
plt.plot(x, y, 'r-', linewidth=2)
plt.grid()
plt.show()
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.bar(x, y, width=0.04, linewidth=0.2)
plt.plot(x, y, 'r--', linewidth=2)
plt.title(u'Sin曲线')
plt.xticks(rotation=-60)
plt.xlabel('X')
plt.ylabel('Y')
plt.grid()
plt.show(
# # 6. 概率分布
# # 6.1 均匀分布
x = np.random.rand(10000)
t = np.arange(len(x))
plt.hist(x, 30, color='m', alpha=0.5)
# plt.plot(t, x, 'r-', label=u'均匀分布')
plt.legend(loc='upper left')
plt.grid()
plt.show()
#
# # # 6.2 验证中心极限定理
t = 10000
a = np.zeros(1000)
for i in range(t):
a += np.random.uniform(-5, 5, 1000)
a /= t
plt.hist(a, bins=30, color='g', alpha=0.5, normed=True)
plt.grid()
plt.show()
数量足够大 正态分布
# # 6.3 Poisson分布
x = np.random.poisson(lam=5, size=10000)
# print x
pillar = 15
a = plt.hist(x, bins=pillar, normed=True, range=[0, pillar], color='g', alpha=0.5)
plt.grid()
plt.show()
# # 6.4 直方图的使用
mu = 2
sigma = 3
data = mu + sigma * np.random.randn(1000)
h = plt.hist(data, 30, normed=1, color='#a0a0ff')
x = h[1]
y = norm.pdf(x, loc=mu, scale=sigma) #概率密度函数
plt.plot(x, y, 'r--', x, y, 'ro', linewidth=2, markersize=4)
plt.grid()
plt.show()
x = np.random.poisson(lam=5, size=10000)
# print x
pillar = 15
a = plt.hist(x, bins=pillar, normed=True, range=[0, pillar], color='g', alpha=0.5)
plt.grid()
plt.show()
# # 6.5 插值
rv = poisson(5)
x1 = a[1]
y1 = rv.pmf(x1) #概率密度函数
itp = BarycentricInterpolator(x1, y1) # 重心插值
x2 = np.linspace(x.min(), x.max(), 50)
y2 = itp(x2)
cs = scipy.interpolate.CubicSpline(x1, y1) # 三次样条插值
plt.plot(x2, cs(x2), 'm--', linewidth=5, label='CubicSpine') # 三次样条插值
plt.plot(x2, y2, 'g-', linewidth=3, label='BarycentricInterpolator') # 重心插值
plt.plot(x1, y1, 'r-', linewidth=1, label='Actural Value') # 原始值
plt.legend(loc='upper right')
plt.grid()
plt.show()
# 7. 绘制三维图像
x, y = np.ogrid[-3:3:100j, -3:3:100j]
# u = np.linspace(-3, 3, 101)
# x, y = np.meshgrid(u, u)
z = x*y*np.exp(-(x**2 + y**2)/2) / math.sqrt(2*math.pi)
# z = x*y*np.exp(-(x**2 + y**2)/2) / math.sqrt(2*math.pi)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# ax.plot_surface(x, y, z, rstride=5, cstride=5, cmap=cm.coolwarm, linewidth=0.1) #
ax.plot_surface(x, y, z, rstride=5, cstride=5, cmap=cm.Accent, linewidth=0.5)
plt.show()
# # cmaps = [('Perceptually Uniform Sequential',
# # ['viridis', 'inferno', 'plasma', 'magma']),
# # ('Sequential', ['Blues', 'BuGn', 'BuPu',
# # 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
# # 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
# # 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
# # ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool',
# # 'copper', 'gist_heat', 'gray', 'hot',
# # 'pink', 'spring', 'summer', 'winter']),
# # ('Diverging', ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr',
# # 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
# # 'seismic']),
# # ('Qualitative', ['Accent', 'Dark2', 'Paired', 'Pastel1',
# # 'Pastel2', 'Set1', 'Set2', 'Set3']),
# # ('Miscellaneous', ['gist_earth', 'terrain', 'ocean', 'gist_stern',
# # 'brg', 'CMRmap', 'cubehelix',
# # 'gnuplot', 'gnuplot2', 'gist_ncar',
# # 'nipy_spectral', 'jet', 'rainbow',
# # 'gist_rainbow', 'hsv', 'flag', 'prism'])]
# ax.plot_surface(x, y, z, rstride=5, cstride=5, cmap=cm.coolwarm, linewidth=0.1)
# # 8.2 使用scipy计算函数极值
# a = opt.fmin(f, 1)
# b = opt.fmin_cg(f, 1)
# c = opt.fmin_bfgs(f, 1)
# print a, 1/a, math.e
# print b
# print c
ptimization terminated successfully.
Current function value: 0.692201
Iterations: 16
Function evaluations: 32
Optimization terminated successfully.
Current function value: 0.692201
Iterations: 4
Function evaluations: 30
Gradient evaluations: 10
Optimization terminated successfully.
Current function value: 0.692201
Iterations: 5
Function evaluations: 24
Gradient evaluations: 8
[0.36787109] [2.71834351] 2.718281828459045
[0.36787948]
[0.36787942]
# marker description
# ”.” point
# ”,” pixel
# “o” circle
# “v” triangle_down
# “^” triangle_up
# “<” triangle_left
# “>” triangle_right
# “1” tri_down
# “2” tri_up
# “3” tri_left
# “4” tri_right
# “8” octagon
# “s” square
# “p” pentagon
# “*” star
# “h” hexagon1
# “H” hexagon2
# “+” plus
# “x” x
# “D” diamond
# “d” thin_diamond
# “|” vline
# “_” hline
# TICKLEFT tickleft
# TICKRIGHT tickright
# TICKUP tickup
# TICKDOWN tickdown
# CARETLEFT caretleft
# CARETRIGHT caretright
# CARETUP caretup
# CARETDOWN caretdown
【转载】原文地址:https://blog.csdn.net/weixin_42247762/article/details/81051672
|