Python;将矩阵转换为二进制版本(基2)

2024-04-26 05:21:18 发布

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

原始问题

(正在寻找有关将矩阵中的整数转换为base=2的二进制版本的函数的帮助。你知道吗

我尝试过使用numpy.binary_repr,但是它对矩阵不起作用。你知道吗

有什么建议/功能吗?你知道吗

(谢谢)

修正问题

这里的目的是创造

-500x50 2D阵列/以前称之为矩阵。随机在-1和+1之间

-将其标准化为介于0和1之间

-乘以1000并取整

-使用固定的 10位大小

到目前为止,代码如下

import numpy as np

np.random.seed(seed=1)
Weights = np.random.uniform(low=-1.0, high=1.0, size=500*50)

Weights = reshape(Weights,(500,50)) 


print(Weights.shape)

#Normalise the Weights
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
Weights_Norm = scaler.fit_transform(Weights)
#print(Weights_Norm)

#Multiply by 1000 to get integers below 1000
Weights_Norm_1000=Weights_Norm*1000
#print(Weights_Norm_1000)

Weights_Norm_1000R= matrix.round(Weights_Norm_1000,0)
print(Weights_Norm_1000R)

Weight_int=Weights_Norm_1000R.astype(int)

x = np.array(Weight_int)
print(np.array([np.binary_repr(a) for b in x for a in b]).reshape(x.shape))

Tags: importnumpynormnp矩阵randomintseed
1条回答
网友
1楼 · 发布于 2024-04-26 05:21:18

假设您有一个numpy矩阵x,您可以尝试:

np.array([np.binary_repr(a) for b in x for a in b]).reshape(x.shape)

例如:

将numpy作为np导入

x = np.array([[1,2,3],[4,5,6]])
np.array([np.binary_repr(a) for b in x for a in b]).reshape(x.shape)
#array([['1', '10', '11'],
#       ['100', '101', '110']], dtype='<U3')

相关问题 更多 >