博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
COMP7404 Machine Learing——SVM
阅读量:2136 次
发布时间:2019-04-30

本文共 12228 字,大约阅读时间需要 40 分钟。

linear SVM

import numpy as npfrom sklearn import datasetsiris = datasets.load_iris()X = iris.data[:, [2, 3]]y = iris.targetfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,                                                    random_state=1, stratify=y)from sklearn.preprocessing import StandardScalerfrom sklearn.svm import SVCsc = StandardScaler()sc.fit(X_train)X_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)svm = SVC(kernel='linear', C=1, random_state=1)svm.fit(X_train_std, y_train)y_pred = svm.predict(X_train_std)print('Misclassified training samples:',(y_train!=y_pred).sum()) y_pred = svm.predict(X_test_std)print('Misclassified samples:', (y_test != y_pred).sum()) from sklearn.metrics import accuracy_scoreprint('Accuracy: %.3f' % accuracy_score(y_test, y_pred))#下面就是可视化的部分X_combined_std = np.vstack((X_train_std, X_test_std))y_combined = np.hstack((y_train, y_test))import matplotlib.pyplot as pltfrom matplotlib.colors import ListedColormapdef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):    markers = ('s', 'x', 'o', '^', 'v')    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')    cmap = ListedColormap(colors[:len(np.unique(y))])    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),                           np.arange(x2_min, x2_max, resolution))    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)    Z = Z.reshape(xx1.shape)    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)    plt.xlim(xx1.min(), xx1.max())    plt.ylim(xx2.min(), xx2.max())    for idx, cl in enumerate(np.unique(y)):        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8,                     c=colors[idx], marker=markers[idx],                     label=cl, edgecolor='black')    if test_idx:        X_test, y_test = X[test_idx, :], y[test_idx]        plt.scatter(X_test[:, 0], X_test[:, 1], c='none', edgecolor='black',                     alpha=1.0, linewidth=1,                    marker='o', s=100, label='test set') from sklearn.svm import SVCsvm = SVC(kernel='linear', C=1, random_state=1)svm.fit(X_train_std, y_train)plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150))plt.xlabel('petal length (standardized)')plt.ylabel('petal width (standardized)')plt.legend(loc='upper left')plt.show()

import pandas as pdimport numpy as pyfrom sklearn import datasetsfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitfrom sklearn.svm import SVCfrom sklearn.metrics import accuracy_scoreiris = datasets.load_iris()X = iris.data[:,[2,3]]#X是numpy array#这是只用花瓣长度和花瓣宽度来预测y = iris.target#y是numpy arrayX_train, X_test, y_train,y_test = train_test_split(X,y,test_size=0.3,                                                   random_state=1, stratify=y)sc = StandardScaler()sc.fit(X_train)X_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)svm = SVC(kernel='linear', C=1, random_state=1)svm.fit(X_train_std, y_train)y_pred = svm.predict(X_train_std)print('misclassified training samples: ', (y_pred != y_train).sum())y_pred = svm.predict(X_test_std)print('misclassified testing samples: ', (y_pred != y_test).sum())print('Accuracy: %.3f' % (accuracy_score(y_pred, y_test)))

 

non-linear kernel

不同的核

  • 线性核函数kernel=‘linear’
  • 多项式核函数kernel=‘poly’
  • 径向基核函数kernel=‘rbf’
  • sigmod核函数kernel=‘sigmod’
     
