|
| 1 | +from sklearn.datasets import load_iris |
| 2 | +from sklearn import svm |
| 3 | +from sklearn.model_selection import train_test_split |
| 4 | +import doctest |
| 5 | + |
| 6 | +# different functions implementing different types of SVM's |
| 7 | +def NuSVC(train_x, train_y): |
| 8 | + svc_NuSVC = svm.NuSVC() |
| 9 | + svc_NuSVC.fit(train_x, train_y) |
| 10 | + return svc_NuSVC |
| 11 | + |
| 12 | + |
| 13 | +def Linearsvc(train_x, train_y): |
| 14 | + svc_linear = svm.LinearSVC() |
| 15 | + svc_linear.fit(train_x, train_y) |
| 16 | + return svc_linear |
| 17 | + |
| 18 | + |
| 19 | +def SVC(train_x, train_y): |
| 20 | + # svm.SVC(C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False,tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, random_state=None) |
| 21 | + # various parameters like "kernal","gamma","C" can effectively tuned for a given machine learning model. |
| 22 | + SVC = svm.SVC(gamma="auto") |
| 23 | + SVC.fit(train_x, train_y) |
| 24 | + return SVC |
| 25 | + |
| 26 | + |
| 27 | +def test(X_new): |
| 28 | + """ |
| 29 | + 3 test cases to be passed |
| 30 | + an array containing the sepal length (cm), sepal width (cm),petal length (cm),petal width (cm) |
| 31 | + based on which the target name will be predicted |
| 32 | + >>> test([1,2,1,4]) |
| 33 | + 'virginica' |
| 34 | + >>> test([5, 2, 4, 1]) |
| 35 | + 'versicolor' |
| 36 | + >>> test([6,3,4,1]) |
| 37 | + 'versicolor' |
| 38 | +
|
| 39 | + """ |
| 40 | + iris = load_iris() |
| 41 | + # splitting the dataset to test and train |
| 42 | + train_x, test_x, train_y, test_y = train_test_split( |
| 43 | + iris["data"], iris["target"], random_state=4 |
| 44 | + ) |
| 45 | + # any of the 3 types of SVM can be used |
| 46 | + # current_model=SVC(train_x, train_y) |
| 47 | + # current_model=NuSVC(train_x, train_y) |
| 48 | + current_model = Linearsvc(train_x, train_y) |
| 49 | + prediction = current_model.predict([X_new]) |
| 50 | + return iris["target_names"][prediction][0] |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + doctest.testmod() |
0 commit comments