Using setTermCriteria of cv2 and svm - python

I am trying to use setTermCriteria with SVM. But when I use it I am getting below error:
AttributeError: 'cv2.ml_SVM' object has no attribute 'setTermCritera_MAX_ITER'
This is how I am using it
svm.setTermCritera_MAX_ITER=10000
svm.setTermCriteria_EPS = 1e-3
I am not getting error but not finding it useful when I use it below way:
cv2.setTermCritera_MAX_ITER=10000
cv2.setTermCriteria_EPS = 1e-3
When I try below method
svm.setTermCriteria(10000)
SystemError: new style getargs format but argument is not a tuple
Which is the right way to use it in Python with OpenCV

The error message is clear, a tuple is needed. Let's see the default value:
svm = cv2.ml.SVM_create()
svm.getTermCriteria()
returns (3, 1000, 1.1920928955078125e-07). So if you want to set only the maximum number of iterations should call:
svm.setTermCriteria((cv2.TermCriteria_MAX_ITER, 10000, 0))
and if want to keep the same epsilon criterion and also set max iter:
svm.setTermCriteria((cv2.TermCriteria_MAX_ITER + cv2.TermCriteria_EPS, 10000, 1.1920928955078125e-07))

Related

How can I convert a LightGBM model to ONXX?

I'm trying to save my model so it can be used in a ASP.NET program, and I think that ONNX is a good way to do so. The problem is that even after checking the docs and googling it all day, I still get the same error raise ValueError('Initial types are required. See usage of ' ValueError: Initial types are required. See usage of convert(...) in skl2onnx.convert for details. I have no idea what's going on and any help is greatly appreciated!
My Code
import onnxmltools
from skl2onnx import convert
import lightgbm as lgb
import pandas as pd
parameters = {
'boosting': 'gbdt',
'feature_fraction': 0.5,
'bagging_fraction': 0.5,
'bagging_freq': 20,
'num_boost_round': 10000,
'verbose': -1 #maybe?
}
model_lgbm = lgb.train(parameters, train_data, valid_sets = test_data, early_stopping_rounds = 200);
onnx_model = convert.convert_sklearn(model_lgbm, ???);
I think this doc will help you.
You have to use :
onnxmltools.convert_lightgbm
and not
convert.convert_sklearn
As the other answer mentions: You have to use : onnxmltools.convert_lightgbm and not convert.convert_sklearn
The error would also be caused since you have not defined the initial_types. The inital_types are in the Docs described as follows:
Example of initial_types: Assume that the specified scikit-learn model takes a heterogeneous list as its input. If the first 5 elements are floats and the last 10 elements are integers, we need to specify initial types as below. The [None] in [None, 5] indicates the batch size here is unknown.
from skl2onnx.common.data_types import FloatTensorType, Int64TensorType
initial_type = [('float_input', FloatTensorType([None, 5])),
('int64_input', Int64TensorType([None, 10]))]

AttributeError: module 'tensorflow' has no attribute 'py_func'

