Day-05 Easy Regression Example

  • 昨天我们提过了 Regression 的流程就是有一个初始目标 -> 检查"糟糕程度" -> 找到最好
  • 上面的流程也就是 Model -> Loss function -> Gradient Descent -> Find the best function
  • 那我们要如何实作呢?

情境假设

  • 我们先假定我们的目标函数是 https://chart.googleapis.com/chart?cht=tx&chl=%24y%20%3D%202%20*%20x%24 ,也就是我们的答案
  • 那在不知道答案的情况下,我们可以先假设 Model 会长 https://chart.googleapis.com/chart?cht=tx&chl=%24y%20%3D%20w%20*%20x%24 ,我们今天要解决的问题就是找出正确的 w
  • 那回到训练的过程,一定需要资料对吧,因此我们就人为生成一些资料 https://chart.googleapis.com/chart?cht=tx&chl=%24x%20%3D%20%5B1%2C%202%2C%203%2C%204%2C%205%2C%206%5D%24 ,答案的部分则是 https://chart.googleapis.com/chart?cht=tx&chl=%24y%20%3D%20%5B2%2C%204%2C%206%2C%208%2C%2010%2C%2012%5D%24
  • 那就基於这样的题目的话,我们要怎麽实作解决呢?

实作

  • 下面就不另外写出来解释了,有 python 基础的 + 注解应该能够理解
import numpy as np

# f = w * x
# f = 2 * x, we set w as 2
x = np.array([1, 2, 3, 4, 5, 6], dtype=np.float32)
y = np.array([2, 4, 6, 8, 10, 12], dtype=np.float32)

# init weight
w = 0.0

# model prediction
# 这边之後会解释为啥叫做 forward,可以先视为计算函数而已
def forward(x):
    
    return w * x
    
# set up loss function as mean square error
def loss(y, y_predicted):

    return ((y_predicted-y) ** 2).mean()
    
# gradient
def gradient(x, y, y_predicted):

    return np.dot(2*x, y_predicted-y).mean()
    
print(f'Prediction before training: f(5) = {forward(5): .3f}')

# Training
learning_rate = 0.01
n_iters = 10

for epoch in range(n_iters):
    # perdiction = forward pass
    y_pred = forward(x)

    # loss
    l = loss(y, y_pred)

    # we know that gradient descent is where 
    # calculate gradient and update parameters
    
    # calculation of gradients
    dw = gradient(x, y, y_pred)

    # update weights
    w -= learning_rate * dw

    if epoch % 1 == 0:
        print(f'epoch {epoch + 1}: w = {w:.3f}, loss = {l:.8f}')

print(f'Prediction after training: f(5) = {forward(5): .3f}')

每日小结

  • 从上面的 Example 应该可以发现,其实整体的计算和概念真的没有很难,机器学习并没有我们想像的复杂
  • 那今天我们学过了 Regression,明天让我们聊聊 Classification 吧~

<<:  Day5 Redis组态档设定-GENERAL 2

>>:  IT铁人DAY 5-MVC 介绍

[Day14]-类别

定义与使用 定义与操作类别的属性与方法 想要使用类别里的属性与方法,需要去宣告类别的物件变数像是上...

[Day29]懒惰的人是时间的奴隶-资料医生,补值高手

昨天我们发现,过多的样本反而会对估计做出反效果,因此我们今天要来缩小样本来补值,说到缩小样本,就不得...

Epic Games 跟 Apple 的诉讼对小开发商有什麽影响?

前天 Epic 跟 Apple 的诉讼第一次出结果,Apple 被判要在 90 天内开始允许所有 A...

[Day2] HTTP 基础

前言 本来想要跳过这章直接进入正题,但如果写那些攻击原理的时候边讲HTTP的东西,感觉会有点混乱,於...

Day30-实作(地图) (part2)

从左侧栏位获取药局位置 当我们在左设拦点击药局列表时,左侧的地图区域不会带我们到对应的位置,此时我们...