# Code source: Gaël Varoquaux # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import svm import gradio as gr from matplotlib.colors import ListedColormap plt.switch_backend("agg") font1 = {'family':'DejaVu Sans','size':20} def create_data(random, size_num, x_min, x_max, y_min, y_max): #emulate some random data if random: size_num = int(size_num) x = np.random.uniform(x_min, x_max, size=(size_num, 1)) y = np.random.uniform(y_min, y_max, size=(size_num, 1)) X = np.hstack((x, y)) Y = [0] * int(size_num/2) + [1] * int(size_num/2) else: X = np.c_[ (0.4, -0.7), (-1.5, -1), (-1.4, -0.9), (-1.3, -1.2), (-1.5, 0.2), (-1.2, -0.4), (-0.5, 1.2), (-1.5, 2.1), (1, 1), # -- (1.3, 0.8), (1.5, 0.5), (0.2, -2), (0.5, -2.4), (0.2, -2.3), (0, -2.7), (1.3, 2.8), ].T Y = [0] * 8 + [1] * 8 return X, Y # fit the model def clf_kernel(color1, color2, dpi, size_num = None, x_min = None, x_max = None, y_min = None, y_max = None, random = False): if size_num is not None or x_min is not None or x_max is not None or y_min is not None or y_max is not None: random = True X, Y = create_data(random, size_num, x_min, x_max, y_min, y_max) kernels = ["linear", "poly", "rbf"] # plot the line, the points, and the nearest vectors to the plane fig, axs = plt.subplots(1,3, figsize = (16,8), facecolor='none', dpi = res[dpi]) cmap = ListedColormap([color1, color2], N=2, name = 'braincell') for i, kernel in enumerate(kernels): clf = svm.SVC(kernel=kernel, gamma=2) clf.fit(X, Y) axs[i].scatter( clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors="none", zorder=10, edgecolors="k", ) axs[i].scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=cmap, edgecolors="k") axs[i].axis("tight") x_min = -3 x_max = 3 y_min = -3 y_max = 3 XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]) # Put the result into a color plot Z = Z.reshape(XX.shape) axs[i].pcolormesh(XX, YY, Z > 0, cmap=cmap) axs[i].contour( XX, YY, Z, colors=["k", "k", "k"], linestyles=["--", "-", "--"], levels=[-0.5, 0, 0.5], ) axs[i].set_xlim(x_min, x_max) axs[i].set_ylim(y_min, y_max) axs[i].set_xticks(()) axs[i].set_yticks(()) axs[i].set_title('Type of kernel: ' + kernel, color = "white", fontdict = font1, pad=20, bbox=dict(boxstyle="round,pad=0.3", color = "#6366F1")) plt.close() return fig, np.round(X, decimals=2) intro = """
Made with ❤
""" link = """