Python 如何使用numpy数组查找具有最小MSE的值?
我可能的价值观是:Python 如何使用numpy数组查找具有最小MSE的值?,python,numpy,mean-square-error,Python,Numpy,Mean Square Error,我可能的价值观是: 0: [0 0 0 0] 1: [1 0 0 0] 2: [1 1 0 0] 3: [1 1 1 0] 4: [1 1 1 1] 我有一些价值观: [[0.9539342 0.84090066 0.46451256 0.09715253], [0.9923432 0.01231235 0.19491441 0.09715253] .... 我想找出哪些可能的值与我的新值最接近。理想情况下,我希望避免对循环执行,并想知道是否有某种向量化的方法来搜索最小均方误差 我希
0: [0 0 0 0]
1: [1 0 0 0]
2: [1 1 0 0]
3: [1 1 1 0]
4: [1 1 1 1]
我有一些价值观:
[[0.9539342 0.84090066 0.46451256 0.09715253],
[0.9923432 0.01231235 0.19491441 0.09715253]
....
我想找出哪些可能的值与我的新值最接近。理想情况下,我希望避免对循环执行,并想知道是否有某种向量化的方法来搜索最小均方误差
我希望它返回一个数组,如下所示:[2,1….
假设您的输入数据是一个字典。然后可以使用NumPy作为矢量化解决方案。首先将输入列表转换为NumPy数组,并使用axis=1
参数来获取RMSE
# Input data
dicts = {0: [0, 0, 0, 0], 1: [1, 0, 0, 0], 2: [1, 1, 0, 0], 3: [1, 1, 1, 0],4: [1, 1, 1, 1]}
new_value = np.array([0.9539342, 0.84090066, 0.46451256, 0.09715253])
# Convert values to array
values = np.array(list(dicts.values()))
# Compute the RMSE and get the index for the least RMSE
rmse = np.mean((values-new_value)**2, axis=1)**0.5
index = np.argmin(rmse)
print ("The closest value is %s" %(values[index]))
# The closest value is [1 1 0 0]
纯努比:
val1 = np.array ([
[0, 0, 0, 0],
[1, 0, 0, 0],
[1, 1, 0, 0],
[1, 1, 1, 0],
[1, 1, 1, 1]
])
print val1
val2 = np.array ([0.9539342, 0.84090066, 0.46451256, 0.09715253], float)
val3 = np.round(val2, 0)
print val3
print np.where((val1 == val3).all(axis=1)) # show a match on row 2 (array([2]),)
您可以使用np.argmin
获取rmse值的最低索引,该值可以使用np.linalg.norm
import numpy as np
a = np.array([[0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0],[1, 1, 1, 0], [1, 1, 1, 1]])
b = np.array([0.9539342, 0.84090066, 0.46451256, 0.09715253])
np.argmin(np.linalg.norm(a-b, axis=1))
#outputs 2 which corresponds to the value [1, 1, 0, 0]
正如编辑中提到的,b可以有多行。op想要避免for循环,但我似乎找不到避免for循环的方法。下面是一个列表comp方法,但可能有更好的方法
[np.argmin(np.linalg.norm(a-i, axis=1)) for i in b]
#Outputs [2, 1]
这个可能值的格式是什么?它看起来像一个字典,所以实际上没有严格的格式,但是是的,如果需要,我们可以把它变成一个dict
,如果我的预测值循环到dict中没有的值,那么它就不起作用了。具体来说,我需要它来处理许多新值e> sI特别为问题添加了一些更详细的内容,我需要它来处理许多新值
linalg.norm是否计算MSE?如果您想找到argmin,它会计算rmse,它本质上是MSE。