机器学习——邹博代码的复现第一节:Python基础讲解

版权声明:未经同意窃取和转载我的内容,如果涉及到权益问题,后果自负! https://blog.csdn.net/weixin_41605937/article/details/84843233

以下所有的函数的代码本人亲自验证了都是可以产生正确的结果的。请记得调用函数就可以得到图像

#-*- coding:utf-8 _*-
"""
@author:24626
@file: 整理代码一.py
@time: 2018/12/{DAY}
"""
#导入必要的包文件
import numpy as np
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import time
from scipy.optimize import leastsq
from scipy import stats
import scipy.optimize as opt
import matplotlib.pyplot as plt
from scipy.stats import norm, poisson
from scipy.interpolate import BarycentricInterpolator
from scipy.interpolate import CubicSpline
import math
import seaborn
from statsmodels.compat import scipy
#画图中的标题中的中文显示
mpl.rcParams['font.sans-serif'] = [u'SimHei']  #FangSong/黑体 FangSong/KaiTi
mpl.rcParams['axes.unicode_minus'] = False

def function1():
    """numpy是非常好用的数据包,如:可以这样得到这个二维数组 """
    a = np.arange(0, 60, 10).reshape((-1, 1)) + np.arange(6)
    print(a)

def function2():
    """标准Python的列表(list)中,元素本质是对象。
    如:L = [1, 2, 3],需要3个指针和三个整数对象,对于数值运算比较浪费内存和CPU。
    因此,Numpy提供了ndarray(N-dimensional array object)对象:存储单一数据类型的多维数组"""
    # 1.使用array创建  通过array函数传递list对象
    L = [1, 2, 3, 4, 5, 6]#表示列表
    print ("L = ", L,type(L))
    a = np.array(L)
    print ("a = ", a,type(a))
    print(a.shape)
    b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
    print (b,b.shape)
    b.shape = 4, 3
    print("经过该改变:\n",b)
    # 数组大小可以通过其shape属性获得的到维度的关系 注:从(3,4)改为(4,3)并不是对数组进行转置,而只是改变每个轴的大小,数组元素在内存中的位置并没有改变
    # 当某个轴为-1时,将根据数组元素的个数自动计算此轴的长度
    b.shape = 2, -1
    print (b)
    # 使用reshape方法,可以创建改变了尺寸的新数组,原数组的shape保持不变
    c = b.reshape((4, -1))
    print("使用的reshape方法的是:\n",c)

    # 可以通过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,"\n",f)

def function3():
    """如果更改元素类型,可以使用astype安全的转换
     但不要强制仅修改元素类型,如下面这句,将会以int来解释单精度float类型
    """
    d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.float)
    f = d.astype(np.int)
    print(f)

def function4():
    """如果生成一定规则的数据,可以使用NumPy提供的专门函数
    arange函数类似于python的range函数:指定起始值、终止值和步长来创建数组
    和Python的range类似,arange同样不包括终值;但arange可以生成浮点类型,而range只能是整数类型
    linspace函数通过指定起始值、终止值和元素个数来创建数组,缺省包括终止值
    """
    a = np.arange(1, 10, 0.5)     #指定起始值、终止值和步长来创建数组
    print(a)
    # 可以通过endpoint关键字指定是否包括终值
    b = np.linspace(1, 10, 10,endpoint=False)
    print ('b = ', b)

def function5():
    """和linspace类似,logspace可以创建等比数列
    下面函数创建起始值为10^1,终止值为10^2,有10个数的等比数列
    """
    d = np.logspace(1, 2, 9, endpoint=True)
    print(d)
    # 使用 frombuffer, fromstring, fromfile等函数可以从字节序列创建数组就是根据ASICC码来构建的
    s = 'abcdz'
    g = np.fromstring(s, dtype=np.int8)
    print (g)

def function6():
    # 3.存取
    # 3.1常规办法:数组元素的存取方法和Python的标准方法相同
    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)

def function7():
    """4.2 元素去重一共有三种方法 1 直接利用库函数进行去重复元素 2 利用是转化为虚数进行除去重复元素
    3 利用set集合的性质不允许重复的原则 """
    # 4.2.1直接使用库函数
    a = np.array((1, 2, 3, 4, 5, 5, 7, 3, 2, 2, 8, 8))
    print('原始数组:', a)
    # # # 使用库函数unique去重复的元素
    b = np.unique(a)
    print('去重后:', b)
    # 4.2.2 二维数组的去重,结果会是预期的么?
    c = np.array(((1, 2), (3, 4), (5, 6), (1, 3), (3, 4), (7, 6)))
    print( u'二维数组:\n', c)
    print('去重后:', np.unique(c))
    # 4.2.3 方案1:转换为虚数
    r, i = np.split(c, (1, ), axis=1)
    x = r + i * 1j
    x = c[:, 0] + c[:, 1] * 1j
    print( '转换成虚数:', x)
    print('虚数去重后:', np.unique(x))
    print(np.unique(x, return_index=True))   # 思考return_index的意义
    idx = np.unique(x, return_index=True)[1]
    print ('二维数组去重:\n', c[idx])
    # 4.2.3 方案2:利用set
    print('去重方案2:\n', np.array(list(set([tuple(t) for t in c]))))

def function8():
    """矩阵之间的运算"""
    # 4.3用来作为堆叠的数组,要求形状维度必须相等
    a = np.arange(1, 10).reshape((3, 3))
    b = np.arange(11, 20).reshape((3, 3))
    c = np.arange(101, 110).reshape((3, 3))
    print('a = \n', a)
    print('b = \n', b)
    print('c = \n', c)
    print('axis = 0 \n', np.stack((a, b, c), axis=0))#axis=0可以认为只是将原数组上下堆叠,增加了0维的个数
    print('axis = 1 \n', np.stack((a, b, c), axis=1))#axis=1,可以看出第一个3*3的数组是由是a,b,c中每个数组的第一行堆叠而成
    print('axis = 2 \n', np.stack((a, b, c), axis=2))#axis=2,可以看到第一个3*3的数组是由a,b,c中的第一列向量组合而成
    #矩阵的点乘运算
    a = np.arange(1, 10).reshape(3,3)
    print (a)
    b = a + 10
    print(b)
    print(np.dot(a, b))
    print(a * b)

def function9():
    a = np.arange(1, 10)
    print(a)
    b = np.arange(20,25)
    print(b)
    #方法一:进行的是数组的拼接concatenate()会进行降维度的处理。
    print ("concatenate:\n",np.concatenate((a, b)))#这个函数用于将多个数组进行连接,这与stack函数很容易混淆,他们之间的区别是concatenate会把当前要匹配的元素降一维,即去掉最外面那一层括号 concatenate()效率更高,适合大规模的数据拼接
    #方法二:思路:首先将数组转成列表,然后利用列表的拼接函数append()、extend() 等进行拼接处理,最后将列表转成数组。
    a = np.array([1, 2, 5])
    b = np.array([10, 12, 15])
    a_list = list(a)
    b_list = list(b)
    e=np.array(a_list.extend(b_list))#不推荐使用该方法
    print(a_list,type(a_list))

def function10():
    # 5.绘图
    # 5.1 绘制正态分布概率密度函数
    mu = 0
    sigma = 1
    x = np.linspace(mu - 3 * sigma, mu + 3 * sigma, 51)#按照等比数列产生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.figure(facecolor='w')
    plt.plot(x, y, 'r-', x, y, 'ro', linewidth=2, markersize=8)
    plt.xlabel('X', fontsize=15)
    plt.ylabel('Y', fontsize=15)
    plt.title(u'高斯分布函数', fontsize=18)
    plt.grid(True)
    plt.savefig("正态分布概率密度函数")
    plt.show()

def function11():
    # 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)#r-表示红色
    plt.plot(x, y_01, 'g-', label='0/1 Loss', linewidth=2)#g-表示绿色
    plt.plot(x, y_hinge, 'b-', label='Hinge Loss', linewidth=2)#b-表示蓝色
    plt.plot(x, y_boost, 'm--', label='Adaboost Loss', linewidth=2)#m-表示紫色
    plt.grid(True)
    plt.legend(loc='upper right')
    plt.savefig('损失函数')
    plt.show()

def f(x):
    y = np.ones_like(x)
    i = x > 0
    y[i] = np.power(x[i], x[i])
    i = x < 0
    y[i] = np.power(-x[i], -x[i])
    return y

