当前位置:网站首页>全方位剖析Numpy中的np.diag源代码
全方位剖析Numpy中的np.diag源代码
2022-08-02 10:04:00 【舞雩.】
Numpy中内置的函数diag是一个变化莫测的函数。
这是np.diag函数的源代码:
def diag(v, k=0):
v = asanyarray(v)
s = v.shape
if len(s) == 1:
n = s[0]+abs(k)
res = zeros((n, n), v.dtype)
if k >= 0:
i = k
else:
i = (-k) * n
res[:n-k].flat[i::n+1] = v
return res
elif len(s) == 2:
return diagonal(v, k)
else:
raise ValueError("Input must be 1- or 2-d.")我们可以看出np.diag函数可以传入的参数有 v和 k。
对于v:
v是一个数组。(一维或者二维)
当v是一个一维数组时,结果形成一个以一维数组为对角线元素的矩阵;
当v是一个二维矩阵时,结果输出矩阵的对角线元素。
对于k:
k默认等于零,意味着取对角线,位置不偏移。
如果k > 0,那么取或者放对角线上面第k斜行。
如果k < 0,那么取或者放对角线下面第k斜行。
使用案例帮助理解:
假设现在有这样一个数组array:
>>> array
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])v :二维数组,k:0
>>> np.diag(a)
array([1, 5, 9])
v:一维数组,k:0
# 把上面的array([1, 5, 9])作为输入, 即np.diag(array) = [1, 5, 9]
>>> np.diag(np.diag(a))
array([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
v:二维数组,k:1
>>> np.diag(array, 1)
array([2, 6])v:一维数组,k:1
# 把上面的array([1, 5, 9])作为输入, 即np.diag(array) = [1, 5, 9]
>>> np.diag(np.diag(array), 1)
array([0 1 0 0]
[0 0 5 0]
[0 0 0 9]
[0 0 0 0]])边栏推荐
- Event 对象,你很了解吗?
- 软件测试之发现和解决bug
- 软件测试与质量 之白盒测试
- Weak yen turns game consoles into "financial products" in Japan: scalpers make big profits
- The ggbarplot function of the R language ggpubr package visualizes the grouped histogram, sets the add parameter to mean_se to visualize the histogram of the mean values of different levels and adds
- 一文带你了解推荐系统常用模型及框架
- 【技术分享】OSPFv3基本原理
- 斯皮尔曼相关系数
- npm ERR! 400 Bad Request - PUT xxx - Cannot publish over previously published version “1.0.0“.
- 如何封装微信小程序的 wx.request() 请求
猜你喜欢

第十五章 多线程

零代码工具推荐---HiFlow

Spearman's correlation coefficient

要长续航还是更安全?海豹与深蓝SL03对比导购

DVWA Clearance Log 2 - Command Injection

Re23:读论文 How Does NLP Benefit Legal System: A Summary of Legal Artificial Intelligence

后管实现面包屑功能

8月份的.NET Conf 活动 专注于 .NET MAUI

DVWA 通关记录 2 - 命令注入 Command Injection

Use compilation to realize special effects of love
随机推荐
超赞!发现一个APP逆向神器!
This article takes you to understand the commonly used models and frameworks of recommender systems
Smoothing of time series data in R language: smoothing time series data to remove noise using the dpill function and locpoly function of the KernSmooth package
一文带你了解推荐系统常用模型及框架
The R language uses the rollapply function in the zoo package to apply the specified function to the time series in a rolling manner and the window moves, and set the align parameter to specify that t
Application scenarios of js anti-shake function and function throttling
利用二维数据学习纹理三维网格生成(CVPR 2020)
R语言ggpubr包的ggbarplot函数可视化分组柱状图、设置add参数为mean_se可视化不同水平均值的柱状图并为柱状图添加误差线(se标准误差)、position参数自定义分组柱状图分离
Spearman's correlation coefficient
周杰伦新歌发布,爬取《Mojito》MV弹幕,看看粉丝们都说的些啥!
WPF 截图控件之文字(七)「仿微信」
全新荣威RX5,27寸大屏吸引人,安全、舒适一个不落
带你认识40G单纤双向光模块-QSFP+ BiDi光模块
瑞萨RZ/G2L处理器详细测评
【云原生】快出数量级的性能是怎样炼成的?就提升了亿点点
Verilog's random number system task----$random
如何封装微信小程序的 wx.request() 请求
Event 对象,你很了解吗?
Facebook自动化数据分析方案,广告投放省心省力
R语言ggplot2可视化:使用ggpubr包的ggbarplot函数可视化水平柱状图(条形图)、使用orientation参数设置柱状图转置为条形图