【问题标题】:Initialize training set in Pandas with Python [closed]使用 Python 在 Pandas 中初始化训练集 [关闭]
【发布时间】:2019-01-28 10:59:28
【问题描述】:

我正在研究随机森林算法,并根据this post 的指令构建分类器

我有以下代码段

import pandas as pd
import numpy as np
# Import train_test_split function
from sklearn.model_selection import train_test_split

data=pd.DataFrame({
'sepal length':iris.data[:,0],
'sepal width':iris.data[:,1],
'petal length':iris.data[:,2],
'petal width':iris.data[:,3],
'species':iris.target}

X=data[['sepal length', 'sepal width', 'petal length', 'petal width']]  # Features
y=data['species']  # Labels

# Split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 70% training and 30% test

我正在使用从sklearn 导入的iris 数据集。但是,每当我运行此代码时,都会出现以下 错误

File "<ipython-input-11-71013f105652>", line 12
X=data[['sepal length', 'sepal width', 'petal length', 'petal width']]  # Features
^
SyntaxError: invalid syntax

我认为这个错误是因为我以错误的方式初始化了X 列表,它充当了Feature

问题是代码中的拼写错误

【问题讨论】:

  • 这是因为您没有关闭 DataFrame 上的括号。 'species':iris.target -> 'species':iris.target})

标签: python pandas scikit-learn


【解决方案1】:

您似乎缺少 pd.DataFrame() 的结尾“})”

from sklearn import datasets
iris = datasets.load_iris()
data = pd.DataFrame({
    'sepal length':iris.data[:,0],
    'sepal width':iris.data[:,1],
    'petal length':iris.data[:,2],
    'petal width':iris.data[:,3],
    'species':iris.target
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 2016-11-16
    • 2014-02-12
    相关资源
    最近更新 更多