создаём массив пар – датасета и соответствующих для него параметров алгоритма…
- User
создаём массив пар – датасета и соответствующих для него параметров алгоритма
datasets_params_list = [ (blobs, {'n_clusters': 3}), (varied, {'n_clusters': 3}), (aniso, {'n_clusters': 3}), (noisy_circles, {'n_clusters': 2}), (noisy_moons, {'n_clusters': 2}), (no_structure, {'n_clusters': 3})]
for i, (X, k_means_params) in enumerate(datasets_params_list, start=1): X = StandardScaler().fit_transform(X) k_means = KMeans(n_clusters=k_means_params['n_clusters'])
k_means.fit(X) y_pred = k_means.labels_.astype(np.int) plt.subplot(f'23{i}') plt.xticks([]); plt.yticks([]) colors = np.array(list(islice(cycle(['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3', '#999999', '#e41a1c', '#dede00']), int(max(y_pred) + 1)))) plt.scatter(X[:, 0], X[:, 1], color=colors[y_pred])/usr/local/lib/python3.10/dist-packages/sklearn/cluster/_kmeans.py:870: FutureWarning: The default value of
n_initwill change from 10 to 'auto' in 1.4. Set the value ofn_initexplicitly to suppress the warning warnings.warn(AttributeError Traceback (most recent call last) in <cell line: 10>() 13 14 k_means.fit(X) ---> 15 y_pred = k_means.labels_.astype(np.int) 16 17 plt.subplot(f'23{i}')
/usr/local/lib/python3.10/dist-packages/numpy/init.py in getattr(attr) 317 318 if attr in former_attrs: --> 319 raise AttributeError(former_attrs[attr]) 320 321 if attr == 'testing':
AttributeError: module 'numpy' has no attribute 'int'.
np.intwas a deprecated alias for the builtinint. To avoid this error in existing code, useintby itself. Doing this will not modify any behavior and is safe. When replacingnp.int, you may wish to use e.g.np.int64ornp.int32to specify the precision. If you wish to review your current use, check the release note link for additional information. The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations - Assistant
There seems to be an issue with the use of
np.intin the code block. The correct way to use it is justint.You can replace
np.intwithintin the line:y_pred = k_means.labels_.astype(np.int)Update it to:
y_pred = k_means.labels_.astype(int)Try making this change and run the code again.
- User
import warnings
from sklearn.neighbors import kneighbors_graph
datasets_params_list = [ (blobs, {'n_clusters': 3, 'n_neighbors': 10}), (varied, {'n_clusters': 3, 'n_neighbors': 2}), (aniso, {'n_clusters': 3, 'n_neighbors': 2}), (noisy_circles, {'n_clusters': 2, 'n_neighbors': 10}), (noisy_moons, {'n_clusters': 2, 'n_neighbors': 10}), (no_structure, {'n_clusters': 3, 'n_neighbors': 10})]
for i, (X, ac_params) in enumerate(datasets_params_list, start=1): X = StandardScaler().fit_transform(X)
# строим матрицу смежности connectivity = kneighbors_graph(X, n_neighbors=ac_params['n_neighbors'], include_self=False) # делаем матрицу смежности симметричной connectivity = 0.5 * (connectivity + connectivity.T) ac = AgglomerativeClustering(n_clusters=ac_params['n_clusters'], linkage='average', connectivity=connectivity) with warnings.catch_warnings(): warnings.filterwarnings( "ignore", message="the number of connected components of the " + "connectivity matrix is [0-9]{1,2}" + " > 1. Completing it to avoid stopping the tree early.", category=UserWarning) ac.fit(X) y_pred = ac.labels_.astype(np) plt.subplot(2,3,i) plt.xticks([]); plt.yticks([]) colors = np.array(list(islice(cycle(['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3', '#999999', '#e41a1c', '#dede00']), int(max(y_pred) + 1)))) plt.scatter(X[:, 0], X[:, 1], color=colors[y_pred]) - Assistant
The error you are encountering,
IndexError: arrays used as indices must be of integer (or boolean) type), indicates that they_predarray might not be of integer type.In your code snippet, you have
y_pred = ac.labels_.astype(np). It seems like there is a missing import fornumpythat's causing the error.Add the following import statement at the beginning of your code:
import numpy as npAfter adding the import, you should change the line:
y_pred = ac.labels_.astype(np)to:
y_pred = ac.labels_.astype(int)This modification should resolve the error. Remember to add the missing import as well for numpy.
- User
Чтение данных из файла
datasets = pd.read_csv(csv_file_path_1) print(datasets.shape) datasets.head()
np.random.seed(0)
Количество объектов в каждом датасете
n_samples = 1500
Вписанные круги
noisy_circles = datasets.make_circles(n_samples=n_samples, factor=.5, noise=.05)
Оставляем только признаки датасета, так как для кластеризации нам не нужны истинные классы объектов
X, y = noisy_circles noisy_circles = X
Полукруги
noisy_moons = datasets.make_moons(n_samples=n_samples, noise=.05) X, y = noisy_moons noisy_moons = X
Кластеры в форме круга
blobs = datasets.make_blobs(n_samples=n_samples, random_state=8) X, y = blobs blobs = X
Отсутствие кластерной структуры
no_structure = np.random.rand(n_samples, 2)
Кластеры лентовидной формы
random_state = 170 X, y = datasets.make_blobs(n_samples=n_samples, random_state=random_state) transformation = [[0.6, -0.6], [-0.4, 0.8]] X_aniso = np.dot(X, transformation) aniso = X_aniso
- Assistant
It seems like there is an issue with the usage of the
datasetsvariable. The errorAttributeError: 'DataFrame' object has no attribute 'make_circles'indicates that themake_circlesfunction is not available in a DataFrame object.The
datasetsvariable seems to be a DataFrame object because you are reading data from a CSV file. To generate the datasets, you need to use themake_circlesand other functions from thesklearn.datasetsmodule.Here's how you can fix the code:
-
Replace the line:
datasets = pd.read_csv(csv_file_path_1)with:
from sklearn.datasets import make_circles, make_moons, make_blobs -
Now you can generate datasets using these functions directly:
np.random.seed(0) # Количество объектов в каждом датасете n_samples = 1500 # Вписанные круги noisy_circles = make_circles(n_samples=n_samples, factor=.5, noise=.05)Do the same for the other dataset generation commands.
-
- User
как сделать по данным datasets = pd.read_csv(csv_file_path_1)
- Assistant
Если вы хотите использовать данные, загруженные из файла CSV с помощью
pd.read_csv(), чтобы создать кластеризационные датасеты, вам нужно сначала преобразовать эти данные в формат, понятный функциям генерации датасетов изsklearn.datasets.Вот пример того, как это можно сделать:
-
Предположим, что у вас есть столбцы в вашем dataframe
datasets, которые представляют признаки для кластеризации. Давайте предположим, что ваши признаки находятся в столбцах 'Feature1' и 'Feature2'. -
Преобразуйте эти столбцы в массив
numpyдля использования в функциях генерации датасетов:
import numpy as np from sklearn.datasets import make_blobs # Преобразуйте столбцы с признаками в массив numpy X = datasets[['Feature1', 'Feature2']].values # Создайте кластеризационный датасет из этих признаков clusters, y = make_blobs(n_samples=len(X), centers=3, n_features=2, random_state=0) -
- User
Чтение данных из файла
datasets = pd.read_csv(csv_file_path_1) print(datasets.shape) datasets.head() np.random.seed(0)
Количество объектов в каждом датасете
datasets = 1500
Вписанные круги
datasets = datasets.datasetss(n_samples=n_samples, factor=.5, noise=.05)
Оставляем только признаки датасета, так как для кластеризации нам не нужны истинные классы объектов
X, y = datasets datasets = X
Полукруги
datasets = datasets.datasets(n_samples=n_samples, noise=.05) X, y = datasets datasetss = X
Кластеры в форме круга
blobs = datasets.datasets(n_samples=n_samples, random_state=8) X, y = blobs blobs = X
Отсутствие кластерной структуры
no_structure = np.random.rand(n_samples, 2)
Кластеры лентовидной формы
random_state = 170 X, y = datasets.datasets(n_samples=n_samples, random_state=random_state) transformation = [[0.6, -0.6], [-0.4, 0.8]] X_aniso = np.dot(X, transformation) aniso = X_aniso
Кластеры в форме кругов с различной дисперсией
varied = datasets.datasets(n_samples=n_samples, cluster_std=[1.0, 2.5, 0.5], random_state=random_state) X, y = varied varied = X
- Assistant
В коде, который вы предоставили, есть несколько проблем:
-
Использование терминологии "datasets" для хранения данных оболочки pandas DataFrame и как переменной для хранения сгенерированных данных. Это может вызвать путаницу. Лучше использовать более информативные и отличающиеся по смыслу имена переменных.
-
Вы пытаетесь переопределить переменные, используя их для разных целей в коде, что приводит к ошибкам.
-
Неправильное использование функций в коде. Например, вы использовали
datasets.datasetssиdatasets.datasets, но это не является корректным способом генерации данных из .
-