线性代数运算、数据处理、画图

2019-07-22  本文已影响0人  Bounty_Hunter

补充

Numpy

NumPy 是一个 Python 包。 它代表 “Numeric Python”

我们用他来做线性代数有关的运算

import numpy as np
  a = np.array([[1, 2], [3, 4]])
  b = np.array([[5, 6], [7, 8]])
  print ('a * b = \n', a * b)

Pandas

Series

Pyplot

#  Task2

- Task2_1_1

  - **Plot on the same figure by calling plt.hist() twice in a row**

    在同一个图里绘制两个list的柱状图,在 `matplotlib.pyplot.hist( x )` 用包含两个这list 的 list 作为第一个参量

  - **Specify a label for each histogram and use a legend**

    hist 函数( 画柱状图函数 ) 的 label 变量赋值 ['xxxx','yyyy']

  - **Specify a colour and transparency/alpha value for each in case they overlap**

    alpha 可以改变每个柱状图的透明度(0 透明到1不透明)

    color 可以改变颜色 代表不同颜色的标示符一共有八种:

    | 标记符 | 颜色 |
    | ------ | ---- |
    | 'r'    | 红   |
    | 'g'    | 绿   |
    | 'b'    | 蓝   |
    | 'c'    | 蓝绿 |
    | 'm'    | 紫红 |
    | 'y'    | 黄   |
    | 'k'    | 黑   |
    | 'w'    | 白   |

    当然还有更多选择

    ```python
    cnames = {
    'aliceblue':            '#F0F8FF',
    'antiquewhite':         '#FAEBD7',
    'aqua':                 '#00FFFF',
    'aquamarine':           '#7FFFD4',
    'azure':                '#F0FFFF',
    'beige':                '#F5F5DC',
    'bisque':               '#FFE4C4',
    'black':                '#000000',
    'blanchedalmond':       '#FFEBCD',
    'blue':                 '#0000FF',
    'blueviolet':           '#8A2BE2',
    'brown':                '#A52A2A',
    'burlywood':            '#DEB887',
    'cadetblue':            '#5F9EA0',
    'chartreuse':           '#7FFF00',
    'chocolate':            '#D2691E',
    'coral':                '#FF7F50',
    'cornflowerblue':       '#6495ED',
    ...
    ```

- Task2_1_2

  - **For reference create a histogram or plot a probability density function of normal distribution**

    画符合正态分布数据的直方图和**画正态分布函数**

  - `numpy.random.randn(*d0*, *d1*, *...*, *dn*)`

    生成符合均值0和方差1的单变量“正态”(高斯)分布的 list , `(*d0*, *d1*, *...*, *dn*)`指的是 list 的维数,例如:

    ```
    np.random.randn(2, 4)
    
    ```

    生成的就是两个 list ,每个 list 包含4个 float 类型数字

  - 计算正态分布的概率密度函数

    ![概率分布函数公式](/Users/apple/Downloads/%E6%A6%82%E7%8E%87%E5%88%86%E5%B8%83%E5%87%BD%E6%95%B0%E5%85%AC%E5%BC%8F.png)

    用`mean()`计算数据的**均值**`mean` 

    用`std()`计算**标准差**`std`

    用函数完成计算概率密度函数

  - 推荐用`matplotlib`库里的 `mlab.normpdf`函数计算

    ```python
    import matplotlib.mlab as mlab 
    y = mlab.normpdf(x,mean,std)
    ```

- Task2_1_3

  - **Standardise the Salary variable to make the comparison clearer (note that the x-axis values are different)**

    **标准化数据**

    一般指的是 Z-Score 标准化,去除均值和方差缩放

    得到的结果是,对于每个属性/每列来说所有数据都聚集在0附近,方差为1。

    公式为:( mean 均值,std 标准差 )
    $$
    (X-mean)/std
    $$
    推荐用公式法

    ```python
    xsalary_st = (xsalary-xsalary.mean())/xsalary.std()
    
    ```

    或者使用`sklearn.preprocessing.scale()`函数,直接将数据标准化

    ```python
     from sklearn import preprocessing
     xsalary_scaled =  preprocessing.scale(xsalary)
    ```

  - **Is the Customer Salary Normally Distributed?**

    **(Optional) Perform a normality test**

    **判断是否满足正态分布**

    目视法

    直方图的柱子数足够多的话,可以观察图像是否是“钟形函数”

    函数法

    使用`scipy.stats.normaltest`函数 测量数据是否符合正态分布

    ```python
    from scipy.stats import normaltest
    normaltest(salary)
    ```

    如果返回的 P 值大于0.05, 一般就认为符合正态分布

    统计学里在差异性的比较中,大于0.05表示无差异,小于0.05表示有差异.大于0.05表明与正态分布无差异,故符合正态分布

