用Python进行神经网络逻辑回归

学习内容:

使用神经网络进行逻辑回归,学习算法的总体框架,包括初始化参数、计算成本函数和梯度、使用优化算法(梯度下降)

使用到的包:

numpy, matplotlib.pyplot, h5py, scipy, PIL.Image, scipy.ndimage, (lr_utils.load_dataset)

读取图片:

plt.imshow(train_set_x_orig[index]

了解训练集和测试集的维度:

train_set_x_orig 是shape为 (m_train, num_px, num_px, 3) 的array

可以通过train_set_x_orig[0]来取得m_train

为方便计算,一般要将图片的形状由(num_px, num_px, 3)转化为(num_px * num_px * 3, 1),使每一列的数组代表一张平铺的图片。

X_flatten = X.reshape(X.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

这里z = np.dot(w.T, x) + b

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

def initialize_with_zeros(dim):

w = np.zeros((dim, 1))

b = 0

return w, b

这里dim = num_px * num_px * 3

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

def propagate(w, b, X, Y):

m = X.shape[1]  # number of examples

A = sigmoid(np.dot(w.T, X) + b) # forward 

cost = - np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) / m

dw = np.dot(X, (A - Y).T) / m # backward

db = np.sum((A - Y)) / m

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):

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 interation %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]):

if A[0, i] <= 0.5:

Y_prediction[0, i] = 0

else:

Y_prediction[0, i] =1

return Y_prediction

模型:

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_interations, 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)) * 100))

print('test accuracy: {} %'.format(100 - np.mean(np.abs(Y_prediction_test)) * 100))

d = {'cost': cost, '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

读取图片:

index = 

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[d['Y_prediction_test'][0, index]].decode('utf-8') + '\' picture.')

图形化成本函数:

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_interations = 1500, learning_rate = i, print_cost = False)

print('\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()

测试新图片:

my_image = ' '

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.')

你可能感兴趣的:(用Python进行神经网络逻辑回归)