【发布时间】: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])
而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