Skip to content

Commit fcfa5f4

Browse files
committed
新增机器学习测试代码
1 parent 265710c commit fcfa5f4

4 files changed

Lines changed: 167 additions & 0 deletions

File tree

‎test/sklearn/test_matplotlib.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# encoding: utf-8
2+
__author__ = 'zhanghe'
3+
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
7+
N = 5
8+
menMeans = (20, 35, 30, 35, 27)
9+
# menStd = (2, 3, 4, 1, 2)
10+
menStd = (1, 1, 1, 1, 1)
11+
12+
ind = np.arange(N) # the x locations for the groups
13+
width = 0.35 # the width of the bars
14+
15+
fig, ax = plt.subplots()
16+
rect_1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)
17+
18+
womenMeans = (25, 32, 34, 20, 25)
19+
# womenStd = (3, 5, 2, 3, 3)
20+
womenStd = (1, 1, 1, 1, 1)
21+
rect_2 = ax.bar(ind + width, womenMeans, width, color='y', yerr=womenStd)
22+
23+
# add some
24+
ax.set_ylabel('Scores')
25+
ax.set_title('Scores by group and gender')
26+
ax.set_xticks(ind + width)
27+
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
28+
29+
ax.legend((rect_1[0], rect_2[0]), ('Men', 'Women'))
30+
31+
32+
def auto_label(rect_bar):
33+
# attach some text labels
34+
for rect in rect_bar:
35+
height = rect.get_height()
36+
ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, '%d' % int(height),
37+
ha='center', va='bottom')
38+
39+
40+
auto_label(rect_1)
41+
auto_label(rect_2)
42+
43+
plt.show()

‎test/sklearn/test_svc.py‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# encoding: utf-8
2+
__author__ = 'zhanghe'
3+
4+
import numpy as np
5+
import scipy as sp
6+
from sklearn import svm
7+
from sklearn.cross_validation import train_test_split
8+
import matplotlib.pyplot as plt
9+
10+
data = []
11+
labels = []
12+
with open("test_svc.txt") as ifile:
13+
for line in ifile:
14+
tokens = line.strip().split(' ')
15+
data.append([float(tk) for tk in tokens[:-1]])
16+
labels.append(tokens[-1])
17+
18+
x = np.array(data)
19+
labels = np.array(labels)
20+
y = np.zeros(labels.shape)
21+
y[labels == 'fat'] = 1
22+
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.0)
23+
24+
h = .02
25+
# create a mesh to plot in
26+
x_min, x_max = x_train[:, 0].min() - 0.1, x_train[:, 0].max() + 0.1
27+
y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1
28+
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
29+
np.arange(y_min, y_max, h))
30+
31+
"""
32+
SVM
33+
"""
34+
# title for the plots
35+
titles = ['LinearSVC (linear kernel)',
36+
'SVC with polynomial (degree 3) kernel',
37+
'SVC with RBF kernel',
38+
'SVC with Sigmoid kernel']
39+
clf_linear = svm.SVC(kernel='linear').fit(x, y)
40+
# clf_linear = svm.LinearSVC().fit(x, y)
41+
clf_poly = svm.SVC(kernel='poly', degree=3).fit(x, y)
42+
clf_rbf = svm.SVC().fit(x, y)
43+
clf_sigmoid = svm.SVC(kernel='sigmoid').fit(x, y)
44+
45+
for i, clf in enumerate((clf_linear, clf_poly, clf_rbf, clf_sigmoid)):
46+
answer = clf.predict(np.c_[xx.ravel(), yy.ravel()])
47+
print(clf)
48+
print(np.mean(answer == y_train))
49+
print(answer)
50+
print(y_train)
51+
52+
plt.subplot(2, 2, i + 1)
53+
plt.subplots_adjust(wspace=0.4, hspace=0.4)
54+
55+
# Put the result into a color plot
56+
z = answer.reshape(xx.shape)
57+
plt.contourf(xx, yy, z, cmap=plt.cm.Paired, alpha=0.8)
58+
59+
# Plot also the training points
60+
plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.cm.Paired)
61+
plt.xlabel(u'身高')
62+
plt.ylabel(u'体重')
63+
plt.xlim(xx.min(), xx.max())
64+
plt.ylim(yy.min(), yy.max())
65+
plt.xticks(())
66+
plt.yticks(())
67+
plt.title(titles[i])
68+
69+
plt.show()

‎test/sklearn/test_svc.txt‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
152 46 ok
2+
156 47 ok
3+
160 49 ok
4+
162 50 ok
5+
164 51 ok
6+
166 52 ok
7+
168 54 ok
8+
170 56 ok
9+
172 58 ok
10+
176 60 ok
11+
152 66 fat
12+
156 67 fat
13+
160 69 fat
14+
162 70 fat
15+
164 71 fat
16+
166 72 fat
17+
168 74 fat
18+
170 76 fat
19+
172 78 fat
20+
176 80 fat

‎test/sklearn/test_svm.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# encoding: utf-8
2+
__author__ = 'zhanghe'
3+
4+
from sklearn import svm
5+
clf = svm.SVC()
6+
7+
8+
def learn(x, y):
9+
"""
10+
学习
11+
"""
12+
clf.fit(x, y)
13+
14+
15+
def predict(x):
16+
"""
17+
预测
18+
"""
19+
result = clf.predict(x)
20+
return result
21+
22+
23+
def test():
24+
"""
25+
测试
26+
"""
27+
x = [[0, 0], [1, 1]]
28+
y = [0, 1]
29+
learn(x, y) # 学习
30+
test_x = [[2., 2.], [.2, .2]]
31+
print predict(test_x) # 预测
32+
33+
34+
if __name__ == '__main__':
35+
test() # [1 0]

0 commit comments

Comments
 (0)