numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)[source]

Estimate a covariance matrix, given data and weights.

Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, , then the covariance matrix element  is the covariance of  and . The element  is the variance of .

See the notes for an outline of the algorithm.

Parameters:

m : array_like

A 1-D or 2-D array containing multiple variables and observations. Each row (行) of m represents a variable(变量), and each column(列) a single observation of all those variables(样本). Also see rowvar below.

y : array_like, optional

An additional set of variables and observations. y has the same form as that of m.

rowvar : bool, optional

If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.

bias : bool, optional

Default normalization (False) is by (N - 1), where N is the number of observations given (unbiased estimate). If bias is True, then normalization is by N. These values can be overridden by using the keyword ddof in numpy versions >= 1.5.

ddof : int, optional

If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified, and ddof=0 will return the simple average. See the notes for the details. The default value is None.

New in version 1.5.

fweights : array_like, int, optional

1-D array of integer freguency weights; the number of times each observation vector should be repeated.

New in version 1.10.

aweights : array_like, optional

1-D array of observation vector weights. These relative weights are typically large for observations considered “important” and smaller for observations considered less “important”. If ddof=0 the array of weights can be used to assign probabilities to observation vectors.

New in version 1.10.

Returns:

out : ndarray

The covariance matrix of the variables.

See also

corrcoef
Normalized covariance matrix

Notes

Assume that the observations are in the columns of the observation array m and let f = fweights and a = aweights for brevity. The steps to compute the weighted covariance are as follows:

  1. >>> w = f * a
  2. >>> v1 = np.sum(w)
  3. >>> v2 = np.sum(w * a)
  4. >>> m -= np.sum(m * w, axis=1, keepdims=True) / v1
  5. >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)

Note that when a == 1, the normalization factor v1 / (v1**2 - ddof * v2) goes over to 1 / (np.sum(f) - ddof) as it should.

Examples

Consider two variables,  and , which correlate perfectly, but in opposite directions:

  1. >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
  2. >>> x
  3. array([[0, 1, 2],
  4. [2, 1, 0]])

Note how  increases while  decreases. The covariance matrix shows this clearly:

  1. >>> np.cov(x)
  2. array([[ 1., -1.],
  3. [-1., 1.]])

Note that element , which shows the correlation between  and , is negative.

Further, note how x and y are combined:

  1. >>> x = [-2.1, -1, 4.3]
  2. >>> y = [3, 1.1, 0.12]
  3. >>> X = np.stack((x, y), axis=0)
  4. >>> print(np.cov(X))
  5. [[ 11.71 -4.286 ]
  6. [ -4.286 2.14413333]]
  7. >>> print(np.cov(x, y))
  8. [[ 11.71 -4.286 ]
  9. [ -4.286 2.14413333]]
  10. >>> print(np.cov(x))
  11. 11.71

总结

理解协方差矩阵的关键就在于牢记它的计算是不同维度之间的协方差,而不是不同样本之间。拿到一个样本矩阵,最先要明确的就是一行是一个样本还是一个维度,心中明确整个计算过程就会顺流而下,这么一来就不会迷茫了。

