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

来源:互联网 发布:linux 重启后挂载失败 编辑:程序博客网 时间:2024/04/24 19:45

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-8import numpy as npimport scipy as spfrom sklearn import svmfrom sklearn.cross_validation import train_test_splitimport 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,胖代表1y[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.]

1 0
原创粉丝点击