- Task_2_2_1

  - **Create the vector a=[2,−1,10]T** 

    **构建向量**

    用 `np.array()` 或者`np.matrix()` 都可以

    强调下`array` 和 `matrix`的区别:

    ```
    matrix 一定是二维的,array 可以是多维的
    
    array 可以作为行向量或者列向量
    
    如果要确定向量的形状,用 matrix 构建向量
    
    如果用了 matrix 或 array 构建向量就一直用,不要混用。
    
    ```

  - **Calculate the transpose of a and store it in variable b:**

    **向量的转置**

    用 `np.transpose()` 函数

  - **Calculate the sum of b by taking the dot product of b with a vector of all ones.**

    **生成全一矩阵**

    用`np.ones()` 函数

    默认生成的矩阵元素都是 float 类型(有小数点),可以在调用函数时加上 `dtype = int` 变量,这样生成的矩阵元素都是整数

    **矢量积(叉乘)** 

    用`np.dot(x,y)`函数,注意矢量积的顺序

    ```python
    import numpy as np
    a = np.matrix([[2,-1,10]]).transpose()
    print(a)
    b = a.transpose()
    print(b)
    ones = np.ones(a.shape)
    b_sum = np.dot(b,ones)
    print(b_sum)
    ```

- Task2_2_2

  - **Create a matrix **
    $$
    \mathbf M = \left [  \begin{array}{ccc} 1 & -1 & 2 \\ 0 & -3 & 1 \end{array} \right]
    $$
    构建矩阵 `np.matrix()`

  - **Sum the rows of M and then store the result along the diagonal of a square matrix**

    **计算矩阵每行元素的和**

    做法一(tutor): 

    M 与一个 3*2 的全一矩阵相乘,这样每一行上的值就是他们这一行的和;

    用`np.diag()` 函数,将整个矩阵相乘的结果矩阵作为参数,取出一个 list 包含对角线上的两个值(分别是第一行之和,第二行之和);

    再用`np.diag()`函数,将这个 list 作为参数,生成并打印矩阵,这个矩阵的对角线上的值就是 list 里的第一行之和,第二行之和

    ```python
    import numpy as np
    M = np.array(((1,-1,2),(0,-3,1)))
    print(M)
    ones = np.ones((3,2))
    S = np.diag( np.dot(M,ones))
    S = np.diag(S)
    print(S)
    ```

    做法二:嵌套循环(循环里还有个循环);

    先计算第一行的元素和,存在 list `row_sum` 的第一个值里;

    再计算第二行的元素和,存在 list `row_sum` 的第二个值里。

    ```python
     import numpy as np
        M = np.array(((1,-1,2),(0,-3,1)))
        print(M)
        sum = [.0,.0]
        print(M.shape)
        for x in range(M.shape[0]):
            for y in range(M.shape[1]):
                sum[x] += M[x,y]
        
         S = np.diag(sum)
         print(S)
    ```
     做法三:做法二里的嵌套循环可以用 `sum` 函数代替

    `M.sum(axis = 1)` 返回的是每行的和组成的 `list`

    ```
    import numpy as np
        M = np.array(((1,-1,2),(0,-3,1)))
        print(M)
        sum = [.0,.0]
        for i in range(len(sum)):
            sum[i] = float(M.sum(axis = 1)[i])
        S = np.diag(sum)
        print(S)
    ```

        **构建对角阵**

       用`np.diag()` 函数,传入一个 list 类型的对象

Challenges

Linspace

The linspace function takes a starting value, a stopping value and how many numbers you want to produce. The following will produce 11 numbers evenly spaced from 0 to 100.

在指定的间隔内返回均匀间隔的数字,linspace()函数

numpy.linspace(start, stop, num, endpoint)

start: 序列的起点

stop:序列的终点

num:生成的样本数

endpoint:可选项,如果是true, 序列包括终点,如果是 false ,序列不包括终点

import numpy as np

start = int(input('Start: '))
stop = int(input('Stop: '))
n = int(input('N: '))
x = np.linspace(start, stop, n)

for i in range(len(x)):
    print(x[i])

Matrix multiplication

Use Python to determine C, the matrix multiplication of matrix A and matrix B. Print the resultant matrix C.

生成矩阵和矩阵运算

import numpy as np
A = np.matrix([[2,0],[8,9],[5,8],[1,6]])
B = np.matrix([[7,9,1],[4,3,8]])
print(A*B)

Simple stats

计算数据中的最小值、最大值、平均值、和、标准差

  a = np.array(values)
  print('Minimum:', a.min())
  print('Maximum:', a.max())
  print('Mean:', a.mean())
  print('Sum:', a.sum())
  print('Standard deviation', a.std())

上一篇 下一篇

猜你喜欢

热点阅读