def function12():
    # 5.3 x^x
    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.savefig("函数x^x的图像")
    plt.show()

def function13():
    # 5.5 心形线
    t = np.linspace(0, 2*np.pi, 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.savefig("心形线")
    plt.show()

def function14():
    # 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.savefig("渐开线")
    plt.show()

def function15():
    # Bar
    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.savefig("bar线")
    plt.show()

def function16():
    # 6. 概率分布
    # 6.1 均匀分布
    """hist的参数非常多,但常用的就这六个,只有第一个是必须的,后面四个可选
    arr: 需要计算直方图的一维数组
    bins: 直方图的柱数,可选项,默认为10
    normed: 是否将得到的直方图向量归一化。默认为0
    facecolor: 直方图颜色
    edgecolor: 直方图边框颜色
    alpha: 透明度
    histtype: 直方图类型,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’
    """
    x = np.random.rand(100)
    t = np.arange(len(x))
    plt.hist(x,bins=10,color='m', alpha=0.5, label=u'均匀分布')
    plt.plot(t, x, 'r-', label=u'均匀分布')
    plt.legend(loc='upper right')
    plt.grid(True)
    plt.savefig("均匀分布")
    plt.show()

def function17():
    # 6.2 验证中心极限定理
    t = 1000
    a = np.zeros(10000)
    for i in range(t):
        a += np.random.uniform(-5, 5, 10000)
    a /= t
    plt.hist(a, bins=30, color='g', alpha=0.5, normed=True, label=u'均匀分布叠加')
    plt.legend(loc='upper left')
    plt.grid()
    plt.savefig("中心极限定理")
    plt.show()

def function18():
    # 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.savefig("直方图")
    plt.show()

def function19():
    # 6.5 插值
    rv = poisson(5)
    a = np.arange(1, 10).reshape((3, 3))
    x=a
    x1 = a[1]
    y1 = rv.pmf(x1)
    itp = BarycentricInterpolator(x1, y1)  # 重心插值
    x2 = np.linspace(x.min(), x.max(), 50)
    y2 = itp(x2)
    cs =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.savefig("插值图")
    plt.show()

def function20():
    # 7. 绘制三维图像
    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)
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.plot_surface(x, y, z, rstride=5, cstride=5, cmap=cm.Accent, linewidth=0.5)
    plt.savefig("三维视图")
    plt.show()

def residual(t, x, y):
    return y - (t[0] * x ** 2 + t[1] * x + t[2])

def function21():
    # 线性回归例1
    x = np.linspace(-2, 2, 50)
    A, B, C = 2, 3, -1
    y = (A * x ** 2 + B * x + C) + np.random.rand(len(x))*0.75
    print(y)
    t = leastsq(residual, [0, 0, 0], args=(x, y))
    theta = t[0]
    print( '真实值:', A, B, C)
    print ('预测值:', theta)
    y_hat = theta[0] * x ** 2 + theta[1] * x + theta[2]
    plt.plot(x, y, 'r-', linewidth=2, label=u'Actual')
    plt.plot(x, y_hat, 'g-', linewidth=2, label=u'Predict')
    plt.legend(loc='upper left')
    plt.grid()

    plt.savefig("线性规划实例1")
    plt.show()

def residual2(t, x, y):
    print (t[0], t[1])
    return y - (t[0]*np.sin(t[1]*x) + t[2])

def function22():
    # 线性回归例2
    x = np.linspace(0, 5, 100)
    a = 5
    w = 1.5
    phi = -2
    y = a * np.sin(w*x) + phi + np.random.rand(len(x))*0.5
    t = leastsq(residual2, [3, 5, 1], args=(x, y))
    theta = t[0]
    print('真实值:', a, w, phi)
    print ('预测值:', theta)
    y_hat = theta[0] * np.sin(theta[1] * x) + theta[2]
    plt.plot(x, y, 'r-', linewidth=2, label='Actual')
    plt.plot(x, y_hat, 'g-', linewidth=2, label='Predict')
    plt.legend(loc='lower left')
    plt.grid()
    plt.savefig("线性规划实例2")
    plt.show()

if __name__ == '__main__':
    pass
    # 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

猜你喜欢

转载自blog.csdn.net/weixin_41605937/article/details/84843233