Wu Enda's homework for the second week of the first lesson of in-depth learning --- solved various bugs in the original homework due to the low version (attached the modified complete code and homework data set)

C1W2-Logistic Regression with a Neural Network mindset

Reference article link: https://github.com/Kulbear/deep-learning-coursera/blob/master/Neural%20Networks%20and%20Deep%20Learning/Logistic%20Regression%20with%20a%20Neural%20Network%20mindset.ipynb

Homework requirements: Use the thinking of neural network to build a logistic regression classifier to identify whether the picture is a cat, and use your own picture to detect

1. Import various modules that need to be used

Original code:

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

%matplotlib inline

after edited:

import numpy as np
import matplotlib.pyplot as plt
import h5py
from PIL import Image
import imageio
from lr_utils import load_dataset

%matplotlib inline

Because of the scipy version problem. scipy>=1.0.0 no longer contains the functions imread, imresize , the explanation and solution given by the official website are as follows:

`imread` is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use ``imageio.imread`` instead.

imresize is deprecated! imresize is deprecated in SciPy 1.0.0, and will be removed in 1.3.0. Use Pillow instead: numpy.array(Image.fromarray(arr).resize()).

You can check the version of each module installed by yourself through the pip list in the command line window cmd, because I installed it directly through the pip install XXX command, so the installed version is the latest version

(Because there was a problem at the time, some bloggers on the Internet said that the scipy version was too high, so the scipy version was lowered)

According to the instructions on the official website, scipy was removed and replaced with imageio, and we will see how to use it later

2. Solve RuntimeWarning: divide by zero encountered in log; RuntimeWarning: invalid value encountered in multiply, etc., and the result appears nan value

These bugs are all caused by the use of the log function. During the training process, the parameter of the log function may be 0. At this time, the calculation result tends to be infinite, that is, the cost overflows. The printed result is the nan value, while The warning is that the log parameter is too large or too small, so just optimize the log function and these problems will be solved.

Solution:

#正向传播和反向传播
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+1e-5)+(1-Y)*(np.log(1-A)))
    cost = np.squeeze(cost)
    assert(cost.shape == ())
    
    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)
    
    grads = {"dw":dw,"db":db}
    return grads,cost

Add a small andvalue in the parentheses of the np.log function, which is added here 10^-5.

3. imread, an alternative to imresize

  • imread

Original code:

my_image = "my_image.jpg"
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))

 After modification:

image = np.array(imageio.imread(r"cat.jpg"))
  • envious

Original code:

my_image = scipy.misc.imresize(image, size=(num_px, num_px)).reshape((1, num_px * num_px * 3)).T

After modification:

my_image = np.array(Image.fromarray(image).resize((num_px, num_px),Image.ANTIALIAS)) #ANTIALIAS表示保留图片所有像素,不丢失原有像素
my_image = my_image.reshape((1, num_px * num_px * 3)).T

Attach the code to test your own download image:

d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.5, print_cost = True)
image = np.array(imageio.imread(r"cat.jpg"))
num_px=64
my_image = np.array(Image.fromarray(image).resize((num_px, num_px),Image.ANTIALIAS))
my_image = my_image.reshape((1, num_px * num_px * 3)).T
#print(image)
#plt.imshow(my_image)
my_predicted_image = predict(d["w"], d["b"], my_image)
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") +  "\" picture.")

final result:

 

Guess you like

Origin blog.csdn.net/weixin_42149550/article/details/99876301