arrays - Python:随机播放并放回numpy数组的初始顺序元素
问题描述
我有一个必须修改一些值的数组。为此,我必须更改数组元素的顺序,在更改其值之后,我想将值放回初始顺序。但2小时后,我真的不知道怎么做。
更改顺序时,我需要将它们从绝对值的最大元素到最小元素进行排序。然后,我需要将元素的总和设为 = 到 1,因此我修改了元素,但随后无法重新排序数组。
这是我的代码:
output = np.random.uniform(-1, 1, (4, 1)).ravel()
sorted_weigths = np.sort(abs(output))[::-1]
sorted_indices = np.argsort(sorted_weigths)[::-1]
signs = [i < 0 for i in output]
if np.sum(abs(sorted_weigths)) > 1:
alloc = 1
for i in range(output.shape[0]):
if alloc > abs(sorted_weigths[i]):
sorted_weigths[i] = sorted_weigths[i]
alloc = alloc - abs(sorted_weigths[i])
elif alloc > 0:
sorted_weigths[i] = alloc
alloc = alloc - alloc
else:
sorted_weigths[i] = 0
else:
pass
sorted_weigths[sorted_indices]
for i in range(len(signs)):
if signs[i] == True:
sorted_weigths[i] = -sorted_weigths[i]
else:
pass
我知道
output = np.random.uniform(-1, 1, (4, 1)).ravel()
sorted_weigths = np.sort(abs(output))
sorted_indices = np.argsort(sorted_weigths)
output[np.argsort(np.sort(abs(output)))]
这是诀窍,但修改输出的值不起作用。因此,任何帮助或提示将不胜感激。非常感谢
解决方案
解决方案实际上是根据原始输出的位置重新排序转换后的数组的位置,而不是通过跟踪打乱的索引。
解决方案是:
output = np.random.uniform(-1, 1, (4, 1)).ravel()
sorted_weigths = np.sort(abs(output))[::-1]
sorted_indices = np.argsort(abs(output))[::-1]
signs = [i < 0 for i in output]
if np.sum(abs(sorted_weigths)) > 1:
alloc = 1
for i in range(output.shape[0]):
if alloc > abs(sorted_weigths[i]):
sorted_weigths[i] = sorted_weigths[i]
alloc = alloc - abs(sorted_weigths[i])
elif alloc > 0:
sorted_weigths[i] = alloc
alloc = alloc - alloc
else:
sorted_weigths[i] = 0
else:
pass
sorted_weigths_ = copy.deepcopy(sorted_weigths)
for i in range(sorted_indices.shape[0]):
sorted_weigths_[sorted_indices[i]] = sorted_weigths[i]
for i in range(len(signs)):
if signs[i] == True:
sorted_weigths_[i] = -sorted_weigths_[i]
else:
pass
print(output)
print(sorted_weigths_)
推荐阅读
- python - 如何在当前的词袋分类中添加另一个文本特征?在 Scikit-learn 中
- python - 帧不会在 Tk 中加载。(TK-GUI-Python)
- python - 通过相同的列值删除和操作熊猫中的日期
- python - 为什么我的代码在函数形式上这么慢?
- sql - 如何有效地将新数据附加到 AWS Athena 中的表中?
- javascript - 如何在 v-if 中处理单击的项目
- python - 如何解决“ImportError:没有名为 marionette_test 的模块”
- asp.net-mvc - asp.net mvc5中使用CKEditor上传图片
- react-native - `找不到模块'../scripts/ios'`复制项目目录后尝试运行iOS模拟器
- python - 如何在我的 django 应用程序中模拟一个访问外部服务的组件?