1-2神经网络编程基础

1:库

numpy
h5py
matplotlib
PIL、scipy

2:魔法函数

IPython组内预先定义好的函数,通过命令行语句形式访问

#加载包和数据
import numpy as np		#python科学计算中最重要的库
import matplotlib.pyplot as plt			#python画图的库
import h5py			#python与H5文件交互的库
import scipy		#python科学计算相关库
from PIL import Image		#python图像相关库
from scipy import ndimage		#ndimage为数据文件夹
from lr_utils import load_dataset		#???
%matplotlib inline		#IPython编译器内嵌绘图,可以省掉plt.show()
#加载数据集
#说明:带orig的后缀为图像数据集(train、test),后续将处理它们。不带orig后缀的为返回值,且不需要进行处理
train_set_x_orig
train_set_y
test_set_x_orig
test_Set_y
classes=load_dataset()

3:squeeze函数

A=squeeze(B)
如果B存在单行单列的维度,去掉即为B,反之则A、B元素相同

4:[ : , n ]

[: , n]取所有行第n个(第n+1列)元素
[n , :]取第一维下标为n(第n+1行)的元素所有值

5:classes函数

???

#一个图片例子
index = 3		#可以修改
plt.imshow(train_set_x_orig[index])			#显示索引的图片
print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") +  "' picture."
#运行结果:y = [0], it's a 'non-cat' picture.

6:BUG

深度学习中代码错误中最常见的就是:向量或矩阵维数对不上,写代码要多注意检查

7:shape函数

X.shape[n]——>X的第n维数据个数
X.shape——>X的维数信息(

m_train = train_set_x_orig.shape[0]		#训练样本的数目
m_test = test_set_x_orig.shape[0]		#测试样本的数目
num_px = train_set_x_orig.shape[1]		#训练图像的高(宽)
print ("Number of training examples: m_train = " + str(m_train))		#209
print ("Number of testing examples: m_test = " + str(m_test))		#50
print ("Height/Width of each image: num_px = " + str(num_px))		#64
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")		#(64,64,3)
print ("train_set_x shape: " + str(train_set_x_orig.shape))		#(209,64,64,3)
print ("train_set_y shape: " + str(train_set_y.shape))		#(1,209)
print ("test_set_x shape: " + str(test_set_x_orig.shape))		#(50,64,64,3)
print ("test_set_y shape: " + str(test_set_y.shape))		#(1,50)

8:reshape函数

X.reshape(X.shape[0],-1)重塑矩形形状,化为二维数据

train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T		#重塑矩形形状后转置,train_set_x_orig.shape[0]=209,身下的一维数据为其他维元素相乘的结果
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T
print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))		#(12288, 209)
print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))		#(12288, 50)
print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0]))		#[17 31 56 22 33]

9:数据集标准化

机器学习中常见的预处理步骤是:将数据集居中并标准化
要从每个示例中减去整个numpy数组的均值,再将每个示例除以numpy数组的标准差。
对图片数据集,只要将数据集的每一行除以255(像素通道的最大值),效果也差不多。

train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.

10:预处理新数据集的常见步骤

a.找出问题的尺寸和形状(m_train,m_test,num_px等)
b.重塑数据集,使每个示例现在都是大小为(num_px * num_px * 3,1)的向量
c.“标准化”数据

11:算法的一般框架

a.辅助功能
b.初始化参数
c.前向、后向传播
d.优化
e.所有功能整合到模型中
f.进一步分析

#辅助函数
def sigmoid(z):

	1/(1+np.exp(-z))   
    return s
    
print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2]))))		#sigmoid([0, 2]) = [0.5        0.88079708]

12:numpy.zeros函数

numpy.zeros(shape,dtype=float,order=‘c’)功能:返回一个给定形状和类型的用0填充的数组
shape:数组形状
dtypt:可选参数,默认为numpy.float64【t/b/i/u/f/c/o/s,a】
order:可选参数,C为行优先,F为列优先
eg:np.zeros((2,1))
array([[0.],
[0.]])

