如何使用numpy数组找到最小MSE的值?

2024-04-16 05:43:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我可能的价值观是:

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]

我有一些价值观:

^{pr2}$

我想知道我的可能值中,哪一个最接近我的新值。理想情况下,我想避免执行for循环,并想知道是否有某种向量化的方法来搜索最小均方误差?在

我希望它返回一个如下的数组:[2, 1 ....


Tags: 方法for情况数组误差理想价值观新值
3条回答

纯裸体:

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循环的方法。这是一个列表补偿的方法,但是还有更好的方法

^{pr2}$

假设您的输入数据是字典。然后,可以使用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]

相关问题 更多 >