<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://pnhuy.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://pnhuy.github.io/" rel="alternate" type="text/html" /><updated>2026-11-11T09:14:52+00:00</updated><id>https://pnhuy.github.io/feed.xml</id><title type="html">HuyNotes</title><subtitle>My Learning Curve
</subtitle><author><name>Huy Pham</name></author><entry><title type="html">An Attention-Based Multi-Input Network for EGFR Inhibitors</title><link href="https://pnhuy.github.io/machinelearning/2026/08/25/attention-multi-input-egfr-inhibitors.html" rel="alternate" type="text/html" title="An Attention-Based Multi-Input Network for EGFR Inhibitors" /><published>2026-08-25T00:00:00+00:00</published><updated>2026-08-25T00:00:00+00:00</updated><id>https://pnhuy.github.io/machinelearning/2026/08/25/attention-multi-input-egfr-inhibitors</id><content type="html" xml:base="https://pnhuy.github.io/machinelearning/2026/08/25/attention-multi-input-egfr-inhibitors.html"><![CDATA[<p>A few years after the <a href="/pharmacy/2026/08/24/tropane-alkaloids-in-angels-trumpet-leaves.html">Angel’s trumpet work</a>,
I was doing the same kind of question — which molecules are active, and why — with a GPU instead of
a separatory funnel. This post introduces the paper I wrote with
<a href="https://www.linkedin.com/in/trung-hoang-le">Trung Hoang Le</a>:
<a href="https://arxiv.org/abs/1906.05168"><em>Attention-based Multi-Input Deep Learning Architecture for Biological Activity Prediction: An Application in EGFR Inhibitors</em></a>
published at the <em>2019 11th International Conference on Knowledge and Systems Engineering (KSE)</em>.
Code is at <a href="https://github.com/lehgtrung/egfr-att">lehgtrung/egfr-att</a>.</p>

<h2 id="the-problem-with-training-features-separately">The problem with training features separately</h2>

<p>A molecule can be described two ways, and they carry different information.</p>

<p>You can describe its <strong>structure</strong> — the atoms, the bonds, the rings — usually as a fingerprint
vector or, as we did, straight from the SMILES string. Or you can describe its <strong>chemistry</strong> —
logP, dipole moment, the thousand-odd computed molecular descriptors that summarise how the
whole molecule behaves.</p>

<p>Studies had already established that combining both helps. But the way it was done was: train
one model on structure, train a second model on descriptors, then feed both outputs into a third
model that makes the final call. That works, and it is also awkward. Every feature set needs its
own algorithm, so you cannot build one pipeline; you build three and hope they stay in sync.
The models never see each other during training.</p>

<p>Our question was simply: what if both go into one network, trained at once?</p>

<p>The second problem was interpretation. A neural network that says <em>0.87, inhibitor</em> and nothing
else is hard to use in medicinal chemistry, where the actionable question is which part of the
molecule you should keep and which part you should change.</p>

<h2 id="the-architecture">The architecture</h2>

<p><img src="/assets/images/egfr-att-architecture.png" alt="Architecture of the attention-based multi-input model: a SMILES feature matrix through two convolution layers into a SMILES vector, a molecular descriptor vector through three linear layers, attention weights applied to the structural branch, then concatenation and a sigmoid output" /></p>

<p>Two branches meeting at a concatenation.</p>

<p>The <strong>CNN branch</strong> takes structure. Each SMILES string is encoded as a matrix using
M. Hirohara’s scheme: one row per character, padded to 150 rows, and 42 features per row — 21
describing the atom (element, attached hydrogens, degree, charge, valence, ring membership,
aromaticity, chirality, hybridisation) and 21 describing SMILES syntax (brackets, bonds,
branch markers, start and end). That matrix goes through two convolution blocks — conv2d, batch
norm, dropout, max pool — and a linear layer.</p>

<p>The <strong>MD branch</strong> takes chemistry. 1613 two-dimensional descriptors computed with <code class="language-plaintext highlighter-rouge">mordred</code>,
cleaned of constant and meaningless columns, standard-scaled, then three fully connected blocks
narrowing 512 → 128 → 64.</p>

<p>The <strong>attention layer</strong> sits on the structural branch. Let $R_i$ be row $i$ of the SMILES
feature matrix — that is, one atom — and $\vec{m}$ the vector coming out of the CNN branch’s
linear layer. The attention weight for that atom is the similarity between the two, squashed:</p>

\[a_i = \frac{1}{1 + \exp(R_i \cdot \vec{m})}\]

<p>and the layer’s output is the weighted sum $\vec{f} = \sum_i a_i R_i$.</p>

<p>The point is that $a_i$ is a number attached to a specific atom. You can read it off after
training and ask the model which atoms it was looking at.</p>

<p>Then $\vec{f}$, $\vec{m}$ and the descriptor vector $\vec{t}$ are concatenated, passed
through one linear layer, and squashed by a sigmoid into the probability that the compound
inhibits EGFR.</p>

<h2 id="the-data">The data</h2>

<p>EGFR — the epidermal growth factor receptor — is a tyrosine kinase whose dysregulation drives
several cancers, lung cancer especially, which makes it one of the most-studied targets in
oncology.</p>

<p>We used H. Singh et al.’s dataset: 3492 compounds labelled inhibitor or non-inhibitor at an
IC<sub>50</sub> threshold of 10 nM. The ratio is 506 inhibitors to 2986 non-inhibitors, about
1 : 6, so the class imbalance is real and the metric choice matters. Singh’s Random Forest model
on the same data is the baseline we had to beat.</p>

<p>Everything was implemented in PyTorch, tuned by grid search, and evaluated by 5-fold
cross-validation with early stopping at 30 epochs of rising loss. The winning configuration:
batch size 128, dropout 0.5, ADAM, learning rate 1e-5, decision threshold 0.2.</p>

<h2 id="results">Results</h2>

<p>We report MCC as the primary metric. Accuracy and F1 both ignore parts of the confusion matrix,
and on a 1 : 6 split that is how you fool yourself; MCC uses all four cells.</p>

<table>
  <thead>
    <tr>
      <th style="text-align: left">Metric</th>
      <th style="text-align: right">H. Singh et al.</th>
      <th style="text-align: right">CNN only</th>
      <th style="text-align: right">CNN + MD</th>
      <th style="text-align: right">CNN + MD + ATT</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: left">Sensitivity</td>
      <td style="text-align: right">69.89%</td>
      <td style="text-align: right">74.31%</td>
      <td style="text-align: right">75.29%</td>
      <td style="text-align: right">74.11%</td>
    </tr>
    <tr>
      <td style="text-align: left">Specificity</td>
      <td style="text-align: right">86.03%</td>
      <td style="text-align: right">85.77%</td>
      <td style="text-align: right">89.75%</td>
      <td style="text-align: right"><strong>90.15%</strong></td>
    </tr>
    <tr>
      <td style="text-align: left">Accuracy</td>
      <td style="text-align: right">83.66%</td>
      <td style="text-align: right">84.10%</td>
      <td style="text-align: right">87.66%</td>
      <td style="text-align: right"><strong>87.83%</strong></td>
    </tr>
    <tr>
      <td style="text-align: left">MCC</td>
      <td style="text-align: right">0.49</td>
      <td style="text-align: right">0.50</td>
      <td style="text-align: right"><strong>0.58</strong></td>
      <td style="text-align: right">0.57</td>
    </tr>
    <tr>
      <td style="text-align: left">AUC</td>
      <td style="text-align: right">89.00%</td>
      <td style="text-align: right">87.52%</td>
      <td style="text-align: right">90.32%</td>
      <td style="text-align: right"><strong>90.84%</strong></td>
    </tr>
    <tr>
      <td style="text-align: left">Loss</td>
      <td style="text-align: right">—</td>
      <td style="text-align: right">0.2727</td>
      <td style="text-align: right">0.2434</td>
      <td style="text-align: right"><strong>0.2399</strong></td>
    </tr>
    <tr>
      <td style="text-align: left">Running time</td>
      <td style="text-align: right">—</td>
      <td style="text-align: right">59 min</td>
      <td style="text-align: right"><strong>31 min</strong></td>
      <td style="text-align: right">37 min</td>
    </tr>
  </tbody>
</table>

<p>Three things in that table are worth pulling out.</p>

<p><strong>Structure alone is not enough.</strong> The CNN-only model barely matches the Random Forest baseline
and is actually worse on AUC. Our reading is sparsity: padding every SMILES string out to 150
rows leaves a mostly-empty matrix, and a sparse input needs more data than 3492 compounds to
train on.</p>

<p><strong>Adding the descriptor branch fixes it.</strong> MCC goes 0.50 → 0.58, AUC 87.5% → 90.3%. The second
input gives the network information it can use immediately, rather than having to extract it
from a sparse matrix.</p>

<p><strong>And it trains faster.</strong> The bigger model takes <em>half</em> the time of the small one — 31 minutes
against 59. The sparse-input model needs many more epochs to converge; when the descriptor
branch is there, information appears to flow between the branches and the loss settles much
sooner. That was the result that surprised us most, and it is exactly what the
train-each-feature-set-separately approach throws away.</p>

<h2 id="what-the-model-looks-at">What the model looks at</h2>

<p><img src="/assets/images/egfr-att-attention-weights.png" alt="Four EGFR inhibitor structures with attention weights rendered as green contour density over the atoms, concentrated on heterocyclic nitrogens and halobenzyl substituents" /></p>

<p>Attention weights, one per atom, rendered over the structure with <code class="language-plaintext highlighter-rouge">rdkit</code>. Darker means the
model weighted that atom more heavily.</p>

<p>Two patterns show up across compounds: <strong>nitrogens in heterocyclic rings</strong> are consistently
highlighted, and <strong>halobenzyl substitution on a heterocycle</strong> contributes positively to
predicted activity. Both are recognisable to anyone who has looked at this chemical series —
which is the point. The model is not being asked to teach us new pharmacology here; it is being
asked to show that its confidence rests on the parts of the molecule that ought to matter.</p>

<p>Note that attention cost us nothing on MCC (0.58 → 0.57) and gained a little on AUC and
specificity. We did not tune the attention model hard, because interpretability was what we
wanted from it.</p>

<h2 id="limitations">Limitations</h2>

<p><strong>Attention is per-atom, so functional groups are invisible.</strong> Each row of the feature matrix is
one atom, weighted independently. A carbonyl or a carboxylic acid is a unit chemically, but the
model has no way to say so. The fix we proposed is a third branch embedding substructure
patterns — ECFP, or a hashed fingerprint — so groups can carry weight as groups.</p>

<p><strong>The dataset is small for deep learning.</strong> 3492 compounds, and the CNN-only result shows what
that costs when the input is sparse.</p>

<p><strong>Attention did not improve accuracy.</strong> It bought interpretation, not performance. Whether
tuning it properly would change that, we did not find out.</p>

<hr />

<p><em>Huy Ngoc Pham, Trung Hoang Le. <a href="https://arxiv.org/abs/1906.05168">“Attention-based Multi-Input Deep Learning Architecture for
Biological Activity Prediction: An Application in EGFR Inhibitors”</a>.
In 2019 11th International Conference on Knowledge and Systems Engineering (KSE), IEEE, 2019.
Preprint: arXiv:1906.05168. Figures reproduced from the paper. Implementation:
<a href="https://github.com/lehgtrung/egfr-att">github.com/lehgtrung/egfr-att</a>.</em></p>]]></content><author><name>Huy Pham</name></author><category term="machinelearning" /><summary type="html"><![CDATA[A few years after the Angel’s trumpet work, I was doing the same kind of question — which molecules are active, and why — with a GPU instead of a separatory funnel. This post introduces the paper I wrote with Trung Hoang Le: Attention-based Multi-Input Deep Learning Architecture for Biological Activity Prediction: An Application in EGFR Inhibitors published at the 2019 11th International Conference on Knowledge and Systems Engineering (KSE). Code is at lehgtrung/egfr-att.]]></summary></entry><entry><title type="html">Tropane Alkaloids in Angel’s Trumpet Leaves</title><link href="https://pnhuy.github.io/pharmacy/2026/08/24/tropane-alkaloids-in-angels-trumpet-leaves.html" rel="alternate" type="text/html" title="Tropane Alkaloids in Angel’s Trumpet Leaves" /><published>2026-08-24T00:00:00+00:00</published><updated>2026-08-24T00:00:00+00:00</updated><id>https://pnhuy.github.io/pharmacy/2026/08/24/tropane-alkaloids-in-angels-trumpet-leaves</id><content type="html" xml:base="https://pnhuy.github.io/pharmacy/2026/08/24/tropane-alkaloids-in-angels-trumpet-leaves.html"><![CDATA[<p>Before any of the machine learning, I spent many years on a bench in Ho Chi Minh City taking a
plant apart. This was my thesis for my Degree of Pharmacist at the University of Medicine
and Pharmacy, supervised by Dr. Nguyen Viet Kinh and Mr. Nguyen Manh Tin Tin. I want to write it down properly, partly
because it is the work I am still most fond of, and partly because the reasoning in it —
find the one step that makes everything downstream easier — turned out to be the same
reasoning I use now on entirely different problems.</p>

<p>The full thesis with all figures, tables and spectra is on ResearchGate: <a href="https://www.researchgate.net/publication/413567545_Studies_On_Chemical_Constituents_From_Angel's_Trumpet_Leaves_Folium_Brugmansiae"><em>Studies on chemical constituents from Angel’s trumpet
leaves</em> (Folium Brugmansiae)</a>. What follows is the short version.</p>

<h2 id="the-question">The question</h2>

<p><em>Brugmansia suaveolens</em>, angel’s trumpet, is grown as an ornamental all over Vietnam. It is
a large, pleasant, drooping-flowered shrub that people plant next to their houses, and its
flowers and leaves have been eaten — sometimes deliberately, sometimes not. The poisonings
that follow have a particular character: dry mouth, dilated pupils, confusion, hallucination.
That is an anticholinergic syndrome, and it points at tropane alkaloids.</p>

<p>So there were two questions, one defensive and one opportunistic. Despite that people conducted
multiple studies on flower, the leaf had limited attention. What is actually in the
leaf that makes it poisonous? And given that whatever is in there is present in quantity,
could the leaf serve as a raw material for scopolamine?</p>

<h2 id="the-material">The material</h2>

<p>Twenty kilograms of dried leaf, collected at Di Linh in Lâm Đồng in March 2014, from the
yellow-flowered variety, ground to about 1×1 mm.</p>

<h2 id="the-separation">The separation</h2>

<p>The whole scheme is below. It is worth reading before the commentary.</p>

<p><img src="/assets/images/isolation-scheme.png" alt="Isolation scheme: 20 kg of dried Brugmansia suaveolens leaf through percolation, partition, pH-gradient separation, column chromatography and MS/NMR to four identified tropane alkaloids" /></p>