I'm trying to run a code on ubuntu that uses tensorflow, it gives me the error:
AttributeError: module 'tensorflow' has no attribute 'py_func'
how can I fix it?
the relevant part of the code:
for i in range(cfg.num_layers):
neighbour_idx = tf.py_func(DP.knn_search, [batch_xyz, batch_xyz, cfg.k_n], tf.int32)
sub_points = batch_xyz[:, :tf.shape(batch_xyz)[1] // cfg.sub_sampling_ratio[i], :]
pool_i = neighbour_idx[:, :tf.shape(batch_xyz)[1] // cfg.sub_sampling_ratio[i], :]
up_i = tf.py_func(DP.knn_search, [sub_points, batch_xyz, 1], tf.int32)
input_points.append(batch_xyz)
input_neighbors.append(neighbour_idx)
input_pools.append(pool_i)
input_up_samples.append(up_i)
batch_xyz = sub_points
input_list = input_points + input_neighbors + input_pools + input_up_samples
input_list += [batch_features, batch_labels, batch_pc_idx, batch_cloud_idx]
It can't get the tf.py_func.
PS: I tried adding tf.compat.v1.py_func and it didn't work.
tf.py_func is designed for Tensorflow 1.
In Tensorflow 2,tf.numpy_function is a near-exact replacement, just drop the stateful argument (all tf.numpy_function calls are considered stateful). It is compatible with eager execution and tf.function.
tf.py_function is a close but not an exact replacement, passing TensorFlow tensors to the wrapped function instead of NumPy arrays, which provides gradients and can take advantage of accelerators.

AttributeError: 'numpy.ndarray' object has no attribute 'cost_'

I am trying to conduct Kprototype clustering algorithm. When I both run the model and try to do the cost graph as follows, I always get a 'no attribute' error for labels_ and cost_ functions. I checked the examples on several web sites, but there is no difference. What can I do? Thank you for your help.
1)
from kmodes.kmodes import KModes
from kmodes.kprototypes import KPrototypes
kproto1 = KPrototypes(n_clusters=15, init='Cao').fit_predict(data,categorical = [23])
labels= kproto1.labels_
**AttributeError: 'numpy.ndarray' object has no attribute 'label_'**
cost = []
range_cluster=[5,8,10,15,20,25,30,35,40,45,50,55,70,85,100]
for num_clusters in range_cluster:
kproto = KPrototypes(n_clusters=num_clusters, init='Cao').fit_predict(data, categorical=[23])
cost.append(kproto.cost_)
plt.plot(cost)
According to the source code, there are 2 ways to achieve this :
fit_predict method will return a tuple of labels, cost. So to get your labels, you should :
kproto1_result = KPrototypes(n_clusters=15, init='Cao').fit_predict(data,categorical = [23])
labels= kproto1[0]
or the 2nd method is just using the fit method :
kproto1 = KPrototypes(n_clusters=15, init='Cao').fit(data,categorical = [23])
labels = kproto1.labels_

How to pass variable keyword-arguments when calling a function

I am trying to write a function which tests out different hyper-parameters with a list of values. I want to use this function to automatically run through the specified hyper-parameter and apply the values that are specified. What would be the correct way to do that?
The correct way to call the logistic regression function would be:
lg = LogisticRegression(solver = "liblinear", max_iter = 10000, C=10)
def hyperparameter_tuning(parameter, test_values):
for value in test_values:
lg = LogisticRegression(solver = "liblinear", max_iter = 10000, parameter=value)
When calling the function like this:
hyperparameter_tuning("C",[0.1, 1, 10, 100])
I get the error message:
__init__() got an unexpected keyword argument 'parameter'
You should use ** for that:
lg = LogisticRegression(solver = "liblinear", max_iter = 10000, **{parameter: value})

Convert KNN train from Opencv 3 to 2

I am reading a tutorial for training KNN using Opencv. The code is written for Opencv 3 but I need to use it in Opencv 2. The original training is:
cv2.ml.KNearest_create().train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
I tried using this:
cv2.KNearest().train(npaFlattenedImages, cv2.CV_ROW_SAMPLE, npaClassifications)
but the error is:
Unsupported index array data type (it should be 8uC1, 8sC1 or 32sC1) in function cvPreprocessIndexArray
The full code is here:
https://github.com/MicrocontrollersAndMore/OpenCV_3_KNN_Character_Recognition_Python/blob/master/TrainAndTest.py
Here the changes that appear to have made the full code work for me for OpenCV 2.4.13:
60c60
< kNearest = cv2.ml.KNearest_create() # instantiate KNN object
---
> kNearest = cv2.KNearest() # instantiate KNN object
62c62
< kNearest.train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
---
> kNearest.train(npaFlattenedImages, npaClassifications)
85c85
< imgContours, npaContours, npaHierarchy = cv2.findContours(imgThreshCopy, # input image, make sure to use a copy since the function will modify this image in the course of finding contours
---
> npaContours, npaHierarchy = cv2.findContours(imgThreshCopy, # input image, make sure to use a copy since the function will modify this image in the course of finding contours
125c125
< retval, npaResults, neigh_resp, dists = kNearest.findNearest(npaROIResized, k = 1) # call KNN function find_nearest
---
> retval, npaResults, neigh_resp, dists = kNearest.find_nearest(npaROIResized, k = 1) # call KNN function find_nearest
Unlike the generic CvStatModel::train(), cv2.KNearest.train() doesn't have the 2nd optional argument int tflag, and the docs say: "Only CV_ROW_SAMPLE data layout is supported".
The error message (btw the cryptic mnemonics are OpenCV data types) was thus caused by the function trying to use npaClassifications as the next argument, sampleIdx.
Further errors after fixing this:
cv2.findCountours() only returns 2 values: → contours, hierarchy (you don't need the 3rd one, imgContours, anyway).
KNearest.findNearest() was KNearest.find_nearest().
And the result now:
Ulrich Stern already did me a favor to provide a raw diff.

Categories