【深度学习】L1W2(2)- 用神经网络思想实现Logistic回归
发布日期:2022-02-10 08:11:05 浏览次数:11 分类:技术文章

本文共 4317 字,大约阅读时间需要 14 分钟。

你需要记住的内容:

预处理数据集的常见步骤是:

  • 找出数据的尺寸维度(m_train,m_test,num_px等)(图片都是lenght,height,3)
  • 重塑数据集,以使每个示例都是大小为(num_px \ num_px \ 3,1)的向量(就是利用reshape函数)
  • “标准化”数据(这里就是简单的将每张图片除以255)

以下是logistic回归的代码,判断图片是否为猫

import numpy as npimport matplotlib.pyplot as pltimport h5pyimport scipyfrom PIL import Imagefrom scipy import ndimagefrom lr_utils import load_datasetdef sigmoid(x):    return 1 / (1 + np.exp(-x))def initialize_with_zeros(dim):    w = np.zeros((dim, 1))    b = 0    assert (w.shape == (dim, 1))    assert (isinstance(b, float) or isinstance(b, int))    # 断言用于判断是否为这个条件,不是的话就直接报错,是的话就继续执行    # 这里断言可有可无,保险起见而已    return w, b# 实现函数propagate()来计算损失函数及其梯度。def propagate(w, b, X, Y):    """       Implement the cost function and its gradient for the propagation explained above       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)   """    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))  # compute cost    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)    cost = np.squeeze(cost)  # 这句可要可不要    assert (cost.shape == ())    grads = {
"dw": dw, "db": db} return grads, costdef 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) # 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, costsdef predict(w, b, X): m = X.shape[1] Y_prediction = np.zeros((1, m)) w = w.reshape(X.shape[0], 1) # 这句其实没起作用 w还是原来的w # Compute vector "A" predicting the probabilities of a cat being present in the picture ### START CODE HERE ### (≈ 1 line of code) A = sigmoid(np.dot(w.T, X) + b) ### END CODE HERE ### for i in range(A.shape[1]): # Convert probabilities A[0,i] to actual predictions p[0,i] ### START CODE HERE ### (≈ 4 lines of code) if A[0, i] <= 0.5: Y_prediction[0, i] = 0 else: Y_prediction[0, i] = 1 ### END CODE HERE ### assert (Y_prediction.shape == (1, m)) return Y_predictiondef model(X_train, Y_train, X_test, Y_test, num_iterations, learning_rate, print_cost): w, b = initialize_with_zeros(X_train.shape[0]) # Gradient descent (≈ 1 line of code) parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) # Retrieve parameters w and b from dictionary "parameters" w = parameters["w"] b = parameters["b"] # 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) ### END CODE HERE ### # 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 dtrain_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()# index = 49# plt.imshow(test_set_x_orig[index])# plt.show()# train_set_x_flatten = train_set_x_orig.reshape(64*64*3, 209) 等价于下方的train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).Ttest_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).Ttrain_set_x = train_set_x_flatten/255.test_set_x = test_set_x_flatten/255.d = model(train_set_x, train_set_y, test_set_x, test_set_y, 2000, 0.005, True)

转载地址:https://blog.csdn.net/qq_43567222/article/details/114680374 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【算法】- DP(动态规划)
下一篇:AtCoder- A+...+B Problem

发表评论

最新留言

不错!
[***.144.177.141]2024年03月07日 05时46分27秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

python 红黑树_红黑树-Python实现 | 学步园 2019-04-21
java string 日期格式_JAVA中String.format的用法 格式化字符串,格式化数字,日期时间格式化,... 2019-04-21
php显示json,使用 PHP 获取并解析 JSON 显示在页面中 2019-04-21
js php排序表格,javascript实现对表格元素进行排序操作_javascript技巧 2019-04-21
php sspi,php 内置的 web 服务器 php -s 2019-04-21
java生成结果集向量,如何解释H2o深度学习输出向量? 2019-04-21
matlab 曲线拟合求导,如何对matlab cftool拟合得到的cfit函数求导数 2019-04-21
matlab 50hzquchu,新手求消除50HZ工频干扰陷波滤波器源程序 2019-04-21
laravel没有route.php,Laravel中的RouteCollection.php中的NotFoundHttpException 2019-04-21
php服务端开启socket,php socket服务端能不能在网页端开启?而不是只能用CLI模式开启... 2019-04-21
php不需要也能输出,php 如何只输出最后生成的那个值?? 2019-04-21
php正则过滤sql关键字,使用正则表达式屏蔽关键字的方法 2019-04-21
php取整v,php取整方式分享 2019-04-21
php写模糊搜索api接口,php通过sphinxapi接口实现全文搜索 2019-04-21
oracle安装出现2932,【案例】Oracle报错ORA-19815 fast_recovery_area无剩余空间解决办法... 2019-04-21
rac数据库下oracle打小补丁,Oracle 11g RAC 环境打PSU补丁的详细步骤 2019-04-21
form表单属性名相同java_form表单提交时候有多个相同name 的input如何处理? 2019-04-21
java图片加气泡文字_图片加气泡文字 2019-04-21
java总结i o流_14.java总结I/O流 2019-04-21
java和历转为西历_日期转西暦,和暦 2019-04-21