13:isinstance函数

isinstance(object,classinfo)——>判断两者是否为同类型,是返回True,否返回False
object:实例对象
classinfo:直接或间接类名,基本类型,由他们组成的元组

#初始化参数
def initialize_with_zeros(dim):

    w = np.zeros((dim,1))
    b = 0
    assert(w.shape == (dim, 1))
    assert(isinstance(b, float) or isinstance(b, int))   
    return w, b
dim = 2
w, b = initialize_with_zeros(dim)

print ("w = " + str(w))
print ("b = " + str(b))

'''w = [[0.]
 		[0.]]
   b = 0'''

14:dot函数

dot()函数:矩阵乘
*:逐个元素相乘
#前向、后向传播
def propagate(w, b, X, Y):

    m = X.shape[1]
    # 前向传播
    A = sigmoid(np.dot(w.T,X)+b)           
    cost = -1/(m*np.sum( Y*np.log(A) + (1-Y) * np.log(1-A) ) )          
    
    # 后向传播
    dw = 1/m*np.dot(X,(A-Y).T)
    db = 1/m*np.sum(A-Y)
    
    assert(dw.shape == w.shape)
    assert(db.dtype == float)
    cost = np.squeeze(cost)
    assert(cost.shape == ())
    
    grads = {"dw": dw,
             "db": db}
    
    return grads, cost
    
w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
grads, cost = propagate(w, b, X, Y)
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print ("cost = " + str(cost)) 

'''dw = [[0.99993216]
 		 [1.99980262]]
   db = 0.49993523062470574
   cost = 0.041666216857687836'''

15:grads函数

???

16:append函数

append(obj) :在列表末尾添加新的对象obj。

#优化
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):

    costs = []
    for i in range(num_iterations):
        grads, cost = propagate(w, b, X, Y)
        dw = grads["dw"]
        db = grads["db"]
        w = w - learning_rate * dw		#更新参数
        b = b - learning_rate * db		#更新参数
        
        if i % 100 == 0:
            costs.append(cost)
        if print_cost and i % 100 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))
   
    params = {"w": w,
              "b": b}    	#字典
    grads = {"dw": dw,
             "db": db}    	#字典
    return params, grads, costs
    
params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)
print ("w = " + str(params["w"]))
print ("b = " + str(params["b"]))
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print(costs)

'''w = [[0.1124579 ]
        [0.23106775]]
   b = 1.5593049248448891
   dw = [[0.90158428]
         [1.76250842]]
   db = 0.4304620716786828
   [0.041666216857687836]'''
def predict(w, b, X):
   
    m = X.shape[1]
    Y_prediction = np.zeros((1,m))
    w = w.reshape(X.shape[0], 1)
    A = sigmoid(np.dot(w.T, X) + b)

    for i in range(A.shape[1]):      
        if A[0,i]<=0.5:
            Y_prediction[0,i]=0
        else:
            Y_prediction[0,i]=1
    assert(Y_prediction.shape == (1, m))
    8
    return Y_prediction
    
print ("predictions = " + str(predict(w, b, X)))

'''predictions = [[1. 1.]]'''
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
  
    w, b = initialize_with_zeros(X_train.shape[0])
    parameters, grads, costs = optimize(w,b,X_train,Y_train,num_iterations,learning_rate,print_cost=False)
    
    w = parameters["w"]               #????
    b = parameters["b"]               #????
    
    Y_prediction_test = predict(w,b,X_test)
    Y_prediction_train = predict(w,b,X_train)

    print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
    print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
    
    d = {"costs": costs,
         "Y_prediction_test": Y_prediction_test, 
         "Y_prediction_train" : Y_prediction_train, 
         "w" : w, 
         "b" : b,
         "learning_rate" : learning_rate,
         "num_iterations": num_iterations}
    
    return d
    
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)

