昨天周末晚上没有出去,码了一小段,先留着kangkang。

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from tqdm import tqdm

# wrapper class for an interval
# readability is more important than efficiency, so I won't use many tricks
class Interval:
    # [@left, @right)
    def __init__(self, left, right):
        self.left = left
        self.right = right

# whether a point is in this interval
    def contain(self, x):
        return self.left <= x < self.right

# length of this interval
    def size(self):
        return self.right - self.left

# domain of the square wave, [0, 2)
DOMAIN = Interval(0.0, 2.0)

# square wave function
def square_wave(x):
    if 0.5 < x < 1.5:
        return 1
    return 0

# get @n samples randomly from the square wave
def sample(n):
    samples = []
    for i in range(0, n):
        x = np.random.uniform(DOMAIN.left, DOMAIN.right)
        y = square_wave(x)
        samples.append([x, y])
    return samples

# wrapper class for value function
class ValueFunction:
    # @domain: domain of this function, an instance of Interval
    # @alpha: basic step size for one update
    def __init__(self, feature_width, domain=DOMAIN, alpha=0.2, num_of_features=50):
        self.feature_width = feature_width
        self.num_of_featrues = num_of_features
        self.features = []
        self.alpha = alpha
        self.domain = domain

# there are many ways to place those feature windows,
        # following is just one possible way
        step = (domain.size() - feature_width) / (num_of_features - 1)
        left = domain.left
        for i in range(0, num_of_features - 1):
            self.features.append(Interval(left, left + feature_width))
            left += step
        self.features.append(Interval(left, domain.right))

# initialize weight for each feature
        self.weights = np.zeros(num_of_features)

# for point @x, return the indices of corresponding feature windows
    def get_active_features(self, x):
        active_features = []
        for i in range(0, len(self.features)):
            if self.features[i].contain(x):
                active_features.append(i)
        return active_features

# estimate the value for point @x
    def value(self, x):
        active_features = self.get_active_features(x)
        return np.sum(self.weights[active_features])

# update weights given sample of point @x
    # @delta: y - x
    def update(self, delta, x):
        active_features = self.get_active_features(x)
        delta *= self.alpha / len(active_features)
        for index in active_features:
            self.weights[index] += delta

# train @value_function with a set of samples @samples
def approximate(samples, value_function):
    for x, y in samples:
        delta = y - value_function.value(x)
        value_function.update(delta, x)

# Figure 9.8
def figure_9_8():
    num_of_samples = [10, 40, 160, 640, 2560, 10240]
    feature_widths = [0.2, 0.4, 1.0]
    plt.figure(figsize=(30, 20))
    axis_x = np.arange(DOMAIN.left, DOMAIN.right, 0.02)
    for index, num_of_sample in enumerate(num_of_samples):
        print(num_of_sample, 'samples')
        samples = sample(num_of_sample)
        value_functions = [ValueFunction(feature_width) for feature_width in feature_widths]
        plt.subplot(2, 3, index + 1)
        plt.title('%d samples' % (num_of_sample))
        for value_function in value_functions:
            approximate(samples, value_function)
            values = [value_function.value(x) for x in axis_x]
            plt.plot(axis_x, values, label='feature width %.01f' % (value_function.feature_width))
        plt.legend()

plt.savefig('../images/figure_9_8.png')
    plt.close()

if __name__ == '__main__':
    figure_9_8()

有更好的想法,再编辑完善一下,嘿嘿

