示例#1
0
def test_svm():
    from models.svm import SVM

    x, y = np.random.randn(2, 400, 2), np.zeros([2, 400], dtype=int)
    y[0] = -1
    y[1] = 1
    for i, theta in enumerate(np.linspace(0, 2 * np.pi, 40)):
        x[0, (10 * i):(
            10 * i +
            10)] += 5 * np.array([np.cos(theta), np.sin(theta)])

    x = x.reshape(-1, 2)
    y = y.flatten()

    plot_scatter([x[y == i] for i in [-1, 1]], 'Real')

    # train
    svm = SVM(C=10, sigma=1, kernel='rbf', max_iter=100)
    svm.fit(x, y)

    pred = np.array(svm.predict(x))
    plot_scatter([x[pred == i] for i in [-1, 1]], 'Pred')
    acc = np.sum(pred == y) / len(pred)
    print(f'Acc = {100 * acc:.2f}%')
    print(svm.support_vectors)
示例#2
0
from sklearn.datasets import load_breast_cancer
from sklearn.datasets import make_blobs
from models.svm import SVM
import matplotlib.pyplot as plt
from validation.classification import A_micro_average
from preprocessing.features_enginering import normalize_dataset
from preprocessing.split import train_test_split

#X, y = load_wine(return_X_y=True)
X = make_blobs(1000, centers=3)
y = X[1]
X = X[0]
#normalize_dataset(X)
x_train, y_train, x_test, y_test = train_test_split(X, y, .8)
plt.scatter(x=X[:, 0], y=X[:, 1], c=y)
plt.show()

# %%
svm = SVM(C=1)
svm.fit(x_train, y_train)

# %%

res = svm.predict(x_test)
A = A_micro_average(y_test, res)

#%%

from mlxtend.plotting import plot_decision_regions
plot_decision_regions(X=X, y=y, clf=svm)
plt.show()