'''Cost after iteration 0: 0.000033
   Cost after iteration 100: 0.000039
   Cost after iteration 200: 0.000049
   Cost after iteration 300: 0.000061
   Cost after iteration 400: 0.000069
   Cost after iteration 500: 0.000075
   Cost after iteration 600: 0.000082
   Cost after iteration 700: 0.000088
   Cost after iteration 800: 0.000094
   Cost after iteration 900: 0.000100
   Cost after iteration 1000: 0.000107
   Cost after iteration 1100: 0.000113
   Cost after iteration 1200: 0.000119
   Cost after iteration 1300: 0.000125
   Cost after iteration 1400: 0.000131
   Cost after iteration 1500: 0.000137
   Cost after iteration 1600: 0.000144
   Cost after iteration 1700: 0.000150
   Cost after iteration 1800: 0.000156
   Cost after iteration 1900: 0.000163
   train accuracy: 99.04306220095694 %
   test accuracy: 70.0 %'''
#Example of a picture that was wrongly classified.
index = 1
plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[int(d["Y_prediction_test"][0,index])].decode("utf-8") +  "\" picture.")

'''y = 1, you predicted that it is a "cat" picture.'''

17:matplotlib.pyplot

plt.plot(* args,scalex = True,scaley = True,data = None,** kwargs )

1、x,y :数组或标量
数据点的水平/垂直坐标。 x值是可选的,默认为range(len(y))。
通常,这些参数是一维数组。
它们也可以是标量,也可以是二维的(在这种情况下,列代表单独的数据集)。
这些参数不能作为关键字传递。
2、fmt str,可选
格式字符串,例如’ro’表示红色圆圈。
格式字符串由颜色,标记和线条的一部分组成,fmt = ‘[marker][line][color]’
[color][marker][line]还支持其他组合,例如,但请注意,它们的解析可能不明确。
格式字符串只是用于快速设置基本行属性的缩写。
所有这些以及更多这些都可以通过关键字参数来控制。
此参数不能作为关键字传递。
3、数据可索引对象,可选
具有标签数据的对象。如果提供,请提供标签名称以在x和y中进行绘制。
注意:从技术上讲,第二个标签是有效的fmt,呼叫中存在一些歧义,可能是或。
在这种情况下,将选择前一种解释,但会发出警告。
可以通过添加空格式字符串来禁止显示警告 。
plot(‘n’, ‘o’, data=obj)plt(x, y)plt(y, fmt)plot(‘n’, ‘o’, ‘’, data=obj)
4、返回值
列表 Line2D,代表绘制数据的线列表。
5、其他参数
scalex,scaley bool,默认值:True
这些参数确定视图限制是否适合数据限制。这些值将传递到autoscale_view。
6、 kwargs Line2D属性,可选**
kwarg用于指定属性,例如线标签(用于自动图例),线宽,抗锯齿,标记面颜色。
来自官网参考连接

# 学习曲线图(costs)
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')		#X轴坐标
plt.xlabel('iterations (per hundreds)')		#Y轴坐标
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show()
learning_rates = [0.01, 0.001, 0.0001]
models = {}
for i in learning_rates:
    print ("learning rate is: " + str(i))
    models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)
    print ('\n' + "-------------------------------------------------------" + '\n')

for i in learning_rates:
    plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"]))

plt.ylabel('cost')
plt.xlabel('iterations')

legend = plt.legend(loc='upper center', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()

'''learning rate is: 0.01
   train accuracy: 99.52153110047847 %
   test accuracy: 68.0 %

   -------------------------------------------------------

   learning rate is: 0.001
   train accuracy: 88.99521531100478 %
   test accuracy: 64.0 %

   -------------------------------------------------------

   learning rate is: 0.0001
   train accuracy: 68.42105263157895 %
   test accuracy: 36.0 %'''
my_image = "cat_in_iran.jpg"  

fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T
my_predicted_image = predict(d["w"], d["b"], my_image)

plt.imshow(image)
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") +  "\" picture.")

注:仅供自己方便日后方便查阅


版权声明:本文为qq_43241756原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。