碎碎念:达叔说 逻辑回归相当于小型的神经网络 就是没有隐含层嘛
先简单介绍一下需要做的事情 共分为7步,接下来将达叔作业里的所有程序 粘贴出来
1.,导入数据集,查看数据格式
操作:train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
train_set_x_orig.shape
一般会得到四个值(n,num_px,num_px,3) n 是训练集的个数,如 100张猫咪的训练照片, num_px 是图片的长宽?比如 64,64 代表一张64×64的图片 3 代表 RGB三个值
2.reshape
操作:train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
X_flatten=X.shape(X.shape[0],-1).T 此操作可以将(a,b,c,d)的矩阵转化为(b*c*d,a)的二维矩阵
将(n,num_px,num_px,3)维度的数据reshape成(num_px×num_px×3,n)样子的数据,如(12288,n)12288行,n列。每一列是一张图片,每张图片有12288个特征。n代表 共有n张图片。这样所有训练集的维度就是一样的了
同时不要忘记对测试集也进行相同的操作
3.预处理
操作:train_set_x = train_set_x_flatten/255.
一般来说 预处理包含center 去中心化和standardize标准化两步,但是因为这里每个12288个值,其实每一值代表图片上64×64个点中的RGB中的一个值,所以每个值得范围是(0,255)。所以每个值除以255就ok了
4.初始化参数
操作:w = np.zeros((dim, 1))
b = 0
一般来说有多少个输入特征,行数 这里是12288 一般就有多少个w
5.代价函数最小化(利用梯度下降法)
参考公式
操作: m = X.shape[1]
A = sigmoid(np.dot(w.T, X) + b) # compute activation 因为w是一个与X的行数一样,一列的向量 ,所以求点积时,需要转置再求
cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) # compute cost
dw = 1 / m * np.dot(X, (A - Y).T)
db = 1 / m * np.sum(A - Y)
w = w - learning_rate * dw
b = b - learning_rate * db
6.更换学习率 α 画图观察不同学习率下的 cost变化情况 得到算法的正确率
操作:learning_rates = [0.01, 0.001, 0.0001]
plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"])
7.得出结论
一步一步定义函数,然后定义模型,在模型中调用函数,画图观察cost 确定合适的学习率α
程序部分
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
def sigmoid(z):
s = 1 / (1 + np.exp(-z))
return s
def sigmoid_derivative(x):
s = sigmoid(x)
ds = s * (1 - s)
return ds
def initialize_with_zeros(dim):
w = np.zeros((dim, 1))
b = 0
return w, b
def propagate(w, b, X, Y):
m = X.shape[1]
A = sigmoid(np.dot(w.T, X) + b) # compute activation
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)
cost = np.squeeze(cost)
grads = {"dw": dw,
"db": db}
return grads, cost
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
#通过梯度下降法实现w,b的更新
costs = []
for i in range(num_iterations):
# Cost and gradient calculation (≈ 1-4 lines of code)
grads, cost = propagate(w, b, X, Y)
# Retrieve derivatives from grads
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
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]):
# Convert probabilities A[0,i] to actual predictions p[0,i]
if A[0, i] <= 0.5:
Y_prediction[0, i] = 0
else:
Y_prediction[0, i] = 1
return Y_prediction
#将以上所有函数结合在一起形成一个model
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
#print_cost -- Set to true to print the cost every 100 iterations
D={}
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)
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))))
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)
#把学习率为0.05 情况下的cost 图画出来
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
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()