2_2逻辑回归在神经网络中的实现

机器学习:神经网络、正则化、多分类问题与Python代码实现 前言:本篇博文主要介绍神经网络(Neural network),介绍一下正则化用于神经网络防止过拟合,以及介绍多分类问题,然后通过Python代码实现相关模型。特别强调,其中大多理论知识来源于《统计学习方法_李航》和斯坦福课程翻译笔记以及Coursera机器学习课程。 本篇博文的理论知识都来自于吴大大的Coursera机器学习课程,人家讲的深入浅出,我就不一一赘述,只是简单概括一下以及记一下自己的见解。 阅读详情

# 2_2Logistic Regression with a Neural Network mindset#

2_2逻辑回归在神经网络中的实现

Welcome to your first (required) programming assignment! You will build a

logistic regression classifier to recognize cats. This assignment will step

you through how to do this with a Neural Network mindset, and so will also

hone your intuitions about deep learning.

Instructions:

- 注意事项:Do not use loops (for/while) in your code, unless the instructions explicitly

ask you to do so.

#

- Build the general architecture of a learning algorithm, including:

- Initializing parameters

- Calculating the cost function and its gradient

- Using an optimization algorithm (gradient descent)

- Gather all three functions above into a main model function, in the right order.

## 1、准备实验所要用的包

numpy用于向量计算,h5py识别格式是H5 file的图片,matplotlib画图

First, let’s run the cell below to import all the packages that you will

need during this assignment.

- numpy is the fundamental package for scientific computing

with Python.

- h5py is a common package to interact with a dataset

that is stored on an H5 file.

- matplotlib is a famous library to plot graphs in Python.

- PIL and scipy

are used here to test your model with your own picture at the end.

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

get_ipython().magic(‘matplotlib inline’)

## 2 - 熟悉我们的实验数据(Overview of the Problem set)

Problem Statement: You are given a dataset (“data.h5”) containing:

- a training set of m_train images labeled as cat (y=1) or non-cat (y=0)

- a test set of m_test images labeled as cat or non-cat

- each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB).

Thus, each image is square (height = num_px) and (width = num_px).

You will build a simple image-recognition algorithm that can correctly classify pictures as cat or non-cat.

Let’s get more familiar with the dataset. Load the data by running the following code.

Loading the data (cat/non-cat)

train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()

train_dataset数据集是209个图片,每个图片都是64*64像素,3表示3种颜色,Red,Blue,Green

test_dataset数据集是50个图片,每个图片都是64*64像素,3表示3种颜色,Red,Blue,Green

We added “_orig” at the end of image datasets (train and test) because we are going to

preprocess them. After preprocessing, we will end up with train_set_x and test_set_x

(the labels train_set_y and test_set_y don’t need any preprocessing).

Each line of your train_set_x_orig and test_set_x_orig is an array representing an image.

You can visualize an example by running the following code. Feel free also to change the

