吴恩达机器学习-编程练习-ex6.1

本节练习是为了应用SVM算法,并灵活运用C和gamma参数

首先load数据集并plot

#----------------------------part1---------------------------#
#读取数据1,并将数据整理成可识别的格式
path = 'C:\\Users\Huanuo\PycharmProjects\ml\ex6_svm\ex6\ex6data1.mat'
m = loadmat(path)
df1 = pd.DataFrame(m['X'])
df2 = pd.DataFrame(m['y'])
df3 = pd.concat([df1,df2],axis=1)
df3.columns = [1,2,3]
#将数据可视化
n = 1024
X1 = df3.loc[df3[3]==1,1]
Y1 = df3.loc[df3[3]==1,2]
scatter(X1,Y1,marker = '*',color = 'r')
X2 = df3.loc[df3[3]==0,1]
Y2 = df3.loc[df3[3]==0,2]
scatter(X2,Y2,marker = '+',color = 'y')
show()

吴恩达机器学习-编程练习-ex6.1_第1张图片
然后简单应用SVM算法,并plot线性拟合结果

#----------------------------part2---------------------------#
#进行线性核函数的训练,C=1
x_train,y_train = df1,df2
clf = SVC(kernel='linear')
clf.fit(x_train,y_train)
#可视化处理
w = clf.coef_
b = clf.intercept_#训练后模型的函数参数
x = np.arange(0,5)
y = (w[0,0]*x+b)/(-w[0,1])
scatter(X1,Y1,marker = '*',color = 'r')
scatter(X2,Y2,marker = '+',color = 'y')
plot(x,y)
show()

吴恩达机器学习-编程练习-ex6.1_第2张图片
然后尝试将C值调整到100,看一下拟合结果

#----------------------------part3---------------------------#
#进行线性核函数的训练,C=100
x_train,y_train = df1,df2
clf = SVC(kernel='linear',C=100)
clf.fit(x_train,y_train)
#可视化处理
w = clf.coef_
b = clf.intercept_#训练后模型的函数参数
x = np.arange(0,5)
y = (w[0,0]*x+b)/(-w[0,1])
scatter(X1,Y1,marker = '*',color = 'r')
scatter(X2,Y2,marker = '+',color = 'y')
plot(x,y)
show()

吴恩达机器学习-编程练习-ex6.1_第3张图片

你可能感兴趣的:(吴恩达机器学习-编程练习-ex6.1)