我應該撰寫一個函式來接收標記的資料集并根據標簽拆分資料點:
def get_clusters(X: np.ndarray, y: np.ndarray) -> List[np.ndarray]:
"""
Receives a labeled dataset and splits the datapoints according to label
Args:
X (np.ndarray): The dataset
y (np.ndarray): The label for each point in the dataset
Returns:
List[np.ndarray]: A list of arrays where the elements of each array
are datapoints belonging to the label at that index.
Example:
>>> get_clusters(
np.array([[0.8, 0.7], [0, 0.4], [0.3, 0.1]]),
np.array([0,1,0])
)
>>> [array([[0.8, 0.7],[0.3, 0.1]]),
array([[0. , 0.4]])]
"""
idx = np.unique(y,return_index = True)[1]
C = []
for i,label in enumerate(np.unique(y)):
if i != len(idx)-1:
C.append(X[idx[i]:idx[i 1]])
else:
C.append(X[idx[i]:])
return C
這是我迄今為止嘗試過的,但顯然它只適用于排序輸入。我不允許使用多個 for 回圈。有誰知道如何改進功能?
我希望我包括了所有必要的資訊。
uj5u.com熱心網友回復:
排序似乎需要做很多作業。另一種選擇是使用np.where來獲取索引。
import numpy as np
def get_clusters(X: np.ndarray, y: np.ndarray) -> List[np.ndarray]:
return [X[np.where(y == label)[0], :] for label in np.unique(y)]
給出相同的結果:
get_clusters(
np.array([[0.8, 0.7], [0, 0.4], [0.3, 0.1]]),
np.array([0,1,0])
)
[array([[0.8, 0.7],
[0.3, 0.1]]),
array([[0. , 0.4]])]
uj5u.com熱心網友回復:
您可以使用 將陣列拆分為一個list子陣列
減少唯一標簽的結果(10000/10 到 10000/90,x 軸標簽不正確)常量陣列大小為 10000

用于基準測驗的代碼
import numpy as np
from typing import List
import perfplot
def get_clusters_sort(X: np.ndarray, y: np.ndarray) -> List[np.ndarray]:
s = np.argsort(y)
return np.split(X[s], np.unique(y[s], return_index=True)[1][1:])
def get_clusters_loop(X: np.ndarray, y: np.ndarray) -> List[np.ndarray]:
return [X[np.where(y == label)[0]] for label in np.unique(y)]
perfplot.show(
setup = lambda n: (np.random.rand(n,2), np.random.randint(n//10, size=n)),
kernels = [
lambda x: get_clusters_sort(*x),
lambda x: get_clusters_loop(*x)
],
labels = ['sort','loop'],
n_range = [2**k for k in range(10,19)],
xlabel = 'len(a)',
equality_check=False
)
代碼更改以估計影響 len(unique(labels))
perfplot.show(
setup = lambda n: (np.random.rand(10000,2), np.random.randint(10000//n, size=10000)),
kernels = [
lambda x: get_clusters_sort(*x),
lambda x: get_clusters_loop(*x)
],
labels = ['sort','loop'],
n_range = [k for k in range(10,100,10)],
xlabel = 'len(unique(labels))',
equality_check=False
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/414387.html
標籤:
