SVM→8.SVM实战→1.训练一个基本的SVM

SVM→8.SVM实战→1.训练一个基本的SVM

《SVM→8.SVM实战→1.训练一个基本的SVM》


描述代码
  1. 导入模块
1
2
3
4
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from sklearn.svm import SVC # "Support vector classifier"
import numpy as np
  1. 生成数据集
    1. 使用make_blobs函数生成用于聚类的数据,主要参数有:
      1. n_samples:样本个数
      2. centers:样本中心(类别)数
      3. random_state:随机种子(被指定后,每次构造数据相同)
      4. cluster_std:数据离散程度
      5. n_features:特征数,默认是2
    2. 返回值有样本数据集X和标签y,且都是ndarray对象
1
2
3
4
In[3]: type(make_blobs)
Out[3]: function
In[4]: X, y = make_blobs(n_samples=50, centers=2,random_state=0, cluster_std=0.60)
In[5]: plt.scatter(X[:, 0], X[:, 1], c=y,  s=50, cmap='autumn')
paste-223913825009667.jpg
  1. 模型选择
    1. 使用svm.SVC(C=1.0, kernel=’rbf’)来创建一个SVC对象,C是惩罚参数,默认是1,kernel是核函数,默认是rbf核函数。主要的属性有:
      1. support_vectors_:支持向量
    2. 主要的方法有:
      1. fit(X,y):根据给定的训练集X及标签y,拟合SVM模型
      2. decision_function(X)paste-93037581565955.jpg
        1
        2
        3
        4
        In[10]: model = SVC(kernel='linear')
           ...: model.fit(X, y)
           ...: type(model.fit(X, y))
        Out[10]: sklearn.svm.classes.SVC
        1
        2
        3
        4
        5
        In[8]: model.support_vectors_
        Out[8]: 
        array([[0.44359863, 3.11530945],
               [2.33812285, 3.43116792],
               [2.06156753, 1.96918596]])
  1. 绘制图形
    1. 调用函数  
      1
      plot_svc_decision_function(model)
    2. 结果显示                paste-291843027763203.jpg
 1
 2
 3
 4  
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def plot_svc_decision_function(model, ax=None, plot_support=True):
    """Plot the decision function for a 2D SVC"""
    if ax is None:
        ax = plt.subplot(111)
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    # create grid to evaluate model
    x = np.linspace(xlim[0], xlim[1], 30)
    y = np.linspace(ylim[0], ylim[1], 30)
    X,Y = np.meshgrid(x, y)
    xy = np.vstack([X.flatten(), Y.flatten()]).T
    P = model.decision_function(xy).reshape(X.shape)

    # plot decision boundary and margins
    #levels是等高线高度 alpha是透明度 linestyles与levels对应
    ax.contour(X, Y, P, colors='k',
               levels=[-1, 0, 1], alpha=0.5,
               linestyles=['--', '-', '--'])

    # plot support vectors
    if plot_support:
        ax.scatter(model.support_vectors_[:, 0],
                   model.support_vectors_[:, 1],
                   s=500,c='',edgecolors='black')





posted on 2018-10-08 08:44 LeisureZhao 阅读(...) 评论(...) 编辑 收藏

opencv svm训练问题

12-16

