Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 不使用scikit学习的列车测试拆分_Python_Numpy_Scikit Learn_Scipy - Fatal编程技术网

Python 不使用scikit学习的列车测试拆分

Python 不使用scikit学习的列车测试拆分,python,numpy,scikit-learn,scipy,Python,Numpy,Scikit Learn,Scipy,我有一个房价预测数据集。我必须将数据集分为train和test 我想知道是否可以使用numpy或scipy? 我现在无法使用scikit学习 import numpy as np import pandas as pd X_data = pd.read_csv('house.csv') Y_data = X_data["prices"] X_data.drop(["offers", "brick", "bathrooms", "prices"], axis=1, in

我有一个房价预测数据集。我必须将数据集分为
train
test

我想知道是否可以使用
numpy
scipy

我现在无法使用
scikit
学习

import numpy as np
import pandas as pd

X_data = pd.read_csv('house.csv')
Y_data = X_data["prices"]
X_data.drop(["offers", "brick", "bathrooms", "prices"], 
            axis=1, inplace=True) # important to drop prices as well

# create random train/test split
indices = range(X_data.shape[0])
num_training_instances = int(0.8 * X_data.shape[0])
np.random.shuffle(indices)
train_indices = indices[:num_training_indices]
test_indices = indices[num_training_indices:]

# split the actual data
X_data_train, X_data_test = X_data.iloc[train_indices], X_data.iloc[test_indices]
Y_data_train, Y_data_test = Y_data.iloc[train_indices], Y_data.iloc[test_indices]
这假设您想要随机拆分。发生的情况是,我们正在创建一个索引列表,只要有数据点的数量,即X_数据(或Y_数据)的第一个轴。然后,我们将它们按随机顺序排列,只取这些随机指标中的前80%作为训练数据,其余用于测试
[:num\u training\u index]
只需从列表中选择第一个num\u training\u index。在这之后,您只需使用随机索引列表从数据中提取行,数据就会被拆分。请记住,如果希望分割是可复制的,请从X_数据中删除价格并设置种子(
np.random.seed(一些整数)
)。

此代码应该有效(假设X_数据是一个数据帧):


希望这有帮助

此解决方案仅使用pandas和numpy

def split_train_valid_test(data,valid_ratio,test_ratio):
    shuffled_indcies=np.random.permutation(len(data))
    valid_set_size= int(len(data)*valid_ratio)
    valid_indcies=shuffled_indcies[:valid_set_size]
    test_set_size= int(len(data)*test_ratio)
    test_indcies=shuffled_indcies[valid_set_size:test_set_size+valid_set_size]
    train_indices=shuffled_indcies[test_set_size:]
    return data.iloc[train_indices],data.iloc[valid_indcies],data.iloc[test_indcies]

train_set,valid_set,test_set=split_train_valid_test(dataset,valid_ratio=0.2,test_ratio=0.2)
print(len(train_set),len(valid_set),len(test_set))
##out: (16512, 4128, 4128)

我知道你的问题只是用
numpy
scipy
进行一次列车测试,但实际上有一种非常简单的方法可以用熊猫进行测试:

将熊猫作为pd导入
#洗牌你的数据集
洗牌_df=df.样本(分形=1)
#为列车组定义一个尺寸
列车尺寸=整数(0.7*len(df))
#分割数据集
训练集=洗牌[训练大小]
测试集=洗牌df[序列大小:]

对于那些想要快速简便解决方案的人

虽然这是个老问题,但这个答案可能会有所帮助

这就是sklearn如何实现
train\u test\u split
,下面给出的方法采用了与sklearn类似的参数

import numpy as np
from itertools import chain

def _indexing(x, indices):
    """
    :param x: array from which indices has to be fetched
    :param indices: indices to be fetched
    :return: sub-array from given array and indices
    """
    # np array indexing
    if hasattr(x, 'shape'):
        return x[indices]

    # list indexing
    return [x[idx] for idx in indices]

def train_test_split(*arrays, test_size=0.25, shufffle=True, random_seed=1):
    """
    splits array into train and test data.
    :param arrays: arrays to split in train and test
    :param test_size: size of test set in range (0,1)
    :param shufffle: whether to shuffle arrays or not
    :param random_seed: random seed value
    :return: return 2*len(arrays) divided into train ans test
    """
    # checks
    assert 0 < test_size < 1
    assert len(arrays) > 0
    length = len(arrays[0])
    for i in arrays:
        assert len(i) == length

    n_test = int(np.ceil(length*test_size))
    n_train = length - n_test

    if shufffle:
        perm = np.random.RandomState(random_seed).permutation(length)
        test_indices = perm[:n_test]
        train_indices = perm[n_test:]
    else:
        train_indices = np.arange(n_train)
        test_indices = np.arange(n_train, length)

    return list(chain.from_iterable((_indexing(x, train_indices), _indexing(x, test_indices)) for x in arrays))
将numpy导入为np
来自itertools进口链
定义索引(x,索引):
"""
:param x:必须从中提取索引的数组
:param index:要获取的索引
:return:给定数组和索引的子数组
"""
#np数组索引
如果hasattr(x,'形状'):
返回x[指数]
#列表索引
返回[x[idx]用于索引中的idx]
def序列测试分割(*阵列,测试大小=0.25,shufffle=真,随机种子=1):
"""
将阵列拆分为训练和测试数据。
:param数组:要在训练和测试中拆分的数组
:param test_size:范围(0,1)内的测试集大小
:param shufffle:是否洗牌数组
:param random_seed:随机种子值
:return:返回2*len(阵列),分为列ans测试
"""
#检查
断言00
长度=len(数组[0])
对于阵列中的i:
断言len(i)=长度
n_测试=int(np.ceil(长度*测试大小))
n_列=长度-n_测试
如果shuffle:
perm=np.random.RandomState(随机种子)。排列(长度)
测试指数=perm[:n\u测试]
列车索引=perm[n\u测试:]
其他:
列车指数=np.arange(n列车)
测试指数=np.arange(n列,长度)
返回列表(数组中x的链自可编((_索引(x,序列索引),_索引(x,测试索引))))

当然,sklearn的实现支持分层k折叠、熊猫系列拆分等。这一个仅适用于拆分列表和numpy数组,我认为这对您的情况适用。

我想在80%的培训到20%的测试中拆分它。那么代码是什么呢?如果要将其拆分为80%到20%,请将num_train_examples变量的值设置为数据集中行数的80%。如果您有100行,您会将其设置为80。@jaguar您能解释一下所有数据吗[:num\u train\u examples]?我们在切吗?还有其他我能读到的资料吗?@CODE\u DIY我相信所有的数据都是你的数据集,你正在对它进行切片,但是你不能用这样一个简单的切片来切片熊猫数据帧。我将发布一个答案,希望能帮助更多。@CODE\u DIY请检查我的答案,我认为这可能会帮助更多。谢谢。还有一个问题。在顶行中,我有列标签。我想我需要把它们去掉。对吗?@CODE_DIY是的,你应该删除列标签。我建议您保存列标签并说:df.columns=[(在此处插入列标签)]。
import numpy as np
from itertools import chain

def _indexing(x, indices):
    """
    :param x: array from which indices has to be fetched
    :param indices: indices to be fetched
    :return: sub-array from given array and indices
    """
    # np array indexing
    if hasattr(x, 'shape'):
        return x[indices]

    # list indexing
    return [x[idx] for idx in indices]

def train_test_split(*arrays, test_size=0.25, shufffle=True, random_seed=1):
    """
    splits array into train and test data.
    :param arrays: arrays to split in train and test
    :param test_size: size of test set in range (0,1)
    :param shufffle: whether to shuffle arrays or not
    :param random_seed: random seed value
    :return: return 2*len(arrays) divided into train ans test
    """
    # checks
    assert 0 < test_size < 1
    assert len(arrays) > 0
    length = len(arrays[0])
    for i in arrays:
        assert len(i) == length

    n_test = int(np.ceil(length*test_size))
    n_train = length - n_test

    if shufffle:
        perm = np.random.RandomState(random_seed).permutation(length)
        test_indices = perm[:n_test]
        train_indices = perm[n_test:]
    else:
        train_indices = np.arange(n_train)
        test_indices = np.arange(n_train, length)

    return list(chain.from_iterable((_indexing(x, train_indices), _indexing(x, test_indices)) for x in arrays))