我最近开始学习Python用于机器学习目的,但遇到了一个问题。我使用 Pandas 从 .csv 文件输入数据,并将行值转换为数字数组。我需要将这些数组传递给 sklearn 函数。我的代码在这里:
# Imports
import pandas as pd
import numpy as np
import sklearn
import os
import seaborn as seabornInstance
import matplotlib.pyplot as plt
from sklearn import preprocessing
# Dataset input
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'Datasets', 'car.data')
data = pd.read_csv(filename)
label_encoder = preprocessing.LabelEncoder()
# Transforming text
x = [label_encoder.fit_transform(list(data[col])) for col in data.columns if col!='class']
y = [label_encoder.fit_transform(list(data['class']))]
问题现在就到这里了。我需要访问 x 内部的嵌套数组并将它们放入我的 sklearn 函数中,因为在那里安装 'x' 会引发错误:
ValueError: Found input variables with inconsistent numbers of samples: [6, 1]
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x[0], y[0], test_size = 0.08)
有没有办法将所有嵌套数组作为 x 传递而不是整个 x 而不写入 x[0],x[1],..?我认为使用循环是行不通的,因为我需要一次性传递所有内容,还是我错了?
编辑:我导入的数据不是数字(字符串),这就是为什么我使用 label_encoder 将这些值转换为数字以在 KNN 算法中使用。
最佳答案
我认为你让事情变得不必要的复杂化。您也不应该对 x
变量进行标签编码。顾名思义,它用于标签,而不是预测变量。对于您的 x
变量,您应该使用以下行:
x = df.loc[:, [i for i in df.columns if i != 'class']]
# or
x = df.drop('class', axis=1)
对于你的y
变量:
y = label_encoder.fit_transform(df['class'])
关于python - 将嵌套列表传递给 sklearn split 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59140691/