昨天周末晚上没有出去,码了一小段,先留着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. Zabbix-(二) 使用docker部署

    Zabbix-(二)使用docker部署 一.前言 前文记录了在服务器上搭建zabbix平台,本文记录使用docker部署zabbix 4.4 准备 Centos7.6 虚拟机,并安装了docker ...

  2. 如果获取ruby的hash的v值?

    最近写ruby,用到hash,通过k去获取v值,有时候通过hash["k"]去获取可以获取到,有时候通过又获取不到,感觉一脸懵逼 仔细观察了下ruby的hash,有两种表现形式,所 ...

  3. C#线程学习笔记一:线程基础

    本笔记摘抄自:https://www.cnblogs.com/zhili/archive/2012/07/18/Thread.html,记录一下学习过程以备后续查用. 一.线程的介绍 进程(Proce ...

  4. Selenium环境要配置浏览器驱动

    1.浏览器环境变量添加到path 2.将浏览器相应的驱动.exe复制到浏览器目录 3.这条就是让我傻逼似的配置一上午的罪魁祸首:将驱动.exe复制到python目录!!!! Selenium

  5. TSC打印机防重码在线检测系统

    条码标签作为产品的一个身份标识,被应用得越来越普及,但随着使用量的增大,在打印条码流水号的过程中,偶尔会出现打印重复号码的标签出现,这样对产品生产及管理过程中会产生极大的混乱,会收到严重的客诉及返工, ...

  6. Eclipse如何重置窗口

    https://jingyan.baidu.com/article/915fc41459585f51394b20c3.html 在Eclipse进行开发的时候,我们经常会由于这个窗口或者那个窗口没有打 ...

  7. Windows自动执行应用程序或脚本(可以通过写bat文件定时关机等)

    1. Windows每天定时执行某个应用程序 1.1 右键我的电脑选择管理,并选择任务计划程序,如下 演示 --- 1.2 创建基本任务 演示 1.3 Windows每天定时关机设置参数 演示 1. ...

  8. Oracle查看 open_cursors 和 session_cached_cursors

    本文转自 http://blog.itpub.net/25583515/viewspace-2152997/ 查看当前session已使用的最大open cursor数 和cached cursor数 ...

  9. 【转载】【笔记】vue-router之路由传递参数

    参考博客地址:https://blog.51cto.com/4547985/2390799 1.通过<router-link> 标签中的to传参 基本语法: <router-link ...

  10. 使用ClickOnce发布Windows应用程序

    前言 因本人工作需要,在一名非常非常好的老师的指导下,入门了C#,再次向老师表示感谢. 本人平时经常遇到的业务就是将数据下发给各部门,并让各部门再上报,此过程中经常会遇到数据格式不正确,数据错误等诸多 ...