# 2.2 模型选择

模型的建立主要有两个步骤：第一，选择适合的模型；第二，根据数据不断优化模型，增强其对数据的解释力度。本章节以线性模型为例，阐述模型的一般使用场景与使用差异。

### 一、线性模型（Linear Model）

线性模型是通过一个或多个自变量来预测因变量，简单而言就是用多个$$x$$（输入）来预测一个$$y$$（输出），可以简单写成以下形式：

$$
y = \beta\_0 + \beta\_1x\_1 + \beta\_2x\_2 + \cdots + \beta\_px\_p + \epsilon  \tag{2.2.1}
$$

其中$$y$$代表因变量，$$β\_0$$代表截距项，$$β\_1$$、$$β\_0$$等代表系数（coefficients），$$x\_1$$、$$x\_2$$等代表自变量。$$\epsilon$$代表误差项，通常假设其服从均值为0的高斯分布。

让我们来看一个粗略的例子。下面这个图展示了我国一个大概的放假随着人口增长的趋势图(只供示例)

<figure><img src="/files/ZE9JJzFelFn6KatbtEP3" alt=""><figcaption><p>图2.2.1 房价与人口的线性关系图</p></figcaption></figure>

这样的一元线性关系可以用以下数学形式表达：

$$
y = a x + b
$$

其中，$$y$$是当地房价，$$x$$是城市人口，$$a$$和$$b$$都是需要拟合的参数。

假设我们设置$$a=0.5$$，$$b=3$$，即$$y=0.5x+3$$。这是用于生成模拟数据的真模型，在一般的应用场景下，这是未知的，在理想状态下通过原始数据建立起的拟合模型应该最大限度接近等于真模型。

```python
import numpy as np
import matplotlib.pyplot as plt

a = 0.5 # coefficient
b = 3   # intercept
noiseVar = 2 # 高斯noise的标准差
x = np.arange(1, 100, 1) # x为1到100的整数

# generate data
y =  a * x + b + noiseVar * np.random.randn(x.size) # 在生成过程中加入高斯noise
```

通过上述代码，我们得到了100个相应的数据点。我们现在通过代码将得到的模拟数据和真模型绘制出来。

```python
plt.plot(x, y, 'o', color='r', label='Data') # plot data
plt.plot(x, a*x+b, '-', color='k', label='True model') # plot tru model
plt.xlabel('Population (1000 ppl)')
plt.ylabel('House price (k yuan)')
plt.legend(fontsize=14)
plt.title('Linear model')
```

会得到如下图像：

<figure><img src="/files/fKNNwC0G6FvqWGVvQbcb" alt=""><figcaption><p>图2.2.2 线性模型模拟结果</p></figcaption></figure>

若模型表达式变成了这样：

$$
y = \beta\_0 + \beta\_1 x + \beta\_2 x^2 + \beta\_3 x^3 + \cdots + \beta\_n x^n + \epsilon
$$

其中，$$y$$表示因变量，$$x$$表示自变量，$$β$$表示系数，$$ϵ$$是误差项。

在此基础上，可以尝试将其改写为类似于线性模型的形式，即：

$$
y = w\_0 + w\_1 x\_1 + w\_2 x\_2 + \cdots + w\_p x\_p + \epsilon
$$

虽然这个模型可以用类似线性模型的方式书写表达式，但其本质上属于非线性模型。

示例：同样用当地人口预测城市房价，假设城市房价与当地人口存在以下关系：

$$
y = ax^2 + bx + c
$$

假设$$a = 0.5$$，$$b = 3$$，$$c = 5$$，生成模拟数据：

```python
import numpy as np
import matplotlib.pyplot as plt

# Here We create data
a = 0.5 # coefficient1
b = 3   # coefficient1
c = 5   # intercept
noiseVar = 500 # noise的程度，增加了噪声大小以便观察
x = np.arange(-50, 100, 1)
# generate data
y =  a * x**2 + b*x + c + noiseVar * np.random.randn(x.size)
```

由此我们获得了150个数据点，接下来我们绘制图像：

```python
plt.plot(x, y, 'o', color='r', label='Data') # plot data
plt.plot(x, a * x**2 + b*x + c, '-', color='k', label='True model') # plot tru model
plt.xlabel('Population (1000 ppl)')
plt.ylabel('House price (k yuan)')
plt.legend(fontsize=14)
plt.title('Linearized model')
```

随后我们可以得到如下图像：

<figure><img src="/files/GAgGhI0HdHCv5wDkPRVu" alt=""><figcaption><p>图2.2.3 线性化模型模拟结果</p></figcaption></figure>

### 二、非线性模型（Nonlinear Model）

用于描述因变量与一个或多个自变量之间的关系，但是因变量与自变量之间无法写作线性组合的形式。其数学表达式一般写作：

$$
y = f(x\_1, x\_2, \ldots, x\_p) + \epsilon
$$

其中，$$y$$为因变量，$$x\_1$$, $$x\_2$$等为自变量，$$f$$是一个非线性函数，$$ϵ$$是误差项。

示例：同样用当地人口预测城市房价，假设城市房价与当地人口存在以下关系：

$$
y = \log(x)
$$

其中y是当地房价，x是当前城市人口。我们通过如下代码来模拟数据：

<pre class="language-python"><code class="lang-python">import numpy as np
import matplotlib.pyplot as plt

<strong># Here We create data
</strong>noiseVar = 1 # noise的程度
x = np.arange(0.01, 3, 0.01)
# generate data
y =  np.log(x) + noiseVar* np.random.randn(x.size)
</code></pre>

我们同样得到了一系列数据点，随后我们绘制图像来直观显示模拟的结果：

```python
plt.plot(x, y, 'o', color='r', label='Data') # plot data
plt.plot(x, np.log(x), '-', color='k', label='True model') # plot tru model
plt.xlabel('Population (1000 ppl)')
plt.ylabel('House price (k yuan)')
plt.legend(fontsize=14)
plt.title('Nonlinear model')
```

随后我们可以得到如下的图像：

<figure><img src="/files/5FPjoAZZiJjL19yi9te7" alt=""><figcaption><p>图2.2.4 非线性模型的模拟结果</p></figcaption></figure>

### 三、模型之间的差异

线性与非线性模型之间存在一定差异，主要差异如下:

1. 线性模型和线性化模型可以写作矩阵形式，而非线性模型一般不行。线性模型和线性化模型都可以写作矩阵形式$$y = WX + \epsilon$$。其中y是因变量，W是参数的矩阵，X是自变量的矩阵，ϵ表示误差项。可以写成矩阵形式在表达、计算和存储等方面有诸多便利。而非线性模型则无法写成矩阵形式。
2. 线性模型较为简单，在优化过程中可能存在已从数学上证明的解析解法，我们也可以通过诸如最小二乘法等简单方法来计算最优参数结果。但非线性模型一般较为复杂，我们通常使用数值估计的方法来优化，比如最大似然估计（MLE）等。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ruyuanzhang.gitbook.io/compmodcogpsy/di-er-zhang-ji-suan-mo-xing-ji-chu/2.2-mo-xing-xuan-ze.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
