基于 Python 中较小的数据集生成较大的综合数据集

2023-12-30

我有一个包含 21000 行(数据样本)和 102 列(特征)的数据集。我希望根据当前数据集生成一个更大的合成数据集,例如 100000 行,这样我就可以将其用于机器学习目的。

我在这篇文章中提到了 @Prashant 的答案https://stats.stackexchange.com/questions/215938/generate-synthetic-data-to-match-sample-data https://stats.stackexchange.com/questions/215938/generate-synthetic-data-to-match-sample-data,但我无法让它为我的数据生成更大的合成数据集。

import numpy as np
from random import randrange, choice
from sklearn.neighbors import NearestNeighbors
import pandas as pd
#referring to https://stats.stackexchange.com/questions/215938/generate-synthetic-data-to-match-sample-data


df = pd.read_pickle('df_saved.pkl')
df = df.iloc[:,:-1] # this gives me df, the final Dataframe which I would like to generate a larger dataset based on. This is the smaller Dataframe with 21000x102 dimensions.


def SMOTE(T, N, k):
# """
# Returns (N/100) * n_minority_samples synthetic minority samples.
#
# Parameters
# ----------
# T : array-like, shape = [n_minority_samples, n_features]
#     Holds the minority samples
# N : percetange of new synthetic samples:
#     n_synthetic_samples = N/100 * n_minority_samples. Can be < 100.
# k : int. Number of nearest neighbours.
#
# Returns
# -------
# S : array, shape = [(N/100) * n_minority_samples, n_features]
# """
    n_minority_samples, n_features = T.shape

    if N < 100:
       #create synthetic samples only for a subset of T.
       #TODO: select random minortiy samples
       N = 100
       pass

    if (N % 100) != 0:
       raise ValueError("N must be < 100 or multiple of 100")

    N = N/100
    n_synthetic_samples = N * n_minority_samples
    n_synthetic_samples = int(n_synthetic_samples)
    n_features = int(n_features)
    S = np.zeros(shape=(n_synthetic_samples, n_features))

    #Learn nearest neighbours
    neigh = NearestNeighbors(n_neighbors = k)
    neigh.fit(T)

    #Calculate synthetic samples
    for i in range(n_minority_samples):
       nn = neigh.kneighbors(T[i], return_distance=False)
       for n in range(N):
          nn_index = choice(nn[0])
          #NOTE: nn includes T[i], we don't want to select it
          while nn_index == i:
             nn_index = choice(nn[0])

          dif = T[nn_index] - T[i]
          gap = np.random.random()
          S[n + i * N, :] = T[i,:] + gap * dif[:]

    return S

df = df.to_numpy()
new_data = SMOTE(df,50,10) # this is where I call the function and expect new_data to be generated with larger number of samples than original df.

我得到的错误的回溯如下所述:-

Traceback (most recent call last):
  File "MyScript.py", line 66, in <module>
    new_data = SMOTE(df,50,10)
  File "MyScript.py", line 52, in SMOTE
    nn = neigh.kneighbors(T[i], return_distance=False)
  File "/trinity/clustervision/CentOS/7/apps/anaconda/4.3.31/3.6-VE/lib/python3.5/site-packages/sklearn/neighbors/base.py", line 393, in kneighbors
    X = check_array(X, accept_sparse='csr')
  File "/trinity/clustervision/CentOS/7/apps/anaconda/4.3.31/3.6-VE/lib/python3.5/site-packages/sklearn/utils/validation.py", line 547, in check_array
    "if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:

我知道这个错误(预期的二维数组,得到一维数组)发生在线路上nn = neigh.kneighbors(T[i], return_distance=False)。准确地说,当我调用该函数时,T 是numpy形状数组 (21000x102),我从 Pandas Dataframe 转换为numpy大批。我知道这个问题可能有一些类似的重复项,但没有一个回答我的问题。在这方面的任何帮助将不胜感激。


所以 T[i] 给出的是一个形状为 (102, ) 的数组。

该函数期望的是形状为 (1, 102) 的数组。

您可以通过调用 reshape 来获得它:

nn = neigh.kneighbors(T[i].reshape(1, -1), return_distance=False)

如果您不熟悉 np.reshape,1 表示第一个维度应为 1,而 -1 表示第二个维度应为 numpy 可以广播到的任何大小;在本例中为原始 102。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

基于 Python 中较小的数据集生成较大的综合数据集 的相关文章

随机推荐