本文整理匯總了Python中sklearn.svm.NuSVC方法的典型用法代碼示例。如果您正苦於以下問題:Python svm.NuSVC方法的具體用法?Python svm.NuSVC怎麽用?Python svm.NuSVC使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sklearn.svm
的用法示例。
在下文中一共展示了svm.NuSVC方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __call__
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def __call__(self, estimator):
fitted_estimator = estimator.fit(self.X_train, self.y_train)
if isinstance(estimator, (LinearClassifierMixin, SVC, NuSVC,
LightBaseClassifier)):
y_pred = estimator.decision_function(self.X_test)
elif isinstance(estimator, DecisionTreeClassifier):
y_pred = estimator.predict_proba(self.X_test.astype(np.float32))
elif isinstance(
estimator,
(ForestClassifier, XGBClassifier, LGBMClassifier)):
y_pred = estimator.predict_proba(self.X_test)
else:
y_pred = estimator.predict(self.X_test)
return self.X_test, y_pred, fitted_estimator
示例2: test_probability
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_probability():
# Predict probabilities using SVC
# This uses cross validation, so we use a slightly bigger testing set.
for clf in (svm.SVC(gamma='scale', probability=True, random_state=0,
C=1.0), svm.NuSVC(gamma='scale', probability=True,
random_state=0)):
clf.fit(iris.data, iris.target)
prob_predict = clf.predict_proba(iris.data)
assert_array_almost_equal(
np.sum(prob_predict, 1), np.ones(iris.data.shape[0]))
assert np.mean(np.argmax(prob_predict, 1)
== clf.predict(iris.data)) > 0.9
assert_almost_equal(clf.predict_proba(iris.data),
np.exp(clf.predict_log_proba(iris.data)), 8)
示例3: test
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test(X_new):
"""
3 test cases to be passed
an array containing the sepal length (cm), sepal width (cm), petal length (cm),
petal width (cm) based on which the target name will be predicted
>>> test([1,2,1,4])
'virginica'
>>> test([5, 2, 4, 1])
'versicolor'
>>> test([6,3,4,1])
'versicolor'
"""
iris = load_iris()
# splitting the dataset to test and train
train_x, test_x, train_y, test_y = train_test_split(
iris["data"], iris["target"], random_state=4
)
# any of the 3 types of SVM can be used
# current_model=SVC(train_x, train_y)
# current_model=NuSVC(train_x, train_y)
current_model = Linearsvc(train_x, train_y)
prediction = current_model.predict([X_new])
return iris["target_names"][prediction][0]
示例4: test_probability
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_probability():
# Predict probabilities using SVC
# This uses cross validation, so we use a slightly bigger testing set.
for clf in (svm.SVC(probability=True, random_state=0, C=1.0),
svm.NuSVC(probability=True, random_state=0)):
clf.fit(iris.data, iris.target)
prob_predict = clf.predict_proba(iris.data)
assert_array_almost_equal(
np.sum(prob_predict, 1), np.ones(iris.data.shape[0]))
assert_true(np.mean(np.argmax(prob_predict, 1)
== clf.predict(iris.data)) > 0.9)
assert_almost_equal(clf.predict_proba(iris.data),
np.exp(clf.predict_log_proba(iris.data)), 8)
示例5: test_error
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_error():
# Test that it gives proper exception on deficient input
# impossible value of C
assert_raises(ValueError, svm.SVC(gamma='scale', C=-1).fit, X, Y)
# impossible value of nu
clf = svm.NuSVC(gamma='scale', nu=0.0)
assert_raises(ValueError, clf.fit, X_sp, Y)
Y2 = Y[:-1] # wrong dimensions for labels
assert_raises(ValueError, clf.fit, X_sp, Y2)
clf = svm.SVC(gamma="scale")
clf.fit(X_sp, Y)
assert_array_equal(clf.predict(T), true_result)
示例6: test_immutable_coef_property
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_immutable_coef_property():
# Check that primal coef modification are not silently ignored
svms = [
svm.SVC(kernel='linear').fit(iris.data, iris.target),
svm.NuSVC(kernel='linear').fit(iris.data, iris.target),
svm.SVR(kernel='linear').fit(iris.data, iris.target),
svm.NuSVR(kernel='linear').fit(iris.data, iris.target),
svm.OneClassSVM(kernel='linear').fit(iris.data),
]
for clf in svms:
assert_raises(AttributeError, clf.__setattr__, 'coef_', np.arange(3))
assert_raises((RuntimeError, ValueError),
clf.coef_.__setitem__, (0, 0), 0)
示例7: test_decision_function_shape_two_class
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_decision_function_shape_two_class():
for n_classes in [2, 3]:
X, y = make_blobs(centers=n_classes, random_state=0)
for estimator in [svm.SVC, svm.NuSVC]:
clf = OneVsRestClassifier(estimator(gamma='scale',
decision_function_shape="ovr")).fit(X, y)
assert_equal(len(clf.predict(X)), len(y))
示例8: NuSVC
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def NuSVC(train_x, train_y):
svc_NuSVC = svm.NuSVC()
svc_NuSVC.fit(train_x, train_y)
return svc_NuSVC
示例9: convert
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def convert(model, feature_names, target):
"""Convert a Nu-Support Vector Classification (NuSVC) model to the protobuf spec.
Parameters
----------
model: NuSVC
A trained NuSVC encoder model.
feature_names: [str], optional (default=None)
Name of the input columns.
target: str, optional (default=None)
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not (_HAS_SKLEARN):
raise RuntimeError(
"scikit-learn not found. scikit-learn conversion API is disabled."
)
_sklearn_util.check_expected_type(model, _NuSVC)
return _SVC.convert(model, feature_names, target)
示例10: test_conversion_bad_inputs
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_conversion_bad_inputs(self):
from sklearn.preprocessing import OneHotEncoder
# Error on converting an untrained model
with self.assertRaises(TypeError):
model = NuSVC()
spec = scikit_converter.convert(model, "data", "out")
# Check the expected class during conversion
with self.assertRaises(TypeError):
model = OneHotEncoder()
spec = scikit_converter.convert(model, "data", "out")
示例11: create_classifiers
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def create_classifiers(nb_workers=-1):
""" create all classifiers with default parameters
:param int nb_workers: number of parallel if possible
:return dict: {str: clf}
>>> classifs = create_classifiers()
>>> classifs # doctest: +ELLIPSIS
{...}
>>> sum([isinstance(create_clf_param_search_grid(k), dict)
... for k in classifs.keys()])
7
>>> sum([isinstance(create_clf_param_search_distrib(k), dict)
... for k in classifs.keys()])
7
"""
clfs = {
'RandForest': ensemble.RandomForestClassifier(n_estimators=20,
# oob_score=True,
min_samples_leaf=2,
min_samples_split=3,
n_jobs=nb_workers),
'GradBoost': ensemble.GradientBoostingClassifier(subsample=0.25,
warm_start=False,
max_depth=6,
min_samples_leaf=6,
n_estimators=200,
min_samples_split=7),
'LogistRegr': linear_model.LogisticRegression(solver='sag',
n_jobs=nb_workers),
'KNN': neighbors.KNeighborsClassifier(n_jobs=nb_workers),
'SVM': svm.SVC(kernel='rbf', probability=True,
tol=2e-3, max_iter=5000),
'DecTree': tree.DecisionTreeClassifier(),
# 'RBM': create_pipeline_neuron_net(),
'AdaBoost': ensemble.AdaBoostClassifier(n_estimators=5),
# 'NuSVM-rbf': svm.NuSVC(kernel='rbf', probability=True),
}
return clfs
示例12: _parse_sklearn_classifier
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def _parse_sklearn_classifier(scope, model, inputs, custom_parsers=None):
probability_tensor = _parse_sklearn_simple_model(
scope, model, inputs, custom_parsers=custom_parsers)
if model.__class__ in [NuSVC, SVC] and not model.probability:
return probability_tensor
options = scope.get_options(model, dict(zipmap=True))
if not options['zipmap']:
return probability_tensor
this_operator = scope.declare_local_operator('SklearnZipMap')
this_operator.inputs = probability_tensor
label_type = Int64TensorType([None])
classes = get_label_classes(scope, model)
if (isinstance(model.classes_, list) and
isinstance(model.classes_[0], np.ndarray)):
# multi-label problem
pass
elif np.issubdtype(classes.dtype, np.floating):
classes = np.array(list(map(lambda x: int(x), classes)))
if set(map(lambda x: float(x), classes)) != set(model.classes_):
raise RuntimeError("skl2onnx implicitly converts float class "
"labels into integers but at least one label "
"is not an integer. Class labels should "
"be integers or strings.")
this_operator.classlabels_int64s = classes
elif np.issubdtype(classes.dtype, np.signedinteger):
this_operator.classlabels_int64s = classes
elif np.issubdtype(classes.dtype, np.unsignedinteger):
this_operator.classlabels_int64s = classes
else:
classes = np.array([s.encode('utf-8') for s in classes])
this_operator.classlabels_strings = classes
label_type = StringTensorType([None])
output_label = scope.declare_local_variable('output_label', label_type)
output_probability = scope.declare_local_variable(
'output_probability',
SequenceType(DictionaryType(label_type, scope.tensor_type())))
this_operator.outputs.append(output_label)
this_operator.outputs.append(output_probability)
return this_operator.outputs
示例13: test_convert_nusvc_binary_pfalse
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_convert_nusvc_binary_pfalse(self):
model, X = self._fit_binary_classification(
NuSVC(probability=False, decision_function_shape='ovo'))
model_onnx = convert_sklearn(
model, "SVC", [("input", FloatTensorType([None, X.shape[1]]))])
nodes = model_onnx.graph.node
self.assertIsNotNone(nodes)
svc_node = nodes[0]
self._check_attributes(
svc_node,
{
"coefficients": None,
"kernel_params": None,
"kernel_type": "RBF",
"post_transform": None,
"rho": None,
"support_vectors": None,
"vectors_per_class": None,
},
)
dump_data_and_model(
X,
model,
model_onnx,
basename="SklearnBinNuSVCPF-NoProbOpp",
allow_failure="StrictVersion(onnxruntime.__version__)"
" < StrictVersion('0.5.0')"
)
示例14: test_convert_nusvc_binary_ptrue
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_convert_nusvc_binary_ptrue(self):
model, X = self._fit_binary_classification(NuSVC(probability=True))
model_onnx = convert_sklearn(
model, "SVC", [("input", FloatTensorType([None, X.shape[1]]))])
nodes = model_onnx.graph.node
self.assertIsNotNone(nodes)
svc_node = nodes[0]
self._check_attributes(
svc_node,
{
"coefficients": None,
"kernel_params": None,
"kernel_type": "RBF",
"post_transform": None,
"rho": None,
"support_vectors": None,
"vectors_per_class": None,
},
)
dump_data_and_model(
X,
model,
model_onnx,
basename="SklearnBinNuSVCPT",
allow_failure="StrictVersion(onnxruntime.__version__)"
" <= StrictVersion('0.4.0')"
)
示例15: test_convert_nusvc_multi_pfalse
# 需要導入模塊: from sklearn import svm [as 別名]
# 或者: from sklearn.svm import NuSVC [as 別名]
def test_convert_nusvc_multi_pfalse(self):
model, X = self._fit_multi_classification(
NuSVC(probability=False, nu=0.1,
decision_function_shape='ovo'))
model_onnx = convert_sklearn(
model, "SVC", [("input", FloatTensorType([None, X.shape[1]]))])
nodes = model_onnx.graph.node
self.assertIsNotNone(nodes)
svc_node = nodes[0]
self._check_attributes(
svc_node,
{
"coefficients": None,
"kernel_params": None,
"kernel_type": "RBF",
"post_transform": None,
"rho": None,
"support_vectors": None,
"vectors_per_class": None,
},
)
dump_data_and_model(
X, model, model_onnx,
basename="SklearnMclNuSVCPF-Dec1", # max relative error is 1e-5
allow_failure="StrictVersion(onnxruntime.__version__)"
" < StrictVersion('0.5.0')")