1 importnumpy as np2 importscipy.io as scio3 importmatplotlib.pyplot as plt4 importscipy.optimize as op5
6 #X:5000*400
7 #Y:5000*10
8 #a1:5000*401(后5000*400)
9 #z2:5000*25
10 #a2:5000*26(后5000*25)
11 #z3:5000*10
12 #a3:5000*10
13 #Theta1:25*401
14 #Theta2:10*26
15 #delta3:5000*10
16 #delta2:5000*25
17 #bigDelta1:25*401
18 #bigDelta2:10*26
19 #Theta1_grad:25*401
20 #Theta2_grad:10*26
21
22
23 #显示图片数据
24 defdisplayData(X):25 m = np.size(X, 0) #X的行数,即样本数量
26 n = np.size(X, 1) #X的列数,即单个样本大小
27 example_width = int(np.round(np.sqrt(n))) #单张图片宽度
28 example_height = int(np.floor(n / example_width)) #单张图片高度
29 display_rows = int(np.floor(np.sqrt(m))) #显示图中,一行多少张图
30 display_cols = int(np.ceil(m / display_rows)) #显示图中,一列多少张图片
31 pad = 1 #图片间的间隔
32 display_array = - np.ones((pad + display_rows * (example_height +pad),33 pad + display_cols * (example_width + pad))) #初始化图片矩阵
34 curr_ex = 0 #当前的图片计数
35 #将每张小图插入图片数组中
36 for j inrange(0, display_rows):37 for i inrange(0, display_cols):38 if curr_ex >=m:39 break
40 max_val =np.max(abs(X[curr_ex, :]))41 jstart = pad + j * (example_height +pad)42 istart = pad + i * (example_width +pad)43 display_array[jstart: (jstart + example_height), istart: (istart + example_width)] =\44 np.array(X[curr_ex, :]).reshape(example_height, example_width) /max_val45 curr_ex = curr_ex + 1
46 if curr_ex >=m:47 break
48 display_array =display_array.T49 plt.imshow(display_array,cmap=plt.cm.gray)50 plt.axis('off')51 plt.show()52
53
54 #计算hθ(z)
55 defsigmoid(z):56 g = 1.0 / (1.0 + np.exp(-z))57 returng58
59
60 #初始化Θ