In [1]:
# Kernel Support Vector Machine (SVM)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
In [2]:
url='https://raw.githubusercontent.com/cagriemreakin/Machine-Learning/master/2%20-%20Classification/3%20-%20Kernel%20SVM/sosyal_ag_reklamlari.csv'
dataset = pd.read_csv(url)
X = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
In [3]:
# Eğitim ve test set olarak ayırma
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
In [4]:
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train_scaled = sc.fit_transform(X_train)
X_test_scaled = sc.transform(X_test)
C:\Users\ceakn\Anaconda3\lib\site-packages\sklearn\utils\validation.py:429: DataConversionWarning: Data with input dtype int64 was converted to float64 by StandardScaler.
  warnings.warn(msg, _DataConversionWarning)
In [5]:
# Modelimizi training set' e göre eğitme
from sklearn.svm import SVC
#Nonlinear SVM . kernel = rbf 
classifier = SVC(kernel = 'rbf', random_state = 0)
classifier.fit(X_train_scaled, y_train)
Out[5]:
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
  max_iter=-1, probability=False, random_state=0, shrinking=True,
  tol=0.001, verbose=False)
In [6]:
# Test setine göre sonuçları tahmin etme
y_pred = classifier.predict(X_test_scaled)
In [7]:
# Confusion Matrix ile hatalı tahminleri bulma
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
cm
Out[7]:
array([[55,  3],
       [ 1, 21]])
In [8]:
print("Doğruluk oranı: %", sum(np.diag(cm))/ cm.sum()*100)
Doğruluk oranı: % 95.0
In [9]:
# Test set tahminlerinin görselleştirilmesi
from matplotlib.colors import ListedColormap
X_set, y_set = X_test_scaled, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('SVM Test Set')
plt.xlabel('Yas')
plt.ylabel('Maas')
plt.legend()
plt.show()