当前位置: 首页>>代码示例>>Python>>正文


Python sklearn.svm方法代码示例

本文整理汇总了Python中sklearn.svm方法的典型用法代码示例。如果您正苦于以下问题:Python sklearn.svm方法的具体用法?Python sklearn.svm怎么用?Python sklearn.svm使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sklearn的用法示例。


在下文中一共展示了sklearn.svm方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fit_new_classifier

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def fit_new_classifier(problem, train_idx):
        """
        References:
            http://leon.bottou.org/research/stochastic
            http://blog.explainmydata.com/2012/06/ntrain-24853-ntest-25147-ncorrupt.html
            http://scikit-learn.org/stable/modules/svm.html#svm-classification
            http://scikit-learn.org/stable/modules/grid_search.html
        """
        print('[problem] train classifier on %d data points' % (len(train_idx)))
        data = problem.ds.data
        target = problem.ds.target
        x_train = data.take(train_idx, axis=0)
        y_train = target.take(train_idx, axis=0)
        clf = sklearn.svm.SVC(kernel=str('linear'), C=.17, class_weight='balanced',
                              decision_function_shape='ovr')

        # C, penalty, loss
        #param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
        #              'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
        #param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
        #              'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
        #clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)
        #clf = clf.fit(X_train_pca, y_train)
        clf.fit(x_train, y_train)
        return clf 
开发者ID:Erotemic,项目名称:ibeis,代码行数:27,代码来源:classify_shark.py

示例2: _create_classifier

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def _create_classifier(self, num_threads, y):
        from sklearn.model_selection import GridSearchCV
        from sklearn.svm import SVC

        C = self.component_config["C"]
        kernels = self.component_config["kernels"]
        gamma = self.component_config["gamma"]
        # dirty str fix because sklearn is expecting
        # str not instance of basestr...
        tuned_parameters = [{"C": C,
                             "gamma": gamma,
                             "kernel": [str(k) for k in kernels]}]

        # aim for 5 examples in each fold

        cv_splits = self._num_cv_splits(y)

        return GridSearchCV(SVC(C=1,
                                probability=True,
                                class_weight='balanced'),
                            param_grid=tuned_parameters,
                            n_jobs=num_threads,
                            cv=cv_splits,
                            scoring=self.component_config['scoring_function'],
                            verbose=1) 
开发者ID:weizhenzhao,项目名称:rasa_nlu,代码行数:27,代码来源:sklearn_intent_classifier.py

示例3: test_monkey_patching

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def test_monkey_patching(self):
        _tokens = daal4py.sklearn.sklearn_patch_names()
        self.assertTrue(isinstance(_tokens, list) and len(_tokens) > 0)
        for t in _tokens:
            daal4py.sklearn.unpatch_sklearn(t)
        for t in _tokens:
            daal4py.sklearn.patch_sklearn(t)

        import sklearn
        for a in [(sklearn.decomposition, 'PCA'),
                  (sklearn.linear_model, 'Ridge'),
                  (sklearn.linear_model, 'LinearRegression'),
                  (sklearn.cluster, 'KMeans'),
                  (sklearn.svm, 'SVC'),]:
            class_module = getattr(a[0], a[1]).__module__
            self.assertTrue(class_module.startswith('daal4py')) 
开发者ID:IntelPython,项目名称:daal4py,代码行数:18,代码来源:test_monkeypatch.py

示例4: _create_classifier

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def _create_classifier(self, num_threads, y):
        from sklearn.model_selection import GridSearchCV
        from sklearn.svm import SVC

        C = self.component_config["C"]
        kernels = self.component_config["kernels"]
        # dirty str fix because sklearn is expecting
        # str not instance of basestr...
        tuned_parameters = [{"C": C,
                             "kernel": [str(k) for k in kernels]}]

        # aim for 5 examples in each fold

        cv_splits = self._num_cv_splits(y)

        return GridSearchCV(SVC(C=1,
                                probability=True,
                                class_weight='balanced'),
                            param_grid=tuned_parameters,
                            n_jobs=num_threads,
                            cv=cv_splits,
                            scoring='f1_weighted',
                            verbose=1) 
开发者ID:crownpku,项目名称:Rasa_NLU_Chi,代码行数:25,代码来源:sklearn_intent_classifier.py

