如何在Python中高效地表示二进制向量

2024-10-04 03:17:44 发布

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

我正在Python上进行数据分析(例如使用本地二进制模式),并试图优化我的代码。在我的代码中,我使用了二进制向量,它们目前被实现为numpu ndarray向量。我的代码中有三个函数:

# Will return a binary vector presentation of the neighbourhood
#
# INPUTS:
# 'ndata' numpy ndarray consisting of the neighbourhood X- and Y- coordinates and values 
# 'thres' decimal value indicating the value of the center pixel
#
# OUTPUT:
# 'bvec' binary vector presentation of the neighbourhood 

def toBinvec(ndata, thres):

    bvec = np.zeros((len(ndata), 1)) 
    for i in range(0, len(ndata)):
        if ndata[i, 2]-thres < 0:
            bvec[i] = 0
        else:
            bvec[i] = 1
    return bvec 



# Will check whether a given binary vector is uniform or not 
# A binary pattern is uniform if when rotated one step, the number of
# bit values changing is <= 2
#
# INPUTS:
# 'binvec' is a binary vector of type numpy ndarray 
#
# OUTPUT:
# 'True/False' boolean indicating uniformness

def isUniform(binvec):

    temp = rotateDown(binvec) # This will rotate the binary vector one step down
    devi = 0
    for i in range(0, len(temp)):
        if temp[i] != binvec[i]:
            devi += 1
    if devi > 2:
        return False
    else:
        return True

# Will return the corresponding decimal number of binary vector
#
# INPUTS:
# 'binvec' is a binary vector of type numpy ndarray 
#
# OUTPUT:
# 'value' The evaluated decimal value of the binary vector 

def evaluate(binvec):

    value = 0
    for i in range(0, len(binvec)):
            value += binvec[i]*(2**i)
    return value

为了使代码更高效,有没有其他方法可以实现二进制向量?代码将用于大数据分析,因此效率是一个重要问题。在

我还需要对二进制向量做一些操作,例如旋转它,计算它的十进制值等等

谢谢您的帮助/提示!=)


Tags: ofthe代码lenreturnisvalue二进制
1条回答
网友
1楼 · 发布于 2024-10-04 03:17:44
def toBinvec(ndata, thres):
    return  np.where(ndata[:,2] < thres, 0, 1 ).reshape(-1,1)

def isUniform(binvec):

    temp = rotateDown(binvec) # This will rotate the binary vector one step down
    if (np.count_nonzero(binvec!=temp)) > 2:
        return False
    else:
        return True

def evaluate(binvec):
    return sum(binvec * 2**np.arange(len(binvec)))

这应该会有所改善。但是,大部分看起来像是在一些高度优化版本的scipy(或相关)软件包中提供的。在

例如,toBinvec只是一个阈值,在许多包中都可以使用。在

相关问题 更多 >