昨天周末晚上没有出去,码了一小段,先留着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. IT兄弟连 HTML5教程 CSS3属性特效 弹性盒模型

    CSS3引入了新的盒模型——弹性盒模型,该模型决定一个盒子在其他盒子中的分布方式以及如何处理可用的空间.使用该模型,可以很轻松的创建自适应浏览器窗口的流动布局或自适应字体大小的弹性布局.弹性盒模型看起 ...

  2. SQLserver还原失败(数据库正在使用,无法获得对数据库的独占访问权)

    问题描述: Sql server还原失败(数据库正在使用,无法获得对数据库的独占访问权) 数据库还原的时候还有其他进程连在上面,导致无法获得独占造成的. 这个问题的原因在于有用户连接了当前要做还原的数 ...

  3. HttpRunner学习3--extract提取数据和引用

    前言 在HttpRunner中,我们要想从当前 HTTP 请求的响应结果中提取参数,可以通过 extract 关键字来实现. 本人环境:HttpRunner V1.5.8 测试场景 在这里,我将以一个 ...

  4. 【原创】WinForm中实现单独Time控件的方式

    WinForm默认只提供了DateTimePicker,今天的项目只用时间,不能出现日期,百撕不得骑姐(^^),也没花多少时间,随便试了一下,就成功了,分享一下. 在DateTimePicker属性中 ...

  5. Redis & memcached PK

    redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorted set ...

  6. Database mirroring connection error 4 'An error occurred while receiving data: '10054(An existing connection was forcibly closed by the remote host.)

    公司一SQL Server镜像发生了故障转移(主备切换),检查SQL Server镜像发生主备切换的原因,在错误日志中发现下面错误: Date        2019/8/31 14:09:17   ...

  7. (办公)记事本_Linux目录

    转载自菜鸟教程:https://www.runoob.com/linux/linux-system-contents.html /bin: bin是Binary的缩写, 这个目录存放着最经常使用的命令 ...

  8. 07-Django视图进阶

    1.调试模式 Django项目下的settings.py 默认是DEBUG=True,开发的时候一般要开启调试模式,当项目完成发布必须要改成False,否则会暴露网站的配置信息,修改以下两行: # D ...

  9. 关于controller层用实体类接收参数为null的问题

    如果你的表单标签中包含enctype="multipart/form-data"属性,那么请将它删掉<form action="xxxxxxx" id=& ...

  10. 字典树(Trie)详解

    详解字典树(Trie) 本篇随笔简单讲解一下信息学奥林匹克竞赛中的较为常用的数据结构--字典树.字典树也叫Trie树.前缀树.顾名思义,它是一种针对字符串进行维护的数据结构.并且,它的用途超级广泛.建 ...