编写了个svm代码,但是运行到train那步就出错,求大神告知错误原因,非常感谢!rn#includern#includern#includernusing namespace std;rnusing namespace cv;rnusing namespace cv::ml;rnrnint r=10,last_x=0,last_y=0,drawing=0;rnMat asd(512, 512, CV_8UC1), clean_asd;rnvoid draw(int x, int y)rnrn circle(asd, Point(x, y), r, Scalar(0, 0, 0), -1, 8);rn asd.copyTo(clean_asd);rn imshow("手写板", clean_asd);rnrnvoid drawCursor(int x, int y)rnrn asd.copyTo(clean_asd);rn circle(clean_asd, Point(x, y), r, Scalar(0, 0, 0), -1, 8);rnrnvoid on_mouse(int event, int x, int y, int flags, void* param)rnrn last_x = x;rn last_y = y;rn drawCursor(x, y);rn //Select mouse Eventrn if (event == CV_EVENT_LBUTTONDOWN)rn rn drawing = 1;rn draw(x, y);rn rn else if (event == CV_EVENT_LBUTTONUP)rn rn drawing = 0;rn rn else if (event == CV_EVENT_MOUSEMOVE && flags & CV_EVENT_FLAG_LBUTTON)rn rn if (drawing)rn draw(x, y);rn rnrnint xmax = 0, xmin = 0;rnvoid findx(Mat src)rnrn int i, j,k,a=0,minfind = 0;rn Mat dst = src.clone();rn threshold(dst, dst, 128, 255, THRESH_BINARY_INV);rn for (i = 0; i < dst.cols; i++)rn rn for (j = 0; j < dst.rows; j++)rn rn uchar* data = dst.ptr(j);rn a += data[i];rn rn if (a>1)rn rn xmax = i;rn if (!minfind)rn rn xmin = i;rn minfind = 1;rn rn rn a = 0;rn rnrnint ymax = 0, ymin = 0;rnvoid findy(Mat src)rnrn int i, j, a = 0, minfind = 0;rn Mat dst = src.clone();rn threshold(dst, dst, 128, 255, THRESH_BINARY_INV);rn for (i = 0; i < dst.rows; i++)rn rn uchar* data = dst.ptr(i);rn for (j = 0; j < dst.cols; j++)rn rn a += data[j];rn rn if (a>1)rn rn ymax = i;rn if (!minfind)rn rn ymin = i;rn minfind = 1;rn rn rn a = 0;rn rnrnint xrange, yrange;rnvoid findrect(Mat src)rnrn rn findx(src);rn findy(src);rn xrange = xmax - xmin;rn yrange = ymax - ymin;rnrnMat data[10];rnstring fname[] = "C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\0\\*.pbm", "C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\1\\*.pbm",rn"C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\2\\*.pbm" ,"C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\3\\*.pbm",rn"C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\4\\*.pbm" ,"C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\5\\*.pbm",rn"C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\6\\*.pbm" ,"C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\7\\*.pbm",rn"C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\8\\*.pbm" ,"C:\\Users\\shinelon\\Desktop\\数字\\数字\\OCR\\9\\*.pbm" ;rnvoid read(void)rnrn vector files;rn int i,j;rn for (j = 0; j < 10; j++)rn rn glob(fname[j], files, false);rn for (i = 0; i < files.size(); i++)rn rn Mat test = imread(files[i]);rn data[j].push_back(test);rn rn rnrnvoid getTrainData(Mat *_train_data, Mat *_train_label)rnrn int i, j, k;rn vector files;rn _train_data->release();//清零rn _train_label->release();//清零rn for (j = 0; j < 10; j++)rn rn glob(fname[j], files, false);rn for (i = 0; i < files.size(); i++)rn rn Mat test = imread(files[i],0);//128*128rn _train_data->push_back(test.reshape(0, 1));//reshape第一个为通道数,0表示不变,第二个为行数,0表示不变rn rn rn int buf[11] = 0,1,2,3,4,5,6,7,8,9;rn for (j = 0; j < 10; j++)rn rn for (i = 0; i < 100; i++)rn rn _train_label->push_back(buf[j]);rn rn rnrnMat dst(128, 128, CV_32SC1);rnvoid svm()rnrn Mat train_data, train_label;rn getTrainData(&train_data, &train_label); //获取样本训练数据rn train_data.convertTo(train_data, CV_32SC1);rn train_label.convertTo(train_label, CV_32SC1);rn Mat train_data2 = Mat::ones(1000, 3, CV_32SC1);rn // 设置训练数据rn Ptr tData = TrainData::create(train_data, ROW_SAMPLE, train_label);rn rn // 设置参数rn Ptr model = SVM::create();rn model->setType(SVM::C_SVC);rn model->setKernel(SVM::LINEAR);rnrn model->setC(1);rn rn model->train(tData);rnrnrnint main()rnrn Mat image(512, 512, CV_8UC1);rn namedWindow("手写板", WINDOW_AUTOSIZE);rn asd = Scalar::all(255);rn asd.copyTo(clean_asd);rn setMouseCallback("手写板",on_mouse,0);rn while (1)rn rn char c;rn imshow("手写板", clean_asd);rn c=waitKey(10);rn if(c==27)rn break;rn else if (c=='r')rn rn asd = Scalar::all(255);rn drawCursor(last_x, last_y);rn rn else if (c=='='||c=='+')rn rn r++;rn drawCursor(last_x, last_y);rn rn else if ((c=='-')&&(r>1))rn rn r--;rn drawCursor(last_x, last_y);rn rn else if (c == 'a')rn rn findrect(clean_asd);rn image = clean_asd( Range(ymin, ymin + yrange),Range(xmin, xmin + xrange));rn resize(image, dst, dst.size());rn dst = dst.reshape(0, 1);rn svm();rn namedWindow("asd", WINDOW_AUTOSIZE);rn imshow("asd", dst);rn rn rn return 0;rn

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试