pythonがsvmを実現して、トビの花を分類します(トビの尾の花のデータがあります).

7719 ワード

トビの花の分類トビの花データリンク:http://bj.bcebos.com/v1/ai-studio-online/93e8a07d6624465c943f60a0b4ec5fd959d44b5e5453410a8b2452ed3720c32f?responseContentDisposition=attachment%3B%20filename%3Diris.data&authorization=bce-auth-v 1%2 F 0 ef 6765 c 1 e 4918 bc 0 d 3 c 3 c 3 c 6 d 1%2 F 2010 8-12-12 T 14%3 A 57%3 A 54 Z%2 F-1%2 F 2 cbe 86672 d 2 d 2 d 44278 cc 3 f 7678930700 c 5 aeffa 85569803 fd 6 e 7 d 625 b 43ca 2方法一
import numpy as np
from sklearn import model_selection as mo
from sklearn import svm
import matplotlib.pyplot as plt
from matplotlib import colors
import matplotlib as mpl

def iris_type(s):
    #       ,        string  int
    it = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2}
    return it[s]

data = np.loadtxt(r'D:\PycharmProjects\untitled\   \iris.data', dtype=float, delimiter=',', converters={4:iris_type})
'''
def loadtxt(fname, dtype=float, comments='#', delimiter=None,
            converters=None, skiprows=0, usecols=None, unpack=False,
            ndmin=0, encoding='bytes', max_rows=None):
'''
x, y = np.split(data, (4, ), axis=1)
x_train, x_test, y_train, y_test = mo.train_test_split(x, y, random_state=1, test_size=0.3)
'''
train_data:         
train_target:        
test_size:      , 0-1  ,      ;              
random_state:       。
     :            ,          ,            。       1,                      。  0   ,       。
           ,                   :
    ,        ;    ,               。
'''
clf = svm.SVC(C=0.5, kernel='linear', decision_function_shape='ovr')
clf.fit(x_train, y_train, sample_weight=None)
print(x_train.shape)
#print(x_train)
#print(y_train)
#print(x_test)
#print(y_test)
acc = clf.predict(x_train) == y_train.flat
print('Accuracy:%f' % (np.mean(acc)))
x1 = x[:, :2]
x_train, x_test, y_train, y_test = mo.train_test_split(x1, y,random_state=1, test_size=0.3)
clf.fit(x_train, y_train, sample_weight=None)
x1_min, x1_max = x1[:, 0].min(), x1[:, 0].max()
x2_min, x2_max = x1[:, 1].min(), x1[:, 1].max()
x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j]
g_test = np.stack((x1.flat, x2.flat), axis=1)
print(g_test.shape)
g_map = clf.predict(g_test).reshape(x1.shape)
y = clf.predict(x_test)
cm_light = colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dack = colors.ListedColormap(['r', 'g', 'b'])
plt.pcolormesh(x1, x2, g_map, cmap=cm_light)
plt.scatter(x_test[:, 0], x_test[:, 1],c=np.squeeze(y.flat), s=50, cmap=cm_dack)
plt.plot()
plt.grid()
plt.show()

python实现svm对鸢尾花进行分类(附带鸢尾花数据)_第1张图片方法2
import numpy as np
from matplotlib import colors
from sklearn import svm
from sklearn.svm import SVC
from sklearn import model_selection
import matplotlib.pyplot as plt
import matplotlib as mpl

def load_data():
    #     
    data = np.loadtxt(r'D:\PycharmProjects\untitled\   \iris.data', dtype=float, delimiter=',', converters={4: iris_type})

    return data


def iris_type(s):
    #       ,        string  int
    it = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2}
    return it[s]


    #      
def classifier():
    clf = svm.SVC(C=0.5,  #        
                  kernel='linear',  #     kenrel="rbf":   
                  decision_function_shape='ovr')  #     

    return clf


def train(clf, x_train, y_train):
    # x_train:     
    # y_train:       
    #     
    clf.fit(x_train, y_train.ravel(),sample_weight=None)  #  flnumpy.ravelatten     


def show_accuracy(a, b, tip):
    acc = a.ravel() == b.ravel()
    print(a)
    print(b)
    print(acc)
    print('%s Accuracy:%.3f' % (tip, np.mean(acc)))


def print_accuracy(clf, x_train, y_train, x_test, y_test):
    #print(x_train)
    show_accuracy(clf.predict(x_train), y_train, 'traing data')
    show_accuracy(clf.predict(x_test), y_test, 'testing data')
    #print(x_train)
    #print(y_train.ravel())
    #print(clf.predict(x_train))


def draw(clf, x):  #          ,    :     
    '''
    print(x.shape)
    (150, 2)
    '''
    iris_feature = 'sepal length', 'sepal width', 'petal lenght', 'petal width'
    x1_min, x1_max = x[:, 0].min(), x[:, 0].max()  #  0    
    x2_min, x2_max = x[:, 1].min(), x[:, 1].max()  #  1    

    x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j]  #        
    grid_test = np.stack((x1.flat, x2.flat), axis=1)  #    
    '''
    print(grid_test.shape)
    (40000, 2)
    '''
    #print('grid_test:
', grid_test) z = clf.decision_function(grid_test) #print('the distance to decision plane:
', z) grid_hat = clf.predict(grid_test) # 【0,0.。。。2,2,2】 ''' print(grid_hat.shape) (40000,) ''' #print('grid_hat:
', grid_hat) grid_hat = grid_hat.reshape(x1.shape) # reshape grid_hat x1 # 3*3 e, e.shape() 3*3, 3 3 cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF']) ''' x3 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j] # print(x3.shape) (2, 200, 200) print(x1.shape) print(x2.shape) print(grid_hat.shape) (200, 200) (200, 200) x1+x2=x3 (200, 200) ''' cm_dark = mpl.colors.ListedColormap(['g', 'b', 'r']) print(grid_hat.shape) plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light) # pcolormesh(x,y,z,cmap) # x1,x2,grid_hat,cmap=cm_light 。 plt.scatter(x[:, 0], x[:, 1], c=np.squeeze(y), edgecolor='k', s=50, cmap=cm_dark) # plt.scatter(x_test[:, 0], x_test[:, 1], s=120, facecolor='none', zorder=10) # plt.xlabel(iris_feature[0], fontsize=20) plt.ylabel(iris_feature[1], fontsize=20) plt.xlim(x1_min, x1_max) plt.ylim(x2_min, x2_max) plt.title('svm in iris data classification', fontsize=30) plt.grid() plt.show() # : data = load_data() x, y = np.split(data, (4,), axis=1) # x ,y ,x ,y # data=(150,5),x=(150,4),y=(150,1) # x_train,x_test,y_train,y_test = , , , x_train, x_test, y_train, y_test = model_selection.train_test_split(x, y, random_state=1, test_size=0.3) # 70%30% clf = classifier() # svm train(clf, x_train, y_train) # print_accuracy(clf, x_train, y_train, x_test, y_test) # ( ) data = load_data() #print(np.shape(data)) x,y = np.split(data,(4,),axis=1) # x ,y ,x ,y #print(np.shape(x)) #print(np.shape(y)) x=x[:,:2] # , , #print(np.shape(x)) x_train,x_test,y_train,y_test=model_selection.train_test_split(x,y,random_state=1,test_size=0.3) clf = classifier() train(clf,x_train,y_train) print_accuracy(clf,x_train,y_train,x_test,y_test) draw(clf,x)
python实现svm对鸢尾花进行分类(附带鸢尾花数据)_第2张图片