2 - 问题描述

假设你是一家餐厅加盟店的首席执行官,正在考虑在不同的城市开设新的分店。

  • 你想把业务扩展到可能给你的餐馆带来更高利润的城市。
  • 该连锁店已经在不同的城市设有餐厅,你有这些城市的利润和人口数据。
  • 你也有一些城市的数据,这些城市是新餐厅的候选城市。
    • 对于这些城市,你有城市人口的数据。

你能利用这些数据来帮助你确定哪些城市有可能给你的企业带来更高的利润吗?

3 - 数据集

你将从加载这个任务的数据集开始。

  • 下面显示的load_data()函数将数据加载到变量x_trainy_train中。

    • x_train是一个城市的人口
    • y_train是该城市的餐馆的利润。利润的负值表示亏损。
    • X_trainy_train都是numpy数组。
import numpy as np
import matplotlib.pyplot as plt
from utils import *
import copy
import math# %matplotlib inline   →  plt.show()# load the dataset
x_train, y_train = load_data()
# print x_train
print("Type of x_train:", type(x_train))
print("First five elements of x_train are:\n", x_train[:5])
# print y_train
print("Type of y_train:", type(y_train))
print("First five elements of y_train are:\n", y_train[:5])
# 打印x_train和y_train的形状,看看你的数据集中有多少训练实例。
print('The shape of x_train is:', x_train.shape)
print('The shape of y_train is: ', y_train.shape)
print('Number of training examples (m):', len(x_train))# 创建一个数据的散点图。要将标记改为红色的 "x",
# 我们使用了'marker'和
# 'c'参数   c就是color
plt.scatter(x_train, y_train, marker='x', c='r')# 设置标题
plt.title("Profits vs. Population per city")
# 设置y轴标签
plt.ylabel('Profit in $10,000')
# 设置x轴标签
plt.xlabel('Population of City in 10,000s')
plt.show()def compute_cost(x, y, w, b):# number of training examplesm = x.shape[0]# You need to return this variable correctlytotal_cost = 0### START CODE HERE #### Variable to keep track of sum of cost from each examplecost_sum = 0# Loop over training examplesfor i in range(m):# Your code here to get the prediction f_wb for the ith examplef_wb = w * x[i] + b# Your code here to get the cost associated with the ith examplecost = (f_wb - y[i]) ** 2# Add to sum of cost for each examplecost_sum = cost_sum + cost# Get the total cost as the sum divided by (2*m)total_cost = (1 / (2 * m)) * cost_sum### END CODE HERE ###return total_cost# UNQ_C2# GRADED FUNCTION: compute_gradientdef compute_gradient(x, y, w, b):"""Computes the gradient for linear regressionArgs:x (ndarray): Shape (m,) Input to the model (Population of cities)y (ndarray): Shape (m,) Label (Actual profits for the cities)w, b (scalar): Parameters of the modelReturnsdj_dw (scalar): The gradient of the cost w.r.t. the parameters wdj_db (scalar): The gradient of the cost w.r.t. the parameter b"""# Number of training examplesm = x.shape[0]# You need to return the following variables correctlydj_dw = 0dj_db = 0### START CODE HERE ###for i in range(m):f_wb = w * x[i] + bdj_db_i = f_wb - y[i]dj_dw_i = (f_wb - y[i]) * x[i]# Update dj_db : In Python, a += 1  is the same as a = a + 1dj_db += dj_db_i# Update dj_dwdj_dw += dj_dw_i# Divide both dj_dw and dj_db by mdj_dw = dj_dw / mdj_db = dj_db / m
#    dj_db = (w * x + b - y).sum() / m
#    dj_dw = ((w * x + b - y) * x).sum() / m### END CODE HERE ###return dj_dw, dj_dbdef gradient_descent(x, y, w_in, b_in, cost_function, gradient_function, alpha, num_iters):"""Performs batch gradient descent to learn theta. Updates theta by takingnum_iters gradient steps with learning rate alphaArgs:x :    (ndarray): Shape (m,)y :    (ndarray): Shape (m,)w_in, b_in : (scalar) Initial values of parameters of the modelcost_function: function to compute costgradient_function: function to compute the gradientalpha : (float) Learning ratenum_iters : (int) number of iterations to run gradient descentReturnsw : (ndarray): Shape (1,) Updated values of parameters of the model afterrunning gradient descentb : (scalar)                Updated value of parameter of the model afterrunning gradient descent"""# number of training examplesm = len(x)# An array to store cost J and w's at each iteration — primarily for graphing laterJ_history = []w_history = []w = copy.deepcopy(w_in)  # avoid modifying global w within functionb = b_infor i in range(num_iters):# Calculate the gradient and update the parametersdj_dw, dj_db = gradient_function(x, y, w, b)# Update Parameters using w, b, alpha and gradientw = w - alpha * dj_dwb = b - alpha * dj_db# Save cost J at each iterationif i < 100000:  # prevent resource exhaustioncost = cost_function(x, y, w, b)J_history.append(cost)# Print cost every at intervals 10 times or as many iterations if < 10if i % math.ceil(num_iters / 10) == 0:w_history.append(w)print(f"Iteration {i:4}: Cost {float(J_history[-1]):8.2f}   ")return w, b, J_history, w_history  # return w and J,w history for graphing# initialize fitting parameters. Recall that the shape of w is (n,)
initial_w = 0.
initial_b = 0.# some gradient descent settings
iterations = 1500
alpha = 0.01w,b,_,_ = gradient_descent(x_train ,y_train, initial_w, initial_b,compute_cost, compute_gradient, alpha, iterations)
print("w,b found by gradient descent:", w, b)m = x_train.shape[0]
predicted = np.zeros(m)for i in range(m):predicted[i] = w * x_train[i] + b# Plot the linear fit
plt.plot(x_train, predicted, c = "b")# Create a scatter plot of the data.
plt.scatter(x_train, y_train, marker='x', c='r')# Set the title
plt.title("Profits vs. Population per city")
# Set the y-axis label
plt.ylabel('Profit in $10,000')
# Set the x-axis label
plt.xlabel('Population of City in 10,000s')
plt.show()