示例5: arg_parse

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def arg_parse():
    parser = argparse.ArgumentParser()
    parser.add_argument('-g', '--gpu', type=str, default='0', help='Use which gpu?')
    parser.add_argument('-d', '--dataset', type=str, help='Train on which dataset')
    parser.add_argument('-b','--bn',type=bool,default=False,help='whether to use BN layer')
    parser.add_argument('--model_path',type=str,help='Path to saved tensorflow CAE model')
    parser.add_argument('--graph_path',type=str,help='Path to saved object detection frozen graph model')
    parser.add_argument('--svm_model',type=str,help='Path to saved svm model')
    parser.add_argument('--dataset_folder',type=str,help='Dataset Fodlder Path')
    parser.add_argument('-c','--class_add',type=bool,default=False,help='Whether to add class one-hot embedding to the featrue')
    parser.add_argument('-n','--norm',type=int,default=0,help='Whether to use Normalization to the Feature and the normalization level')
    parser.add_argument('--test_CAE',type=bool,default=False,help='Whether to test CAE')
    parser.add_argument('--matlab',type=bool,default=False,help='Whether to use matlab weights and biases to test')
    args = parser.parse_args()
    return args 
开发者ID:fjchange,项目名称:object_centric_VAD,代码行数:17,代码来源:test.py

示例6: fit_new_linear_svm

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def fit_new_linear_svm(problem, train_idx):
        print('[problem] train classifier on %d data points' % (len(train_idx)))
        data = problem.ds.data
        target = problem.ds.target
        x_train = data.take(train_idx, axis=0)
        y_train = target.take(train_idx, axis=0)
        clf = sklearn.svm.SVC(kernel=str('linear'), C=.17, class_weight='balanced',
                              decision_function_shape='ovr')
        clf.fit(x_train, y_train) 
开发者ID:Erotemic,项目名称:ibeis,代码行数:11,代码来源:classify_shark.py

示例7: getModelNode

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def getModelNode(classifier):
    if classifier.startswith("svm"):
        node = "poolingLayer"
    else:
        node = []
    return(node) 
开发者ID:Azure-Samples,项目名称:MachineLearningSamples-ImageClassificationUsingCntk,代码行数:8,代码来源:helpers.py

示例8: runClassifier

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def runClassifier(classifier, dnnOutput, imgDict = [],  lutLabel2Id = [], svmPath = [], svm_boL2Normalize = []):
    # Run classifier on all known images, if not otherwise specified
    if imgDict == []:
        imgDict = {}
        for label in list(dnnOutput.keys()):
            imgDict[label] = list(dnnOutput[label].keys())

    # Compute SVM classification scores
    if classifier.startswith('svm'):
        learner = readPickle(svmPath)
        feats, gtLabels, imgFilenames = getSvmInput(imgDict, dnnOutput, svm_boL2Normalize, lutLabel2Id)
        print("Evaluate SVM...")
        scoresMatrix = learner.decision_function(feats)

        # If binary classification problem then manually create 2nd column
        # Note: scoresMatrix is of size nrImages x nrClasses
        if len(scoresMatrix.shape) == 1:
            scoresMatrix = [[-scoresMatrix[i],scoresMatrix[i]] for i in range(len(scoresMatrix))]
            scoresMatrix = np.array(scoresMatrix)

    # Get DNN classification scores
    else:
        gtLabels = []
        scoresMatrix = []
        imgFilenames = []
        for label in list(imgDict.keys()):
            for imgFilename in imgDict[label]:
                scores = dnnOutput[label][imgFilename]
                if lutLabel2Id == []:
                    gtLabels.append(label)
                else:
                    gtLabels.append(int(lutLabel2Id[label]))
                scoresMatrix.append(scores)
                imgFilenames.append(imgFilename)
        scoresMatrix = np.vstack(scoresMatrix)
    return scoresMatrix, imgFilenames, gtLabels 
开发者ID:Azure-Samples,项目名称:MachineLearningSamples-ImageClassificationUsingCntk,代码行数:38,代码来源:helpers.py

示例9: __init__

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def __init__(self, path):
        self.train_data  = []
        self.test_data   = []
        self.train_labels = []
        self.test_labels = []
        self.classification = []
        self.svm_classifier = svm.SVC(gamma=0.001, C=50,decision_function_shape='ovr',kernel='rbf')
        self.corpus_path = path
        self.corpus = {}
        self.vocab = [] 
开发者ID:skashyap7,项目名称:TBBTCorpus,代码行数:12,代码来源:svm-bagofWords.py

