如何仅使用 numpy 而不是 pandas 将数据拆分为训练和测试集
pytorch 254
原文标题 :How to split data into training and testing set only using numpy not pandas
我正在做 CNN 并尝试将我的数据拆分为训练和测试数据集。拆分后,我想用sklearn.preprocessing.StandardScaler
用训练数据的参数来缩放我的测试数据。
所以在缩放之前,我需要拆分数据。我将使用sklearn.model_selection.train_test_split
,但要使用该方法,我必须将我的数据转换为pandas.DataFrame
。由于我的数据是针对 CNN 的,因此它们的长度不符合 DataFrame 的要求
print(x.shape, delta.shape, z.shape, y.shape, non_spatial_data.shape, p.shape, g.shape)
# (15000, 175) (15000, 175) (15000, 175) (15000, 1225) (15000, 264) (15000, 175) (15000, 175)
以上是我的数据被展平后的大小。15000是样本大小。你可以看到不同数据的长度是不同的,这导致我无法将它们转换成DataFrame。那么我怎样才能只使用numpy进行拆分呢?还是有其他方法可以进行整体拆分和缩放过程?
PS:我用于 CNN 的数据并不是真正的图像。它们是一些具有空间属性的数据。
回复
我来回复-
svfat 评论
该回答已被采纳!
这是工作示例:
import pandas as pd import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) b = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) c = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) n = 0.2 spl = None for arr in [a, b, c]: if spl is None: rand_ind = np.random.choice(range(len(arr)), len(arr)) spl, remaining = np.split(rand_ind, [int(n * len(rand_ind))]) print([arr[i] for i in spl])
2年前 -
Aaron Tseng 评论
来自Mr. svfat 的回答,我发现我想多了。我的问题也让 svfat 先生想多了。总之,要拆分数据,我们只需要随机选择一个固定比例的索引并将它们应用于每个数据的切片。
2年前