index` value and re-run to see other images.

2.1显示一个不太清晰的图片

index = 5
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.”)
plt.show()

classes是一个ndarry类型,保存2个值,一个是b’non-cat’,另一个是b’cat’

np.squeeze是去掉数组中维数为1的向量,如果不加这个函数,decode无法工作

train_set_y是一个(1,209)的一个行向量,train_set_y[:,index]意思是第index列元素的值

Many software bugs in deep learning come from having matrix/vector dimensions that don’t fit.

If you can keep your matrix/vector dimensions straight you will go a long way toward eliminating

many bugs.

Exercise: Find the values for:

- m_train (number of training examples)

- m_test (number of test examples)

- num_px (= height = width of a training image)

Remember that train_set_x_orig is a numpy-array of shape (m_train, num_px, num_px, 3).

For instance, you can access m_train by writing train_set_x_orig.shape[0].

2.2输出这几个关键参数的含义

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))#m_train = 209
print (“Number of testing examples: m_test = ” + str(m_test))#m_test = 50
print (“Height/Width of each image: num_px = ” + str(num_px))#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),行向量

**Expected Output for m_train=209, m_test=50 and num_px为64:

For convenience, you should now reshape images of shape (num_px, num_px, 3) in a numpy-array

of shape (num_px*num_px*3, 1). After this, our training (and test) dataset is a numpy-array

where each column represents a flattened image. There should be m_train (respectively m_test) # columns.

Reshape the training and test data sets so that images of size (num_px, num_px, 3) are

flattened into single vectors of shape (num_px*num_px*3, 1).

A trick when you want to flatten a matrix X of shape (a,b,c,d) to a matrix X_flatten

of shape (b*c*d, a) is to use:

X_flatten = X.reshape(X.shape[0], -1).T # X.T is the transpose of X

Reshape the training and test examples

2.3自己添加,测试用的,目的是搞懂图片像素的维度

“””
print(“train_set_x_orig:”)
print(train_set_x_orig)

print(“train_set_x_orig.shape[0]:”)
print(train_set_x_orig.shape[0])#209

print(“train_set_x_orig.shape[1]:”)
print(train_set_x_orig.shape[1])#64

print(“train_set_x_orig.shape[2]:”)
print(train_set_x_orig.shape[2])#64

print(“train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).shape:”)
print(train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).shape)#值为209,12288
“””
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T#值为12288,209的一个向量
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T#值为12288,50的一个向量
print(“train_set_x_flatten:”,train_set_x_flatten)

print (“train_set_x_flatten shape: ” + str(train_set_x_flatten.shape))#值为12288,209
print (“train_set_y shape: ” + str(train_set_y.shape))#值为1,209
print (“test_set_x_flatten shape: ” + str(test_set_x_flatten.shape))#值为12288,50
print (“test_set_y shape: ” + str(test_set_y.shape))#值为1,50
print (“sanity check after reshaping: ” + str(train_set_x_flatten[0:5,0]))

输出第0列从第0个到第4个元素,值为[17 31 56 22 33]

To represent color images, the red, green and blue channels (RGB) must be specified for each pixel,

and so the pixel value is actually a vector of three numbers ranging from 0 to 255.

One common preprocessing step in machine learning is to center and standardize your dataset,

meaning that you substract the mean of the whole numpy array from each example, and then divide

each example by the standard deviation of the whole numpy array. But for picture datasets, it is

simpler and more convenient and works almost as well to just divide every row of the dataset

by 255 (the maximum value of a pixel channel).

initial inputs in order to observe neuron activations. Then you backpropogate with the

gradients to train the model

But, it is extremely important for each feature to have a similar range such that our gradients

don’t explode. You will see that more in detail later in the lectures. !–>

Let’s standardize our dataset.

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

What you need to remember:

Common steps for pre-processing a new dataset are:

(1)Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, …)

(2)Reshape the datasets such that each example is now a vector of size (num_px*num_px* 3, 1)

(3)”Standardize” the data

## 3 - General Architecture of the learning algorithm

## 3 - ##一般的方法流程

It’s time to design a simple algorithm to distinguish cat images from non-cat images.

应该用一个算法去区分猫的图片和非猫的图片

You will build a Logistic Regression, using a Neural Network mindset. The following

Figure explains why Logistic Regression is actually a very simple Neural Network!

The cost is then computed by summing over all training examples:

Key steps:

In this exercise, you will carry out the following steps:

(1)Initialize the parameters of the model

(2)Learn the parameters for the model by minimizing the cost

(3)Use the learned parameters to make predictions (on the test set)

(4)Analyse the results and conclude

## 4 - Building the parts of our algorithm

## 4 - 构建自己的算法

The main steps for building a Neural Network are:

1. Define the model structure (such as number of input features)

2. Initialize the model’s parameters

3. Loop:

- Calculate current loss (forward propagation)

- Calculate current gradient (backward propagation)

- Update parameters (gradient descent)

You often build 1-3 separately and integrate them into one function we call model().

### 4.1 - 激活函数(Helper functions)

Using your code from “Python Basics”, implement sigmoid(). As you’ve seen in the

figure above, you need to compute sigmoid( w^T x + b) to make predictions. Use np.exp().

def sigmoid(z):
#Compute the sigmoid of z
#Arguments:z – A scalar or numpy array of any size.
#Return:s – sigmoid(z)
s = 1 / (1 + np.exp(-z))
return s

print (“sigmoid([0, 2]) = ” + str(sigmoid(np.array([0,2]))))#值为[ 0.5 0.88079708]

### 4.2 - 初始化参数(Initializing parameters)

初始化w和b的值

Implement parameter initialization in the cell below. You have to initialize

w as a vector of zeros. If you don’t know what numpy function to use,

look up np.zeros() in the Numpy library’s documentation.

GRADED FUNCTION: initialize_with_zeros

def initialize_with_zeros(dim):
#This function creates a vector of zeros of shape (dim, 1) for w
# and initializes b to 0.
#Argument:dim – size of the w vector we want (or number of parameters in this case)

#Returns:w -- initialized vector of shape (dim, 1)
#        b -- initialized scalar (corresponds to the bias)

w = np.zeros((dim, 1))#生成一个dim行,1列的向量
b = 0

assert(w.shape == (dim, 1))
assert(isinstance(b, float) or isinstance(b, int))
return w, b

测试上面的initialize_with_zeros函数

dim = 2
w, b = initialize_with_zeros(dim)
print (“w = ” + str(w))#w的值为[[0][0]]
print (“b = ” + str(b))#b的值为0

For image inputs, w will be of shape (num_px*num_px*3, 1).

### 4.3 - 正向传播和反向传播(Forward and Backward propagation)

Now that your parameters are initialized, you can do the “forward” and “backward”

propagation steps for learning the parameters.

Implement a function propagate() that computes the cost function and its gradient.

Forward Propagation:

- You get X

- You compute A

- You calculate the cost function: J

定义传播函数

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

Implement the cost function and its gradient for the propagation explained above

input Arguments:

#   w -- weights, a numpy array of size (num_px * num_px * 3, 1)
#   b -- bias, a scalar
#   X -- data of size (num_px * num_px * 3, number of examples)
#   Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size(1, number of examples)

Return:

#   cost -- negative log-likelihood cost for logistic regression
#   dw -- gradient of the loss with respect to w, thus same shape as w
#   db -- gradient of the loss with respect to b, thus same shape as b
#   Tips:Write your code step by step for the propagation. np.log(), np.dot()

m = X.shape[1]

# FORWARD PROPAGATION (FROM X TO COST)前向传播
#print("w.T:",w.T)#w.T: [[1 2]]
#print("np.dot(w.T,X):",np.dot(w.T,X))#np.dot(w.T,X): [[ 7 10]]
#print("np.dot(w.T,X)+b:",np.dot(w.T,X)+b)#np.dot(w.T,X)+b: [[ 9 12]]

A=sigmoid(np.dot(w.T,X)+b)
#print("A1:",A)#A的值为0.99987661,0.99999386

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

# print(“cost1:”,cost)

# BACKWARD PROPAGATION (TO FIND GRAD)反向传播
dw=1/m*np.dot(X,(A-Y).T)#dw/dz的值
db=1/m*np.sum(A-Y)#

assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)#把shape为1的维度去掉
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(“w=”,w)#输出w的值[[ 1][ 2]]
print(“b=”,b)#输出b的值为2
print (“dw = ” + str(grads[“dw”]))#dw = [[ 0.99993216][ 1.99980262]]
print (“db = ” + str(grads[“db”]))#db = 0.499935230625
print (“cost2 = ” + str(cost))#cost = 6.00006477319

“”“输出结果为:
w = [[ 1][ 2]]
b = 2
dw = [[ 0.99993216][ 1.99980262]],在慢慢变小
db = 0.499935230625,在慢慢变小
cost = 6.00006477319
“”“

### 4.4 优化 Optimization#

- You have initialized your parameters.

- You are also able to compute a cost function and its gradient.

- Now, you want to update the parameters using gradient descent.

Write down the optimization function. The goal is to learn w and b by minimizing

the cost function J, For a parameter theta,the update rule is theta = theta - alpha*theta

where alpha is the learning rate.

GRADED FUNCTION: optimize

def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
#This function optimizes w and b by running a gradient descent algorithm
“””
Arguments:
w – weights, a numpy array of size (num_px * num_px * 3, 1)
b – bias, a scalar
X – data of shape (num_px * num_px * 3, number of examples)
Y – true “label” vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
num_iterations – number of iterations of the optimization loop
learning_rate – learning rate of the gradient descent update rule
print_cost – True to print the loss every 100 steps

Returns:
params – dictionary containing the weights w and bias b
grads – dictionary containing the gradients of the weights and bias with respect to the cost function
costs – list of all the costs computed during the optimization, this will be used to plot the learning curve.

Tips:
You basically need to write down two steps and iterate through them:
(1) Calculate the cost and the gradient for the current parameters. Use propagate().
(2) Update the parameters using gradient descent rule for w and 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"]#dw为[0.99993215,1.999802619]
    db = grads["db"]#db为0.499935230625

    # update rule (≈ 2 lines of code)
    w = w - learning_rate * dw
    b = b - learning_rate * db

    # Record the costs
    if i % 100 == 0:
        costs.append(cost)

    # Print the cost every 100 training examples
    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

w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
params, grads, costs = optimize(w, b, X, Y, num_iterations= 1000, 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:”,costs)

“””
输出结果为:
w = [[ 0.1124579 ][ 0.23106775]]
b = 1.55930492484
dw = [[ 0.90158428][ 1.76250842]],变化幅度比上次大
db = 0.430462071679,变化幅度比上次大
costs: 根据观察,迭代次数越多,逐步变小
(1、)num_iterations= 100时,cost的值为:
[6.0000647731922054, 5.9528238404019787, 5.9055835580118288, 5.8583439731360443
1.7829431852935509, 1.7418687698781761, 1.7012327949342381,..1.4681764883914099]
(2、)num_iterations= 1000时,cost的值为:
[6.0000647731922054, 5.9528238404019787, 5.9055835580118288, 5.8583439731360443,
1.7829431852935509, 1.7418687698781761, 1.7012327949342381,..1.4681764883914099
….0.45007550362095522, 0.44996277790930794, 0.44985009639693085…0.44872570768284936]
“”“

The previous function will output the learned w and b. We are able to use

w and b to predict the labels for a dataset X. Implement the predict() function.

There is two steps to computing predictions:

1. Calculate sigmod(w.T*x+b)

2. Convert the entries of a into 0 (if activation <= 0.5) or 1 (if activation > 0.5),

stores the predictions in a vector Y_prediction. If you wish, you can use an `

