工具设计

本章主要关注计量学习工具设计,尝试现代学习工具的实现。

1 数学符号系统

1.1 基本设想

我这里更关注的是数学符号和表达式的系统化构建,最直观的就是打造一个类似js库(library)的系统。系统应该具备如下功能:

  • 具有明确的结构体系,并且可以扩展,最好以以某种有前景的编程语言为基础进行编写。

  • 能展现出基本要素之间较为复杂的关系链或逻辑链,以表达计量经济学分析过程。

需要具备的基本条件:

  • 可靠、严谨的计量知识体系蓝本,例如基于(Hansen 2022, 2021)

  • 基于R语言生态进行设计开发,当然也可以扩展使用相关现代工具。

  • 工作重点在于针对特定开发难点和想法,找到可行解决方案。

  • 通过典型的计量应用情景进行迭代式开发设计,例如误差成分模型(error components model)。

Jo 等 (2021) 对学术文献中的数学符号进行了语义建模(semantics modeling)。他们认为自然语言模型(NLM)在理解和生成数学符号时往往表现不佳。他们提出了一种数学文本预测模型,比遮掩语言模型(masked language modeling)要有更高的预测准确度。同时还发现与符号层预测任务(symbol-level)相比,字典层预测(token-level)任务的模型预测准确度要更高。

Head 等 (2021) 构建了一种基于pdf文档的条目符号实时化科学文献扩展阅读工具。Head, Xie, 和 Hearst (2022) 全面比较了目前为了增强数学公式的可读性目标下的各种视觉化和交互性表达实践。

1.2 LaTex周边工具

一个传统或主流的记号系统工具是LaTex

Quarto html网页输出支持多种方式的LaTex公式渲染(参看quarto说明页),包括:

  • mathjax: Use MathJax to display embedded TeX math in HTML output.

  • katex: Use KaTeX to display embedded TeX math in HTML output.

(Head, Xie, 和 Hearst 2022 sec 2.1.2) KaTeX implicitly supports a broad array of augmentations by allowing authors to use the full complement of CSS styles on arbitrary expressions.

  • webtex: Convert TeX formulas to tags that link to an external script that converts formulas to images.

  • gladtex: Enclose TeX math in tags in HTML output. The resulting HTML can then be processed by GladTeX to produce images of the typeset formulas and an HTML file with links to these images.

  • mathml: Convert TeX math to MathML (note that currently only Firefox and Safari natively support MathML)

  • plain: No special processing (formulas are put inside a span with class=“math”).

公式的颜色设定往往需要定义个性化的宏脚本(macro)。但是过于个性化或不受约束的宏脚本,会严重影响公式编写效率和可读性(Head, Xie, 和 Hearst 2022 sec 4.2.4, fig. 12)

提示

一个Quarto presentation的示例,可以参看。其中公式被添加了红色和绿色(slide 28);(xaringan slide也可以同此设置)宏脚本定义(见代码)如下:

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
  TeX: {
    Macros: {
      red: ["{\\color{red}{#1}}", 1],
      green: ["{\\color{green}{#1}}", 1],
    },
    loader: {load: ['[tex]/color']},
    tex: {packages: {'[+]': ['color']}}
  }
});
</script>

1.3 基于JS语言

(1)Quarto原生支持observable JavaScript,具体可以参看quarto说明页。Observable官方的简介可以参看A taste of Observable (链接)。

在quarto文档中可以直接调用observable引擎,如下。

```{ojs}
//| echo: false
filtered = data.filter(function(penguin) {
  return bill_length_min < penguin.bill_length_mm &&
         islands.includes(penguin.island);
})
```

(2)Penrose是一种基于observable语言开发的视觉化交互设计工具(可参看:官方首页;以及(Head, Xie, 和 Hearst 2022, section 5.2))。

Penrose “is a platform that enables people to create beautiful diagrams just by typing mathematical notation in plain text. The goal is to make it easy for non-experts to create and explore high-quality diagrams, providing deeper insight into challenging technical concepts. We aim to democratize the process of creating visual intuition.”

(3)Tangle是另一种基于JavaScript的js库(JavaScript library),可用于创建交互性公式(github 仓库已经很久没有维护)。

官网介绍 :Tangle is a JavaScript library for creating reactive documents. Your readers can interactively explore possibilities, play with parameters, and see the document update immediately. Tangle is super-simple and easy to learn.

1.4 基于json语法

(1)Vega-Lite是一种基于json格式的可视化语法(可参看:github官网(Head, Xie, 和 Hearst 2022, section 6.2.1))。

Vega-Lite is a high-level grammar of interactive graphics. It provides a concise, declarative JSON syntax to create an expressive range of visualizations for data analysis and presentation.

(2)类似的语法工具还包括Canis

1.5 基于动态语法

Manim可以用于数学符号或公式的视频化编程制作(github 仓库是通过python进行维护和更新,暂时没有R语言方案)。

