Python從零開始(習題2.8和2.9)
阿新 • • 發佈:2019-02-05
前言():
{
因為工作的原因,這次更新的比較晚,以後試著跟上進度。
之後大部分的Python學習都是從《神經網路與機器學習第三版》中的習題出發的。
}
正文():
{
本次實驗習題比較簡單,所以主要收貨是對numpy的用法的熟悉。
習題2.8():
{
程式碼如下:
import numpy as np
#主要函式,其完全按照書上的公式編寫
def least_square_for_weight(input_data, input_label, lambda_=0): #①
data_amount=input_data.shape[0 ]
Rxx = [[0,0,0],
[0,0,0],
[0,0,0]]
rdx = [[0],
[0],
[0]]
i = 0
j = 0
while i < data_amount:
while j < data_amount:
Rxx = Rxx - np.reshape(np.insert(input_data[i],2,1),(3,1)) * np.insert(input_data[j],2,1)
j = j + 1
rdx = rdx - np.reshape(np.insert(input_data[i],2 ,1),(3,1)) * input_label[i]
i = i + 1
return np.dot(np.linalg.inv(Rxx+np.identity(3)*lambda_), rdx) #②
#計算並列印決策邊界(權值)
print(least_square_for_weight(np.loadtxt("training_sample.txt"), np.loadtxt("training_label.txt",'int')))
①剛開始我直接用lambda作變數名,發現其已經被Python定義了,其具體用法我參考了:http://blog.csdn.net/lemon_tree12138/article/details/50774827
②關於numpy的乘法,參考了http://blog.csdn.net/bbbeoy/article/details/72576863。如果想得到比乘數小的結果,就需要使用點積函式。值得注意的是,使用點積函式需要對齊,比如Rxx的計算就不能用點積函式。
結果如下(lambda_=0):
可以看出,決策邊界貼近x軸並稍微向逆時針方向偏轉。
}
習題2.9():
{
為了大概瞭解lambda_與決策邊界的關係,我用了空間散點圖。程式碼如下:
import numpy as np
#主要函式,其完全按照書上的公式編寫
def least_square_for_weight(input_data, input_label, lambda_=0): #①
data_amount=input_data.shape[0]
Rxx = [[0,0,0],
[0,0,0],
[0,0,0]]
rdx = [[0],
[0],
[0]]
i = 0
j = 0
while i < data_amount:
while j < data_amount:
Rxx = Rxx - np.reshape(np.insert(input_data[i],2,1),(3,1)) * np.insert(input_data[j],2,1)
j = j + 1
rdx = rdx - np.reshape(np.insert(input_data[i],2,1),(3,1)) * input_label[i]
i = i + 1
return np.dot(np.linalg.inv(Rxx+np.identity(3)*lambda_), rdx) #②
def data_displayer_in_3D(X, Y, Z):
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z, c='r', marker='o')
plt.show()
#顯示決策邊界的引數(y=kx+b中的k和b)和lambda_的空間曲線(100個點)
X = np.empty([1,100])
Y = np.empty([1,100])
Z = np.empty([1,100])
i = 0
while i < 100:
Z[0,i] = (i*0.03)*(i*0.03)*(i*0.03)*(i*0.03)*(i*0.03)*(i*0.03)*(i*0.03)*(i*0.03)*(i*0.03)*(i*0.03)
XY = least_square_for_weight(np.loadtxt("training_sample.txt"),np.loadtxt("training_label.txt",'int'),Z[0,i])
X[0,i] = -XY[0,0] / XY[1,0]
Y[0,i] = -XY[2,0] / XY[1,0]
if i%10 == 0:
print(i/10) #顯示進度
i = i + 1
data_displayer_in_3D(X, Y, Z)
結果如下:
k與lambda_:
b與lambda_:
可以看到,當lambda_在7500左右時,決策邊界有一次很大的變化;其他情況下,決策邊界接近x軸。至於為什麼,等到書看一段時間再解決{問題1}。
}
結語():
{
因為我手上的資料沒有本章和其他幾章的習題答案,所以也沒法很快確認是否正確。如果以後我發現錯誤了,再回來修改。
}