栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

机器学习

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

机器学习

问题描述:根据房屋大小预测房价。两个数据如下:

 1.调用相关库。numpy是一个流行的科学计算库,Matplotlib是一个流行的数据绘图库,lab_utils_uni.py是本地绘图例程。

import numpy as np
%matplotlib widget  
import matplotlib.pyplot as plt
from lab_utils_uni import plt_intuition, plt_stationary, plt_update_onclick, soup_bowl
plt.style.use('./deeplearning.mplstyle')

2.创建x_train和y_train变量,数据存储在一维numpy数组中。

x_train = np.array([1.0, 2.0])           #(size in 1000 square feet)
y_train = np.array([300.0, 500.0])           #(price in 1000s of dollars)

3.计算成本。成本用来衡量模型预测房屋目标价格的好坏,是衡量模型对训练数据准确程度的标准。

具有一个变量的成本方程为:

其中 

通过遍历每个示例来计算成本。

def compute_cost(x, y, w, b): 
    """
    Computes the cost function for linear regression.
    
    Args:
      x (ndarray (m,)): Data, m examples 
      y (ndarray (m,)): target values
      w,b (scalar)    : model parameters  
    
    Returns
        total_cost (float): The cost of using w,b as the parameters for linear regression
               to fit the data points in x and y
    """
    # number of training examples
    m = x.shape[0] 
    
    cost_sum = 0 
    for i in range(m): 
        f_wb = w * x[i] + b   
        cost = (f_wb - y[i]) ** 2  
        cost_sum = cost_sum + cost  
    total_cost = (1 / (2 * m)) * cost_sum  

    return total_cost

 4.选择w和b使得成本函数为零或最小。这里我们设置b=100,通过滑块控件选择w是成本最小化。

plt_intuition(x_train,y_train)

 当w=200时,成本最小

5.通过3D绘图或使用等高线图来了解成本如何随w和b变化。

使用更多的数据点。

x_train = np.array([1.0, 1.7, 2.0, 2.5, 3.0, 3.2])
y_train = np.array([250, 300, 480,  430,   630, 730,])
plt.close('all') 
fig, ax, dyn_items = plt_stationary(x_train, y_train)
updater = plt_update_onclick(fig, ax, x_train, y_train, dyn_items)

 w=209,b=2.4时成本最低。

6.平方损失的成本函数确保“误差曲面”像汤碗一样是凸起的,它总有一个最小值,可以通过在所有维度上跟随梯度来达到。

soup_bowl()

小结:成本函数提供了预测与训练数据匹配程度的衡量标准,通过提供最佳的w,b使成本最小化。

程序源码:

链接:https://pan.baidu.com/s/1qk_MYfIL386WHMQJW7oDZg 
提取码:0000

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/989761.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号