示例10: start_program

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def start_program():
    Total_correct = 0
    Total_labelled = 0
    clf = svm.SVC(gamma=0.001, C=50, kernel='rbf')
    train_features = []
    train_labels = []
    test_features = []
    test_labels = []
    for season in range(1,5):
        for episode in range(1,Season_Episode_Mapping[season]-4):
            features, labels = episode2feature(season,episode)
            train_features.extend(features)
            train_labels.extend(labels)
    #print(all_features)
    for season in range(5,8):
        for episode in range(Season_Episode_Mapping[season]-4,Season_Episode_Mapping[season]+1):
            features, labels = episode2feature(season,episode)
            test_features.extend(features)
            test_labels.extend(labels)
    #print(train_features)
    clf.fit(train_features,train_labels)
    result = clf.predict(test_features)


    txt = "\n Speaker\tPrecision\tRecall\t\tF1\n"
    for i in range(1,7):
        precision, recall,f1_score,correct,total = get_stats(result, train_labels,i)
        Total_correct += correct
        Total_labelled += total
        txt += speaker_rev_enum[i]+"\t\t"+ str(format(precision,'.2f'))+"\t\t"+str(format(recall,'.2f'))+"\t\t"+str(format(f1_score,'.2f'))+"\n"
    with open("output.txt","w") as fh:
        fh.write(txt)
    print("Accuracy of the system is : "+str(Total_correct/Total_labelled)) 
开发者ID:skashyap7,项目名称:TBBTCorpus,代码行数:35,代码来源:svmClassifier.py

示例11: init_classifier_impl

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def init_classifier_impl(field_code: str, init_script: str):
    if init_script is not None:
        init_script = init_script.strip()

    if not init_script:
        from sklearn import tree as sklearn_tree
        return sklearn_tree.DecisionTreeClassifier()

    from sklearn import tree as sklearn_tree
    from sklearn import neural_network as sklearn_neural_network
    from sklearn import neighbors as sklearn_neighbors
    from sklearn import svm as sklearn_svm
    from sklearn import gaussian_process as sklearn_gaussian_process
    from sklearn.gaussian_process import kernels as sklearn_gaussian_process_kernels
    from sklearn import ensemble as sklearn_ensemble
    from sklearn import naive_bayes as sklearn_naive_bayes
    from sklearn import discriminant_analysis as sklearn_discriminant_analysis
    from sklearn import linear_model as sklearn_linear_model

    eval_locals = {
        'sklearn_linear_model': sklearn_linear_model,
        'sklearn_tree': sklearn_tree,
        'sklearn_neural_network': sklearn_neural_network,
        'sklearn_neighbors': sklearn_neighbors,
        'sklearn_svm': sklearn_svm,
        'sklearn_gaussian_process': sklearn_gaussian_process,
        'sklearn_gaussian_process_kernels': sklearn_gaussian_process_kernels,
        'sklearn_ensemble': sklearn_ensemble,
        'sklearn_naive_bayes': sklearn_naive_bayes,
        'sklearn_discriminant_analysis': sklearn_discriminant_analysis
    }
    return eval_script('classifier init script of field {0}'.format(field_code), init_script, eval_locals) 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:34,代码来源:field_based_ml_field_detection.py

示例12: svm_example

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def svm_example(n_samples = 10000, n_features = 100):
	from sklearn.svm import SVR
	from sklearn.datasets import make_regression

	X,Y = make_regression(n_samples, n_features)
	m = SVR()

	m.fit(X,Y) 
开发者ID:sfalkner,项目名称:pynisher,代码行数:10,代码来源:unit_tests.py

示例13: svc_example

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def svc_example(n_samples = 10000, n_features = 4):
	from sklearn.svm import LinearSVC
	from sklearn.preprocessing import PolynomialFeatures
	from sklearn.datasets import make_classification
	
	X,Y = make_classification(n_samples, n_features)
	#pp = PolynomialFeatures(degree=3)
	
	#X = pp.fit_transform(X)
	m = LinearSVC()
	m.fit(X,Y) 
开发者ID:sfalkner,项目名称:pynisher,代码行数:13,代码来源:unit_tests.py

示例14: run

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def run(self):
        df_train = self.input().load()
        if self.model=='ols':
            model = sklearn.linear_model.LogisticRegression()
        elif self.model=='svm':
            model = sklearn.svm.SVC()
        else:
            raise ValueError('invalid model selection')
        model.fit(df_train.iloc[:,:-1], df_train['y'])
        self.save(model)

# Check task dependencies and their execution status 
开发者ID:d6t,项目名称:d6tflow,代码行数:14,代码来源:example.py

示例15: svm

# 需要导入模块: import sklearn [as 别名]
# 或者: from sklearn import svm [as 别名]
def svm(K1, K2, y1, y2, C, c):
    n_val, n_train = K2.shape
    clf = SVC(kernel = "precomputed", C = C, cache_size = 100000)
    clf.fit(K1, y1)
    z = clf.predict(K2)
    return 1.0 * np.sum(z == y2) / n_val 
开发者ID:LeoYu,项目名称:neural-tangent-kernel-UCI,代码行数:8,代码来源:tools.py


注:本文中的sklearn.svm方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。