【问题标题】:How do I get data into the ndarray format for SKLearn?如何将数据转换为 SKLearn 的 ndarray 格式?
【发布时间】:2016-11-11 16:31:32
【问题描述】:

Scikit-Learn 是一个很棒的 Python 模块,它为 support vector machine 提供了许多算法。过去几天我一直在学习如何使用该模块,我注意到它在很大程度上依赖于单独的 numpy 模块。

我了解该模块的作用,但我仍在了解它的工作原理。这是我使用sklearn 的一个非常简短的示例:

from sklearn import datasets, svm
import numpy

digits = datasets.load_digits() #image pixel data of digits 0-9 as well as a chart of the corresponding digit to each image

clf = svm.SVC(gamma=0.001,C=100) #SVC is the algorithm used for classifying this type of data

x,y = digits.data[:-1], digits.target[:-1] #feed it all the data
clf.fit(x,y) #"train" the SVM

print(clf.predict(digits.data[0])) #>>>[0]
#with 99% accuracy, all of the data consists of 1797 samples.
#if this number gets smaller, the accuracy decreases. with 10 samples (0-9),
#accuracy can still be up to as high as 90%.

这是非常基本的分类。 有 10 个类:0,1,2,3,4,5,6,7,8,9。

在 matplotlib.pyplot 中使用以下代码:

import matplotlib.pyplot as plt #in shell after running previous code
plt.imshow(digits.images[0],cmap=plt.cm.gray_r,interpolation="nearest")
plt.show()

给出以下图像:

第一个像素(从左到右,从上到下,如阅读)将由 0 表示。第二个相同,但第三个将由 7 或其他值表示(范围是 0 到 15),第四个是大约 13。这是图像的实际数据:

[[  0.   0.   5.  13.   9.   1.   0.   0.]
 [  0.   0.  13.  15.  10.  15.   5.   0.]
 [  0.   3.  15.   2.   0.  11.   8.   0.]
 [  0.   4.  12.   0.   0.   8.   8.   0.]
 [  0.   5.   8.   0.   0.   9.   8.   0.]
 [  0.   4.  11.   0.   1.  12.   7.   0.]
 [  0.   2.  14.   5.  10.  12.   0.   0.]
 [  0.   0.   6.  13.  10.   0.   0.   0.]]

所以我的问题是:如果我想对文本数据进行分类,例如错误子论坛/类别中的论坛帖子,我将如何将该数据转换为此数据集示例中使用的数字系统?

【问题讨论】:

  • 您需要将其展平为单个向量。所以你的 numpy 数组将是 nx64,其中 n 是图像的数量,每一列代表图像中的一个像素。显然,这种图像表示会丢失很多有趣的信息,这就是为什么卷积神经网络通常在图像分类方面要优越得多的原因之一。

标签: python scikit-learn classification svm


【解决方案1】:

对于每个样本(例如每个论坛帖子),您必须有一个向量(在 python 中是一个列表)。例如,如果您有 200 个帖子及其各自的类别,则必须有 200 个用于训练数据的列表,并且每个 200 个类别必须有一个包含 200 个元素的列表。 每个培训类别列表都可以是一个模型(例如 Bag Of Word。请参见此处:https://en.wikipedia.org/wiki/Bag-of-words_model)。请注意,所有用于训练的列表必须具有相同的元素(相同的维度)(例如,每个列表必须有 3000 个元素,每个元素代表一个词的存在或不存在) 试试看这个,对初学者来说很容易:https://www.kaggle.com/c/word2vec-nlp-tutorial/details/part-1-for-beginners-bag-of-words

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2011-10-15
    相关资源
    最近更新 更多