<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>一颗鼠儿果的博客</title>
  
  <subtitle>鼠儿果，恢复少量神</subtitle>
  <link href="https://syuoni.github.io/atom.xml" rel="self"/>
  
  <link href="https://syuoni.github.io/"/>
  <updated>2021-01-21T06:06:29.787Z</updated>
  <id>https://syuoni.github.io/</id>
  
  <author>
    <name>syuoni</name>
    
  </author>
  
  <generator uri="https://hexo.io/">Hexo</generator>
  
  <entry>
    <title>Pre-Training in NLP</title>
    <link href="https://syuoni.github.io/posts/Pre-Training-in-NLP/"/>
    <id>https://syuoni.github.io/posts/Pre-Training-in-NLP/</id>
    <published>2021-01-14T07:36:33.000Z</published>
    <updated>2021-01-21T06:06:29.787Z</updated>
    
    <content type="html"><![CDATA[<p>This blog briefly reviews the pre-training embeddings and models in NLP.<br><a id="more"></a></p><h2 id="Pre-Trained-Embeddings"><a href="#Pre-Trained-Embeddings" class="headerlink" title="Pre-Trained Embeddings"></a>Pre-Trained Embeddings</h2><h3 id="Word2Vec"><a href="#Word2Vec" class="headerlink" title="Word2Vec"></a>Word2Vec</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">T. Mikolov, et al., 2013. Efficient Estimation of Word Representations in Vector Space. arXiv preprint arXiv:1301.3781.</span><br><span class="line">T. Mikolov, et al., 2013. Distributed representations of words and phrases and their compositionality. NIPS 2013. </span><br><span class="line">X. Rong, 2014. Word2vec parameter learning explained. arXiv preprint arXiv:1411.2738.</span><br></pre></td></tr></table></figure><p><img src="/images/CBOW-and-Skip-Gram.png" alt="CBOW and Skip-Gram"></p><h4 id="Continuous-Bag-of-Words-Model"><a href="#Continuous-Bag-of-Words-Model" class="headerlink" title="Continuous Bag-of-Words Model"></a>Continuous Bag-of-Words Model</h4><p>Given a sequence of words $w_1, w_2, w_3, \cdots, w_T$, maximize the average log probability:</p><script type="math/tex; mode=display">\frac{1}{T} \sum_{t=1}^{T} \log p \left( w_t | w_{t-c}, \dots, w_{t-1}, w_{t+1}, \dots, w_{t+c} \right)</script><p>where </p><script type="math/tex; mode=display">\begin{aligned}p \left( w_t | w_{t-c}, \dots, w_{t-1}, w_{t+1}, \dots, w_{t+c} \right) &= \frac{\exp \left( v'_t \cdot \bar{v}_{t,c} \right)}{\sum_{k=1}^W \exp \left( v'_k \cdot \bar{v}_{t,c} \right)} \\\bar{v}_{t,c} &= \frac{1}{2C} \sum_{-c \le j \le c, j \neq 0} v_{t+j}\end{aligned}</script><p>where $v_i$ and $v’_i$ are “input” and “output” vector representations of word $i$, and $W$ is the vocabulary size. </p><h4 id="Continuous-Skip-Gram-Model"><a href="#Continuous-Skip-Gram-Model" class="headerlink" title="Continuous Skip-Gram Model"></a>Continuous Skip-Gram Model</h4><p>Given a sequence of words $w_1, w_2, w_3, \cdots, w_T$, maximize the average log probability: </p><script type="math/tex; mode=display">\frac{1}{T} \sum_{t=1}^{T} \sum_{-c \le j \le c, j \neq 0} \log p \left( w_{t+j} | w_t \right)</script><p>where the basic formula of $p \left( w_{t+j} | w_t \right)$ can be:</p><script type="math/tex; mode=display">p \left( w_{t+j} | w_t \right) = \frac{\exp \left( v'_{t+j} \cdot v_t \right)}{\sum_{k=1}^W \exp \left( v'_k \cdot v_t \right)}</script><h4 id="Hierarchical-Softmax"><a href="#Hierarchical-Softmax" class="headerlink" title="Hierarchical Softmax"></a>Hierarchical Softmax</h4><h4 id="Negative-Sampling"><a href="#Negative-Sampling" class="headerlink" title="Negative Sampling"></a>Negative Sampling</h4><h3 id="GloVe-Global-Vectors-for-Word-Representation"><a href="#GloVe-Global-Vectors-for-Word-Representation" class="headerlink" title="GloVe: Global Vectors for Word Representation"></a>GloVe: Global Vectors for Word Representation</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">J. Pennington, R. Socher, C. D. Manning, 2014. GloVe: Global vectors for word representation. EMNLP 2014.</span><br></pre></td></tr></table></figure><p>The embeddings are trained only on the non-zero elements in a <strong>word-word co-occurrence matrix</strong>.</p><p>Let the word-word co-occurrence matrix be denoted by $X$, whose entries $X_{ij}$ tabulate the number of times word $j$ occurs in the context of word $i$.<br>Let $X_i = \sum_k X_{ik}$ be the number of times any word appears in the context of word $i$.<br>Let $P_{ij} = P(j|i) = X_{ij} / X_{i}$ be the probability that word $j$ appear in the context of word $i$. </p><h4 id="How-certain-aspects-of-meaning-can-be-extracted-from-co-occurance-probabilities"><a href="#How-certain-aspects-of-meaning-can-be-extracted-from-co-occurance-probabilities" class="headerlink" title="How certain aspects of meaning can be extracted from co-occurance probabilities?"></a>How certain aspects of meaning can be extracted from co-occurance probabilities?</h4><p>Take $i = ice$ and $j = steam$, then: </p><ul><li>For words $k$ related to $ice$ but not $steam$ (e.g., $k = solid$), the ratio $P_{ik}/P_{jk}$ should be large; </li><li>For words $k$ related to $steam$ but not $ice$ (e.g., $k = gas$), the ratio $P_{ik}/P_{jk}$ should be small; </li><li>For words $k$ related to both (e.g., $k = water$) or neither (e.g., $k = fashion$), the ratio $P_{ik}/P_{jk}$ should be close to one. </li></ul><p>Hence, compared to the <strong>raw probabilities</strong>, the <strong>ratio</strong> is better able to distinguish relevant words ($solid$ and $gas$) from irrelevant words ($water$ and $fashion$). </p><h4 id="The-GloVe-Model"><a href="#The-GloVe-Model" class="headerlink" title="The GloVe Model"></a>The GloVe Model</h4><p>Note that the ratio $P_{ik}/P_{jk}$ depends on three words $i$, $j$ and $k$, so <strong>the most general model</strong> takes the form: </p><script type="math/tex; mode=display">F \left( w_i, w_j, \tilde{w}_k \right) = \frac{P_{ik}}{P_{jk}}</script><p>where $w \in \mathbb{R}^d$ are word vectors, and $\tilde{w} \in \mathbb{R}^d$ are <strong>separate</strong> context word vectors. </p><ol><li><p>To only consider vector differences, the equation becomes:</p><script type="math/tex; mode=display">F \left( w_i - w_j, \tilde{w}_k \right) = \frac{P_{ik}}{P_{jk}}</script></li><li><p>To keep the linear structure of vector space, the equation becomes:</p><script type="math/tex; mode=display">F \left( (w_i - w_j)^T \tilde{w}_k \right) = \frac{P_{ik}}{P_{jk}}</script></li><li><p>Require that $F = \exp$, then: </p><script type="math/tex; mode=display">\exp \left( (w_i - w_j)^T \tilde{w}_k \right) = \frac{\exp \left( w_i^T \tilde{w}_k \right)}{\exp \left( w_j^T \tilde{w}_k \right)} = \frac{P_{ik}}{P_{jk}}</script><p>Then:</p><script type="math/tex; mode=display">\exp \left( w_i^T \tilde{w}_k \right) = P_{ik} = \frac{X_{ik}}{X_i}</script><p>Then:</p><script type="math/tex; mode=display">w_i^T \tilde{w}_k = \log \left( P_{ik} \right) = \log \left( X_{ik} \right) - \log \left( X_i \right)</script></li><li><p>Absorb $\log \left( X_i \right)$ to a bias $b_i$, and add another bias $\tilde{b}_k$ for symmetry: </p><script type="math/tex; mode=display">w_i^T \tilde{w}_k + b_i + \tilde{b}_k = \log \left( X_{ik} \right)</script></li></ol><p>A <strong>weighted least squares regression model</strong> to estimate the parameters: </p><script type="math/tex; mode=display">J = \sum_{i,j=1}^{V} f(X_{ij}) \left( w_i^T \tilde{w}_k + b_i + \tilde{b}_k - \log \left( X_{ik} \right) \right)^2</script><p>where $V$ is the vocabulary size and $f$ is the weighting function. </p><h4 id="Training-Details"><a href="#Training-Details" class="headerlink" title="Training Details"></a>Training Details</h4><p>Train the model using <strong>AdaGrad</strong>, stochastically sampling nonzero elements from $X$. </p><h3 id="FastText"><a href="#FastText" class="headerlink" title="FastText"></a>FastText</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">P. Bojanowski, E. Grave, A. Joulin, T. Mikolov, 2016. Enriching word vectors with subword information. ACL 2017.</span><br></pre></td></tr></table></figure><p>Each word is represented as a bag of <strong>character n-grams</strong>.<br>Each <strong>character n-gram</strong> is associated to a vector representation, and a word is represented as the sum of the vector representations of its <strong>character n-grams</strong>. </p><h2 id="Pre-Trained-Models"><a href="#Pre-Trained-Models" class="headerlink" title="Pre-Trained Models"></a>Pre-Trained Models</h2><h3 id="CoVe-Learned-in-Translation-Contextualized-Word-Vectors"><a href="#CoVe-Learned-in-Translation-Contextualized-Word-Vectors" class="headerlink" title="CoVe: Learned in Translation: Contextualized Word Vectors"></a>CoVe: Learned in Translation: Contextualized Word Vectors</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">B. McCann, et al., 2017. Learned in Translation: ContextualizedWord Vectors. NIPS 2017.</span><br></pre></td></tr></table></figure><p>Train an encoder for a <strong>large</strong> NLP task, and transfer the trained encoder to other NLP tasks.<br>Specifically, McCann et al. (2017) train an attentional seq2seq model for <strong>machine translation</strong>, and use the LSTM-based encoder (which is a <strong>common component</strong> in NLP tasks) to transfer to other tasks. </p><p>The largest machine translation dataset is WMT 2017, consisting roughly 7M sentence pairs. </p><h3 id="ELMo"><a href="#ELMo" class="headerlink" title="ELMo"></a>ELMo</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">M. E. Peters, et al., 2018. Deep contextualized word representations. ACL 2018.</span><br></pre></td></tr></table></figure><h4 id="Bidirectional-language-models"><a href="#Bidirectional-language-models" class="headerlink" title="Bidirectional language models"></a>Bidirectional language models</h4><p>Given a sequence of words $(w_1, w_2, w_3, \cdots, w_T)$, a forward language model (forward LM) computes the probability of the sequence by modeling the word $w_k$ given the history $(w_1, w_2, \cdots, w_{k-1})$: </p><script type="math/tex; mode=display">p \left( w_1, w_2, \dots, w_T \right) = \prod_{k=1}^T p \left( w_k | w_1, w_2, \cdots, w_{k-1} \right)</script><p>And a backward LM computes:</p><script type="math/tex; mode=display">p \left( w_1, w_2, \dots, w_T \right) = \prod_{k=1}^T p \left( w_k | w_{k+1}, w_{k+2}, \cdots, w_T \right)</script><p>With a bidirectional LSTM, the log likelihood is:</p><script type="math/tex; mode=display">\begin{aligned}\sum_{k=1}^T &\log p \left( w_k | w_1, w_2, \cdots, w_{k-1}; \Theta_x, \overrightarrow{\Theta}_{LSTM}, \Theta_s \right) + \\&\log p \left( w_k | w_{k+1}, w_{k+2}, \cdots, w_T; \Theta_x, \overleftarrow{\Theta}_{LSTM}, \Theta_s \right) \end{aligned}</script><p>where $\Theta_x$ is the token representation layer, and $\Theta_s$ is the softmax layer. </p><h4 id="ELMo-representations"><a href="#ELMo-representations" class="headerlink" title="ELMo representations"></a>ELMo representations</h4><p>Combine the outputs of different LSTM layers (including the token representation layer) as ELMo representations. </p><h3 id="Flair"><a href="#Flair" class="headerlink" title="Flair"></a>Flair</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">A. Akbik, et al., 2018. Contextual String Embeddings for Sequence Labeling. COLING 2018.</span><br></pre></td></tr></table></figure><p><strong>Character-level language modeling</strong>: An bidirectional LSTM, each LSTM is trained to predict the next character given the history characters. </p><h3 id="BERT"><a href="#BERT" class="headerlink" title="BERT"></a>BERT</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">J. Devlin, et al., 2018. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019.</span><br></pre></td></tr></table></figure><p><img src="/images/BERT-GPT-ELMo.png" alt="BERT vs. GPT vs. ELMo"></p><h4 id="Model-Architecture"><a href="#Model-Architecture" class="headerlink" title="Model Architecture"></a>Model Architecture</h4><p><strong>Transformer encoder</strong>: Transformer blocks attend to both left and right contexts. </p><h4 id="Input-Representation"><a href="#Input-Representation" class="headerlink" title="Input Representation"></a>Input Representation</h4><ul><li>WordPiece Embeddings: Split word pieces are denoted with ##.</li><li>Trainable positional embeddings with supported sequence lengths up to 512 tokens. </li><li>The first token of every sequence is always <code>[CLS]</code>, which is used as the aggregate sequence representation<br>for classification tasks. </li><li>Sentence pairs are packed into single sequence. <ul><li>The two sentences are seperated with <code>[SEP]</code>. </li><li>Add a trainable <strong>sentence A embedding</strong> to every token of the first sentence.</li><li>Add a trainable <strong>sentence B embedding</strong> to every token of the second sentence.</li><li>For single-sentence inputs, only use the sentence A embeddings.</li></ul></li></ul><p><img src="/images/BERT-input-representation.png" alt="BERT Input Representation"></p><h4 id="Pre-Training-Task-1-Masked-LM-MLM"><a href="#Pre-Training-Task-1-Masked-LM-MLM" class="headerlink" title="Pre-Training Task #1: Masked LM (MLM)"></a>Pre-Training Task #1: Masked LM (MLM)</h4><p><strong>Masked LM</strong>: Randomly mask some percentage of the input tokens, and use other tokens to predict the masked tokens. Or referred as <strong>Cloze Task</strong>.<br>Specifically, 15% tokens are masked, being replaced with a <code>[MASK]</code> token. However, this creates a <strong>mismatch</strong> between pre-training and fine-tuning, since the <code>[MASK]</code> token is never seen during fine-tuning. Hence, the data generator chooses 15% random tokens and performs:</p><ul><li>80% of the time: Replace with <code>[MASK]</code> token; </li><li>10% of the time: Replace with a random word; </li><li>10% of the time: Keep the word unchanged. </li></ul><h4 id="Pre-Training-Task-2-Next-Sentence-Prediction-NSP"><a href="#Pre-Training-Task-2-Next-Sentence-Prediction-NSP" class="headerlink" title="Pre-Training Task #2: Next Sentence Prediction (NSP)"></a>Pre-Training Task #2: Next Sentence Prediction (NSP)</h4><p>Many downstream tasks such as Question Answering (QA) and Natural Language Inference (NLI) are based on understanding the relationship between two text sentences.<br><strong>Next Sentence Prediction</strong>: Choose the sentences A and B for each pretraining example</p><ul><li>50% of the time: B is the actual next sentence that follows A;</li><li>50% of the time: B is a random sentence from the corpus. </li></ul><p>The objective is to predict whether B is actually following A. </p><h4 id="Pre-Training-Procedure"><a href="#Pre-Training-Procedure" class="headerlink" title="Pre-Training Procedure"></a>Pre-Training Procedure</h4><ul><li>Batch size: 256 sequences (256 * 512 = 128,000 tokens)</li><li>Training steps: 1,000,000</li><li>Optimization<ul><li>Adam with learning rate of 1e-4, L2 weight decay of 0.01</li><li>Learning rate warmup over the first 10,000 steps, and linear decay of the learning rate</li></ul></li><li>Dropout: 0.1 on all layers</li></ul><h4 id="Fine-Tuning-Procedure"><a href="#Fine-Tuning-Procedure" class="headerlink" title="Fine-Tuning Procedure"></a>Fine-Tuning Procedure</h4><ul><li>Batch size: 16, 32</li><li>Learning rate (Adam): 5e-5, 3e-5, 2e-5</li><li>Number of epochs: 3, 4</li></ul><h3 id="GPT-Generative-Pre-Training"><a href="#GPT-Generative-Pre-Training" class="headerlink" title="GPT (Generative Pre-Training)"></a>GPT (Generative Pre-Training)</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">A. Radford, et al., 2018. Improving Language Understanding by Generative Pre-Training.</span><br></pre></td></tr></table></figure><h4 id="Model-Architecture-1"><a href="#Model-Architecture-1" class="headerlink" title="Model Architecture"></a>Model Architecture</h4><p><strong>Transformer decoder</strong>: Transformer blocks attend to only left contexts. </p><h4 id="Unsupervised-Pre-Training"><a href="#Unsupervised-Pre-Training" class="headerlink" title="Unsupervised Pre-Training"></a>Unsupervised Pre-Training</h4><p>Given an unlabeled sequence of tokens $\mathcal{U} = (u_1, u_2, u_3, \cdots, u_T)$, use a standard language modeling objective to maximize the following likelihood:</p><script type="math/tex; mode=display">L_1(\mathcal{U}) = \sum_{k} \log p \left( u_k | u_{k-1}, u_{k-2}, \dots, u_{k-c}; \Theta \right)</script><p>where $c$ is the context window size, $\Theta$ represents the model parameters. </p><p>Specifically, </p><script type="math/tex; mode=display">\begin{aligned}h_0 &= U W_e + W_p \\h_l &= \mathrm{transformer\_decoder\_block} (h_{l-1}),  \forall i \in [1, n] \\p(u) &= \mathrm{softmax} (h_n W_e^T)\end{aligned}</script><p>where $U = (u_{-k}, \dots, u_{-1})$ is the context vector of tokens, $n$ is the number of layers, $W_e$ is the token embedding matrix, and $W_p$ is the position embedding matrix. </p><h4 id="Supervised-Fine-Tuning"><a href="#Supervised-Fine-Tuning" class="headerlink" title="Supervised Fine-Tuning"></a>Supervised Fine-Tuning</h4><p>Given a labeled dataset $\mathcal{C}$, consisting sequences of input tokens $(x^1, x^2, x^3, \cdots, x^T)$, along with labels $y$, maximize:</p><script type="math/tex; mode=display">L_2(\mathcal{C}) = \sum_{(x, y)} \log p \left( y | x^1, x^2, x^3, \cdots, x^T \right)</script><p>Include language modeling as an auxiliary objective:</p><script type="math/tex; mode=display">L_3(\mathcal{C}) = L_2(\mathcal{C}) = \lambda \cdot L_1(\mathcal{C})</script><h4 id="Task-Specific-Input-Transformations"><a href="#Task-Specific-Input-Transformations" class="headerlink" title="Task-Specific Input Transformations"></a>Task-Specific Input Transformations</h4><p>Introduce special tokens for downstream tasks with <strong>structured inputs</strong> like textual entailment or QA. </p><ul><li>Randomly initialized start token <code>&lt;s&gt;</code> and end token <code>&lt;e&gt;</code>. </li><li>Delimiter token <code>$</code>. </li></ul><h4 id="Zero-Shot-Behaviors"><a href="#Zero-Shot-Behaviors" class="headerlink" title="Zero-Shot Behaviors"></a>Zero-Shot Behaviors</h4><p><strong>Zero-Shot</strong> Evaluation: Use the <strong>pre-trained generative model</strong> to perform tasks <strong>without supervised finetuning</strong>:</p><ul><li>CoLA (Linguistic acceptability): Scored as the average token log-probability the generative model assigns and predictions are made by thresholding.</li><li>SST-2 (Sentiment analysis): Append the token <code>very</code> to each example, restrict the language model’s output distribution to only the words <code>positive</code> and <code>negative</code>, and guess the token it assigns higher probability to as the prediction. </li><li>RACE (Question answering): Pick the answer the generative model assigns the highest average token log-probability when conditioned on the document and question. </li><li>DPRD (Winograd schemas): Replace the definite pronoun with the two possible referrents and predict the resolution that the generative model assigns higher average token log-probability to the rest of the sequence after the substitution.</li></ul><h3 id="GPT-2"><a href="#GPT-2" class="headerlink" title="GPT-2"></a>GPT-2</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">A. Radford, et al., 2019. Language Models are Unsupervised Multitask Learners.</span><br><span class="line">B. McCann, et al., 2018. The Natural Language Decathlon: Multitask Learning as Question Answering.</span><br></pre></td></tr></table></figure><p>Language models can learn multiple NLP tasks <strong>without any explicit supervision</strong>. </p><ul><li>When conditioned on a document plus questions, the answers generated by GPT-2 reach 55 F1 on the CoQA dataset - matching or exceeding the performance of baseline systems without using the 127,000+ training examples.</li></ul><h4 id="Task-Conditioning"><a href="#Task-Conditioning" class="headerlink" title="Task Conditioning"></a>Task Conditioning</h4><p>A single-task model: estimating a conditional distribution $p (output | input)$<br>A multi-task model: conditioning on both input and task, i.e., modeling $p (output | input, task)$</p><ul><li>Task conditioning implemented at architectural level</li><li>Task conditioning implemented at algorithmic level</li><li>Specify task, input and output as sequence of symbols <ul><li>Machine translation: <code>(translate to french, english text, french text)</code></li><li>Reading comprehension: <code>(answer the question, document, question, answer)</code></li></ul></li></ul><h4 id="Training-Dataset"><a href="#Training-Dataset" class="headerlink" title="Training Dataset"></a>Training Dataset</h4><p><strong>Common Crawl</strong> results in significant data quality issues.<br>Scrape all <strong>outbound links from Reddit</strong>, which can be thought of as a heuristic indicator for whether other users found the link interesting, educational, or just funny.</p><h4 id="Input-Representation-1"><a href="#Input-Representation-1" class="headerlink" title="Input Representation"></a>Input Representation</h4><p><strong>Byte Pair Encoding (BPE)</strong>: Byte-level version of BPE. </p><h4 id="Experiments"><a href="#Experiments" class="headerlink" title="Experiments"></a>Experiments</h4><ul><li>Children’s Book Test (Cloze): Compute the probability of each choice in the sentence, and predict the one with the highest probability. </li><li>CoQA (Reading comprehension): Greedy decode from GPT-2 when conditioned on the document, the history of conversation (such as “<code>Why?</code>“), and a final token <code>A</code>. </li><li>Summarization: Add the text <code>TL;DR</code>. </li><li>Translation: Condition the language model on a context of example pairs of the formart <code>english sentence = french sentence</code> and then after the final prompt of <code>english sentence =</code>, sample from the model with greedy decoding. <ul><li>Do good at French-English translation, while bad at English-French translation. </li></ul></li></ul><h3 id="GPT-3"><a href="#GPT-3" class="headerlink" title="GPT-3"></a>GPT-3</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T. B. Brown, et al., 2020. Language Models are Few-Shot Learners.</span><br></pre></td></tr></table></figure><h4 id="In-Context-Learning"><a href="#In-Context-Learning" class="headerlink" title="In-Context Learning"></a>In-Context Learning</h4><ul><li>Fine-Tuning: Update the weights of LM by training on a supervised dataset specific to the desired task. </li><li>Few-Shot: No weights are updated; The LM is given <strong>a few demonstrations of the desired task</strong> at inference time as conditioning. </li><li>One-Shot: No weights are updated; The LM is given <strong>ONE demonstration</strong>. </li><li>Zero-Shot: No weights are updated; The LM is given <strong>a natural language description of the desired task</strong>. </li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;This blog briefly reviews the pre-training embeddings and models in NLP.&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="NLP" scheme="https://syuoni.github.io/tags/NLP/"/>
    
  </entry>
  
  <entry>
    <title>WSL 使用笔记</title>
    <link href="https://syuoni.github.io/posts/WSL-usage-notes/"/>
    <id>https://syuoni.github.io/posts/WSL-usage-notes/</id>
    <published>2021-01-14T07:24:58.000Z</published>
    <updated>2021-01-21T06:21:33.551Z</updated>
    
    <content type="html"><![CDATA[<p>这篇博客记录如何使用 WSL 在 Windows 上本地运行 Linux 服务。<br><a id="more"></a></p><h2 id="安装-WSL"><a href="#安装-WSL" class="headerlink" title="安装 WSL"></a>安装 WSL</h2><p>参考 <a href="https://www.jianshu.com/p/3e627ff45ccb" target="_blank" rel="noopener">Windows 安装和配置 WSL</a></p><h3 id="启用-适用于Linux的Windows子系统"><a href="#启用-适用于Linux的Windows子系统" class="headerlink" title="启用 适用于Linux的Windows子系统"></a>启用 <code>适用于Linux的Windows子系统</code></h3><p>首先在 Win10 搜索栏中搜索并打开 <code>启用或关闭Windows功能</code>，勾选 <code>适用于Linux的Windows子系统</code> 项。<br>只有开启这项设置才能正常安装 WSL。</p><h3 id="安装-WSL-1"><a href="#安装-WSL-1" class="headerlink" title="安装 WSL"></a>安装 WSL</h3><p>在微软应用商店搜索 Linux，可以看到一系列 Linux 发行版，根据自己需要选择适合自己的发行版（如 Ubuntu 18.04 LTS），下载。<br>下载完成后启动，等待安装完成，输入账户和密码，便得到一个 Linux 环境。</p><h3 id="WSL-文件位置"><a href="#WSL-文件位置" class="headerlink" title="WSL 文件位置"></a>WSL 文件位置</h3><p><code>C:\Users\&lt;user-name&gt;\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState\rootfs</code></p><h3 id="使用国内-Ubuntu-镜像"><a href="#使用国内-Ubuntu-镜像" class="headerlink" title="使用国内 Ubuntu 镜像"></a>使用国内 Ubuntu 镜像</h3><p>参考 <a href="https://mirrors.tuna.tsinghua.edu.cn/help/ubuntu/" target="_blank" rel="noopener">清华大学开源软件镜像站 - Ubuntu 镜像使用帮助</a>。</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;这篇博客记录如何使用 WSL 在 Windows 上本地运行 Linux 服务。&lt;br&gt;</summary>
    
    
    
    
    <category term="WSL" scheme="https://syuoni.github.io/tags/WSL/"/>
    
    <category term="Linux" scheme="https://syuoni.github.io/tags/Linux/"/>
    
  </entry>
  
  <entry>
    <title>Brat 标注工具使用笔记</title>
    <link href="https://syuoni.github.io/posts/NLP-annotation-with-brat/"/>
    <id>https://syuoni.github.io/posts/NLP-annotation-with-brat/</id>
    <published>2021-01-14T07:21:38.000Z</published>
    <updated>2021-11-18T06:59:10.206Z</updated>
    
    <content type="html"><![CDATA[<p>这篇博客记录如何使用 Brat 标注工具。<br>Brat 的服务必须置于 UNIX-like 系统，如果是 Windows，建议使用虚拟机或者 WSL。<br><a id="more"></a></p><h2 id="Brat-标注平台安装-（官网版本-Python2）"><a href="#Brat-标注平台安装-（官网版本-Python2）" class="headerlink" title="Brat 标注平台安装 （官网版本 / Python2）"></a>Brat 标注平台安装 （官网版本 / Python2）</h2><p>参考 <a href="http://brat.nlplab.org/installation.html" target="_blank" rel="noopener">Brat 官网教程 - Installation</a>。</p><p>在 <a href="http://brat.nlplab.org/" target="_blank" rel="noopener">Brat 官网</a> 下载 <code>brat-v1.3_Crunchy_Frog.tar.gz</code> 安装包，解压：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ tar xzf brat-v1.3_Crunchy_Frog.tar.gz</span><br></pre></td></tr></table></figure></p><p>进入解压后的目录进行安装：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">cd</span> brat-v1.3_Crunchy_Frog</span><br><span class="line">$ ./install.sh</span><br></pre></td></tr></table></figure></p><p>然后，运行服务：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ python2 standalone.py</span><br></pre></td></tr></table></figure></p><h2 id="Brat-标注平台安装-（Github版本-Python3）"><a href="#Brat-标注平台安装-（Github版本-Python3）" class="headerlink" title="Brat 标注平台安装 （Github版本 / Python3）"></a>Brat 标注平台安装 （Github版本 / Python3）</h2><p>Clone <a href="https://github.com/nlplab/brat" target="_blank" rel="noopener">Brat - Github</a> 仓库。<br>进入目录后进行安装：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">cd</span> brat-v1.3_Crunchy_Frog</span><br><span class="line">$ ./install.sh</span><br></pre></td></tr></table></figure></p><p>然后，运行服务：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ python3 standalone.py</span><br></pre></td></tr></table></figure></p><h2 id="Brat-标注平台配置"><a href="#Brat-标注平台配置" class="headerlink" title="Brat 标注平台配置"></a>Brat 标注平台配置</h2><p>参考 <a href="http://brat.nlplab.org/configuration.html" target="_blank" rel="noopener">Brat 官网教程 - Configuration</a>。</p><p>配置文件包括四个文件：</p><ul><li><code>annotation.conf</code>: 定义实体、关系、属性类型</li><li><code>visual.conf</code>: 定义标注结果的显示效果</li><li><code>tools.conf</code>: 定义 Normalization 等工具</li><li><code>kb_shortcuts.conf</code>: 定义快捷键</li></ul><p>数据文件放置在 <code>data</code> 目录下。</p><h3 id="Normalization-标注配置"><a href="#Normalization-标注配置" class="headerlink" title="Normalization 标注配置"></a>Normalization 标注配置</h3><p>参考 <a href="http://brat.nlplab.org/normalization.html" target="_blank" rel="noopener">Brat 官网教程 - Normalization</a>。</p><p>根据格式要求准备好 Brat Normalization DB 文件，生成数据库：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ python tools/norm_db_init.py &lt;DBNAME&gt;.txt</span><br></pre></td></tr></table></figure><br>可以在 <code>work</code> 目录下查看生成的名为 <code>&lt;DBNAME&gt;</code> 数据库文件。</p><p>修改配置文件 <code>tools.conf</code>，在 <code>[normalization]</code> 下添加数据库信息：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DBNAME     &lt;URL&gt;:HOMEURL, &lt;URLBASE&gt;:ENTRYURL</span><br></pre></td></tr></table></figure></p><p>修改配置文件 <code>annotation.conf</code>，在 <code>[entities]</code> 定义实体时指明对应的标准化数据库，如：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ORG &lt;NORM&gt;:&lt;DBNAME&gt;</span><br><span class="line">LOC &lt;NORM&gt;:&lt;DBNAME&gt;</span><br><span class="line">MISC &lt;NORM&gt;:&lt;DBNAME&gt;</span><br></pre></td></tr></table></figure></p><h3 id="安装-SimString"><a href="#安装-SimString" class="headerlink" title="安装 SimString"></a>安装 SimString</h3><p><code>SimString</code> 用于 normalization 标注时关键词匹配，仅测试通 Python2 版本。<br>参考 <a href="http://chokkan.org/software/simstring/" target="_blank" rel="noopener">SimString 官网</a>。</p><p>在 <a href="http://chokkan.org/software/simstring/" target="_blank" rel="noopener">SimString 官网</a> 下载源码包 <code>simstring-1.0.tar.gz</code>，解压。</p><p>如系统没有 <code>gcc</code> / <code>g++</code> / <code>python-dev</code> 包，则需要安装：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ sudo apt install gcc</span><br><span class="line">$ sudo apt install g++</span><br><span class="line">$ sudo apt install python-dev</span><br></pre></td></tr></table></figure></p><p>进入解压后的目录，在 <code>include/simstring/memory_mapped_file_posix.h</code> 添加一行：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br></pre></td></tr></table></figure></p><p>进行编译安装：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ ./configure</span><br><span class="line">$ make</span><br><span class="line"><span class="comment"># To install the SimString header files</span></span><br><span class="line">$ make install</span><br></pre></td></tr></table></figure></p><p>封装成 Python2 模块<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$ ./configure </span><br><span class="line">$ <span class="built_in">cd</span> swig/python </span><br><span class="line">$ ./prepare.sh </span><br><span class="line">$ python setup.py build_ext </span><br><span class="line">$ python setup.py install</span><br></pre></td></tr></table></figure></p><p>然后，可在 Python2 中调用 <code>simstring</code> 包。</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;这篇博客记录如何使用 Brat 标注工具。&lt;br&gt;Brat 的服务必须置于 UNIX-like 系统，如果是 Windows，建议使用虚拟机或者 WSL。&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="NLP" scheme="https://syuoni.github.io/tags/NLP/"/>
    
  </entry>
  
  <entry>
    <title>LeetCode 笔记</title>
    <link href="https://syuoni.github.io/posts/leetcode-notes/"/>
    <id>https://syuoni.github.io/posts/leetcode-notes/</id>
    <published>2021-01-14T05:48:20.240Z</published>
    <updated>2019-12-18T03:37:48.000Z</updated>
    
    <content type="html"><![CDATA[<p>这是我 2019 年秋招过程中刷 LeetCode 做的笔记。<br><a id="more"></a></p><h2 id="双指针法"><a href="#双指针法" class="headerlink" title="双指针法"></a>双指针法</h2><p>适用于这样一种情形：需要确定一个<strong>范围</strong>作为解，使得<strong>目标函数</strong>取值最大。<br>用左右两端两个<strong>指针</strong>代表该范围，则：<br>如果在任意时刻，一定可以有至少一端，只要调整这一段就会使得目标函数取值变小；且如果只调整这一端的话，目标函数永远不会超过当前时刻的目标函数取值。那么，如果存在优于当前情况的解，迟早要调整另一端。所以，调整另一端一定不会错过最优解。</p><h2 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h2><p>快速排序<br>归并排序</p><h2 id="递归和回溯"><a href="#递归和回溯" class="headerlink" title="递归和回溯"></a>递归和回溯</h2><p>遍历二叉树</p><h2 id="动态规划"><a href="#动态规划" class="headerlink" title="动态规划"></a>动态规划</h2><h2 id="举行重叠"><a href="#举行重叠" class="headerlink" title="举行重叠"></a>举行重叠</h2><p>判断角点</p><h2 id="拓扑排序"><a href="#拓扑排序" class="headerlink" title="拓扑排序"></a>拓扑排序</h2><p><a href="https://leetcode-cn.com/problems/course-schedule/" target="_blank" rel="noopener">LeetCode-207. 课程表</a><br>参考：<a href="https://www.jianshu.com/p/3347f54a3187" target="_blank" rel="noopener">https://www.jianshu.com/p/3347f54a3187</a></p><p>如果一个有向图为有向无环图（Directed Acyclic Graph, DAG），就能得到对应该图的拓扑排序，满足这样的条件：对于图中任意两个节点 u 和 v，若从 u 到 v 存在一条边，则拓扑排序中 u 一定排在 v 前面。</p><p>对于一个有向图，找到其一个拓扑排序的算法：</p><ol><li>初始化一个数组 <code>in_degree</code> 用于保存每个结点的入度；</li><li>对图中每一个结点的子结点，使其入度加 1；</li><li>选取入度为 0 的结点加入输出（拓扑排序）；若无法找到入度为 0 的结点，则说明原有向图存在环，不存在对应的拓扑排序；</li><li>对输出结点，遍历其子结点，每个子结点的入度减 1；</li><li>重复步骤 3-4，直至遍历完所有结点。</li></ol><h2 id="其他-Tips"><a href="#其他-Tips" class="headerlink" title="其他 Tips"></a>其他 Tips</h2><ul><li>对数组进行操作时，试试排序后能否简化思路。</li><li>当考虑用 Hashmap 来判别对象的唯一性时，尝试采用其他 Coding 方案，比如当 Hashmap 的 Keys 在一个固定范围内时（如小写字母），就可以采用固定长度的数组来实现 Coding。</li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;这是我 2019 年秋招过程中刷 LeetCode 做的笔记。&lt;br&gt;</summary>
    
    
    
    <category term="算法" scheme="https://syuoni.github.io/categories/%E7%AE%97%E6%B3%95/"/>
    
    
    <category term="LeetCode" scheme="https://syuoni.github.io/tags/LeetCode/"/>
    
    <category term="Python" scheme="https://syuoni.github.io/tags/Python/"/>
    
    <category term="C++" scheme="https://syuoni.github.io/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>使用 Hexo 搭建博客并部署到 Github</title>
    <link href="https://syuoni.github.io/posts/blog-with-hexo-github/"/>
    <id>https://syuoni.github.io/posts/blog-with-hexo-github/</id>
    <published>2021-01-14T05:48:20.160Z</published>
    <updated>2021-01-14T07:20:26.533Z</updated>
    
    <content type="html"><![CDATA[<p>一份使用 Hexo 搭建博客并部署到 Github 的简要指南。<br>网上不少博客使用的 NexT 主题还是 v5.1.x 的版本（<a href="http://theme-next.iissnan.com/" target="_blank" rel="noopener">官网</a>，<a href="https://github.com/iissnan/hexo-theme-next" target="_blank" rel="noopener">Github</a>），但事实上这个版本已经不再维护。最新版本已经更新到 v7.6.0 （<a href="https://pisces.theme-next.org/" target="_blank" rel="noopener">官网</a>，<a href="https://github.com/theme-next/hexo-theme-next" target="_blank" rel="noopener">Github</a>）。</p><p>我在使用 v5.1.x 版本时就遇到了 Bug，菜单栏和侧边栏的链接解析一直是错误的，网上教程很多是删除主题配置文件对应位置的空格，但这仅能修复菜单栏的问题，侧边栏的问题无法修复。最好的方案是把 NexT 更新到最新版本。<br>这里有一份 NexT 官网给的指南：<a href="https://github.com/theme-next/hexo-theme-next/blob/master/docs/UPDATE-FROM-5.1.X.md" target="_blank" rel="noopener">Update from NexT v5.1.x</a><br><a id="more"></a></p><h2 id="下载安装和环境配置"><a href="#下载安装和环境配置" class="headerlink" title="下载安装和环境配置"></a>下载安装和环境配置</h2><p>参考 <a href="https://hexo.io/zh-cn/docs/index.html" target="_blank" rel="noopener">Hexo 文档</a></p><h3 id="安装-Git-和-Node-js"><a href="#安装-Git-和-Node-js" class="headerlink" title="安装 Git 和 Node.js"></a>安装 Git 和 Node.js</h3><ul><li>安装 <a href="https://git-scm.com/" target="_blank" rel="noopener">Git</a></li><li>安装 <a href="https://nodejs.org/en/" target="_blank" rel="noopener">Node.js</a></li></ul><h3 id="安装-Hexo"><a href="#安装-Hexo" class="headerlink" title="安装 Hexo"></a>安装 Hexo</h3><p>使用 <code>npm</code> 命令安装<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install -g hexo-cli</span><br></pre></td></tr></table></figure><br>安装完毕后，使用 <code>npx hexo &lt;command&gt;</code> 执行 Hexo 命令。</p><h3 id="新建博客的本地目录"><a href="#新建博客的本地目录" class="headerlink" title="新建博客的本地目录"></a>新建博客的本地目录</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo init &lt;blog-folder&gt;</span><br><span class="line">$ <span class="built_in">cd</span> &lt;blog-folder&gt;</span><br><span class="line">$ npm install</span><br></pre></td></tr></table></figure><h3 id="安装并启用-NexT-主题"><a href="#安装并启用-NexT-主题" class="headerlink" title="安装并启用 NexT 主题"></a>安装并启用 NexT 主题</h3><p>进入博客的本地目录后<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git clone https:&#x2F;&#x2F;github.com&#x2F;theme-next&#x2F;hexo-theme-next themes&#x2F;next</span><br></pre></td></tr></table></figure><br>注意，不要使用这个不再维护的项目地址：<a href="https://github.com/iissnan/hexo-theme-next" target="_blank" rel="noopener">https://github.com/iissnan/hexo-theme-next</a></p><p>然后，在站点配置文件（博客本地目录下的 <code>_config.yml</code>）中修改<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">theme: next</span><br></pre></td></tr></table></figure></p><h2 id="使用-VS-Code-作为-Markdown-编辑器"><a href="#使用-VS-Code-作为-Markdown-编辑器" class="headerlink" title="使用 VS Code 作为 Markdown 编辑器"></a>使用 VS Code 作为 Markdown 编辑器</h2><p>安装 <code>Markdown Preview Enhanced</code> 插件即可。</p><h2 id="Hexo-的基本使用"><a href="#Hexo-的基本使用" class="headerlink" title="Hexo 的基本使用"></a>Hexo 的基本使用</h2><h3 id="新建页面"><a href="#新建页面" class="headerlink" title="新建页面"></a>新建页面</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo new <span class="string">"My New Post"</span></span><br></pre></td></tr></table></figure><p>More info: <a href="https://hexo.io/docs/writing.html" target="_blank" rel="noopener">Writing</a></p><h3 id="运行服务"><a href="#运行服务" class="headerlink" title="运行服务"></a>运行服务</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo server</span><br></pre></td></tr></table></figure><p>More info: <a href="https://hexo.io/docs/server.html" target="_blank" rel="noopener">Server</a></p><h3 id="根据-Markdown-文件生成静态-html-文件"><a href="#根据-Markdown-文件生成静态-html-文件" class="headerlink" title="根据 Markdown 文件生成静态 html 文件"></a>根据 Markdown 文件生成静态 html 文件</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo generate</span><br></pre></td></tr></table></figure><p>More info: <a href="https://hexo.io/docs/generating.html" target="_blank" rel="noopener">Generating</a></p><h3 id="部署"><a href="#部署" class="headerlink" title="部署"></a>部署</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo deploy</span><br></pre></td></tr></table></figure><p>More info: <a href="https://hexo.io/docs/one-command-deployment.html" target="_blank" rel="noopener">Deployment</a></p><p>一般，在部署前需要重新生成静态页面，即需要运行<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo clean</span><br><span class="line">$ npx hexo generate</span><br><span class="line">$ npx hexo deploy</span><br></pre></td></tr></table></figure></p><h2 id="部署到-Github"><a href="#部署到-Github" class="headerlink" title="部署到 Github"></a>部署到 Github</h2><p>参考这篇博客：<a href="https://www.jianshu.com/p/f9b213097c42" target="_blank" rel="noopener">使用Github搭建Hexo技术博客托管在GitHub Pages上</a></p><h3 id="创建-Github-Pages-并-SHH-授权"><a href="#创建-Github-Pages-并-SHH-授权" class="headerlink" title="创建 Github Pages 并 SHH 授权"></a>创建 Github Pages 并 SHH 授权</h3><p>在 Github 上创建以 <code>&lt;username&gt;.github.io</code> 为名的 Repo。<br>创建 SHH 密钥，在 Git Bash 中输入<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ ssh-keygen -t rsa -C <span class="string">"&lt;email-address&gt;"</span></span><br></pre></td></tr></table></figure><br>然后，查看目录 <code>C:/Users/&lt;username&gt;/.ssh</code> 下是否有两个文件：私钥文件 <code>id_rsa</code> 和公钥文件 <code>id_rsa.pub</code>。<br>打开 <code>id_rsa.pub</code> 并复制其内容，访问 <a href="https://github.com/settings/ssh" target="_blank" rel="noopener">https://github.com/settings/ssh</a> 新建密钥后粘贴 <code>id_rsa.pub</code> 中的内容。</p><h3 id="安装部署相关的-Hexo-插件"><a href="#安装部署相关的-Hexo-插件" class="headerlink" title="安装部署相关的 Hexo 插件"></a>安装部署相关的 Hexo 插件</h3><p>在本地博客目录下<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ npm install hexo -server --save</span><br><span class="line">$ npm install hexo-deployer-git --save</span><br></pre></td></tr></table></figure><br>然后，编辑站点配置文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"># Deployment</span><br><span class="line">## Docs: https:&#x2F;&#x2F;hexo.io&#x2F;docs&#x2F;deployment.html</span><br><span class="line">deploy:</span><br><span class="line">  type: git</span><br><span class="line">  repo: </span><br><span class="line">    github: git@github.com:&lt;username&gt;&#x2F;&lt;username&gt;.github.io.git,master</span><br><span class="line">    coding: git@git.coding.net:&lt;username&gt;&#x2F;&lt;username&gt;.git,master</span><br></pre></td></tr></table></figure><br>注意：密钥文件在原来的目录 <code>C:/Users/&lt;username&gt;/.ssh</code> 下时，系统会自动识别。</p><h3 id="部署-1"><a href="#部署-1" class="headerlink" title="部署"></a>部署</h3><p>在检查本地站点无误后，运行<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo deploy</span><br></pre></td></tr></table></figure></p><h2 id="站点配置"><a href="#站点配置" class="headerlink" title="站点配置"></a>站点配置</h2><h3 id="添加菜单"><a href="#添加菜单" class="headerlink" title="添加菜单"></a>添加菜单</h3><h4 id="创建-About-菜单"><a href="#创建-About-菜单" class="headerlink" title="创建 About 菜单"></a>创建 About 菜单</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo new page about</span><br></pre></td></tr></table></figure><p>生成 <code>source/about</code> 目录，修改其中 <code>index.md</code> 文件内容即可。</p><h4 id="创建-Categories-菜单"><a href="#创建-Categories-菜单" class="headerlink" title="创建 Categories 菜单"></a>创建 Categories 菜单</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo new page categories</span><br></pre></td></tr></table></figure><p>生成 <code>source/categories</code> 目录，修改其中 <code>index.md</code> 文件标题：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">title: 分类</span><br><span class="line">date: xxxx-xx-xx xx:xx:xx</span><br><span class="line">type: &quot;categories&quot;</span><br></pre></td></tr></table></figure></p><h4 id="创建-Tags-菜单"><a href="#创建-Tags-菜单" class="headerlink" title="创建 Tags 菜单"></a>创建 Tags 菜单</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npx hexo new page tags</span><br></pre></td></tr></table></figure><p>生成 <code>source/tags</code> 目录，修改其中 <code>index.md</code> 文件标题：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">title: 标签</span><br><span class="line">date: xxxx-xx-xx xx:xx:xx</span><br><span class="line">type: &quot;tags&quot;</span><br></pre></td></tr></table></figure></p><h4 id="启用菜单"><a href="#启用菜单" class="headerlink" title="启用菜单"></a>启用菜单</h4><p>在主题配置文件（<code>themes/next</code> 下的 <code>_config.yml</code>）启用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">menu:</span><br><span class="line">  home: &#x2F; || home</span><br><span class="line">  about: &#x2F;about&#x2F; || user</span><br><span class="line">  tags: &#x2F;tags&#x2F; || tags</span><br><span class="line">  categories: &#x2F;categories&#x2F; || th</span><br><span class="line">  archives: &#x2F;archives&#x2F; || archive</span><br></pre></td></tr></table></figure></p><h3 id="添加站内搜索功能"><a href="#添加站内搜索功能" class="headerlink" title="添加站内搜索功能"></a>添加站内搜索功能</h3><p>首先，在本地博客目录下安装搜索插件包<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ npm install hexo-generator-search --save</span><br><span class="line">$ npm install hexo-generator-searchdb --save</span><br></pre></td></tr></table></figure></p><p>然后，打开站点配置文件，增加以下内容<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">search:</span><br><span class="line">  path: search.xml</span><br><span class="line">  field: post</span><br><span class="line">  format: html</span><br><span class="line">  limit: 10000</span><br></pre></td></tr></table></figure></p><p>最后，打开主题配置文件，启用搜索功能<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">local_search:</span><br><span class="line">  enable: true</span><br></pre></td></tr></table></figure></p><h3 id="添加动态背景"><a href="#添加动态背景" class="headerlink" title="添加动态背景"></a>添加动态背景</h3><p>以 <code>canvas-nest</code> 为例，在本地博客目录下进入 <code>themes/next</code> 目录后安装至其下的 <code>source/lib</code> 目录<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">cd</span> themes/next</span><br><span class="line">$ git <span class="built_in">clone</span> https://github.com/theme-next/theme-next-canvas-nest <span class="built_in">source</span>/lib/canvas-nest</span><br></pre></td></tr></table></figure></p><p>然后，修改主题配置文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"># Canvas-nest</span><br><span class="line"># Dependencies: https:&#x2F;&#x2F;github.com&#x2F;theme-next&#x2F;theme-next-canvas-nest</span><br><span class="line"># For more information: https:&#x2F;&#x2F;github.com&#x2F;hustcc&#x2F;canvas-nest.js</span><br><span class="line">canvas_nest:</span><br><span class="line">  enable: true</span><br><span class="line">  onmobile: true # Display on mobile or not</span><br><span class="line">  color: &quot;0,0,0&quot; # RGB values, use &#96;,&#96; to separate</span><br><span class="line">  opacity: 0.5 # The opacity of line: 0~1</span><br><span class="line">  zIndex: -1 # z-index property of the background</span><br><span class="line">  count: 99 # The number of lines</span><br></pre></td></tr></table></figure></p><h3 id="添加评论系统"><a href="#添加评论系统" class="headerlink" title="添加评论系统"></a>添加评论系统</h3><p>参考 NexT 官网的说明：<a href="https://pisces.theme-next.org/docs/third-party-services/comments.html" target="_blank" rel="noopener">Comment Systems</a><br>以 Valine 为例，先去 <a href="https://www.leancloud.cn/" target="_blank" rel="noopener">LeanCloud</a> 注册帐号并创建项目，获得 <code>App ID</code> 和 <code>App Key</code>，然后修改主题配置文件 <code>valine</code> 下的内容。</p><h3 id="启用-Latex-公式渲染"><a href="#启用-Latex-公式渲染" class="headerlink" title="启用 Latex 公式渲染"></a>启用 Latex 公式渲染</h3><p>参考 NexT 官网的说明：<a href="https://pisces.theme-next.org/docs/third-party-services/math-equations.html" target="_blank" rel="noopener">Math Equations</a><br>首先，在本地博客目录下卸载原来的 <code>hexo-renderer-marked</code> 渲染工具，然后安装新的 <code>hexo-renderer-kramed</code> 渲染工具<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ npm uninstall hexo-renderer-marked</span><br><span class="line">$ npm install hexo-renderer-kramed</span><br></pre></td></tr></table></figure></p><p>然后，修改主题配置文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"># Math Formulas Render Support</span><br><span class="line">math:</span><br><span class="line">  # Default (true) will load mathjax &#x2F; katex script on demand.</span><br><span class="line">  # That is it only render those page which has &#96;mathjax: true&#96; in Front-matter.</span><br><span class="line">  # If you set it to false, it will load mathjax &#x2F; katex srcipt EVERY PAGE.</span><br><span class="line">  per_page: true</span><br><span class="line"></span><br><span class="line">  # hexo-renderer-pandoc (or hexo-renderer-kramed) required for full MathJax support.</span><br><span class="line">  mathjax:</span><br><span class="line">    enable: true</span><br><span class="line">    # See: https:&#x2F;&#x2F;mhchem.github.io&#x2F;MathJax-mhchem&#x2F;</span><br><span class="line">    mhchem: false</span><br><span class="line"></span><br><span class="line">  # hexo-renderer-markdown-it-plus (or hexo-renderer-markdown-it with markdown-it-katex plugin) required for full Katex support.</span><br><span class="line">  katex:</span><br><span class="line">    enable: false</span><br><span class="line">    # See: https:&#x2F;&#x2F;github.com&#x2F;KaTeX&#x2F;KaTeX&#x2F;tree&#x2F;master&#x2F;contrib&#x2F;copy-tex</span><br><span class="line">    copy_tex: false</span><br></pre></td></tr></table></figure></p><p>这里的 <code>per_page</code> 设置为 <code>true</code> 时，需要在（需要公式渲染的）页面标题处设置 <code>mathjax: true</code> 才会开启公式渲染，如<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">---</span><br><span class="line">title: A Post with Math Equations</span><br><span class="line">mathjax: true</span><br><span class="line">---</span><br></pre></td></tr></table></figure></p><h4 id="行内公式渲染问题"><a href="#行内公式渲染问题" class="headerlink" title="行内公式渲染问题"></a>行内公式渲染问题</h4><p>在行内公式中，下划线（<code>_</code>）会被解析成 Markdown 语法中斜体字体的开始标记，这种时候可以使用 <code>\_</code>。更好的处理方案是，到博客根目录下，找到 <code>node_modules/kramed/lib/rules/inline.js</code>，把第 11 行的 <code>escape</code> 变量的值做相应的修改：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; escape: &#x2F;^\\([\\&#96;*&#123;&#125;\[\]()#$+\-.!_&gt;])&#x2F;,</span><br><span class="line">escape: &#x2F;^\\([&#96;*\[\]()#$+\-.!_&gt;])&#x2F;,</span><br></pre></td></tr></table></figure><br>再把第 20 行的 <code>em</code> 变量的值也做相应的修改：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; em: &#x2F;^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)&#x2F;,</span><br><span class="line">em: &#x2F;^\*((?:\*\*|[\s\S])+?)\*(?!\*)&#x2F;,</span><br></pre></td></tr></table></figure><br>然后重新渲染所有页面即可。</p><h2 id="博客项目迁移"><a href="#博客项目迁移" class="headerlink" title="博客项目迁移"></a>博客项目迁移</h2><p>参考这篇博客：<a href="https://blog.csdn.net/eternity1118_/article/details/71194395?ref=myread" target="_blank" rel="noopener">hexo：更换电脑，如何继续写博客</a></p><h3 id="安装-Git-和-Node-js-1"><a href="#安装-Git-和-Node-js-1" class="headerlink" title="安装 Git 和 Node.js"></a>安装 Git 和 Node.js</h3><h3 id="安装-Hexo-1"><a href="#安装-Hexo-1" class="headerlink" title="安装 Hexo"></a>安装 Hexo</h3><h3 id="拷贝以下几个文件和目录"><a href="#拷贝以下几个文件和目录" class="headerlink" title="拷贝以下几个文件和目录"></a>拷贝以下几个文件和目录</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">_config.yml</span><br><span class="line">package.json</span><br><span class="line">scaffolds&#x2F;</span><br><span class="line">source&#x2F;</span><br><span class="line">themes&#x2F;</span><br></pre></td></tr></table></figure><h3 id="安装模块"><a href="#安装模块" class="headerlink" title="安装模块"></a>安装模块</h3><p>进入博客的本地目录后<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ npm install</span><br><span class="line">$ npm install hexo-deployer-git --save</span><br><span class="line">$ npm install hexo-generator-feed --save</span><br><span class="line">$ npm install hexo-generator-sitemap --save</span><br></pre></td></tr></table></figure></p>]]></content>
    
    
    <summary type="html">&lt;p&gt;一份使用 Hexo 搭建博客并部署到 Github 的简要指南。&lt;br&gt;网上不少博客使用的 NexT 主题还是 v5.1.x 的版本（&lt;a href=&quot;http://theme-next.iissnan.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;官网&lt;/a&gt;，&lt;a href=&quot;https://github.com/iissnan/hexo-theme-next&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Github&lt;/a&gt;），但事实上这个版本已经不再维护。最新版本已经更新到 v7.6.0 （&lt;a href=&quot;https://pisces.theme-next.org/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;官网&lt;/a&gt;，&lt;a href=&quot;https://github.com/theme-next/hexo-theme-next&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Github&lt;/a&gt;）。&lt;/p&gt;
&lt;p&gt;我在使用 v5.1.x 版本时就遇到了 Bug，菜单栏和侧边栏的链接解析一直是错误的，网上教程很多是删除主题配置文件对应位置的空格，但这仅能修复菜单栏的问题，侧边栏的问题无法修复。最好的方案是把 NexT 更新到最新版本。&lt;br&gt;这里有一份 NexT 官网给的指南：&lt;a href=&quot;https://github.com/theme-next/hexo-theme-next/blob/master/docs/UPDATE-FROM-5.1.X.md&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Update from NexT v5.1.x&lt;/a&gt;&lt;br&gt;</summary>
    
    
    
    <category term="网站" scheme="https://syuoni.github.io/categories/%E7%BD%91%E7%AB%99/"/>
    
    
    <category term="博客" scheme="https://syuoni.github.io/tags/%E5%8D%9A%E5%AE%A2/"/>
    
  </entry>
  
  <entry>
    <title>Linux 常用 bash 命令</title>
    <link href="https://syuoni.github.io/posts/linux-bash-commands-notes/"/>
    <id>https://syuoni.github.io/posts/linux-bash-commands-notes/</id>
    <published>2020-06-04T10:10:32.000Z</published>
    <updated>2021-12-03T04:15:09.619Z</updated>
    
    <content type="html"><![CDATA[<p>Linux 常用 bash 命令。<br><a id="more"></a></p><p>在 <code>root</code> 权限下新建用户<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ useradd -d /home/&lt;user-name&gt; -m &lt;user-name&gt;</span><br><span class="line">$ usermod -s /bin/bash &lt;user-name&gt;</span><br><span class="line">$ passwd &lt;user-name&gt;</span><br></pre></td></tr></table></figure></p><p>在 <code>root</code> 权限下修改文件夹权限<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ chmod 777 &lt;dir-name&gt;</span><br></pre></td></tr></table></figure></p><p>复制和移动文件</p><ul><li><p>本地复制和移动单个文件</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ cp &lt;src-file-name&gt; &lt;trg-dir-name&gt;</span><br><span class="line">$ mv &lt;src-file-name&gt; &lt;trg-dir-name&gt;</span><br></pre></td></tr></table></figure></li><li><p>本地复制和移动文件夹</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ cp -r &lt;src-dir-name&gt; &lt;trg-dir-name&gt;</span><br><span class="line">$ mv -r &lt;src-dir-name&gt; &lt;trg-dir-name&gt;</span><br></pre></td></tr></table></figure></li><li><p>远程复制文件</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ scp &lt;user-name&gt;@&lt;ip&gt;:&lt;src-file-name&gt; &lt;trg-dir-name&gt;</span><br></pre></td></tr></table></figure></li><li><p>远程复制文件夹</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ scp -r &lt;user-name&gt;@&lt;ip&gt;:&lt;src-dir-name&gt; &lt;trg-dir-name&gt;</span><br></pre></td></tr></table></figure></li></ul><p>解压 <code>tar.gz</code> 文件<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ tar -zxvf &lt;file-name&gt;.tar.gz -C &lt;trg-dir-name&gt;</span><br></pre></td></tr></table></figure></p><p>发布 <code>pip</code> 包（<code>wheel</code> 文件）<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ python setup.py bdist_wheel</span><br></pre></td></tr></table></figure></p><p>离线安装 <code>pip</code> 包（<code>wheel</code> 或 <code>tar.gz</code> 文件，参考：<a href="https://docs.conda.io/projects/conda-build/en/latest/user-guide/wheel-files.html）" target="_blank" rel="noopener">https://docs.conda.io/projects/conda-build/en/latest/user-guide/wheel-files.html）</a><br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ pip install &lt;package-name&gt;.&lt;whl/tar.gz&gt; --no-deps</span><br></pre></td></tr></table></figure></p><p>离线安装 <code>conda</code> 包（<code>conda</code> 或 <code>tar.bz2</code> 文件）<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ conda install &lt;package-name&gt;.&lt;conda/tar.bz2&gt; --offline</span><br></pre></td></tr></table></figure></p><p>离线安装 <code>deb</code> 软件<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ sudo apt install ./&lt;file-name&gt;.deb</span><br></pre></td></tr></table></figure></p><p>离线安装 <code>VS Code</code> 的 Extension<br>先从 <a href="https://marketplace.visualstudio.com/vscode" target="_blank" rel="noopener">https://marketplace.visualstudio.com/vscode</a> 下载 <code>vsix</code> 文件<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ code --install-extension &lt;file-name&gt;.vsix</span><br></pre></td></tr></table></figure></p><p>查看 CPU 和内存状态<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ top -u &lt;user-name&gt;</span><br></pre></td></tr></table></figure></p><p>查看 Nvidia 显卡状态<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ nvidia-smi</span><br><span class="line">$ watch -n 1 -d nvidia-smi</span><br><span class="line">$ fuser -v /dev/nvidia*</span><br></pre></td></tr></table></figure></p><p>虚拟命令行会话</p><ul><li>新建会话<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ screen -S &lt;session-name&gt;</span><br></pre></td></tr></table></figure></li><li>暂时离开会话（Detach）：<code>Ctrl</code> + <code>A</code> + <code>D</code></li><li>显示当前所有存在的会话<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ screen -ls</span><br></pre></td></tr></table></figure></li><li>重新连接会话（Attach）<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ screen -r &lt;session-name&gt;</span><br></pre></td></tr></table></figure></li></ul><p>杀死进程<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">kill</span> &lt;process-id&gt;</span><br></pre></td></tr></table></figure></p><p>查看和改变进程被 OOM killer 杀死的优先度<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ sudo cat /proc/&lt;process-id&gt;/oom_score</span><br><span class="line">$ sudo <span class="built_in">echo</span> -1000 &gt; /proc/&lt;process-id&gt;/oom_score_adj</span><br></pre></td></tr></table></figure></p><p>软链接</p><ul><li>创建软链接：一个名为 <code>real</code> 的文件（夹）链接会出现在 <code>/path/to/link</code> 路径下，可以通过 <code>/path/to/link/real</code> 访问<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ ln -s /path/to/real /path/to/link</span><br></pre></td></tr></table></figure></li><li>删除软链接：只会删除链接，不会影响原 <code>/path/to/real</code><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ rm /path/to/link/real</span><br></pre></td></tr></table></figure></li></ul><p>使用代理</p><ul><li><p>服务器代理</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">export</span> http_proxy=<span class="string">"http://&lt;user-name&gt;:&lt;password&gt;@&lt;proxyhost&gt;:&lt;port&gt;"</span></span><br><span class="line">$ <span class="built_in">export</span> https_proxy=<span class="string">"https://&lt;user-name&gt;:&lt;password&gt;@&lt;proxyhost&gt;:&lt;port&gt;"</span></span><br></pre></td></tr></table></figure></li><li><p>本地代理</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">export</span> http_proxy=<span class="string">"http://127.0.0.1:&lt;port&gt;"</span></span><br><span class="line">$ <span class="built_in">export</span> https_proxy=<span class="string">"https://127.0.0.1:&lt;port&gt;"</span></span><br></pre></td></tr></table></figure></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;Linux 常用 bash 命令。&lt;br&gt;</summary>
    
    
    
    <category term="语言" scheme="https://syuoni.github.io/categories/%E8%AF%AD%E8%A8%80/"/>
    
    
    <category term="linux" scheme="https://syuoni.github.io/tags/linux/"/>
    
    <category term="bash" scheme="https://syuoni.github.io/tags/bash/"/>
    
  </entry>
  
  <entry>
    <title>Attention is All You Need</title>
    <link href="https://syuoni.github.io/posts/Attention-is-All-You-Need/"/>
    <id>https://syuoni.github.io/posts/Attention-is-All-You-Need/</id>
    <published>2020-06-03T06:36:09.000Z</published>
    <updated>2020-06-06T00:58:10.000Z</updated>
    
    <content type="html"><![CDATA[<p>Notes on Attention is All You Need, i.e., the Transformer.<br><a id="more"></a></p><h2 id="Encoder-Decoder-Stacks"><a href="#Encoder-Decoder-Stacks" class="headerlink" title="Encoder-Decoder Stacks"></a>Encoder-Decoder Stacks</h2><p><img src="/images/Transformer.jpg" alt="The Transformer"></p><h3 id="Encoder"><a href="#Encoder" class="headerlink" title="Encoder"></a>Encoder</h3><p>A stack of $N=6$ identical layers; each layer has two sub-layers:</p><ul><li>A multi-head self-attention layer</li><li>A simple, position-wise fully-connected feed-forward network (FC-FFN)</li></ul><h3 id="Decoder"><a href="#Decoder" class="headerlink" title="Decoder"></a>Decoder</h3><p>A stack of $N=6$ identical layers; each layer has three sub-layers:</p><ul><li>A multi-head self-attention layer<ul><li>Mask out subsequent positions</li></ul></li><li>A multi-head encoder-decoder attention layer</li><li>A simple, position-wise fully connected feed-forward network (FC-FFN)</li></ul><h3 id="Residual-Connection-and-Layer-Norm"><a href="#Residual-Connection-and-Layer-Norm" class="headerlink" title="Residual Connection and Layer Norm"></a>Residual Connection and Layer Norm</h3><p>Empoly a <em>residual connection</em> around each of the sub-layers, followed by <em>layer normalization</em>. That is, the final output of each sub-layer is $\mathrm{LayerNorm} (x + \mathrm{SubLayer}(x))$, where $\mathrm{SubLayer}(x)$ is the output of a multi-head or FC-FFN layer. </p><h2 id="Attention"><a href="#Attention" class="headerlink" title="Attention"></a>Attention</h2><p>Scaled dot-product attention, multi-head attention, self-attention.<br>See <a href="../Attention-in-NLP">Attention in NLP</a>.</p><h2 id="Position-Wise-Fully-Connected-Feed-Forward-Network"><a href="#Position-Wise-Fully-Connected-Feed-Forward-Network" class="headerlink" title="Position-Wise Fully-Connected Feed-Forward Network"></a>Position-Wise Fully-Connected Feed-Forward Network</h2><p>Apply a FC-FFN to each position separately and identically: </p><script type="math/tex; mode=display">\mathrm{FFN}(x) = \mathrm{ReLU}\left( x W_1 + b_1 \right) W_2 + b_2</script><p>where $x \in \Bbb{R}^{d_{model}}$ is the vector on a certain position, $W_1 \in \Bbb{R}^{d_{model} \times d_{ff}}$ and $W_2 \in \Bbb{R}^{d_{ff} \times d_{model}}$ are trainable parameter matrices. </p><h2 id="Embeddings-and-Softmax"><a href="#Embeddings-and-Softmax" class="headerlink" title="Embeddings and Softmax"></a>Embeddings and Softmax</h2><p>Use learned embeddings to convert the source tokens and target tokens to vectors of dimension $d_{model}$.<br>Use learned transformation and softmax function to convert the decoder output to predicted next-token probabilities. </p><h2 id="Positional-Encodings"><a href="#Positional-Encodings" class="headerlink" title="Positional Encodings"></a>Positional Encodings</h2><p>To make use of the order of sequence, add <em>positional encodings</em> to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimensions $d_{model}$ as the embeddings, so that they can be summed. </p><script type="math/tex; mode=display">\begin{aligned}\mathrm{PE}(pos, 2i) &= \sin \left( \frac{pos}{10000^{2i/d_{model}}} \right) \\\mathrm{PE}(pos, 2i+1) &= \cos \left( \frac{pos}{10000^{2i/d_{model}}} \right)\end{aligned}</script><p>where $pos$ is the position and $i$ is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from $2\pi$ to $10000 \cdot 2\pi$.<br>This positional encoding would allow the model to learn to attend by <em>relative positions</em>, since for any fixed offset $k$, $\mathrm{PE}_{pos+k}$ can be represented as a linear function of $\mathrm{PE}_{pos}$. </p><script type="math/tex; mode=display">\begin{aligned}\mathrm{PE}(pos+k, 2i) &= \sin \left( \frac{pos+k}{10000^{2i/d_{model}}} \right) \\&= \sin \left( \frac{pos}{10000^{2i/d_{model}}} \right) \cos \left( \frac{k}{10000^{2i/d_{model}}} \right) + \cos \left( \frac{pos}{10000^{2i/d_{model}}} \right) \sin \left( \frac{k}{10000^{2i/d_{model}}} \right) \\&= \mathrm{PE}(pos, 2i) \cos \left( \frac{k}{10000^{2i/d_{model}}} \right) + \mathrm{PE}(pos, 2i+1) \sin \left( \frac{k}{10000^{2i/d_{model}}} \right)\end{aligned}</script>]]></content>
    
    
    <summary type="html">&lt;p&gt;Notes on Attention is All You Need, i.e., the Transformer.&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="NLP" scheme="https://syuoni.github.io/tags/NLP/"/>
    
  </entry>
  
  <entry>
    <title>Attention in NLP</title>
    <link href="https://syuoni.github.io/posts/Attention-in-NLP/"/>
    <id>https://syuoni.github.io/posts/Attention-in-NLP/</id>
    <published>2020-06-02T08:25:43.000Z</published>
    <updated>2020-06-09T11:58:58.000Z</updated>
    
    <content type="html"><![CDATA[<p>This blog briefly reviews the attention mechanisms in NLP.<br><a id="more"></a></p><h2 id="The-Encoder-Decoder-Framework"><a href="#The-Encoder-Decoder-Framework" class="headerlink" title="The Encoder-Decoder Framework"></a>The Encoder-Decoder Framework</h2><p><img src="/images/Encoder-Decoder.jpg" alt="Encoder-Decoder Framework"></p><p>In the Encoder-Decoder framework, an encoder reads the source sentence, a sequence of vectors $x=\left( x_1, \cdots, x_{T_x} \right)$, into a fixed-length <em>context vector</em> $c$. </p><script type="math/tex; mode=display">\begin{aligned}\bar{h}_s &= f \left( x_s, \bar{h}_{s-1} \right) \\c &= q \left( \bar{h}_1, \cdots, \bar{h}_{T_x} \right)\end{aligned}</script><p>where $\bar{h}_s$ is the encoder’s hidden state at time $s$. $f$ and $q$ are some nonlinear functions. For example, one may use:</p><script type="math/tex; mode=display">\begin{aligned}f &= \mathrm{LSTM} \\ q \left( \bar{h}_1, \cdots, \bar{h}_{T_x} \right) &= \bar{h}_{T_x}\end{aligned}</script><p>The decoder is often trained to predict the next word $y_t$ given the context vector $c$ and all the previous predicted words $\left\{ y_1, \cdots, y_{t-1} \right\}$. In other words, the decoder defines a probability over the translation $y=\left( y_1, \cdots, y_{T_y} \right)$ by decomposing the joint probability into the ordered conditional probabilities. </p><script type="math/tex; mode=display">p(y) = \prod_{t=1}^{T_y} p\left( y_t | y_1, \cdots, y_{t-1}, c \right)</script><p>With an RNN, each conditional probability is modeled as</p><script type="math/tex; mode=display">p\left( y_t | y_1, \cdots, y_{t-1}, c \right) = g\left( y_{t-1}, h_t, c \right)</script><p>where $g$ is a nonlinear function. $h_t$ is the decoder’s hidden state at time $t$. </p><h2 id="Learning-to-Align-and-Translate"><a href="#Learning-to-Align-and-Translate" class="headerlink" title="Learning to Align and Translate"></a>Learning to Align and Translate</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Bahdanau, D., Cho, K. and Bengio, Y., 2014. Neural machine translation by jointly learning to align and translate. arXiv preprint arXiv:1409.0473.</span><br></pre></td></tr></table></figure><p>Define each conditional probability as </p><script type="math/tex; mode=display">p\left( y_t | y_1, \cdots, y_{t-1}, x \right) = g\left( y_{t-1}, h_t, c_t \right)</script><p>where $h_t$ is the decoder’s hidden state at time $t$, computed by</p><script type="math/tex; mode=display">h_t = f\left( h_{t-1}, y_{t-1}, c_t \right)</script><p>Note that here the probability is conditioned on a <em>distinct context vector</em> $c_t$ for each target word $y_t$.<br>The context vector $c_t$ depends on a sequence of <em>annotations</em> $\left( \bar{h}_1, \cdots, \bar{h}_{T_x} \right)$ to which the encoder maps the source sentence. Each annotation $\bar{h}_s$ contains information about the whole source sequence with a strong focus on the parts surrounding the $s$-th word. For example, the annotations can be hidden states from a <em>bidirectional RNN</em>.<br>The context vector $c_t$ is computed as a weighted sum of these annotations: </p><script type="math/tex; mode=display">c_t = \sum_{s=1}^{T_x} \alpha_{st} \bar{h}_s</script><p>The weight $\alpha_{st}$ of each annotation $\bar{h}_s$ is computed by:</p><script type="math/tex; mode=display">\alpha_{st} = \frac{\exp(e_{st})}{\sum_{s'=1}^{T_x} \exp(e_{s't})}</script><p>where</p><script type="math/tex; mode=display">e_{st} = \mathrm{score} \left( \bar{h}_s, h_{t-1} \right)</script><p>is an <em>alignment model</em> which scores how well the source words around position $s$ and the target word at position $t$ match. The score is based on the decoder’s hidden state $h_{t-1}$ and the encoder’s annotation $\bar{h}_s$.<br>The probability $\alpha_{st}$, or its associated <em>energy</em> $e_{st}$, reflects the importance of the annotation $\bar{h}_s$ with respect to the previous hidden state $h_{t-1}$ in deciding the next state $h_t$ and generating $y_t$. Intuitively, this implements an <em>attention mechanism</em> in the decoder.<br>The implement of the alignment model is</p><script type="math/tex; mode=display">\mathrm{score} \left( \bar{h}_s, h_{t-1} \right) = v_a^\top \tanh \left( W_a \left[ \bar{h}_s; h_{t-1} \right] \right)</script><p>where $W_a$ and $v_a$ are trainable weights. </p><h2 id="Global-and-Local-Attetions"><a href="#Global-and-Local-Attetions" class="headerlink" title="Global and Local Attetions"></a>Global and Local Attetions</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Luong, M.T., Pham, H. and Manning, C.D., 2015. Effective approaches to attention-based neural machine translation. arXiv preprint arXiv:1508.04025.</span><br></pre></td></tr></table></figure><h3 id="Global-Attention"><a href="#Global-Attention" class="headerlink" title="Global Attention"></a>Global Attention</h3><p>Very similar to Bahdanau et al. (2015).<br>The idea of global attention is to consider all the encoder’s hidden states when deriving the context vector $c_t$. The <em>alignment vector</em> $\alpha_t$, whose size equals the length on the source side, is: </p><script type="math/tex; mode=display">\begin{aligned}\alpha_{st} &= \mathrm{align} \left( \bar{h}_s, h_t \right) \\&= \frac{\exp \left( \mathrm{score} \left( \bar{h}_s, h_t \right) \right)}{\sum_{s'=1}^{T_x} \exp \left( \mathrm{score} \left( \bar{h}_{s'}, h_t \right) \right)}\end{aligned}</script><p>where $\mathrm{score}$ is the <em>alignment function</em>, which may have four alternatives: </p><script type="math/tex; mode=display">\mathrm{score} \left( \bar{h}_s, h_t \right) = \begin{cases}\bar{h}_s^\top h_t, &\text{Dot product} \\\bar{h}_s^\top W_a h_t, &\text{General product} \\v_a^\top \tanh \left( W_a \left[ \bar{h}_s; h_t \right] \right), &\text{Concat} \\\text{The } s\text{-th element of } W_a h_t, &\text{Location based}\end{cases}</script><p>where the location-based attention is computed sorely from the target hidden states, so it is fixed-length. Practically, For short sentences, only use the top part of $\alpha_t$; while for long sentences, ignore words near the end. </p><h3 id="Local-Attention"><a href="#Local-Attention" class="headerlink" title="Local Attention"></a>Local Attention</h3><p>Local attention choose to focus on only a small subset of the source positions, for each target word. The model first generates an <em>alignment position</em> $p_t$ for target word at time $t$. The context vector $c_t$, thus, is derived as a weighted average over the source hidden states within the window $\left[p_t-D, p_t+D \right]$. Hence, the alignment vector $\alpha_t$ is fixed-length now. </p><script type="math/tex; mode=display">p_t = \begin{cases}t, &\text{Monotonic alignment} \\S \cdot \mathrm{sigmoid} \left( v_p^\top \tanh \left( W_p h_t \right) \right), &\text{Predictive alignment} \end{cases}</script><p>where $W_p$ and $v_p$ are trainable parameters, and $S$ is the source length.<br>To favor alignment points near $p_t$, place a Gaussian distribution centered around $p_t$. Then, the alignment weights are:</p><script type="math/tex; mode=display">a_{st} = \mathrm{align} \left( \bar{h}_s, h_t \right) \cdot \exp \left( -\frac{(s-p_t)^2}{2\sigma^2} \right)</script><p>The standard deviation is empirically set as $\sigma = \frac{D}{2}$.</p><h2 id="Neural-Turing-Machines"><a href="#Neural-Turing-Machines" class="headerlink" title="Neural Turing Machines"></a>Neural Turing Machines</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Graves, A., Wayne, G., &amp; Danihelka, I. 2014. Neural Turing machines. arXiv preprint arXiv:1410.5401.</span><br></pre></td></tr></table></figure><p>An alternative of alignment function named content-based addressing: </p><script type="math/tex; mode=display">\mathrm{score} \left( \bar{h}_s, h_t \right) = \mathrm{cosine} \left( \bar{h}_s, h_t \right)</script><h2 id="An-Survey-on-Attention-in-NLP"><a href="#An-Survey-on-Attention-in-NLP" class="headerlink" title="An Survey on Attention in NLP"></a>An Survey on Attention in NLP</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Hu, D. 2019. An introductory survey on attention mechanisms in NLP problems. In Proceedings of SAI Intelligent Systems Conference (pp. 432-448). Springer, Cham.</span><br></pre></td></tr></table></figure><p>An alternative of alignment function based on MLP: </p><script type="math/tex; mode=display">\mathrm{score} \left( \bar{h}_s, h_t \right) = \sigma \left( v_a^\top \tanh \left( W_a \left[ \bar{h}_s; h_t \right] + b_{a1} \right) + b_{a2} \right)</script><h3 id="Memory-Based-Attention"><a href="#Memory-Based-Attention" class="headerlink" title="Memory-Based Attention"></a>Memory-Based Attention</h3><h4 id="What-are-Qurey-and-Key-Value-Pairs"><a href="#What-are-Qurey-and-Key-Value-Pairs" class="headerlink" title="What are Qurey and Key-Value Pairs?"></a>What are Qurey and Key-Value Pairs?</h4><p>Given a list of key-value vector pairs $\left\{ \left( k_i, v_i \right) \right\}$ stored in <em>memory</em> and a query vector $q$, the attention computation follows three steps:</p><script type="math/tex; mode=display">\begin{aligned}e_i &= \mathrm{score} (q, k_i), &\text{Address Memory} \\\alpha_i &= \frac{\exp(e_i)}{\sum_k \exp(e_k)}, &\text{Normalize} \\c &= \sum_i \alpha_i v_i, &\text{Read Contents}\end{aligned}</script><p>Typically, <em>memory</em> is simply a synonym for the source sequence. In other words, each key-value pair is aligned to a step in the source sequence. Further, the key and value are typically equal within each pair (e.g., both are the encoder’s hidden state), and this reduces to the basic attention mechanism.<br>The query vector is distinct in different NLP tasks. For example, in language translation, the query is the decoder’s last hidden state; in question-answering system, the query is the embedding of question. </p><h2 id="Attention-is-All-You-Need"><a href="#Attention-is-All-You-Need" class="headerlink" title="Attention is All You Need"></a>Attention is All You Need</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Vaswani, A., Shazeer, N., Parmar, N., et al. 2017. Attention is all you need. In Advances in neural information processing systems (pp. 5998-6008).</span><br></pre></td></tr></table></figure><p><img src="/images/Scaled-Dot-Product-and-Multi-Head-Attention.jpg" alt="Scaled Dot-Product and Multi-Head Attention"></p><h3 id="Scaled-Dot-Product-Attention"><a href="#Scaled-Dot-Product-Attention" class="headerlink" title="Scaled Dot-Product Attention"></a>Scaled Dot-Product Attention</h3><p>An <em>attention function</em> can be described as mapping a query and a set of key-value pairs to an output (i.e., context vector). The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a <em>compatibility function</em> (i.e., normalized alighment function) of the query with the corresponding key. </p><p>Assume the <em>queries</em> and <em>keys</em> are of dimension $d_k$, and <em>values</em> are of dimension $d_v$, the alighment function is:</p><script type="math/tex; mode=display">\mathrm{score} (q, k) = \frac{q^\top k}{\sqrt{d_k}}</script><p>where $q$ and $k$ are query and key vectors. It is idential to the dot-product attention, expect for the scaling factor $\frac{1}{\sqrt{d_k}}$.<br>In practice, pack the queries, keys and values into matrices: </p><ul><li>Quries: A matrix $Q \in \Bbb{R}^{N_q \times d_k}$;</li><li>Keys: A matrix $K \in \Bbb{R}^{N_k \times d_k}$;</li><li>Values: A matrix $V \in \Bbb{R}^{N_k \times d_v}$.  </li></ul><p>And the full <em>attentioned values</em> (context vectors) are computed by:</p><script type="math/tex; mode=display">\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left( \frac{QK^\top}{\sqrt{d_k}} \right) V</script><h3 id="Multi-Head-Attention"><a href="#Multi-Head-Attention" class="headerlink" title="Multi-Head Attention"></a>Multi-Head Attention</h3><p>In the single-head scenario, the attention function is performed with $d_{model}$-dimensional queries, keys and values. (e.g., the queries, keys and values are all $d_{model}$-dimensional embeddings).<br>In the multi-head scenario:</p><ul><li>Project the $d_{model}$-dimensional queries, keys and values to $d_k$, $d_k$ and $d_v$ dimensions, for $h$ times, resulting in $h$ versions of projected queries, keys and values. </li><li>For each version, perform attention function on the projected queries, keys and values, yielding $h$ versions of $d_v$-dimensional attentioned values. </li><li>Concatenate the $h$ versions of attentioned values and then futher project the concatenated attentioned values to $d_{model}$ dimension. </li></ul><p>Formerly, </p><script type="math/tex; mode=display">\begin{aligned}\mathrm{MultiHead}(Q, K, V) &= \mathrm{Concat}(head_1, \dots, head_h) W^O \\\text{where } head_i &= \mathrm{Attention} \left( Q W_i^Q, K W_i^K, V W_i^V \right)\end{aligned}</script><p>where $W_i^Q \in \Bbb{R}^{d_{model} \times d_k}$, $W_i^K \in \Bbb{R}^{d_{model} \times d_k}$, $W_i^V \in \Bbb{R}^{d_{model} \times d_v}$ and $W^O \in \Bbb{R}^{hd_v \times d_{model}}$ are trainable parameter matrices. </p><p>Multi-head attention allows the model to jointly attend to information from different <em>representation subspaces</em> at different positions. While with a single attention head, averaging inhibits this.</p><h3 id="Application-of-Attention-in-Transformer"><a href="#Application-of-Attention-in-Transformer" class="headerlink" title="Application of Attention in Transformer"></a>Application of Attention in Transformer</h3><p>The Transformer uses multi-head attention in three different ways:</p><ul><li>Encoder-Decoder Attention layers<ul><li>Queries come from the output of the previous decoder layer</li><li>Memory keys and values come from the output of the encoder</li><li>This mimics the typical Encoder-Decoder attention mechanisms in Seq2Seq models </li></ul></li><li>Self-Attention layers in the encoder<ul><li>All the queries, keys and values come from the output of the previous encoder layer</li><li>Each position can attend to <em>all positions</em> in the previous layer</li></ul></li><li>Self-Attention layers in the decoder<ul><li>All the queries, keys and values come from the output of the previous decoder layer</li><li>Each position attends to positions <em>up to and including that position</em> in the previous layer (The target sequence is right shifted by one position)</li><li>Mask out (setting to $-\infty$) all values in the input of the softmax which correspond to illegal connections</li></ul></li></ul><h3 id="Self-Attention"><a href="#Self-Attention" class="headerlink" title="Self-Attention"></a>Self-Attention</h3><p>Self-attention is a new scheme, other than RNN and CNN, used for mapping a variable-length sequence of representations $\left(x_1, x_2, \dots, x_n\right)$ to another sequence of equal length $\left(z_1, z_2, \dots, z_n\right)$, with $x_i, z_i \in \Bbb{R}^d$. </p><div class="table-container"><table><thead><tr><th style="text-align:center">Layer Type</th><th style="text-align:center">Complexity per Layer</th><th style="text-align:center">Sequential Operations</th><th style="text-align:center">Max Path Length</th></tr></thead><tbody><tr><td style="text-align:center">Self-Attention</td><td style="text-align:center">$O(n^2 \cdot d)$</td><td style="text-align:center">$O(1)$</td><td style="text-align:center">$O(1)$</td></tr><tr><td style="text-align:center">RNN</td><td style="text-align:center">$O(n \cdot d^2)$</td><td style="text-align:center">$O(n)$</td><td style="text-align:center">$O(n)$</td></tr><tr><td style="text-align:center">CNN</td><td style="text-align:center">$O(k \cdot n \cdot d^2)$</td><td style="text-align:center">$O(1)$</td><td style="text-align:center">$O(\log_k(n))$</td></tr><tr><td style="text-align:center">Self-Attention (Restricted)</td><td style="text-align:center">$O(r \cdot n \cdot d)$</td><td style="text-align:center">$O(1)$</td><td style="text-align:center">$O(n/r)$</td></tr></tbody></table></div><p><img src="/images/Self-Attention-Visual.jpg" alt="Self-Attention Visualizations"></p>]]></content>
    
    
    <summary type="html">&lt;p&gt;This blog briefly reviews the attention mechanisms in NLP.&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="NLP" scheme="https://syuoni.github.io/tags/NLP/"/>
    
  </entry>
  
  <entry>
    <title>重装 Python 包</title>
    <link href="https://syuoni.github.io/posts/reinstall-python-packages/"/>
    <id>https://syuoni.github.io/posts/reinstall-python-packages/</id>
    <published>2020-05-01T06:09:11.000Z</published>
    <updated>2020-05-01T06:19:30.000Z</updated>
    
    <content type="html"><![CDATA[<p>重装了一遍 Python，记录一下需要重装的包。<br><a id="more"></a></p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$ conda install pyshp</span><br><span class="line">$ conda install shapely</span><br><span class="line"></span><br><span class="line">$ pip install jieba</span><br><span class="line">$ pip install hanziconv</span><br><span class="line">$ pip install splinter</span><br><span class="line">$ pip install filterpy</span><br></pre></td></tr></table></figure>]]></content>
    
    
    <summary type="html">&lt;p&gt;重装了一遍 Python，记录一下需要重装的包。&lt;br&gt;</summary>
    
    
    
    <category term="Python" scheme="https://syuoni.github.io/categories/Python/"/>
    
    
    <category term="Python" scheme="https://syuoni.github.io/tags/Python/"/>
    
  </entry>
  
  <entry>
    <title>《医学统计学》笔记</title>
    <link href="https://syuoni.github.io/posts/Medical-Statistics-Notes/"/>
    <id>https://syuoni.github.io/posts/Medical-Statistics-Notes/</id>
    <published>2020-04-20T11:43:56.000Z</published>
    <updated>2020-04-26T11:37:50.000Z</updated>
    
    <content type="html"><![CDATA[<p>《医学统计学》（第二版，颜虹主编，人民卫生出版社）读书笔记。<br><a id="more"></a></p><h2 id="第3章：统计描述"><a href="#第3章：统计描述" class="headerlink" title="第3章：统计描述"></a>第3章：统计描述</h2><h3 id="3-1-频数分布"><a href="#3-1-频数分布" class="headerlink" title="3.1 频数分布"></a>3.1 频数分布</h3><p>直方图（Histogram）</p><h3 id="3-2-计量资料的统计描述"><a href="#3-2-计量资料的统计描述" class="headerlink" title="3.2 计量资料的统计描述"></a>3.2 计量资料的统计描述</h3><h4 id="集中趋势"><a href="#集中趋势" class="headerlink" title="集中趋势"></a>集中趋势</h4><ol><li>算术均值（Arithmetic Mean）</li><li>几何均值（Geometric Mean）</li><li>中位数（Median）</li></ol><h4 id="离散趋势"><a href="#离散趋势" class="headerlink" title="离散趋势"></a>离散趋势</h4><ol><li>全距（Range）</li><li>分位数（Quantile）</li><li>方差（Variance）</li><li>标准差（Standard Deviation）</li></ol><h3 id="3-3-分类资料的统计描述"><a href="#3-3-分类资料的统计描述" class="headerlink" title="3.3 分类资料的统计描述"></a>3.3 分类资料的统计描述</h3><h4 id="常用相对数指标"><a href="#常用相对数指标" class="headerlink" title="常用相对数指标"></a>常用相对数指标</h4><ol><li>比（Ratio）：一个指标是另一个指标的几倍或百分之几</li><li>比例（Proportion）：一个集合的内部各组成部分的占比</li><li><p>率（Rate）：某个 <strong>时间段</strong> 内事件发生的频率或强度</p><ul><li>生存率、发病率、死亡率、复发率<script type="math/tex; mode=display">率 = \frac{某时期内发生事件的观察单位数}{该时期开始时暴露的观察单位数}</script><script type="math/tex; mode=display">率 = \frac{发生事件的观察单位数}{\Sigma 观察单位 \times 观察时间}</script></li></ul></li><li><p>相对危险度（Relative Risk, RR）：同一事件在两种不同情况下的 <strong>发生率</strong> 之比</p><script type="math/tex; mode=display">RR = \frac{P_1}{P_2}</script><ul><li>暴露和未暴露于危险因素两种情况下的患病率之比（Prevalence Risk Ratio, PRR）</li></ul></li><li><p>比数比（Odds Ratio, OR）</p><ul><li>设 $P$ 为某事件的发生率，则 <strong>比数</strong> $Odds = P / (1 - P)$</li><li>比数比就是两个比数之比<script type="math/tex; mode=display">OR = \frac{Odds_1}{Odds_2} = \frac{P_1 / (1 - P_1)}{P_2 / (1 - P_2)}</script></li></ul></li></ol><ul><li>两种随机抽样方式<ul><li>按因素的暴露和未暴露进行抽样，分别得到暴露样本和未暴露样本的发病 Odds</li><li>按是否发病进行抽样，分别得到发病样本和不发病样本的暴露 Odds</li></ul></li></ul><h4 id="动态数列"><a href="#动态数列" class="headerlink" title="动态数列"></a>动态数列</h4><ol><li>增长量</li><li>发展速度 和 增长速度</li><li>平均发展速度 和 平均增长速度</li></ol><h4 id="率的标准化"><a href="#率的标准化" class="headerlink" title="率的标准化"></a>率的标准化</h4><h3 id="3-4-统计图表"><a href="#3-4-统计图表" class="headerlink" title="3.4 统计图表"></a>3.4 统计图表</h3><h2 id="第4章：常见的概率分布"><a href="#第4章：常见的概率分布" class="headerlink" title="第4章：常见的概率分布"></a>第4章：常见的概率分布</h2><h3 id="4-1-随机事件与概率"><a href="#4-1-随机事件与概率" class="headerlink" title="4.1 随机事件与概率"></a>4.1 随机事件与概率</h3><h3 id="4-2-二项分布"><a href="#4-2-二项分布" class="headerlink" title="4.2 二项分布"></a>4.2 二项分布</h3><p>Bernoulli 实验每次成功的概率为 $\pi$，那么 $n$ 次独立重复的成功次数 $X$ 服从二项分布。</p><script type="math/tex; mode=display">P(X=k) = C_n^k \cdot \pi^k (1-\pi)^{(n-k)}</script><p>成功次数 $X$ 的</p><ul><li>总体均值：$n \pi$</li><li>总体方差：$n \pi (1 - \pi)$</li><li>总体标准差：$\sqrt{n \pi (1 - \pi)}$</li></ul><p>成功率 $X / n$ 的</p><ul><li>总体均值：$\pi$</li><li>总体方差：$\pi (1 - \pi) / n$</li><li>总体标准差：$\sqrt{\pi (1 - \pi) / n}$</li></ul><h3 id="4-3-Poisson-分布"><a href="#4-3-Poisson-分布" class="headerlink" title="4.3 Poisson 分布"></a>4.3 Poisson 分布</h3><p>单位时间内发生某事件的次数 $X$，服从 Poisson 分布。</p><script type="math/tex; mode=display">P(X=k) = \frac{\lambda^k}{k!} e^{-\lambda}</script><h3 id="4-3-正态分布"><a href="#4-3-正态分布" class="headerlink" title="4.3 正态分布"></a>4.3 正态分布</h3><script type="math/tex; mode=display">f(X) = \frac{1}{\sqrt{2\pi} \sigma} e^{\frac{-(x-\mu)^2}{2 \sigma^2}}</script><h2 id="第5章：参数估计"><a href="#第5章：参数估计" class="headerlink" title="第5章：参数估计"></a>第5章：参数估计</h2><h3 id="5-1-抽样分布与抽样误差"><a href="#5-1-抽样分布与抽样误差" class="headerlink" title="5.1 抽样分布与抽样误差"></a>5.1 抽样分布与抽样误差</h3><h4 id="样本均值"><a href="#样本均值" class="headerlink" title="样本均值"></a>样本均值</h4><p>从一个均值为 $\mu$、标准差为 $\sigma$ 的总体分布中随机抽取样本量为 $n$ 的样本，其样本均值 $\bar{X}$ 的期望为</p><script type="math/tex; mode=display">\mu_{\bar{X}} = \mu</script><p>其标准误为</p><script type="math/tex; mode=display">\sigma_{\bar{X}} = \frac{\sigma}{\sqrt{n}}</script><p>在实际中，由于总体标准差 $\sigma$ 常常是未知的，用样本标准差 $S$ 来估计，因此样本均值 $\bar{X}$ 标准误的估计值为</p><script type="math/tex; mode=display">S_{\bar{X}} = \frac{S}{\sqrt{n}}</script><p>中心极限定理：</p><ul><li>从正态分布 $N(\mu, \sigma^2)$ 的总体中随机抽取样本量为 $n$ 的样本，其样本均值 $\bar{X}$ 服从正态分布 $N(\mu, \sigma^2 / n)$。</li><li>从非正态分布中抽样，当样本量较大（$n \ge 30$），样本均值的分布接近正态分布。</li></ul><h4 id="样本率"><a href="#样本率" class="headerlink" title="样本率"></a>样本率</h4><p>从一个总体分布（成功率为 $\pi$ 的 Bernoulli 分布）中随机抽取样本量为 $n$ 的样本，其成功率为 $p$，则其期望为</p><script type="math/tex; mode=display">\mu_{p} = \pi</script><p>样本率的标准误为</p><script type="math/tex; mode=display">\sigma_p = \sqrt{\frac{\pi (1 - \pi)}{n}}</script><p>在实际中，由于总体率 $\pi$ 常常是未知的，用样本率 $p$ 来估计，因此样本率 $p$ 标准误的估计值为</p><script type="math/tex; mode=display">S_p = \sqrt{\frac{p (1 - p)}{n}}</script><h3 id="5-2-总体均值的估计"><a href="#5-2-总体均值的估计" class="headerlink" title="5.2 总体均值的估计"></a>5.2 总体均值的估计</h3><h4 id="t-分布"><a href="#t-分布" class="headerlink" title="t 分布"></a>t 分布</h4><p>标准正态分布 $N(0, 1)$ 也被称为 z 分布，对样本均值 $\bar{X}$ 进行 z 变换得到 $\frac{\bar{X} - \mu}{\sigma_{\bar{X}}}$，服从 z 分布。但是，实际中 $\sigma_{\bar{X}}$ 常常未知，用 $S_{\bar{X}}$ 代替，得到的 $\frac{\bar{X} - \mu}{S_{\bar{X}}}$ 服从 t 分布。</p><h4 id="点估计和区间估计"><a href="#点估计和区间估计" class="headerlink" title="点估计和区间估计"></a>点估计和区间估计</h4><h4 id="两总体均数之差的区间估计"><a href="#两总体均数之差的区间估计" class="headerlink" title="两总体均数之差的区间估计"></a>两总体均数之差的区间估计</h4><h3 id="5-3-总体率的估计"><a href="#5-3-总体率的估计" class="headerlink" title="5.3 总体率的估计"></a>5.3 总体率的估计</h3><h4 id="点估计和区间估计-1"><a href="#点估计和区间估计-1" class="headerlink" title="点估计和区间估计"></a>点估计和区间估计</h4><p>区间估计</p><ul><li>查表法：二项分布的计算结果。</li><li>正态近似法：当 $n$ 较大，且 $np$ 和 $n(1-p)$ 均大于 5 时，样本率 $p$ 的分布近似正态分布。</li></ul><h4 id="两总体率之差的区间估计"><a href="#两总体率之差的区间估计" class="headerlink" title="两总体率之差的区间估计"></a>两总体率之差的区间估计</h4><ul><li>正态近似法</li></ul><h3 id="5-4-Poisson-分布总体均数的区间估计"><a href="#5-4-Poisson-分布总体均数的区间估计" class="headerlink" title="5.4 Poisson 分布总体均数的区间估计"></a>5.4 Poisson 分布总体均数的区间估计</h3><ul><li>查表法</li><li>正太近似法</li></ul><h3 id="5-5-RR-值和-OR-值的估计"><a href="#5-5-RR-值和-OR-值的估计" class="headerlink" title="5.5 RR 值和 OR 值的估计"></a>5.5 RR 值和 OR 值的估计</h3><p>相对危险度 RR 是暴露组的发病率与非暴露组的发病率之比。</p><ul><li>当 RR 大于 1 时，该因素为危险因素</li><li>当 RR 小于 1 时，该因素为保护因素</li></ul><h4 id="队列研究（Cohort-Study）"><a href="#队列研究（Cohort-Study）" class="headerlink" title="队列研究（Cohort Study）"></a>队列研究（Cohort Study）</h4><ul><li>又称前瞻性研究（Prospective Study）、随访研究（Follow-Up Study）</li><li>对不同暴露水平的对象跟踪调查其疾病发生情况</li><li>可以计算不同暴露水平组的发病率，可以直接估计相对危险度</li></ul><p>情况1：随访期间研究对象因为失访、死亡等原因而变化，以“观察人-时”为分母计算发病率，又称为 <strong>发病密度</strong>。</p><div class="table-container"><table><thead><tr><th style="text-align:center">组别</th><th style="text-align:center">发病人数</th><th style="text-align:center">观察人时数</th><th style="text-align:center">发病密度</th></tr></thead><tbody><tr><td style="text-align:center">暴露组</td><td style="text-align:center">$a$</td><td style="text-align:center">$L_1$</td><td style="text-align:center">$a / L_1$</td></tr><tr><td style="text-align:center">非暴露组</td><td style="text-align:center">$b$</td><td style="text-align:center">$L_0$</td><td style="text-align:center">$b / L_0$</td></tr><tr><td style="text-align:center">合计</td><td style="text-align:center">$m$</td><td style="text-align:center">$L$</td><td style="text-align:center">$m / L$</td></tr></tbody></table></div><script type="math/tex; mode=display">\hat{RR} = \frac{a / L_1}{b / L_0}</script><p>区间估计为</p><script type="math/tex; mode=display">\begin{aligned}& \hat{RR}^{\left( 1 \pm z_{\alpha/2} / \sqrt{\chi^2} \right)} \\& \chi^2 = \frac{(aL-mL_1)^2}{mL_1L_0}\end{aligned}</script><p>情况2：随访期间研究对象没有变化，以观察人数为分母计算发病率，又称为 <strong>累计发病率</strong>。</p><div class="table-container"><table><thead><tr><th style="text-align:center">组别</th><th style="text-align:center">发病人数</th><th style="text-align:center">未发病人数</th><th style="text-align:center">合计</th><th style="text-align:center">累计发病率</th></tr></thead><tbody><tr><td style="text-align:center">暴露组</td><td style="text-align:center">$a$</td><td style="text-align:center">$b$</td><td style="text-align:center">$n_1$</td><td style="text-align:center">$a / n_1$</td></tr><tr><td style="text-align:center">非暴露组</td><td style="text-align:center">$c$</td><td style="text-align:center">$d$</td><td style="text-align:center">$n_0$</td><td style="text-align:center">$c / n_0$</td></tr><tr><td style="text-align:center">合计</td><td style="text-align:center">$m_1$</td><td style="text-align:center">$m_0$</td><td style="text-align:center">$n$</td><td style="text-align:center">$m_1 / n$</td></tr></tbody></table></div><script type="math/tex; mode=display">\hat{RR} = \frac{a / n_1}{b / n_0}</script><p>区间估计为</p><script type="math/tex; mode=display">\begin{aligned}& \hat{RR}^{\left( 1 \pm z_{\alpha/2} / \sqrt{\chi^2} \right)} \\& \chi^2 = \frac{(n-1)(ad-bc)^2}{n_1n_0m_1m_0}\end{aligned}</script><h4 id="病例-对照研究"><a href="#病例-对照研究" class="headerlink" title="病例-对照研究"></a>病例-对照研究</h4><ul><li>根据研究对象的目前发病状态划分到病例组或对照组，然后回顾性地询问过去的危险因素暴露情况，比较病例组和对照组的暴露水平差异</li><li>不能计算不同暴露水平组的发病率，通常使用优势比或比数比来近似估计相对危险度</li></ul><p>设计1：<strong>成组设计</strong> 的病例对照研究</p><div class="table-container"><table><thead><tr><th style="text-align:center">组别</th><th style="text-align:center">暴露</th><th style="text-align:center">未暴露</th><th style="text-align:center">合计</th></tr></thead><tbody><tr><td style="text-align:center">病例组</td><td style="text-align:center">$a$</td><td style="text-align:center">$b$</td><td style="text-align:center">$n_1$</td></tr><tr><td style="text-align:center">对照组</td><td style="text-align:center">$c$</td><td style="text-align:center">$d$</td><td style="text-align:center">$n_0$</td></tr><tr><td style="text-align:center">合计</td><td style="text-align:center">$m_1$</td><td style="text-align:center">$m_0$</td><td style="text-align:center">$n$</td></tr></tbody></table></div><p>在病例组，暴露事件的 Odds 为</p><script type="math/tex; mode=display">Odds_1 = \frac{a/n_1}{b/n_1} = \frac{a}{b}</script><p>在对照组，暴露事件的 Odds 为</p><script type="math/tex; mode=display">Odds_0 = \frac{c/n_0}{d/n_0} = \frac{c}{d}</script><p>所以，病例组相比对照组，暴露事件的优势比为</p><script type="math/tex; mode=display">\hat{OR} = \frac{Odds_1}{Odds_0} = \frac{a / b}{c / d} = \frac{ad}{bc}</script><p>当发病率很低（如小于 1% 时），OR 近似等于 RR。</p><p>Miettinen 法区间估计为</p><script type="math/tex; mode=display">\begin{aligned}& \hat{OR}^{\left( 1 \pm z_{\alpha/2} / \sqrt{\chi^2} \right)} \\& \chi^2 = \frac{(n-1)(ad-bc)^2}{n_1n_0m_1m_0}\end{aligned}</script><p>设计2：<strong>配对设计</strong> 的病例对照研究</p><p>在 1:1 配对设计病例对照研究中，每一个病例都有对应的一个对照。一对病例与对照的暴露情况可能有四种：</p><ul><li>病例与对照都暴露（a）</li><li>病例暴露，对照未暴露（b）</li><li>病例未暴露，对照暴露（c）</li><li>病例与对照都未暴露（d）</li></ul><div class="table-container"><table><thead><tr><th style="text-align:center"></th><th style="text-align:center">对照暴露</th><th style="text-align:center">对照未暴露</th><th style="text-align:center">合计</th></tr></thead><tbody><tr><td style="text-align:center">病例暴露</td><td style="text-align:center">$a$</td><td style="text-align:center">$b$</td><td style="text-align:center">$a+b$</td></tr><tr><td style="text-align:center">病例未暴露</td><td style="text-align:center">$c$</td><td style="text-align:center">$d$</td><td style="text-align:center">$c+d$</td></tr><tr><td style="text-align:center">合计</td><td style="text-align:center">$a+c$</td><td style="text-align:center">$b+d$</td><td style="text-align:center">$n$</td></tr></tbody></table></div><p>注：上表中 $a$、$b$、$c$、$d$ 每个数字都代表 <strong>双份</strong> 的样本，一份是病例，一份是对照。</p><p>如果整理成 <strong>成组设计</strong> 的表格</p><div class="table-container"><table><thead><tr><th style="text-align:center">组别</th><th style="text-align:center">暴露</th><th style="text-align:center">未暴露</th><th style="text-align:center">合计</th></tr></thead><tbody><tr><td style="text-align:center">病例组</td><td style="text-align:center">$a+b$</td><td style="text-align:center">$c+d$</td><td style="text-align:center">$a+b+c+d$</td></tr><tr><td style="text-align:center">对照组</td><td style="text-align:center">$a+c$</td><td style="text-align:center">$b+d$</td><td style="text-align:center">$a+b+c+d$</td></tr><tr><td style="text-align:center">合计</td><td style="text-align:center">$2a+b+c$</td><td style="text-align:center">$b+c+2d$</td><td style="text-align:center">$2(a+b+c+d)$</td></tr></tbody></table></div><p>可以发现，病例和对照暴露水平一致的情况（$a$ 和 $d$）没有提供暴露和发病之间的相关信息，因此估计优势比 $OR$ 只需要使用 $b$ 和 $c$。</p><script type="math/tex; mode=display">\begin{aligned}& \hat{OR} = \frac{b}{c} \\& \chi^2 = \frac{(\vert b-c \vert -1)^2}{b + c}\end{aligned}</script><h2 id="第6章：假设检验"><a href="#第6章：假设检验" class="headerlink" title="第6章：假设检验"></a>第6章：假设检验</h2><h3 id="6-3-z-检验"><a href="#6-3-z-检验" class="headerlink" title="6.3 z 检验"></a>6.3 z 检验</h3><h3 id="6-7-检验效能"><a href="#6-7-检验效能" class="headerlink" title="6.7 检验效能"></a>6.7 检验效能</h3><h2 id="第7章：两样本均数比较的假设检验"><a href="#第7章：两样本均数比较的假设检验" class="headerlink" title="第7章：两样本均数比较的假设检验"></a>第7章：两样本均数比较的假设检验</h2><h3 id="7-1-单样本均数的-t-检验"><a href="#7-1-单样本均数的-t-检验" class="headerlink" title="7.1 单样本均数的 t 检验"></a>7.1 单样本均数的 t 检验</h3><h3 id="7-2-配对样本均数的-t-检验"><a href="#7-2-配对样本均数的-t-检验" class="headerlink" title="7.2 配对样本均数的 t 检验"></a>7.2 配对样本均数的 t 检验</h3><h3 id="7-3-两独立样本均数的-t-检验"><a href="#7-3-两独立样本均数的-t-检验" class="headerlink" title="7.3 两独立样本均数的 t 检验"></a>7.3 两独立样本均数的 t 检验</h3><h3 id="7-4-正态性检验"><a href="#7-4-正态性检验" class="headerlink" title="7.4 正态性检验"></a>7.4 正态性检验</h3><h3 id="7-5-两样本的方差的齐性检验"><a href="#7-5-两样本的方差的齐性检验" class="headerlink" title="7.5 两样本的方差的齐性检验"></a>7.5 两样本的方差的齐性检验</h3><h3 id="7-6-两总体方差不等时均数比较的-t’-检验"><a href="#7-6-两总体方差不等时均数比较的-t’-检验" class="headerlink" title="7.6 两总体方差不等时均数比较的 t’ 检验"></a>7.6 两总体方差不等时均数比较的 t’ 检验</h3><h2 id="第8章：多个样本均数比较的假设检验"><a href="#第8章：多个样本均数比较的假设检验" class="headerlink" title="第8章：多个样本均数比较的假设检验"></a>第8章：多个样本均数比较的假设检验</h2><h3 id="8-1-方差分析的基本思想与应用条件"><a href="#8-1-方差分析的基本思想与应用条件" class="headerlink" title="8.1 方差分析的基本思想与应用条件"></a>8.1 方差分析的基本思想与应用条件</h3><p>判断多个处理组之间，处理效应是否有差异。</p><h2 id="第9章：行列表资料的假设检验"><a href="#第9章：行列表资料的假设检验" class="headerlink" title="第9章：行列表资料的假设检验"></a>第9章：行列表资料的假设检验</h2><h3 id="9-1-四格表资料的-chi-2-检验"><a href="#9-1-四格表资料的-chi-2-检验" class="headerlink" title="9.1 四格表资料的 $\chi^2$ 检验"></a>9.1 四格表资料的 $\chi^2$ 检验</h3><div class="table-container"><table><thead><tr><th style="text-align:center"></th><th style="text-align:center">有疗效</th><th style="text-align:center">无疗效</th><th style="text-align:center">合计</th><th style="text-align:center">有效率</th></tr></thead><tbody><tr><td style="text-align:center">A 药物</td><td style="text-align:center">$a$</td><td style="text-align:center">$b$</td><td style="text-align:center">$a+b$</td><td style="text-align:center">$a/(a+b)$</td></tr><tr><td style="text-align:center">B 药物</td><td style="text-align:center">$c$</td><td style="text-align:center">$d$</td><td style="text-align:center">$c+d$</td><td style="text-align:center">$c/(c+d)$</td></tr><tr><td style="text-align:center">合计</td><td style="text-align:center">$a+c$</td><td style="text-align:center">$b+d$</td><td style="text-align:center">$n$</td><td style="text-align:center">$(a+c)/n$</td></tr></tbody></table></div><h4 id="chi-2-检验的基本思想"><a href="#chi-2-检验的基本思想" class="headerlink" title="$\chi^2$ 检验的基本思想"></a>$\chi^2$ 检验的基本思想</h4><p>如果零假设成立，则各格子的实际观察频数（Observed Frequency, O）与相应的理论期望频数（Expected Frequency, E）相差不会太大，即</p><script type="math/tex; mode=display">\chi^2 = \sum \frac{(O-E)^2}{E}</script><p>的值不会太大。</p><h4 id="四格表的-chi-2-检验"><a href="#四格表的-chi-2-检验" class="headerlink" title="四格表的 $\chi^2$ 检验"></a>四格表的 $\chi^2$ 检验</h4><p>组别 A、B 和总体的有效率分别是 $\pi_1$、$\pi_2$、$\pi$，其估计值分别是</p><script type="math/tex; mode=display">\begin{aligned}\hat{\pi_1} & = \frac{a}{a+b} \\ \hat{\pi_2} & = \frac{c}{c+d} \\\hat{\pi} & = \frac{a+c}{a+b+c+d} \\\end{aligned}</script><p>$\chi^2$ 检验的基本步骤是：</p><ol><li>建立假设<ul><li>H0：$\pi_1 = \pi_2 = \pi$</li><li>H1：$\pi_1 \neq \pi_2$</li></ul></li><li>计算期望频数和检验统计量<ul><li>以 <strong>总体有效率</strong> 和 <strong>周边合计</strong> 计算各格子的期望频数<script type="math/tex; mode=display">\begin{aligned}E[a] & = (a+b) \cdot \frac{a+c}{a+b+c+d} \\E[b] & = (a+b) \cdot \frac{b+d}{a+b+c+d} \\E[c] & = (c+d) \cdot \frac{a+c}{a+b+c+d} \\E[d] & = (c+d) \cdot \frac{b+d}{a+b+c+d} \\\end{aligned}</script></li><li>计算 $\chi^2$ 统计量<script type="math/tex; mode=display">\chi^2 = \frac{(a-E[a])^2}{E[a]} + \frac{(b-E[b])^2}{E[b]} + \frac{(c-E[c])^2}{E[c]} + \frac{(d-E[d])^2}{E[d]}</script></li></ul></li></ol><h4 id="交叉分类-2×2-表关联性分析"><a href="#交叉分类-2×2-表关联性分析" class="headerlink" title="交叉分类 2×2 表关联性分析"></a>交叉分类 2×2 表关联性分析</h4><p>两变量相关分析</p><ul><li>通过 $\chi^2$ 检验判断两 <strong>定性变量</strong> 之间是否相关。</li><li>通过 Pearson 相关系数或 Spearman 秩相关系数来描述两 <strong>定量变量</strong> 之间的相关关系。</li></ul><h3 id="9-2-配对四格表资料的-chi-2-检验"><a href="#9-2-配对四格表资料的-chi-2-检验" class="headerlink" title="9.2 配对四格表资料的 $\chi^2$ 检验"></a>9.2 配对四格表资料的 $\chi^2$ 检验</h3><div class="table-container"><table><thead><tr><th style="text-align:center"></th><th style="text-align:center">乙法治疗有效</th><th style="text-align:center">乙法治疗无效</th><th style="text-align:center">合计</th></tr></thead><tbody><tr><td style="text-align:center">甲法治疗有效</td><td style="text-align:center">$a$</td><td style="text-align:center">$b$</td><td style="text-align:center">$a+b$</td></tr><tr><td style="text-align:center">甲法治疗无效</td><td style="text-align:center">$c$</td><td style="text-align:center">$d$</td><td style="text-align:center">$c+d$</td></tr><tr><td style="text-align:center">合计</td><td style="text-align:center">$a+c$</td><td style="text-align:center">$b+d$</td><td style="text-align:center">$n$</td></tr></tbody></table></div><p>注：上表中 $a$、$b$、$c$、$d$ 每个数字都代表 <strong>双份</strong> 的样本，一份进行甲法治疗，一份进行乙法治疗。</p><p>显然，$a$ 和 $d$ 的治疗结果一致，不影响两种治疗方法效果的差异；所以只需要比较 $b$ 和 $c$ 是否相同即可。$b$ 和 $c$ 的期望频数为 $(b+c)/2$，所以</p><script type="math/tex; mode=display">\chi^2 = \frac{\left( b-\frac{b+c}{2} \right)^2}{\frac{b+c}{2}} + \frac{\left( c-\frac{b+c}{2} \right)^2}{\frac{b+c}{2}} = \frac{(b-c)^2}{b+c}</script><h3 id="9-3-行×列表资料的-chi-2-检验"><a href="#9-3-行×列表资料的-chi-2-检验" class="headerlink" title="9.3 行×列表资料的 $\chi^2$ 检验"></a>9.3 行×列表资料的 $\chi^2$ 检验</h3><p>对 R 行 C 列表资料，第 i 行第 j 列的频数记作 $a_{ij}$，代表第 i 种情况（如治疗方法、暴露情况）下第 j 中结果（如疗效、发病）的频数。<br>那么，先计算期望频数：</p><script type="math/tex; mode=display">E[a_{ij}] = \left( \sum_l a_{il} \right) \cdot \frac{\sum_k a_{kj}}{\sum_{k, l} a_{kl}}</script><p>然后，再计算 $\chi^2$ 统计量</p><script type="math/tex; mode=display">\chi^2 = \sum \frac{(O-E)^2}{E} = \sum_{ij} \frac{\left( a_{ij} - E[a_{ij}] \right)^2}{E[a_{ij}]}</script><h3 id="9-4-多个样本率的多重比较"><a href="#9-4-多个样本率的多重比较" class="headerlink" title="9.4 多个样本率的多重比较"></a>9.4 多个样本率的多重比较</h3><p>对多个样本率进行比较时，如果拒绝零假设，则说明至少有某两个率之间存在显著差异，则需要进行多个率之间的两两比较。<br>Bonferroni 法：</p><ol><li>对行×列表资料进行分割，变成多个四格表</li><li>对每个四格表进行 $\chi^2$ 检验</li><li>采用 $\alpha’ = \alpha / 比较次数$ 调整显著性水平</li><li>以 $\alpha’$ 作为检验水准，下有无统计学意义的结论</li></ol><h3 id="9-5-行×列表资料的-chi-2-检验的注意事项"><a href="#9-5-行×列表资料的-chi-2-检验的注意事项" class="headerlink" title="9.5 行×列表资料的 $\chi^2$ 检验的注意事项"></a>9.5 行×列表资料的 $\chi^2$ 检验的注意事项</h3><ol><li>样本含量应足够大<ul><li>80% 以上格子的期望频数大于 5，且不存在期望频数小于 1 的格子。</li><li>否则，补充样本、合并行或列、删除行或列、采用 Fisher 确切概率检验。</li></ul></li><li>行×列表资料经 $\chi^2$ 检验后，如果假设检验结果拒绝 H0，意味着各组总体率或构成比之间整体上存在显著差异，并不一定两两之间均有显著差异。</li><li>当结果变量为等级资料时，不采用 $\chi^2$ 检验。<ul><li>组别和结果变量双向无序：采用 $\chi^2$ 检验</li><li>组别变量有序、结果变量无序：采用 $\chi^2$ 检验</li><li>组别变量无序、结果变量有序：采用秩和检验</li><li>组别和结果变量均有序、且属性相同：采用一致性检验（如 Kappa 检验）<ul><li>例如用两种检测方法检测样品的等级，检验两种检测方法的一致性</li></ul></li><li>组别和结果变量均有序、但属性不同<ul><li>研究不同组别的结果是否存在差异：采用秩和检验</li><li>研究两个有序变量是否相关：采用 Spearman 秩相关分析</li><li>研究两个有序变量是否存在线性变化趋势：采用线性趋势检验</li></ul></li></ul></li><li>各分类间彼此互斥</li></ol><h3 id="9-6-频数分布拟合优度的-chi-2-检验"><a href="#9-6-频数分布拟合优度的-chi-2-检验" class="headerlink" title="9.6 频数分布拟合优度的 $\chi^2$ 检验"></a>9.6 频数分布拟合优度的 $\chi^2$ 检验</h3><h3 id="9-7-确切概率法"><a href="#9-7-确切概率法" class="headerlink" title="9.7 确切概率法"></a>9.7 确切概率法</h3><p>当样本量较少（如四格表资料总例数小于 40），采用 Fisher 确切概率检验。<br>在表格周围合计数不变的条件下，表格中各格子的频数有多种可能组合，其概率分布是超几何分布。那么，可以求出所有组合的概率，再将所有小于等于原组合（观察到的实际组合）概率的所有概率相加，作为双侧检验的 p 值。</p><h3 id="9-8-OR-值的-chi-2-检验"><a href="#9-8-OR-值的-chi-2-检验" class="headerlink" title="9.8 OR 值的 $\chi^2$ 检验"></a>9.8 OR 值的 $\chi^2$ 检验</h3><p>参考 5.5 内容。</p><h2 id="第10章：基于秩次的假设检验方法"><a href="#第10章：基于秩次的假设检验方法" class="headerlink" title="第10章：基于秩次的假设检验方法"></a>第10章：基于秩次的假设检验方法</h2><p>秩和检验的应用场景</p><ul><li>当计量资料不服从正态分布，或者所比较的样本间方差不齐是，不适宜采用 t 检验和方差分析</li><li>对于结果变量为等级资料（有序分类资料），不适宜采用 $\chi^2$ 检验</li></ul><h3 id="10-1-配对设计资料的符号秩和检验"><a href="#10-1-配对设计资料的符号秩和检验" class="headerlink" title="10.1 配对设计资料的符号秩和检验"></a>10.1 配对设计资料的符号秩和检验</h3><p>对于计量配对资料，有观察值 $(x_i, y_i)$，有差值 $d_i = x_i - y_i$。<br>如果 $d$ 服从正态分布，则采用配对 t 检验即可。<br>如果 $d$ 不服从正态分布，则采用 Wilcoxon 符号秩和检验（Wilcoxon Signed Rank Test）。</p><p>Wilcoxon 符号秩和检验步骤</p><ol><li>求差值</li><li>建立假设<ul><li>H0：$M_d = 0$，即差值的总体中位数等于零</li><li>H1：$M_d \neq 0$，即差值的总体中位数不等于零</li></ul></li><li>编秩：按差值的绝对值有小到大编秩，并按照差值的正负号给秩次加上正负号<ul><li>差值为零，舍去不计</li><li>多个差值绝对值相等，取平均秩次</li></ul></li><li>求秩和：分别求出正负秩次之和，将其绝对值记作 $T_+$ 和 $T_-$</li><li>计算统计量 T，有 $T = \min(T_+, T_-)$；有效的秩次数记作 $n$</li><li>计算 p 值，做出推断<ul><li>若 $5 &lt; n \leq 50$，查表</li><li>若 $n &gt; 50$，正态近似法<script type="math/tex; mode=display">\begin{aligned}T & \sim N \left(\mu_T, \sigma_T^2 \right) \\\mu_T & = \frac{n(n+4)}{4} \\\sigma_T & = \sqrt{\frac{n(n+1)(2n+1)}{24}}\end{aligned}</script></li></ul></li></ol><h3 id="10-2-单样本资料的符号秩和检验"><a href="#10-2-单样本资料的符号秩和检验" class="headerlink" title="10.2 单样本资料的符号秩和检验"></a>10.2 单样本资料的符号秩和检验</h3><p>将每个样本取值与已知总体值（理论值、标准值或大量样本观察值）比较。</p><h3 id="10-3-完全随机设计两独立样本的秩和检验"><a href="#10-3-完全随机设计两独立样本的秩和检验" class="headerlink" title="10.3 完全随机设计两独立样本的秩和检验"></a>10.3 完全随机设计两独立样本的秩和检验</h3><h4 id="两组计量资料的秩和检验"><a href="#两组计量资料的秩和检验" class="headerlink" title="两组计量资料的秩和检验"></a>两组计量资料的秩和检验</h4><p>两独立样本的 Wilcoxon 秩和检验步骤</p><ol><li>建立假设<ul><li>H0：两总体分布相同</li><li>H1：两总体分布不同</li></ul></li><li>编秩：将两组数据混合、有小到大统一编秩<ul><li>相同数据取平均秩次</li></ul></li><li>求秩和：将两组样本的秩次分别相加</li><li>计算统计量 T<ul><li>若两组样本数相等，任取一组秩和作为统计量 T</li><li>若两组样本数不等，以样本数较小的那组对应的秩和作为统计量 T</li></ul></li><li>计算 p 值，做出推断<ul><li>查表法</li><li>正态近似法</li></ul></li></ol><h4 id="两组等级资料的秩和检验"><a href="#两组等级资料的秩和检验" class="headerlink" title="两组等级资料的秩和检验"></a>两组等级资料的秩和检验</h4><p>同一等级的数据取平均秩次</p><h3 id="10-4-完全随机设计多独立样本的秩和检验"><a href="#10-4-完全随机设计多独立样本的秩和检验" class="headerlink" title="10.4 完全随机设计多独立样本的秩和检验"></a>10.4 完全随机设计多独立样本的秩和检验</h3><h4 id="多组计量资料的秩和检验"><a href="#多组计量资料的秩和检验" class="headerlink" title="多组计量资料的秩和检验"></a>多组计量资料的秩和检验</h4><p>Kruskal-Wallis 秩和检验步骤</p><ol><li>建立假设<ul><li>H0：多个总体分布相同</li><li>H1：多个总体分布不同</li></ul></li><li>编秩</li><li>求秩和：第 $i$ 组的秩和记作 $R_i$</li><li>计算统计量 H<script type="math/tex; mode=display">H = \frac{12}{N(N+1)} \sum \frac{R_i^2}{n_i} - 3(N+1)</script></li><li>计算 p 值，做出推断<ul><li>当组数 $k = 3$，每组样本数 $n_i \leq 5$，查表</li><li>当组数 $k &gt; 3$，或每组样本数 $n_i &gt; 5$，H 近似服从 $\chi^2$ 分布</li></ul></li></ol><h4 id="多组等级资料的秩和检验"><a href="#多组等级资料的秩和检验" class="headerlink" title="多组等级资料的秩和检验"></a>多组等级资料的秩和检验</h4><p>同一等级的数据取平均秩次</p><h4 id="多重比较"><a href="#多重比较" class="headerlink" title="多重比较"></a>多重比较</h4><p>Bonferroni 法校正检验水平 $\alpha’$</p><h3 id="10-5-随机化区组设计资料的秩和检验"><a href="#10-5-随机化区组设计资料的秩和检验" class="headerlink" title="10.5 随机化区组设计资料的秩和检验"></a>10.5 随机化区组设计资料的秩和检验</h3><h2 id="第11章：简单线性回归"><a href="#第11章：简单线性回归" class="headerlink" title="第11章：简单线性回归"></a>第11章：简单线性回归</h2><h3 id="11-1-简单线性回归"><a href="#11-1-简单线性回归" class="headerlink" title="11.1 简单线性回归"></a>11.1 简单线性回归</h3><h3 id="11-2-线性回归的应用"><a href="#11-2-线性回归的应用" class="headerlink" title="11.2 线性回归的应用"></a>11.2 线性回归的应用</h3><h3 id="11-3-残差分析"><a href="#11-3-残差分析" class="headerlink" title="11.3 残差分析"></a>11.3 残差分析</h3><p>线性回归模型成立的四个条件</p><ul><li>线性（Linear）</li><li>独立（Independence）</li><li>正态（Normal）</li><li>等方差（Equal Variance）<br>首字母相连为 LINE。</li></ul><h2 id="第12章：线性相关"><a href="#第12章：线性相关" class="headerlink" title="第12章：线性相关"></a>第12章：线性相关</h2><h3 id="12-1-直线相关"><a href="#12-1-直线相关" class="headerlink" title="12.1 直线相关"></a>12.1 直线相关</h3><p>Pearson 相关系数</p><script type="math/tex; mode=display">r = \frac{\sum \left( x_i-\bar{x} \right) \left( y_i-\bar{y} \right)}{\sqrt{\sum \left( x_i-\bar{x} \right)^2} \sqrt{\sum \left( y_i-\bar{y} \right)^2}}</script><h3 id="12-2-Spearman-相关"><a href="#12-2-Spearman-相关" class="headerlink" title="12.2 Spearman 相关"></a>12.2 Spearman 相关</h3><p>Spearman 相关系数<br>先对变量 $x$ 与 $y$ 各自编秩，得到 $R_x$ 和 $R_y$，再代入 Pearson 相关系数的计算公式</p><script type="math/tex; mode=display">r_s = \frac{\sum \left( R_{xi}-\bar{R_x} \right) \left( R_{yi}-\bar{R_y} \right)}{\sqrt{\sum \left( R_{xi}-\bar{R_x} \right)^2} \sqrt{\sum \left( R_{yi}-\bar{R_y} \right)^2}}</script><h2 id="第13章：多因素线性回归"><a href="#第13章：多因素线性回归" class="headerlink" title="第13章：多因素线性回归"></a>第13章：多因素线性回归</h2><h3 id="13-1-多因素线性回归"><a href="#13-1-多因素线性回归" class="headerlink" title="13.1 多因素线性回归"></a>13.1 多因素线性回归</h3><h3 id="13-2-回归分析中的自变量选择"><a href="#13-2-回归分析中的自变量选择" class="headerlink" title="13.2 回归分析中的自变量选择"></a>13.2 回归分析中的自变量选择</h3><h3 id="13-3-注意事项"><a href="#13-3-注意事项" class="headerlink" title="13.3 注意事项"></a>13.3 注意事项</h3><p>一般情况，应当校正基线、年龄、性别等常规的可能混杂因素。<br>对实验性研究的统计分析，一般不应采用逐步回归。<br>将名义变量、等级变量进行数量化（转换为哑元）；连续变量也可以先离散化再哑元化。</p><h2 id="第21章：Logistic回归分析"><a href="#第21章：Logistic回归分析" class="headerlink" title="第21章：Logistic回归分析"></a>第21章：Logistic回归分析</h2><h3 id="21-1-回归"><a href="#21-1-回归" class="headerlink" title="21.1 回归"></a>21.1 回归</h3><script type="math/tex; mode=display">\rm{logit}(P) = \ln \left( \frac{P}{1-P} \right) = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_n x_n</script><h4 id="参数的流行病学意义"><a href="#参数的流行病学意义" class="headerlink" title="参数的流行病学意义"></a>参数的流行病学意义</h4><p>$\beta_0$ 的意义：当所有 $\beta_i = 0$，有</p><script type="math/tex; mode=display">\ln \left( \frac{P}{1-P} \right) = \beta_0</script><p>所以，$\beta_0$ 代表所有因素均不起作用时，发病与不发病的概率之比（Odds）的对数。</p><p>$\beta_i$ 的意义：如果 $x_i$ 取 0 和 1，有</p><script type="math/tex; mode=display">\ln OR_i = \ln \left[ \frac{P_1/(1-P_1)}{P_0/(1-P_0)} \right] = \beta_i</script><p>因此，</p><script type="math/tex; mode=display">OR_i = \exp(\beta_i)</script><p>所以，$\beta_i$ 代表 $x_i$ 增加一个单位前后发病的比数比（Odds Ratio）。</p><h3 id="21-2-条件-Logitstic-回归"><a href="#21-2-条件-Logitstic-回归" class="headerlink" title="21.2 条件 Logitstic 回归"></a>21.2 条件 Logitstic 回归</h3><p>按照 1:M 的比例匹配了病例和对照。</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;《医学统计学》（第二版，颜虹主编，人民卫生出版社）读书笔记。&lt;br&gt;</summary>
    
    
    
    <category term="医学统计" scheme="https://syuoni.github.io/categories/%E5%8C%BB%E5%AD%A6%E7%BB%9F%E8%AE%A1/"/>
    
    
    <category term="医学" scheme="https://syuoni.github.io/tags/%E5%8C%BB%E5%AD%A6/"/>
    
    <category term="统计" scheme="https://syuoni.github.io/tags/%E7%BB%9F%E8%AE%A1/"/>
    
  </entry>
  
  <entry>
    <title>《线性代数的本质》笔记</title>
    <link href="https://syuoni.github.io/posts/Essence-of-Linear-Algebra-notes/"/>
    <id>https://syuoni.github.io/posts/Essence-of-Linear-Algebra-notes/</id>
    <published>2020-03-14T06:11:06.000Z</published>
    <updated>2020-03-19T01:25:24.000Z</updated>
    
    <content type="html"><![CDATA[<p>3Blue1Brown 视频《线性代数的本质》（<a href="https://www.bilibili.com/video/av6731067" target="_blank" rel="noopener">bilibili</a>, <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab" target="_blank" rel="noopener">YouTube</a>）的笔记。用于构建线性代数的几何直觉。</p><a id="more"></a><h3 id="向量"><a href="#向量" class="headerlink" title="向量"></a>向量</h3><ul><li><p>不同学科视角下的 <strong>向量</strong></p><ul><li>物理学视角：<strong>箭头</strong>（<strong>长度</strong> + <strong>方向</strong>）决定一个向量，向量平移不变</li><li>计算机学视角：向量等同于有序的数字 <strong>列表</strong></li><li>数学视角：向量是任意支持符合向量计算规则（加法和乘法）的对象</li></ul></li><li><p>如果把向量的起点默认为原点，就能将 <strong>箭头</strong> 和 <strong>列表</strong> 两种视角相统一</p><ul><li>向量加法<ul><li>箭头视角：把向量依次首尾相连</li><li>列表视角：把向量各元素分别加总</li></ul></li><li>向量乘以标量（Scalar）<ul><li>箭头视角：缩放（Scaling）</li><li>列表视角：把向量各元素分别乘以标量，分别缩放</li></ul></li></ul></li></ul><p>定义基向量（Basis Vectors）</p><script type="math/tex; mode=display">{\pmb i} = \begin{bmatrix} 1 \\ 0 \end{bmatrix}, \;{\pmb j} = \begin{bmatrix} 0 \\ 1 \end{bmatrix}</script><p>把向量看成是基向量的 <strong>缩放后相加</strong> 的结果，例如</p><script type="math/tex; mode=display">\begin{bmatrix} 3 \\ -2 \end{bmatrix} = 3 {\pmb i} -2 {\pmb j}</script><p>我们完全可以使用不同的基向量。因此，当我们使用数字列表表示向量时，实际的向量总是依赖于我们所采用的基向量。</p><p>这种向量的 <strong>缩放后相加</strong> 实际上就是 <strong>线性组合</strong>（Linear Combination）。也就是说，<strong>向量可以理解成基向量的线性组合</strong>。</p><p>一组基向量的线性组合所能到达的点的集合就是该组基向量张成的 <strong>空间</strong>（Span）。在二维情况下，只要基向量不共线，它们张成的空间就覆盖平面上所有的点；如果基向量共线，它们张成的空间就只有一条线；如果基向量都是零向量，它们张成的空间就只有一个点。</p><p>如果能从基向量中移除一个向量，而不影响它们张成的空间，就说这组基向量是 <strong>线性相关</strong>（Linearly Dependent）；否则就是 <strong>线性无关</strong>（Linearly Independent）。</p><h3 id="矩阵乘以向量"><a href="#矩阵乘以向量" class="headerlink" title="矩阵乘以向量"></a>矩阵乘以向量</h3><p><strong>线性变换</strong>（Linear Transformation）：<strong>变换</strong> 就是函数的另一种说法，线性变换就是向量到向量的映射；<strong>变换</strong> 一词暗示了是输入向量 <strong>移动</strong> 到输出向量的位置。</p><p>在 <strong>线性变换</strong> 中，只要确定基向量的变换后位置，就能确定其他所有向量的变换后位置。如果</p><script type="math/tex; mode=display">{\pmb v} = \begin{bmatrix} x \\ y \end{bmatrix} = x \left( {\pmb i} \right) + y \left( {\pmb j} \right)</script><p>那么，在变换后有</p><script type="math/tex; mode=display">{\pmb v'} = x \left( {\pmb i'} \right) + y \left( {\pmb j'} \right)</script><p>举个例子，假设在变换后有</p><script type="math/tex; mode=display">{\pmb i'} = \begin{bmatrix} 1 \\ -2 \end{bmatrix}, \;{\pmb j'} = \begin{bmatrix} 3 \\ 0 \end{bmatrix}</script><p>就有</p><script type="math/tex; mode=display">\begin{aligned}{\pmb v'} =& x \left( {\pmb i'} \right) + y \left( {\pmb j'} \right) \\=& x \begin{bmatrix} 1 \\ -2 \end{bmatrix} + y \begin{bmatrix} 3 \\ 0 \end{bmatrix} \\=& \begin{bmatrix} x+3y \\ -2x \end{bmatrix}\end{aligned}</script><p>把基向量变换后的向量作为列排成 2*2 的矩阵 $\begin{bmatrix} 1 &amp; 3 \\\\ -2 &amp; 0 \end{bmatrix}$，此时矩阵乘以向量 ${\pmb v} = \begin{bmatrix} x \\\\ y \end{bmatrix}$，就是</p><script type="math/tex; mode=display">\begin{bmatrix} 1 & 3 \\ -2 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} = \begin{bmatrix} x+3y \\ -2x \end{bmatrix} = {\pmb v'}</script><p>也就是在求变换后的 ${\pmb v}$。</p><p>所以，<strong>矩阵中的各列依次代表线性变换中，各基向量在变换后的结果（位置）</strong>，也就是 <strong>列向量</strong>。如果说，<strong>向量是基向量的线性组合</strong>，那么，<strong>矩阵乘以向量的结果可以理解成，线性变换之后的基向量的线性组合</strong>。</p><p>整体上，矩阵对应的线性变换将 <strong>原基向量张成的空间</strong> 映射到 <strong>变换后基向量张成的空间</strong>。如果矩阵的各列是线性相关的，说明在线性变换后，基向量是共线的。在二维的情况下，就是将平面压缩成一维直线。</p><h3 id="矩阵乘以矩阵"><a href="#矩阵乘以矩阵" class="headerlink" title="矩阵乘以矩阵"></a>矩阵乘以矩阵</h3><p>依次两个线性变换称为 <strong>复合变换</strong>（Composition of Transformations）。<br>一个向量依次经历两个矩阵的线性变换得到的结果，等价于其经过一个复合变换的结果，例如</p><script type="math/tex; mode=display">\underbrace{\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}}_{\text{Shear}}  \left( \underbrace{\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}}_{\text{Rotation}} \begin{bmatrix} x \\ y \end{bmatrix} \right) = \underbrace{\begin{bmatrix} 1 & -1 \\ 1 & 0 \end{bmatrix}}_{\text{Composition}} \begin{bmatrix} x \\ y \end{bmatrix}</script><p>那么，可以定义矩阵的乘法</p><script type="math/tex; mode=display">\underbrace{\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}}_{\text{Shear}}  \underbrace{\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}}_{\text{Rotation}} = \underbrace{\begin{bmatrix} 1 & -1 \\ 1 & 0 \end{bmatrix}}_{\text{Composition}}</script><p>注意，如果将矩阵的乘法看成是两个相继的线性变换，则需要 <strong>从右往左</strong> 阅读，即被作用的向量是先经历靠右矩阵的变换，然后经历靠左矩阵的变换。这类似函数的嵌套，即 $f \left( g(x) \right)$。</p><p>我们来追踪一下基向量的变换过程，以 ${\pmb i}$ 为例。经历第一个矩阵的变换后，该基向量变成 $\begin{bmatrix} 0 \\\\ 1 \end{bmatrix}$ （即右侧矩阵的第一列）。经历第二个矩阵的变换后，该基向量进一步变成 $\begin{bmatrix} 1 &amp; 1 \\\\ 0 &amp; 1 \end{bmatrix} \begin{bmatrix} 0 \\\\ 1 \end{bmatrix} = \begin{bmatrix} 1 \\\\ 1 \end{bmatrix}$，正好是复合矩阵的第一列。</p><h3 id="行列式"><a href="#行列式" class="headerlink" title="行列式"></a>行列式</h3><p><strong>行列式</strong>（Determinant）是线性变换后相比变换前空间中体积（二维情况下的面积）的缩放比例（Scaling Factor）。<br>如果变换改变了空间的定向（Orientation），那么行列式就是 <strong>负值</strong>。对二维平面而言，改变定向类似“翻转平面”；对三维空间而言，改变定向意味着是否符合“右手定则”。</p><p>行列式的计算：</p><script type="math/tex; mode=display">\det \left( \begin{bmatrix} a & b \\ c & d \end{bmatrix} \right) = ad - bc</script><p>如果矩阵的行列式等于 <strong>零</strong>，则意味着原空间经过该线性变换后，被压缩到一个低维空间里，使得“体积”变为零。同时，这也意味着变换后的基向量是 <strong>线性相关</strong> 的。</p><h3 id="线性方程组"><a href="#线性方程组" class="headerlink" title="线性方程组"></a>线性方程组</h3><p><strong>线性方程组</strong>（Linear System of Equations）</p><script type="math/tex; mode=display">\overbrace{\begin{bmatrix} 2 & 5 & 3 \\ 4 & 0 & 8 \\ 1 & 3 & 0 \end{bmatrix}}^{\pmb A} \overbrace{\begin{bmatrix} x \\ y \\ z \end{bmatrix}}^{\pmb x} = \overbrace{\begin{bmatrix} -3 \\ 0 \\ 2 \end{bmatrix}}^{\pmb v}</script><p>这相当于在问：什么向量 ${\pmb x}$ 经过变换 ${\pmb A}$ 后，能得到向量 ${\pmb v}$？<br>从几何直观出发，如果 ${\pmb A}$ 的行列式不为零，则有一个 <strong>逆变换</strong>（Inverse Transformation） ${\pmb A}^{-1}$，有</p><script type="math/tex; mode=display">{\pmb x} = {\pmb A}^{-1} {\pmb v}</script><p>如果 ${\pmb A}$ 的行列式为零，该矩阵将原空间压缩到一个低维空间里，则不存在逆变换，因为不存在一个“函数”，可以将一个值映射到多个值。<br>如果 ${\pmb A}$ 的行列式为零，只有当 ${\pmb v}$ 恰好处在那个被压缩后的低维空间里，原方程组才有解（且有无穷多个解），否则没有解。</p><p><strong>秩</strong>（Rank）是矩阵对应的 <strong>线性变换的输出空间的维度</strong>。这里，输出空间其实就是矩阵的每一列作为向量所张成的空间，被称为 <strong>列空间</strong>（Column Space）。一个矩阵的秩的最大可能取值就是其列数，只有取到该最大值时，行列式才不为零，此时被称为 <strong>满秩</strong>（Full Rank）；当秩小于列数时，行列式为零。</p><p>当矩阵满秩时，只有零向量会被映射为零向量。当矩阵不满秩时，意味着有些非零向量被映射成零向量，这些原空间中的非零向量张成的空间被称为 <strong>零空间</strong>（Null Space）或者 <strong>核</strong>（Kernel）。当 ${\pmb v}$ 正好是零向量时，零空间中的所有向量构成原方程组的解集。</p><h3 id="非方阵"><a href="#非方阵" class="headerlink" title="非方阵"></a>非方阵</h3><p><strong>非方阵</strong>（Non-Square Matrix）是不同维度的空间之间的线性变换，从 <strong>列数维度</strong> 的空间映射到 <strong>行数维度</strong> 的空间（但不一定能够“充满”、“张成”该空间），矩阵中的各 <strong>列向量</strong> 依然代表线性变换后的基向量，张成 <strong>列空间</strong>。</p><p>一个3*2（3行2列）的矩阵，就是从一个2维空间映射到3维空间，但显然不能张成该3维空间；通常只能张成一个平面，也可能压缩成直线或原点。</p><p>一个2*3（2行3列）的矩阵，就是从一个3维空间映射到2维空间，通常能够张成该2维空间，也可能压缩成直线或原点。</p><h3 id="点积"><a href="#点积" class="headerlink" title="点积"></a>点积</h3><p>${\pmb v}$ 和 ${\pmb w}$ 的点积，在几何上等价于先将 ${\pmb w}$ <strong>投影</strong>（Project）到 ${\pmb v}$ 的方向上，然后投影得到的长度乘以 ${\pmb v}$ 的长度。<br><img src="/images/dot-product.png" alt="向量点积"></p><script type="math/tex; mode=display">{\pmb v} \cdot {\pmb w} = \Vert {\pmb v} \Vert \Vert {\pmb w} \Vert \cos \theta</script><p>代数的计算方法：</p><script type="math/tex; mode=display">{\pmb v} \cdot {\pmb w} = \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} \cdot \begin{bmatrix} w_1 \\ w_2 \end{bmatrix} = v_1 w_1 + v_2 w_2 = \begin{bmatrix} v_1 & v_2 \end{bmatrix} \begin{bmatrix} w_1 \\ w_2 \end{bmatrix}</script><p>可以把向量 ${\pmb v}$ 看成一个1*2的矩阵，该矩阵代表了一个线性变换，该线性变换将一个2维空间映射为1维空间，那么 $[v_1]$ 代表第一个基向量映射后的位置，$[v_2]$ 代表第二个基向量映射后的位置，向量 ${\pmb w} = \begin{bmatrix} w_1 \\\\ w_2 \end{bmatrix}$ 映射后的位置就是 $w_1 [v_1] + w_2 [v_2]$，即 $w_1 v_1 + w_2 v_2$。</p><p>在以上过程中，2维空间映射为1维空间其实就是 <strong>投影</strong> 的过程。</p><p>所以，向量也可以理解成一个1行多列的矩阵，对应一个线性变换。任意一个其他向量经过该线性变换得到的结果，就是两个向量的点积。</p><h3 id="叉积"><a href="#叉积" class="headerlink" title="叉积"></a>叉积</h3><p>${\pmb v}$ 和 ${\pmb w}$ 的叉积，在几何上是向量张成的平行四边形的面积（并考虑定向问题决定正负号/方向）。</p><p>对于二维空间，叉积的结果是一个数（不严格定义）：</p><script type="math/tex; mode=display">{\pmb v} \times {\pmb w} = \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} \times \begin{bmatrix} w_1 \\ w_2 \end{bmatrix} = \det \left( \begin{bmatrix} v_1 & w_1 \\ v_2 & w_2 \end{bmatrix} \right) = v_1 w_2 - v_2 w_1</script><p>对于三维空间，叉积的结果是一个向量：</p><script type="math/tex; mode=display">{\pmb v} \times {\pmb w} = \begin{bmatrix} v_1 \\ v_2 \\ v_3 \end{bmatrix} \times \begin{bmatrix} w_1 \\ w_2 \\ w_3 \end{bmatrix} = \det \left( \begin{bmatrix} {\pmb i} & v_1 & w_1 \\ {\pmb j} & v_2 & w_2 \\ {\pmb k} & v_3 & w_3 \end{bmatrix} \right)</script><p>该向量垂直于 ${\pmb v}$ 和 ${\pmb w}$ 张成的平面，方向根据右手定则确定，长度等于 ${\pmb v}$ 和 ${\pmb w}$ 张成的面积。</p><p>在几何上，叉积的含义是：如果一个向量  ${\pmb p} = \begin{bmatrix} p_1 \\\\ p_2 \\\\ p_3 \end{bmatrix}$ 与任意向量 ${\pmb x} = \begin{bmatrix} x \\\\ y \\\\ z \end{bmatrix}$ 的点积等于由 ${\pmb x}$、${\pmb v}$ 和 ${\pmb w}$ 排成的矩阵的行列式，那么这个向量 ${\pmb p}$ 是多少？即</p><script type="math/tex; mode=display">\begin{bmatrix} p_1 \\ p_2 \\ p_3 \end{bmatrix} \cdot \begin{bmatrix} x \\ y \\ z \end{bmatrix} = \det \left( \begin{bmatrix} x & v_1 & w_1 \\ y & v_2 & w_2 \\ z & v_3 & w_3 \end{bmatrix} \right)</script><p>向量 ${\pmb p}$ 就是 ${\pmb v}$ 和 ${\pmb w}$ 的叉积。</p><p>实际上，由 ${\pmb x}$、${\pmb v}$ 和 ${\pmb w}$ 排成的矩阵的行列式是一个将 ${\pmb x}$ 从3维空间映射到1维空间的线性变换；既然是线性变换，就一定存在一个向量 ${\pmb p}$ 与之对应。</p><h3 id="基变换"><a href="#基变换" class="headerlink" title="基变换"></a>基变换</h3><p>当我们采用 ${\pmb i}$ 和 ${\pmb j}$ 作为基向量，意味着在对应的 <strong>坐标系</strong>（Coordinate System）下定义它们的 <strong>坐标</strong>（Coordinates）依次为 $\begin{bmatrix} 1 \\\\ 0 \end{bmatrix}$ 和 $\begin{bmatrix} 0 \\\\ 1 \end{bmatrix}$。</p><p>如果我们换一组向量作为基向量呢？比如，我们把向量 $2{\pmb i}+{\pmb j}$ 和 $-{\pmb i}+{\pmb j}$ 分别作为新的基向量，由此定义了一个 <strong>新坐标系</strong>，在这一 <strong>新坐标系</strong> 下，$2{\pmb i}+{\pmb j}$ 和 $-{\pmb i}+{\pmb j}$ 的坐标也依次定义为 $\begin{bmatrix} 1 \\\\ 0 \end{bmatrix}$ 和 $\begin{bmatrix} 0 \\\\ 1 \end{bmatrix}$。但显然，这两个向量在 <strong>原坐标系</strong> 中的坐标为 $\begin{bmatrix} 2 \\\\ 1 \end{bmatrix}$ 和 $\begin{bmatrix} -1 \\\\ 1 \end{bmatrix}$。</p><p>不同的基向量意味着不同的坐标系，不同的坐标系下，我们描述同一个 <strong>向量</strong>（Vector）所采用的 <strong>坐标</strong>（Coordinates）是不同的。事实上，空间本身并没有内蕴的（Intrinsic）坐标系，并不存在绝对的基向量选择；一开始的 ${\pmb i}$ 和 ${\pmb j}$ 其实也是任意选取的。</p><p>如何在不同坐标系下进行变换（Translate）？例如，在新坐标系下的坐标 $\begin{bmatrix} x \\\\ y \end{bmatrix}$ 对应的向量，在原坐标系下的坐标是多少？</p><script type="math/tex; mode=display">\begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} = x \begin{bmatrix} 2 \\ 1 \end{bmatrix} + y \begin{bmatrix} -1 \\ 1 \end{bmatrix} = \begin{bmatrix} 2x-y \\ x+y \end{bmatrix}</script><p>矩阵 $\begin{bmatrix} 2 &amp; -1 \\\\ 1 &amp; 1 \end{bmatrix}$ 是用 <strong>原坐标系的基向量</strong> 下的坐标来描述 <strong>新坐标系的基向量</strong>，却可以用来将 <strong>新坐标系下的坐标</strong> 转换为 <strong>原坐标系下的坐标</strong>。类似地，逆矩阵的定义和作用完全相反。</p><h3 id="基变换与线性变换"><a href="#基变换与线性变换" class="headerlink" title="基变换与线性变换"></a>基变换与线性变换</h3><p>此时，再回头看矩阵所代表的线性变换，之前的描述是 <strong>矩阵的各列依次代表变换后的各基向量</strong>。但更为精确的描述可以是，<strong>矩阵的各列依次代表变换后的各基向量的坐标</strong>。</p><ul><li>区分线性变换和基变换<ul><li>线性变换中，基向量（坐标系）只有一组，变化的是向量。</li><li>基变换中，向量不变，但需要在不同的基向量（坐标系）下描述该向量的坐标。</li></ul></li></ul><p>如果在 <strong>原坐标系</strong> 下发生了线性变换 $\begin{bmatrix} 0 &amp; -1 \\\\ 1 &amp; 0 \end{bmatrix}$，那么这个变换在 <strong>新坐标系</strong> 下该如何描述？<br>首先，对于 <strong>新坐标系</strong> 下的任意向量 ${\pmb v}$，先“翻译”到 <strong>原坐标系</strong>，即</p><script type="math/tex; mode=display">\begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix} {\pmb v}</script><p>然后，经过 <strong>原坐标系</strong> 下发生的线性变换，即</p><script type="math/tex; mode=display">\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix} {\pmb v}</script><p>最后，将结果“翻译”回 <strong>新坐标系</strong>，即</p><script type="math/tex; mode=display">\begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix}^{-1} \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix} {\pmb v}</script><p>所以，<strong>新坐标系</strong> 下描述该线性变换的矩阵就是 $\begin{bmatrix} 2 &amp; -1 \\\\ 1 &amp; 1 \end{bmatrix}^{-1} \begin{bmatrix} 0 &amp; -1 \\\\ 1 &amp; 0 \end{bmatrix} \begin{bmatrix} 2 &amp; -1 \\\\ 1 &amp; 1 \end{bmatrix}$。</p><p>在看到类似 ${\pmb A}^{-1} {\pmb M} {\pmb A}$ 的矩阵结构时，通常中间的矩阵 ${\pmb M}$ 代表一种变换，而两侧的矩阵 ${\pmb A}$ 代表一种转移作用。其结果是，变换仍然是 ${\pmb M}$ 所代表的变换，只是切换了一种视角来看待这种变换。</p><h3 id="特征向量与特征值"><a href="#特征向量与特征值" class="headerlink" title="特征向量与特征值"></a>特征向量与特征值</h3><p>要理解 <strong>特征向量</strong>（Eigenvectors）和 <strong>特征值</strong>（Eigenvalues），需要建立在理解众多预备知识的基础上，包括线性变换、行列式、线性方程组和基变换。</p><p>在线性变换中，绝大部分向量都偏离了原来的方向，只有少部分向量仍然保留在原来的方向。对这部分向量而言，线性变换的效果相当于缩放（乘以一个标量）。这样的向量被称为 <strong>特征向量</strong>，缩放的比例就是 <strong>特征值</strong>。</p><script type="math/tex; mode=display">\begin{aligned}{\pmb A} {\pmb v} =& \lambda {\pmb v} \\{\pmb A} {\pmb v} =& \lambda I {\pmb v} \\\left( {\pmb A} - \lambda I \right) {\pmb v} =& 0\end{aligned}</script><p>由于我们希望 ${\pmb v}$ 是非零解，就意味着矩阵 $\left( {\pmb A} - \lambda I \right)$ 是不满秩的（行列式为零），即</p><script type="math/tex; mode=display">\det \left( {\pmb A} - \lambda I \right) = 0</script><p>如果我们采用特征向量作为基向量，会怎么样？这种情况下，线性变换的效果是，每个基向量仍然保留在原来的方向上进行缩放。所以，对应的矩阵就是一个 <strong>对角矩阵</strong>（Diagnal Matrix），其对角元素就是特征值。</p><p>所以，在给定基向量（和对应的坐标系）的情况下，可以先“翻译”到特征向量作为基向量的坐标系中，进行线性变换（此时退化为每个基向量方向上的缩放变换），然后再“翻译”回原坐标系下。</p><p>假设原线性变换的矩阵是 ${\pmb M}$，存在特征向量 ${\pmb v_1}$、${\pmb v_2}$、……、${\pmb v_n}$，作为列向量排成矩阵 ${\pmb V} = \begin{bmatrix} {\pmb v_1} &amp; {\pmb v_2} &amp; \cdots &amp; {\pmb v_n} \end{bmatrix}$；对应特征根  $\lambda_1$、$\lambda_2$、……、$\lambda_n$，排成对角阵 ${\pmb \Lambda} = \begin{bmatrix} \lambda_1 &amp; 0 &amp; \cdots &amp; 0 \\\\ 0 &amp; \lambda_2 &amp; \cdots &amp; 0 \\\\ \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\\\ 0 &amp; 0 &amp; \cdots &amp; \lambda_n \end{bmatrix}$。由上一节结论可知，从 特征向量作为基向量的坐标系 中看这个线性变换，对应的矩阵是 ${\pmb V}^{-1} {\pmb M} {\pmb V}$，该矩阵必然等于 ${\pmb \Lambda}$，即</p><script type="math/tex; mode=display">\begin{aligned}{\pmb V}^{-1} {\pmb M} {\pmb V} =& {\pmb \Lambda}  \\{\pmb M} =& {\pmb V} {\pmb \Lambda} {\pmb V}^{-1}\end{aligned}</script><h3 id="抽象向量空间"><a href="#抽象向量空间" class="headerlink" title="抽象向量空间"></a>抽象向量空间</h3><p>线性代数中最为本质的概念，行列式和特征向量等，与所选取的坐标系（基向量）是无关的。</p><p>对某种对象，如果存在某种运算，该运算满足 <strong>可加性</strong>（Additivity）和 <strong>成比例</strong>（Scaling）这两个特性，都可以被看做向量。<br>可加性：$L\left( {\pmb v} + {\pmb w} \right) = L\left( {\pmb v} \right) + L\left( {\pmb w} \right)$<br>成比例：$L\left( c {\pmb v} \right) = c L\left( {\pmb v} \right)$</p><p>对 <strong>向量</strong> 而言，<strong>线性变换</strong> 这一运算就满足可加性和成比例两个特性。<br>特别地，<strong>函数</strong> 也可以被看成是 <strong>向量</strong>，<strong>求导</strong> 运算对函数就满足可加性和成比例两个特性。</p><div class="table-container"><table><thead><tr><th style="text-align:center">线性代数中的概念</th><th style="text-align:center">应用于函数时的别名</th></tr></thead><tbody><tr><td style="text-align:center">线性变换</td><td style="text-align:center">线性算子</td></tr><tr><td style="text-align:center">点积</td><td style="text-align:center">内积</td></tr><tr><td style="text-align:center">特征向量</td><td style="text-align:center">特征函数</td></tr></tbody></table></div>]]></content>
    
    
    <summary type="html">&lt;p&gt;3Blue1Brown 视频《线性代数的本质》（&lt;a href=&quot;https://www.bilibili.com/video/av6731067&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;bilibili&lt;/a&gt;, &lt;a href=&quot;https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;YouTube&lt;/a&gt;）的笔记。用于构建线性代数的几何直觉。&lt;/p&gt;</summary>
    
    
    
    <category term="数学" scheme="https://syuoni.github.io/categories/%E6%95%B0%E5%AD%A6/"/>
    
    
    <category term="数学" scheme="https://syuoni.github.io/tags/%E6%95%B0%E5%AD%A6/"/>
    
    <category term="线性代数" scheme="https://syuoni.github.io/tags/%E7%BA%BF%E6%80%A7%E4%BB%A3%E6%95%B0/"/>
    
    <category term="几何" scheme="https://syuoni.github.io/tags/%E5%87%A0%E4%BD%95/"/>
    
    <category term="3Blue1Brown" scheme="https://syuoni.github.io/tags/3Blue1Brown/"/>
    
  </entry>
  
  <entry>
    <title>《失落的学艺》笔记</title>
    <link href="https://syuoni.github.io/posts/Lost-Tools-of-Learning-notes/"/>
    <id>https://syuoni.github.io/posts/Lost-Tools-of-Learning-notes/</id>
    <published>2020-02-11T04:16:40.000Z</published>
    <updated>2020-02-11T05:34:50.000Z</updated>
    
    <content type="html"><![CDATA[<p>2020年初寒假，《失落的学艺》笔记<br><a id="more"></a></p><h2 id="一些令人不安的问题"><a href="#一些令人不安的问题" class="headerlink" title="一些令人不安的问题"></a>一些令人不安的问题</h2><ul><li><p>学生在校时间不断延长</p><ul><li>需要学习的知识增多了，但真的懂得更多了吗？</li></ul></li><li><p>令人担忧的现象</p><ul><li>人们越来越容易受到大众传媒的影响</li><li>辩论时，无法抓住问题关键</li><li>讨论时，提出无关议题</li><li>写作时，没有正确使用字词</li><li>离开学校后，忘记所学的内容，也没有学习新知识的能力</li><li>查阅资料时，无法辨别与所关注问题相关的内容</li><li>知识局限在固定的领域</li></ul></li></ul><h2 id="学习的艺术"><a href="#学习的艺术" class="headerlink" title="学习的艺术"></a>学习的艺术</h2><ul><li>学生什么都学，但却不学习 <strong>学习的技艺</strong></li></ul><h2 id="中世纪的教育大纲"><a href="#中世纪的教育大纲" class="headerlink" title="中世纪的教育大纲"></a>中世纪的教育大纲</h2><ul><li>三艺（Trivium） vs. 四艺（Quadrivium）<ul><li>三艺就是处理不同科目的必经办法<ul><li>文法（语言的结构）：语言是如何组织起来的</li><li>逻辑（语言的应用）：如何论述、组织逻辑、与人辩论</li><li>修辞（用语言表达自己）：优雅、有说服力</li><li>完成一篇论文并答辩</li></ul></li><li>四艺是具体的学科</li></ul></li></ul><h2 id="没有装备的人"><a href="#没有装备的人" class="headerlink" title="没有装备的人"></a>没有装备的人</h2><ul><li>将没有受到良好训练的人置于印刷品的摆布下，就像没有装备的人上战场</li><li>归回中世纪</li><li>三艺的教育开展对孩子越早越好</li></ul><h2 id="三个阶段"><a href="#三个阶段" class="headerlink" title="三个阶段"></a>三个阶段</h2><ul><li>鹦鹉学舌阶段<ul><li>擅长记忆、对推理不感兴趣，单纯地在积累材料</li><li>对应“文法”的学习：学习曲折语，尤其建议是 <strong>拉丁文文法</strong></li></ul></li><li>莽撞阶段<ul><li>喜欢争辩、顶嘴、纠正别人、提出难以回答的问题</li><li>对应“逻辑”的学习：以 <strong>形式逻辑</strong> 作为统领性训练</li></ul></li><li>诗意阶段<ul><li>以自己为中心，渴望表达自己，想要独立，开始有创造力</li><li>对应“修辞”的学习</li></ul></li></ul><h2 id="文法学习阶段：记忆的功能"><a href="#文法学习阶段：记忆的功能" class="headerlink" title="文法学习阶段：记忆的功能"></a>文法学习阶段：记忆的功能</h2><ul><li>英语：背诵诗歌和散文，为辩论和演讲打基础</li><li>历史：以时代服装、建筑照片构建视觉印象<ul><li>历史的文法包括时间、事件、轶事和人物</li></ul></li><li>地理：以地图、自然特征、风俗、动植物图片构建视觉印象</li><li>科学：从博物学开始</li><li>数学：乘法表、辨认几何图形和数字组</li><li><p>神学：应该去熟悉上帝和人的故事大纲，背诵主祷文、信经和十诫</p><ul><li>学生在掌握三艺后，能自己处理神学内容</li></ul></li><li><p>这些具体学科都应该作为三艺学习的材料</p></li></ul><h2 id="逻辑学习阶段"><a href="#逻辑学习阶段" class="headerlink" title="逻辑学习阶段"></a>逻辑学习阶段</h2><ul><li><p>何时从文法学习转入逻辑学习？</p><ul><li>当孩子出现争辩的倾向时，表现出抽象思维能力时</li></ul></li><li><p>阅读：从叙事类和抒情类转向散文、论说和批评类</p></li><li>数学：代数、几何、高阶算术<ul><li>作为逻辑学的分支被教授，因为数学基本就是在不断应用三段论</li></ul></li><li>历史：讨论如“政治家的行为合理吗？”、“这样的政策会产生什么影响？”等问题，从而进入宪政历史</li><li>神学：为辩论行为与道德提供材料，教义与伦理</li><li>地理和科学：也可以为逻辑辩论提供材料</li><li><p>周围的世界：也能为逻辑推理提供素材</p></li><li><p>如何在教育中批评？</p><ul><li>重点在论证的优美和精简上</li><li>错误、推理不严谨、论证模糊、论题无关和冗长</li><li>锻炼概要写作，然后精简到四分之一或一半的篇幅</li></ul></li></ul><h2 id="修辞学习阶段"><a href="#修辞学习阶段" class="headerlink" title="修辞学习阶段"></a>修辞学习阶段</h2><ul><li><p>何时从逻辑学习转入修辞学习？</p><ul><li>孩子发现自己的知识和经验不足，无法提供材料进行逻辑辩论；同时开始怀疑逻辑和理性的局限性</li></ul></li><li><p>文学：欣赏先于批评</p></li><li>写作：练习个性的表达</li><li>允许专业化的发展，但也要求学习辅修科目</li><li><p>神学：万般知识终归于一</p></li><li><p>掌握了三艺，就已经预备好学习任何具体学科的能力，在后续学习中将明显更高效；换言之，可以直接上大学</p></li></ul><h2 id="挥霍教育老本-amp-被忽视的根源"><a href="#挥霍教育老本-amp-被忽视的根源" class="headerlink" title="挥霍教育老本 &amp; 被忽视的根源"></a>挥霍教育老本 &amp; 被忽视的根源</h2><ul><li>拓展后的四艺并不能取代三艺</li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;2020年初寒假，《失落的学艺》笔记&lt;br&gt;</summary>
    
    
    
    <category term="信仰" scheme="https://syuoni.github.io/categories/%E4%BF%A1%E4%BB%B0/"/>
    
    
    <category term="基督教" scheme="https://syuoni.github.io/tags/%E5%9F%BA%E7%9D%A3%E6%95%99/"/>
    
    <category term="教育" scheme="https://syuoni.github.io/tags/%E6%95%99%E8%82%B2/"/>
    
  </entry>
  
  <entry>
    <title>《宗教情感》读后感</title>
    <link href="https://syuoni.github.io/posts/Religious-Affections-comments/"/>
    <id>https://syuoni.github.io/posts/Religious-Affections-comments/</id>
    <published>2020-02-08T06:53:26.000Z</published>
    <updated>2020-05-14T11:25:58.000Z</updated>
    
    <content type="html"><![CDATA[<p>2020年初寒假，《宗教情感》读后感<br><a id="more"></a></p><h2 id="从信心到情感，再到行为"><a href="#从信心到情感，再到行为" class="headerlink" title="从信心到情感，再到行为"></a>从信心到情感，再到行为</h2><p>我们似乎一直在谈论信心与行为，圣经中也常将信心与行为对比分析。《宗教情感》单独把 <strong>情感</strong> 拿出来强调，才让我发现圣经中对情感的描述并不少，只是很少单独作为一个概念来强调，以至于我们常常忽略其作用。</p><p>在我的理解里，情感似乎是介于信心与行为之间的。情感有类似信心的特质，就是当人有了信心或情感，然后出于信心或情感去做某件事时，是自愿自发的；而行为可能是自愿的，也可能是受律法辖制、不得已而为之。人顺应自己的信心或情感而行，通常是喜乐的。情感与信心的区别在于，信心本身是外源性的、纯粹的，而情感可能建立在外源性的信心上，也可以是从自己的血气而来。</p><p>情感也和行为有共性，就是两者都可以是自己努力伪造出来的。甚至，人可以先伪造自己的情感，然后顺应这样的情感行出行为，以至于行为好像也是自愿的。</p><p>我们可以很轻易地断定（合理定义下的）信心是好的，也可以很轻易地分辨行为的好坏（因为行为是外显的）。然而，情感内藏在人的心中，可以如同行为一样被伪造，也可以建立在信心上，所以分辨自己的情感是否属灵才显得如此之难。</p><p>在属灵上，情感在某种程度上也是信心与行为之间的桥梁。从信心激发属灵情感，然后情感驱动好的行为。反之，行为也能不断巩固情感，进而使得信心长进。</p><h2 id="《宗教情感》所批判的“属灵”境界，都常常是自己所不能及的"><a href="#《宗教情感》所批判的“属灵”境界，都常常是自己所不能及的" class="headerlink" title="《宗教情感》所批判的“属灵”境界，都常常是自己所不能及的"></a>《宗教情感》所批判的“属灵”境界，都常常是自己所不能及的</h2><p>在读《宗教情感》时，最直观的感觉是作者对属灵情感界定之严格，以至于很多我们常常以为的属灵认知或表现，在他笔下都是批判的对象。</p><p>例如，在第二部分第八节，作者对谦卑的讨论中指出：</p><blockquote><p>有时候人们以为他们谦卑，其实那不过是灰心丧气而已，因为他们曾经依赖的东西证明是靠不住的。这种所谓的顺服上帝并不是绝对顺服，其中还隐藏着讨价还价，只是难以察觉。</p></blockquote><p>我常以为，如果一个人发现世上万事都不可倚赖，最后回转投靠上帝，这是是属灵的。有些经文也似乎在表达类似的意思，如经典的经文：</p><blockquote><p>耶稣回答说，凡喝这水的，还要再渴。人若喝我所赐的水就永远不渴。我所赐的水，要在他里头成为泉源，直涌到永生。（约 4:13-14）</p></blockquote><p>似乎就在对比世界和上帝，并指出上帝才是可倚靠的。</p><p>再如，在第三部分第二节，作者说人完全因为上帝爱自己而爱上帝，也是不可取的：</p><blockquote><p>只要他们首先认定基督，宇宙的主宰，做了他们的俘虏，非爱他们不可，他的心肠因他们而消化，看他们的价值远远超过别人，在永恒当中预先爱了他们，且为他们而死，将来还要他们和他一同在天上掌权，同享永恒的荣耀。</p></blockquote><p>我也常以为，上帝就是通过先爱人，让人受感动而“回应”上帝的爱，也是没错的。例如，作者自己举出的经文：</p><blockquote><p>我们爱，因为上帝先爱我们。（约一 4:19）</p></blockquote><p>我原来甚至以为，也曾在门训中提出这样的观点，就是如果人觉得自己能够单单因为神的圣洁荣耀而爱上帝，不依赖任何上帝对其应许的利益（无论是今世的祝福，还是永生的盼望），似乎显得特别自高自大。这样美好的描述用在原本是罪人、且如今还常常受试探而软弱的我们身上，真的合适吗？</p><p>不过，其中需要分辨的是，作者对真宗教情感描述的对象是真圣徒，他们因圣灵感动而有了“属灵器官”，能感受到神圣事物的圣洁，所以能够通过认识上帝的圣洁荣耀而爱上帝。可是，这仅仅是理论上可行，实际上真的做起来又是何等的难。甚至，我常常连上帝爱自己这一点也需要刻意自我提醒才能认知到，面临困境时还可能会抱怨“上帝不爱我、不帮助我”。</p><p>某种意义上，作者仿佛在讨论一个逻辑上允许存在矛盾的虚拟世界。在那个世界里，世界是可以倚靠的、上帝是可能不爱世人的（当然，这些违背上帝圣洁或慈爱的属性，因此说是矛盾的），但是，作者要求人在这种情况下依然单单因为上帝的荣耀而爱上帝。</p><p>更让人灰心的是，作者在第三部分第一节中还指出：</p><blockquote><p>真圣徒所有的情感和体验都是属灵的，其他人的情感则完全没有属灵的本质。</p></blockquote><p>如果这句话是定义的话，那就真让人绝望了。因为这意味着，但凡心中有不属灵的情感，就不是真圣徒。在我自己读《宗教情感》之前，门训班里有姊妹说，读这本书的时候就感觉自己好像还没信耶稣。这感觉，在我心中也是强烈的。</p><p>不过，作者说这句话的语境是，强调圣灵使得圣徒产生全新的“生命原则”。或许作者本意并不是给出真圣徒的定义，正如作者在第一部分第二节最后，也指出：</p><blockquote><p>真圣徒的情感里面也有许多不属灵的情感，他们的宗教情感常常是混合的，多数不是来自上帝的恩典，而是来自人属血气的本性。</p></blockquote><p>然而无论如何，我自己省察自己，可以明显感觉自己离作者所描述的真宗教情感真的太远，甚至不能达到他所批判的境界。虽然不乏灰心，但也正如作者所说，自我省察虽然有益，但不能真的培养自己的宗教情感；我们应该去行动，做该做的事，也就是更殷勤地操练属灵生活并且服事教会。读《宗教情感》，至少让我明白了我该向着什么方向去努力，好过在黑暗中行走，不知目的地为何处，以至于找了赝品当做真品。愿主帮助我操练我的宗教情感，阿们。</p><h2 id="第三部分门训"><a href="#第三部分门训" class="headerlink" title="第三部分门训"></a>第三部分门训</h2><h4 id="第一章-圣灵特殊的感动"><a href="#第一章-圣灵特殊的感动" class="headerlink" title="第一章 圣灵特殊的感动"></a>第一章 圣灵特殊的感动</h4><p>因圣灵的工作，为信徒创造了一种全新的 <strong>感官</strong>，这感官能使人感受到神圣事物的美好。这感官既是“全新的”，就与其他一切人本来所有的感官不同，正如视觉、味觉、嗅觉之间完全不同。尽管视觉感受到的悦目、味觉感受到的甜、嗅觉感受到的香之间存在共性，即都是正面的情感，因此也可以互相描述，但本质上是不同的。<strong>属灵感官</strong> 也是一样，它能体验到神圣事物的美好，和属血气的感官感受到的美好（甚至可能也是神圣事物的美好），有共性，但本质上不同。</p><h4 id="第二章-上帝美善的本质"><a href="#第二章-上帝美善的本质" class="headerlink" title="第二章 上帝美善的本质"></a>第二章 上帝美善的本质</h4><p>人首先要以上帝本身的美好而爱上帝，其次才发现上帝为信徒预备的救赎计划竟然是对信徒有益的。两者的主次关系不可颠倒。</p><h4 id="第三章-宗教的道德之美"><a href="#第三章-宗教的道德之美" class="headerlink" title="第三章 宗教的道德之美"></a>第三章 宗教的道德之美</h4><p>在神圣事物各样美好属性中，<strong>圣洁</strong> 是首要的。能否感受到圣洁（或者说圣洁在感受中所占的比重），可以帮助判断是否出于属灵感官。毫无恩典的人也能感受到上帝的威严、伟大、全能，即使魔鬼也是如此，但他们对上帝的圣洁则毫无感觉。</p><h4 id="第四章-圣灵的光照"><a href="#第四章-圣灵的光照" class="headerlink" title="第四章 圣灵的光照"></a>第四章 圣灵的光照</h4><p>第四章强调的是 <strong>理性</strong> 和 <strong>感性</strong> 在信仰中的关系，提出了 <strong>属灵的理解力</strong> 这一概念。属灵的理解力，非常类似第一章所描述的 <strong>属灵感官</strong>，但是属灵理解力相对更强调 <strong>理性之光</strong> 在我们对属灵事物感受中所发挥的作用。理性之光是属灵情感的必要基础，没有理性的情感绝不可能是真属灵情感；当然，理性之光也不必然导向属灵情感（圣灵有普遍恩典）。但即便如此，作者依然强调在属灵的理解力中，对属灵之美的 <strong>感受能力</strong> 是要优先于对属灵事物的 <strong>推断能力</strong> 的。<br>然后，作者论述这种理解力与前三章内容的关系。具体地，强调了</p><ol><li>理解力的对象是道德美和圣洁，并因此而爱上帝。</li><li>明白神圣事物的荣耀是一切知识的基础。</li><li>（仅有）理性光照和救赎启示的区别。</li><li>将属灵感官和理解力引申为 <strong>属灵品味</strong>，一种类似直觉但符合属灵理性的判断能力。</li></ol><p>总的来说，合乎圣经地去追求属灵知识是非常重要的，单纯依赖感性是靠不住的。但是，我们还是需要明白，理性的建立还是为了服务属灵情感，一切都是为了更多地去认识神，并以神为乐。</p><h4 id="第五章-属灵的确信"><a href="#第五章-属灵的确信" class="headerlink" title="第五章 属灵的确信"></a>第五章 属灵的确信</h4><p>如果有属灵的确信，那它必然对我们的生命产生统管的作用。属灵确信必须是合理的，不能单纯来自文化思潮或者理性论证，而必须采用一种“内证”的方式。<br>上帝也迫切地想要通过属灵事物的圣洁之美让我们认出他，并预备了充分的证据，也就是属灵的内证；这样的证据在可靠性上远超过从历史、文献、研究中得来的证据。<br>属灵的确信，很大程度上依赖于属灵感官对圣洁之美的感受、属灵判断力对圣洁之美的理解。<br>其实，如果真的有确信，我们一切的行为都将有本质改变。毕竟，属灵事物与我们的关系过于重大，以至于地上的一切利益都算不得什么。很多时候，我省察自己，其实都觉得自己的信心都称不上确信，还不如对明天太阳照常升起的信心，这似乎说明我对太阳升起的体验不如属灵体验的程度？如果说上帝预备的证据是极其充分的，那我却常常看不见，真如瞎眼的。</p><h4 id="第六章-福音的谦卑"><a href="#第六章-福音的谦卑" class="headerlink" title="第六章 福音的谦卑"></a>第六章 福音的谦卑</h4><p>其实我感觉自己最容易犯的罪就是骄傲的罪，因为总是习惯让自己处在一个自我感觉良好的状态中，也希望在人面前获得称赞，甚至为此去“表演”谦卑。今天分享的律法主义精神、看重自己属灵知识和体验、热衷于宣告自己的义等，我都有过。<br>真的谦卑是要认识自己的罪是何等的大，罪本身是何等的可恶，以至于自己无论遭受什么，都算不得什么（照着我们配受的，我们的担子是轻省的），所以甘心乐意处于任何环境。</p><h2 id="恩典情感在人里面的工作原理：为什么会导致行为上的果实？"><a href="#恩典情感在人里面的工作原理：为什么会导致行为上的果实？" class="headerlink" title="恩典情感在人里面的工作原理：为什么会导致行为上的果实？"></a>恩典情感在人里面的工作原理：为什么会导致行为上的果实？</h2><p>在《宗教情感》第三部分中，可能有这样一条脉络：</p><ul><li>圣灵通过感动人心，为信徒建立 <strong>属灵感官</strong>（第一章）。</li><li>这种属灵感官也是符合圣经的理性检验的，在这一层面上也被称为 <strong>属灵判断力</strong>（第四章）。</li><li>这种属灵感官能够感受属灵事物，尤其是属灵事物的道德之美，并且集中体现为 <strong>圣洁之美</strong>（第三章）。</li><li>借由这种属灵感官，人可以因 <strong>上帝的美好本质</strong>，也就是圣洁而爱上帝；而不是因上帝赐给人的好处（无论是普遍护理还是特殊救恩）而爱上帝（第二章）。</li><li>借由属灵感官与上帝建立关系，从而用圣灵内证的方式建立 <strong>属灵的确信</strong>（第五章），弃绝律法主义、操练 <strong>福音的谦卑</strong>（第六章）；进而持久性地 <strong>改变本性</strong>（第七章），有份于 <strong>基督的性情</strong>（第八章），为罪忧伤并有 <strong>温柔的心灵</strong>（第九章）；最终表现出比例和谐、<strong>具有美感的属灵情感</strong>（第十章）。</li><li>至此，圣徒也不会感到满足而停止追求，而是 <strong>不断渴慕更加属灵</strong>，因为圣徒真爱圣洁事物（第十一章）。</li><li>总结来说，圣徒因圣灵感动建立起属灵感官，从而感受到属灵事物的圣洁之美，并因此爱上帝；然后在与上帝和属灵事物相交的过程中培养起圣洁的属灵情感，并不断追求。这些圣灵工作的外在表现就是，圣徒愿意有 <strong>圣洁行为</strong>，结出果实来（第十二章）。</li></ul><p>可以说，行为是最外在的，而圣灵在人心里的工作是最内在的，由内而外依次是：圣灵工作 -&gt; 属灵感官/判断力 -&gt; 圣洁情感 -&gt; 圣洁行为。</p><h2 id="《宗教情感》中所描述的恩典情感的标志成为新的律法？"><a href="#《宗教情感》中所描述的恩典情感的标志成为新的律法？" class="headerlink" title="《宗教情感》中所描述的恩典情感的标志成为新的律法？"></a>《宗教情感》中所描述的恩典情感的标志成为新的律法？</h2><p>《宗教情感》中批判了很多看似属灵但虚假的情感模式，也就是其第二部分所讨论的。这其中很多表现可能是我们以往所竭力追求的，比如热烈的情感、有丰富的宗教知识、经文忽然进入头脑、确信自己得救，以及因知道上帝救赎自己离开地狱、上天堂而爱上帝等。现在，读完《宗教情感》，我们知道这一切都不是恩典情感的可靠标志。</p><p>此时，我们是否会转而追求第三部分中的恩典情感的标志呢？当然，爱德华兹所描述的这些标志其实是非常严苛的，如果不是真的出于恩典，其情感是很难符合这些标志的。但问题在于，我们已经知晓了这些标志，会不会以一种律法的心态去追求这些标志呢？比如，我们是否会特意去想象上帝本身的美善，不断自我强化这种印象，然后宣称自己因上帝的美善而爱上帝呢？并且，我们还可能批判那些不这样行的信徒……如果这样，那么《宗教情感》这本书就成了一部新的律法。</p><p>然而，我们知道，律法虽是好的，但律法主义却常常绊倒人。《宗教情感》给出的恩典情感标志，只是让我们自我省察用的，而不是以律法的心态去遵守。一方面是确实无法完全遵守（就像无法遵守律法一样），另一方面遵守律法永远无法使得我们得救。我们要得救，终究只有一条道路，就是基督。</p><p>所以，如果我们达不到《宗教情感》的标准，其实也不必太过沮丧（？）。毕竟，我们得救只在乎恩典，而不是是否达到这些标准。人都是软弱的，无法遵行律法，也无法遵行这些恩典情感的标准；然而，基督已经为我们成就了这一切我们无法成就的。我们当仰望基督，将他为我们成就的义批戴在自己身上。</p><h2 id="《宗教情感》最后对圣洁行为的强调是律法主义吗？"><a href="#《宗教情感》最后对圣洁行为的强调是律法主义吗？" class="headerlink" title="《宗教情感》最后对圣洁行为的强调是律法主义吗？"></a>《宗教情感》最后对圣洁行为的强调是律法主义吗？</h2><p>爱德华兹在书的最后其实已经直接回答了这个问题，他强调：圣洁行为是上帝恩典的 <strong>标志</strong>，是上帝白白赐下信心的同时，白白附赠给我们的。反之，如果把行为当做赚取上帝恩典的 <strong>工价</strong>，才违背因信称义，这种情况下的信徒突出表现就是自夸。恩典的本质（白白的恩典）和圣洁行为的必要性，在圣经中并行不悖；后者绝不会降低前者的地位。</p><p>然而，爱德华兹阐释的是理论上的逻辑关系，确实没有问题。但在实践中，我们</p><ul><li>是不是会为了证明自己有这样的标志，而勉励自己去遵行律法呢？（爱德华兹也这样鼓励）</li><li>是不是发现自己无法遵行时，又深感气馁呢？（人在地上的时候几乎不可能完全成圣，甚至按爱德华兹所说，真信徒会不断深入地认识自己的罪）</li><li>如果行为是最主要证据，那是不是会怀疑自己没信心、没得救呢？（爱德华兹也鼓励这样自我省察）</li></ul><p>上述心态在我们使用律法主义时，几乎一模一样。那么，当我们看重行为时，就会“在直观上”觉得恩典不是白白的。虽然我们可以在理性上认识到恩典是白白的，但感性上却完全不是这个样子。爱德华兹所强调的“属灵行为是恩典的标志，而不是工价”，看起来不过是调换了行为和恩典的顺序：</p><ul><li>律法主义：行为在前，恩典在后</li><li>因信称义：恩典在前，行为在后</li></ul><p>现在，上帝固然不是因我们的行为而把恩典赏赐给我们，而是“借”给我们恩典好叫我们“还”行为。这其实就是我小时候未清晰认识因信称义之前的感觉：恩典是白白的，但我没有好行为（严格的定义是存在坏行为），所以我在恩典之外。</p><p>所以，对因信称义的认识永远是需要最先被建立起来的，但在建立起来之后，也需要进一步认识行为的意义。明显，《宗教情感》是写给那些对因信称义有认识的信徒的。无论我们的属灵实践成功与否（在初期可能更多的是失败），我们都应该常常使用因信称义，至少不让我们自暴自弃。</p><p>另一方面，还需要特别操练 <strong>谦卑</strong>。要知道无论怎么样的行为，都既不足以“换取”，也不足以“偿还”恩典——人在上帝面前就是毫无价值的，人的行为也毫无价值，怎么能“换取”或“偿还”上帝独生子为我们舍弃生命呢？因此，关键问题绝不是行为和恩典在这场人心所臆想“交易”中的交割顺序，而在于根本不存在这样的“交易”，因为世界上没有比这更不等价的交易了。从价值上看，毫无疑问恩典就是白白的。</p><p>然而，读完这本书的直观感受还是气馁，仿佛自己根本没信……愿主帮助我。</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;2020年初寒假，《宗教情感》读后感&lt;br&gt;</summary>
    
    
    
    <category term="信仰" scheme="https://syuoni.github.io/categories/%E4%BF%A1%E4%BB%B0/"/>
    
    
    <category term="基督教" scheme="https://syuoni.github.io/tags/%E5%9F%BA%E7%9D%A3%E6%95%99/"/>
    
    <category term="《宗教情感》" scheme="https://syuoni.github.io/tags/%E3%80%8A%E5%AE%97%E6%95%99%E6%83%85%E6%84%9F%E3%80%8B/"/>
    
    <category term="清教徒" scheme="https://syuoni.github.io/tags/%E6%B8%85%E6%95%99%E5%BE%92/"/>
    
  </entry>
  
  <entry>
    <title>《宗教情感》读书笔记</title>
    <link href="https://syuoni.github.io/posts/Religious-Affections-notes/"/>
    <id>https://syuoni.github.io/posts/Religious-Affections-notes/</id>
    <published>2020-01-28T12:49:01.000Z</published>
    <updated>2020-04-16T13:25:14.000Z</updated>
    
    <content type="html"><![CDATA[<p>2020年初寒假，《宗教情感》读书笔记。</p><p>第一遍阅读从1月28日开始，到3月27日结束，历时正好两个月。读这本书的过程中，无时无刻不感灰心气馁，仿佛自己从来没信耶稣一般；也更新了自己好多对信仰的认识。我愿意相信这是个去芜存菁的过程——剔除那些盲目的“信心”，虽然在感觉上很糟糕，但终究好过永远陷在那些虚妄的认知里还感觉良好。</p><p>在这段时间里，还遇见了上帝为我预备的另一半，原来她早就出现在我的生命中。倘若我在四年之前悬崖勒马，也不至于“在好些医生手里受了许多的苦”。感谢上帝管教我、带领我回来，也在这个过程中建立我的生命，以至于如今我能清楚地认识她就是上帝为我预备的；也感谢上帝，她竟然一直等候到如今。</p><p>顺便完成了令人头秃的学位论文的理论部分，完成了初稿和预答辩，目前期待毕业中。</p><p>愿荣耀归于至高神！</p><a id="more"></a><h2 id="第一部分-情感的本质及其在宗教中的重要性"><a href="#第一部分-情感的本质及其在宗教中的重要性" class="headerlink" title="第一部分　情感的本质及其在宗教中的重要性"></a>第一部分　情感的本质及其在宗教中的重要性</h2><h3 id="一-关于情感的开场白"><a href="#一-关于情感的开场白" class="headerlink" title="一　关于情感的开场白"></a>一　关于情感的开场白</h3><blockquote><p>你们虽然没有见过他，却是爱他；如今虽不得看见，却因信他就有说不出来、满有荣光的大喜乐。（彼前 1:8）  </p></blockquote><p>试炼的三重好处：</p><ul><li>凸显宗教的真实性、区别真假宗教</li><li>彰显宗教的美（美德、荣耀）</li><li>净化并加强宗教</li></ul><p>两种情感使得上述益处得以显明：</p><ul><li>爱（爱基督）：基督徒爱那看不见的，并舍弃可见之物</li><li>喜乐（以基督为乐）<ul><li>来自基督</li><li>不同于世俗之乐，满有荣光的</li></ul></li></ul><p>因此，真宗教很大部分在于圣洁的情感。</p><h3 id="二-真宗教很大部分在于圣洁的情感"><a href="#二-真宗教很大部分在于圣洁的情感" class="headerlink" title="二　真宗教很大部分在于圣洁的情感"></a>二　真宗教很大部分在于圣洁的情感</h3><ul><li><p>情感是什么？</p><ul><li>情感就是人心中意向（Inclination）和意志（Will）较活跃而明显的活动。在看待事物时，不作为旁观者，而能有态度（喜欢/不喜欢、愉悦/厌恶、赞成/反对）。</li><li>情感有倾向和程度之分；程度高时会引起身体和血气的反应。</li><li>情感所居在于心灵，而非身体。</li></ul></li><li><p>真宗教很大部分在于情感</p><ul><li>情感的定义和本质就决定如此<ul><li>圣经要求我们尽心爱主</li><li>宗教重要性极高，因此如果情感不强烈，两者就不相称<ul><li>也只有在宗教中，不冷不热才显得特别可憎</li></ul></li><li>宗教的情感当胜过肉体和情欲</li></ul></li><li>情感是人行为的泉源<ul><li>人宗教活动的泉源也是宗教情感</li></ul></li><li>宗教掌管人心的程度不超过其感动人心的程度<ul><li>如果宗教不感动人心，人对宗教就是无动于衷的</li></ul></li><li>圣经用情感描述宗教<ul><li>敬畏、盼望、爱、恨、渴慕、忧伤、感恩、怜悯和热心</li></ul></li><li>圣经把真宗教总结为爱<ul><li><blockquote><p>耶稣对他说：“你要尽心、尽性、尽意，爱主你的　神。这是诫命中的第一，且是最大的。其次也相仿，就是要爱人如己。这两条诫命是律法和先知一切道理的总纲。”（太22:37-40）</p></blockquote></li><li><blockquote><p>爱人的就完全了律法。（罗13:8）</p></blockquote></li></ul></li><li>圣经中圣徒的信仰很大部分是圣洁的情感<ul><li>大卫的诗篇</li><li>保罗的书信</li><li>约翰的书信</li></ul></li><li>耶稣表达的圣洁情感</li><li>天上的宗教很大部分在于情感<ul><li>圣洁而强烈的爱和喜乐</li></ul></li><li>教会礼仪和信徒的宗教责任是情感的表达<ul><li>祷告是为了感动自己的心</li><li>诗歌是为了打动我们的情感</li><li>圣餐礼是为了我们受到感动</li><li>讲道（而非神学书籍）来打动人心</li></ul></li><li>罪主要在于人的心硬（不受感动的心）</li></ul></li><li><p>宗教的在圣徒心中的真实性不一定与情绪的热烈程度成正比</p><ul><li>真圣徒也有属血气的情感</li><li>不能看当前情感的强烈程度，而要看情感习惯的固定强度（不一定与外在表现或内在效果成正比）</li></ul></li></ul><h3 id="三-教义推论"><a href="#三-教义推论" class="headerlink" title="三　教义推论"></a>三　教义推论</h3><ul><li><p>完全摒弃一切宗教情感，或完全依赖强烈的情感，都不可取</p><ul><li>理性上对教义的认识（光）和宗教情感（热），两者都不可或缺</li><li>如果对宗教中那些大事有正确认识，人心必然受到感动</li><li>情感丰富不一定有真宗教，但毫无情感则必定没有</li></ul></li><li><p>使得人心感动的蒙恩之道是正确的</p><ul><li>光靠宗教书籍是不够的</li></ul></li><li><p>认识到自己在上帝面前的羞耻和恐惧</p><ul><li>我们常常对世俗之事情感过于敏感，却对宗教之事情感麻木</li><li>情感就应当尽可能地被用于宗教（而非世俗之事），这也是上帝赋予人情感的目的</li></ul></li></ul><h2 id="第二部分-无法证明宗教情感是否出于恩典的一些现象"><a href="#第二部分-无法证明宗教情感是否出于恩典的一些现象" class="headerlink" title="第二部分　无法证明宗教情感是否出于恩典的一些现象"></a>第二部分　无法证明宗教情感是否出于恩典的一些现象</h2><p>并非一切受宗教事务的感动都是真的宗教情感。因此，需要分辨宗教情感的真伪。</p><h3 id="一-宗教情感热烈"><a href="#一-宗教情感热烈" class="headerlink" title="一　宗教情感热烈"></a>一　宗教情感热烈</h3><ul><li><p>真宗教情感应该是热烈的</p><ul><li>没道理限制自己受到宗教感动的程度</li><li>圣经中对宗教情感热烈程度的描述</li><li>天上圣徒的宗教情感是热烈的</li></ul></li><li><p>有些高涨的情感并非属灵情感</p><ul><li>有些情感热烈，但转眼就忘记<ul><li>加拉太基督徒</li><li>以色列人出埃及时，见神迹时情感热烈，但转眼就拜金牛犊</li><li>犹太人在耶稣进入耶路撒冷时欢呼</li></ul></li></ul></li></ul><h3 id="二-身体的生理反应强烈"><a href="#二-身体的生理反应强烈" class="headerlink" title="二　身体的生理反应强烈"></a>二　身体的生理反应强烈</h3><ul><li>情感越强烈，就可能引起越强烈的生理反应，但这无法判断出自哪一类情感<ul><li>属血气的情感也能引起强烈的生理反应</li><li>强烈的生理反应也可能是属灵情感引起的<ul><li>圣经的描述：发抖、叹息、成病、呼吁、切慕、渴想等</li></ul></li></ul></li></ul><p>血肉之躯太软弱，尤其不适合属灵情感和属天情感剧烈运行（太26:41; 林前15:43,50）。</p><h3 id="三-善于谈论宗教"><a href="#三-善于谈论宗教" class="headerlink" title="三　善于谈论宗教"></a>三　善于谈论宗教</h3><ul><li>善于谈论宗教，无法判断是健谈浮夸（法利赛人的作风）、还是为圣灵感动<ul><li>善于谈论，说明人深受感动，但不能判断是否出于恩典</li><li>受施洗约翰洗礼而感动的，有并未领受恩典的</li><li>有渴慕耶稣讲道的，也并未悔改</li></ul></li></ul><h3 id="四-情感源于外界"><a href="#四-情感源于外界" class="headerlink" title="四　情感源于外界"></a>四　情感源于外界</h3><ul><li><p>恩典本身来自上帝外源性的运行，而不是人自己的努力，所以真宗教情感的产生来自外界才是合理的</p><ul><li>上帝要显明人的软弱，叫人无可自夸；显明人无法自救，唯独倚靠上帝<ul><li>上帝救以色列人出埃及</li><li>上帝帮助基甸击败米甸人（士师记第7章）</li><li>上帝帮助大卫击败歌利亚人</li></ul></li><li>圣灵的工作是人能察觉的<ul><li>人能够分辨圣灵的感动和属血气的感动之间的不同</li><li>圣灵没有必要“不让人察觉地”工作</li></ul></li></ul></li><li><p>情感不是自己营造出来的，无法证明一定来自恩典</p><ul><li>不能依赖超自然的外源性感动，尤其是在蒙恩之道以外的</li><li>邪灵也能感动人，并且冒充圣灵感动人</li><li>圣灵有普遍性的感动，但不一定都是救赎性的</li><li>有些人身体软弱喜欢幻想</li></ul></li></ul><h3 id="五-情感伴随经文进入头脑"><a href="#五-情感伴随经文进入头脑" class="headerlink" title="五　情感伴随经文进入头脑"></a>五　情感伴随经文进入头脑</h3><ul><li>宗教情感伴随着经文进入头脑，不足以判断是否属灵<ul><li>要分辨经文及其教导的内容，而不能以经文进入头脑这一方式作为判断依据</li><li>经文是纯全无缪的，但从经文联想得到的情感并不一定正确应用了经文，可能是滥用经文的结果</li><li>魔鬼可能使用经文欺骗我们<ul><li>魔鬼曾经用经文试探耶稣（此处，魔鬼对经文的应用就是错误的应用）</li></ul></li><li>异端的教师也会曲解经文，用来败坏人心</li></ul></li></ul><h3 id="六-情感包含爱意"><a href="#六-情感包含爱意" class="headerlink" title="六　情感包含爱意"></a>六　情感包含爱意</h3><ul><li>情感里包含爱，不一定能证明其出于救恩<ul><li>魔鬼虽然没有爱，但是可以伪装出爱</li><li><blockquote><p>只因不法的事增多，许多人的爱心才渐渐冷淡了。惟有忍耐到底的，必然得救。（太 24:12-13）</p></blockquote></li><li>基督徒对于主内弟兄姊妹的爱也可能掺假</li></ul></li></ul><h3 id="七-多种情感交织"><a href="#七-多种情感交织" class="headerlink" title="七　多种情感交织"></a>七　多种情感交织</h3><ul><li>多种宗教情感交织，不一定能证明其包含恩典<ul><li>假宗教也有情感，在表面上与恩典情感并无二致</li><li>既然人在属血气的状态下能表现出每一种宗教情感，那么也能同时表现出多种宗教情感<ul><li>耶稣荣入耶路撒冷时，百姓的情感</li></ul></li><li>爱是一切情感的泉源<ul><li>爱从基督而来，则一切情感都是真的</li><li>爱从血气而来，也能衍生出各种情感，但都不是真宗教情感</li></ul></li></ul></li></ul><h3 id="八-宗教体验顺序"><a href="#八-宗教体验顺序" class="headerlink" title="八　宗教体验顺序"></a>八　宗教体验顺序</h3><ul><li><p>上帝拯救罪人时，会首先使人认识自己的罪、并且需要拯救，此时人会痛苦；然后大施拯救，使人感到安慰和喜乐 </p><ul><li>以色列人在埃及、旷野的受苦</li><li>血漏妇人在医生手里受苦</li><li>迦南妇人完全自卑</li><li>保罗遭遇的危险</li></ul></li><li><p>上帝向圣徒显现，也常常先令人恐惧，然后显出安慰</p></li><li>这也是上帝对付人的最普遍方式</li><li><p>圣经中有很多例子是，人先认罪痛苦，然后得到安慰</p><ul><li>耶路撒冷众人“觉得扎心”</li></ul></li><li><p>认罪、安慰、喜乐按照顺序而来，无法证明情感的真伪</p><ul><li>恐惧感不等于认罪<ul><li>有的人仅仅害怕地狱和魔鬼，但没有看到自己的罪</li><li>魔鬼也能使人感到恐惧</li><li>某些人的身体和性格上的特质导致其容易恐惧</li></ul></li><li>真的受圣灵感动而认罪之后，也不一定导致真的安慰<ul><li>人心可以消灭圣灵的感动</li></ul></li><li>魔鬼能伪造人领受恩典后的谦卑，就是假谦卑<ul><li>扫罗在大卫面前认罪，是假谦卑</li><li>有些人自以为谦卑，其实不过是灰心丧气，因为他们曾经依赖的东西证明是靠不住的；这种顺服不是绝对顺服，还隐藏着讨价还价，只是难以察觉。</li></ul></li><li>魔鬼能伪造一切情感，当然也能按顺序伪造情感来欺骗人</li><li>最终不得救得人经历的种种情感和悔罪都不是属灵的<ul><li>情感及其顺序都与得救与否没有必然联系</li></ul></li><li>按作者的经验，按顺序出现的情感不是恩典的确据，尽管其常见于真信徒</li></ul></li><li><p>一个人表面上缺乏步骤，也不能证明其不信主</p><ul><li>圣灵的工作是神秘莫测的</li><li><blockquote><p>圣灵在圣徒里面所做的改变一开始的时候更像是一种混乱，叫圣徒不知如何是好。（谢泼德）</p></blockquote></li><li>人决不能试图“引导”圣灵按步骤工作</li><li>真信徒在回忆自己得救的过程中，常常会甄选出那些符合步骤的，并反复强调和讲述；而忽视那些不符合步骤的</li><li>圣灵工作的关键在于圣灵果子的本质，而不是结果子的方式</li></ul></li></ul><h3 id="九-参加宗教活动"><a href="#九-参加宗教活动" class="headerlink" title="九　参加宗教活动"></a>九　参加宗教活动</h3><ul><li><p>宗教情感能促使人长期、乐意参加宗教活动、履行敬拜责任</p><ul><li>先知亚拿昼夜侍奉上帝</li><li>初代基督徒同心合意、恒切在殿里</li><li>但以理一天三次认真祷告</li><li>大卫作诗篇</li></ul></li><li><p>大量参与宗教活动，不能证明是否是真宗教情感</p><ul><li>旧约以色列人、新约法利赛人的敬拜</li><li>假宗教也能使人热心参与宗教活动，甚至离群索居，献上所有时间来灵修祷告</li><li>希律王喜欢听施洗约翰的讲道，众人也“暂时喜欢他的光”</li></ul></li></ul><h3 id="十-开口赞美上帝"><a href="#十-开口赞美上帝" class="headerlink" title="十　开口赞美上帝"></a>十　开口赞美上帝</h3><ul><li>宗教情感使人开口赞美上帝，但这也无法确认情感的本质<ul><li>福音书里，众人看见耶稣的神迹后，都“归荣耀于上帝”</li><li><blockquote><p>他们的口多显爱情，心却追随财利。（以西结书 33:31）</p></blockquote></li><li><blockquote><p>你们因耶和华言语战兢的人当听他的话：你们的弟兄，就是恨恶你们、因我名赶出你们的，曾说：“愿耶和华得荣耀，使我们得见你们的喜乐”，但蒙羞的究竟是他们！（以赛亚书 66:5）</p></blockquote></li></ul></li></ul><h3 id="十一-确信自己得救"><a href="#十一-确信自己得救" class="headerlink" title="十一　确信自己得救"></a>十一　确信自己得救</h3><ul><li><p>圣徒可以有完全、绝对的得救确据</p><ul><li>上帝将特殊恩宠清楚地启示给圣徒<ul><li>挪亚、亚伯拉罕、以撒、雅各、摩西、但以理</li></ul></li><li>约伯、大卫、希西家对自己信心的宣告</li><li>耶稣明白地指示门徒（约 15:11, 16:33, 17:13）</li><li>保罗在书信中宣告自己将得到天上的赏赐</li><li>上帝愿意圣徒还在地上生活的时候就确信自己必将承受永生</li><li>并非极端情况下（如殉道）才可以确信自己得救<ul><li>多数基督徒都应该有这样的确信</li></ul></li></ul></li><li><p>确信自己得救，这样的情感不一定就是出于恩典</p><ul><li>法利赛人会高调地宣告自己是圣徒</li><li>良知被蒙蔽，认罪的信就死了，假情感却高涨起来<ul><li>没有真圣徒的谨慎感</li><li>不知道自己的盲目和内心诡诈</li><li>魔鬼攻击真圣徒的真盼望，却不攻击假盼望</li><li>不像真圣徒那样看到自己的败坏</li></ul></li><li>两种假冒伪善<ul><li>律法主义的假冒伪善：外在道德和宗教生活</li><li>福音派的假冒伪善：批评功德和自义，讲论白白的恩典，但却以这样的神学知识和“谦卑”为义</li><li>后者比前者更危险、更难以察觉、更难以醒悟</li><li>部分福音派的假冒伪善者可以一边犯罪，一边保持大无畏的盼望</li></ul></li><li>凭信心 vs. 凭眼见<ul><li>凭信心不是说，信靠上帝不需要先具备正确的属灵知识和体验</li><li>人相信上帝的程度不可能超过他认识上帝的程度</li><li>凭信心是指，在身处黑暗时，环境中看不见上帝应许实现的可能时，依然保持盼望</li><li>信心绝不是“相信自己已经得救”</li></ul></li><li>怀疑自己得救，并不等于不信<ul><li>缺乏得救的证据 -&gt; 应当更多操练信息、运用恩典</li><li>怀疑自己是否配得领受恩典</li><li>上帝对付人的方式特别奇妙，人无法理解，以至于觉得应许无法实现</li></ul></li><li>怀疑自己得救可能也是上帝的安排<ul><li>人在跌倒时，怀疑自己得救是好事；因为这使得人反省，并且因为 <strong>恐惧</strong> 而约束自己不犯罪，更关注属灵的事，最后通过 <strong>爱</strong> 来去除这样的 <strong>恐惧</strong>。</li><li><blockquote><p>爱里没有惧怕；爱既完全，就把惧怕除去。（约一 4:18）</p></blockquote></li></ul></li></ul></li></ul><h3 id="十二-人际关系良好"><a href="#十二-人际关系良好" class="headerlink" title="十二　人际关系良好"></a>十二　人际关系良好</h3><ul><li><p>上帝没有给人辨明谁是真信徒、谁是假信徒的能力</p><ul><li>尤其不要在人的灵魂这件事上论断人</li><li>只要人又敬虔的表现，就应该接纳并把他看做主内弟兄</li><li><blockquote><p>圣灵向众教会所说的话，凡有耳的，就应当听！得胜的，我必将那隐藏的吗哪赐给他，并赐他一块白石，石上写着新名，除了那领受的以外，没有人能认识。（启 2:17）</p></blockquote></li><li><blockquote><p>所以，时候未到，什么都不要论断，只等主来，他要照出暗中的隐情，显明人心的意念。那时，各人要从上帝那里得着称赞。（林前 4:5）</p></blockquote></li></ul></li><li><p>假信徒可以赢得教会中良好的人际关系</p><ul><li>假信徒的假情感，可以非常热烈，有各种貌似属灵的表现</li><li>假信徒的“圣洁”表现和经历，可以激发真信徒的共鸣</li></ul></li><li><p>人不应该以自己是否喜欢对方，来判断对方的属灵状况</p><ul><li>大卫因亚希多弗背叛他而不敢相信（诗 55:12-14）</li><li>耶稣教导我们用最终的果子来判断树木的好坏，而不是花朵</li><li>区分麦子和稗子很难，但区分特殊恩典和普遍恩典更难</li><li>基督徒可以误判别人是否真正得救，并不影响上帝借这样的错误运行恩典</li></ul></li></ul><h2 id="第三部分-恩典情感和圣洁情感的明显标志"><a href="#第三部分-恩典情感和圣洁情感的明显标志" class="headerlink" title="第三部分　恩典情感和圣洁情感的明显标志"></a>第三部分　恩典情感和圣洁情感的明显标志</h2><p>借助哪些现象或标志可以识别属灵和恩典情感？</p><ul><li>这些标志绝不是让人来辨别别人的情感真假</li><li>有些人几乎没有恩典，不应该指望借助这些标志得救</li><li>信徒不知道自己得救，可能有两种缺乏<ul><li>考察对象的缺乏：恩典过于低迷、软弱，以至于和假信心无法区分</li><li>考察能力的缺乏：人对属灵的事不明感</li></ul></li><li>反复自我审视并不能使自己得救<ul><li>人需要通过 <strong>行动</strong> （蒙恩之道、敬拜服事）来获取得救的确据</li></ul></li><li>作者也不鼓励使用这些标志来与假冒伪善者辩论</li></ul><h3 id="一-圣灵特殊的感动"><a href="#一-圣灵特殊的感动" class="headerlink" title="一　圣灵特殊的感动"></a>一　圣灵特殊的感动</h3><ul><li>属灵情感来源于圣灵的感动和运行，是超自然的</li><li><p>属灵 vs. 属血气/肉体/情欲</p><ul><li>属灵：恩典、圣灵</li><li>属血气：不敬虔、不圣洁</li></ul></li><li><p>属灵一词并非在讨论是否与人的灵魂相关，而是是否与 <strong>圣灵</strong> 有关；并且，受到圣灵 <strong>普遍的感动</strong> 并非属灵，受到圣灵 <strong>特殊的、恩典的、救赎性感动</strong> 才是属灵的</p><ul><li>只有在特殊感动中，圣灵才住在圣徒心中，与圣徒的灵 <strong>合而为一</strong>，成为他们 <strong>生命的原则</strong></li><li>只有在特殊感动中，圣灵才传递自己的本质、属神的性情给信徒</li><li>特殊感动是圣灵最崇高的工作，因为祂使受造物与上帝有份（彼后 1:4; 来 12:10）</li></ul></li><li><p>真圣徒所有的情感和体验都是属灵的，其他人的情感则完全没有属灵的本质</p><ul><li>属灵是全新的感受和感官（感受到属灵之事的能力），是不能靠改善、混合其他情感所能达到的</li><li>属灵意味着全新的生命原则，而圣灵的普遍感动可能改善人属血气的生命原则</li><li>属灵情感与属血气的情感可能有相似的部分，但本质不同<ul><li>人可以分别通过味觉和视觉获得积极或消极的情感，但两种感觉的本质不同</li></ul></li><li>属血气的人也能有全新的情感体验，但不一定就是属灵的<ul><li>例如，旧的情感原则运行到新的高度</li></ul></li></ul></li><li><p>通过想象来看见意象</p><ul><li>想象的印象：想象的意象非常强烈，仿佛真的感受到一样</li><li>圣经用意象和比喻描述圣灵，因为圣灵不可见<ul><li>光：属灵事物</li><li>看见：拥有属灵事物有清晰的认识</li><li>听见呼召：相信福音、相信基督</li></ul></li><li>这些用于比喻的意象并非说，人在生动的想象中“看见”“光”，“听见呼召”，就是属灵的</li></ul></li><li><p>无论是经文还是意象，出现方式的特殊性（通过想象看见意象，或经文忽然进入头脑）都和是否属灵没有必然关系</p><ul><li>想象得到的意象，即使进入头脑的方式特殊，但本质上和直接看到、听到没有高下之分；换言之，相当于教皇派信徒在教堂中看基督的画像。另外，魔鬼或者生理病痛也能引发人想象出意象</li><li>头脑中联想圣经话语，本身也无属灵之处；和直接阅读圣经，没有本质区别<ul><li>巴兰也知道上帝启示的话语来自上帝</li></ul></li><li>真正属灵的事，不在于它们的出现方式，而在于圣灵在信徒心中的运行效果本身是神圣的</li></ul></li><li><p>圣灵的见证/圣灵的印/圣灵的凭据：圣灵在圣徒心中动工产生的特殊效果，是属血气的人在仍属血气时所不可能体会的情感</p><ul><li>圣徒在地上因圣灵而体会到的光明、生命、圣洁、完美、喜乐和天上的圣徒是一样的，但程度不同</li><li><blockquote><p>圣灵与我们的心同证我们是上帝的儿女（罗 8:16）</p></blockquote></li></ul></li></ul><h3 id="二-上帝美善的本质"><a href="#二-上帝美善的本质" class="headerlink" title="二　上帝美善的本质"></a>二　上帝美善的本质</h3><ul><li><p>恩典情感首要的是神圣事物的美好本质，其次才可能伴随着这些事物与信徒自身的关系或利益，两者顺序不能颠倒</p></li><li><p>人爱上帝并以此为乐，所以人还是为了自己的喜乐？为了爱自己？</p><ul><li>不对。因为人首先得爱上帝，这件事成为人的喜乐是衍生的结果，而非起初的目的。</li><li>人爱上帝的体现可以是：连他自爱或追求自己的幸福也会使他渴慕上帝并以上帝为乐。</li><li>这不同于：以对方对自己的利益为基础而爱对方。</li><li><blockquote><p>你们若单爱那爱你们的人，有什么可酬谢的呢？就是罪人也爱那爱他们的人。（路 6:32）</p></blockquote></li><li>两者的区别在于究竟谁是因？谁是果？</li></ul></li><li><p>血气和自爱，通过激发感激之情，也能使人爱上帝</p><ul><li>扫罗一再因大卫饶自己性命而感激，但其中没有真正的爱；当然，不懂感恩就是更邪恶的。</li><li>当自爱成为爱上帝的基础，就是不承认上帝的自由和主权（似乎上帝非爱人不可），相当于臆造了一个“上帝”。</li><li>自爱甚至能驱使人因上帝对群体（而非其个人）显明的慈爱而感动</li></ul></li><li><p>属灵的感激之情 vs. 属血气的感激之情</p><ul><li>真感恩之情存在一个根基，就是因上帝本身的伟大而爱上帝<ul><li>真感恩并不完全排除自爱，但自爱绝不是根基</li></ul></li><li>人应该因为上帝良善的属性、白白的恩典而感动，不在于这恩典关乎自己的利益，而在于这恩典是上帝荣耀的一部分<ul><li>白白施与的恩典是神性完美道德的重要部分</li><li>不排除自爱在其中所发挥的辅助作用，但它服从更高的原则</li></ul></li><li><blockquote><p>我们爱，因为上帝先爱我们。（约一 4:19）</p><ul><li>这经文的重点不在于先后关系，而在于凸显上帝的爱的伟大</li><li>圣徒内心的爱也是上帝的恩赐</li><li>上帝的爱藉着基督的救赎之功得以显明，尤其彰显了其荣耀</li><li>上帝将荣耀启示给罪人，激发人心中的爱</li></ul></blockquote></li><li>对真正的圣徒而言，上帝本身的完美、荣耀、可爱就是他们爱上帝的充分理由；然后，他们才发现这教义于他们有利。<ul><li>他们专注于上帝本身，看不见自己和自己的属灵成就，并觉得花时间筹算如何炫耀成就时，是无法容忍的。</li></ul></li><li>假冒伪善者在喜乐之时，一贯地关注自己，谈论时也集中在自己的体验和成就，而缺乏对上帝、上帝的工作、基督的美好的谈论。<ul><li>他们的其他宗教情感，包括为罪忧伤、谦卑顺服也都出于自爱。</li></ul></li></ul></li></ul><h3 id="三-宗教的道德之美"><a href="#三-宗教的道德之美" class="headerlink" title="三　宗教的道德之美"></a>三　宗教的道德之美</h3><ul><li><p>真正圣洁情感的首要基础是神圣事物的 <strong>道德之美</strong>，即因这道德之美而产生的热爱之情</p></li><li><p>出于上帝的道德 vs. 自然的道德</p><ul><li>出于上帝的道德善恶：是否犯罪、悖逆上帝</li><li>自然的道德善恶：是否违背自然状态（如苦难）</li></ul></li><li><p>上帝的道德属性 vs. 自然属性</p><ul><li>道德属性：公义、慈爱、良善、信实，总结为 <strong>圣洁</strong></li><li>自然属性：全知、全能、永恒、无处不在，构成上帝的 <strong>威严</strong></li></ul></li><li><p>真宗教情感的根基在于神圣事物本身的美好本质，其中最首要的是 <strong>圣洁</strong></p><ul><li>圣徒爱上帝的每个属性，每个属性也都是美好而荣耀的，但圣洁是基础与核心</li><li>一切智慧生命/神圣事物的美好，首先在于其道德美好，也就是圣洁</li><li>没有圣洁，能力和知识反而显得丑恶；圣洁使其他一切属性变得更加美好</li><li>爱上帝必须从爱慕上帝的圣洁开始，而不是其他属性</li><li>圣洁必须通过属灵感官才能感受到</li><li>从反面来说，罪性仇视神圣事物，首先就是仇视其圣洁<ul><li><blockquote><p>光照在黑暗里，黑暗却不接受光。（约 1:5）</p></blockquote></li></ul></li><li>毫无恩典的人和魔鬼都可以认识到上帝的能力、威严，但由于没有属灵认知，对上帝的完美道德（尤其是圣洁）毫无感觉<ul><li>毫无恩典的人也能因看见上帝的能力和威严而赞美上帝</li></ul></li></ul></li></ul><h3 id="四-圣灵的光照"><a href="#四-圣灵的光照" class="headerlink" title="四　圣灵的光照"></a>四　圣灵的光照</h3><ul><li><p>恩典情感来自圣灵正确的光照，内心得到属灵光照才能正确理解神圣事物</p></li><li><p>圣洁情感更出自 <strong>理智和知识</strong></p><ul><li>两种情况：接受的属灵教训，受光照或实践知识</li><li>若情感并非源于理性之光，无论多热烈也不是属灵的<ul><li>源于个人想象的情感、经文忽然进入头脑、忽然的情绪高涨、身体出现生理变化，这些特殊形式均不能带来新知识</li></ul></li><li>即使确实是源于理性教导，也可能不是出于恩典的<ul><li>来源于圣灵的普遍光照，人借此提高了对宗教事物的理解能力</li></ul></li></ul></li><li><p>圣徒会有一种针对属灵事物的 <strong>理解力</strong>，而其他人则完全没有这种能力</p><ul><li><blockquote><p>然而，属血气的人不领会上帝圣灵的事，反倒以为愚拙，并且不能知道，因为这些事惟有属灵的人才能看透。（林前 2:14）</p></blockquote></li><li>这种新的感官能使人认识神圣事物的可爱之处（道德之美），从而成为人爱神圣事物的基础</li><li>这种理解力不仅涉及 <strong>推理能力</strong>，更重要的是对属灵之美的 <strong>感受能力</strong></li><li>只有认识到神圣事物的道德美，特别是基督身上和救赎计划里彰显出来的道德美，人才能理解基督作为中保的充分性；信徒对基督的认识才能超过魔鬼对基督的认识</li><li>不明白神圣事物的荣耀，那一切知识都是知识的影子，没有意义；正如没有圣洁，能力和知识就反而显得丑恶。</li><li>获得属灵感官会使人内心产生剧变，其强烈程度要远远胜于天生瞎眼的人获得视觉</li><li>圣灵为人建立属灵的 <strong>品味</strong>：人通过属灵感官来感受圣洁事物的美好，不需要通过任何推理。<ul><li>就像欣赏外在美貌，不需要分析外貌特征的精确比例；欣赏音乐，不需要分析每个音符的比例；欣赏美食，不需要分析食物的构成。</li><li>来自品味的判断是迅速而又准确的。具有属灵品味的人做出谦卑、温柔、仁爱等行为，效果远远好过一个没有属灵品味而依赖刻苦学习、推理的人。</li><li>来自属灵品味的判断，在事后也经得起规则和理性的检验，即符合圣经的标准</li><li>这完全不同于“上帝直接通过隐秘的启示直接命令”人如何去行。反面例子就是巴兰和扫罗。</li></ul></li><li>魔鬼无法直接知晓人的内心想法（这能力唯独属于上帝），所以常借助人身体血气的运行、头脑的幻想来攻击人。</li></ul></li><li><p>（对属血气之人）理性的光照 vs. 救赎的启示</p><ul><li>解释教义 vs. 品尝救恩</li><li><blockquote><p>我若有先知讲道之能，也明白各样的奥秘、各样的知识，而且有全备的信，叫我能够移山，却没有爱，我就算不得什么。（林前 13:2）</p></blockquote></li><li>上帝多次直接给巴兰/扫罗启示其旨意，但巴兰/扫罗没有属灵光照</li><li>对经文属灵的理解，就是理解 <strong>经文本来的含义</strong>，而不是为其新造一个意思。<ul><li>例如，当一个人想要去国外宣教，忽然想起耶和华对雅各下埃及的应许，并将这应许应用在自己身上。这就是自欺。</li></ul></li></ul></li></ul><h3 id="五-属灵的确信"><a href="#五-属灵的确信" class="headerlink" title="五　属灵的确信"></a>五　属灵的确信</h3><ul><li><p>真恩典情感伴随着属灵的确信：神圣事物完全属实、不容置疑</p><ul><li>对真信徒而言，看不见的属灵事物就像看得见的事物一样发挥作用；并且，由于属灵事物本身的重要性，它们统治信徒的情感、管理其一生。</li><li><blockquote><p>信就是所望之事的实底，是未见之事的确据。（来 11:1）</p></blockquote></li><li>受到感动、情绪高涨 vs. 对 <strong>福音真理</strong> 的确信</li><li>合理的确信<ul><li>基于真实证据、符合理性，而不是受到文化思潮影响下的确信</li><li>单纯因周围的基督教文化而确信福音，和因周围的伊斯兰文化而确信伊斯兰教，本质上并无区别，只是前者的内容碰巧是真的。</li></ul></li><li>即使确信来自理性，也可能仍然不属灵<ul><li>因理性和论证而赞同基督教，但内心仍然属血气，如卖耶稣的犹大</li></ul></li><li>属灵确信不仅在果子上（人的行为）上与属血气的不同，而且仅属于圣徒，属血气的人则根本没有</li><li>符合理性的判断，源于对事物本质的正确把握；而事物的本质正是上帝亲自揭示的</li></ul></li><li><p>心灵被圣灵光照后，会看见福音的神圣荣耀，并通过直接和间接的两种方式使人相信所看见的是神圣的</p><ul><li>荣耀本身作为证据，<strong>直接</strong> 使人相信事物的神圣性<ul><li>上帝的荣耀远超属世的一切美好，本身就促使人产生确信</li><li>上帝也愿意让神圣事物显现荣耀，使人认出来是出于上帝的<ul><li>人若无法认出，是因为他们在属灵上是瞎眼的</li></ul></li><li>属灵的品味（及其所品尝到的恩典的甘甜、罪的苦涩、救恩计划的完美），也使人产生确信</li><li>福音必须通过这种“内证”的方式使人产生确信，否则福音就无法使那些缺乏教育背景的人产生确信<ul><li>如果没有“内证”，他们就只能听信权威，但这就像跟随文化潮流的信仰一样，是不合理的</li><li>福音不是写给学者的。</li></ul></li><li>上帝为我们预备了充分的证据，而不是“可能成立的证据”，使我们相信恩典；这证据比从考古、历史、文献研究中得来的可靠得多。</li><li>历史上，绝大多数殉道的基督徒都不是通过推理和研究的方式相信福音的；采用推理和研究的方式护教后，教会的属灵光景也没有得到明显复兴</li><li>做基督的见证人，必须有“第一手资料”才能作证，所以必须通过圣灵“内证”的方式先使人产生确信。<ul><li><blockquote><p>我们所说的，是我们知道的；我们所见证 的，是我们见过的。（约 3:11）</p></blockquote></li></ul></li><li>外在的论证也是有价值的，可以用来唤醒不信的人，使他们认真思考。</li></ul></li><li>看见荣耀会 <strong>间接</strong> 影响人心，使人信服真理<ul><li>消除人内心的偏见（人在原始状态中对福音的敌意）</li><li>积极地帮助理性，使人更好地理解神圣事物</li></ul></li></ul></li><li><p>真恩典情感会伴随着属灵确信，但也有一些与此相关的假信心</p><ul><li>圣灵的普遍光照下，有些人会明显感受到宗教中属血气的内容，包括他们畏惧上帝的威严（但体会不到上帝的圣洁），以致于产生“确信”</li><li>基于奇特想象的，使人相信圣经启示的道理<ul><li>教皇派捏造神迹欺骗人，使人相信新约里的事情</li></ul></li><li>信心的根基在于人以为在教会里能获得好处（天堂）</li></ul></li></ul><h3 id="六-福音的谦卑"><a href="#六-福音的谦卑" class="headerlink" title="六　福音的谦卑"></a>六　福音的谦卑</h3><ul><li><p>真恩典情感伴随着出于福音的谦卑：基督徒感到自己必须向上帝交差，从而认识到自己彻底匮乏、可鄙、可憎</p></li><li><p>出于律法的谦卑 vs. 出于福音的谦卑</p><ul><li>出于律法的谦卑<ul><li>圣灵的普遍感动、促进属血气的良知</li><li>不认识、不恨恶罪，而只恨恶罪带来的惩罚</li><li>人被迫低声下气，心有不甘</li><li>没有生命的改变</li></ul></li><li>出于福音的谦卑<ul><li>圣灵的特殊感动、构建超自然的原则</li><li>上帝启示其道德之美，使人认识罪本身的可憎</li><li>人甘心顺服，内心自由、喜乐</li></ul></li><li>律法的谦卑并非无益，它是获得福音谦卑的渠道；正如宗教知识能帮助人走属灵真道。</li><li>整个救赎计划的目的（之一）就是使人产生真正的谦卑</li><li><blockquote><p>虚心的人有福了，因为天国是他们的。（太 5:3）</p></blockquote></li><li><blockquote><p>我实在告诉你们，你们若不回转，变成小孩子的样式，断不得进天国。所以，凡自己谦卑像这小孩子的，他在天国里就是最大的。（太 18:3-4）</p></blockquote></li><li><blockquote><p>凡自高的，必降为卑；自卑的，必升为高。（路 18:14）</p></blockquote></li></ul></li><li><p>基督徒舍己的责任（真谦卑）</p><ul><li>两点舍己的责任<ul><li>弃绝世俗的喜好，排斥属世的物质和娱乐<ul><li>隐士和修士也能靠着血气做到，但仍然是为了荣耀自己</li></ul></li><li>弃绝属血气的自高自大，放弃自己的尊严和荣耀，甘心情愿地倒空自己、放弃自己、忘记自己。</li></ul></li><li>真谦卑，正是一切假冒伪善者跌倒之处；他们往往热衷于在人面前宣告自己的卑微，但无法接受别人真的指出他们的不是。</li><li><strong>律法主义的灵</strong> 是极其诡诈的：人在批判他人律法主义时，往往自己就已经被律法主义胜过了。<ul><li>人在堕落前，律法主义的灵可能不是骄傲；但在堕落后，律法主义的灵一定是骄傲。</li><li>以因信称义之名批判律法主义，并沾沾自喜，也是一种极其危险的律法主义。</li><li><blockquote><p>人心比万物都诡诈，坏到极处，谁能识透呢？（耶 17:9）</p></blockquote></li></ul></li><li>属灵体验只能作为蒙恩的证据，而决不能以此接近上帝、期望上帝回报</li></ul></li><li><p>属灵骄傲的两个标志</p><ul><li><strong>第一个标志</strong>：骄傲的人喜欢居首位、指教人、当师傅。真谦卑则觉得自己不配教导人，而愿意接受别人的教导，看别人比自己强；并且在说的时候，也谨慎战兢，不喜欢用教训人的口气。<ul><li><blockquote><p>只要存心谦卑，各人看别人比自己强。 （腓 2:3）</p></blockquote></li><li><blockquote><p>你们各人要快快地听，慢慢地说。（雅 1:19）</p></blockquote></li><li><blockquote><p>不要做多人的师傅。 （雅 3:1）</p></blockquote></li></ul></li><li>真圣徒即使有超乎他人的宗教经历，也依然看别人更强，看自己的恩典和良善为小，看自己的罪为大<ul><li>真的恩典使人明白自己离本应有的圣洁样式（上帝的标准）还差得远；愈发发现上帝的爱如此之多，自己的爱如此之少，以至于自己是一个“特例”，众人都应该强于自己（他只能看其他信徒的外表，却省察自己的内心）。<ul><li>圣徒内心的爱是随着其认识上帝的程度而增加，但和上帝本身的爱比起来，永远是极其渺小的</li></ul></li><li>当圣徒认识到自己离上帝的标准如此之远，就认识到自己的败坏有多严重。</li><li>信徒最小的罪里的病态扭曲，也显得很大，远远超过信徒最大的圣洁。<ul><li>最小的罪，得罪的也是无限的上帝，所以是无限的；最大的圣洁，因为人本身的有限，圣洁也是有限的</li></ul></li><li>真正的救赎性认识，使人不仅勇于承认过往的过犯，也承认当下内心的邪恶。救赎性认识可以遏制人犯罪的欲望（恶毒、嫉妒、贪婪、淫荡等），但显露人隐藏和亏欠的罪（缺乏爱、谦卑和感恩）。</li><li>真正的圣徒可能认识到自己比他人强，但这对他而言并不是显然的（需要谨慎推理），而且也绝不会占据他的主要想法。</li><li>一个人越有属灵的知识，就越感到自己的无知。<ul><li><blockquote><p>若有人以为自己知道什么，按他所当知道的，他仍是不知道。（林前 8:2）</p></blockquote></li></ul></li></ul></li><li><strong>第二个标志</strong>：人高估自己的谦卑。<ul><li>虚假的宗教情感常使人注意、赞美自己的谦卑；而真正的宗教情感使人认识自己为什么应该谦卑，并且自己的谦卑如何微不足道。</li><li>人应该根据自己的身份来判断自己是否谦卑。在上帝面前，人本身就毫无价值，所以俯伏在上帝面前并不能算谦卑（而是理所应当）。因此，在上帝面前宣称自己的谦卑，就是再抬举自己的地位，就是骄傲。</li><li>真正的认罪，不是因为自己行为上穷凶极恶而痛悔（这是理所应当的），而是能深刻地鉴查出自己隐藏的罪，并且把自己的认罪归结于自己罪孽深重（而非敏于思过）。</li><li>考虑到谦卑的 <strong>理由</strong>（自己本身的污秽），对比自己谦卑的 <strong>程度</strong>，圣徒会发现谦卑就是理所当然，自己谦卑的程度也不值一提。</li><li>圣徒鉴查自己骄傲的敏锐度远高于看见自己谦卑，也积极看待别人的行为，多看到别人的谦卑而少看到别人的骄傲。假冒伪善的人完全相反。</li><li>高估自己谦卑的习气，引出喜欢炫耀谦卑的毛病<ul><li><blockquote><p>你们禁食的时候，不可像那假冒为善的人，脸上带着愁容，因为他们把脸弄得难看，故意叫人看出他们是禁食。我实在告诉你们：他们已经得了他们的赏赐。（太 6:16）</p></blockquote></li><li><blockquote><p>你禁食的时候，要梳头洗脸。（太 6:17）</p></blockquote></li></ul></li><li>自我评价的时候，不要盲目相信自己不会骄傲。很多时候，看到自己的罪而谦卑，然后心满意足（觉得自己比人强），就是骄傲；进一步，认识到上述情况是骄傲，并且自卑，然后又心满意足（觉得自己比人强），也是骄傲。</li><li>真正谦卑的人，在很多方面就和穷人一样，在上帝面前穷困潦倒，乞求恩典。</li><li>信徒在人面前也当谨慎谦卑<ul><li><blockquote><p>我们留心行光明的事，不但在主面前，就在人面前，也是这样。（林后 8:21）</p></blockquote></li><li><blockquote><p>务要尊敬众人，亲爱教中的弟兄，敬畏神，尊敬君王。（彼前 2:17）</p></blockquote></li></ul></li></ul></li></ul></li></ul><h3 id="七-人改变本性"><a href="#七-人改变本性" class="headerlink" title="七　人改变本性"></a>七　人改变本性</h3><ul><li>恩典情感的另一个明显标志是人的本性被改变。<ul><li><blockquote><p>我们众人既然敞着脸得以看见主的荣光，好像从镜子里返照，就变成主的形状，荣上加荣，如同从主的灵变成的。（林后 3:18）</p></blockquote></li><li>上帝赋予人全新的性情，将人从喜爱犯罪转向渴慕上帝和圣洁；并且，这种改变是 <strong>持久</strong> 的，因为改变的是本性。</li><li>信主之后难免仍然有血气，信主之前容易犯的罪依然会成为试探，但这些罪不再能支配信徒。</li><li>圣徒的良善确实完全来自上帝，但因着圣灵的工作，圣徒的性情与上帝有份，自己也能发出光来（尽管程度上完全不能与上帝相比）。<ul><li>基督的生命传递给人的灵魂，活在人心里；圣灵藉此成为人真实而活泼的性情。</li><li><blockquote><p>从他腹中要流出活水的江河来。（约 7:38）</p></blockquote></li></ul></li><li>人的性情因属灵光照而不断被改造，不止在信主之初，而且直到生命的尽头（那时圣徒的荣耀就得以完全）。<ul><li><blockquote><p>不要效法这个世界，只要心意更新而变化，叫你们察验何为神的善良、纯全、可喜悦的旨意。（罗 12:2）</p></blockquote></li></ul></li></ul></li></ul><h3 id="八-基督的性情"><a href="#八-基督的性情" class="headerlink" title="八　基督的性情"></a>八　基督的性情</h3><ul><li>真情感伴随着羔羊的心、鸽子的灵和基督的性情；自然生出慈爱、温柔、安静、饶恕和怜悯的心肠，也就是基督的心肠。<ul><li>这种心灵（核心是 <strong>圣洁</strong>）成为信徒的真正品格。</li><li>这些美德也是基督自己的品格；如果我们没有这些品格，就不配称为基督徒。<ul><li><blockquote><p>我心里柔和谦卑，你们当负我的轭，学我的样式。（太 11:29）</p></blockquote></li></ul></li><li><strong>温柔</strong>：温柔与圣洁在圣经里是同义词（？），要像小孩子<ul><li>基督徒也当刚强壮胆，为主争战；但最主要的争战在于克制自己的情欲<ul><li><blockquote><p>不轻易发怒的，胜过勇士。治服己心的，强如取城。（箴 16:32）</p></blockquote></li><li><blockquote><p>他被欺压、在受苦的时候却不开口。他像羊羔被牵到宰杀之地，又像羊在剪毛的人手下无声，他也是这样不开口。（赛 53:7）</p></blockquote></li></ul></li><li>暴躁的情绪往往显明人的软弱而非刚强</li><li>骄傲也能使人伪装成刚强的样式</li></ul></li><li><strong>饶恕</strong>：愿意忽略和赦免别人给我们的伤害<ul><li><blockquote><p>免我们的债，如同我们免了人的债。（太 6:12）</p></blockquote></li></ul></li><li><strong>仁爱</strong>：驯良、乐善好施；爱使人认出我们是耶稣的门徒<ul><li><blockquote><p>我赐给你们一条新命令，乃是叫你们彼此相爱；我怎样爱你们，你们也要怎样相爱。（约 13:34）</p></blockquote></li></ul></li><li><strong>怜悯</strong>：只有真心怜悯并帮扶穷困、劳苦、病患同胞的才是真圣徒<ul><li><blockquote><p>怜恤人的人有福了，因为他们必蒙怜恤。（太 5:7）</p></blockquote></li><li><blockquote><p>凡有世上财物的，看见弟兄穷乏，却塞住怜恤的心，爱上帝的心怎能存在他里面呢？（约一 3:17）</p></blockquote></li></ul></li><li>这些美德是基督徒各样情感（惧怕、希望、忧伤、喜乐）的 <strong>固有倾向</strong>。基督徒可能在软弱时违背这些品德，但总有这种倾向。</li><li>我们信主之后难免仍然有血气，但信主导致的变化也是明显的，尤其体现在治死从前喜欢犯的罪方面。</li></ul></li></ul><h3 id="九-温柔的心灵"><a href="#九-温柔的心灵" class="headerlink" title="九　温柔的心灵"></a>九　温柔的心灵</h3><ul><li>恩典情感使人心柔软，使基督徒有温柔的心灵。<ul><li>假情感在开始时似乎能融化人心，但最终会使人心刚硬<ul><li>这样的人恃恩犯罪，光景甚至不如悔改之前的</li><li>他们用基督的恩典反对上帝的律法<ul><li><blockquote><p>将我们上帝的恩变作放纵情欲的机会。（犹 1:4）</p></blockquote></li></ul></li></ul></li><li>恩典情感使石心变得柔软，成为肉心<ul><li>虽然是肉心，但坚决憎恶一切冒犯上帝的事，并保持警醒自律，效果远胜过奴性的恐惧感。</li><li>出于上帝恩典的 <strong>圣洁忧伤</strong> 比出于自私原则的 <strong>律法忧伤</strong> 更加能软化人心。</li><li>具有这样温柔性情的人就像小孩子<ul><li>小孩子容易感动、受教、顺从，基督徒在属灵的事上也是如此。</li><li>小孩子有同情心、害怕危险、敬畏长辈……</li></ul></li><li><strong>神圣的勇气</strong> 也存在，但主要存在于大圣徒心中<ul><li>神圣的勇气主要在于消除奴性和纷争，大圣徒反而比一般信徒在上帝面前更为敬虔。</li></ul></li><li>恩典会促进良心认罪，从而使人心柔软<ul><li>恩典使人停止犯罪，但不使人停止认罪，反而使人更深地认罪</li><li>恩典使人更深地认识罪，超过律法使人认罪的功效</li></ul></li><li>除了圣洁的忧伤，感恩的喜乐、确凿信息和盼望也能使人温柔。</li></ul></li></ul></li></ul><h3 id="十-圣洁情感具有美感"><a href="#十-圣洁情感具有美感" class="headerlink" title="十　圣洁情感具有美感"></a>十　圣洁情感具有美感</h3><ul><li><p>真恩典情感 <strong>比例平衡</strong>，具有美感。</p><ul><li>基督徒在今生，因为恩典不完全、属血气的缺陷，情感也可能在具体的事情上显得不足，但不会出现极端的比例失衡。</li><li><p>成圣时，信徒的各个部分和肢体都脱去旧人，穿上新人。</p></li><li><p>假冒伪善者在情感种类上有很强的偏好，某些情感很强烈，某些情感很冷淡；比例明显失调。</p><ul><li><blockquote><p>以法莲是没有翻过的饼。（何 7:8）（一面烤糊了，一面还是生的）</p></blockquote></li><li>不同情感之间不平衡。例如，只有喜乐，没有敬畏。</li><li>同种情感在不同对象上也不平衡。例如，宣告自己爱上帝，却不爱弟兄；或者特别爱某些人，却不爱另一些人。<ul><li>你们若单爱那爱你们的人，有什么赏赐呢？（太 5:45）</li></ul></li><li>对同一个人，情感也不平衡。例如，只关心外在需求、却不关心属灵需求，或者只关心属灵需求、却不在乎外在需求。<ul><li>耶稣也关心人的身体需要，如五饼二鱼。</li></ul></li><li>恨恶其他基督徒的缺点，却对自己的缺点视而不见。</li><li>如果人看似取得较高的宗教成就（如撇弃世界、单单盼望神的国），却没有达到较低的标准（如交奉献），就是在装假。</li><li>猛烈地、缺乏耐心地追求次要的东西，却忽视更要紧的事；例如，特别关心别人、却不愿意独自面对上帝。</li><li>只恨恶特定的某些罪（自己不犯的），却纵容另一些罪（自己常犯的）。</li><li>在不同的时间也不平衡，忽冷忽热；如在旷野的以色列人。</li><li>在不同的地点也不平衡；例如，在公众场合很热情，但缺乏独自面对上帝的时间。<ul><li>恩典情感更喜欢安静和私密，圣徒各自为自己的罪忧伤。</li><li>圣经里的圣徒得到最大恩宠时，往往是独处的时候。例如，亚伯拉罕、以撒、雅各、摩西、以利亚和以利沙。</li></ul></li></ul></li><li><p>圣徒有许多恩典和情感，彼此都成比例。</p><ul><li><strong>喜乐、盼望</strong> 和 <strong>为罪忧伤、哀恸</strong> 并重；圣徒在蒙受安慰、得到喜乐之后，仍然为罪忧伤。<ul><li><blockquote><p>我领你们进入以色列地……你们在那里要追念玷污自己的行动作为、又要因所作的一切恶事厌恶自己。（结 20:42-43）</p></blockquote></li><li>恩典里的喜乐不妨碍我们继续为罪忧伤。</li></ul></li><li>凡是属灵事物，圣徒都有渴慕之情，并且渴慕的程度与这些事物的美好程度、重要程度相符。</li><li>恨恶和反对一切的罪。<ul><li><blockquote><p>我恨一切的假道。（诗 119:104）</p></blockquote></li></ul></li><li>虽然在不同时间情感有起伏，但为此忧伤，并愿意持守正道。<ul><li><blockquote><p>然而义人要持守所行的道、手洁的人要力上加力。（伯 17:9）</p></blockquote></li></ul></li></ul></li></ul></li></ul><h3 id="十一-圣徒渴望更加属灵"><a href="#十一-圣徒渴望更加属灵" class="headerlink" title="十一　圣徒渴望更加属灵"></a>十一　圣徒渴望更加属灵</h3><ul><li>恩典情感驱使人想要取得更高的属灵成就，但假情感使人自满且安于现状。<ul><li>真基督徒越爱上帝，就渴望更爱祂；越恨恶罪，就越希望自己能更恨恶罪；越渴慕圣洁，就愿意自己更渴慕圣洁。</li><li>人拥有的圣洁情感越多，就越具有属灵的品味，能感觉到圣洁的美好和自己的匮乏；因此就越急切地乞求恩典和灵粮，好让自己成长。</li><li>属灵喜乐可以 <strong>满足</strong> 人心<ul><li>属灵喜乐是完全符合人心本质的，因此使人不再追求其他种类的欢乐。</li><li>世俗欢乐都是有极限的，无法满足人不断提高的期待；但属灵喜乐没有极限，可以回应人最深的期望。</li><li>世俗欢乐中的满足感是短暂的，人得到满足后，就开始厌烦；但属灵喜乐中的满足感是持久的</li><li>属灵喜乐满足人心的程度是最高的</li></ul></li><li>人在体验过属灵喜乐后，就知道属灵喜乐的美好，就越渴望更多；反之，如果人不愿意渴望更多，就说明其体验到的并不是真正的属灵喜乐。</li><li>如果一个人相信自己的罪被赦免，将进天堂，就满足了，并拒绝更多的恩典；显得好像已经完成了工作，并以过去的工作为荣；这样就是没认识到自己的缺乏，情感是有问题的。<ul><li>基督徒的寻求、努力、工作是信主之后，信主是一生辛勤工作的起点。</li></ul></li><li>真圣徒追求圣洁本身，并且是自然的；但假冒伪善者另有所图，如追求神学知识可能是为了感觉自己得救、为了在人前显荣耀、为了证明上帝爱他。</li></ul></li></ul><h3 id="十二-一生追求圣洁行为"><a href="#十二-一生追求圣洁行为" class="headerlink" title="十二　一生追求圣洁行为"></a>十二　一生追求圣洁行为</h3><ul><li><p>恩典情感结出行为的果实，规范和指导信徒的行为，使得圣洁行为成为信徒一生的实践和追求。</p><ul><li>完全顺服基督徒的道统<ul><li>离弃一切的罪，尤其是自己最喜爱的罪，并且恪守那些最难以遵守、最反感的责任。</li><li>不仅仅是消极地不犯罪，还要积极地爱神爱人、活出美好的品质。</li></ul></li><li>立志成圣，把圣洁生活作为人生最重要的工作。<ul><li>一个人不能侍奉两个主。我们当殷勤服事，为主做工。</li></ul></li><li>矢志不渝，在人生起伏的各个阶段均竭力追求信仰。<ul><li>经历各种试炼和试探，使自己明确自己得救的地位，并让世界认出基督徒的与众不同。</li><li>真圣徒可以在某些事上有退步，陷入试探而犯罪，但不至于持续不断地厌弃信仰、违逆上帝，不至于堕落到与信主之前毫无二致的地步。<ul><li>倘若真的完全堕落，只能说明该“信徒”并未与基督一同复活。</li><li><blockquote><p>那人末后的景况比先前更不好了。（太 12:45）</p></blockquote></li></ul></li></ul></li></ul></li><li><p>恩典情感使人的行为产生变化（<strong>实践性</strong>）</p><ul><li>因为这是圣灵的（上帝的）工作，具有大能力的；恩典情感深入人心，成为生命的泉源，掌管人的一切行为。</li><li>真敬虔的能力在于有实际的行为。</li><li>恩典情感的首要客观基础是圣洁事物本身的美好，而不是对信徒有利；因此，圣洁事物会持续产生作用，而不是让人得到满足就停止追求。<ul><li>类似爱钱的人永远不会嫌钱太多，我们如果真爱上帝，也永远不会觉得自己对上帝的追求过多。</li></ul></li><li>属灵事物本身的圣洁之美使人爱圣洁，并践行一切圣洁之事；属灵知识使人认识基督的宝贵胜过一切，并愿意跟从他。</li><li>属灵情感伴随着 <strong>确信</strong>，使信徒坚信神圣事物的真实性；既然确信，信徒的生活就必然被其掌管。</li><li>属灵情感使人的 <strong>本性</strong> 被改变，并体现在实际行为上。</li><li>属灵情感伴随着真正的 <strong>谦卑</strong>，使人严格地、整体地、持续地顺服，愿意去遵行律法。</li><li>圣经看重 <strong>诚恳的态度</strong> 和 <strong>坚定的意志</strong><ul><li>为了爱基督，就恨恶地上的一切享乐，厌弃自己和自己的生命</li></ul></li><li>恩典在圣徒心中直接导致圣洁行为；恩典是最活跃的（因它是生命本身），激发出人的行为<ul><li><blockquote><p>我们原是他的工作，在基督耶稣里造成的，为要叫我们行善。（弗 2:10）</p></blockquote></li><li>金灯台有球（果实）有花，预表信仰告白和圣洁行为，都是恩典的内在原则的外在表现</li></ul></li><li>信徒实践的果实在经历试炼的时候愈发显明出来<ul><li>部分人被上帝对付的时候，都是迫于压力临时离弃罪；但只要压力一缓，就又食言；就像埃及的法老一样。</li></ul></li></ul></li><li><p>基督徒实践是向 <strong>邻居和弟兄</strong> 证明信仰真实性的最明显标志</p><ul><li>要凭着果子认出树来，而不是凭着叶子和花认出树来<ul><li><blockquote><p>凭着他们的果子，就可以认出他们来。（太 7:16）</p></blockquote></li></ul></li><li>基督让我们通过好的行为，让别人看见我们的圣洁。</li><li><blockquote><p>我的弟兄们，若有人说自己有信心，却没有行为，有什么益处呢？这信心能救他吗？（雅 2:14）</p></blockquote></li><li><blockquote><p>你将你没有行为的信心指给我看，我便藉着我的行为，将我的信心指给你看。（雅 2:18）</p></blockquote></li><li>天然的理性也教导，人的行为比宣告更能证明人的内心</li><li>行为的代价是高昂的；假冒伪善者容易学会基督徒的话语，却很难活出基督徒的样式</li><li>需要注意的点：<ol><li>信仰告白是预设和前提；根据人的行为判断人的信仰，前提是他必须公开宣告自己的基督教信仰。<ul><li>信仰告白必须包括基督教的必要内容（耶稣是弥撒亚、救赎计划、悔改、舍己等），并且宣告的人必须正确理解信仰告白的内容。</li><li>不一定需要描述圣灵的具体工作方式，如体验的顺序等。</li></ul></li><li>需要正确理解基督徒实践的含义，以及行为在多大程度上被人看见；不同的人用行为证明信仰的力度不同，但至少好过言语的描述。</li><li>当人判断别人时，任何外在行为都算不上恩典的 <strong>绝对确据</strong>。</li></ol></li></ul></li><li><p>基督徒实践是向 <strong>自己的良心</strong> 证明恩典真实性的最佳明证</p><ul><li><blockquote><p>小子们哪，我们相爱，不要只在言语和舌头上。总要在行为和诚实上。（约一 3:18）</p></blockquote></li></ul><ol><li>把“基督徒行为、实践、行善或遵守诫命”作为向良心证明自己是真基督徒的确据<ul><li>人的行为不仅仅是外在的表现，还有驱动行为的内在意志</li><li>恩典的两种运行方式：内在活动 vs. 外在实践</li><li>恩典的内在运行指导身体的外在行为</li><li>好的行为必须伴随着内心对上帝的顺服和服侍，否则就不算基督徒实践</li></ul></li><li>基督徒实践是向自己证明具有真敬虔的首要证据<ul><li>该证据胜过认罪、光照、蒙受安慰、内在认识等其他证据</li></ul><ol><li>理性清楚地说明：最能证明一个人内心真实倾向的，就是当他可以自由选择时，他的实际选择。<ul><li>在上帝和其他事物相争时，以实际行动选择上帝。</li><li>伪装有善心，却没有善行，就是荒谬的、欺哄上帝的。</li></ul></li><li>圣经描述的 <strong>试炼</strong>，正是检查信徒是否爱上帝胜过一切。<ul><li>试炼帮助我们自己判断自己对上帝的爱是否彻底，向自己的良心显出证据</li><li>基督徒美德经过试炼更显宝贵，试炼的结果就是信仰真实性的最佳证据</li><li>上帝设立试炼，不是为了让他自己明白我们的信心，而是为了让我们自己明白</li></ul></li><li>圣经说，恩典藉着行为得以完全或长成<ul><li>可见信心是与他的行为并行，而且信心因着行为才得成全。（雅 2:22）</li><li>树木藉着果子（而不是叶子或花）得以完全</li><li>恩典在实践中运行是恩典的 <strong>最完美运行</strong>，所以恩典行为是恩典的最高明证</li></ul></li><li>圣经强调行为上的证据（圣洁实践）超过其他一切证据<ul><li>检验宣信者敬虔的标志和特征（沙土 vs. 磐石）</li><li>弟兄相爱首先表现在实践中；第二块法版上的具体责任（而非单单的内在情感）才是彼此相爱的真意</li><li>圣洁实践是上帝选择的、最合适我们的敬虔标志，因此在圣经中反复强调；故意忽视这一点是很危险的</li></ul></li><li>圣经清楚地说道：基督徒实践不仅是向他人证明而且是向基督徒自己的良心证明基督徒内心真恩典的主要证据。<ul><li>反过来，圣经也说明：不圣洁行为是假冒伪善和内心邪恶的明证</li></ul></li><li>我们的行为是在审判台前最重要的呈堂证供<ul><li>审判的目的不是为了上帝自己形成判断，而是为了向我们的 <strong>良心</strong> 和 <strong>世人</strong> 宣告并显明他的 <strong>公义</strong></li><li>上帝为了为了显明公义，在审判中使用的证据正是人在世的行为（而不是人内在体验的步骤、信主的方式等）<ul><li><blockquote><p>死了的人都凭着这些案卷所记载的，照他们所行的受审判。（启 20:12）</p></blockquote></li></ul></li><li>上帝用以判断我们的首要证据，当然应该成为我们用以判断自己的首要证据</li></ul></li></ol></li></ol></li><li><p>除了基督徒实践，不排除还有其他说明真恩典运行的证据，但基督徒实践是 <strong>最首要的证据</strong>。正如可以有很多辅助证据证明一棵树是无花果树，但首要证据永远是它的果子是否是无花果。</p></li><li><p>基督徒实践是 <strong>记号中的记号</strong>，是印证其他一切敬虔记号的最大证据</p><ul><li>上帝给我们恩典就是为了让我们在实践中运用，从而加以验证</li><li>实践是证明我们 <strong>认识上帝</strong> 的最佳证据</li><li>实践是 <strong>悔改</strong> 的最好证据<ul><li><blockquote><p>你们要结出果子来，与悔改的心相称。（太 3:8）</p></blockquote></li></ul></li><li>实践是信徒具有 <strong>得救信心</strong> 的证据</li><li>实践是说明信徒内心 <strong>相信真理并因此得救</strong> 的最佳明证</li><li>实践是证明信徒真正 <strong>跟从基督</strong> 的证据<ul><li>在实际行动中撇下一切跟从耶稣，跟从耶稣的心就得以完全</li></ul></li><li>实践是证明信徒 <strong>相信基督以至得救</strong> 的最好证据<ul><li>“信”本身就包含着愿意为所信之事承担风险的意思；如果不愿意冒任何风险，那就与不信毫无二致。</li><li>只有因相信福音而牺牲世俗利益的人，才配说是为福音摆上自己</li></ul></li><li>实践是说明信徒 <strong>对上帝和对人的爱</strong> 的证据</li><li>实践是 <strong>真谦卑</strong> 的证据</li><li>实践是检验信徒是否 <strong>真敬畏上帝</strong> 的证据</li><li>以实际行动回报所领受的恩惠是 <strong>真感恩</strong> 的证据</li><li>实践是 <strong>真渴慕</strong> 的证据</li><li>欢喜地实践宗教责任和遵行上帝旨意是 <strong>真圣洁喜乐</strong> 的证据</li><li>实践是 <strong>基督徒勇气</strong> 的正确标志</li><li>属灵体验对基督徒实践的影响程度，也最能说明其体验的属灵程度</li></ul></li><li><p>反对意见1：判断基督徒应该主要依据内在体验，属灵体验才是判断真恩典的主要证据</p><ul><li>基督徒的圣洁实践本身就是属灵的实践，也是 <strong>身心一致</strong> 的活动</li><li>内在活动（爱上帝）直接产生和影响外在行为（舍己和牺牲），才能荣耀上帝</li><li>基督徒的体验和实践不应该是割裂的；实践是体验的最重要和最明显的部分<ul><li>不是所有基督徒体验都是实践，但所有基督徒实践都是体验</li><li>由实践而来的属灵体验，也是在圣经中反复强调的</li></ul></li><li>属灵实践作为恩典运行的本质，使得基督教成为“实验性宗教”<ul><li>用真实经历检验自己信心的真实性</li></ul></li><li>只有实践没有体验，是没有价值的，但也没有害处；但只有体验却没有实践，（有些情况下）可能比没有体验还糟糕。</li><li>圣灵的见证（圣灵的印）在于基督徒体验，而上帝在人的实践中用最明显的方式为基督徒作见证，并打下印记</li></ul></li><li><p>反对意见2：过于强调基督徒实践作为恩典的证据，会导致律法主义，使人过于关注外在行为，引起人自夸，以至于违反了因信称义的教义</p><ul><li>圣洁行为是上帝恩典的标志，所以行为也是上帝白白馈赠的；圣洁行为是与信心伴随的，白白赐给我们的。</li><li>如果把行为当做赚取上帝恩典的工价，才违背因信称义；突出表现为自夸。</li><li>恩典的本质（白白的恩典）和圣洁行为的必要性，在圣经中并行不悖；后者绝不会降低前者的地位。</li><li>只强调个人知识、良心和恩典的内在运行，而轻视恩典的外在作用，会对基督教造成极大破坏。<ul><li>圣经已经指出属灵实践是最好的证据，也是上帝预备的最适合我们的证据；妄图另寻证据的都是徒劳。</li><li>看重属灵实践有很多直接的好处：督促假冒伪善者认罪；帮助我们摆脱（关于体验的方法和步骤的）疑惑、免去随之而来的纷争；防止宣信者放任自流；鼓励我们用好行为宣告信仰，而不是炫耀个人体验</li></ul></li></ul></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;2020年初寒假，《宗教情感》读书笔记。&lt;/p&gt;
&lt;p&gt;第一遍阅读从1月28日开始，到3月27日结束，历时正好两个月。读这本书的过程中，无时无刻不感灰心气馁，仿佛自己从来没信耶稣一般；也更新了自己好多对信仰的认识。我愿意相信这是个去芜存菁的过程——剔除那些盲目的“信心”，虽然在感觉上很糟糕，但终究好过永远陷在那些虚妄的认知里还感觉良好。&lt;/p&gt;
&lt;p&gt;在这段时间里，还遇见了上帝为我预备的另一半，原来她早就出现在我的生命中。倘若我在四年之前悬崖勒马，也不至于“在好些医生手里受了许多的苦”。感谢上帝管教我、带领我回来，也在这个过程中建立我的生命，以至于如今我能清楚地认识她就是上帝为我预备的；也感谢上帝，她竟然一直等候到如今。&lt;/p&gt;
&lt;p&gt;顺便完成了令人头秃的学位论文的理论部分，完成了初稿和预答辩，目前期待毕业中。&lt;/p&gt;
&lt;p&gt;愿荣耀归于至高神！&lt;/p&gt;</summary>
    
    
    
    <category term="信仰" scheme="https://syuoni.github.io/categories/%E4%BF%A1%E4%BB%B0/"/>
    
    
    <category term="基督教" scheme="https://syuoni.github.io/tags/%E5%9F%BA%E7%9D%A3%E6%95%99/"/>
    
    <category term="《宗教情感》" scheme="https://syuoni.github.io/tags/%E3%80%8A%E5%AE%97%E6%95%99%E6%83%85%E6%84%9F%E3%80%8B/"/>
    
    <category term="清教徒" scheme="https://syuoni.github.io/tags/%E6%B8%85%E6%95%99%E5%BE%92/"/>
    
  </entry>
  
  <entry>
    <title>西瓜书笔记：支持向量机（第 6 章）</title>
    <link href="https://syuoni.github.io/posts/ML-book-notes-6/"/>
    <id>https://syuoni.github.io/posts/ML-book-notes-6/</id>
    <published>2019-12-20T02:51:07.000Z</published>
    <updated>2019-12-22T14:44:08.000Z</updated>
    
    <content type="html"><![CDATA[<p>支持向量机，核方法等。<br><a id="more"></a></p><h2 id="最大化间隔"><a href="#最大化间隔" class="headerlink" title="最大化间隔"></a>最大化间隔</h2><p>给定训练集 </p><script type="math/tex; mode=display">D=\{ ({\pmb{x_1}}, y_1), ({\pmb{x_2}}, y_2), \ldots, ({\pmb{x_m}}, y_m) \}, y_i \in \{ -1, +1 \}</script><p>寻找 <strong>划分超平面</strong> 将样本集按不同类别分开。其中，<strong>划分超平面</strong> 可以用如下方程表示：</p><script type="math/tex; mode=display">{\pmb w}^{\mathrm T} {\pmb x} + b = 0</script><p>其中 ${\pmb w}^{\mathrm T}$ 为法向量，$b$ 为位移项。则样本空间中任意点 ${\pmb x}$ 到该平面的距离为</p><script type="math/tex; mode=display">r = \frac{\vert {\pmb w}^{\mathrm T} {\pmb x} + b \vert}{\Vert {\pmb w} \Vert}</script><p>缩放 ${\pmb w}$ 与 $b$ 使得训练集中所有点到到超平面的最小距离为 $\frac{1}{\Vert {\pmb w} \Vert}$，则有</p><script type="math/tex; mode=display">\begin{cases}{\pmb w}^{\mathrm T} {\pmb{x_i}} + b \geq 1, \; & \mathrm{if} \; y_i = +1 \\{\pmb w}^{\mathrm T} {\pmb{x_i}} + b \leq -1, \; & \mathrm{if} \; y_i = -1\end{cases}</script><p>上式等价于</p><script type="math/tex; mode=display">y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) \geq 1</script><p><strong>支持向量机</strong> 的目标是最大化间隔，即</p><script type="math/tex; mode=display">\begin{aligned}\max_{\pmb w, b} \quad & \frac{2}{\Vert {\pmb w} \Vert} \\\mathrm{s.t.} \quad & y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) \geq 1\end{aligned}</script><p>上式等价于</p><script type="math/tex; mode=display">\begin{aligned}\min_{\pmb w, b} \quad & \frac{1}{2} \Vert {\pmb w} \Vert^2 \\\mathrm{s.t.} \quad & y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) \geq 1\end{aligned}</script><p>这就是 <strong>支持向量机</strong> 的 <strong>基本型</strong>。该问题本身是一个 <strong>凸二次规划</strong> 问题，可以直接用优化计算包求解。</p><h2 id="对偶问题"><a href="#对偶问题" class="headerlink" title="对偶问题"></a>对偶问题</h2><p>对 <strong>基本型</strong> 的每一条约束添加朗格朗日乘子 $\alpha_i \geq 0$，则该问题的拉格朗日函数可以写为</p><script type="math/tex; mode=display">L({\pmb w}, b, {\pmb \alpha}) = \frac{1}{2} \Vert {\pmb w} \Vert^2 + \sum_{i=1}^{m} \alpha_i \left( 1 - y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) \right)</script><p>令 $L({\pmb w}, b, {\pmb \alpha})$ 对 ${\pmb w}$ 与 $b$ 求偏导，得到</p><script type="math/tex; mode=display">\begin{cases}{\pmb w} = \sum_{i=1}^{m} \alpha_i y_i {\pmb{x_i}} \\0 = \sum_{i=1}^{m} \alpha_i y_i\end{cases}</script><p>将上式代回 $L({\pmb w}, b, {\pmb \alpha})$，得到</p><script type="math/tex; mode=display">\begin{aligned}\max_{\pmb \alpha} \quad & \sum_{i=1}^{m} \alpha_i - \frac{1}{2} \underbrace{\sum_{i=1}^{m} \sum_{j=1}^{m} \alpha_i \alpha_j y_i y_j {\pmb{x_i}}^{\mathrm T} {\pmb{x_j}}}_{=\Vert \sum_{i=1}^{m} \alpha_i y_i {\pmb{x_i}} \Vert^2} \\\mathrm{s.t.} \quad & \sum_{i=1}^{m} \alpha_i y_i = 0, \, \alpha_i \geq 0\end{aligned}</script><p>这就是 <strong>支持向量机</strong> 的 <strong>对偶型</strong>。该问题也是一个 <strong>凸二次规划</strong> 问题，可以直接用优化计算包求解。</p><p>注意到</p><ul><li>对偶问题约束有<script type="math/tex; mode=display">\alpha_i \geq 0</script></li><li>原问题约束有<script type="math/tex; mode=display">y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) - 1 \geq 0</script></li><li>拉格朗日函数中，若 $\alpha_i &gt; 0$，则必有 $ 1 - y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) = 0$，因此<script type="math/tex; mode=display">\alpha_i \left( y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) - 1 \right) = 0</script>以上三条构成 KKT （Karush-Kuhn-Tucker）条件，即<script type="math/tex; mode=display">\begin{cases}\alpha_i \geq 0 \\y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) - 1 \geq 0 \\\alpha_i \left( y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) - 1 \right) = 0\end{cases}</script>其中，$\alpha_i &gt; 0$ 对应的点 ${\pmb{x_i}}$ 满足 $ y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) - 1 = 0$，也就是 <strong>支持向量</strong>。一般，绝大多数点对应的 $\alpha_i = 0$，是 <strong>非支持向量</strong>。</li></ul><h3 id="SMO-算法"><a href="#SMO-算法" class="headerlink" title="SMO 算法"></a>SMO 算法</h3><p>每次选取一对 $( \alpha_i, \alpha_j)$，确保 $( \alpha_i, \alpha_j)$ 中至少有一个违背 KKT 条件；然后，固定 ${\pmb \alpha}$ 向量中所有其他元素，更新 $( \alpha_i, \alpha_j)$ 的值。这样每次更新后目标函数的值都能变大。</p><h2 id="核函数"><a href="#核函数" class="headerlink" title="核函数"></a>核函数</h2><p>若训练集线性不可分，则可以将样本 ${\pmb x}$ 从 <strong>原始空间</strong> 映射到一个 <strong>高维空间</strong>，记映射后得到的 <strong>特征向量</strong> 为 $\phi({\pmb x})$。在映射后特征空间中的 <strong>划分超平面</strong> 为</p><script type="math/tex; mode=display">f({\pmb x}) = {\pmb w}^{\mathrm T} \phi({\pmb x}) + b</script><p>映射后特征空间中的 <strong>基本型</strong> 为</p><script type="math/tex; mode=display">\begin{aligned}\min_{\pmb w, b} \quad & \frac{1}{2} \Vert {\pmb w} \Vert^2 \\\mathrm{s.t.} \quad & y_i \left({\pmb w}^{\mathrm T} {\phi(\pmb{x_i})} + b \right) \geq 1\end{aligned}</script><p>其  <strong>对偶型</strong> 为</p><script type="math/tex; mode=display">\begin{aligned}\max_{\pmb \alpha} \quad & \sum_{i=1}^{m} \alpha_i - \frac{1}{2} \sum_{i=1}^{m} \sum_{j=1}^{m} \alpha_i \alpha_j y_i y_j {\phi(\pmb{x_i})}^{\mathrm T} {\phi(\pmb{x_j})} \\\mathrm{s.t.} \quad & \sum_{i=1}^{m} \alpha_i y_i = 0, \, \alpha_i \geq 0\end{aligned}</script><p>在实践中，只需要知道任意 ${\pmb{x_i}}$ 与 ${\pmb{x_j}}$ 在映射后的内积 $\phi({\pmb{x_i}})^{\mathrm T} \phi({\pmb{x_j}})$ 即可，不必知道映射 $\phi$ 的具体形式。所以，定义核函数：</p><script type="math/tex; mode=display">\kappa({\pmb{x_i}}, {\pmb{x_j}}) = \phi({\pmb{x_i}})^{\mathrm T} \phi({\pmb{x_j}})</script><p>常用核函数有</p><div class="table-container"><table><thead><tr><th style="text-align:center">核函数</th><th style="text-align:center">表达式</th><th style="text-align:center">参数说明</th></tr></thead><tbody><tr><td style="text-align:center">线性核</td><td style="text-align:center">$\kappa({\pmb{x_i}}, {\pmb{x_j}}) = \pmb{x_i}^{\mathrm T} \pmb{x_j}$</td><td style="text-align:center"></td></tr><tr><td style="text-align:center">多项式核</td><td style="text-align:center">$\kappa({\pmb{x_i}}, {\pmb{x_j}}) = \left( \pmb{x_i}^{\mathrm T} \pmb{x_j} \right)^d$</td><td style="text-align:center">$d \ge 1$，为多项式次数</td></tr><tr><td style="text-align:center">高斯核</td><td style="text-align:center">$\kappa({\pmb{x_i}}, {\pmb{x_j}}) = \exp \left( -\frac{\Vert \pmb{x_i} - \pmb{x_j} \Vert^2}{2 \sigma^2} \right)$</td><td style="text-align:center">$\sigma &gt; 0$，为带宽</td></tr></tbody></table></div><h2 id="软间隔"><a href="#软间隔" class="headerlink" title="软间隔"></a>软间隔</h2><p>允许一些样本不满足约束 $y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) \geq 1$，但需要施加惩罚。所以，优化目标可以写为</p><script type="math/tex; mode=display">\min_{\pmb w, b} \quad \frac{1}{2} \Vert {\pmb w} \Vert^2 + C \cdot \sum_{i=1}^{m} {\mathcal L}_{0/1} \left( y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) - 1 \right)</script><p>其中，$C$ 是惩罚力度，${\mathcal L}_{0/1}(\cdot)$ 是 0/1 损失函数，即</p><script type="math/tex; mode=display">{\mathcal L}_{0/1}(z) = \begin{cases} 1, \; \mathrm{if} \; z < 0 \\0, \; \mathrm{if} \; z \ge 0\end{cases}</script><p>注意该损失函数中，约束违背的 <strong>程度</strong> 不影响惩罚项的大小。其他损失函数形式有：</p><div class="table-container"><table><thead><tr><th style="text-align:center">损失函数</th><th style="text-align:center">表达式</th></tr></thead><tbody><tr><td style="text-align:center">Hinge 损失函数</td><td style="text-align:center">${\mathcal L}_{hinge}(z) = \max(0, 1-z)$</td></tr><tr><td style="text-align:center">指数损失函数</td><td style="text-align:center">${\mathcal L}_{exp}(z) = \exp(-z) $</td></tr><tr><td style="text-align:center">对数损失函数</td><td style="text-align:center">${\mathcal L}_{log}(z) = \log(1 + \exp(-z))$</td></tr></tbody></table></div><p>若采用 Hinge 损失函数，引入 <strong>松弛变量</strong> （Slack Variables） $\xi_i \ge 0$，可以将 <strong>原问题</strong> 重写为</p><script type="math/tex; mode=display">\begin{aligned}\min_{\pmb w, b, \pmb \xi} \quad & \frac{1}{2} \Vert {\pmb w} \Vert^2 + C \cdot \sum_{i=1}^m \xi_i \\\mathrm{s.t.} \quad & y_i \left({\pmb w}^{\mathrm T} {\pmb{x_i}} + b \right) \geq 1 - \xi_i, \; \xi_i \ge 0\end{aligned}</script><p>则其 <strong>对偶问题</strong> 为</p><script type="math/tex; mode=display">\begin{aligned}\max_{\pmb \alpha} \quad & \sum_{i=1}^{m} \alpha_i - \frac{1}{2} \sum_{i=1}^{m} \sum_{j=1}^{m} \alpha_i \alpha_j y_i y_j {\pmb{x_i}}^{\mathrm T} {\pmb{x_j}} \\\mathrm{s.t.} \quad & \sum_{i=1}^{m} \alpha_i y_i = 0, \, 0 \le \alpha_i \le C\end{aligned}</script><p>若采用对数损失函数，则模型很接近 Logit 回归。</p><h3 id="结构风险与经验风险"><a href="#结构风险与经验风险" class="headerlink" title="结构风险与经验风险"></a>结构风险与经验风险</h3><p>更一般地，可以将优化目标写成</p><script type="math/tex; mode=display">\min_{f} \quad \Omega(f) + C \sum_{i=1}^m \mathcal{L}(f(\pmb{x_i}), y_i)</script><p>其中，$\Omega(f)$ 代表 <strong>结构风险</strong>，如 $\frac{1}{2} \Vert {\pmb w} \Vert^2$，也被称为 <strong>正则化项</strong>，这里是 $\mathrm{L}_2$ 范数。<br>$\sum_{i=1}^m \mathcal{L}(f(\pmb{x_i}), y_i)$ 代表 <strong>经验风险</strong>，用于描述模型与数据的契合程度，如似然函数。</p><h2 id="支持向量回归"><a href="#支持向量回归" class="headerlink" title="支持向量回归"></a>支持向量回归</h2><p>支持向量回归（Support Vector Regression, SVR）是指，在回归中容忍 $f({\pmb x})$ 与 $y$ 存在 $\varepsilon$ 的偏差，当实际偏差大于 $\varepsilon$ 才开始计算损失。<br>支持向量回归问题可以写为</p><script type="math/tex; mode=display">\min_{\pmb w, b} \quad \frac{1}{2} \Vert {\pmb w} \Vert^2 + C \cdot \sum_{i=1}^m \mathcal{L}_{\varepsilon} \left( f({\pmb{x_i}}) - y_i \right)</script><p>其中损失函数为</p><script type="math/tex; mode=display">\mathcal{L}_{\varepsilon}(z) = \begin{cases} 0, \; & \mathrm{if} \; \vert z \vert \le \varepsilon \\\vert z \vert - \varepsilon, \; & \mathrm{if} \; \vert z \vert > \varepsilon\end{cases}</script><ul><li>如果损失函数是均方误差，则 SVR 等价于 Ridge 回归。</li><li>如果 $\varepsilon = 0$，即损失函数是误差的绝对值，则 SVR 等价于带有 $\mathrm{L}_2$ 范数的中位数回归。</li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;支持向量机，核方法等。&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="支持向量机" scheme="https://syuoni.github.io/tags/%E6%94%AF%E6%8C%81%E5%90%91%E9%87%8F%E6%9C%BA/"/>
    
    <category term="核方法" scheme="https://syuoni.github.io/tags/%E6%A0%B8%E6%96%B9%E6%B3%95/"/>
    
    <category term="结构风险" scheme="https://syuoni.github.io/tags/%E7%BB%93%E6%9E%84%E9%A3%8E%E9%99%A9/"/>
    
    <category term="经验风险" scheme="https://syuoni.github.io/tags/%E7%BB%8F%E9%AA%8C%E9%A3%8E%E9%99%A9/"/>
    
  </entry>
  
  <entry>
    <title>西瓜书笔记：神经网络（第 5 章）</title>
    <link href="https://syuoni.github.io/posts/ML-book-notes-5/"/>
    <id>https://syuoni.github.io/posts/ML-book-notes-5/</id>
    <published>2019-12-19T13:48:34.000Z</published>
    <updated>2019-12-22T12:01:34.000Z</updated>
    
    <content type="html"><![CDATA[<p>神经网络，反向传播等。<br><a id="more"></a></p><h2 id="神经元模型"><a href="#神经元模型" class="headerlink" title="神经元模型"></a>神经元模型</h2><script type="math/tex; mode=display">\operatorname{logistic}(x) = \operatorname{sigmoid}(x) = \frac{1}{1+\exp(-x)}</script><p>单层感知机（Perception）模型，只能处理线性可分问题</p><script type="math/tex; mode=display">y = f\left( \sum_{i=1}^{n} w_i x_i - \theta \right)</script><h2 id="多层网络"><a href="#多层网络" class="headerlink" title="多层网络"></a>多层网络</h2><p>多层前馈神经网络（Multi-Layer Feedforward Neural Networks）</p><h3 id="反向传播算法（Back-Propagation）"><a href="#反向传播算法（Back-Propagation）" class="headerlink" title="反向传播算法（Back Propagation）"></a>反向传播算法（Back Propagation）</h3><h4 id="损失函数（Loss-Function）"><a href="#损失函数（Loss-Function）" class="headerlink" title="损失函数（Loss Function）"></a>损失函数（Loss Function）</h4><ul><li>均方误差<script type="math/tex; mode=display">\mathcal{E}(y_i, \hat{y}_i) = \frac{1}{2} \cdot (y_i - \hat{y}_i)^2</script></li><li>交叉熵（Cross Entropy）<script type="math/tex; mode=display">\begin{aligned}\mathcal{L}(y_i, \hat{y}_i) =& \begin{cases} \log(P(y_i=1 \mid \hat{y}_i)) = \log(\hat{y}_i), & {\mathrm{if}} \; y_i=1 \\\log(P(y_i=0 \mid \hat{y}_i)) = 1 - \log(\hat{y}_i), & {\mathrm{if}} \; y_i=0 \end{cases} \\=& y_i \cdot \log(\hat{y}_i) + (1 - y_i) \cdot \log(1 - \hat{y}_i)\end{aligned}</script></li></ul><h4 id="反向传播"><a href="#反向传播" class="headerlink" title="反向传播"></a>反向传播</h4><p>对特定的一层神经元，其输出为</p><script type="math/tex; mode=display">{\pmb y} = f({\pmb W}{\pmb x} + {\pmb b})</script><p>其中，${\pmb x}$ 为上一层的输出，${\pmb W}$ 和 ${\pmb b}$ 为上一层与当前层之间的权重矩阵和偏置向量，$f$ 为激活函数。已知 $\frac{\partial \mathcal{L}}{\partial {\pmb y}}$，那么</p><script type="math/tex; mode=display">\begin{aligned}\frac{\partial \mathcal{L}}{\partial {\pmb W}} =& \frac{\partial \mathcal{L}}{\partial {\pmb y}} \cdot \frac{\partial {\pmb y}}{\partial ({\pmb W}{\pmb x}+{\pmb b})} \cdot \frac{\partial ({\pmb W}{\pmb x}+{\pmb b})}{\partial {\pmb W}} \\\frac{\partial \mathcal{L}}{\partial {\pmb b}} =& \frac{\partial \mathcal{L}}{\partial {\pmb y}} \cdot \frac{\partial {\pmb y}}{\partial ({\pmb W}{\pmb x}+{\pmb b})} \cdot \frac{\partial ({\pmb W}{\pmb x}+{\pmb b})}{\partial {\pmb b}} \\\frac{\partial \mathcal{L}}{\partial {\pmb x}} =& \frac{\partial \mathcal{L}}{\partial {\pmb y}} \cdot \frac{\partial {\pmb y}}{\partial ({\pmb W}{\pmb x}+{\pmb b})} \cdot \frac{\partial ({\pmb W}{\pmb x}+{\pmb b})}{\partial {\pmb x}}\end{aligned}</script><p>其中，$\frac{\partial \mathcal{L}}{\partial {\pmb W}}$ 和 $\frac{\partial \mathcal{L}}{\partial {\pmb b}}$ 可以用于更新 ${\pmb W}$ 和 ${\pmb b}$。以 $\eta$ 为学习速率，则</p><script type="math/tex; mode=display">\begin{aligned}\Delta {\pmb W} =& -\eta \cdot \frac{\partial \mathcal{L}}{\partial {\pmb W}} \\\Delta {\pmb b} =& -\eta \cdot \frac{\partial \mathcal{L}}{\partial {\pmb b}}\end{aligned}</script><p>$\frac{\partial \mathcal{L}}{\partial {\pmb x}}$ 则用于进一步反向传播。</p><h2 id="全局最小与局部最小"><a href="#全局最小与局部最小" class="headerlink" title="全局最小与局部最小"></a>全局最小与局部最小</h2><h3 id="防止过拟合的策略"><a href="#防止过拟合的策略" class="headerlink" title="防止过拟合的策略"></a>防止过拟合的策略</h3><ul><li>Early Stopping</li><li>正则化</li></ul><h3 id="防止局部最小的策略"><a href="#防止局部最小的策略" class="headerlink" title="防止局部最小的策略"></a>防止局部最小的策略</h3><ul><li>多组不同参数初始化网络</li><li>模拟退火（Simulated Annealing）：以一定概率接受比当前解更差的结果</li><li>随即梯度下降（SGD）</li></ul><h2 id="深度学习"><a href="#深度学习" class="headerlink" title="深度学习"></a>深度学习</h2><p>增加隐藏层的层数比增加隐藏层的神经元数目更有效。</p><h3 id="防止梯度发散-消失策略"><a href="#防止梯度发散-消失策略" class="headerlink" title="防止梯度发散/消失策略"></a>防止梯度发散/消失策略</h3><ul><li>Pre-Training + Fine-Tuning</li><li>深度信念网络（Deep Belief Network, DBN），每层都是受限玻尔兹曼机（Restricted Boltzmann Machine, RBM）</li></ul><h3 id="节省训练开销"><a href="#节省训练开销" class="headerlink" title="节省训练开销"></a>节省训练开销</h3><ul><li>权值共享，如 CNN</li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;神经网络，反向传播等。&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="神经网络" scheme="https://syuoni.github.io/tags/%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C/"/>
    
    <category term="反向传播" scheme="https://syuoni.github.io/tags/%E5%8F%8D%E5%90%91%E4%BC%A0%E6%92%AD/"/>
    
  </entry>
  
  <entry>
    <title>西瓜书笔记：决策树（第 4 章）</title>
    <link href="https://syuoni.github.io/posts/ML-book-notes-4/"/>
    <id>https://syuoni.github.io/posts/ML-book-notes-4/</id>
    <published>2019-12-19T12:24:52.000Z</published>
    <updated>2019-12-22T11:36:54.000Z</updated>
    
    <content type="html"><![CDATA[<p>决策树，信息熵等。<br><a id="more"></a></p><h2 id="基本流程"><a href="#基本流程" class="headerlink" title="基本流程"></a>基本流程</h2><p>决策树的生成过程是一个 <strong>分治递归</strong> 算法</p><ul><li>递归：在当前结点找到 <strong>最优属性</strong> 进行划分/展开，划分得到的各部分生成子结点</li><li>递归边界：<ul><li>当前结点均为同一类别：将当前结点标记为该类别</li><li>当前结点样本所有属性的取值均相同：将当前结点标记为样本数最多的类别</li><li>当前结点样本为空：将当前结点标记为其父结点中样本数最多的类别</li></ul></li></ul><h2 id="划分选择"><a href="#划分选择" class="headerlink" title="划分选择"></a>划分选择</h2><h3 id="信息增益"><a href="#信息增益" class="headerlink" title="信息增益"></a>信息增益</h3><p>假定当前样本集合 $D$ 中第 $k$ 类样本所占的比例为 $p_k$ （$k=1,2,…,\vert y \vert$），则 $D$ 的 <strong>信息熵</strong> 为</p><script type="math/tex; mode=display">Ent(D) = -\sum_{k=1}^{\vert y \vert} p_k \log_2 p_k</script><p>假设属性 $a$ 有 $V$ 个可能的取值 $\{a^1, a^2,…, a^V\}$，则给定属性 $a$ 后的 <strong>条件熵</strong> 为</p><script type="math/tex; mode=display">Ent(D \mid a) = \sum_{v=1}^V \frac{\vert D^v \vert}{\vert D \vert} Ent(D^v)</script><p>则，使用属性 $a$ 对样本集 $D$ 进行划分得到的 <strong>信息增益</strong> 为</p><script type="math/tex; mode=display">Gain(D,a) = Ent(D) - Ent(D \mid a)</script><p>可以证明，<strong>信息增益</strong> 一定大于等于 0。</p><h4 id="ID3-决策树学习算法"><a href="#ID3-决策树学习算法" class="headerlink" title="ID3 决策树学习算法"></a>ID3 决策树学习算法</h4><p><strong>最优属性</strong> 的选择使得 <strong>信息增益</strong> 最大化，即</p><script type="math/tex; mode=display">a^\star = \underset{a \in A}{\mathrm{argmax}} \, Gain(D, a)</script><h4 id="C4-5-决策树学习算法"><a href="#C4-5-决策树学习算法" class="headerlink" title="C4.5 决策树学习算法"></a>C4.5 决策树学习算法</h4><p><strong>最优属性</strong> 的选择使得 <strong>信息增益率</strong> 最大化，其中 <strong>信息增益率</strong> 为 $\frac{Gain(D,a)}{Ent(a)}$，其中 $Ent(a)$ 是把属性 $a$ 当作数据集 $D$ 上的目标变量后计算的信息熵。</p><h4 id="CART-决策树学习算法"><a href="#CART-决策树学习算法" class="headerlink" title="CART 决策树学习算法"></a>CART 决策树学习算法</h4><p>基尼系数</p><script type="math/tex; mode=display">\begin{aligned}Gini(D) = \sum_{k=1}^{\vert y \vert} \sum_{k' \neq k} p_k p'_k = 1 - \sum_{k=1}^{\vert y \vert} p_k^2 \\GiniIndex(D, a) = \sum_{v=1}^V \frac{\vert D^v \vert}{\vert D \vert} Gini(D^v)\end{aligned}</script><h2 id="剪枝处理"><a href="#剪枝处理" class="headerlink" title="剪枝处理"></a>剪枝处理</h2><p>采用 <strong>留出法</strong> 预先保留一部分作为验证集，评估模型 <strong>泛化性能</strong></p><ul><li>预剪枝：展开每个结点时，评估泛化性能是否提升；若不提升则停止展开。因此，模型存在欠拟合风险。</li><li>后剪枝：将树完全展开后，依次评估每个结点剪枝后泛化性能是否提升；若提升则进行剪枝。训练时间一般较长。</li></ul><h2 id="连续值处理：二分法"><a href="#连续值处理：二分法" class="headerlink" title="连续值处理：二分法"></a>连续值处理：二分法</h2><p>假设连续属性 $a$ 在数据集 $D$ 上出现的取值从小到大排序为 $\{a^1, a^2,…, a^n\}$，则存在 $n-1$ 个潜在划分点 $t_i = \frac{a^i+a^{i+1}}{2}, \, 1 \leq i \leq n-1$。<br>此时，可以将 $a$ 作为 $n-1$ 个离散属性 $(a, t_i)$ 考虑并计算信息增益 $Gain(D, a, t_i)$ ，则 $a$ 的信息增益为</p><script type="math/tex; mode=display">Gain(D,a) = \max_{t_i} Gain(D, a, t_i)</script><p>即选出信息增益最大的那个划分点。</p><h2 id="缺失值处理"><a href="#缺失值处理" class="headerlink" title="缺失值处理"></a>缺失值处理</h2><h3 id="如何选择最优属性？"><a href="#如何选择最优属性？" class="headerlink" title="如何选择最优属性？"></a>如何选择最优属性？</h3><p>假设在当前结点中样本 $x$ 的权重为 $w_x$。令 $\tilde{D}$ 代表 $D$ 中属性 $a$ 没有缺失的样本，则</p><script type="math/tex; mode=display">Gain(D, a) = Gain(\tilde{D}, a) \times \frac{\sum_{x \in \tilde{D}}{w_x}}{\sum_{x \in D}{w_x}}</script><h3 id="如何进行样本划分？"><a href="#如何进行样本划分？" class="headerlink" title="如何进行样本划分？"></a>如何进行样本划分？</h3><p>若样本 $x$ 的属性 $a$ 缺失，则 <strong>分别同时</strong> 划入所有子结点，权重调整为</p><script type="math/tex; mode=display">w_x \cdot \frac{\sum_{x \in \tilde{D}^v}{w_x}}{\sum_{x \in \tilde{D}}{w_x}}</script><h2 id="回归树"><a href="#回归树" class="headerlink" title="回归树"></a>回归树</h2><h3 id="CART-算法"><a href="#CART-算法" class="headerlink" title="CART 算法"></a>CART 算法</h3><p>对属性 $a$ 的切分点 $t$，求解</p><script type="math/tex; mode=display">(a^\star, t^\star) = \underset{(a, t)}{\mathrm{argmin}} \left[ \min_{c_1} \sum_{x_i \in R_1(a, t)} (y_i-c_1)^2 + \min_{c_2} \sum_{x_i \in R_2(a, t)} (y_i-c_2)^2 \right]</script><p>其中，$R_1(a, t)$ 与 $R_2(a, t)$ 是 $(a, t)$ 划分得到的两个子集。显然，$c_1$ 和 $c_2$ 分别是这两个子集上 $y_i$ 的均值，即</p><script type="math/tex; mode=display">\begin{aligned}c_1 =& \frac{1}{\vert R_1(a, t) \vert} \cdot \sum_{x_i \in R_1(a, t)} y_i \\c_2 =& \frac{1}{\vert R_2(a, t) \vert} \cdot \sum_{x_i \in R_2(a, t)} y_i\end{aligned}</script>]]></content>
    
    
    <summary type="html">&lt;p&gt;决策树，信息熵等。&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="决策树" scheme="https://syuoni.github.io/tags/%E5%86%B3%E7%AD%96%E6%A0%91/"/>
    
    <category term="信息熵" scheme="https://syuoni.github.io/tags/%E4%BF%A1%E6%81%AF%E7%86%B5/"/>
    
  </entry>
  
  <entry>
    <title>西瓜书笔记：线性模型（第 3 章）</title>
    <link href="https://syuoni.github.io/posts/ML-book-notes-3/"/>
    <id>https://syuoni.github.io/posts/ML-book-notes-3/</id>
    <published>2019-12-19T08:02:07.000Z</published>
    <updated>2019-12-22T11:35:30.000Z</updated>
    
    <content type="html"><![CDATA[<p>线性回归，二值选择等。<br><a id="more"></a></p><h2 id="基本形式"><a href="#基本形式" class="headerlink" title="基本形式"></a>基本形式</h2><p>线性模型的基本形式</p><script type="math/tex; mode=display">f({\pmb x}) = {\pmb w}^{\mathrm T} {\pmb x} + b</script><h2 id="线性回归"><a href="#线性回归" class="headerlink" title="线性回归"></a>线性回归</h2><p>估计方法是最小二乘，即最小化均方误差（MSE）</p><script type="math/tex; mode=display">\begin{aligned}({\pmb w}^\star, b^\star) =& \underset{({\pmb w},b)}{\mathrm{argmin}} \sum_{i=1}^{m} (f({\pmb{x_i}}) - y_i)^2 \\=& \underset{({\pmb w},b)}{\mathrm{argmin}} \sum_{i=1}^{m} ({\pmb w}^{\mathrm T} {\pmb{x_i}} + b - y_i)^2\end{aligned}</script><p>令 $\hat{\pmb w} = ({\pmb w}; b)$，则有闭式解 </p><script type="math/tex; mode=display">\hat{\pmb w}^\star = ({\pmb X}^{\mathrm T} {\pmb X})^{-1} {\pmb X}^{\mathrm T} {\pmb y}</script><p>引入正则</p><ul><li>Lasso</li><li>Ridge</li></ul><h2 id="对数几率回归"><a href="#对数几率回归" class="headerlink" title="对数几率回归"></a>对数几率回归</h2><p>模型为</p><script type="math/tex; mode=display">P(y=1 \mid {\pmb x}) = \begin{cases} \Phi({\pmb w}^{\mathrm T} {\pmb x}) = \int_{-\infty}^{w^{\mathrm T} x} \phi({\pmb x}) {\mathrm d}x, & \text{若使用正态分布累计函数，即 Probit 回归} \\ \Lambda({\pmb w}^{\mathrm T} {\pmb x}) = \frac{\exp({\pmb w}^{\mathrm T} {\pmb x})}{1+\exp({\pmb w}^{\mathrm T} {\pmb x})} = \frac{1}{1+\exp(-{\pmb w}^{\mathrm T} {\pmb x})}, & \text{若使用逻辑分布累计函数，即 Logit 回归} \end{cases}</script><p>Logit 回归即对数几率回归</p><script type="math/tex; mode=display">y = \frac{1}{1+\exp(-{\pmb w}^{\mathrm T} {\pmb x})} \implies \log(\frac{y}{1-y}) = {\pmb w}^{\mathrm T} {\pmb x}</script><p>使用 MLE 估计，对数似然函数为</p><script type="math/tex; mode=display">\begin{aligned}\mathcal{L}({\pmb w}) =& \log \left[\prod_i P(y_i \mid {\pmb{x_i}}; {\pmb w}) \right] \\=& \sum_{y_i=1} \log \left[ P(y=1 \mid {\pmb{x_i}}; {\pmb w}) \right] + \sum_{y_i=0} \log \left[ P(y=0 \mid {\pmb{x_i}}; {\pmb w}) \right] \\=& \sum_{y_i=1} \log \left[ \frac{\exp({\pmb w}^{\mathrm T} {\pmb{x_i}})}{1+\exp({\pmb w}^{\mathrm T} {\pmb{x_i}})} \right] + \sum_{y_i=0} \log \left[ \frac{1}{1+\exp({\pmb w}^{\mathrm T} {\pmb{x_i}})} \right] \\=& \sum_i y_i({\pmb w}^{\mathrm T} {\pmb{x_i}}) - \log(1+\exp({\pmb w}^{\mathrm T} {\pmb{x_i}}))\end{aligned}</script><h2 id="线性判别分析"><a href="#线性判别分析" class="headerlink" title="线性判别分析"></a>线性判别分析</h2><p>线性判别分析（Linear Discriminant Analysis, LDA）是将样本投影到直线（或低维空间）上，使得组内距离尽可能小、组间距离尽可能大。<br>线性判别分析也被用于监督降维。</p><h2 id="多分类学习"><a href="#多分类学习" class="headerlink" title="多分类学习"></a>多分类学习</h2><p>二分类模型推广至多分类的方案：</p><ul><li>One vs. One</li><li>One vs. Many</li><li>Many vs. Many</li></ul><h2 id="类别不平衡问题"><a href="#类别不平衡问题" class="headerlink" title="类别不平衡问题"></a>类别不平衡问题</h2><h3 id="再缩放（Rescaling）"><a href="#再缩放（Rescaling）" class="headerlink" title="再缩放（Rescaling）"></a>再缩放（Rescaling）</h3><p>原本， $\frac{y}{1 - y} &gt; 1$ 时，预测为正例<br>现在，$\frac{y}{1 - y} &gt; \frac{m^+}{m^-}$ 时，预测为正例；其中 ${m^+}$ 与 ${m^-}$ 分别为正例与负例的数目。</p><h3 id="重采样"><a href="#重采样" class="headerlink" title="重采样"></a>重采样</h3><ul><li>欠采样/下采样：训练多个模型并集成</li><li>过采样/上采样：对数目少的那一类样本进行插值</li><li>阈值移动：将再缩放的公式嵌入决策过程</li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;线性回归，二值选择等。&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="线性模型" scheme="https://syuoni.github.io/tags/%E7%BA%BF%E6%80%A7%E6%A8%A1%E5%9E%8B/"/>
    
    <category term="分类模型" scheme="https://syuoni.github.io/tags/%E5%88%86%E7%B1%BB%E6%A8%A1%E5%9E%8B/"/>
    
    <category term="回归模型" scheme="https://syuoni.github.io/tags/%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/"/>
    
  </entry>
  
  <entry>
    <title>西瓜书笔记：模型评估与选择（第 2 章）</title>
    <link href="https://syuoni.github.io/posts/ML-book-notes-2/"/>
    <id>https://syuoni.github.io/posts/ML-book-notes-2/</id>
    <published>2019-12-19T01:46:27.000Z</published>
    <updated>2019-12-22T12:04:54.000Z</updated>
    
    <content type="html"><![CDATA[<p>过拟合，经验误差，评估方法，性能度量等。<br><a id="more"></a></p><h2 id="经验误差与过拟合"><a href="#经验误差与过拟合" class="headerlink" title="经验误差与过拟合"></a>经验误差与过拟合</h2><ul><li>经验误差</li><li>过拟合</li></ul><h2 id="评估方法"><a href="#评估方法" class="headerlink" title="评估方法"></a>评估方法</h2><ul><li>留出法</li><li>Cross-Validation</li><li>自助法（Bootstrapping）：平均 36.8% 的样本在采样集外，可用于包外估计（Out-of-Bag Estimate）。</li></ul><h2 id="性能度量"><a href="#性能度量" class="headerlink" title="性能度量"></a>性能度量</h2><ul><li>回归任务：Mean Square Error</li><li>分类任务：Accuracy</li></ul><h3 id="Precision-和-Recall"><a href="#Precision-和-Recall" class="headerlink" title="Precision 和 Recall"></a>Precision 和 Recall</h3><p>Precision 和 Recall 的定义</p><script type="math/tex; mode=display">\begin{aligned}Precision =& \frac {N_{TruePos}} {N_{PredPos}} = \frac {N_{TruePos}} {N_{TruePos} + N_{FalsePos}} \\Recall =& \frac {N_{TruePos}} {N_{OriPos}} = \frac {N_{TruePos}} {N_{TruePos} + N_{FalseNeg}}\end{aligned}</script><p>F1-score 是 Precision 和 Recall 的调和平均数</p><script type="math/tex; mode=display">F1 = \left( \frac {P^{-1} + R^{-1}} {2} \right)^{-1} = \frac {2}{1/P + 1/R}</script><h4 id="P-R-曲线"><a href="#P-R-曲线" class="headerlink" title="P-R 曲线"></a>P-R 曲线</h4><ul><li>当判别为正例的标准最严格（仅有极少数最明显的被判别为正例），此时 $Recall \to 0$，$Precision \to 1$。</li><li>当判别为正例的标准最宽松（所有样本均判别为正例），此时 $Recall \to 1$，$Precision \to N_{OriPos} / N$。<br><em>Precision 应该不会趋近于 0 吧？</em></li></ul><p><img src="/images/ML-book/2.3.png" alt="图2.3 P-R 曲线与平衡点示意图"></p><h3 id="ROC-和-AUC"><a href="#ROC-和-AUC" class="headerlink" title="ROC 和 AUC"></a>ROC 和 AUC</h3><h4 id="ROC-曲线"><a href="#ROC-曲线" class="headerlink" title="ROC 曲线"></a>ROC 曲线</h4><p>ROC 全称受试者工作特征（Receiver Operating Characteristics），该曲线横轴为假正例率（False Positive Rate, FPR），纵轴为真正例率（True Positive Rate,TPR），定义为</p><script type="math/tex; mode=display">\begin{aligned}{\it FPR} =& \frac {N_{FalsePos}} {N_{OriNeg}} \\{\it TPR} =& \frac {N_{TruePos}} {N_{OriPos}} = Recall\end{aligned}</script><ul><li>当判别为正例的标准最严格（仅有极少数最明显的被判别为正例），此时 ${\it TPR} \to 0$，${\it FPR} \to 0$。</li><li>当判别为正例的标准最宽松（所有样本均判别为正例），此时 ${\it TPR} \to 1$，${\it FPR} \to 1$。</li></ul><p><img src="/images/ML-book/2.4.png" alt="图2.4 ROC 曲线与 AUC 示意图"></p><ul><li>AUC （Area under ROC Curve）就是 ROC 曲线下的面积，可以作为模型性能指标。</li><li>K-S 指标：${\it KS} = \max {\it TPR} - {\it FPR}$</li></ul><p>在风险管理中，假正例的成本远高于假反例，因此需要更关注提高 Precision （或者说降低 FPR），而 Recall （或者 TPR）的权重更小。</p><h2 id="方差与偏差"><a href="#方差与偏差" class="headerlink" title="方差与偏差"></a>方差与偏差</h2><p>模型的 <strong>泛化误差</strong> 可以分解为 <strong>偏差</strong>、<strong>方差</strong>、<strong>噪声</strong> 之和。<br>以回归任务为例，对测试样本 ${\pmb x}$，令 $y_D$ 为 ${\pmb x}$ 在整个数据集中的标记，$y$ 为 ${\pmb x}$ 的真实标记，则 <strong>噪声</strong> 为</p><script type="math/tex; mode=display">\varepsilon^2 = \mathbb{E}_D [(y_D-y)^2]</script><p>$f({\pmb x}; D)$ 为训练集 $D$ 上学得的模型 $f$ 在 ${\pmb x}$ 上的预测输出。在潜在的不同训练集 $D$ 上训练得到的学习算法的 <strong>期望预测</strong> 为</p><script type="math/tex; mode=display">\bar{f}({\pmb x}) = \mathbb{E}_D [f({\pmb x}; D)]</script><p>因此，使用不同训练集产生的 <strong>方差</strong> 为</p><script type="math/tex; mode=display">var({\pmb x}) = \mathbb{E}_D [(f({\pmb x}; D) - \bar{f}({\pmb x}))^2]</script><p><strong>期望预测</strong> 与真实标记的差别 <strong>偏差</strong> 为</p><script type="math/tex; mode=display">bias^2({\pmb x}) = (\bar{f}({\pmb x}) - y)^2</script><p>对算法的 <strong>期望泛化误差</strong> 进行分解</p><script type="math/tex; mode=display">\begin{aligned}\mathbb{E}_D [(f({\pmb x}; D) - y_D)^2] =& \mathbb{E}_D [(f({\pmb x}; D) - \bar{f}({\pmb x}) + \bar{f}({\pmb x}) - y_D)^2] \\=& \mathbb{E}_D [(f({\pmb x}; D) - \bar{f}({\pmb x}))^2] + \mathbb{E}_D [(\bar{f}({\pmb x}) - y_D)^2] + \underbrace{ \mathbb{E}_D [ 2 (f({\pmb x}; D) - \bar{f}({\pmb x}))(\bar{f}({\pmb x}) - y_D) ]}_{=0, \, \text{because of independence}} \\=& var({\pmb x}) + \mathbb{E}_D [(\bar{f}({\pmb x}) - y + y - y_D)^2] \\=& var({\pmb x}) + (\bar{f}({\pmb x}) - y)^2 + \mathbb{E}_D [(y - y_D)^2] + \underbrace{ \mathbb{E}_D [ 2 (\bar{f}({\pmb x}) - y)(y - y_D) ]}_{=0, \, \text{because of independence}} \\=& var({\pmb x}) + bias^2({\pmb x}) + \varepsilon^2\end{aligned}</script><p>对方差与偏差的理解：</p><ul><li>过拟合：不同训练集 $D$ 产生的预测 $f({\pmb x}; D)$ 之间差异大，也就是 <strong>方差大</strong>。</li><li>欠拟合：训练集未能使得模型 $f({\pmb x}; D)$ 显著变化，也就是 <strong>偏差大</strong>。</li></ul><h2 id="相关概念：第一类错误和第二类错误"><a href="#相关概念：第一类错误和第二类错误" class="headerlink" title="相关概念：第一类错误和第二类错误"></a>相关概念：第一类错误和第二类错误</h2><ul><li>第一类错误是 <strong>拒真</strong> 错误，显著性 $\alpha$ 就是 <strong>拒真</strong> 的概率。</li><li>第二类错误时 <strong>纳伪</strong> 错误。</li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;过拟合，经验误差，评估方法，性能度量等。&lt;br&gt;</summary>
    
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    
    <category term="机器学习" scheme="https://syuoni.github.io/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/"/>
    
    <category term="模型评估" scheme="https://syuoni.github.io/tags/%E6%A8%A1%E5%9E%8B%E8%AF%84%E4%BC%B0/"/>
    
  </entry>
  
  <entry>
    <title>Python 和 C++ 字符串比较</title>
    <link href="https://syuoni.github.io/posts/python-cpp-string-functions/"/>
    <id>https://syuoni.github.io/posts/python-cpp-string-functions/</id>
    <published>2019-12-18T02:25:09.000Z</published>
    <updated>2019-12-19T01:45:04.000Z</updated>
    
    <content type="html"><![CDATA[<p>从本科大三学了 Python 之后，基本就一直在用 Python，除了部分课程作业用 Java 完成项目以及研一暑假时学了一小段时间的 R。<br>尤其是研二初学会了 Python 的 numpy 和 pandas 库之后，基本也没有再遇到过性能问题。因为我写代码主要是为了科研数据处理，多数情况都可以把问题向量化。<br>2019 年秋招开始后，也用着 Python 刷了 LeetCode 的前 70 多道题，遇到一些无法向量化的问题，这时候 Python 的性能劣势就体现出来了。其中，最主要的一点是，Python 的封装实在太高级了，在使用时用户对很多内建函数的复杂度都没有概念。所以，花了一周多时间复习完 C++ 语法后，我开始用 C++ 刷 LeetCode。<br>这篇博文是比较 Python 和 C++ 在字符串处理中的不同。<br><a id="more"></a></p><h2 id="定义字符串"><a href="#定义字符串" class="headerlink" title="定义字符串"></a>定义字符串</h2><h3 id="Python"><a href="#Python" class="headerlink" title="Python"></a>Python</h3><p>不区分字符与字符串，单引号与双引号可以替换使用<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">char0 = <span class="string">"A"</span></span><br><span class="line">str0 = <span class="string">"Hello World!"</span></span><br></pre></td></tr></table></figure></p><h3 id="C"><a href="#C" class="headerlink" title="C++"></a>C++</h3><p>区分字符与字符串，字符用单引号，字符串用双引号<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">char</span> c0 = <span class="string">'A'</span>;</span><br><span class="line"><span class="keyword">char</span> str0[] = <span class="string">"Hello World!"</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">string</span> str1 = <span class="string">"Hello World!"</span>;</span><br><span class="line"><span class="function"><span class="built_in">string</span> <span class="title">str2</span><span class="params">(str0)</span></span>;</span><br><span class="line"><span class="function"><span class="built_in">string</span> <span class="title">str3</span><span class="params">(<span class="number">5</span>, c0)</span></span>;</span><br></pre></td></tr></table></figure></p><h2 id="截取字符串"><a href="#截取字符串" class="headerlink" title="截取字符串"></a>截取字符串</h2><h3 id="Python-1"><a href="#Python-1" class="headerlink" title="Python"></a>Python</h3><p>字符串可以用切片截取；字符串是 <strong>Immutable</strong>，不可修改的<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">str0 = <span class="string">"Hello World!"</span></span><br><span class="line">print(str0[<span class="number">1</span>])      <span class="comment"># 输出 "e"</span></span><br><span class="line">print(str0[<span class="number">1</span>:<span class="number">4</span>])    <span class="comment"># 输出 "ell"</span></span><br><span class="line"></span><br><span class="line">str0[<span class="number">1</span>] = <span class="string">"A"</span>       <span class="comment"># 会报错</span></span><br></pre></td></tr></table></figure></p><h3 id="C-1"><a href="#C-1" class="headerlink" title="C++"></a>C++</h3><p>字符串可以用下标访问或修改对应位置字符<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">string</span> str1 = <span class="string">"Hello World!"</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; str1[<span class="number">3</span>] &lt;&lt; <span class="built_in">endl</span>;    <span class="comment">// 输出字符 'l'</span></span><br><span class="line">str1[<span class="number">3</span>] = <span class="string">'U'</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; str1 &lt;&lt; <span class="built_in">endl</span>;       <span class="comment">// 输出字符串 "HelUo World!"</span></span><br></pre></td></tr></table></figure></p><p>使用 <code>string</code> 类自带的函数 <code>substr</code> 来截取字符；具体地，<code>substr(pos, n)</code> 返回 <code>pos</code> 开始的 <code>n</code> 个字符组成的字符串<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cout</span> &lt;&lt; str1.substr(<span class="number">3</span>, <span class="number">5</span>) &lt;&lt; <span class="built_in">endl</span>;    <span class="comment">// 输出 "Uo Wo"</span></span><br></pre></td></tr></table></figure></p><h2 id="连接字符串"><a href="#连接字符串" class="headerlink" title="连接字符串"></a>连接字符串</h2><h3 id="Python-2"><a href="#Python-2" class="headerlink" title="Python"></a>Python</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">str0 = <span class="string">"Hello World!"</span></span><br><span class="line">print(str0 + str0)     <span class="comment"># 输出 "Hello World!Hello World!"</span></span><br></pre></td></tr></table></figure><h3 id="C-2"><a href="#C-2" class="headerlink" title="C++"></a>C++</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cout</span> &lt;&lt; str1 + str2 &lt;&lt; <span class="built_in">endl</span>;     <span class="comment">// 输出 "HelUo World!Hello World!"</span></span><br><span class="line">str1 += str2;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; str1 &lt;&lt; <span class="built_in">endl</span>;            <span class="comment">// 输出 "HelUo World!Hello World!"</span></span><br><span class="line">str1.append(str2);</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; str1 &lt;&lt; <span class="built_in">endl</span>;            <span class="comment">// 输出 "HelUo World!Hello World!Hello World!"</span></span><br></pre></td></tr></table></figure><h2 id="字符串长度"><a href="#字符串长度" class="headerlink" title="字符串长度"></a>字符串长度</h2><h3 id="Python-3"><a href="#Python-3" class="headerlink" title="Python"></a>Python</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">str0 = <span class="string">"Hello World!"</span></span><br><span class="line">print(len(str0))     <span class="comment"># 输出 12</span></span><br></pre></td></tr></table></figure><h3 id="C-3"><a href="#C-3" class="headerlink" title="C++"></a>C++</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cout</span> &lt;&lt; str1.<span class="built_in">size</span>() &lt;&lt; <span class="string">" "</span> &lt;&lt; str1.length() &lt;&lt; <span class="built_in">endl</span>;  <span class="comment">// 输出 36 36</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; str1.empty() &lt;&lt; <span class="built_in">endl</span>;                         <span class="comment">// 输出 false</span></span><br></pre></td></tr></table></figure><h2 id="字符串查找"><a href="#字符串查找" class="headerlink" title="字符串查找"></a>字符串查找</h2><h3 id="Python-4"><a href="#Python-4" class="headerlink" title="Python"></a>Python</h3><p>使用 <code>str</code> 类的 <code>find</code> 和 <code>index</code> 函数进行查找；其中，<code>find</code> 在查找失败时返回 -1，而 <code>index</code> 查找失败时报错<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">str0 = <span class="string">"Hello World!"</span></span><br><span class="line">print(<span class="string">"A"</span> <span class="keyword">in</span> str0)         <span class="comment"># 输出 False</span></span><br><span class="line">print(str0.find(<span class="string">"W"</span>))      <span class="comment"># 输出 6</span></span><br><span class="line">print(str0.find(<span class="string">"A"</span>))      <span class="comment"># 输出 -1</span></span><br><span class="line"></span><br><span class="line">print(str0.index(<span class="string">"W"</span>))     <span class="comment"># 输出 6</span></span><br><span class="line">print(str0.index(<span class="string">"A"</span>))     <span class="comment"># 报错</span></span><br></pre></td></tr></table></figure></p><h3 id="C-4"><a href="#C-4" class="headerlink" title="C++"></a>C++</h3><p>使用 <code>string</code> 类的 查找成功时返回所在位置，失败返回 <code>string::npos</code> 的值<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cout</span> &lt;&lt; str1.<span class="built_in">find</span>(<span class="string">'o'</span>) &lt;&lt; <span class="built_in">endl</span>;       <span class="comment">// 输出 4</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; str1.<span class="built_in">find</span>(<span class="string">"llo"</span>) &lt;&lt; <span class="built_in">endl</span>;     <span class="comment">// 输出 14</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; str1.<span class="built_in">find</span>(<span class="string">'A'</span>) &lt;&lt; <span class="string">" "</span> &lt;&lt; str1.npos &lt;&lt; <span class="built_in">endl</span>;   <span class="comment">// 输出 18446744073709551615 18446744073709551615</span></span><br></pre></td></tr></table></figure></p><h2 id="字符串替换、插入"><a href="#字符串替换、插入" class="headerlink" title="字符串替换、插入"></a>字符串替换、插入</h2><h3 id="Python-5"><a href="#Python-5" class="headerlink" title="Python"></a>Python</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">str0 = <span class="string">"Hello World!"</span></span><br><span class="line">print(str0.replace(<span class="string">"l"</span>, <span class="string">"L"</span>))     <span class="comment"># 输出 "HeLLo WorLd!"</span></span><br></pre></td></tr></table></figure><h3 id="C-5"><a href="#C-5" class="headerlink" title="C++"></a>C++</h3><p>从下标为 2 的位置开始，删除 4 个字符，并替换为 “ZEW”<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str1.replace(<span class="number">2</span>, <span class="number">4</span>, <span class="string">"ZEW"</span>);</span><br></pre></td></tr></table></figure><br>把 “SYUONI” 插入，并使得其开始位置下标为 2<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str1.insert(<span class="number">2</span>, <span class="string">"SYUONI"</span>);</span><br></pre></td></tr></table></figure></p><h2 id="统计子串出现次数"><a href="#统计子串出现次数" class="headerlink" title="统计子串出现次数"></a>统计子串出现次数</h2><h3 id="Python-6"><a href="#Python-6" class="headerlink" title="Python"></a>Python</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">str0 = <span class="string">"Hello World!"</span></span><br><span class="line">print(str0.count(<span class="string">"l"</span>))     <span class="comment"># 输出 3</span></span><br></pre></td></tr></table></figure><h2 id="补齐长度"><a href="#补齐长度" class="headerlink" title="补齐长度"></a>补齐长度</h2><h3 id="Python-7"><a href="#Python-7" class="headerlink" title="Python"></a>Python</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">str0 = <span class="string">"Hello World!"</span></span><br><span class="line">print(str0.ljust(<span class="number">20</span>, <span class="string">"-"</span>))   <span class="comment"># 输出 "Hello World!--------"</span></span><br><span class="line">print(str0.rjust(<span class="number">20</span>, <span class="string">"-"</span>))   <span class="comment"># 输出 "--------Hello World!"</span></span><br></pre></td></tr></table></figure>]]></content>
    
    
    <summary type="html">&lt;p&gt;从本科大三学了 Python 之后，基本就一直在用 Python，除了部分课程作业用 Java 完成项目以及研一暑假时学了一小段时间的 R。&lt;br&gt;尤其是研二初学会了 Python 的 numpy 和 pandas 库之后，基本也没有再遇到过性能问题。因为我写代码主要是为了科研数据处理，多数情况都可以把问题向量化。&lt;br&gt;2019 年秋招开始后，也用着 Python 刷了 LeetCode 的前 70 多道题，遇到一些无法向量化的问题，这时候 Python 的性能劣势就体现出来了。其中，最主要的一点是，Python 的封装实在太高级了，在使用时用户对很多内建函数的复杂度都没有概念。所以，花了一周多时间复习完 C++ 语法后，我开始用 C++ 刷 LeetCode。&lt;br&gt;这篇博文是比较 Python 和 C++ 在字符串处理中的不同。&lt;br&gt;</summary>
    
    
    
    <category term="语言" scheme="https://syuoni.github.io/categories/%E8%AF%AD%E8%A8%80/"/>
    
    
    <category term="Python" scheme="https://syuoni.github.io/tags/Python/"/>
    
    <category term="C++" scheme="https://syuoni.github.io/tags/C/"/>
    
  </entry>
  
</feed>