官方介绍Manim is an animation engine for explanatory math videos. A community-maintained Python framework for creating mathematical animations.

1.6 基于智能学习

(1)Mathpix借助了当前的AI技术来增强图片(或截图)、文档(如pdf)等的智能化公式识别和转换。根据最新推出的功能,甚至可以实现公式识别后的求解计算(solver),具体参看”New Solver tab in Snip”(链接)。

官方介绍:Powering scientific communication through AI. Snipping Tool is a desktop app that allows you to copy math and chemistry from your screen to your clipboard from a single keyboard shortcut. Compatible with LaTeX, Markdown, and MS Word.

(2)WolframAlpha具有开创性的计算分析平台,独立创建了专门的分析语言Wolfram Language,并且持续整合当前的AI技术,提供了众多的计算和分析工具。

官方介绍:Compute expert-level answers using Wolfram’s breakthrough algorithms, knowledgebase and AI technology.

Wolfram language emphasizes symbolic computation, functional programming, and rule-based programming[9] and can employ arbitrary structures and data.。

MathematicaWolframAlpha发行的一款符号运算(symbolic computation)软件。Mathematica version 9提供了R交互接口(参看说明)。

提示

博文”How do I connect an R installation to my Wolfram product?“介绍了如何实现二者的交互连接(参看

(2)方程求解绘图展示工具:Online Equation Solver

2 多语言站点

2.1 谷歌翻译API

Google Cloud Translation API(网址

  • Google Cloud 控制台

  • IAM 和管理 》服务账号(service account)

  • Google Cloud 项目:选择已经创建的项目名称

  • 已启用的API和服务:Google Cloud Translation API 》凭据

每月前50万个字符免费

2.2 DeepL API翻译

The goal of babeldown is to support workflows that include automatic translation of Markdown-based R content, through DeepL API.

DeepL API 官方网址。需要注册和信用卡。免费翻译限制:50万字符/月。

需要国外受支持国家的(美国)地址和信用卡:4116 Balboa St, Lake Isabella, California 93240, USA

babeldown包(github仓库

renv::install("ropensci-review-tools/babeldown")

2.3 站点实现

方法1:使用quarto book的多语言版本风格:

The goal of babelquarto (github仓库)is to render a Quarto multilingual book structured like the rOpenSci dev guide:

  • each qmd is present once for the main language,

  • and once more for each other language with an extension à la .es.qmd

开发者提供了一个样本站点

方法2:当然,我们也可以使用quarto site风格的多语言站点。可以参看A multi-language (German/ English) Quarto website,这里通过设定了Project Profiles,例如设定_quarto.english.yml。这种方法的缺点是没有以book样式呈现。

参考资源:

3 数学公式

3.1 问题描述

下面是一个典型的回归分析R代码文件:

```{r ols-reg}
#| message: false
#| warning: false

library(tidyverse)
library(magrittr)
library(scales)
source(here::here("Rscript/case-ols-FF-restaurant.R"), encoding = "UTF-8")

options(scipen=999)
```
  • 给定已经写好回归模型的R代码(例如上面案例为一元线性回归)

  • 回归分析的中间步骤对象都得到了保存。例如,FF平方和:\(\sum_\limits{i=1}^n {X^2_i}\)R对象为FXX,计算值为682744;\(\sum_\limits{i=1}^n {X_i Y_i}\)R对象为FXY,计算值为444 342.58;诸如此类。

  • 计算相关系数\(r_{XY}\)和截距系数\(\hat{\beta}_2\),中间计算步骤过程需要用到前述R对象(FXXFXY等)

  • 最终将理论公式、中间计算步骤、最终结果以LaTex数学公式进行呈现。

一般而言,我们有两种方法来实现上述目标:

  1. 嵌套行内R代码(inline code)到Latex公式(见 节 3.2)。最大优点在于保持正常的LaTex数学公式写作风格。缺点在于复杂的行内R代码会带来公式命令行的复杂化;此外,在LaTex环境下(双美元符号环境$$,或者```latex),这时的行内R代码不能直接运行。

  2. 使用cat函数构造Latex公式(见 节 3.3)。最大优点在于可以实时运行R代码。缺点在于不能保持正常LaTex数学公式写作风格。例如:需要敲写更多的特殊逃逸字符(escape)\\;需要使用cat()函数;要求设定R代码块参数results = asis

3.2 嵌套行内R代码(inline code)到Latex公式

销售价格\(X_i\)与销售额\(Y_i\)之间的简单相关系数\(r_{XY}\)

(1)双货币符号环境,不能够运行number(r, 0.0001)代码:

$$
\begin{aligned}
r &= \frac{n \sum{X_iY_i} - \sum{X_i}\cdot \sum{Y_i}}{\sqrt{n\sum{X_i^2} - (\sum{X_i})^2} \cdot \sqrt{n\sum{Y_i^2} - (\sum{Y_i})^2}} \\
& = \frac{`r n` \times `r number(FXY, 0.01)` - `r FX` \times `r number(FY, 0.01)`}{\sqrt{`r n` \times `r FXX` - (`r FX`)^2} \cdot \sqrt{`r n` \times `r
number(FYY, 0.01)` - (`r number(FY, 0.01)`)^2}} \\
& = `r number(r, 0.0001)`
\end{aligned}
$$ {#eq-dollar}

\[ \begin{aligned} r &= \frac{n \sum{X_iY_i} - \sum{X_i}\cdot \sum{Y_i}}{\sqrt{n\sum{X_i^2} - (\sum{X_i})^2} \cdot \sqrt{n\sum{Y_i^2} - (\sum{Y_i})^2}} \\ & = \frac{30 \times 444 342.58 - 4524 \times 2 943.60}{\sqrt{30 \times 682744 - (4524)^2} \cdot \sqrt{30 \times `r number(FYY, 0.01)` - (2 943.60)^2}} \\ & = 0.9649 \end{aligned} \tag{1}\]

(2)`` `latex环境,仅用于展示公式的LaTex渲染代码,但是行内R代码还是会自动执行:

`` `latex
$$
\begin{aligned}
r &= \frac{n \sum{X_iY_i} - \sum{X_i}\cdot \sum{Y_i}}{\sqrt{n\sum{X_i^2} - (\sum{X_i})^2} \cdot \sqrt{n\sum{Y_i^2} - (\sum{Y_i})^2}} \\
& = \frac{`r n` \times `r number(FXY, 0.01)` - `r FX` \times `r number(FY, 0.01)`}{\sqrt{`r n` \times `r FXX` - (`r FX`)^2} \cdot \sqrt{`r n` \times `r
number(FYY, 0.01)` - (`r number(FY, 0.01)`)^2}} \\
& = `r number(r, 0.0001)`
\end{aligned}
$$
`` `
\begin{aligned}
r &= \frac{n \sum{X_iY_i} - \sum{X_i}\cdot \sum{Y_i}}{\sqrt{n\sum{X_i^2} - (\sum{X_i})^2} \cdot \sqrt{n\sum{Y_i^2} - (\sum{Y_i})^2}} \\
& = \frac{30 \times 444 342.58 - 4524 \times 2 943.60}{\sqrt{30 \times 682744 - (4524)^2} \cdot \sqrt{30 \times 289 236.10 - (2 943.60)^2}} \\
& = 0.9649
\end{aligned}
注释

R行内代码的执行力量非常顽强,甚至knitr引擎之外也能被运行,这是一个长久存在的话题。可参看:

3.3 使用cat函数构造Latex公式

普通最小二乘法(OLS)下的斜率系数\(\hat{\beta}_2\)

```{r eq-cat}
#| results: asis

cat(
  "$$\\begin{align}",
  "\\hat{\\beta}_2 &=\\frac{n\\sum{X_iY_i}-\\sum{X_i}\\sum{Y_i}}{n\\sum{X_i^2}-\\left ( \\sum{X_i} \\right)^2}\\\\",
str_c(
  "&=\\frac{",n,"\\ast",number(FXY, 0.01),"-",FX, "\\ast",number(FY, 0.01),"}{",n,"\\ast",FXX,"-",FX,"^2}",
  "=",number(b2, 0.0001)
  ),
"\\end{align}$$",
sep="\n"
)
```

\[\begin{align} \hat{\beta}_2 &=\frac{n\sum{X_iY_i}-\sum{X_i}\sum{Y_i}}{n\sum{X_i^2}-\left ( \sum{X_i} \right)^2}\\ &=\frac{30\ast444 342.58-4524\ast2 943.60}{30\ast682744-4524^2}=0.8524 \end{align}\]

参考

Hansen, Bruce. 2021. 《Probability and Statistics for Economists. This textbook is the first in a two-part series covering the core material typically taught in a one-year Ph.D. course in econometrics.
———. 2022. Econometrics. Princeton: Princeton University Press.
Head, Andrew, Kyle Lo, Dongyeop Kang, Raymond Fok, Sam Skjonsberg, Daniel S. Weld, 和 Marti A. Hearst. 2021. 《Augmenting Scientific Papers with Just-in-Time, Position-Sensitive Definitions of Terms and Symbols. Proceedings of the 2021 CHI Conference on Human Factors in Computing Systems, 五月, 1–18.
Head, Andrew, Amber Xie, 和 Marti A. Hearst. 2022. 《Math Augmentation: How Authors Enhance the Readability of Formulas Using Novel Visual Design Practices. 收入 Proceedings of the 2022 CHI Conference on Human Factors in Computing Systems, 1–18. CHI ’22. New York, NY, USA: Association for Computing Machinery. https://doi.org/10.1145/3491102.3501932.
Jo, Hwiyeol, Dongyeop Kang, Andrew Head, 和 Marti A. Hearst. 2021. 《Modeling Mathematical Notation Semantics in Academic Papers. 收入 Findings of the Association for Computational Linguistics: EMNLP 2021, 3102–15.