【问题标题】:Create a matrix using values from a tuple with numpy使用 numpy 元组中的值创建矩阵
【发布时间】:2017-11-12 15:49:53
【问题描述】:

我正在尝试创建一个矩阵,其值基于我存储在元组中的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

【问题讨论】:

    标签: python python-2.7 numpy matrix


    【解决方案1】:

    使用np.newaxis/None 将数组版本的x 扩展到2D,并沿第二个暗淡(长度=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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 2018-11-04
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多