题目翻译原文:

王者归来,全新升级!吴恩达《机器学习2022》——民间自制中文翻译版 - 知乎

引用和数据文件:

https://download.csdn.net/download/qq_27785023/86737600

2022吴的机器学习C1-W2 Home Work:线性回归相关推荐

  1. 会议交流 | DataFunSummit 2022:图机器学习在线峰会

    深度学习模型是当今人工智能研究的核心.众所周知,对欧几里得数据(例如图像)和序列数据(例如文本)具有颠覆性学习能力的深度学习技术不能直接适用于图结构数据.这种差距推动了图深度学习研究的浪潮,在学术界不 ...

  2. 吴恩达机器学习python作业之多变量线性回归

    建议先看单变量线性回归再看多变量线性回归哦. 参考链接: (7条消息) 吴恩达|机器学习作业1.1多变量线性回归_学吧学吧终成学霸的博客-CSDN博客 数据集:一共三列,左边两列是自变量x,最右边一列 ...

  3. 机器学习实战(七)线性回归(Linear Regression)

    目录 0. 前言 1. 假设函数(Hypothesis) 2. 标准线性回归 2.1. 代价函数(Cost Function) 2.2. 梯度下降(Gradient Descent) 2.3. 特征缩 ...

  4. python机器学习手写算法系列——线性回归

    本系列另一篇文章<决策树> https://blog.csdn.net/juwikuang/article/details/89333344 本文源代码: https://github.c ...

  5. 《机器学习》实验一:线性回归

    <机器学习>实验一:线性回归 <机器学习>实验一:线性回归 实验目的 实验原理 1. 线性回归 2. 梯度下降法 3. 最小二乘法 实验内容 实验器材 实验步骤 1. 随机生成 ...

  6. Coursera公开课笔记: 斯坦福大学机器学习第四课“多变量线性回归(Linear Regression with Multiple Variables)”

    Coursera公开课笔记: 斯坦福大学机器学习第四课"多变量线性回归(Linear Regression with Multiple Variables)" 斯坦福大学机器学习第 ...

  7. Coursera公开课笔记: 斯坦福大学机器学习第二课“单变量线性回归(Linear regression with one variable)”

    Coursera公开课笔记: 斯坦福大学机器学习第二课"单变量线性回归(Linear regression with one variable)" 发表于 2012年05月6号 由 ...

  8. l2正则化python_机器学习入门之机器学习之路: python线性回归 过拟合 L1与L2正则化...

    本文主要向大家介绍了机器学习入门之机器学习之路: python线性回归 过拟合 L1与L2正则化,通过具体的内容向大家展现,希望对大家学习机器学习入门有所帮助. 正则化:    提高模型在未知数据上的 ...

  9. 斯坦福大学机器学习第三课“多变量线性回归“

    斯坦福大学机器学习第三课"多变量线性回归(Linear Regression with Multiple Variables)" 斯坦福大学机器学习第四课"多变量线性回归 ...

最新文章

  1. android profile分析器,Android性能优化之分析工具Profile的使用
  2. 项目管理一般知识:典型的信息系统项目的生命周期模型
  3. 注销linux/solaris桌面的命令
  4. Visual Studio Online,带来四种开发模式,未来已来。
  5. selenide_使用Selenide进行有效的UI测试
  6. 大数据之-Hadoop本地模式_执行Grep官方案例---大数据之hadoop工作笔记0021
  7. java正则和python正则差距,在C/Java中处理正则表达式比在Python中快多少?
  8. Typora使用技巧--不定期更新
  9. Mac技巧:如何使用macOS Big Sur中“通知中心”的小组件?
  10. anaconda r 语言_Centos7系统下R、 Rstudio及sparklyr的安装与配置
  11. debian7 安装配置
  12. 傅里叶级数与傅里叶变换
  13. android 辅助功能_关于辅助功能的9个神话
  14. 【前端初/中级面经】中小型公司面试时都会问些什么,VUE出境最高?
  15. 央企招聘:中储粮集团2023公开招聘公告(校招+社招,共700人)
  16. 无憾,2019!加油,2020!
  17. mysql积累--面试题
  18. 硬汉内贾德:让美国人战栗(推荐)
  19. 希拉里败选演说和特朗普胜选演说(中英文)
  20. 程序员的创世传说 第六节 棚户区的怪人

热门文章

  1. ABLIC推出用于基础设施设备的S-576Z R系列 Zero Crossing Latch霍尔效应IC
  2. (转)戴尔Dell服务器远程管理卡的配置和应用
  3. 11.JVMGC基础
  4. win7计算机信息服务,Win7怎么打开系统服务?Win7查看系统服务信息方法
  5. 目标检测系列——开山之作RCNN原理详解
  6. idea clone failed
  7. DB2 V9.7 SQL10007N错误解决。
  8. 授时保护装置在石油石化治安反恐领域的应用
  9. stm32无源蜂鸣器定时器_stm32实现无源蜂鸣器发声
  10. 实现磁盘/U盘个性化图标