题解
from typing import List
from random import *
def unbalanced_data_pipeline(data: List[List[List[int]]], batch_size: int) -> List[List[List[int]]]:
# 在此函数中完成上下采样的功能
labelNum = len(data[0][1])
lendata = len(data)
batch_data = []
count = 0
if batch_size%labelNum == 0:
n = batch_size/labelNum
else:
n = 1
testList = [int(n)]*labelNum
disList = [0]*labelNum
#print(testList)
while count<batch_size:
i_rand = randint(0, lendata-1)
i_ans = GetAns(data[i_rand][1])
disList[i_ans] += 1
#print(i_ans)
print(disList,testList)
#print(disList==testList)
#print(IsLagel(disList,testList))
if IsLagel(disList,testList):
count += 1
batch_data.append(data[i_rand])
if disList == testList:
disList = [0]*len(disList)
else:
disList[i_ans] -= 1
return batch_data
def GetAns(one_hot:List[int]):
for i in range(len(one_hot)):
if one_hot[i] == 1:
return i
return 0
def IsLagel(disList,testList):
for i in range(len(disList)):
if disList[i] > testList[i]:
return False
return True
data = [[[1, 2, 5], [1, 0]],
[[1, 6, 0], [1, 0]],
[[4, 1, 8], [1, 0]],
[[7, 0, 4], [0, 1]],
[[5, 9, 4], [0, 1]],
[[2, 0, 1], [0, 1]],
[[1, 9, 3], [0, 1]],
[[5, 5, 5], [0, 1]],
[[8, 4, 0], [0, 1]],
[[9, 6, 3], [0, 1]],
[[7, 7, 0], [0, 1]],
[[0, 3, 4], [0, 1]]]
batch_size = 3
print(unbalanced_data_pipeline(data, batch_size))