昨天周末晚上没有出去,码了一小段,先留着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. Orcle如何获取当前时间

    Oracle获取当月所有日期: SELECT TRUNC(SYSDATE, 'MM') + ROWNUM - 1 FROM DUAL CONNECT BYROWNUM <= TO_NUMBER( ...

  2. Serverless 实战——使用 Rendertron 搭建 Headless Chrome 渲染解决方案

    为什么需要 Rendertron? 传统的 Web 页面,通常是服务端渲染的,而随着 SPA(Single-Page Application) 尤其是 React.Vue.Angular 为代表的前端 ...

  3. 【HTML】--- 列表、表格、form表单标签

    Html常用标签(2) 上篇博客讲了些常用的html标签 :[HTML]---常用标签(1) 这里主要讲 列表.表格标签和 form表单标签. 一.列表.表格标签 1.列表标签 概念 把内容以列表的形 ...

  4. inux CPU监控分析

    一.vmstat 可对操作系统的虚拟内存.进程.CPU活动进行监控 Procs(进程) r: 运行队列中进程数量,这个值也可以判断是否需要增加CPU.(长期大于1) b: 等待IO的进程数量. Mem ...

  5. JDK性能分析工具-引用于深入理解JVM

    1.jps(JVM Process Status Tool) 列出正在运行的虚拟机进程. 2.jstat(JVM Statistics Monitoring Tool) 显示运行状态信息. 3.jin ...

  6. 海康Poe 摄像头尾线与8根网线连接方法

    家里海康POE摄像头铜丝断了一根,拆开自己接了个RJ44座,线序黑. 棕. 绿. 橙. 红. 黄. 紫. 蓝 以此 对应橙白.橙.绿白.蓝.蓝白.绿.棕白.棕经测试无误,可以正常使用

  7. Centos7_sl命令跑火车

    一.更新yum源 wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo 二.安装sl命令 yum ...

  8. Linux系统学习 十四、VSFTP服务—配置文件解析、客户端使用

    3.配置文件解析 默认配置选项: 一般情况下不允许匿名用户登录 全局配置选项:(手工添加) listen_address=192.168.4.1             #设置监听地址 listen_ ...

  9. IT兄弟连 HTML5教程 HTML5文字版面和编辑标签 HTML基础标签

    指引 网页中的信息主要是以文本为主的,可以通过字体.大小.颜色.底纹.边框等来设置文本的属性.文字版面的编辑包括文本标签和格式标签两种,在浏览器中显示的文字内容和格式都要在<body>标记 ...

  10. springboot hikari 连接池 在启动时未初始化数据库连接问题

    在启动Springboot 项目时 2019-11-18 21:32:38.223 INFO 1080 --- [on(4)-127.0.0.1] o.s.web.servlet.Dispatcher ...