if/elsestatement in afor` loop (though there is also a way to vectorize this).

4.5 函数预测(predict)

def predict(w, b, X):
”’
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)

Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)

Returns:
Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
'''
m = X.shape[1]
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0], 1)

# Compute vector "A" predicting the probabilities of a cat being present in the picture
A = sigmoid(np.dot(w.T, X) + b)
#print("A2:",A)用于测试
for i in range(A.shape[1]):
    # Convert probabilities A[0,i] to actual predictions p[0,i]
    if A[0, i] <= 0.5:#A的值为: [[ 0.99987661  0.99999386]]
        Y_prediction[0, i] = 0
    else:
        Y_prediction[0, i] = 1

assert(Y_prediction.shape == (1, m))
return Y_prediction

w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
print (“predictions = ” + str(predict(w, b, X)))#预测的结果为[[1,1]]

You’ve implemented several functions that:

(1)Initialize (w,b)

(2)Optimize the loss iteratively to learn parameters (w,b):

- computing the cost and its gradient

- updating the parameters using gradient descent

(3)Use the learned (w,b) to predict the labels for a given set of examples

## 5 - 在模型中合并所有函数(Merge all functions into a model )

You will now see how the overall model is structured by putting together all the building blocks

(functions implemented in the previous parts) together, in the right order.

Implement the model function. Use the following notation:

- Y_prediction for your predictions on the test set

- Y_prediction_train for your predictions on the train set

- w, costs, grads for the outputs of optimize()

def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
“””
Builds the logistic regression model by calling the function you’ve implemented previously

Arguments:
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)
X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)
num_iterations -- hyperparameter representing the number of iterations to optimize the parameters
learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()
print_cost -- Set to true to print the cost every 100 iterations

Returns:
d -- dictionary containing information about the model.
"""
# (1)initialize parameters with zeros (≈ 1 line of code)
w, b = initialize_with_zeros(X_train.shape[0])

# (2)Gradient descent
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)

# (3)Retrieve parameters w and b from dictionary "parameters"
w = parameters["w"]
b = parameters["b"]

# (4)Predict test/train set examples (≈ 2 lines of code)
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)

# (5)Print train/test Errors
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)

print(“d[‘costs’]:”,d[‘costs’])#输出costs的值

Comment:Training accuracy is close to 100%. This is a good sanity check: your model is working

and has high enough capacity to fit the training data. Test error is 68%. It is actually not bad for

this simple model, given the small dataset we used and that logistic regression is a linear classifier.

But no worries, you’ll build an even better classifier next week!

Also, you see that the model is clearly overfitting the training data. Later in this specialization

you will learn how to reduce overfitting, for example by using regularization. Using the code

below (and changing the index variable) you can look at predictions on pictures of the test set.

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.”)
plt.show()

Plot cost function and the gradients learning curve (with costs)

costs = np.squeeze(d[‘costs’])

print(“costs2:”,costs)用于测试

plt.plot(costs)
plt.ylabel(‘cost’)
plt.xlabel(‘iterations (per hundreds)’)
plt.title(“Learning rate =” + str(d[“learning_rate”]))
plt.show()

Interpretation:

You can see the cost decreasing. It shows that the parameters are being learned.

However, you see that you could train the model even more on the training set.

Try to increase the number of iterations in the cell above and rerun the cells. You

might see that the training set accuracy goes up, but the test set accuracy goes down.

This is called overfitting.

## 6 - 特征值分析(Further analysis (optional/ungraded exercise))

Congratulations on building your first image classification model. Let’s analyze it

further, and examine possible choices for the learning rate

#### Choice of learning rate

#(1)In order for Gradient Descent to work you must choose the learning rate wisely.

The learning rate determines how rapidly we update the parameters. If the learning rate

is too large we may “overshoot” the optimal value. Similarly, if it is too small we

will need too many iterations to converge to the best values. That’s why it is crucial

to use a well-tuned learning rate.

#(2)Let’s compare the learning curve of our model with several choices of learning rates

Run the cell below. This should take about 1 minute. Feel free also to try different

values than the three we have initialized the learning_rates variable to contain,

and see what happens.

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(“models[str(i)][costs]:”, models[str(i)][“costs”])
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 %
“”“

“””

- Different learning rates give different costs and thus different predictions results.

- If the learning rate is too large (0.01), the cost may oscillate up and down. It may

even diverge (though in this example, using 0.01 still eventually ends up at a
good value for the cost).

- A lower cost doesn’t mean a better model. You have to check if there is

possibly overfitting. It happens when the training accuracy is a lot higher than
the test accuracy.

- In deep learning, we usually recommend that you:

(1)Choose the learning rate that better minimizes the cost function.

(2)If your model overfits, use other techniques to reduce overfitting.

(We’ll talk about this in later videos.)

“”“

## 7 - 用自己的图片测试模型(Test with your own image (optional/ungraded exercise) )

Congratulations on finishing this assignment. You can use your own image and

see the output of your model. To do that:

1. Click on “File” in the upper bar of this notebook, then click “Open”

to go on your Coursera Hub.

2. Add your image to this Jupyter Notebook’s directory, in the “images” folder

3. Change your image’s name in the following code

4. Run the code and check if the algorithm is right (1 = cat, 0 = non-cat)!

my_image = “xiangmao.jpg” # change this to the name of your image file

We preprocess the image to fit your algorithm.

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)
plt.show()
print(“y = ” + str(np.squeeze(my_predicted_image)) + “, your algorithm predicts a \”” +
classes[int(np.squeeze(my_predicted_image)),].decode(“utf-8”) + “\” picture.”)

What to remember from this assignment:

1. Preprocessing the dataset is important.

2. You implemented each function separately: initialize(), propagate(), optimize(). Then you built a model().

3. Tuning the learning rate (which is an example of a “hyperparameter”) can make a big difference to the

algorithm. You will see more examples of this later in this course!

Finally, if you’d like, we invite you to try different things on this Notebook. Make sure you submit before

trying anything. Once you submit, things you can play with include:

- Play with the learning rate and the number of iterations

- Try different initialization methods and compare the results

- Test other preprocessings (center the data, or divide each row by its standard deviation)

Bibliography:

- http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/

- https://stats.stackexchange.com/questions/211436/why-do-we-normalize-images-by-subtracting-the-datasets-image-mean-and-not-the-c

从逻辑回归到神经网络 逻辑回归: 假设函数 逻辑函数 代价函数 防止过拟合的代价函数 逻辑回归通常用于解决分类问题,最终要预测的结果是离散的值,分类通常有二元分类和多元分类/n元分类。 针对二元分类,如 0-1分类,的结果表示根据选择的参数计算输出变量=1的可能性,eg.= 0.7,表示有70%的概率 y=1,30%的概率 y=0. 针对多元分类,如邮件分类:有来自家人的邮件、来自工作的邮件、来自朋友的邮件、有关兴趣爱好邮件,这四类可分别用y=1、... 阅读详情

相关推荐

理解和实现逻辑回归(神经网络的“祖宗”)

Sklearn 实现 LogisticRegression详细分析

MiaLove 1068

神经网络思维的逻辑回归python代码

一、工具包 numpy是Python科学计算的基本包。 h5py是一个与存储在H5文件中的数据集交互的常用包。 matplotlib是一个著名的Python绘图库。 PIL和scipy在这里用来测试模型。 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 loa

weixin_44235615的博客 1065

逻辑回归之tensorflow实现

逻辑回归是机器学习中很简答的一个栗子,这篇文章就是要介绍如何使用tensorflow实现一个简单的逻辑回归算法。 逻辑回归可以看作只有一层网络的前向神经网络,并且参数连接的权重只是一个值,而非矩阵。公式为:y_predict=logistic(X*W+b),其中X为输入,W为输入与隐含层之间的权重,b为隐含层神经元的偏置,而logistic为激活函数,一般为sigmoid或者tanh, y_pr

u013206066的博客 7971

python逻辑回归识别猫(持续更新中)

逻辑回归 简单来说, 逻辑回归(Logistic Regression)是一种用于解决二分类(0 or 1)问题的机器学习方法,用于估计某种事物的可能性。比如某用户购买某商品的可能性,某病人患有某种疾病的可能性,以及某广告被用户点击的可能性等。 注意,这里用的是“可能性”,而非数学上的“概率”,logisitc回归的结果并非数学定义中的概率值,不可以直接当做概率值来用。该结果往往用于和其他特征值加...

qq_42370313的博客 2412

神经网络(二):Softmax函数与多元逻辑回归

文章目录一、 Softmax函数与多元逻辑回归二、广告时间 一、 Softmax函数与多元逻辑回归 为了之后更深入地讨论神经网络,本节将介绍在这个领域里很重要的softmax函数,它常被用来定义神经网络的损失函数(针对分类问题)。 根据机器学习的理论,二元逻辑回归的模型公式可以写为如下的形式: (1)P(y=1)=11+e−XWT+bP(y = 1) = \frac{1}{1 + e^{-XW^T...

LLM学堂 2271

神经网络和逻辑回归的区别

神经网络和逻辑回归是重要的机器学习技术,可以帮助解决各种分类和回归问题。由于它们在进行预测时的准确性和处理各种数据类型的适应性,因此这些模型已经变得越来越流行。例如,神经网络在图像识别和自然语言处理等领域非常有用,因为它们可以识别数据中难以看到的模式,并捕捉数据中的非线性相关性。另一方面,由于其简单易懂,二元结果情况经常受益于使用逻辑回归。此外,更复杂的模型如神经网络可以建立在逻辑回归的基础上。机器学习实践者必须完全理解这些模型之间的差异及其在特定问题上的应用,以选择适当的算法并获得最佳结果。

AI168178的博客 974

deeplearning.ai学习(numpy方法使用)

train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset() train_set_x_orig -- 一组图片 plt.imshow(train_set_x_orig[index]) -- 展示出第index图片 train_set_y[:, index] --

solar一抹阳光的专栏 2855

多类别分类——逻辑回归和神经网络

假设有一个训练集如下图左部分所示,有3个类别。逻辑回归的方法是将其分成3个二元分类问题。先从类别1开始,创建一个新的“伪”训练集,类别2和类别3定为负类,类别1设定为正类,如图所示: 对新的训练集训练一个标准的逻辑回归分类器,记作hθ(1)(x)h_{\theta }^{\left ( 1 \right )}\left ( x \right )hθ(1)​(x)。接着类似地,选择另一个类标记为正向类,将其它类都标记为负向类,将这个模型记作hθ(2)(x)h_{\theta }^{\left ( 2 \ri

吴小胖的博客 1632

NG深度学习第一门课作业1 构建一个逻辑回归分类器来识别猫

欢迎来到你的第一个(必需的)编程任务!你将建立一个逻辑回归分类器来识别猫。这项作业将带你逐步了解如何用神经网络思维来做这件事,因此也将磨练你对深度学习的直觉。 第一部分:导包 在开始之前,我们有需要引入的库: numpy :是用Python进行科学计算的基本软件包。h5py:是与H5文件中存储的数据集进行交互的常用软件包。matplotlib:是一个著名的库,用于在Python中绘制图...

SpringRolls的博客 793

神经网络(一):神经元模型与逻辑回归

文章目录一、仿生学二、神经元三、Sigmoid神经元与二元逻辑回归 一、仿生学 在经典的机器学习领域,有很多不同类型的模型,它们大致可以分为两类:一类是比较注重模型可解释性的传统统计模型,比如线性回归和逻辑回归;另一类是侧重于从结构上“模仿”数据的机器学习模型,比如监督式学习SVM和非监督式学习KMeans。 这些模型虽然在结构和形态上千差万别,但它们有一个共同的建模理念,就是首先对数据做假设,然...

LLM学堂 1万+

Codesys软运动控制进阶:用SMC_FreeEncoder为ECAT轴搭建一个“虚拟手轮”调试工具

本文详细介绍了如何利用Codesys的SMC_FreeEncoder功能为ECAT轴搭建虚拟手轮调试工具,解决自动化设备开发中的硬件依赖问题。通过软件模拟手轮脉冲信号,实现无硬件依赖的运动控制逻辑验证,显著提升调试效率。适用于汇川AM400等PLC平台,特别适合机械安装滞后或伺服驱动器故障时的调试场景。

weixin_33737774的博客 477

【机器学习】逻辑回归原理

目录 1、分类和回归 2、逻辑回归 3、推导逻辑回归 3.1 从手推线性回归开始 3.2 逻辑回归代价函数 3.3 逻辑回归推导 4、例子 参考:手推逻辑回归--面试前拯救一下 手推记录-logistic regression (逻辑斯蒂回归) 1、分类和回归 回归(Regression)和分类(Classification)是机器学习中...

Mr_health的博客 734

转录组PCA分析3大常见误区:数据标准化、离群样本与批次效应处理

本文深入探讨转录组PCA分析中的三大常见误区:数据标准化、离群样本识别与批次效应处理。通过实战案例和R代码演示,揭示如何优化PCA结果以提升生物学解释力,特别关注数据标准化策略的选择和批次校正方法的应用,帮助研究者避免常见陷阱并获得可靠的转录组分析结果。

weixin_28362173的博客 372

单分类线性逻辑回归

携手共同学习,共同进取,吾辈自当相互勉励!存有异议或建议,敬请留言指正批评。

qq_42217078的博客 468

【MagicDrive环境配置】新手配俩星期版

1.创建一个新的环境conda create -n newdrive python==3.82.激活该环境conda activate newdrive3.下载MagicDrive源码 git clone --recursive https://github.com/cure-lab/MagicDrive.git,如果出现时间超时八成是网的问题,直接自己下载解压就好3.我的cuda版本是11.7,但11.7导致后续安装有冲突,因此进入。

m0_46261292的博客 2203

基于IMU的纯惯性导航轨迹绘制实践与优化

本文深入探讨了基于IMU的纯惯性导航轨迹绘制实践。通过修改开源组合导航算法KF-GINS,屏蔽GPS更新并简化地球参数,实现了仅依赖IMU数据的轨迹解算。文章详细介绍了代码改造、轨迹可视化方法,并分析了误差累积的根本原因,为深入理解惯性导航原理与传感器融合的必要性提供了宝贵的实践经验。

ff678的博客 395

逻辑回归与神经网络

来看下面这个例子:在平面 x1-0-x2 中,分布着蓝色圆圈表示的正样本,红色叉叉表示的负样本,它们有两个特征 x1 和 x2 .其中正样本的标签是 y = 1,负样本的标签是 y = 0,然后在平面上画出一条直线:x1 + x2 - 3 = 0该直线交 x1 轴于点(3, 0) ,交 x2 轴于点(0, 3):此时可以观察到正负两种样本刚好分布在直线的两侧。

qq_53324833的博客 1975

DRM遇到的实际问题及领悟(3)

DRM遇到的实际问题及领悟(3)

phmatthaus的专栏 636

神经网络 逻辑回归_神经网络心态的逻辑回归

神经网络 逻辑回归Note From Author: 作者注: This tutorial is the foundation of computer vision delivered as “Lesson 8” of the series, there are more Lessons upcoming which would talk to the extend of building yo...

weixin_26712065的博客 936

网络分析工具Wireshark系列专栏:01-专栏导读

随着人工智能技术的普及,越来越多的博主开始利用AI进行内容创作,导致优快云等平台上充斥着大量低质量的洗稿文章,严重影响了技术软文的质量和可信度。为了应对这一现象,提升技术内容的质量,瑞哥决定推出系列技术专栏,为大家带来系统、深入且高质量的技术学习资源。这些专栏将帮助读者从入门到精通,特别适合习惯通过文档学习的技术爱好者。作为首个专栏,我们将聚焦于Wireshark——一款广受欢迎的网络协议分析工具。根据优快云后台的反馈,许多读者表示Wireshark是他们欠缺的一项技能。因此,本专栏将通过精心设计的课程

网络技术联盟站 359

TIM 2024 | AD-YOLO:一种结合 Swin Transformer 和注意力机制的实时 YOLO 网络用于机场场景检测

实时获取机场场景信息对于保障机场安全和提升机场运营效率至关重要。然而,机场场景图像中的人员和车辆目标尺寸较小,而且公开的机场数据不足,这使得机场物体检测成为一项颇具挑战的任务,难以同时实现高精度和实时检测。本文提出了一种全新的机场物体检测方法——机场检测器YOLO(AD - YOLO),它融合了改进的你只看一次(YOLO)算法、Swin Transformer和注意力机制的优势,以应对这一挑战。

小白学视觉 315

由逻辑回归到神经网络

至此,我们已经比较透彻的理解了逻辑回归模型假设函数图片(也就是用于预测类别的函数)。纯从计算顺序上来说,逻辑回归预测类别的顺序即: 输入样本X与模型参数图片作内积,结果记为z 将中间结果z输入到Sigmoid函数,输出为0到1之间的一个数,a(在前两文中已经证明了这个a即其中一个类的后验概率) 然后,小夕要将上面的过程画出来。 这里假设输入的样本X是4维的,即图片,因此模型参数图片也是4维,即图片。为了方便,本文中忽略偏置项b的问题啦,自行脑补上。然后,blingling释放小仙女的仙气~ 如

YJ语 776

【unity小技巧】委托(Delegate)的基础使用和介绍

在Unity中,委托(Delegate)是一种用于处理方法回调的特殊类型。它允许您将方法作为参数传递给其他方法,并在需要时调用这些方法。委托在游戏开发中非常有用,特别是在事件处理、消息传递和异步操作方面。它提供了一种灵活的方式来注册和触发方法,而无需显式地知道这些方法的实现细节。个人理解:可以把委托理解为一个容器,容器里面放可以放很多函数方法。一调用委托,里面所有的函数方法都会同步被执行。

向宇的博客,专注php/web全栈 unity游戏开发,欢迎大家评论纠错 7238

神经网络基础及逻辑回归实现

1. Logistic回归 1.1 Logistic回归 逻辑回归是一个主要用于二分分类类的算法。那么逻辑回归是给定一个xx, 输出一个该样本属于1对应类别的预测概率\hat{y}=P(y=1|x)​y​^​​=P(y=1∣x)。 Logistic 回归中使用的参数如下: ...

IT之一小佬的博客 2127

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

逻辑回归与神经网络:本质联系与核心区别

本文探讨了逻辑回归与神经网络的内在联系。逻辑回归作为机器学习基础算法,通过线性变换和Sigmoid激活实现二分类,其本质是一个单神经元模型。神经网络则通过多层级联的"逻辑回归单元"获得了处理非线性问题的能力。两者共享相同的数学基础(如交叉熵损失函数和梯度下降优化),但神经网络通过反向传播实现更复杂的参数更新。逻辑回归适合小数据量、线性可分问题,而神经网络擅长处理复杂非线性关系和大数据场景。理解逻辑回归这一"原子"单位,有助于掌握深度学习模型的"第一性原理"。

Dfreedom.的博客 1230

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

神经网络算法与逻辑回归:优势与差异

选择合适的模型应基于问题的类型、数据的规模与维度、非线性关系、特征工程、可解释性、计算资源与优化以及业务领域与实际需求等多方面因素进行综合考虑。例如,可以将逻辑回归作为神经网络的初始或辅助层,利用其线性分类能力与神经网络的非线性学习和泛化能力相结合,实现更强大的预测模型。神经网络算法和逻辑回归都是预测模型中的重要工具,但它们在处理复杂和非线性问题时表现出不同的性能。本文将通过理论分析和实证研究,深入探讨神经网络算法相对于逻辑回归的优势,以及它们在不同场景下的适用性。三、逻辑回归的优势与局限性。

huanfeng_AI的博客 2013

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

上一篇: zip()函数函数的使用
下一篇: 测试lamdba、map和filter这三个函数
junchengberry
博客等级 码龄19年 27粉丝 38原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值