import numpy as npfrom sklearn import datasetsiris = datasets.load_iris()X = iris.data[:, [2, 3]]y = iris.targetfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,                                                    random_state=1, stratify=y)from sklearn.preprocessing import StandardScalersc = StandardScaler()sc.fit(X_train)X_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)from sklearn.svm import SVCsvm = SVC(kernel='rbf', C=20.0, gamma = 1, random_state=1)svm.fit(X_train_std, y_train)y_pred = svm.predict(X_train_std)print('Misclassified training samples:',(y_train!=y_pred).sum()) y_pred = svm.predict(X_test_std)print('Misclassified samples:', (y_test != y_pred).sum()) from sklearn.metrics import accuracy_scoreprint('Accuracy: %.3f' % accuracy_score(y_test, y_pred))X_combined_std = np.vstack((X_train_std, X_test_std))y_combined = np.hstack((y_train, y_test))import matplotlib.pyplot as pltfrom matplotlib.colors import ListedColormapdef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):    markers = ('s', 'x', 'o', '^', 'v')    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')    cmap = ListedColormap(colors[:len(np.unique(y))])    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),                           np.arange(x2_min, x2_max, resolution))    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)    Z = Z.reshape(xx1.shape)    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)    plt.xlim(xx1.min(), xx1.max())    plt.ylim(xx2.min(), xx2.max())    for idx, cl in enumerate(np.unique(y)):        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8,                     c=colors[idx], marker=markers[idx],                     label=cl, edgecolor='black')    if test_idx:        X_test, y_test = X[test_idx, :], y[test_idx]        plt.scatter(X_test[:, 0], X_test[:, 1], c='none', edgecolor='black',                     alpha=1.0, linewidth=1,                    marker='o', s=100, label='test set') #create linear inseperable dataimport matplotlib.pyplot as pltimport numpy as npnp.random.seed(1)X_xor = np.random.randn(200, 2)y_xor = np.logical_xor(X_xor[:,0] > 0, X_xor[:, 1] > 0)y_xor = np.where(y_xor, 1, -1)plt.scatter(X_xor[y_xor == 1, 0], X_xor[y_xor == 1, 1])plt.scatter(X_xor[y_xor == -1, 0], X_xor[y_xor == -1, 1])plt.xlim([-3, 3])plt.ylim([-3, 3])plt.show() from sklearn.svm import SVCsvm = SVC(kernel='rbf', C=20.0, gamma = 1, random_state=1)svm.fit(X_xor, y_xor)plot_decision_regions(X_xor, y_xor, classifier=svm)plt.legend(loc='upper left')plt.show()

import pandas as pdimport numpy as pyfrom sklearn import datasetsfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitfrom sklearn.svm import SVCfrom sklearn.metrics import accuracy_scoreiris = datasets.load_iris()X = iris.data[:,[2,3]]#X是numpy array#这是只用花瓣长度和花瓣宽度来预测y = iris.target#y是numpy arrayX_train, X_test, y_train,y_test = train_test_split(X,y,test_size=0.3,                                                   random_state=1, stratify=y)sc = StandardScaler()sc.fit(X_train)X_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)svm = SVC(kernel='rbf', C=20, gamma=1, random_state=1)svm.fit(X_train_std, y_train)y_pred = svm.predict(X_train_std)print('misclassified training samples: ', (y_pred != y_train).sum())y_pred = svm.predict(X_test_std)print('misclassified testing samples: ', (y_pred != y_test).sum())print('Accuracy: %.3f' % (accuracy_score(y_pred, y_test)))

 

different parameters

import numpy as npfrom sklearn import datasetsiris = datasets.load_iris()X = iris.data[:, [2, 3]]y = iris.targetfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,                                                    random_state=1, stratify=y)from sklearn.preprocessing import StandardScalersc = StandardScaler()sc.fit(X_train)X_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)X_combined_std = np.vstack((X_train_std, X_test_std))y_combined = np.hstack((y_train, y_test))import matplotlib.pyplot as pltfrom matplotlib.colors import ListedColormapdef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):    markers = ('s', 'x', 'o', '^', 'v')    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')    cmap = ListedColormap(colors[:len(np.unique(y))])    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),                           np.arange(x2_min, x2_max, resolution))    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)    Z = Z.reshape(xx1.shape)    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)    plt.xlim(xx1.min(), xx1.max())    plt.ylim(xx2.min(), xx2.max())    for idx, cl in enumerate(np.unique(y)):        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8,                     c=colors[idx], marker=markers[idx],                     label=cl, edgecolor='black')    if test_idx:        X_test, y_test = X[test_idx, :], y[test_idx]        plt.scatter(X_test[:, 0], X_test[:, 1], c='none', edgecolor='black',                     alpha=1.0, linewidth=1,                    marker='o', s=100, label='test set')#create linear inseperable dataimport matplotlib.pyplot as pltimport numpy as npnp.random.seed(1)X_xor = np.random.randn(200, 2)y_xor = np.logical_xor(X_xor[:,0] > 0, X_xor[:, 1] > 0)y_xor = np.where(y_xor, 1, -1)plt.scatter(X_xor[y_xor == 1, 0], X_xor[y_xor == 1, 1])plt.scatter(X_xor[y_xor == -1, 0], X_xor[y_xor == -1, 1])plt.xlim([-3, 3])plt.ylim([-3, 3])plt.show()from sklearn.svm import SVCsvm = SVC(kernel='rbf', random_state=1, gamma=0.2, C=1.0)svm.fit(X_train_std, y_train)plot_decision_regions(X_combined_std, y_combined,classifier=svm, test_idx=range(105, 150))plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.tight_layout()plt.show()

 

