参考:https://www.heywhale.com/mw/project/5dd3946900b0b900365f3a48
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import sklearn.datasets
import sklearn.linear_model
#如果你在生成随机数之前不设置种子值,NumPy会使用系统时间作为默认的种子值,从而产生每次运行时都不同的随机数序列。
def sigmoid(x):
s = 1/(1+np.exp(-x))
return s
def layer_sizes(X, Y):
n_x = X.shape[0] #取决于输入X,单个样本所含的数据数目
n_y = Y.shape[0] #取决输出Y,取决于输出Y,n_y个参数,列:列个值
n_h = 4 #自由设置,单层神经网络,隐藏层的节点数
return (n_x, n_h, n_y)
def initialize_parameters(n_x, n_h, n_y):
np.random.seed(2)
W1 = np.random.randn(n_h,n_x)*0.01 #n_h是该层节点数,n_x为单个样本的数据数,没有转置
#使用随机数的原因是如果用相同的数,那么就没必要分几个行,一个行即可
#rand服从均匀分布0-1,值在0-1之间
#randn该函数和rand()函数比较类似,只不过运用该函数之后返回的结果是服从均值为0,方差为1的标准正态分 布,而不是局限在0-1之间,也可以为负值
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h)*0.01 #梯度下降的速度问题,如果值过大,导致迭代缓慢
b2 = np.zeros((n_y, 1))
assert (W1.shape == (n_h, n_x))
assert (b1.shape == (n_h, 1))
assert (W2.shape == (n_y, n_h))
assert (b2.shape == (n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
def forward_propagation(X, parameters):
#根据参数
W1 = parameters["W1"] #4*2
b1 = parameters["b1"] #4*1
W2 = parameters["W2"]
b2 = parameters["b2"]
#计算相关的值
Z1 = np.dot(W1,X) + b1
A1 = np.tanh(Z1) #双曲正切函数,优于sigmoid函数
Z2 = np.dot(W2,A1) + b2
A2 = sigmoid(Z2)
assert(A2.shape == (1, X.shape[1]))
cache = {"Z1": Z1,
"A1": A1,
"Z2": Z2,
"A2": A2}
return A2, cache
def compute_cost(A2, Y, parameters):
m = Y.shape[1] # number of example,样本数
logprobs = Y*np.log(A2) + (1-Y)* np.log(1-A2)
cost = (-1/m)*np.sum(logprobs) # no need to use a for loop! 总费用
cost = np.squeeze(cost) # makes sure cost is the dimension we expect. 去1
assert(isinstance(cost, float))
return cost
def backward_propagation(parameters, cache, X, Y):
m = X.shape[1]
W1 = parameters["W1"]
W2 = parameters["W2"]
A1 = cache["A1"]
A2 = cache["A2"]
#矩阵求导
dZ2= A2 - Y
dW2 = 1 / m * np.dot(dZ2,A1.T)
db2 = 1 / m * np.sum(dZ2,axis=1,keepdims=True)
dZ1 = np.dot(W2.T,dZ2) * (1-np.power(A1,2))
dW1 = 1 / m * np.dot(dZ1,X.T)
db1 = 1 / m * np.sum(dZ1,axis=1,keepdims=True)
grads = {"dW1": dW1,
"db1": db1,
"dW2": dW2,
"db2": db2}
return grads
def update_parameters(parameters, grads, learning_rate = 1.2):
#更新参数
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
dW1 = grads["dW1"]
db1 = grads["db1"]
dW2 = grads["dW2"]
db2 = grads["db2"]
W1 = W1 - learning_rate * dW1
b1 = b1 - learning_rate * db1
W2 = W2 - learning_rate * dW2
b2 = b2 - learning_rate * db2
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
np.random.seed(3)
#获取神经网络的框架
n_x = layer_sizes(X, Y)[0]
n_y = layer_sizes(X, Y)[2]
#初始化参数,n_h很自由
parameters = initialize_parameters(n_x,n_h,n_y)
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b1 = parameters["b2"]
for i in range(0, num_iterations):
# Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".
A2,cache = forward_propagation(X,parameters)
# Cost function. Inputs: "A2, Y, parameters". Outputs: "cost".
cost = compute_cost(A2,Y,parameters)
# Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads".
grads = backward_propagation(parameters,cache,X,Y)
# Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters".
parameters = update_parameters(parameters,grads)
# Print the cost every 1000 iterations
if print_cost and i % 1000 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
#目的是为了训练出参数,w,b的值
return parameters
def nn_model_test_case(): #测试数据集
np.random.seed(1)
X_assess = np.random.randn(2, 3)
Y_assess = np.random.randn(1, 3)
return X_assess, Y_assess
X_assess, Y_assess = nn_model_test_case()
print(X_assess)
parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=False)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
输出:
def predict(parameters, X):
#用训练出来的参数去预测,前向传播的过程
A2, cache = forward_propagation(X, parameters)
predictions = np.round(A2) #相当于一个if判断
return predictions
def predict_test_case(): #测试数据集
np.random.seed(1)
X_assess = np.random.randn(2, 3)
parameters = {'W1': np.array([[-0.00615039, 0.0169021 ],
[-0.02311792, 0.03137121],
[-0.0169217 , -0.01752545],
[ 0.00935436, -0.05018221]]),
'W2': np.array([[-0.0104319 , -0.04019007, 0.01607211, 0.04440255]]),
'b1': np.array([[ -8.97523455e-07],
[ 8.15562092e-06],
[ 6.04810633e-07],
[ -2.54560700e-06]]),
'b2': np.array([[ 9.14954378e-05]])}
return parameters, X_assess
parameters, X_assess = predict_test_case()
predictions = predict(parameters, X_assess)
print("predictions mean = " + str(np.mean(predictions)))
输出: