更改由sklearn.model_selection.train_test_split生成的数组中的值类型

Mr.*_*ent 6 python arrays python-3.x scikit-learn

我正在做关于机器学习的本教程,其中使用了以下代码:

import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv('breast-cancer-wisconsin.data.csv')
df.replace('?', -99999, inplace = True)
df.drop(['id'], 1, inplace = True)
X = np.array(df.drop(['class'], 1))
y = np.array(df['class'])

X_train, X_test, y_test, y_train = train_test_split(X, y)
Run Code Online (Sandbox Code Playgroud)

以下是csv文件中的示例:

id,clump_thickness,unif_cell_size,unif_cell_shape, marg_adhesion,
single_epith_cell_size,bare_nuclei,bland_chrom,norm_nucleoli, mitoses,class
    1000025,5,1,1,1,2,1,3,1,1,2
    1002945,5,4,4,5,7,10,3,2,1,2
    1015425,3,1,1,1,2,2,3,1,1,2
    1016277,6,8,8,1,3,4,3,7,1,2
    1017023,4,1,1,3,2,1,3,1,1,2
    1017122,8,10,10,8,7,10,9,7,1,4
    1018099,1,1,1,1,2,10,3,1,1,2
    1018561,2,1,2,1,2,1,3,1,1,2
    1033078,2,1,1,1,2,1,1,1,5,2
    1033078,4,2,1,1,2,1,2,1,1,2
    1035283,1,1,1,1,1,1,3,1,1,2
    1036172,2,1,1,1,2,1,2,1,1,2
    1041801,5,3,3,3,2,3,4,4,1,4
    1043999,1,1,1,1,2,3,3,1,1,2
    1044572,8,7,5,10,7,9,5,5,4,4
    1047630,7,4,6,4,6,1,4,3,1,4
    1048672,4,1,1,1,2,1,2,1,1,2
    1049815,4,1,1,1,2,1,3,1,1,2
    1050670,10,7,7,6,4,10,4,1,2,4
    1050718,6,1,1,1,2,1,3,1,1,2
    1054590,7,3,2,10,5,10,5,4,4,4
    1054593,10,5,5,3,6,7,7,10,1,4
    1056784,3,1,1,1,2,1,2,1,1,2
    1057013,8,4,5,1,2,?,7,3,1,4
    1059552,1,1,1,1,2,1,3,1,1,2
    1065726,5,2,3,4,2,7,3,6,1,4
    1066373,3,2,1,1,1,1,2,1,1,2
Run Code Online (Sandbox Code Playgroud)

在查看结果时,sklearn.model_selection.train_test_split我发现了一些奇怪的东西(至少对我而言).如果我跑

    print(type(y_test[0]))
    print()
    print(type(X_train[:,1][0]))
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

<class 'numpy.int64'>
<class 'int'>
Run Code Online (Sandbox Code Playgroud)

不知何故,X_train类型中int的值和类型中的值y_test都是numpy.int64.我不知道为什么train_test_split会这样 - 我不认为它与被拆分的数据有关 - 而且文档似乎也没有提到它.

因为我希望值in y_test也是常规整数,所以我尝试更改y_testwith 的类型astype().不幸的是,以下代码

y_test = y_test.astype(int)
print(type(y_test[0]))
Run Code Online (Sandbox Code Playgroud)

回报

<class 'numpy.int64'>
Run Code Online (Sandbox Code Playgroud)

问题:为什么train_test_split返回数组包含具有不同类型数据类型的值?为什么我无法将值转换y_test为整数?

编辑:类型的差异是由数据引起的.如果我跑

 print(type(X[:,1][0]))
 print(type(y[0])) 
Run Code Online (Sandbox Code Playgroud)

我明白了

<class 'int'>
<class 'numpy.int64'>
Run Code Online (Sandbox Code Playgroud)

我仍然想知道为什么astype不起作用!:)

STJ*_*STJ 1

要将 numpy 值转换为 python 类型,可以使用numpy.ndarray.item

y_test_int = [v.item() for v in y_test]
print(type(y_test_int[0]))
#<class 'int'>
Run Code Online (Sandbox Code Playgroud)