SKLERN多类分类

2024-10-01 02:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了以下代码从文件中导入数据向量并测试SVM分类器的性能(使用sklearn和python)。在

然而,分类器的性能比任何其他分类器都要低(例如,NNet在测试数据上的准确率为98%,但这最多只能达到92%)。根据我的经验,支持向量机对这类数据应该能产生更好的结果。在

我可能做错什么了吗?在

import numpy as np

def buildData(featureCols, testRatio):
    f = open("car-eval-data-1.csv")
    data = np.loadtxt(fname = f, delimiter = ',')

    X = data[:, :featureCols]  # select columns 0:featureCols-1
    y = data[:, featureCols]   # select column  featureCols 

    n_points = y.size
    print "Imported " + str(n_points) + " lines."

    ### split into train/test sets
    split = int((1-testRatio) * n_points)
    X_train = X[0:split,:]
    X_test  = X[split:,:]
    y_train = y[0:split]
    y_test  = y[split:]

    return X_train, y_train, X_test, y_test

def buildClassifier(features_train, labels_train):
    from sklearn import svm

    #clf = svm.SVC(kernel='linear',C=1.0, gamma=0.1)
    #clf = svm.SVC(kernel='poly', degree=3,C=1.0, gamma=0.1)
    clf = svm.SVC(kernel='rbf',C=1.0, gamma=0.1)
    clf.fit(features_train, labels_train)
    return clf

def checkAccuracy(clf, features, labels):
    from sklearn.metrics import accuracy_score

    pred = clf.predict(features)
    accuracy = accuracy_score(pred, labels)
    return accuracy

features_train, labels_train, features_test, labels_test = buildData(6, 0.3)
clf           = buildClassifier(features_train, labels_train)
trainAccuracy = checkAccuracy(clf, features_train, labels_train)
testAccuracy  = checkAccuracy(clf, features_test, labels_test)
print "Training Items: " + str(labels_train.size) + ", Test Items: " + str(labels_test.size)
print "Training Accuracy: " + str(trainAccuracy)
print "Test Accuracy: " + str(testAccuracy)

i = 0
while i < labels_test.size:
  pred = clf.predict(features_test[i])
  print "F(" + str(i) + ") : " + str(features_test[i]) + " label= " + str(labels_test[i]) + " pred= " + str(pred);
  i = i + 1

如果默认情况下不进行多类别分类,怎么可能进行多类别分类?在

注:我的数据格式如下(最后一列为类):

^{pr2}$

Tags: testdatasizelabels分类器trainsplitfeatures
1条回答
网友
1楼 · 发布于 2024-10-01 02:38:26

我发现问题后很久,我把它张贴出来,以防有人需要它。在

问题是数据导入函数不会洗牌数据。如果数据是以某种方式排序的,那么就存在这样的风险:用一些数据训练分类器,然后用完全不同的数据测试它。在NNet的情况下,使用Matlab对输入数据进行自动洗牌。在

def buildData(filename, featureCols, testRatio):
f = open(filename)
data = np.loadtxt(fname = f, delimiter = ',')
np.random.shuffle(data)    # randomize the order

X = data[:, :featureCols]  # select columns 0:featureCols-1
y = data[:, featureCols]   # select column  featureCols 

n_points = y.size
print "Imported " + str(n_points) + " lines."

### split into train/test sets
split = int((1-testRatio) * n_points)
X_train = X[0:split,:]
X_test  = X[split:,:]
y_train = y[0:split]
y_test  = y[split:]

return X_train, y_train, X_test, y_test

相关问题 更多 >