将Numpy数组缩放到一定范围 [英] Scale Numpy array to certain range

查看:680
本文介绍了将Numpy数组缩放到一定范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于此问题,我想将Numpy数组放入某个范围内,但是与链接的问题不同,我不想对其进行归一化.我如何有效地做到这一点? Numpy中有内置方法吗?

Similar to this question, I want to fit a Numpy array into a certain range, however unlike the linked question I don't want to normalise it. How can I do this efficiently? Is there a built-in method in Numpy?

举个例子来说明,其中my_scale是我要寻找的函数,而out_range定义了输出范围:

To clarify with an example, where my_scale is the function I'm looking for and out_range defines the output range:

res = my_scale(np.array([-3, -2, -1], dtype=np.float), out_range)
assert res == [-1, 0, 1]
assert res != [-1, -2/3, -1/3]

推荐答案

询问CodeReview 之后,我通知有一个内置的 np.interp 完成此操作:

After asking on CodeReview, I was informed there is a built-in np.interp that accomplishes this:

np.interp(a, (a.min(), a.max()), (-1, +1))

为了后代,我在下面留下了我的旧答案.

I've left my old answer below for the sake of posterity.

我根据此答案中的D3.js代码制作了自己的函数:

I made my own function based off of the D3.js code in this answer:

import numpy as np

def d3_scale(dat, out_range=(-1, 1)):
    domain = [np.min(dat, axis=0), np.max(dat, axis=0)]

    def interp(x):
        return out_range[0] * (1.0 - x) + out_range[1] * x

    def uninterp(x):
        b = 0
        if (domain[1] - domain[0]) != 0:
            b = domain[1] - domain[0]
        else:
            b =  1.0 / domain[1]
        return (x - domain[0]) / b

    return interp(uninterp(dat))

print(d3_scale(np.array([-2, 0, 2], dtype=np.float)))
print(d3_scale(np.array([-3, -2, -1], dtype=np.float)))

这篇关于将Numpy数组缩放到一定范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