zoukankan      html  css  js  c++  java
  • 一、python2.7用法

           有关于python,和Matlab一样属于脚本类型语言。用作数据分析时,要求熟悉Numpy、Matplotlib、Scipy等库就行。python入门较为简单,仅此一篇博客作为入门练习。

    • 1.使用array创建
    • 2.使用函数创建
    • 3.存取
    • 4. numpy与Python数学库的时间比较
    • 5.绘图
    • 6. 概率分布
    • 7. 绘制三维图像
    • 8 scipy

    库引入

     1 # 导入NumPy函数库
     2 import numpy as np
     3 import matplotlib
     4 from mpl_toolkits.mplot3d import Axes3D
     5 from matplotlib import cm
     6 import time
     7 from scipy.optimize import leastsq
     8 import scipy.optimize as opt
     9 import scipy
    10 import matplotlib.pyplot as plt
    11 from scipy.stats import norm, poisson
    12 from scipy.interpolate import BarycentricInterpolator
    13 from scipy.interpolate import CubicSpline
    14 import math

    1.使用array创建

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Sat May  4 20:09:45 2019
     4 
     5 @author: shiruiyu
     6 """
     7 
     8 # 导入NumPy函数库
     9 import numpy as np
    10 
    11 #if __name__ == "__name__":
    12 # 默认创建list
    13 L = [1,2,3,4,5,6]
    14 print "L = ", L
    15 print type(L)
    16 # 通过array函数传递list对象
    17 a = np.array(L)
    18 print "a = ", a
    19 print type(a)
    20 #  创建矩阵
    21 b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
    22 print b
    23 # 数组size
    24 print b.shape
    25 print b.shape[0]
    26 print b.shape[1]
    27 # 也可以强制修改shape
    28 b.shape = 4,3
    29 print b
    30 # 当某个轴为-1时,将根据数组元素的个数自动计算此轴的长度
    31 b.shape = 2,-1
    32 print b
    33 # 使用reshape方法,可以创建改变了尺寸的新数组,原数组的shape保持不变
    34 c = b.reshape((4,-1))
    35 print "c = ",c 
    36 print "b = ",b
    37 # 数组b和c共享内存,修改任意一个将影响另外一个
    38 b[0][0] = 999
    39 print "c = ",c 
    40 print "b = ",b
    41 # 数组的元素类型可以通过dtype属性获得
    42 print a.dtype
    43 print b.dtype
    44 # 可以通过dtype参数在创建时指定元素类型
    45 d = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],dtype=np.float)
    46 f = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],dtype=np.complex)
    47 print d
    48 print f
    49 # 但不要强制仅修改元素类型,如下面这句,将会以int来解释单精度float类型
    50 #d.dtype = np.int
    51 #print d

     2.使用函数创建

     1 # 2.使用函数创建
     2 # 如果生成一定规则的数据,可以使用NumPy提供的专门函数
     3 # arange函数类似于python的range函数:指定起始值、终止值和步长来创建数组
     4 # 和Python的range类似,arange同样不包括终值;但arange可以生成浮点类型,而range只能是整数类型
     5 a = np.arange(1,10,0.5)
     6 print a
     7 # # # linspace函数通过指定起始值、终止值和元素个数来创建数组,缺省包括终止值
     8 b = np.linspace(1,10,10)
     9 print "b = ",b
    10 # 可以通过endpoint关键字指定是否包括终值
    11 c = np.linspace(1,10,10, endpoint = False)
    12 print "c = ", c
    13 # 下面函数创建起始值为10^1,终止值为10^2,有10个数的等比数列
    14 d = np.logspace(1,2,10,endpoint = True)
    15 print "d = ", d
    16 # # # 下面创建起始值为2^0,终止值为2^10(包括),有11个数的等比数列
    17 f = np.logspace(0, 10, 11, endpoint=True, base=2)
    18 print "f = ",f
    19 # 使用 frombuffer, fromstring, fromfile等函数可以从字节序列创建数组
    20 s = 'abcd'
    21 g = np.fromstring(s, dtype=np.int8)
    22 print g

     3.存取

     1 # 3.1常规办法:数组元素的存取方法和Python的标准方法相同
     2 a = np.arange(10)
     3 a[8] = 888
     4 print a
     5 # # # # 切片[3,6),左闭右开
     6 print a[3:6]
     7 # # # # 省略开始下标,表示从0开始
     8 print a[:5]
     9 # 下标为负表示从后向前数
    10 print a[3:]
    11 # 步长为2,范围:[1,7)
    12 print a[1:7:2]
    13 # 步长为-1,即:翻转
    14 print a[::-1]
    15 # # # # 切片数据是原数组的一个视图,与原数组共享内容空间,可以直接修改元素值
    16 a[2:4] = 10,20
    17 print a
    18 # 因此,在实践中,切实注意原始数据是否被破坏,如:
    19 b = a[2:5]
    20 b[0] = 200
    21 print a
    22 
    23 
    24 # # 3.2 整数/布尔数组存取
    25 # # 3.2.1
    26 # 根据整数数组存取:当使用整数序列对数组元素进行存取时,
    27 # 将使用整数序列中的每个元素作为下标,整数序列可以是列表(list)或者数组(ndarray)。
    28 # 使用整数序列作为下标获得的数组不和原始数组共享数据空间。
    29 a = np.logspace(0,9,10, base=2)
    30 print a
    31 i = np.arange(1,10,2)
    32 print i
    33 # 利用i取a中的元素
    34 b = a[i]
    35 print b
    36 # b的元素更改,a中元素不受影响
    37 b[2] = 1.6
    38 print b
    39 print a
    40 
    41 # # 3.2.2
    42 # 使用布尔数组i作为下标存取数组a中的元素:返回数组a中所有在数组b中对应下标为True的元素
    43 # # 生成10个满足[0,1)中均匀分布的随机数
    44 a = np.random.rand(10)
    45 print a
    46 # 大于0.5的元素索引
    47 print a > 0.5
    48 #大于0.5的元素
    49 b = a[a > 0.5]
    50 print b
    51 # 将原数组中大于0.5的元素截取成0.5
    52 a[a > 0.5] = 0.5
    53 print a
    54 # b不受影响
    55 print b
    56 
    57 # 3.3 二维数组的切片
    58 a = np.arange(0,60,10) #行向量
    59 print 'a = ', a
    60 b = a.reshape((-1,1)) #转为列向量
    61 print 'b = ',b
    62 c = np.arange(6)
    63 print c
    64 # 行 + 列
    65 f = b + c
    66 #合并上述代码
    67 a = np.arange(0,60,10).reshape((-1,1))+np.arange(6)
    68 print a
    69 #二维数组的切片
    70 print a[(0,1,2,3),(2,3,4,5)]#取出第(0,2)(1,3)(2,4)(3,5)个元素
    71 print a[3:,[0,2,5]]
    72 i = np.array([True, False, True, False, False, True])
    73 print a[i]
    74 print a[i,3]

    4. numpy与Python数学库的时间比较

     1 #for j in np.logspace(0, 7, 10):
     2 #    j = int(j)
     3 #    x = np.linspace(0, 10, j)
     4 #    #记住是怎么计算程序运行时间
     5 #    start = time.clock()
     6 #    y = np.sin(x)
     7 #    t1 = time.clock() - start
     8 #
     9 #    x = x.tolist()
    10 #    start = time.clock()
    11 #for i, t in enumerate(x):
    12 #    x[i] = math.sin(t)
    13 #    t2 = time.clock() - start
    14 #    print j, ": ", t1, t2, t2/t1

    5.绘图

     1 # 5.1 绘制正态分布概率密度函数
     2 mu = 0
     3 sigma = 1
     4 x = np.linspace(mu - 3 * sigma, mu + 3 * sigma, 50)
     5 y = np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / (math.sqrt(2 * math.pi) * sigma)
     6 print x.shape
     7 print 'x = 
    ', x
     8 print y.shape
     9 print 'y = 
    ', y
    10 plt.plot(x, y, 'ro-', linewidth=2)
    11 plt.plot(x, y, 'r-', x, y, 'go', linewidth=2, markersize=8)
    12 plt.grid(True)
    13 plt.show()
    14 
    15 # 5.2 损失函数:Logistic损失(-1,1)/SVM Hinge损失/ 0/1损失
    16 x = np.array(np.linspace(start=-2, stop=3, num=1001, dtype=np.float))
    17 y_logit = np.log(1 + np.exp(-x)) / math.log(2)
    18 y_boost = np.exp(-x)
    19 y_01 = x < 0
    20 y_hinge = 1.0 - x
    21 y_hinge[y_hinge < 0] = 0
    22 plt.plot(x, y_logit, 'r-', label='Logistic Loss', linewidth=2)
    23 plt.plot(x, y_01, 'g-', label='0/1 Loss', linewidth=2)
    24 plt.plot(x, y_hinge, 'b-', label='Hinge Loss', linewidth=2)
    25 plt.plot(x, y_boost, 'm--', label='Adaboost Loss', linewidth=2)
    26 plt.grid()
    27 plt.legend(loc='upper right')
    28 # plt.savefig('1.png')
    29 plt.show()
    30 
    31 #5.3 x^x
    32 
    33 # x ** x        x > 0
    34 # (-x) ** (-x)  x < 0
    35 def f(x):
    36     y = np.ones_like(x)
    37     i = x > 0
    38     y[i] = np.power(x[i], x[i])
    39     i = x < 0
    40     y[i] = np.power(-x[i], -x[i])
    41     return y
    42 
    43 x = np.linspace(-1.3, 1.3, 101)
    44 y = f(x)
    45 plt.plot(x, y, 'g-', label='x^x', linewidth = 2)
    46 plt.grid()
    47 plt.legend(loc = 'upper left')
  • 相关阅读:
    [转]来扯点ionic3[2] 页面一线牵 珍惜这段缘
    [转]ionic工作原理
    [转]禁止浏览器自动保存密码弹框
    [转]git提交代码时遇到代码库有更新以及本地有更新的解决方法
    [转]Angular 4 *ngIf/Else
    [转]Angular4 引用 material dialog时自定义对话框/deep/.mat-dialog-container
    ES之五:ElasticSearch聚合
    Logstash之四:配置说明
    Logstash之三:命令行中常用的命令
    Logstash之二:原理
  • 原文地址:https://www.cnblogs.com/winslam/p/10809736.html
Copyright © 2011-2022 走看看