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

时间:2019-03-06 16:04:47

标签: python machine-learning scikit-learn imputation

我有一个包含21000行(数据样本)和102列(功能)的数据集。我想基于当前数据集生成一个更大的综合数据集,比如说有100000行,因此可以将其用于机器学习。

在这篇帖子https://stats.stackexchange.com/questions/215938/generate-synthetic-data-to-match-sample-data上,我一直指的是@Prashant的答案,但是无法为我的数据生成更大的综合数据集。

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)上发生此错误(预期2D数组,得到1D数组)。准确地讲,当我调用该函数时,T是numpy形状的数组(21000x102),即我从Pandas Dataframe转换为numpy数组的数据。我知道这个问题可能有一些重复,但是没有一个回答我的问题。在这方面的任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

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

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

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

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

如果您不熟悉np.reshape,则1表示第一个尺寸应为1,而-1表示第二个尺寸应为numpy可以广播到的尺寸;在这种情况下是原始的102。

答案 1 :(得分:1)

可能对您有用

SMOTE and other advanced over_sampling techniques

此软件包imblearn具有类似于API的sklearn和许多过采样技术。

答案 2 :(得分:0)

我有同样的问题。我研究了一段时间,但找不到合适的解决方案,然后尝试将自己的解决方案应用于此问题。它对我有帮助,我希望它对所有有相同问题的人都有效。

columns = df.columns.to_numpy()
iteration_count = 30
new_df = pd.DataFrame(columns=columns)

for i in range(iteration_count):
    for k in df.iterrows():
        data_obj = {}
        for j in range(columns.size):
            random_index = np.random.randint(0,13, dtype='int')
            data_obj[columns[j]] = df.loc[random_index][columns[j]]
        new_df = new_df.append(data_obj, ignore_index=True)

df = df.append(new_df, ignore_index=True)