机器学习算法之七:5分钟上手SVM

时间:2022-02-23 17:37:04

1.案例:承袭Decision Tree的案例数据,同样用身高和体重来界定胖瘦。如下文字档(7.SVM.txt),三个栏位各代表身高(m)、体重(kg)与胖瘦(thin/fat)。

2.问题:现在有两人,其中一位身高1.6m、体重30kg,另一位身高1.6m、体重300kg,请问各是胖是瘦呢?

3.数据文档:7.SVM.txt,内容如下。

1.5 40 thin
1.5 50 fat
1.5 60 fat
1.6 40 thin
1.6 50 thin
1.6 60 fat
1.6 70 fat
1.7 50 thin
1.7 60 thin
1.7 70 fat
1.7 80 fat
1.8 60 thin
1.8 70 thin
1.8 80 fat
1.8 90 fat
1.9 80 thin
1.9 90 fat

4.Sampe code:

#coding: utf-8
import numpy as np
import scipy as sp
from sklearn import svm
from sklearn.cross_validation import train_test_split
import matplotlib.pyplot as plt

#----载入资料
data = []
labels = []
with open("7.svm.txt") as ifile:
for line in ifile:
tokens = line.strip().split(' ')
data.append([float(tk) for tk in tokens[:-1]]) #读取身高与体重数据
labels.append(tokens[-1]) #读取胖瘦

#将资料放是array中
x = np.array(data)
labels = np.array(labels)
y = np.zeros(labels.shape)

#标签转换为0/1,瘦代表0,胖代表1
y[labels=='fat']=1

#训练模型、提取特徵
#参数说明:linear代表是选择线性模型
clf=svm.SVC(kernel='linear')
clf.fit(x,y)

#----预测并输出结果
print clf.predict([[1.6, 30]])
print clf.predict([[1.6, 300]])

5.结果:

[ 0.]
[ 1.]