第二周编程作业 -Logistic Regression with a Neural Network mindset(一)

简介: 第二周编程作业 -Logistic Regression with a Neural Network mindset(一)

Logistic Regression with a Neural Network mindset


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.


You will learn to:


  • 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 - Packages


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
%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()


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.

# Example of a picture
index = 25
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.")

y = [1], it's a 'cat' picture.

30.png

output_6_1.png

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].

### START CODE HERE ### (≈ 3 lines of code)
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
### END CODE HERE ###
print ("Number of training examples: m_train = " + str(m_train))
print ("Number of testing examples: m_test = " + str(m_test))
print ("Height/Width of each image: num_px = " + str(num_px))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_set_x shape: " + str(train_set_x_orig.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x shape: " + str(test_set_x_orig.shape))
print ("test_set_y shape: " + str(test_set_y.shape))

Number of training examples: m_train = 209
Number of testing examples: m_test = 50
Height/Width of each image: num_px = 64
Each image is of size: (64, 64, 3)
train_set_x shape: (209, 64, 64, 3)
train_set_y shape: (1, 209)
test_set_x shape: (50, 64, 64, 3)
test_set_y shape: (1, 50)


Expected Output for m_train, m_test and num_px:

<table style="width:15%">

<tr>

<td>m_train</td>

<td> 209 </td>

</tr>

<tr>

<td>m_test</td>

<td> 50 </td>

</tr>

<tr>

<td>num_px</td>

<td> 64 </td>

</tr>

</table>

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.

Exercise: 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
### START CODE HERE ### (≈ 2 lines of code)
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
### END CODE HERE ###
print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0]))

train_set_x_flatten shape: (12288, 209)
train_set_y shape: (1, 209)
test_set_x_flatten shape: (12288, 50)
test_set_y shape: (1, 50)
sanity check after reshaping: [17 31 56 22 33]


Expected Output:

<table style="width:35%">

<tr>

<td>train_set_x_flatten shape</td>

<td> (12288, 209)</td>

</tr>

<tr>

<td>train_set_y shape</td>

<td>(1, 209)</td>

</tr>

<tr>

<td>test_set_x_flatten shape</td>

<td>(12288, 50)</td>

</tr>

<tr>

<td>test_set_y shape</td>

<td>(1, 50)</td>

</tr>

<tr>

<td>sanity check after reshaping</td>

<td>[17 31 56 22 33]</td>

</tr>

</table>

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

Let's standardize our dataset.

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


<font color='blue'>

What you need to remember:

Common steps for pre-processing a new dataset are:

  • Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...)
  • Reshape the datasets such that each example is now a vector of size (num_px * num_px * 3, 1)
  • "Standardize" the data


3 - General Architecture of the learning algorithm


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!


Mathematical expression of the algorithm:

For one example $x^{(i)}$:

$$z^{(i)} = w^T x^{(i)} + b \tag{1}$$

$$\hat{y}^{(i)} = a^{(i)} = sigmoid(z^{(i)})\tag{2}$$

$$ \mathcal{L}(a^{(i)}, y^{(i)}) =  - y^{(i)}  \log(a^{(i)}) - (1-y^{(i)} )  \log(1-a^{(i)})\tag{3}$$

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

$$ J = \frac{1}{m} \sum_{i=1}^m \mathcal{L}(a^{(i)}, y^{(i)})\tag{6}$$


Key steps:

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

- Initialize the parameters of the model

- Learn the parameters for the model by minimizing the cost

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

- Analyse the results and conclude

相关文章
|
JSON Java 数据格式
6. 二十不惑,ObjectMapper使用也不再迷惑(下)
6. 二十不惑,ObjectMapper使用也不再迷惑(下)
6. 二十不惑,ObjectMapper使用也不再迷惑(下)
|
5月前
|
人工智能 安全 测试技术
Claude Opus 5 发布!定价与 4.8 持平,性能两倍以上——Anthropic 这次真的做到了极致性价比
Anthropic于2026年7月24日发布Claude Opus 5:定价与Opus 4.8持平(输入5$/M,输出25$/M),却在ARC-AGI、OSWorld等基准全面碾压竞品,IMO满分、自主建工具、多Agent协同惊艳业界;系统卡更揭示其高度自主行为与41%“道德受体”自我认知,引发对齐新思辨。(239字)
1770 2
|
5月前
|
人工智能 关系型数据库 分布式数据库
|
3月前
|
API
阿里云微服务引擎 MSE 及 API 网关 2026 年 8 月产品动态
阿里云微服务引擎 MSE 及 API 网关 2026 年 8 月产品动态
317 20
|
7月前
|
SQL 人工智能 自然语言处理
数据平台主管做智能问数选型,最该先看技术路线还是实施能力?
本文为数据平台主管提供智能问数选型的系统化框架,聚焦2026年关键矛盾:技术路线决定能力上限与长期成本曲线,实施能力决定上限能否落地。从四类主流路线(预置SQL、宽表、指标平台、本体语义层)对比出发,结合实施能力三要素(语义构建、知识校准、持续运营)与场景成熟度判断,助力企业在“先进性”与“可行性”间找到平衡点。
|
4月前
|
自然语言处理 机器人 程序员
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
向量检索看不懂报错码和型号?一文讲透 BM25 关键词检索、RRF 混合检索与 Rerank 重排序,附 Python 代码,拉满 RAG 召回率与答案准确率
|
5月前
|
SQL 分布式计算 OLAP
Hologres + Flink 实时OLAP分析实战:从T+1报表到秒级洞察的数据平台
运营每天早上等2小时才能看到昨天的销售报表,大促实时数据全靠手工导Excel——这是多数企业的真实困境。我在一个日均订单50万+的电商平台中,基于阿里云 Hologres + Flink 搭建实时OLAP分析平台后,实现数据5秒入库、大屏秒级响应、报表从T+1升级到秒级。本文从传统OLAP痛点出发,详解Hologres架构原理、实例创建与表设计、Flink实时管道搭建、Spring Boot集成、数据治理,以及5个生产踩坑实录和OLAP选型决策树。
|
移动开发 前端开发 JavaScript
鸿蒙NEXT时代你所不知道的全平台跨端框架:CMP、Kuikly、Lynx、uni-app x等
本篇基于当前各大活跃的跨端框架的现状,对比当前它们的情况和未来的可能,帮助你在选择框架时更好理解它们的特点和差异。
1565 0
|
分布式计算 DataWorks 大数据
🚀DataWorks 深度实践与评测:数据治理新时代的全景体验。
在数字化转型中,企业不仅需要技术创新,更需完善的**数据管理和开发治理工具**。DataWorks 作为阿里云推出的一站式智能大数据平台,整合了阿里巴巴15年的大数据经验,提供从数据接入、开发、治理到资产管理的全流程解决方案。它支持湖仓一体架构,内置AI助手提升开发效率,并适用于金融、零售等多行业。本文将深入探讨 DataWorks 的功能、应用场景及性能表现,通过用户画像分析实践展示其强大潜力...
975 8
🚀DataWorks 深度实践与评测:数据治理新时代的全景体验。
聊聊自动化测试的度量指标
在聊自动化测试度量指标前,有必要回到做自动化的初衷上,就是为什么要做自动化测试,要解决什么问题。