I'm learning python, numpy and machine learning. I'm trying to set up neural network from scratch and I have a problem.
I have some outputs e.g [[2], [4], [1]]
and I'm trying to create mask for it that will look like this
[
[0 0 1 0 0]
[0 0 0 0 1]
[0 1 0 0 0]
]
for now I'm using following code:
tmpY = np.array(Y)
tmp = np.zeros([m, 10])
for i in range (0, m):
index = tmpY[i][0]
tmp[i][index] = 1
But I think there is a cleaner way.
Edit:
Thanks guys for your help. I think I've found solution that will work best for me
C = np.array([[0], [2], [4], [2], [4], [1] ,[3], [8], [5], [3], [1], [2]])
np.eye(C.shape[0], np.amax(C) + 1, dtype=int)[C.flatten()]
[[1 0 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0]
[0 0 0 0 1 0 0 0 0]
[0 0 1 0 0 0 0 0 0]
[0 0 0 0 1 0 0 0 0]
[0 1 0 0 0 0 0 0 0]
[0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 0 0 0 1]
[0 0 0 0 0 1 0 0 0]
[0 0 0 1 0 0 0 0 0]
[0 1 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0]]
I'll leave it here in case someone else will look it.
答案 0 :(得分:0)
您的解决方案是正确的,这只是一个清洁一点的版本
indices = [[2],[4],[1]]
mask = np.zeros((m,10),dtype=np.uint8)
for i,indices in enumerate(indices): mask[i,indices] = 1
不确定从何处获得indices
数组,但是您有某种条件想要掩盖原始图像,可以这样做:
original = np.random.uniform((100,100))
mask = np.zeros(original.shape,dtype=np.uint8)
mask[condition(original)] = 1 # eg mask[original < 0.5] = 1
答案 1 :(得分:-1)
sklearn has a class that can help you do this. You can use OneHotEncoder
to create the mask as per the documentation
In your example
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder(handle_unknown='ignore')
X = [[2], [4], [1]]
enc.fit(X)
Then the output looks like:
enc.transform(X).toarray()
array([[0., 1., 0.],
[0., 0., 1.],
[1., 0., 0.]])
EDIT:
You'll notice the output here has 3 elements for each transformed entry; this is because category 3 does not appear in the data we use to fit OneHotEncoder