我有此函数,它获得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]]
但是应该返回一个numpy.array像np.array([-576.67947107, 77.45913349, 31.50189177])
并print(result[2])
应返回31.50189177
但由于不是np.array而给出错误?
我希望你可以帮助我!提前致谢。
您不需要这一行:weights = np.array([weights])
weights已经是之后的一维numpy数组weights = np.matmul(a,b)
。多余的线会给砝码增加尺寸,并且砝码的形状变为(1,3)。您可以使用print(weights.shape)进行检查
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句