Skip to main content
 首页 » 编程设计

python之使用 numpy 元组中的值创建矩阵

2024年10月01日8www_RR

我正在尝试创建一个矩阵,其值基于我存储在元组中的 x,y 值。我使用循环遍历元组并对数据执行简单计算:

import numpy as np 
 
# Trying to fit quadratic equation to the measured dots 
 
N = 6 
num_of_params = 3 
 
# x values 
x = (1,4,3,5,2,6) 
 
# y values 
y = (3.96, 24.96,14.15,39.8,7.07,59.4) 
 
# X is a matrix N * 3 with the x values to the power of {0,1,2} 
X = np.zeros((N,3)) 
Y = np.zeros((N,1)) 
 
print X,"\n\n",Y 
 
for i in range(len(x)): 
    for p in range(num_of_params): 
        X[i][p] = x[i]**(num_of_params - p - 1) 
    Y[i] = y[i] 
 
print "\n\n" 
print X,"\n\n",Y 

这可以通过更简单的方式实现吗?我正在寻找一些方法来初始化矩阵,例如 X = np.zeros((N,3), read_values_from = x)

这可能吗?还有其他简单的方法吗?

Python 2.7

请您参考如下方法:

扩展 x 的数组版本至 2D使用 np.newaxis/None 沿第二个使用单例暗淡(长度 = 1 的暗淡) .这让我们可以利用 NumPy broadcasting 得到2D以向量化的方式输出。 y 的类似理念.

因此,实现将是 -

X = np.asarray(x)[:,None]**(num_of_params - np.arange(num_of_params)  - 1) 
Y = np.asarray(y)[:,None] 

或者对np.power使用内置的外部方法得到X负责引擎盖下的数组转换-

X = np.power.outer(x, num_of_params - np.arange(num_of_params)  - 1) 

或者,对于 Y , 使用 np.expand_dims -

Y = np.expand_dims(y,1)