【问题标题】:create a matrix with a matrix + vector (features + label)创建一个矩阵+向量(特征+标签)的矩阵
【发布时间】:2019-06-10 17:02:45
【问题描述】:

如何在 Python 中创建具有特征和标签的新矩阵?例如。在 scikit-learn 中:我如何“看到”(打印)一个带有特征 + 标签的新表:[5. 2.5 1.5 0.2 0] 其中最后一个 0 是该样本的标签。另外:我创建了训练和测试数据集——我如何用训练或测试集成员“标记”基本数据? (我是 Python 新手)

feature matrix
    [[5.1 3.5 1.4 0.2]
     [4.9 3.  1.4 0.2]
     [4.7 3.2 1.3 0.2]
     [4.6 3.1 1.5 0.2]]

    label vector
    [0 1 0 2]

     how can I "put" together into one matrix?
    [[5.1 3.5 1.4 0.2 0]
     [4.9 3.  1.4 0.2 1]
     [4.7 3.2 1.3 0.2 0]
     [4.6 3.1 1.5 0.2 2]]

代码:

from sklearn.datasets import load_iris
iris_dataset = load_iris()

print ((iris_dataset['data']))
print ((iris_dataset['target']))

print("Type of data: {}".format(type(iris_dataset['data'])))
print("Type of target: {}".format(type(iris_dataset['target'])))


Type of data: <class 'numpy.ndarray'>
Type of target: <class 'numpy.ndarray'>

【问题讨论】:

  • 这些是列表还是 numpy 数组?您能否发布一个minimal reproducible example,最好是可以进行这些示例输入的python代码,以便我们可以复制粘贴并自己运行代码?
  • 您可以使用np.c_[iris_dataset['data'], iris_dataset['target']]。但是,我不确定这是否真的是你想要做的......

标签: python scikit-learn


【解决方案1】:

您可以使用 numpy hstack 以这种方式轻松连接数组。

from sklearn.datasets import load_iris
iris_dataset = load_iris()

print(iris_dataset['data'].shape)
print(iris_dataset['target'].shape)

import numpy as np
result = np.hstack((iris_dataset['data'], iris_dataset['target'].reshape(-1, 1)))

print(result.shape)

#Output:
(150, 4)
(150,)
(150, 5)

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 2018-10-12
    • 2011-09-29
    • 1970-01-01
    • 2019-04-27
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多