【问题标题】:How can I print a Numpy Array as a result from a function?如何打印一个 Numpy 数组作为函数的结果?
【发布时间】:2020-09-30 22:31:06
【问题描述】:

我有这个函数,它可以获取 3 个输入并进行一些矩阵计算。

import numpy as np

def func(input_x, output_y, lambda_param):
        
    if input_x.shape[0]<input_x.shape[1]:
        input_x = np.transpose(input_x)
    
    input_x = np.c_[np.ones(input_x.shape[0]),input_x]
    
    lambda_param = np.identity(input_x.shape[1])*lambda_param
    

    a = np.linalg.inv(lambda_param+np.matmul(np.transpose(input_x),input_x))
    b = np.matmul(np.transpose(input_x),output_y)

    weights = np.matmul(a,b)
    weights = np.array([weights])
    return weights

该函数运行良好,但结果的数据类型有问题。例如,我有输入 yy、xx 和 lamb:


yy = np.array([208500, 181500, 223500, 
                                140000, 250000, 143000, 
                                307000, 200000, 129900, 
                                118000])
                                
xx = np.array([[1710, 1262, 1786, 
                                1717, 2198, 1362, 
                                1694, 2090, 1774, 
                                1077], 
                               [2003, 1976, 2001, 
                                1915, 2000, 1993, 
                                2004, 1973, 1931, 
                                1939]])
lamb = 10

result = func(xx, yy, lamb)

print(result) #--> np.array([-576.67947107,   77.45913349,   31.50189177])
#print(result[2]) #--> 31.50189177

print(result) 给我[[-576.67947107 77.45913349 31.50189177]] 但应该返回一个类似np.array([-576.67947107, 77.45913349, 31.50189177])

的numpy.array

print(result[2]) 应该返回31.50189177 但由于它不是np.array 而给出错误?

我希望你能帮助我!提前致谢。

【问题讨论】:

  • 你试过weights = np.array(weights)而不是weights = np.array([weights])吗?
  • 我试过了,但这会返回[-576.67947107 77.45913349 31.50189177] 31.501891773638363 但不会返回np.array([...])
  • 尝试使用 type(result) 检查结果的数据类型。对我来说,它显示的是 numpy.ndarray。
  • print(arr) 显示数组的str 格式,省略了array 和逗号。 repr 提供了更多详细信息。

标签: python arrays numpy printing


【解决方案1】:

你不需要这行:weights = np.array([weights]) weights 在weights = np.matmul(a,b) 之后已经是一维 numpy 数组。多余的线会给权重一个额外的维度,权重的形状变成(1,3)。您可以使用 print(weights.shape) 来检查这些

【讨论】:

    【解决方案2】:

    删除倒数第二行 func (weights = np.array([weights])) 应该会为您解决问题。你无意中用那条线创建了一个二维数组。例如:

    x = np.array([0.25, 0.50, 0.75])
    print(x.shape)  #--> (3,) 
    print(x[2])  #--> 0.75
    
    y = np.array([x])
    print(y.shape) #--> (1, 3)
    print(y[2])  #--> IndexError
    

    上面的y是一个二维数组,第一个索引长度为1,第二个索引长度为3,所以y[2](适用于第一个索引)不存在。

    您可以改为使用 np.array(weights)(不将权重放入列表中),但这已经过时,因为 weights 已经是一个 numpy 数组。

    就打印的内容而言 - 您可以通过执行 print(type(weights)) 来检查 weights 是否真的是一个 numpy 数组。即使print(weights) 不清楚,它也是一个 numpy 数组。

    【讨论】:

    • 谢谢,很简单但我没看到,现在可以了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多