<p>Percolation with 100 L of 70% ethanol, then the ethanol recovered and the concentrate left
in the cold so the chlorophyll would settle out — roughly 22 L of aqueous concentrate.
Basifying that to pH 11 with Na<sub>2</sub>CO<sub>3</sub> and shaking against chloroform
gave <strong>40 g of total alkaloid extract from 20 kg of leaf, a 0.20% yield</strong>.</p>

<p>Then the step the rest of the work rests on. Rather than take 40 g of mixed alkaloids
straight onto a column, I re-acidified with 5% HCl and raised the pH back up in stages,
extracting at each stop:</p>

<table>
  <thead>
    <tr>
      <th style="text-align: left">Fraction</th>
      <th style="text-align: left">pH</th>
      <th style="text-align: left">Mass</th>
      <th style="text-align: left">Then</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: left">CF8</td>
      <td style="text-align: left">8</td>
      <td style="text-align: left">22 g</td>
      <td style="text-align: left">classical silica-gel column</td>
    </tr>
    <tr>
      <td style="text-align: left">CF10</td>
      <td style="text-align: left">10</td>
      <td style="text-align: left">12 g</td>
      <td style="text-align: left">vacuum liquid chromatography</td>
    </tr>
    <tr>
      <td style="text-align: left">CF11</td>
      <td style="text-align: left">11</td>
      <td style="text-align: left">3 g</td>
      <td style="text-align: left">not investigated</td>
    </tr>
  </tbody>
</table>

<p>Alkaloids differ in basicity, so they cross back into the organic phase at different pH.
Sorting them that way first means each fraction going onto a column already has one
predominant compound in it, and the chromatography has far less to do. This is the pivot of
the thesis: a cheap, low-tech separation placed before the expensive one, so the expensive
one becomes easy.</p>

<p>Six isolates came off the columns. Two of them, BA-L2 from CF8 and BA-L3 from CF10, turned
out by TLC and NMR to be the same substance appearing in both fractions — 30 mg and 440 mg
of the same compound.</p>

<h2 id="the-four-compounds">The four compounds</h2>

<p>Structures were assigned from MS together with <sup>1</sup>H, <sup>13</sup>C, DEPT, HSQC and
HMBC, run on a Bruker Avance 500 at the Institute of Chemistry, Vietnam Academy of Science
and Technology in Hanoi.</p>

<table>
  <thead>
    <tr>
      <th style="text-align: left">Code</th>
      <th style="text-align: left">Compound</th>
      <th style="text-align: left">Formula</th>
      <th style="text-align: right">MW</th>
      <th style="text-align: right">Isolated</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: left">BA-L1</td>
      <td style="text-align: left">Scopolamine</td>
      <td style="text-align: left">C<sub>17</sub>H<sub>21</sub>NO<sub>4</sub></td>
      <td style="text-align: right">303</td>
      <td style="text-align: right">70 mg</td>
    </tr>
    <tr>
      <td style="text-align: left">BA-L2 / L3</td>
      <td style="text-align: left">Meteloidine</td>
      <td style="text-align: left">C<sub>13</sub>H<sub>21</sub>NO<sub>4</sub></td>
      <td style="text-align: right">255</td>
      <td style="text-align: right">470 mg</td>
    </tr>
    <tr>
      <td style="text-align: left">BA-L4</td>
      <td style="text-align: left">Noratropine</td>
      <td style="text-align: left">C<sub>16</sub>H<sub>21</sub>NO<sub>3</sub></td>
      <td style="text-align: right">275</td>
      <td style="text-align: right">250 mg</td>
    </tr>
    <tr>
      <td style="text-align: left">BA-L6</td>
      <td style="text-align: left">Atropine</td>
      <td style="text-align: left">C<sub>17</sub>H<sub>23</sub>NO<sub>3</sub></td>
      <td style="text-align: right">289</td>
      <td style="text-align: right">120 mg</td>
    </tr>
    <tr>
      <td style="text-align: left">BA-L5</td>
      <td style="text-align: left">not determined</td>
      <td style="text-align: left">—</td>
      <td style="text-align: right">—</td>
      <td style="text-align: right">2.5 mg</td>
    </tr>
  </tbody>
</table>

<p>All four share the tropane skeleton.</p>

<h2 id="what-it-established">What it established</h2>

<p><strong>The leaf is not incidentally toxic.</strong> Three of the four identified compounds — atropine,
scopolamine, noratropine — are anticholinergic tropane alkaloids, and they are there in
quantity. The reported poisonings are exactly what you would predict from this composition.
That is the answer to the defensive question, and it argues for public awareness about a
plant most people treat as decoration.</p>

<p><strong>The pH-gradient partition is transferable.</strong> Partitioning at pH 8, 10 and 11 before
chromatography should work on other Vietnamese Solanaceae carrying this compound class.</p>

<p><strong>Four reference NMR profiles</strong>, usable in reference-substance documentation for testing
raw material and finished products.</p>

<p><strong>A supply signal.</strong> Recovery is high enough that the leaf is worth evaluating seriously as
a source of scopolamine and hyoscyamine.</p>

<h2 id="what-i-left-open">What I left open</h2>

<p>The honest part of any thesis is the list of things you ran out of time for.</p>

<p>The <strong>3 g of CF11</strong> was never worked up, so the most basic alkaloids in the leaf remain
unmapped. The <strong>70 mg scopolamine figure is a floor, not an estimate</strong> — only 1 g of the
12.89 g of fraction D was ever converted to the salt, so the leaf holds considerably more
than that number suggests. <strong>BA-L5</strong> was 2.5 mg, too little to run NMR on. And I found
<em>Brugmansia versicolor</em> growing in Nghệ An, which deserves the same treatment and never
got it.</p>

<hr />

<p><em>Ngoc-Huy Pham. <a href="https://www.researchgate.net/publication/413567545_Studies_On_Chemical_Constituents_From_Angel's_Trumpet_Leaves_Folium_Brugmansiae">“Studies on chemical constituents from Angel’s trumpet leaves (Folium Brugmansiae)”</a>. Thesis for the degree of Bachelor of Pharmacy, University of Medicine and Pharmacy at Ho Chi Minh City, 2015–2016. Supervisor: Viet-Kinh Nguyen, PhD. Spectroscopy performed at the Institute of Chemistry, Vietnam Academy of Science and Technology, Hanoi.</em></p>]]></content><author><name>Huy Pham</name></author><category term="pharmacy" /><summary type="html"><![CDATA[Before any of the machine learning, I spent many years on a bench in Ho Chi Minh City taking a plant apart. This was my thesis for my Degree of Pharmacist at the University of Medicine and Pharmacy, supervised by Dr. Nguyen Viet Kinh and Mr. Nguyen Manh Tin Tin. I want to write it down properly, partly because it is the work I am still most fond of, and partly because the reasoning in it — find the one step that makes everything downstream easier — turned out to be the same reasoning I use now on entirely different problems.]]></summary></entry><entry><title type="html">Introduction to Linear Algebra</title><link href="https://pnhuy.github.io/2021/05/28/Introduction-to-Linear-Algebra.html" rel="alternate" type="text/html" title="Introduction to Linear Algebra" /><published>2021-05-28T00:00:00+00:00</published><updated>2021-05-28T00:00:00+00:00</updated><id>https://pnhuy.github.io/2021/05/28/Introduction-to-Linear-Algebra</id><content type="html" xml:base="https://pnhuy.github.io/2021/05/28/Introduction-to-Linear-Algebra.html"><![CDATA[<h2 id="vector">Vector</h2>
<div class="definition">
    A vector is an ordered list of number, for example: <br />
    $$
    x = \begin{bmatrix}
    x_1 \\ x_2 \\ \vdots \\ x_n
    \end{bmatrix}
    $$
</div>

<figure>
  <img src="https://hadrienj.github.io/assets/images/2.1/scalar-vector-matrix-tensor.png" style="max-width: 50%;" />
  <figcaption>Basic elements of linear algebra. Credit <a href="https://hadrienj.github.io/posts/Deep-Learning-Book-Series-2.1-Scalars-Vectors-Matrices-and-Tensors/">github/hadrienj</a></figcaption>
</figure>

<h3 id="operations-on-vectors">Operations on Vectors</h3>
<h4 id="vector-vector-addition--substraction">Vector-Vector addition &amp; substraction</h4>
<div class="definition">
    If $x,y \in \mathbb{R}^n$, the vectors addition &amp; substraction is defined by<br />
    $$
    x \pm y 
    = 
    \begin{bmatrix}
    x_1 \pm y_1 \\
    x_2 \pm y_2 \\
    \vdots \\
    x_n \pm y_n
    \end{bmatrix} 
    $$
</div>

<figure>
  <img src="http://media5.datahacker.rs/2020/03/Picture40-1024x724.jpg" />
  <figcaption>Illustation of vector addition. Credit <a href="http://datahacker.rs/essence-of-linear-algebra-vectors/">datahacker</a></figcaption>
</figure>

<h4 id="vector-vector-multiplication">Vector-Vector multiplication</h4>
<div class="definition">
    If $x,y \in \mathbb{R}^n$, <strong>the vector multiply</strong> is defined by <br />
    $$
    x * y 
    = 
    \begin{bmatrix}
    x_1 \times y_1 \\
    x_2 \times y_2 \\
    \vdots \\
    x_n \times y_n
    \end{bmatrix} 
    $$
</div>

<p>For example:</p>

\[\begin{bmatrix}
1 \\ 
2 \\ 
3
\end{bmatrix} *
\begin{bmatrix}
4 \\
5 \\
6
\end{bmatrix}
= 
\begin{bmatrix}
1 \times 4 \\ 
2 \times 5 \\
3 \times 6
\end{bmatrix}
=
\begin{bmatrix}
4 \\ 
10 \\
18
\end{bmatrix}\]

<div class="definition">
If $x,y \in \mathbb{R}^n$, the <strong>inner product</strong> or <strong>dot product</strong> is a number given by
$$
x^T y 
=  
\begin{bmatrix}
x_1 &amp; x_2 &amp; \dots &amp; x_n
\end{bmatrix}
\begin{bmatrix}
y_1 \\ y_2 \\ \vdots \\ y_n
\end{bmatrix}   
=\sum_{i=1}^{n}x_i y_i
$$
</div>

<p>For example:</p>

\[\begin{bmatrix}
1 &amp; 2 &amp; 3
\end{bmatrix}
\begin{bmatrix}
4 \\ 
5 \\
6
\end{bmatrix}
= [1 \times 4 +2 \times 5 + 3 \times 6] = 32\]

<div class="definition">
    If $x,y \in \mathbb{R}^n$, the <strong>outer product</strong> is the matrix whose entries are given by $(xy^T)_{ij} = x_i y_j$ <br />
    $$
    x y^T 
    =  
    \begin{bmatrix}
    x_1 \\ x_2 \\ \vdots \\ x_n
    \end{bmatrix}
    \begin{bmatrix}
    y_1 &amp; y_2 &amp; \dots &amp; y_n
    \end{bmatrix}   
    =
    \begin{bmatrix}
    x_1 y_1 &amp; x_1 y_2 &amp; \dots &amp; x_1 y_n \\
    x_2 y_1 &amp; x_2 y_2 &amp; \dots &amp; x_2 y_b \\
    \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
    x_m y_1 &amp; x_m y_2 &amp; \dots &amp; x_m y_n
    \end{bmatrix}
    $$
</div>

<p>For example:</p>

\[\begin{bmatrix}
1 \\ 2 \\ 3\\
\end{bmatrix}
\begin{bmatrix}
4 &amp; 5 &amp; 6
\end{bmatrix}
=
\begin{bmatrix}
1 \times 4 &amp; 1 \times 5 &amp; 1 \times 6 \\
2 \times 4 &amp; 2 \times 5 &amp; 2 \times 6 \\
3 \times 4 &amp; 3 \times 5 &amp; 3 \times 6 \\
\end{bmatrix}
=
\begin{bmatrix}
4 &amp; 5 &amp; 6 \\
8 &amp; 10 &amp; 12 \\
12 &amp; 15 &amp; 18
\end{bmatrix}\]