numpy协方差矩阵numpy.cov的更多相关文章

  1. numpy入门—numpy是什么

    numpy是什么?为什么使用numpy 使用numpy库与原生python用于数组计算性能对比

  2. Python的 numpy中 numpy.ravel() 和numpy.flatten()的区别和使用

    两者所要实现的功能是一致的(将多维数组降为一维), 两者的区别在于返回拷贝(copy)还是返回视图(view),numpy.flatten() 返回一份拷贝,对拷贝所做的修改不会影响(reflects ...

  3. Python 关于数组矩阵变换函数numpy.nonzero(),numpy.multiply()用法

    1.numpy.nonzero(condition),返回参数condition(为数组或者矩阵)中非0元素的索引所形成的ndarray数组,同时也可以返回condition中布尔值为True的值索引 ...

  4. numpy.ravel()/numpy.flatten()/numpy.squeeze()

    numpy.ravel(a, order='C') Return a flattened array numpy.chararray.flatten(order='C') Return a copy ...

  5. 【numpy】新版本中numpy(numpy>1.17.0)中的random模块

    numpy是Python中经常要使用的一个库,而其中的random模块经常用来生成一些数组,本文接下来将介绍numpy中random模块的一些使用方法. 首先查看numpy的版本: import nu ...

  6. NumPy之:NumPy简介教程

    目录 简介 安装NumPy Array和List 创建Array Array操作 sort concatenate 统计信息 reshape 增加维度 index和切片 从现有数据中创建Array 算 ...

  7. numpy入门—Numpy的核心array对象以及创建array的方法

    Numpy的核心array对象以及创建array的方法 array对象的背景: Numpy的核心数据结构,就叫做array就是数组,array对象可以是一维数组,也可以是多维数组: Python的Li ...

  8. 使用numpy实现批量梯度下降的感知机模型

    生成多维高斯分布随机样本 生成多维高斯分布所需要的均值向量和方差矩阵 这里使用numpy中的多变量正太分布随机样本生成函数,按照要求设置均值向量和协方差矩阵.以下设置两个辅助函数,用于指定随机变量维度 ...

  9. python(5):scipy之numpy介绍

    python 的scipy 下面的三大库: numpy, matplotlib, pandas scipy 下面还有linalg 等 scipy 中的数据结构主要有三种: ndarray(n维数组), ...

随机推荐

  1. 数据库事务MTDC出错解决办法

    Communication with the underlying transaction manager has failed 与基础事务管理器的通信失败 排除步驟: 1.檢查MS DTC 設置.[ ...

  2. mysql数据库2

    命令行客户端软件MySQL Command Line Client, 打开该程序,输入数据库密码,登陆到MySQL软件, 如果想通过该命令行工具来操作MySQL软件,只需要在"mysql&g ...

  3. ios的单元測试OCUnit以及更新了之后的XCTestCase

    1.像一般创建项目的步骤一样.创建一个用于測试的项目或者打开一个待測试的项目. (oc是5.0之前所使用的測试,如今用的是XCtestCase,默认会创建一个主的測试类.曾经版本号可能非常多步骤省去) ...

  4. passport登录问题:passport.use 方法没有被调用

    写passport登录验证时,无论如何passport.use 方法都没有被调用,最后在同事的帮助下,才找到问题: 我是用form提交登陆数据的, input type:"text" ...

  5. 在Windows系统上搭建aria2下载器

    Aria2是一个命令行下运行.多协议.多来源下载工具(HTTP/HTTPS.FTP.BitTorrent.Metalink),并且支持迅雷离线以及百度云等常用网盘的多线程下载(甚至可以超过专用客户端的 ...

  6. composer 更新指定包

    1)网上搜了大半天都不知道怎么更新 componser 包,update upgrade 命令根本不知道怎么用!! 2)其实用 require 命令就可以更新包(它会判断包存不存在,不存在就安装,存在 ...

  7. Java访问数据库Mysql

    一.概述 本文主要介绍Java接连数据库的基本方法和步骤,并对其中的几个要点进行简要说明. 二.数据库访问步骤 在Java中连接数据库进行的访问主要有以下几个步骤: 加载数据库驱动 注册数据库驱动 建 ...

  8. listView优化方案

    1.如果自定义适配器,那么在getView方法中要考虑方法传进来的参数contentView是否为null,如果为null就创建contentView并返回,如果不为null则直接使用.在这个方法中尽 ...

  9. openlayers中利用vector实现marker的方式

    项目需要一个小型的gis.openlayers,geoserver,postgres组合是比较好的选择. openlayers的marker层好像不支持拖动操作.通过研究api发现,可以利用vecto ...

  10. python爬虫---->github上python的项目

    这里面通过爬虫github上的一些start比较高的python项目来学习一下BeautifulSoup和pymysql的使用.我一直以为山是水的故事,云是风的故事,你是我的故事,可是却不知道,我是不 ...