昨天周末晚上没有出去,码了一小段,先留着kangkang。的更多相关文章

  1. 需要中文版《The Scheme Programming Language》的朋友可以在此留言(内附一小段译文)

    首先给出原著的链接:http://www.scheme.com/tspl4/. 我正在持续翻译这本书,大概每天都会翻译两小时.若我个人拿不准的地方,我会附上原文,防止误导:还有些不适合翻译的术语,我会 ...

  2. 处理TCP连包的一小段代码

    学习网络编程也有一段时间了,一直听说TCP数据会连包,但一直不知道怎么测试好.最近测试了下:发送方使用对列,将发送的数据存入队列,然后开线程,专门发送.发送多包数据之间不延时.在接收方,他们确实连在一 ...

  3. Cookie是存储在客户端上的一小段数据

    背景 在HTTP协议的定义中,采用了一种机制来记录客户端和服务器端交互的信息,这种机制被称为cookie,cookie规范定义了服务器和客户端交互信息的格式.生存期.使用范围.安全性. 在JavaSc ...

  4. 曹工说JDK源码(4)--抄了一小段ConcurrentHashMap的代码,我解决了部分场景下的Redis缓存雪崩问题

    曹工说JDK源码(1)--ConcurrentHashMap,扩容前大家同在一个哈希桶,为啥扩容后,你去新数组的高位,我只能去低位? 曹工说JDK源码(2)--ConcurrentHashMap的多线 ...

  5. 软件工程-构建之法 理解C#一小段程序

    一.前言 老师给出的要求: 阅读下面程序,请回答如下问题: 问题1:这个程序要找的是符合什么条件的数? 问题2:这样的数存在么?符合这一条件的最小的数是什么? 问题3:在电脑上运行这一程序,你估计多长 ...

  6. 一天一小段js代码(no.4)

    最近在看网上的前端笔试题,借鉴别人的自己来试一下: 题目: 写一段脚本,实现:当页面上任意一个链接被点击的时候,alert出这个链接在页面上的顺序号,如第一个链接则alert(1), 依次类推. 有一 ...

  7. 一天一小段js代码(no.3)

    //遍历属性,返回名值对 function outputAttributes(element){ var pairs = new Array(), attrName, attrValue, i, le ...

  8. 一天一小段js代码(no.2)

    (一)可以用下面js代码来检测弹出窗口是否被屏蔽: var blocked = false ; try { /*window.open()方法接受4个参数window.open(要加载的url,窗口目 ...

  9. 一天一小段js代码(no.1)

    10000个数字中缺少三个数,编程找出缺少的三个数字. 算法实现: /*生成10000个数中随机抽掉三个数后的数组*/ function supplyRandomArray(){ /*生成含有1000 ...

随机推荐

  1. TortoiseGit 保存账号密码

    TortoiseGit下载网址:http://download.tortoisegit.org/tgit/ 修改.gitconfig .gitconfig 用于记录git配置信息 路径:系统盘:\Us ...

  2. SourceTree Mac安装跳过注册步骤

    1.打开sourcetree2.关闭sourcetree3.命令终端输入defaults write com.torusknot.SourceTreeNotMAS completedWelcomeWi ...

  3. Kali Linux install "Veil-Evasion"

    Xx_Step wget https://github.com/ChrisTruncer/Veil/archive/master.zip unzip master.zip cd Veil-Evasio ...

  4. Java实现Kafka的生产者和消费者例子

    Kafka的结构与RabbitMQ类似,消息生产者向Kafka服务器发送消息,Kafka接收消息后,再投递给消费者.生产者的消费会被发送到Topic中,Topic中保存着各类数据,每一条数据都使用键. ...

  5. 20190608_浅谈go&java差异(三)

    20190608_浅谈go&java差异(三) 转载请注明出处https://www.cnblogs.com/funnyzpc/p/10990703.html 第三节内容概览 多线程通讯(线程 ...

  6. macOS Catalina Kernel panic 因为意外而重新启动

    0x00 What's Happend? 我的 MacBook Air 在升级到 Catalina 之后,经常在休眠模式重启,随后在桌面上显示"因为意外而重新启动"的信息,以下是跟 ...

  7. Bug 28450914 : ORA-600: [KDLRCI_GET_INLINE_DATA] SELECTING FROM CDB_FEATURE_USAGE_STATISTICS

    alert日志报错: 2019-11-18T07:15:12.704938+08:00Errors in file /u01/app/oracle/diag/rdbms/sibcyb1/SIBCYB1 ...

  8. 人体分析Demo-百度API

    本示例是采用Delphi 7 调用百度人体分析API:首先说明一下,怎么创建测试应用. 1.  登录百度云官网 https://cloud.baidu.com/ 当然需要一个百度账号 2.  进入管理 ...

  9. Sqlite—数据库管理与表管理

    数据库管理 创建数据库,创建完成之后自动进入 [root@localhost ~]# sqlite3 /www/wwwroot/task.db 使用数据库,如果 /www/wwwroot 路径下面没有 ...

  10. MySQL数据库:聚合函数的使用

    聚合函数 max() 最大值 min() 最小值 avg() 平均值 sum() 求和 count() 符合条件数据的数目 聚合函数不能嵌套使用 # 在统计时字段内没有满足条件的数值只有count返回 ...