different parameters

import numpy as npfrom sklearn import datasetsiris = datasets.load_iris()X = iris.data[:, [2, 3]]y = iris.targetfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,                                                    random_state=1, stratify=y)from sklearn.preprocessing import StandardScalersc = StandardScaler()sc.fit(X_train)X_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)X_combined_std = np.vstack((X_train_std, X_test_std))y_combined = np.hstack((y_train, y_test))import matplotlib.pyplot as pltfrom matplotlib.colors import ListedColormapdef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):    markers = ('s', 'x', 'o', '^', 'v')    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')    cmap = ListedColormap(colors[:len(np.unique(y))])    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),                           np.arange(x2_min, x2_max, resolution))    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)    Z = Z.reshape(xx1.shape)    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)    plt.xlim(xx1.min(), xx1.max())    plt.ylim(xx2.min(), xx2.max())    for idx, cl in enumerate(np.unique(y)):        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8,                     c=colors[idx], marker=markers[idx],                     label=cl, edgecolor='black')    if test_idx:        X_test, y_test = X[test_idx, :], y[test_idx]        plt.scatter(X_test[:, 0], X_test[:, 1], c='none', edgecolor='black',                     alpha=1.0, linewidth=1,                    marker='o', s=100, label='test set')#create linear inseperable dataimport matplotlib.pyplot as pltimport numpy as npnp.random.seed(1)X_xor = np.random.randn(200, 2)y_xor = np.logical_xor(X_xor[:,0] > 0, X_xor[:, 1] > 0)y_xor = np.where(y_xor, 1, -1)plt.scatter(X_xor[y_xor == 1, 0], X_xor[y_xor == 1, 1])plt.scatter(X_xor[y_xor == -1, 0], X_xor[y_xor == -1, 1])plt.xlim([-3, 3])plt.ylim([-3, 3])plt.show()from sklearn.svm import SVCsvm = SVC(kernel='rbf', random_state=1, gamma=100.0, C=1.0)svm.fit(X_train_std, y_train)plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150))plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.tight_layout()plt.show()

 

转载地址:http://mmygf.baihongyu.com/

你可能感兴趣的文章
Ubuntu解决gcc编译报错/usr/bin/ld: cannot find -lstdc++
查看>>
解决Ubuntu14.04 - 16.10版本 cheese摄像头灯亮却黑屏问题
查看>>
解决Ubuntu 64bit下使用交叉编译链提示error while loading shared libraries: libz.so.1
查看>>
VS生成DLL文件供第三方调用
查看>>
Android Studio color和font设置
查看>>
Python 格式化打印json数据(展开状态)
查看>>
Centos7 安装curl(openssl)和libxml2
查看>>
Centos7 离线安装RabbitMQ,并配置集群
查看>>
Centos7 or Other Linux RPM包查询下载
查看>>
运行springboot项目出现:Type javax.xml.bind.JAXBContext not present
查看>>
Java中多线程向mysql插入同一条数据冲突问题
查看>>
Idea Maven项目使用jar包,添加到本地库使用
查看>>
FastDFS集群架构配置搭建(转载)
查看>>
HTM+CSS实现立方体图片旋转展示效果
查看>>
FFmpeg 命令操作音视频
查看>>
问题:Opencv(3.1.0/3.4)找不到 /opencv2/gpu/gpu.hpp 问题
查看>>
目的:使用CUDA环境变量CUDA_VISIBLE_DEVICES来限定CUDA程序所能使用的GPU设备
查看>>
问题:Mysql中字段类型为text的值, java使用selectByExample查询为null
查看>>
程序员--学习之路--技巧
查看>>
解决问题之 MySQL慢查询日志设置
查看>>