<p>Python code for vector multiplication:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([</span><span class="mi">1</span><span class="p">],</span> <span class="p">[</span><span class="mi">2</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">b</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span><span class="o">*</span><span class="n">b</span>
<span class="n">array</span><span class="p">([</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">18</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span><span class="p">.</span><span class="n">dot</span><span class="p">(</span><span class="n">b</span><span class="p">.</span><span class="n">T</span><span class="p">)</span>
<span class="mi">32</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">np</span><span class="p">.</span><span class="n">outer</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span>
<span class="n">array</span><span class="p">([[</span> <span class="mi">4</span><span class="p">,</span>  <span class="mi">5</span><span class="p">,</span>  <span class="mi">6</span><span class="p">],</span>
       <span class="p">[</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">12</span><span class="p">],</span>
       <span class="p">[</span><span class="mi">12</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">18</span><span class="p">]])</span>
</code></pre></div></div>

<h2 id="matrices">Matrices</h2>

<div class="definition">
    Matrix is a rectangular array of numbers.<br />
    For example
    $$
    \begin{bmatrix}
        23 &amp; 402 \\
        69 &amp; 221 \\
        118 &amp; 0
    \end{bmatrix}
    $$
</div>

<p><strong>Dimension of matrix</strong> is defined by number of rows $\times$ number of columns. In the above example, the dimension of matrix is 3 $\times$ 2.</p>

<p>Vector is a special case of matrix with dimension of (n $\times$ 1) in case of <strong>column vector</strong> or (1 $\times$ n) in case of <strong>row vector</strong>.</p>

<p>They use the notation $a_{ij}$ or $A_{ij}$ to denote the entry of A in the $i$th row and $j$th column.</p>

\[A = 
\begin{bmatrix}
    a_{11} &amp; a_{12} &amp; \cdots &amp; a_{1n} \\
    a_{21} &amp; a_{22} &amp; \cdots &amp; a_{2n} \\
    \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
    a_{m1} &amp; a_{12} &amp; \cdots &amp; a_{1n}
\end{bmatrix}\]

<p>Define a matrix in <code>Python</code> using <code>numpy</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span>
<span class="n">array</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span>
       <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">]])</span>
</code></pre></div></div>

<h3 id="transpose">Transpose</h3>
<p>The transpose of a matrix $A \in \mathbb{R}^{m \times n}$ is $A^T \in \mathbb{R}^{m \times n}$ whose entries are given by</p>

\[(A^T)_{ij} = A_{ji}\]

<p>The properties of transpose:</p>
<ul>
  <li>$(A^T)^T=A$</li>
  <li>$(AB)^T = B^T A^T$</li>
  <li>$(A+B)^T = A^T + B^T$</li>
</ul>

<p>Given a square matrix $A$, if $A = A^T$, A is said to be <strong>symmetric</strong>. It is <strong>anti-symmetric</strong> if $A = -A^T$.
For any square matrix $A$, the matrix $A + A^T$ is symmetric and the matrix $A-A^T$ is anti-symmetric.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">m</span><span class="p">.</span><span class="n">T</span>
<span class="n">array</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span>
       <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span> <span class="o">+</span> <span class="n">m</span><span class="p">.</span><span class="n">T</span>
<span class="n">array</span><span class="p">([[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span>
       <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">8</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span> <span class="o">-</span> <span class="n">m</span><span class="p">.</span><span class="n">T</span>
<span class="n">array</span><span class="p">([[</span> <span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">],</span>
       <span class="p">[</span> <span class="mi">1</span><span class="p">,</span>  <span class="mi">0</span><span class="p">]])</span>
</code></pre></div></div>

<h3 id="identity-matrix">Identity Matrix</h3>

<div class="definition">
    The <strong>identity matrix</strong> $I \in \mathbb{R}^{n \times n}$ is a square matrix with ones on the diagonal and zeros everywhere else. For all $A \in \mathbb{R}^{m \times n}$, $AI = IA = A$
</div>

<p>Python code for generating identity matrix:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">np</span><span class="p">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="n">array</span><span class="p">([[</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">],</span>
       <span class="p">[</span><span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">np</span><span class="p">.</span><span class="n">eye</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="n">array</span><span class="p">([[</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">],</span>
       <span class="p">[</span><span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">],</span>
       <span class="p">[</span><span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">]])</span>
</code></pre></div></div>

<h3 id="inverse">Inverse</h3>
<div class="definition">
    The <strong>inverse matrix</strong> of $A \in \mathbb{R}^{n \times n}$ is denoted $A^{-1}$ if and only if 

    $$A^{-1} A = A A^{-1} = I_n $$
    
    If the inverse matrix of $A$ exists, A is <strong>invertible</strong> or <strong>nonsingular</strong>. Otherwise, if A has no inverse, A is <strong>singular</strong> or <strong>non-invertible</strong>.
</div>

<p>For example, let
\(A = 
\begin{bmatrix}
a &amp; b \\
c &amp; d 
\end{bmatrix}\).
If $ad - bc \ne 0$, then A is invertible and</p>

\[A^{-1} = \frac{1}{ad-bc}
\begin{bmatrix}
d &amp; -b \\
-c &amp; a 
\end{bmatrix}\]

<p>Properties of inverse</p>
<ul>
  <li>$(A^{-1})^{-1} = A$</li>
  <li>$(AB)^{-1} = B^{-1} A^{-1}$</li>
  <li>$(A^T)^{-1} = (A^{-1})^T$</li>
</ul>

<p>The way to invert a matrix in Python:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">np</span><span class="p">.</span><span class="n">invert</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
<span class="n">array</span><span class="p">([[</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">3</span><span class="p">],</span>
       <span class="p">[</span><span class="o">-</span><span class="mi">4</span><span class="p">,</span> <span class="o">-</span><span class="mi">5</span><span class="p">]])</span>
</code></pre></div></div>

<h3 id="matrices-operations">Matrices operations</h3>

<h4 id="matrices-additionsubstraction">Matrices addition/substraction</h4>
<p>Matrix addition is the operation of adding two matrices by adding the corresponding entries together.</p>

\[\begin{align}
 A \pm B &amp; =
    \begin{bmatrix}
        a_{11} &amp; a_{12} &amp; \cdots &amp; a_{1n} \\ 
        a_{21} &amp; a_{22} &amp; \cdots &amp; a_{2n} \\
        \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
        a_{m1} &amp; a_{m2} &amp; \cdots &amp; a_{mn}
    \end{bmatrix} \pm 
    \begin{bmatrix}
        b_{11} &amp; b_{12} &amp; \cdots &amp; b_{1n} \\ 
        b_{21} &amp; b_{22} &amp; \cdots &amp; b_{2n} \\
        \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
        b_{m1} &amp; b_{m2} &amp; \cdots &amp; b_{mn} \\
    \end{bmatrix} \\
    &amp; =
    \begin{bmatrix}
        a_{11} \pm b_{11} &amp; a_{12} \pm b_{12} &amp; \cdots &amp; a_{1n} \pm b_{1n} \\ 
        a_{21} \pm b_{21} &amp; a_{22} \pm b_{22} &amp; \cdots &amp; a_{2n} \pm b_{2n} \\
        \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
        b_{m1} \pm b_{m1} &amp; b_{m2} \pm b_{m2} &amp; \cdots &amp; b_{mn} \pm b_{mn}
    \end{bmatrix}
\end{align}\]

<h4 id="scalar-multiplication">Scalar multiplication</h4>
<p>If $r$ is a scalar and A is a matrix, then scalar multiple $rA$ is the matrix whose elements are $r$ times the corresponding elements in $A$.</p>

\[r \times A = 
r \times
\begin{bmatrix}
a_{11} &amp; a_{12} &amp; \cdots &amp; a_{1n} \\ 
a_{21} &amp; a_{22} &amp; \cdots &amp; a_{2n} \\
\vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
a_{m1} &amp; a_{m2} &amp; \cdots &amp; a_{mn}
\end{bmatrix}
=
\begin{bmatrix}
r \times a_{11} &amp; r \times a_{12} &amp; \cdots &amp; r \times a_{1n} \\ 
r \times a_{21} &amp; r \times a_{22} &amp; \cdots &amp; r \times a_{2n} \\
\vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
r \times a_{m1} &amp; r \times a_{m2} &amp; \cdots &amp; r \times a_{mn}
\end{bmatrix}\]

<p>For example:</p>

\[3 \times 
\begin{bmatrix}
23 &amp; 402 \\
69 &amp; 221 \\
118 &amp; 0
\end{bmatrix}
= 
\begin{bmatrix}
69 &amp; 1206 \\
207 &amp; 663 \\
354 &amp; 0
\end{bmatrix}\]

<p>In Python programming language:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">m</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">23</span><span class="p">,</span> <span class="mi">402</span><span class="p">],</span> <span class="p">[</span><span class="mi">69</span><span class="p">,</span> <span class="mi">221</span><span class="p">],</span> <span class="p">[</span><span class="mi">118</span><span class="p">,</span> <span class="mi">0</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="mi">3</span><span class="o">*</span><span class="n">m</span>
<span class="n">array</span><span class="p">([[</span>  <span class="mi">69</span> <span class="mi">1206</span><span class="p">]</span>
       <span class="p">[</span> <span class="mi">207</span>  <span class="mi">663</span><span class="p">]</span>
       <span class="p">[</span> <span class="mi">354</span>    <span class="mi">0</span><span class="p">]])</span>
</code></pre></div></div>
<h3 id="matrix-matrix-multiplication">Matrix-Matrix multiplication</h3>

<p>With two matrices $A \in \mathbb{R}^{m \times n}$ and $B \in \mathbb{R}^{n \times p}$, <strong>the product of A and B</strong> is the matrix $C \in \mathbb{R}^{m \times p}$ and \(C_{ij} = \sum^{n}_{k=1}A_{ik} B_{kj}\)</p>

<p>The product matrix only exists if the number of columns in $A$ equal to the number of rows in $B$.</p>

<figure>
    <!-- <img src="https://d2r55xnwy6nx47.cloudfront.net/uploads/2021/03/Matrix-graphic-1.svg"> -->
    <img src="https://d2r55xnwy6nx47.cloudfront.net/uploads/2021/03/Matrix-graphic-2.svg" />
    <figcaption>Matrix multiplication demostation. Credit <a href="https://www.quantamagazine.org/mathematicians-inch-closer-to-matrix-multiplication-goal-20210323/">quantamagazine</a>.</figcaption>
</figure>

<p>Python demo code for matrix multiplication:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">B</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">],</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span><span class="mi">8</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">A</span><span class="p">.</span><span class="n">dot</span><span class="p">(</span><span class="n">B</span><span class="p">)</span>
<span class="n">array</span><span class="p">([[</span><span class="mi">19</span><span class="p">,</span> <span class="mi">22</span><span class="p">],</span>
       <span class="p">[</span><span class="mi">43</span><span class="p">,</span> <span class="mi">50</span><span class="p">]])</span>
</code></pre></div></div>

<p>Properties of Matrix Multiplication:
Given A be an $m \times n$ matrix, B and C have sizes for which the indicated sums and products are defined.</p>
<ul>
  <li>$A(BC) = (AB)C$</li>
  <li>$A(B+C) = AB + AC$</li>
  <li>$(B+C)A = BA + CA$</li>
  <li>$r(AB) = (rA)B = A(rB)$ for any scalar r</li>
  <li>$I_m A = A I_n = A$</li>
</ul>

<p>Read more:</p>
<ul>
  <li><a href="https://www.youtube.com/watch?v=OMA2Mwo0aZg">Instruction from Khan Academy</a></li>
  <li><a href="https://www.quantamagazine.org/mathematicians-inch-closer-to-matrix-multiplication-goal-20210323/">Recent progression on matrix multiplication computation</a></li>
</ul>

<h3 id="determinant">Determinant</h3>
<div class="definition">
    For $n \ge 2$, the <strong>determinant</strong> of an $n \times n$ matrix $A = [a_{ij}]$ is the sum of $n$ terms of the form $\pm a_{1j} \det A_{1j}$, with plus and minus signs alternating, where the entries $a_{11}, a_{12}, \dots, a_{1n} $ are from the first row of $A$.
    $$ \det A = |A| = a_{11} \det A_{11} - a_{12} \det A_{12} + \dots + (-1)^{1+n} a_{1n} \det A_{1n} $$
    with $A_{ij}$ denotes the submatrix formed by deleting the $i$th row and $j$th column of A.
    <br />
    When the $(i,j)$-<strong>cofactor</strong> of A is the number $C_{ij}$ given by 
    $$ C_{ij} = (-1)^{i+j} \det A_{ij} $$
    the determinant of A can be defined by
    $$\begin{align}
        \det A &amp;= a_{i1} C_{i1} + a_{i2} C_{i2} + \dots + a_{in} C_{in} \\
        &amp;= a_{1j} C_{1j} + a_{2j} C_{2j} + \dots + a_{nj} C_{nj}
    \end{align}$$
</div>

<p>In the case $2 \times 2$ matrix:</p>

\[\det 
\begin{bmatrix}
a &amp; b \\
c &amp; b
\end{bmatrix}
= 
\begin{vmatrix}
a &amp; b \\
c &amp; b
\end{vmatrix}
= ad - bc\]

<p>and $3 \times 3$ matrix:</p>

\[\begin{align}
\det 
\begin{bmatrix}
a &amp; b &amp; c\\
d &amp; e &amp; f\\
g &amp; h &amp; i
\end{bmatrix}
&amp;= a
\begin{vmatrix}
e &amp; f \\
h &amp; i
\end{vmatrix} -
b
\begin{vmatrix}
d &amp; f \\
g &amp; i
\end{vmatrix} +
c
\begin{vmatrix}
d &amp; e \\
g &amp; h
\end{vmatrix}\\
&amp;= aei - afh -bdi +bfg + cdh - ceg
\end{align}\]

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">np</span><span class="p">.</span><span class="n">linalg</span><span class="p">.</span><span class="n">det</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
<span class="o">-</span><span class="mf">2.0000000000000004</span>
</code></pre></div></div>

<h4 id="properties-of-the-determinant">Properties of the Determinant</h4>
<ul>
  <li>The determinant of the identity matrix is 1 <br />
  \(\det I = \det \begin{vmatrix} 1 &amp; 0 \\ 0 &amp; 1 \end{vmatrix} = 1\)</li>
  <li>
    <p>The determinant changes sign when two rows are exchanged <br />
  \(\begin{vmatrix} c &amp; d \\ a &amp; b  \end{vmatrix} = - \begin{vmatrix} a &amp; b \\ c &amp; d  \end{vmatrix}\)</p>
  </li>
  <li>
    <p>The determinant depends linearly on the first row <br />
  \(\begin{vmatrix} a+a' &amp; b+b' \\ c &amp; d  \end{vmatrix} = 
  \begin{vmatrix} a &amp; b \\ c &amp; d  \end{vmatrix} +
  \begin{vmatrix} a' &amp; b' \\ c &amp; d  \end{vmatrix}\)
  \(\begin{vmatrix} ta &amp; tb \\ c &amp; d  \end{vmatrix} = 
  t \begin{vmatrix} a &amp; b \\ c &amp; d  \end{vmatrix}\)</p>
  </li>
  <li>
    <p>If two rows of A are equal, then $\det A = 0$ <br />
  \(\begin{vmatrix} a &amp; b \\ a &amp; b  \end{vmatrix} = ab-ba = 0\)</p>
  </li>
  <li>
    <p>Substracting a multiple of one row from another row leaves the same determinant <br />
  \(\begin{vmatrix} a- tc &amp; b - td \\ c &amp; d  \end{vmatrix} =
  \begin{vmatrix} a &amp; b \\ c &amp; d  \end{vmatrix} - t \begin{vmatrix} c &amp; d \\ c &amp; d  \end{vmatrix} = \begin{vmatrix} a &amp; b \\ c &amp; d  \end{vmatrix}\)</p>
  </li>
  <li>
    <p>If $A$ is triangular then $\det A$ is the product $a_{11} a_{22} \dots a_{nn}$ of the diagonal entries. <br />If the triangular A has 1s , then $\det A = 1$ <br />
  \(\begin{vmatrix} a &amp; b \\ 0 &amp; d  \end{vmatrix} = \begin{vmatrix} a &amp; 0 \\ c &amp; d  \end{vmatrix} = ad\)</p>
  </li>
  <li>
    <p>If $A$ is singular, then $\det A = 0$. If $A$ is invertible, then $\det A \ne 0$</p>
  </li>
  <li>
    <p>The determinant of AB is the product of $\det A$ times $\det B$: \(|A| |B| = |AB|\) <br />
  The special case is when $B = A^{-1}$: <br />
  \((\det A) (\det A^{-1}) = \det AA^{-1} = \det I = 1\)
  \(\Rightarrow \det A^{-1} = \frac{1}{\det A}\)</p>
  </li>
  <li>The transpose of $A$ has the same determinant as $A$ itself: $\det A^T = \det A$ <br />
  \(|A| = \begin{vmatrix} a &amp; b \\ c &amp; d  \end{vmatrix} = \begin{vmatrix} a &amp; c \\ b &amp; d  \end{vmatrix} = |A^T|\)</li>
</ul>

<h4 id="application-of-determinants">Application of Determinants</h4>
<ul>
  <li>
    <p>Computation of $A^{-1}$:</p>

\[A^{-1} = \frac{C^T}{\det A} \text{ or } (A^{-1})_{ij} = \frac{C_{ij}}{\det A}\]

    <p>In case of 2 by 2 matrix, we have 
\(\begin{bmatrix}
a &amp; b \\
c &amp; d \\
\end{bmatrix}
= \frac{1}{\det A}
\begin{bmatrix}
C_{11} &amp; C_{21} \\
C_{12} &amp; C_{22}
\end{bmatrix}
= \frac{1}{ad-bc}
\begin{bmatrix}
d &amp; -b \\
-c &amp; a
\end{bmatrix}\)</p>
  </li>
  <li>
    <p>The Solution of $Ax = b$ (Cramer’s rule)</p>

\[x_j = \frac{\det B_j}{\det A} \text{, where } B_j = 
\begin{bmatrix}
a_{11} &amp; a_{12} &amp; b_1 &amp; a_{1n} \\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
a_{n1} &amp; a_{n2} &amp; b_n &amp; a_{nn} \\
\end{bmatrix}
\text{ has b in column j}\]
  </li>
  <li>
    <p>Determinants as Area or Volume</p>

    <p>If $A$ is a $2 \times 2$ matrix, the area of the parallelogram determined by te columns of $A$ is $|\det A|$. If $A$ is a $3 \times 3$ matrix, the volume of the paralellepiped determined by the columns of $A$ is $|\det A|$.</p>
  </li>
</ul>

<div class="row">
  <div class="column"><img src="https://upload.wikimedia.org/wikipedia/commons/a/ad/Area_parallellogram_as_determinant.svg" style="max-height: 300px;" /></div>
  <div class="column"><img src="https://upload.wikimedia.org/wikipedia/commons/b/b9/Determinant_parallelepiped.svg" style="max-height: 300px;" /></div>
  <figcaption>Determinants as Area or Volume. Credit <a href="https://en.wikipedia.org/wiki/Determinant">Wikipedia/Determinant</a></figcaption>
</div>

<h3 id="linear-independence-and-rank">Linear Independence and Rank</h3>
<div class="definition"><strong>Linear Independence</strong><br />
An set of vectors $\{ v_1, \dots , v_p \} \in \mathbb{R}^n$ is said to be <strong>linearly independent</strong> if the vector equation 
$$ x_1 v_1 + x_2 v_2 + \dots + x_p v_p = 0 $$
has only the trivial solution. <br />
The set $\{ v_1, \dots , v_p \} $ is said to be <strong>linearly dependent</strong> if there exist weights $c_1, \dots , c_p$, not all zero, such that
$$ c_1 v_1 + c_2 v_2 + \dots + c_p v_p = 0 $$
</div>

<div class="definition"><strong>Rank</strong><br />
Given a matrix $A \in \mathbb{R}^{m \times n}$:
<ul>
  <l>The <strong>column rank</strong> of $A$ is the size of the largest subset of columns of $A$ that constitute a linearly independent set.</l>
  <l>The <strong>row rank</strong> of $A$ is the size of the largest subset of rows of $A$ that constitute a linearly independent set</l>
  <li>If the column rank of $A$ is equal to its row rank, this number is the <strong>rank</strong> of $A$.</li>
</ul>
</div>

<p>The properties of the rank, for $A, B \in \mathbb{R}^{m\times n}$:</p>
<ul>
  <li>$rank(A) \le \min (m,n)$. If $rank(A) = \min(m,n)$, $A$ is said to be <strong>full rank</strong>.</li>
  <li>$rank(A) = rank(A^T)$</li>
  <li>$rank(AB) \le \min(rank(A), rank(B)$</li>
  <li>$rank(A+B) \le rank(A) + rank(B)$</li>
</ul>

<h3 id="norms">Norms</h3>
<div class="definition">
A <strong>norm</strong> is a function that satisfies the following three conditions:

<ul>
    <li>Nonnegativity and mapping of the identity: if $x \ne 0$, then $\|x\| &gt; 0$, and $\| 0 \|=0$</li>
    <li>Scalar multiplication: $\| ax \| = |a| \| x\|$, for all real $a$</li>
    <li>Triangle inequality: $\| x+y \| \le \|x\| + \|y\|$</li>
</ul>
</div>

<p>For $p \ge 1$, $L _ p$ norm is defined by
\(\| x \| _ {p} = \left( \sum_i \| x_i \|^p \right)^{\frac{1}{p}}\)</p>

<p>Some common $L_p$ norms:</p>
<ul>
  <li>$ | x |_ 1 = \sum _ {i} |x_i|$, also called the <strong>Manhattan norm</strong>.</li>
  <li>$| x |_ 2 = \sqrt{\sum _ {i} x_i^2}$, also called the <strong>Euclidean norm</strong>, the <strong>Euclidean length</strong>, or the <strong>length</strong> of the vector. The $L_2$ is the square root of the inner product of the vector with itself: $|x|_ 2 = \sqrt{\langle x,x \rangle}$.</li>
  <li>$| x |_ \infty = \max_{i} |x_i|$, also called the <strong>max norm</strong> or the <strong>Chebyshev norm</strong>.</li>
</ul>

<p>A generalization of $L_p$ is the <strong>weighted $L_p$ norm</strong>: 
\(\| x \|_ {wp} = \left(\sum_{i} w_i |x_i|^p \right)^{\frac{1}{p}}\)</p>

<h3 id="quadratic-forms">Quadratic forms</h3>
<div class="definition">
    A <strong>quadratic form</strong> in $\mathbb{R}^n$ is a function $Q$ defined on $\mathbb{R}^n$ whose value at a vector $x \in \mathbb{R}^n$ can be computed by an expression of the form $Q(x) = x^T Ax$, where $A$ is an $n \times n$ symmetric matrix. The matrix A is called the <strong>matrix of quadratic form</strong>.
    $$
    x^T Ax = \sum_{i=1}^{n}x_i (Ax)_i = \sum_{i=1}^{n}x_i \left( \sum_{j=1}^{n} A_{ij}x_{j}\right) = \sum_{i=1}^{n} \sum_{j=1}^{n} A_{ij} x_i x_j
    $$
</div>

<h3 id="positive-definite-and-positive-semidefinite">Positive definite and Positive semidefinite</h3>
<div class="definition">
Let A be symmetric matrix in $\mathbb{R}^n$:
<ul>
    <li>A is <strong>positive definite</strong> if for all nonzero vectors $x\in \mathbb{R}^n$, $x^T Ax &gt; 0$.</li>
    <li>A is <strong>positive semidefinite</strong> if for all nonzero vectors $x\in \mathbb{R}^n$, $x^T Ax \ge 0$.</li>
    <li>A is <strong>negative definite</strong> if for all nonzero vectors $x\in \mathbb{R}^n$, $x^T Ax &lt; 0$.</li>
    <li>A is <strong>negative semidefinite</strong> if for all nonzero vectors $x\in \mathbb{R}^n$, $x^T Ax \le 0$.</li>
    <li>A is <strong>indefinite</strong> if A is neither positive semidefinite or negative semidefinite. </li>
</ul>
</div>

<h3 id="eigenvalues-and-eigenvectors">Eigenvalues and Eigenvectors</h3>
<div class="definition">
Given square matrix $A \in \mathbb{R}^{n \times n}$, we call that a scalar $\lambda$ is an eigenvalue of $A$ and a nonzero vector $x$ is the corresponding eigenvectr if $Ax = \lambda x$
</div>

<h4 id="how-to-find-eigenvalues-and-eigenvectors">How to find Eigenvalues and Eigenvectors?</h4>
<ul>
  <li>
    <p>Find the values of $\lambda$ which satisfy the <strong>characteristic equation</strong>:</p>

\[\det (A- \lambda I) = 0\]

    <p>where $I$ is the identity matrix.</p>

    <p>The solution of this equation is the <strong>eigenvalue</strong> of the matrix.</p>
  </li>
  <li>
    <p>For each eigenvalue solved, we have</p>

\[(A - \lambda I) x = 0\]

    <p>where x is the <strong>eigenvector</strong> associated with eigenvalue $\lambda$.</p>

    <p>Find X by Gaussian elimination.</p>
  </li>
</ul>

<p>For example, find the eigenvalues and eigenvectors of 
\(A=
\begin{bmatrix}
2 &amp; -4 \\
-1 &amp; -1
\end{bmatrix}\)</p>

<ul>
  <li>
    <p>Solve the characteristic equation for eigenvalues:</p>

\[\begin{align}
\det (A - \lambda I) &amp;= \det \begin{bmatrix} 2 - \lambda &amp; -4 \\ -1 &amp; -1 - \lambda \end{bmatrix} \\
&amp; = (2 - \lambda)(-1-\lambda) - (-4)(-1) \\
&amp;= \lambda^2 -\lambda - 6 \\
&amp;= (\lambda -3)(\lambda + 2) \\
\end{align}\]

    <p>So that</p>

\[\begin{align}
\det (A - \lambda I) &amp;= 0 \\
\Leftrightarrow (\lambda -3)(\lambda + 2) &amp;= 0 \\
\Leftrightarrow \lambda &amp;= 3 \\
\text{ or } \lambda &amp;= -2
\end{align}\]

    <p>The eigenvalues of A are $\lambda = 3 \text{ or } \lambda = -2  $</p>
  </li>
  <li>
    <p>Solve for eigenvectors $x = \begin{bmatrix} x_1 \ x_2 \end{bmatrix}$:</p>

\[(A-3I)x = 0\]

    <ul>
      <li>
        <p>For $\lambda = 3$, we have the augmented matrix:</p>

\[\begin{bmatrix}
    2-3 &amp; -4 &amp; 0 \\
    -1 &amp; -1 - 3 &amp; 0     
\end{bmatrix}
\rightarrow
\begin{bmatrix}
-1 &amp; -4 &amp; 0 \\
-1 &amp; -4 &amp; 0     
\end{bmatrix}
\rightarrow
\begin{bmatrix}
1 &amp; 4 &amp; 0 \\
0 &amp; 0 &amp; 0       
\end{bmatrix}\]

        <p>The eigenvector corresponding to $\lambda = 3$:</p>

        <p>\(x = k \begin{pmatrix}
    -4 \\
    1
\end{pmatrix}\) where $k$ is nonzero scalar.</p>
      </li>
      <li>
        <p>For $\lambda = -2$, the eigenvectors have the form:</p>

        <p>\(x =  k\begin{pmatrix}
1\\
1 
\end{pmatrix}\) where k is nonzero scalar.</p>
      </li>
    </ul>
  </li>
</ul>

<p>The <code>numpy</code> package in Python supports finding eigenvalues quickly:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">4</span><span class="p">],[</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">]])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">np</span><span class="p">.</span><span class="n">linalg</span><span class="p">.</span><span class="n">eigvals</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
<span class="n">array</span><span class="p">([</span> <span class="mf">3.</span><span class="p">,</span> <span class="o">-</span><span class="mf">2.</span><span class="p">])</span>
</code></pre></div></div>

<h2 id="reference">Reference</h2>
<p>[1] Lecture from course Machine learning at VEF Academy. <br />
[2] Zico Kolter. Linear algebra review and reference, 2008. <br />
[3] D.C. Lay, S.R. Lay, and J.J. McDonald. Linear Algebra and Its Applications. Pearson Education, 2015. <br />
[4] G. Strang. Linear Algebra and Its Applications. Thomson, Brooks/Cole, 2006.</p>

<style>.column {
  float: left;
  width: 50%;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}</style>]]></content><author><name>Huy Pham</name></author><summary type="html"><![CDATA[Vector A vector is an ordered list of number, for example: $$ x = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} $$]]></summary></entry><entry><title type="html">Introduction to Graph Theory</title><link href="https://pnhuy.github.io/2021/04/13/Introduction-to-Graph-theory.html" rel="alternate" type="text/html" title="Introduction to Graph Theory" /><published>2021-04-13T00:00:00+00:00</published><updated>2021-04-13T00:00:00+00:00</updated><id>https://pnhuy.github.io/2021/04/13/Introduction-to-Graph-theory</id><content type="html" xml:base="https://pnhuy.github.io/2021/04/13/Introduction-to-Graph-theory.html"><![CDATA[<h2 id="graph-and-graph-models">Graph and Graph models</h2>

<p>A graph $G=(V,E)$ consists of $V$, an nonempty set of <em>vertices</em> (or <em>nodes</em>) and $E$, a set of edges. Each edge has either one or two vertices associated with it, called its <em>endpoints</em>. An edge is said to <em>connect</em> its endpoints.</p>

<p>A graph with infinite vertex or egdes is called <strong>infinite graph</strong>. In the otherwise case, <strong>finite graph</strong>.</p>

<p>A graph in which each edge connects two different vertices and where no two edges connect the same pair of vertices is called a <strong>simple graph</strong>.</p>

<p>Graph that may have multiple edges connecting the same vertices are called <strong>multigraphs</strong>.</p>

<p>The edges that connect a vertex to itself are called <strong>loops</strong>.</p>

<p>Graphs including loops, and possibly multiple edges connecting the same pair of vertices or a vertex to itself, are called <strong>pseudographs</strong>.</p>

<p>The graph with <strong>undirected</strong> edges is an <strong>undirected graph</strong>.</p>

<p>A directed graph (or digraph) $(V,E)$ consists of a nonempty set of vertices $V$ and a set of directed edges (or arcs) $E$. Each directed edge is associated with an ordered pair of vertices. The directed edge associated with the ordered pair $(u,v)$ is said to start at $u$ and end at $v$.</p>

<p>A directed graph has no loops and has no multiple directed edges is called a <strong>simple directed graph</strong>.</p>

<p>Directed graphs that may have <strong>multiple directed edges</strong> from a vertex to a second (possibly the same) vertex are used to model such networks are called <strong>directed multigraphs</strong>. When there are $m$ directed edges, each associated to an ordered pair of vertices $(u,v)$, we say that $(u,v)$ is an edge of multiplicity $m$.</p>

<p>A graph with both directed and undirected edges is called a <strong>mixed graph</strong>.</p>

<p>Graphs are used in a wide variety of models:</p>
<ul>
  <li>Social networks</li>
  <li>Communication networks</li>
  <li>Information networks</li>
  <li>Software design applications</li>
  <li>Transportation networks</li>
  <li>Biological networks</li>
  <li>Tournaments</li>
</ul>

<h2 id="terminology-and-special-types-of-graph">Terminology and special types of graph</h2>

<h3 id="terminology">Terminology</h3>

<p>Two vertices u and v in an undirected graph G are called <strong>adjacent</strong> (or <strong>neighbors</strong>) in G if u and v are endpoints of an edge e of G. Such an edge e is called <strong>incident with</strong> the vertices u and v and e is said to connect u and v.</p>

<p>The set of all neighbors of a vertex v of $G=(V,E)$, denoted by $N(v)$, is called the <strong>neighborhood</strong> of $v$. If $A$ is a subset of $V$ , we denote by $N(A)$ the set of all vertices in $G$ that are adjacent to at least one vertex in A. So, $N(A)=\bigcup_{v\in A}N(v)$.</p>

<p>The <strong>degree of a vertex in an undirected graph</strong> is the number of edges incident with it, <em>except that a loop at a vertex contributes twice to the degree of that vertex</em>. The degree of the vertex v is denoted by $deg(v)$.</p>

<p>A vertex of degree zero is called <strong>isolated</strong> (not adjacent to any vertex).</p>

<p>A vertex is <strong>pendant</strong> if and only if it has degree one (adjacent to exactly one other vertex).</p>

<div class="theorem">
    The handshaking theorem <br />
    Let $G=(V,E)$ be an undirected graph with $m$ edges:
    $$2m=\sum_{v\in V}\deg(v)$$
</div>

<p>This theorem shows that the sum of the degrees of the vertices of an undirected graph is even, which lead to the below theorem.</p>

<div class="theorem">
    An undirected graph has an even number of vertices of odd degree.
</div>

<p>When $(u,v)$ is an edge of the graph G with directed edges, $u$ is said to be <strong>adjacent to</strong> $v$ and $v$ is said to be <strong>adjacent from</strong> $u$. The vertex $u$ is called the <strong>initial vertex</strong> of $(u,v)$, and $v$ is called the <strong>terminal</strong> or <strong>end vertex</strong> of $(u,v)$. The initial vertex and terminal vertex of a loop are the same.</p>

<p>In a graph with directed edges the <strong>in-degree</strong> of a vertex v, denoted by $\deg^{-}(v)$, is the number of edges with v as their terminal vertex. The <strong>out-degree</strong> of v, denoted by $\deg^{+}(v)$, is the number of edges with v as their initial vertex. (Note that a loop at a vertex contributes 1 to both the in-degree and the out-degree of this vertex.)</p>

<div class="theorem">
    Let $G=(V,E)$be a graph with directed edges:
    $$\sum_{v\in V}\deg^{-}(v)=\sum_{v\in V}\deg^{+}(v)=|E|$$
</div>

<p>Some special simple graphs:</p>
<ul>
  <li>Complete Graphs: a complete graph on n vertices, denoted by $K_{n}$, is a simple graph that contains exactly one edge between each pair of distinct vertices.</li>
  <li>Wheels</li>
  <li>n-cube / n-dimensional hypercube, denoted by $Q_{n}$, is a graph that has vertices representing the $2^{n}$ bit strings of length n.</li>
</ul>

<h3 id="bipartite-graph">Bipartite Graph</h3>

<p>A simple graph $G$ is called <strong>bipartite</strong> if its vertex set $V$ can be partitioned into two disjoint sets $V_{1}$ and $V_{2}$ such that every edge in the graph connects a vertex in $V_{1}$ and a vertex in $V_{2}$ (so that no edge in $G$ connects either two vertices in $V_{1}$ or two vertices in $V_{2}$). When this condition holds, we call the pair $(V_{1},V_{2})$ a bipartition of the vertex set $V$ of $G$.</p>

<div class="theorem">
    A simple graph is bipartite if and only if it is possible to assign one of two different colors to each vertex of the graph so that no two adjacent vertices are assigned the same color.
</div>

<p>A <strong>complete bipartite graph</strong> $K_{m,n}$ is a graph that has its vertex set partitioned into two subsets of $m$ and $n$ vertices, respectively with an edge between two vertices if and only if one vertex is in the first subset and the other vertex is in the second subset.</p>

<p>A <strong>matching</strong> $M$ in a simple graph $G=(V,E)$ is a subset of the set $E$ of edges of the graph such that no two edges are incident with the same vertex. In other words, a matching is a subset of edges such that if ${s,t}$ and ${u,v}$ are distinct edges of the matching, then s, t, u, and v are distinct.</p>

<p>A vertex that is the endpoint of an edge of a matching $M$ is said to be matched in $M$; otherwise it is said to be unmatched.</p>

<p>A <strong>maximum matching</strong> is a matching with the largest number of edges. We say that a matching M in a bipartite graph $G=(V,E)$ with bipartition $(V_{1},V_{2})$ is a complete matching from $V_{1}$ to $V_{2}$ if every vertex in $V_{1}$ is the endpoint of an edge in the matching, or equivalently, if $|M|=|V_1|$.</p>

<div class="theorem">
<strong>Hall's marriage theorem / Necessary and sufficient conditions for complete matching</strong>
<br />
The bipartite graph $G=(V,E)$ with bipartition $(V_{1},V_{2})$ has a complete matching from $V_{1}$ to $V_{2}$ if and only if $\|N(A)\| \ge \|A\|$ for all subsets A of $V_{1}$.
</div>

<h2 id="representing-graphs-and-graph-isomorphism">Representing Graphs and Graph Isomorphism</h2>

<h3 id="adjacency-lists">Adjacency Lists</h3>

<p>One way to represent a graph without multiple edges is to list all the edges of this graph. Another way to represent a graph with no multiple edges is to use <strong>adjacency lists</strong>, which specify the vertices that are adjacent to each vertex of the graph.</p>

<p><img src="https://storage.googleapis.com/algodailyrandomassets/curriculum/graphs/implementing-graphs-adjacencylist.png" alt="Adjacency List" /></p>

<h3 id="adjacency-matrices">Adjacency Matrices</h3>

<p>Suppose that $G = (V , E)$ is a simple graph where $|V| = n$. Suppose that the vertices of $G$ are listed arbitrarily as $v_1, v_2, …, v_n$ .</p>

<p>The adjacency matrix $A$ (or $A_G$ ) of $G$, with respect to this listing of the vertices, is the $n \times n$ zero–one matrix with 1 as its $(i, j)$th entry when $v_i$ and $v_j$ are adjacent, and 0 as its $(i,j)$th entry when they are not adjacent.</p>

<p>In other words, if its adjacency matrix is $A = [a_{ij}]$, then</p>

\[a_{ij} = \left\{
\begin{matrix}
1 &amp; \text{if } {v_i, v_j} \text{ is an edge of G} \\
0 &amp; \text{otherwise}
\end{matrix}
\right.\]

<p><img src="https://storage.googleapis.com/algodailyrandomassets/curriculum/graphs/implementing-graphs-adjacencymatrix.png" alt="Adjacency Matrix" /></p>

<h3 id="incidence-matrices">Incidence Matrices</h3>

<p>Let $G = (V , E)$ be an undirected graph. Suppose that $v_1 , v_2 , . . . , v_n$ are the vertices and $e1 , e2 , . . . , e_m$ are the edges of G. Then the incidence matrix with respect to this ordering of $V$ and $E$ is the $n \times m$ matrix $M = [m_{ij}]$, where</p>

\[m_{ij} = \left\{
\begin{matrix}
1 &amp; \text{when edge } e_j \text{ is incident with } v_i  \\
0 &amp; \text{otherwise}
\end{matrix}
\right.\]

<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Incidence_matrix_-_undirected_graph.svg/800px-Incidence_matrix_-_undirected_graph.svg.png" alt="Incidence Matrix" /></p>

<h3 id="isomorphism">Isomorphism</h3>

<div class="definition">
The simple graphs $G_1 = (V_1 , E_1 )$ and $G_2 = (V_2 , E_2 )$ are isomorphic if there exists a one-to-one and onto function $f$ from $V_1$ to $V_2$ with the property that $a$ and $b$ are adjacent in $G_1$ if and only if $f(a)$ and $f(b)$ are adjacent in $G_2$ , for all $a$ and $b$ in $V_1$ . Such a function $f$ is called
an <strong>isomorphism</strong>. Two simple graphs that are not isomorphic are called <strong>nonisomorphic</strong>.

</div>

<p>In other words, when two simple graphs are isomorphic, there is a one-to-one correspondence between vertices of the two graphs that preserves the adjacency relationship. Isomorphism of simple graphs is an equivalence relation.</p>

<p align="center"><img src="https://qph.fs.quoracdn.net/main-qimg-16c40327f5a5eec560705ddf2e8eceb9" /></p>

<p>A property preserved by isomorphism of graphs is called a <strong>graph invariant</strong>. For example, isomorpic graphs must have:</p>
<ul>
  <li>The same # of vertices</li>
  <li>The same # of edges</li>
  <li>The degrees of the vertices in the graphs must be the same</li>
</ul>

<h2 id="connectivity">Connectivity</h2>
<h3 id="paths">Paths</h3>

<div class="definition">
Let $n$ be a nonnegative integer and $G$ an undirected graph.
<br />
A <strong>path</strong> of length $n$ from $u$ to $v$ in $G$ is a sequence of $n$ edges $e_1,...,e_n$ of $G$ for which there exists a sequence $x_0 = u,x_1,\dots,x_{n−1},x_n = v$ of vertices such that $e_i$ has, for $i = 1,\dots,n$, the endpoints $x_{i−1}$ and $x_i$.
</div>

<p>When the graph is simple, we denote this path by its vertex sequence $x_0,x_1,\dots,x_n$ (because listing these vertices uniquely determines the path).</p>

<p>The path is a circuit if it begins and ends at the same vertex, that is, if u = v, and has length greater than zero.</p>

<p>The path or circuit is said to pass through the vertices $x_1, x_2,\dots, x_{n−1}$ or traverse the edges $e_1, e_2,\dots, e_n$. A path or circuit is simple if it does not contain the same edge more than once.</p>

<p>Read more: <a href="https://mathworld.wolfram.com/ErdosNumber.html">Erdős Number</a>, <a href="https://simple.wikipedia.org/wiki/Bacon_number">Bacon number</a>.</p>

<h3 id="connectedness-in-undirected-graphs">Connectedness in Undirected Graphs</h3>

<div class="definition">
An <strong>undirected graph</strong> is called <em>connected</em> if there is a path between every pair of distinct
vertices of the graph.
<br />
An <strong>undirected graph</strong> that is <em>not connected</em> is called <em>disconnected</em>.
<br />
We say that we disconnect a graph when we remove vertices or edges, or both, to produce a
disconnected subgraph.
</div>

<figure>
  <img src="https://walkenho.github.io/images/graph-theory-and-networkX-part2-fig1.jpg" align="center" />
  <figcaption>Connected vs Disconnected Graph (<a href="https://walkenho.github.io/graph-theory-and-networkX-part2/">walkenho</a>)</figcaption>
</figure>

<div clas="theorem">
There is a simple path between every pair of distinct vertices of a connected undirected graph.
</div>

<div class="definition">
A <strong>connected component</strong> of a graph G is a connected subgraph of G that is not a proper subgraph of another connected subgraph of G.
</div>
<p>That is, a connected component of a graph G is a maximal connected subgraph of G.</p>

<p>A graph G that is not connected has two or more connected components that are disjoint and have G as their union.</p>

<figure>
  <img src="https://www.mathworks.com/matlabcentral/mlc-downloads/downloads/submissions/46457/versions/3/screenshot.jpg" width="75%" />
  <figcaption>Connected Components (<a href="https://www.mathworks.com/matlabcentral/fileexchange/46457-splitting-a-network-into-connected-components">mathworks</a>)</figcaption>
</figure>

<p>Read more: <a href="https://www.baeldung.com/cs/graph-connected-components#finding-connected-components">Finding Connected Components using DFS</a></p>

<h3 id="how-connected-is-a-graph">How Connected is a Graph?</h3>

<div class="definition">
<strong>Cut vertices</strong> or <strong>Articulation points</strong> is the vertices that if they and their incident edges are removed from a graph, a subgraph with more connected components is produced.<br />
An edge whose removal produces a graph with more connected components than in the original graph is called a <strong>Cut edge</strong> or <strong>Bridge</strong>.
</div>

<figure>
    <img src="https://static.javatpoint.com/tutorial/graph-theory/images/connectivity3.png" />
    <figcaption>The vertices b, c, e is cut vertices and the edge (c, e) is cut edge <br /> (<a href="https://www.javatpoint.com/graph-theory-connectivity">javatpoint</a>)</figcaption>
</figure>

<h4 id="vertex-connectivity">Vertex Connectivity</h4>

<p>When a complete graph $K_n$ removes a vertex and all incidents to it, the resulting graph is a complete graph $K_{n-1}$ which also a connected graph.</p>

<figure>
    <img src="https://media.geeksforgeeks.org/wp-content/uploads/kargest-subset-of-graph-vertices-with-edges-of-2-or-more-colors-3.png" />
    <figcaption>Remove a vertex from a $K_6$ makes a $K_5$ graph (<a href="https://www.geeksforgeeks.org/largest-subset-graph-vertices-edges-2-colors/">geeksforgeeks</a>)</figcaption>
</figure>

<p>Connected graph having no cut vertex is a <strong>nonseparable graph</strong> which is more connected than a graph with a cut vertex.</p>

<div class="definition"><br />
    A subset $V'$ of the vertex set $V$ of $G=(V,E)$ is a <strong>vertex cut</strong>, or <strong>separating set</strong>, if $G-V'$ is disconnected.
    <br />
    <strong>Vertex connectivity</strong> of a noncomplete graph $G$, denoted by $\kappa(G)$, is the minimum number of vertices in a vertex cut.
</div>

<figure>
    <img src="https://i.stack.imgur.com/3zwRU.png" />
    <figcaption>The Vertex connectivity is 1, because removing the vertex A makes 2 connected components <br /> (<a href="https://math.stackexchange.com/questions/1951447/find-a-graph-that-has-a-high-minimum-degree-but-low-connectivity-and-edge-conne">stackexchange</a>)</figcaption>
</figure>

<p>When $G$ is a complete graph, it has no vertex cuts. Because removing any vertex and its incident edges still leaves a complete graph.</p>

<p>So, it’s impossible to define $\kappa(G)$ as the smallest number of vertices in a vertex cut when $G$ is complete. In this case, we define $\kappa(K_n) = n-1$ as the number of vertices needed to be removed to produce a graph with a single vertex.</p>

<p>In conclusion, for every graph G, $\kappa(G)$ is the minimum number of verties that can be removed from graph to either:</p>
<ul>
  <li>Disconnect G or</li>
  <li>Prduce a graph with a single vertex</li>
</ul>

<p>We have:</p>
<ul>
  <li>$0 \le \kappa(G) \le n-1$ if G has n vertices</li>
  <li>$\kappa(G) = 0$ if and only if G is disconnected or $G = K_1$</li>
  <li>$\kappa(G) = 1$ if and only if G is complete</li>
</ul>

<p>The larger k(G) is, the more connected G is:</p>
<ul>
  <li>Disconnected graph or $K_1$ have $\kappa(G) = 0$</li>
  <li>Connected graph with cut vetices and $K_2$ have $\kappa(G) = 1$</li>
  <li>Graph without cut vertices and $K_3$ have $\kappa(G) = 2$</li>
  <li>so on …</li>
</ul>

<p>A graph is <strong>k-connected</strong> or <strong>k-vertex-connected</strong> if $\kappa(G) \ge k$:</p>
<ul>
  <li>1-connected graph if it is connected and not a graph containing a single vertex</li>
  <li>2-connected is also called <strong>biconnected</strong> that is non seperable and has at least three vertices</li>
  <li>G is a k-connected graph, then G is a j-connected for all j with $0 \le j \le k$</li>
</ul>

<h4 id="edge-connectivity">Edge Connectivity</h4>

<div class="definition"><br />
    A set of edge E' is called an <strong>edge cut</strong> of G if the subgraph $G - E'$ is disconnected.
    <br />
    The <strong>edge connectivity</strong> of a graph G, denoted $\lambda(G)$, is the minimum number of edges in an edge cut of G.
</div>

<p>We always define $\lambda(G)$ for any connected graphs with at least one vertex because it is always possible to disconnect a graph by removing all edges incident to one of its vertices.</p>
<ul>
  <li>$\lambda(G) = 0$ if G is not connected.</li>
  <li>If G is a graph with $n$ vertices, then $0 \le \lambda(G) \le n - 1$</li>
  <li>$\lambda(G) = n - 1$ <em>if and only if</em> $G = K_n$</li>
  <li>$\lambda(G) \le n - 2$ <em>if and only if</em> G is <strong>not</strong> a complete graph.</li>
</ul>

<div class="theorem">
    When $G = (V,E)$ is a noncomplete connected graph with at least three vertices:
    $$\kappa(G) \le \lambda(G) \le \min_{v \in V} \deg(v) $$
</div>

<p>Proof: <a href="https://math.stackexchange.com/questions/1441288/inequality-relating-connectivity-edge-connectivity-and-minimum-degreewhitneys">[1]</a>, <a href="http://www.math.nagoya-u.ac.jp/~richard/teaching/s2020/Suzuki_Quang.pdf">[2]</a></p>

<p>Read more:</p>
<ul>
  <li><a href="http://www.cse.msu.edu/~esfahani/book_chapter/Graph_connectivity_chapter.pdf">Connectivity algorithm</a></li>
  <li><a href="http://algorist.com/problems/Edge_and_Vertex_Connectivity.html">Edge and Vertex Connectivity</a></li>
</ul>

<h3 id="connectedness-in-directed-graphs">Connectedness in Directed Graphs</h3>

<div class="definition"><br />
    A directed graph is <strong>strongly connected</strong> if there is a path from a to b and from b to a whenever a and b are vertices in the graph. <br />
    A directed graph is <strong>weakly connected</strong> if there is a path between every two vertices in the underlying undirected graph.
</div>

<p>A directed graph is weakly connected <em>if and only if</em> there is always a path between two vertices when the directions of the edges are disregarded. Clearly, any strongly connected directed graph is also weakly connected.</p>

<figure>
    <img src="https://www.mssqltips.com/tipimages2/6746_graph-analytics-using-apache-spark-graphframe-api.025.png" />
    <figcaption>Strong connected and Weakly connected graph (<a href="https://www.mssqltips.com/sqlservertip/6746/graph-analytics-apache-spark-graphframe-api/">mssqltips</a>)</figcaption>
</figure>

<div class="definition">
    The <strong>strongly connected components</strong> or <strong>strong components</strong> of $G$ are the maximal strongly connected subgraphs which is the subgraphs of a directed graph $G$ that are strongly connected but not contained in larger strongly connected subgraphs.
</div>

<figure>
    <img src="https://upload.wikimedia.org/wikipedia/commons/5/5c/Scc.png" />
    <figcaption>
        Graph with strongly connected components marked (<a href="https://en.wikipedia.org/wiki/Strongly_connected_component">Wikipedia</a>)
    </figcaption>
</figure>

<p>Read more:</p>
<ul>
  <li><a href="https://www.geeksforgeeks.org/strongly-connected-components/">Kosaraju’s algorithm</a></li>
  <li><a href="https://www.youtube.com/watch?v=wUgWX0nc4NY">Tarjan’s algorithm</a></li>
</ul>

<h3 id="paths-and-isomorphism">Paths and Isomorphism</h3>

<p><img src="https://rpruim.github.io/m252/S19/from-class/images/GraphFig9-4-6.png" /></p>

<p>Both $G$ and $H$ have same three invariants: number of vertices, number of edges, and degrees of vertices—all agree for the two graphs.</p>

<p>However, $H$ has a simple circuit of length three, namely, $v_1, v_2, v_6, v_1$, whereas $G$ has no simple circuit of length three, as can be determined by inspection (all simple circuits in $G$ have length at least four). Because the existence of a simple circuit of length three is an isomorphic invariant, $G$ and $H$ are not isomorphic.</p>

<p><img src="https://rpruim.github.io/m252/S19/from-class/images/GraphFig9-4-7.png" /></p>

<p>Both G and H have five vertices and six edges, both have two vertices of degree three and three vertices of degree two, and both have a simple circuit of length three, a simple circuit of length four, and a simple circuit of length five. Because all these isomorphic invariants agree, G and H may be isomorphic.</p>

<p>To confirm isomorphism, find the path go through all same degrees of 2 graphs. For example, the paths $u_1 \rightarrow u_4 \rightarrow u_3 \rightarrow u_2 \rightarrow u_5$ in $G$ and $v_3 \rightarrow v_2 \rightarrow v_1 \rightarrow v_5 \rightarrow v_4$ in $H$ both go through degrees: $3 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 2$. So, we can establish a mapping $f$ with $f(u_1) = v_3$, $f(u_4) = v_2$, $f(u_3) = v_1$, $f(u_2) = v_5$, and $f(u_5) = v_4$, this leads to that $G$ and $H$ are isomorphic.</p>

<h3 id="counting-paths-between-vertices">Counting Paths Between Vertices</h3>

<div class="definition">
    Let G be a graph with adjacency matrix $A$ with respect to the ordering $v_1, v_2, \dots, v_n$ of the vertices of the graph (with directed or undirected edges, with multiple edges and loops allowed).<br />
    The number of different paths of length $r$ from $v_i$ to $v_j$, where $r$ is a positive integer, equals the $(i, j)$th entry of $A^r$.
</div>

<p>For example (<a href="https://www.cs.sfu.ca/~ggbaker/zju/math/paths.html">sfu</a>):</p>

<p>The graph :</p>

<p><img src="https://www.cs.sfu.ca/~ggbaker/zju/math/img/graph-path3.svg" alt="" /></p>

<p>Adjacency Matrix:</p>

\[M=\left[\begin{smallmatrix}1&amp;1&amp;0&amp;0&amp;1 \\ 1&amp;0&amp;0&amp;0&amp;0 \\ 0&amp;1&amp;0&amp;1&amp;0 \\ 0&amp;1&amp;1&amp;0&amp;0 \\ 1&amp;0&amp;0&amp;0&amp;1 \end{smallmatrix}\right]\]

<p>The number of paths of length 2 between each pair of vertices:</p>

\[M^2=\left[\begin{smallmatrix}3&amp;1&amp;0&amp;0&amp;2 \\ 1&amp;1&amp;0&amp;0&amp;1 \\ 1&amp;1&amp;1&amp;0&amp;0 \\ 1&amp;1&amp;0&amp;1&amp;0 \\ 2&amp;1&amp;0&amp;0&amp;2\end{smallmatrix}\right]\]

<h2 id="euler-and-hamilton-paths">Euler and Hamilton Paths</h2>

<h3 id="euler-paths-and-circuits">Euler Paths and Circuits</h3>

<div class="definition">
    An <em>Euler circuit</em> in a graph G is a simple circuit containing every edge of G. <br />
    An <em>Euler path </em>in G is a simple path containing every edge of G.
</div>

<figure>
    <div class="row">
        <div class="column">
            <img src="https://user-images.githubusercontent.com/35303672/48727444-3da06880-ec58-11e8-9df5-821c5c1e3b1c.png" />
        </div>
        <div class="column">
            <img src="https://user-images.githubusercontent.com/35303672/48727417-28c3d500-ec58-11e8-9715-33b168a50b7c.png" />
        </div>
    </div>
    <figcaption>Euler circuit and Euler path (Credit: <a href="https://github.com/memr5/Eulerian-Path-and-Cycle-Detector">github/memr5</a>)</figcaption>
</figure>

<div class="theorem">
    A connected multigraph with at least two vertices has an <strong>Euler circuit</strong> if and only if each of its vertices has even degree.
</div>

<div class="theorem">
    A connected multigraph has an Euler path but not an Euler circuit if and only if it has exactly two vertices of odd degree.
</div>

<p>This is the recursive procedure to find the Euler path of a graph:</p>

<pre><code class="language-html">procedure FindEulerPath(V)
  1. iterate through all the edges outgoing from vertex V;
       remove this edge from the graph,
       and call FindEulerPath from the second end of this edge;
  2. add vertex V to the answer.</code></pre>

<p>The procedure could be rewrite in the non-recursive version:</p>

<pre><code class="language-html">stack St;
put start vertex in St;
until St is empty
  let V be the value at the top of St;
  if degree(V) = 0, then
    add V to the answer;
    remove V from the top of St;
  otherwise
    find any edge coming out of V;
    remove it from the graph;
    put the second end of this edge in St;</code></pre>

<p>Credit <a href="https://cp-algorithms.com/graph/euler_path.html">cp-algorithms</a> for the pseudocode.</p>

<div class="definition">
    An <em>Euler circuit</em> in a graph G is a simple circuit containing every edge of G. <br />
    An <em>Euler path </em>in G is a simple path containing every edge of G.
</div>

<figure>
    <div class="row">
        <div class="column">
            <img src="https://user-images.githubusercontent.com/35303672/48727444-3da06880-ec58-11e8-9df5-821c5c1e3b1c.png" />
        </div>
        <div class="column">
            <img src="https://user-images.githubusercontent.com/35303672/48727417-28c3d500-ec58-11e8-9715-33b168a50b7c.png" />
        </div>
    </div>
    <figcaption>Euler circuit and Euler path (Credit: <a href="https://github.com/memr5/Eulerian-Path-and-Cycle-Detector">github/memr5</a>)</figcaption>
</figure>

<div class="theorem">
    A connected multigraph with at least two vertices has an <strong>Euler circuit</strong> if and only if each of its vertices has even degree.
</div>

<div class="theorem">
    A connected multigraph has an Euler path but not an Euler circuit if and only if it has exactly two vertices of odd degree.
</div>

<p>This is the recursive procedure to find the Euler path of a graph:</p>

<pre><code class="language-html">procedure FindEulerPath(V)
  1. iterate through all the edges outgoing from vertex V;
       remove this edge from the graph,
       and call FindEulerPath from the second end of this edge;
  2. add vertex V to the answer.</code></pre>

<p>The procedure could be rewrite in the non-recursive version:</p>

<pre><code class="language-html">stack St;
put start vertex in St;
until St is empty
  let V be the value at the top of St;
  if degree(V) = 0, then
    add V to the answer;
    remove V from the top of St;
  otherwise
    find any edge coming out of V;
    remove it from the graph;
    put the second end of this edge in St;</code></pre>

<p>Credit <a href="https://cp-algorithms.com/graph/euler_path.html">cp-algorithms</a> for the pseudocode.</p>

<h3 id="hamilton-paths-and-circuits">Hamilton Paths and Circuits</h3>

<div class="definition">
    A simple path in a graph $G$ that passes through every vertex exactly once is called a <strong>Hamilton path</strong>, and a simple circuit in a graph G that passes through every vertex exactly once is called a <strong>Hamilton circuit</strong>. 
    <br />
    That is, the simple path $x_0, x_1, \dots ,x_{n−1}, x_n$ in the graph $G = (V , E)$ is a Hamilton path if $V = {x_0, x_1, \cdots , x_{n−1}, x_n}$ and $x_i = x_j$ for $0 \le i &lt; j \le n$, and the simple circuit $x_0, x_1, \dots , x_{n−1}, x_n, x_0$ (with $n &gt; 0$) is a Hamilton circuit if $x_0, x_1, \dots , x_{n−1}, x_n$ is a Hamilton path.
</div>

<p>There are no known simple
necessary and sufficient criteria for the existence of Hamilton circuits. However, many theorems are known that give sufficient conditions for the existence of Hamilton circuits. Also, certain properties can be used to show that a graph has no Hamilton circuit.</p>

<div class="theorem"><strong>Dirac's theorem</strong>
    If $G$ is a simple graph with n vertices with $n \ge 3$ such that the degree of every vertex in $G$ is at least $n/2$, then $G$ has a Hamilton circuit.
</div>

<div class="theorem"><strong>Ore's Theorem</strong>
    If $G$ is a simple graph with $n$ vertices with $n \ge 3$ such that \deg(u) + \deg(v) \ge n for every pair of nonadjacent vertices $u$ and $v$ in $G$, then $G$ has a Hamilton circuit.
</div>

<h2 id="shortest-path-problems">Shortest-Path Problems</h2>

<h2 id="planar-graphs">Planar Graphs</h2>

<h2 id="graph-coloring">Graph Coloring</h2>

<style>
.column {
  float: left;
  width: 50%;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}
</style>]]></content><author><name>Huy Pham</name></author><summary type="html"><![CDATA[Graph and Graph models]]></summary></entry><entry><title type="html">Fundamentals of Unconstrained Optimization</title><link href="https://pnhuy.github.io/optimization/2018/11/11/Fundamental-of-Unconstrained-Optimization.html" rel="alternate" type="text/html" title="Fundamentals of Unconstrained Optimization" /><published>2018-11-11T00:00:00+00:00</published><updated>2018-11-11T00:00:00+00:00</updated><id>https://pnhuy.github.io/optimization/2018/11/11/Fundamental-of-Unconstrained-Optimization</id><content type="html" xml:base="https://pnhuy.github.io/optimization/2018/11/11/Fundamental-of-Unconstrained-Optimization.html"><![CDATA[<p>In unconstrained optimization, we minimize an objective function that depends on real variable, with no restriction:</p>

\[\min_{x} f(x)\]

<p>where $x \in \mathbb{R}^n$ is a real vector with $n \ge 1$ components and $f: \mathbb{R}^n \rightarrow \mathbb{R}$ is a smooth function.</p>

<h2 class="label" id="what-is-a-solution">What is a solution?</h2>

<div class="definition">
A point $x*$ is a <em>global minimizer</em> if $f(x^*) \le f(x), \forall x \in \mathbb{R}^n$
</div>

<p>The global minimizer can be difficult to find. And most algorithms are able to find only a <em>local minimizer</em>:</p>

<div class="definition">
A point $x*$ is a <em>local minimizer</em> if there is a neighborhood N of $x*$ such that $f(x^*) \le f(x), \forall x \in N$
</div>

<p>This is sometimes called a <em>weak local minimizer</em>.</p>

<div class="definition">
A point $x*$ is a <em>strict local minimizer</em> (also called a strong local minimizer) if there is a neighborhood N of $x*$ such that $f(x^ *) &lt; f(x), \forall x \in N$  with $x \ne x^ *$.
</div>

<p>A slightly more exotic type of <em>local minimizer</em>:</p>

<div class="definition">A point $x*$ is an <em>isolated local minimizer</em> if there is a neighborhood N of $x*$ such that $x*$ is the only local minimizer in N.</div>

<p>While strict local minimizers are not always isolated, it is true that all isolated local minimizers are strict.</p>

<h2 id="recognizing-a-local-minimum">Recognizing a local minimum</h2>

<p>Is x* is a local minimum? → Examine all the points in its immediate vicinity to make sure that none of them has a smaller function value.</p>

<p>If f is twice continuously differentiable, we may be able to tell that x* is a local minimizer (and possibly a strict local minimizer) by examining just the gradient $\nabla f(x^ * )$ and the Hessian $\nabla^2 f(x^ * )$  by using Taylor’s theorem.</p>

<div class="theorem">
<strong>Taylor's Theorem</strong>
<br />
Suppose that $f: \mathbb{R}^2 \rightarrow \mathbb{R}$ is continuously differentiable and that $p \in \mathbb{R}^n$. Then we have that
$$f(x+p) = f(x) + \nabla f(x+tp)^Tp$$
for some $t \in (0,1)$.
<br />
Moreover, if $f$ is twice continuously differentiable, we have that 
$$\nabla f(x+p) = \nabla f(x) + \int_0^1 \nabla ^2 f(x+tp)p \mathrm{d}t$$
and that
$$f(x+p) = f(x) + \nabla f(x+tp)^Tp +\frac{1}{2}p^T \nabla ^2 f(x+tp)p$$
</div>

<p><em>Necessary conditions</em> for optimality are derived by assuming that x* is a local minimizer and then providing facts about $\nabla f(x^ * $ and $\nabla^2 f(x^ * )$.</p>

<div class="theorem">
	<strong>First-Order Necessary Conditions</strong>
	<br />
	If x* is a local minimizer and f is continuous differentiable in an open neighborhood of x* , then $\nabla f(x^*) = 0$.
</div>

<div class="theorem">
	<strong>Second-Order Necessary Conditions</strong>
	<br />
	If x* is a local minimizer of $f$ and $\nabla^2 f$ is continuous in an open neighborhood of x* , then  $\nabla f(x^ * ) = 0$ and $\nabla^2 f(x^*)$  is positive semidefinite.
</div>

<div class="theorem">
	<strong>Second-Order Sufficient Conditions</strong>
	<br />
	Suppose that $\nabla^2 f$ is continuous in an open neighborhood of x* and that $\nabla f(x^ * ) = 0$ and $\nabla^2 f(x^ * ) $ is positive definite. Then x* is a strict *local minimizer* of $f$.
</div>

<div class="theorem">When f is convex, any local minimizer x* is a global minimizer of f. If in addition f is differentiable, then any stationary point x* is a global minimizer of f.</div>

<h2 id="algorithms">Algorithms</h2>

<h3 id="line-search-vs-trust-region">Line Search <em>vs</em> Trust Region</h3>

<p>General approach of algorithms for unconstrained minimization:</p>

<ul>
  <li>Supply a starting point $x_0$</li>
  <li>Generate a sequence of iterates ${x_k}_{k=0}^\infty$</li>
  <li>Terminate when either no more progress can be made or when it seems that a solution point has been approximated with sufficient accuracy.</li>
</ul>

<p>There are 2 common strategies for moving from the current point $x_k$ to a new iterate $x_{k+1}$: <em>Line search</em> and <em>Trust region</em>.</p>

<h4 id="line-search-strategy"><em>Line search</em> strategy</h4>

<ul>
  <li>Choose a direction $p_k$</li>
  <li>Search along this direction from the current state $x_k$ for a new state with a lower function value</li>
  <li>The distance can be found by solving approximately ($\alpha$ is step length):</li>
</ul>

\[\min_{\alpha&gt;0} f(x_k + \alpha p_k)\]

<p>The exact minimization is expensive and unnecessary. In fact, the line search algorithm generates a limited number of trial step lengths until it finds one that the loosely approximates the minimum of above minimization.</p>

<h4 id="trust-region-strategy"><em>Trust region</em> strategy</h4>

<ul>
  <li>Construct a <em>model function</em> $m_k$ that approximately similar to $f$ in neighborhood of $x_k$.</li>
  <li>
    <p>Search minimizer of $m_k$ (also $x_k$) in some region around $x_k$. In other words, we find the candidate step p by approximately solving the following subproblem:</p>

\[\min_{p} m_k(x_k+p)\]

    <p>where $x_k +p$ lies inside the trust region.</p>
  </li>
  <li>
    <p>If solution does not produce a sufficient decrease in $f$ → <em>Trust region</em> is too large → Shrink it and re-solve.</p>

    <p>The trust region is defined by $|p|_2 \le \Delta$ where the scalar $\Delta &gt; 0$ is called the trust-region radius. The model $m_k$  is usually defined to be a quadratic function of the form:</p>

\[m_k(x_k + p)= f_k + p^T \nabla f_k + \frac{1}{2} p^T B_k p\]

    <p>where $f_k, \nabla f_k, B_k$ are a scalar, vector, matrix, respectively. $B_k$ is either the Hessian $\nabla^2 f_k$ or some approximation to it.</p>
  </li>
</ul>

<p>The <em>line search</em> and <em>trust region</em> approaches differ in the order in which they choose the direction and distance of the move to the next iterate.</p>

<p>For line search, fixing the direction $p_k$ → identifying an appropriate distance $\alpha_k$</p>

<p>For trust region, choose a maximum distance - the trust region radius $\Delta_k$ → seek a direction and step</p>

<h4 id="search-directions-for-line-search-methods">Search directions for <em>Line search</em> methods</h4>

<h5 id="the-steepest-descent-direction">The steepest-descent direction</h5>

<p>The most obvious choice for search direction for line search method is <em>the steepest-descent direction</em> $- \nabla f_k$. That means among all the directions we could move from $x_k$, this is the way that $f$ decreases most rapidly.</p>

<p>Let’s prove this. By Taylor’s theorem, we have</p>

\[f(x_k +\alpha p) = f(x_k) +\alpha p^T \nabla f_k + \frac{1}{2} \alpha^2 p^T \nabla^2 f(x_k + tp) p \text{, for some }t \in (o, \alpha)\]

<p>which p is the search direction and $\alpha$ is the step-length parameter.</p>

<p>So, in this formula, <em>the rate of change</em> in $f$ along the direction $p$ at $x_k$ is $p^T \nabla f_k$.</p>

<p>As the result, the unit direction $p$ of the most rapid decrease is the solution to the problem</p>

\[\min_p p^T \nabla f_k \text{, subject to } \|p\| =1\]

<p>Because $p^T \nabla f_k = |p| | \nabla f_k | \cos \theta$ and $| p|=1$, we have $p^T \nabla f_k = | \nabla f_k | \cos \theta$. Minimization in (9) occurs when $\cos \theta = -1$ at $\theta = \pi$. In other words, the solution to (9) is</p>

\[p = -\nabla f_k / \|\nabla f_k\|\]

<p>In visual representation, this direction is orthogonal to the contours of the function.</p>

<p><img src="http://trond.hjorteland.com/thesis/img200.gif" alt="The direction" /></p>

<p><strong>Advantage of the steepest descent direction</strong> is that it require calculation of the gradient $\nabla f_k$ but not of second derivatives. However, it can be excruciatingly slow on difficult problems.</p>

<p>When the $\theta$ is not exactly $\pi$ or the direction is just descent, Taylor’s theorem also verifies that $f$ is still decreased with a sufficiently small. In this situation, $p_k$ is <em>a down hill direction</em>.</p>

<h5 id="newton-direction">Newton direction</h5>

<p>From the second-order Taylor series approximation to $f(x_k + p)$ :</p>

\[f(x_k + p) \approx f_k + p^T \nabla f_k + \frac{1}{2} p^T \nabla^2 f_k p \overset{def}{=} m_k(p)\]

<p>Assuming that $\nabla^2 f_k$ is positive definite, the Newton direction is defined by finding the vector $p$ that minimizes $m_k (p)$. By simply setting the derivative of $m_k(p)$ to zero, we obtain the following explicit formula:</p>

\[p^N_k = -\nabla^2 f_k^{-1} \nabla f_k\]

<p><strong>When $\nabla^2 f_k$ is positive definite</strong>, we have</p>

\[\nabla f_k^T p_k^N = -p_k^{NT} \nabla^2 f_k p_k^N \le -\sigma_k \| p_k^N \|^2 \text{, for some }\sigma_k &gt; 0\]

<p>Unless the gradient $\nabla f_k$ is zero, we have that $\nabla f_k^T p_k^N &lt; 0 $, so the Newton direction is a descent direction.</p>

<p>Unlike the steepest descent direction, there is a “natural” step length of 1 associated with the Newton direction. Most line search implementations of Newton’s method use the unit step $\alpha = 1$ where possible and adjust this step length only when it does not produce a satisfactory reduction in the value of $f$.</p>

<p><strong>When</strong> $\nabla^2 f_k$ <strong>is not positive definite</strong>, the Newton direction may not even be defined, since $\nabla^2 f_k^{-1}$ may not exist. Even when it is defined, it may not satisfy the descent property $\nabla f_k^T p_k^N  &lt; 0$. So that, it is unsuitable as a search direction.</p>

<p>In these cases,  <em>$p_k$ need to be changed</em> to guarantee the downhill condition while keeping the benefit of second-order information in $\nabla^2 f_k$.</p>

<p>The Newton direction approach has a fast rate of local convergence - quadratic.</p>

<p><em>The main disadvantage</em> of the Newton direction is the need for the Hessian $\nabla^2 f(x)$. This is usually a cumbersome, error-prone and expensive process.</p>

<h5 id="quasi-newton-direction">Quasi-Newton direction</h5>

<p>This method do not require computation of the Hessian but still have a super linear rate of convergence.</p>

<p>They use an approximation $B_k$ for the true Hessian $\nabla^2 f_k$. In this case, $B_k$ is updated to take account of the additional knowledge gained after each step. The updates make use of the fact that changes in the gradient $g$ provide information about the second derivative of $f$ along the search direction.</p>

<p>\[
\nabla f(x+p) = \nabla f(x) + \nabla^2 f(x) p + \int_{0}^{1} \left[\nabla^2 f(x+tp) - \nabla^2 f(x) \right]p dt
\]</p>

<p>Because $\nabla f(.)$ is continuous, the size of final integral term is $o(|p|)$. By setting $x = x_k$ and $p = x_{k+1} - x_k$:
\[
\nabla f_{k+1} = \nabla f_k + \nabla^2 f_{k+1} (x_{k+1} - x_k) + o(| x_{k+1} - x_k |)
\]</p>

<p>When $x_k$ and $x_{k+1}$ lie nearly the solution $x*$, within which $\nabla f$ is positive definite, the final term in this expansion is eventually dominated by the $\nabla^2 f_k (x_{k+1} - x_k)$ and $\nabla^2 f_{k+1} (x_{k+1} - x_k) \approx \nabla f_{k+1} - \nabla f_k$</p>

<p>We choose the new Hessian approximation $B_{k+1}$ so that it mimics this property. This means that it needs to satisfy the <em>secant equation</em>:
\[
B_{k+1} s_k = y_k
\]
where
\[
s_k = x_{k+1} - x_k, y_k = \nabla f_{k+1} - \nabla f_k
\]</p>

<p>There are two most popular way to choose $B_{k+1}$:</p>
<ul>
  <li>The <em>symmetric-rank-one</em> (SR1) formula:
  \[
  B_{k+1} = B_k + \frac{(y_k - B_k s_k)(y_k - B_k s_k)^T}{(y_k - B_k s_k)^T s_k}
  \]</li>
  <li>The <em>BFGS</em> (Broyden-Fletcher-Goldfarb-Shanno) formula (which is a rank-two matrix):
  \[
  B_{k+1} = B_k - \frac{B_k s_k s_k^T B_k}{s_k^T B_k s_k} + \frac{y_k y_k^T}{y_k^T s_k}
  \]</li>
</ul>

<p>The quasi-Newton search direction is $p_k = -B_k^{-1} \nabla f_k$</p>

<p>By applying the inverse approximation $H_k \overset{def}{=} B_k^{-1}$, the above formula is equivalent to
\[
H_{k+1} = (I - \rho_k s_k y_k^T) H_k (I - \rho_k y_k s_k^T) + \rho_k s_k s_k^T, \rho_k = \frac{1}{y_k^T s_k}
\]</p>

<p>This can be implemented as a matrix-vector multiplication, which is typically simpler than the previous formula.</p>

<h5 id="nonlinear-conjugate-gradient-methods">Nonlinear conjugate gradient methods</h5>

<p>This method of search direction has form
\[
p_k = -\nabla f(x_k) + \beta_k p_{k-1}
\]</p>

<p>where $\beta_k$ is a scalar that ensure that $p_k$ and $p_{k-1}$ are <em>conjugate</em>.<br />
This method is much more effective than the steepest descent direction, not requiring storage of matrices and simple to compute but does not retain the fast convergence rates of Newton or quasi-Newton methods.</p>

<h4 id="models-for-trust-region-methods">Models for Trust-region methods</h4>

<p>The subproblem of Trust-region is</p>

\[\min_{p} m_k(x_k + p)\]

<p>where $x_k + p$ lies inside the trust region.</p>

<p>The model function has the quadratic fuction form:</p>

\[m_k(x_k + p)= f_k + p^T \nabla f_k + \frac{1}{2} p^T B_k p\]

<p>We have some ways to choose $B_k$:</p>
<ul>
  <li>We set $B_k = 0$ and define the trust region using the Euclidean norm, the trust region subproblem becomes
  \[
  \min_{p} f_k + p^T \nabla f_k \text{, subject to }| p |_2 \le \Delta_k
  \]
  We can write the solution to this problem in closed form as
  \[
  p_k = -\frac{\Delta_k \nabla f_k}{| \nabla f_k |}
  \]
  This is simply a steepest descent step in which the step length is determined by the trust-region radius; the trust-region and line search approaches are essentially the same in this case.</li>
  <li>We can choose $B_k$ to be exact Hessian $\nabla^2 f_k$ in quadratic model. The subprolem is guaranteed to have a solution $p_k$ even though the $\nabla^2 f_k$ is not positive definite because of the restriction $| p|_2 \le \Delta_k$.</li>
  <li>We are also able to choose $B_k$ by means of a quasi-Newton approximation. This is <em>trust-region quasi-Newton method</em>.</li>
</ul>

<h2 id="scaling">Scaling</h2>

<!-- \begin{figure}
	\centering
	\includegraphics[width=0.5\linewidth]{scaling.png}
	\caption{Poorly scaled and Well-scaled problems. In the poorly scaled problem, the steepest descent direction does not yield much reduction in the function, while the well-scaled problem performs much better.}
	\label{fig:scaling}
\end{figure} -->

<p>A uncontrained optimization is <em>poorly scaled</em> if changes to x in a certain direction prodct much larger variations in the value of $f$ than do changes to x in another direction.</p>

<p>Steepest descent and som optimization algorithms are sensitive to poor scaling, while others such as Newton’s method are unaffected by it.
In design complete algorithms, <em>scale invariance</em> is included in all aspects of algoritm. In general, it is easier to preserve scale invariance for line search algorithms than for trust-region algorithms.</p>

<h2 id="rates-of-convergence">Rates of convergence</h2>

<div class="definition">
	Let $\{x_k\}$ be a sequence in $\mathbb{R}^n$ that converges to $x^{*}$.
	We say that the convergence is <strong>Q-linear</strong> if there is a constant $r \in (0,1)$ such that
	$$\frac{\| x_{k+1} - x* \|}{\| x_k - x* \|} \le r \text{, for all k sufficiently large}$$
	The convergence is said to be <strong>Q-superlinear</strong> if
	$$\lim_{k \rightarrow \infty} \frac{\| x_{k+1} - x* \|}{\| x_k - x* \|} = 0 \text{, for all k sufficiently large}$$
	<strong>Q-quadratic</strong> is optained if
	$$\frac{\| x_{k+1} - x* \|}{\| x_k - x* \|^2} \le M \text{, for all k sufficiently large}$$
	In general, the <strong>Q-order</strong> of convergence is p (with p &gt; 1) if there is a positive constant M such that
	$$\frac{\| x_{k+1} - x* \|}{\| x_k - x* \|^p} \le M \text{, for all k sufficiently large}$$
</div>

<p>For example:</p>
<ul>
  <li>$1+(0.5)^k$ converges <em>Q-linearly</em> to 1</li>
  <li>$1+k^{-k}$ converges <em>superlinearly</em> to 1</li>
  <li>$1+ (0.5)^{2^k}$ converses <em>quadratically</em> to 1</li>
</ul>

<p>The speed of convergence depends on $r$ and $M$. These values depend on both algorithms and properties of problem. However, a quadratically convergent sequence will always eventually converge faster than a linearly convergent sequence.</p>

<p>Quasi-Newton methods typically converge Q-superlinearly, whereas Newton’s method converges Q-quadratically. In contrast, steepest descent algorithms converge only at a Q-linear rate, and when the problem is ill-conditioned the convergence constant $r$ is close to 1.</p>]]></content><author><name>Huy Pham</name></author><category term="optimization" /><summary type="html"><![CDATA[In unconstrained optimization, we minimize an objective function that depends on real variable, with no restriction:]]></summary></entry><entry><title type="html">How To Choose Data Visualization Techniques</title><link href="https://pnhuy.github.io/2018/07/19/How-to-choose-data-visualization-techniques.html" rel="alternate" type="text/html" title="How To Choose Data Visualization Techniques" /><published>2018-07-19T00:00:00+00:00</published><updated>2018-07-19T00:00:00+00:00</updated><id>https://pnhuy.github.io/2018/07/19/How-to-choose-data-visualization-techniques</id><content type="html" xml:base="https://pnhuy.github.io/2018/07/19/How-to-choose-data-visualization-techniques.html"><![CDATA[<p><img src="https://farm1.staticflickr.com/836/43458860252_be443be255_o.png" alt="" /></p>

<p>Credit: <a href="https://towardsdatascience.com/5-quick-and-easy-data-visualizations-in-python-with-code-a2284bae952f">George Seif</a></p>]]></content><author><name>Huy Pham</name></author><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Introduction to Machine learning</title><link href="https://pnhuy.github.io/machinelearning/2018/07/17/Fundamental-Machine-Learning.html" rel="alternate" type="text/html" title="Introduction to Machine learning" /><published>2018-07-17T00:00:00+00:00</published><updated>2018-07-17T00:00:00+00:00</updated><id>https://pnhuy.github.io/machinelearning/2018/07/17/Fundamental-Machine-Learning</id><content type="html" xml:base="https://pnhuy.github.io/machinelearning/2018/07/17/Fundamental-Machine-Learning.html"><![CDATA[<h2 id="four-branches-of-machine-learning">Four branches of machine learning</h2>

<h3 id="supervised-learning">Supervised learning</h3>
<p>It consists of learning to map input data to known targets:
$f: x (input) \rightarrow y (output)$
There are 2 major techniques in supervised: classification and regression, and there are more exotic variants as well:</p>

<ul>
  <li>Sequence generation, eg: captioning the picture</li>
  <li>Syntax tree prediction, eg: decomposition a sentence</li>
  <li>Object detection, eg: draw a bounding box aroung certain objects inside a picture</li>
  <li>Image segmentation, eg:..</li>
</ul>

<h3 id="unsupervised-learning">Unsupervised learning</h3>
<p>It consists of finding interesting transformations of the input data without targets.
Application of unsupervised learning is supports in data visualization, data compression or data denoising or to better understanding the correlation present in the data.
Well-known categories of unsupervised learning are <strong>Dimensionality reduction</strong> and <strong>clustering</strong></p>

<h3 id="self-supervised-learning">Self-supervised learning</h3>
<p>It is supervised learning without human-annotated labels, they’re generated from the input data, typically using a heuristic algorithms</p>

<p>Well-knowns instance of self-supervised learning: autoencoders</p>

<h3 id="reinforcement-learning">Reinforcement learning</h3>
<p>An <em>agent</em> receives information about its environment and learns to choose actions that will maximize some reward. Some potential application area of reinforcement learning: self-driving cars, robotics, resource management, education,…</p>

<h2 id="evaluating-machine-learning-models">Evaluating machine learning models</h2>
<p>In machine learning, the main goal is to archive models that <em>generalize</em> (perform well on <em>never-before-seen</em> data) and <em>overfitting</em> is the central obstacle. There are some strategies to measure generalization or evaluate machine-learning models.</p>

<h3 id="training-validation-and-test-sets">Training, validation and test sets</h3>
<p>The data set is divided into <strong>THREE</strong> sets:</p>

<ul>
  <li>Training set: train the model</li>
  <li>Validation set: evaluate the model</li>
  <li>Test set: test the model</li>
</ul>

<p>The model developing always involves tuning its configuration, eg:</p>
<ul>
  <li>The number of layers</li>
  <li>The size of layers</li>
  <li>other <em>hyperparameters</em>…</li>
</ul>

<p>Tuning the configuration can result in the <em>overfitting to the validation set</em> because of <em>information leaks</em>. Every time you tune a hyperparameter of the model based on the model’s performance on the validation set, some information about the validation data leaks into the model. At the end, the model performs well on the validation data, so you need to use a completely differet dataset to evaluate the model: the test dataset.</p>

<p>There are some methods for validation:</p>

<h4 id="simple-hold-out-validation">Simple hold-out validation</h4>

<p><img src="https://image.ibb.co/f6f1my/hold_out_validation.png" alt="" /></p>

<h4 id="k-fold-validation">K-fold validation</h4>

<p><img src="https://image.ibb.co/bUm7Ry/k_fold_validation.png" alt="" /></p>

<h4 id="iterated-k-fold-validation-with-shuffling">Iterated K-fold validation with shuffling</h4>

<p>It consists of applying K-fold validation multiple times and shuffling the data every time before splitting it K ways.</p>

<h4 id="notes">Notes</h4>

<ul>
  <li>Data representativeness: you should randomly shuffle your data before splitting it to make sure that the training set and test set could be representative of the whole data.</li>
  <li>Time series data should not randomly shuffle, the test set should be posterior to the data in the training set.</li>
  <li>Redundancy in your data</li>
</ul>

<h2 id="data-preprocessing-feature-engineering-and-feature-learning">Data preprocessing, feature engineering, and feature learning</h2>

<h3 id="data-preprocessing">Data preprocessing</h3>

<p>Aim: making the raw data more amenable (easy to control) to neural networks.</p>

<h4 id="vectorization">Vectorization</h4>

<p>Inputs or targets in a neural network must be tensors of floating-point data (or integers).
If your data is sound, images, text, you should first turn into tensors. This step called <em>data vectorization</em>.</p>

<h4 id="value-normalization">Value normalization</h4>

<p>In general, it isn’t safe to feed the neural networks data that takes relatively large values or data the is heterogeneous (one feature is in the range 0-1, one feature is in the range 100-200).
This causes large gradient updates that will prevent the network from converging. To make learning easier for your network, your data should have the following characteristics:</p>
<ul>
  <li>Take small values</li>
  <li>Be homogenous</li>
</ul>

<p>The normalization (to mean of 0 and standard deviation of 1) is the common practice.</p>

<h4 id="handling-the-missing-values">Handling the missing values</h4>

<p>In general, with neural networks, it’s safe to input missing values as 0, with the condition that 0 isn’t already a meaningful value. The network will learn from exposure to the data that the value 0 means missing data and will start ignoring the value.</p>

<h3 id="feature-engineering">Feature engineering</h3>

<p>The essense of feature engineering is making a problem easier by expressing it in a simpler way. It usually requires understanding the problem in depth.</p>

<p>Example:
Raw data: Pixel gird of clock -&gt; Better feature: clock hands’ coordinates {x1, y2}, {x2, y2} -&gt; Even better features: angles of clock hands theta1, theta 2</p>

<p>Good features allow you to solve problems more elegantly while using fewer resources. For instance, it would be ridiculous to solve the problem of reading a clock face using a convolutional neural network.
Good features let you solve a problem with far less data. The ability of deep</p>

<h2 id="overfitting-and-underfitting">Overfitting and Underfitting</h2>

<p>The fundamental issue in machine learning is the tension between optimization and generalization.</p>
<ul>
  <li>Optimization: adjusting a model to get the best performance possible on the training data.</li>
  <li>Generalization: how well the trained model performs on data it has never seen before.</li>
</ul>

<p>At the beginning of training: optimization and generalization are correlated: the lower the loss on training data, the lower the loss on test data. While this is happening, your model is said to be <strong>underfit</strong> -&gt; there is still progress to be made; the network hasn’t yet modeled all relevant patterns in the training data.</p>

<p>After a certain number of iterations on the training data, generalization stops improving and validation metrics stall and then begin to degrade: the model is starting to <strong>overfit</strong> -&gt; it’s beginning to learn patterns that are specific to the training data but that are misleading or irrelevant when it comes to new data.</p>

<p><strong>Get more training data is usually useful:</strong> a model trained on more data will naturally generalize better.
If more data failed, the next solution is <strong>to modulate the quantity of information that your model is allowed to store or to add constraints on what information it’s allowed to store.</strong> -&gt; <strong>regularization</strong>.</p>

<h3 id="reducing-the-networks-size">Reducing the network’s size</h3>
<p>This is the simplest way to prevent overfitting.</p>

<p>The network’s size or The number of learnable paramaters in a model (determined by the number of layers and the number of units per layer) is often referred to as the model’s capacity. A model with more parameters has more memorization capacity, so it can easily learn a perfect dictionary-like mapping between training samples and their targets - a mapping with out any generalization power.</p>

<p>Deep learning models tend to be good at fitting to the training data, but the real challenge is generalization.</p>

<p>The model should have just enough parameters that they don’t underfitting.</p>

<p><strong>No formula to determine the right number of layers or the right size of each layer</strong>. Need to research to find the optimal model size of your data.</p>

<h3 id="adding-weight-regularization">Adding weight regularization</h3>

<p>This way to mitigate overfitting is to put constraints on the complexity of a network by forcing its weights to take only small values, which makes the distribution of weight values more <strong>regular</strong> =&gt; <strong>weight regularization</strong>
There are 2 flavors:</p>
<ul>
  <li>L1 regularization -&gt; The cost added is proportional to the <em>absolute value of the weight coefficients</em> (L1 norm of the weights)</li>
  <li>L2 regularization -&gt; The cost added is proportional to the <em>square of the value of the weight coefficients</em> (L2 norm of the weights/ <em>Weight decay</em>)</li>
</ul>

<h3 id="adding-dropout">Adding dropout</h3>
<p><strong>Dropout</strong> is one of the most effective and most commonly used regularization techniques for neural networks.
When apply to a layer,dropout consists of randomly dropping out (setting to zero) a number of output features of the layer during training.</p>

<p>Eg: [0.2, 0.5, 1.3, 0.8, 1.1] –dropout–&gt; [0, 0.5, 1.3, 0, 1.1]</p>

<p>The <strong>dropout rate</strong> is the fraction of the features that are zeroed out; it’s usually set between 0.2 and 0.5.</p>

<h2 id="the-universal-workflow-of-machine-learning">The universal workflow of machine learning</h2>
<h3 id="defining-the-problem-and-assembling-a-dataset">Defining the problem and assembling a dataset</h3>
<ul>
  <li>What will your input data be?</li>
  <li>What are you trying to predict?</li>
  <li>What type of problem are you facing?</li>
  <li>Is it binary classification or multiclass classification? Scala or vector regression? Multiclass, multilabel classification?…</li>
</ul>

<h3 id="choosing-a-measure-of-success">Choosing a measure of success</h3>
<p>For regression problems:</p>
<ul>
  <li>Accuracy? Precision and Recall?</li>
  <li>Customer-retention rate?</li>
</ul>

<p>For balanced-classification problems, accuracy and <em>area under the receiver operating chracteristic curve (ROC AUC)</em> are common metrics.</p>

<p>For ranking problems or multilabel classification: mean average precision.</p>
<h3 id="deciding-on-an-evaluation-protocol">Deciding on an evaluation protocol</h3>
<ul>
  <li>Maintaining a hold-out validation set: having plenty of data</li>
  <li>Doing K-fold cross-validation: having too few samples for hold-out validation to be reliable</li>
  <li>Doing iterated K-fold validation: for performing highly accurate model evaluation when little data is available.</li>
</ul>

<h3 id="preparing-your-data">Preparing your data</h3>
<ul>
  <li>Formatted as tensors</li>
  <li>Scaled to small values</li>
  <li>Normalized</li>
  <li>Feature engineering</li>
</ul>

<h3 id="developing-a-model-that-does-better-than-a-baseline">Developing a model that does better than a baseline</h3>
<ul>
  <li>Last-layer activation: eg: sigmoid in the last layer, regression didn’t use last-layer activation,…</li>
  <li>Loss function</li>
  <li>Optimization configuration: which optimizer?</li>
</ul>

<table>
  <thead>
    <tr>
      <th>Problem type</th>
      <th>Last-layer activation</th>
      <th>Loss function</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Binary classification</td>
      <td>sigmoid</td>
      <td>binary crossentropy</td>
    </tr>
    <tr>
      <td>Multiclass, single-label classification</td>
      <td>softmax</td>
      <td>categorical crossentropy</td>
    </tr>
    <tr>
      <td>Multiclass, multilabel classification</td>
      <td>sigmoid</td>
      <td>binary crossentropy</td>
    </tr>
    <tr>
      <td>Regression to arbitrary values</td>
      <td>None</td>
      <td>MSE</td>
    </tr>
    <tr>
      <td>Regression to values between 0 and 1</td>
      <td>sigmoid</td>
      <td>MSE or binary crossentropy</td>
    </tr>
    <tr>
      <td>Regression to values between 0 and 1</td>
      <td>sigmoid</td>
      <td>MSE or binary crossentropy</td>
    </tr>
  </tbody>
</table>

<h3 id="scaling-up-developing-a-model-that-overfits">Scaling up: developing a model that overfits</h3>
<ul>
  <li>Add layers</li>
  <li>Make the layers bigger</li>
  <li>Train for more epochs</li>
</ul>

<p>→ Monitor the training loss and validation loss or other metrics.</p>

<h3 id="regularizing-your-model-and-tuning-your-hyperparameters">Regularizing your model and tuning your hyperparameters</h3>
<ul>
  <li>Add dropout</li>
  <li>Try different architectures: add or remove layers</li>
  <li>Add L1 and or L2 regularization</li>
  <li>Try different hyperparameters to find the optimal configuration</li>
  <li>Optionally, iterate on feature engineering: add new features, remove features.</li>
</ul>]]></content><author><name>Huy Pham</name></author><category term="machinelearning" /><summary type="html"><![CDATA[Four branches of machine learning]]></summary></entry></feed>