[{"content":"My mother said that out of all five of her children, I was the easiest baby. I think what she meant was that I hardly cried, rarely fussed, and was generally asleep, which I guess was a good thing, for her. As the fourth of five, she had a lot to deal with before she could get to me, so I made it easier for her.\nI kept doing it as I grew up. If one of my siblings dropped their ice cream, I\u0026rsquo;d give them mine so they\u0026rsquo;d stop making a scene. When someone had to sit in a middle seat, you can bet that\u0026rsquo;s where my car seat would be strapped. In fifth grade, when Clara Gomez stole my cookie from my lunch box, I just shrugged and ate my carrot sticks.\nMy nickname was \u0026ldquo;montanita\u0026rdquo;, little mountain, because I was never moved, never bothered, always calm.\nIn seventh grade, I broke my leg, but I didn\u0026rsquo;t tell anyone for three days. I just gritted my teeth and hopped along until my father found me crying on the bathroom floor. He took me to the hospital and bought me a cast we couldn\u0026rsquo;t afford. And when the kids at school called me a cripple, well, you can guess what I did.\nIn high school, my little sister Sofia was getting picked on by some boys. I pretended I didn\u0026rsquo;t see it happen, but that night I switched out her too-small uniform skirt for mine. She stopped getting teased, and I wore pants for the rest of the year.\nWhen my college Algebra professor lost my test and made me retake it, I just nodded and did it. When I got catcalled walking across campus, I just looked down at the ground.\nAnd you. The first day you came up to me and offered to buy me coffee, I was sure you were making fun of me too, so I stayed quiet. Eventually, you flashed me that blinding smile and told me, \u0026ldquo;Guess I\u0026rsquo;ll take that as a yes, then.\u0026rdquo; I think I said about three words to you that first day, but I gave you my number and answered when you called.\nAt first, I think, you just thought I was shy. But as the months went on and things got more serious, you started to get upset when I didn\u0026rsquo;t tell you things. When I got fired from my part-time job and started skipping lunch to afford my textbooks, I didn\u0026rsquo;t want to tell you because I knew it\u0026rsquo;d upset you. I was right, wasn\u0026rsquo;t I? You were so mad when you figured it out. \u0026ldquo;Here!\u0026rdquo; you yelled, shoving money at me. \u0026ldquo;Take it! I don\u0026rsquo;t need it! You know I have a scholarship, you know my parents send me money. Take the goddamn money!\u0026rdquo;\nI just stood there. I\u0026rsquo;d never had someone yell at me while doing something nice before. When you noticed how stunned I was, you softened your voice. \u0026ldquo;Please, it hurts me to see you starving yourself. Please, take the money.\u0026rdquo;\nFor the first time ever, I talked back. \u0026ldquo;Why?\u0026rdquo;\nYou laughed at me. \u0026ldquo;Because I love you, you idiot.\u0026rdquo;\nI took the money, but snuck most of it back into your wallet that night when you were asleep.\nFor most of the time we dated, we never fought, even when one of your friends tried to tell me you cheated on me. (I know you hadn\u0026rsquo;t; the friend was just a jerk.) When he tried to tell me, I just stared at him. Didn\u0026rsquo;t cry, or yell, or demand proof. That freaked the friend out a bit. He kept trying to convince me, but I stayed so calm he eventually gave up and admitted the truth. Later, you told me you couldn\u0026rsquo;t believe how amazing I was to trust you so much. The truth was, I had no idea if it was the truth or not. I just didn\u0026rsquo;t react because I knew if I did, it wouldn\u0026rsquo;t change the outcome, and I\u0026rsquo;d learned that staying calm in situations like that gave me the power.\nOur marriage, too, had very few fights. If you didn\u0026rsquo;t take out the trash like you said you would, I did it. And when you noticed I\u0026rsquo;d done your chores, you felt so bad that you\u0026rsquo;d do some of mine to make it up. When our children misbehaved, I never raised my voice or screamed or made a scene. I just asked them what they did, and eventually they\u0026rsquo;d cave. Our oldest told me once it\u0026rsquo;d be much less scary if I\u0026rsquo;d just shout at them like Dad did.\nI figured I\u0026rsquo;d stay like I was: calm, quiet, a peacemaker, nonreactive, for the rest of my life. But you changed that. You jerk.\nWhen you died. When you died, it was like that frozen mountain of emotional outbursts inside me melted all at once. Nobody expected it when I started screaming and sobbing at the funeral. My older brother tried to take me outside, and I punched him in the jaw. (I apologized later, of course.)\nYou\u0026rsquo;d hardly recognize me now, I think. It\u0026rsquo;s a lot harder for me to stare blankly and take things, because I keep remembering you saying, \u0026ldquo;Stand up for yourself! You deserve better, mi amor.\u0026rdquo; And you\u0026rsquo;re not here anymore to stand up for me, or our kids.\nI don\u0026rsquo;t know how to describe it exactly, what changed the moment you left this Earth, but it\u0026rsquo;s like I was blue one moment and red the next, hard as ice before I melted into a hurricane. I was a mess for a year or two, I think, before I managed to get everything under control again. But even now, I\u0026rsquo;m not like I was. I\u0026rsquo;m still calm and rational and think before I speak, but if anything or anyone threatens our children or their happiness, I know I have to be the one to protect them.\nAnd as anyone who\u0026rsquo;s gone mountain climbing knows, the serene snow-covered peaks that look so tranquil from a distance are the deadliest.\nfrom https://commaful.com/play/aknier/the-mountain/\n","date":"2026-06-15T13:50:22+10:00","image":"/posts/mountain/index.png","permalink":"/posts/mountain/","title":"Mountain"},{"content":"Issues and Solutions Dual Boot With Windows As of Fedora 41, /etc/default/grub has been removed. Consequently, we cannot modify the default GRUB settings and generate the config file in the usual way. According to discussions on the Fedora Forum, we must modify the config files in /boot/grub2 directly.\nFor example, to set a longer timeout, add the following line to /boot/grub2/user.cfg:\nShow/Hide the code 1 set timeout=5 To add a Windows entry, add the following code to /boot/grub2/custom.cfg:\nShow/Hide the code 1 2 3 4 5 6 menuentry \u0026#39;Windows 11\u0026#39; { insmod part_gpt insmod fat search --no-floppy --fs-uuid --set=root EFI_UUID chainloader /EFI/Microsoft/Boot/bootmgfw.efi } Replace EFI_UUID with the actual UUID found using blkid.\nThe difference between these two files is the order of execution: user.cfg runs first, while custom.cfg runs last.\nChrome shows CJK characters as tofu Show/Hide the code 1 mv .cache/fontconfig .cache/fontconfig.save ","date":"2025-12-22T22:36:43+11:00","permalink":"/posts/a-trial-on-atomic-linux/","title":"A Trial on Atomic Linux"},{"content":"Histogram A very common tool for data exploration is histogram, which provides a clear visualization of the distribution of a dataset. It can be viewed as a discrete approximation of the underlying probability density function (PDF) of the data.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import numpy as np import matplotlib.pyplot as plt def histogram(data, bins): data = np.asarray(data) if isinstance(bins, int): bin_edges = np.linspace(data.min(), data.max(), bins + 1) else: bin_edges = np.asarray(bins) counts = np.zeros(len(bin_edges) - 1) for i in range(len(bin_edges) - 1): mask = (data \u0026gt;= bin_edges[i]) \u0026amp; (data \u0026lt; bin_edges[i + 1]) counts[i] = np.sum(mask) counts[-1] += np.sum(data == bin_edges[-1]) return counts, bin_edges Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 np.random.seed(42) data = np.concatenate([np.random.normal(-2, 0.6, 6), np.random.normal(3, 0.6, 6)]) counts, bin_edges = histogram(data, bins=30) plt.bar( bin_edges[:-1], counts, width=np.diff(bin_edges), alpha=0.5, align=\u0026#34;edge\u0026#34;, label=\u0026#34;Histogram\u0026#34;, ) plt.legend() plt.show() KDE Kernel Density Estimation (KDE), on the other hand, provides a smooth estimate of the PDF of the data.\nAccording to the definition of PDF, it is the derivative of the Cumulative Distribution Function (CDF) \\(F(x)\\):\n$$ f(x) = F'(x) = \\lim_{h \\to 0} \\frac{F(x+h) - F(x-h)}{2h} $$Here, \\(F(x+h)-F(x-h)\\) represents the probability that a random variable falls within the interval \\([x-h, x+h]\\), namely \\(P(x-h \\le X \\le x+h)\\). We can estimate this probability using the frequency. That is, we can count the number of data points that fall within this interval and divide it by the total number of data points \\(N\\):\n$$ P(x-h \\le X \\le x + h) \\approx \\frac{\\text{Count of points in } [x-h, x+h]}{N} $$Therefore, we can estimate the PDF as follows:\n$$ \\hat{f}(x) = \\lim_{h \\to 0} \\frac{1}{2Nh} \\cdot \\text{Count of points in } [x-h, x+h] $$To express the count function mathematically, we can define an indicator function:\n$$ I(u) = \\begin{cases} 1 \u0026 \\text{if } |u| \\le 1 \\\\ 0 \u0026 \\text{if } |u| \u003e 1 \\end{cases} $$Here, \\(u\\) is a normalized distance defined as \\(u = \\frac{x - x_i}{h}\\), where \\(x_i\\) represents each data point. When \\(|u| \u003c 1\\), \\(x_i\\) falls within the interval \\([x - h, x + h]\\) and \\(I(u) = 1\\); otherwise, \\(I(u) = 0\\). Thus, we can express the count of points in the interval as:\n$$ \\text{Count of points in } [x-h, x+h] = \\sum_{i=1}^{N} I\\left(\\frac{x - x_i}{h}\\right) $$Correspondingly, the estimated PDF becomes:\n$$ \\hat{f}(x) = \\frac{1}{N} \\sum_{i=1}^{N} \\frac{1}{2h} I\\left(\\frac{x - x_i}{h}\\right) $$ Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 def compute_kde(data, xvals, h, kernel): N = len(data) u = (xvals[:, None] - data[None, :]) / h kernels = kernel(u) density = np.sum(kernels, axis=1) / (N * h) scaled_kernels = kernels / (N * h) return density, scaled_kernels def uniform_kernel(u): return 0.5 * (np.abs(u) \u0026lt;= 1) h = 0.3 xvals = np.linspace(-5, 5, 500) yvals, component_curves = compute_kde(data, xvals, h, uniform_kernel) plt.figure(figsize=(10, 6)) plt.plot(xvals, yvals, color=\u0026#34;blue\u0026#34;, linewidth=3, label=\u0026#34;KDE Estimate\u0026#34;) plt.plot( data, np.zeros_like(data), \u0026#34;kx\u0026#34;, markersize=10, markeredgewidth=2, label=\u0026#34;Data Points $x_i$\u0026#34;, ) for i in range(len(data)): label = \u0026#34;Individual Kernels\u0026#34; if i == 0 else None plt.plot( xvals, component_curves[:, i], color=\u0026#34;red\u0026#34;, linestyle=\u0026#34;--\u0026#34;, alpha=0.5, linewidth=1, label=label, ) plt.xlabel(\u0026#34;x\u0026#34;) plt.ylabel(\u0026#34;Probability Density\u0026#34;) plt.legend() plt.grid(True, alpha=0.3) plt.tight_layout() plt.show() Instead of purely counting the points within the interval, which equates to using a uniform kernel, we can use other kernel functions to assign different weights to the points based on their distance from \\(x\\). For example, using a Gaussian kernel will produce a much smoother estimate:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 def gaussian_kernel(u): return (1 / np.sqrt(2 * np.pi)) * np.exp(-0.5 * u**2) yvals, component_curves = compute_kde(data, xvals, h, gaussian_kernel) plt.figure(figsize=(10, 6)) plt.plot(xvals, yvals, color=\u0026#34;blue\u0026#34;, linewidth=3, label=\u0026#34;KDE Estimate\u0026#34;) plt.plot( data, np.zeros_like(data), \u0026#34;kx\u0026#34;, markersize=10, markeredgewidth=2, label=\u0026#34;Data Points $x_i$\u0026#34;, ) for i in range(len(data)): label = \u0026#34;Individual Kernels\u0026#34; if i == 0 else None plt.plot( xvals, component_curves[:, i], color=\u0026#34;red\u0026#34;, linestyle=\u0026#34;--\u0026#34;, alpha=0.5, linewidth=1, label=label, ) plt.xlabel(\u0026#34;x\u0026#34;) plt.ylabel(\u0026#34;Probability Density\u0026#34;) plt.legend() plt.grid(True, alpha=0.3) plt.tight_layout() plt.show() Triangular Kernel:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 def triangular_kernel(u): return (1 - np.abs(u)) * (np.abs(u) \u0026lt;= 1) yvals, component_curves = compute_kde(data, xvals, h, triangular_kernel) plt.figure(figsize=(10, 6)) plt.plot(xvals, yvals, color=\u0026#34;blue\u0026#34;, linewidth=3, label=\u0026#34;KDE Estimate\u0026#34;) plt.plot( data, np.zeros_like(data), \u0026#34;kx\u0026#34;, markersize=10, markeredgewidth=2, label=\u0026#34;Data Points $x_i$\u0026#34;, ) for i in range(len(data)): label = \u0026#34;Individual Kernels\u0026#34; if i == 0 else None plt.plot( xvals, component_curves[:, i], color=\u0026#34;red\u0026#34;, linestyle=\u0026#34;--\u0026#34;, alpha=0.5, linewidth=1, label=label, ) plt.xlabel(\u0026#34;x\u0026#34;) plt.ylabel(\u0026#34;Probability Density\u0026#34;) plt.legend() plt.grid(True, alpha=0.3) plt.tight_layout() plt.show() Kernel Regression Moving from estimating the probability of \\(X\\) to estimating the expected value of a response variable \\(Y\\) given \\(X=x\\), we can apply a similar kernel-based approach known as kernel regression.\nAttention ","date":"2025-11-28T09:38:45Z","permalink":"/posts/from-histogram-to-attention/","title":"From Histogram to Attention"},{"content":"\u0026ldquo;Heuristic\u0026rdquo; 这个词在英文中有两个近似的含义, 根据 Oxford Dictionary 的定义, 第一个意思是: \u0026ldquo;Enabling a person to discover or learn something for themselves.\u0026rdquo; 这个意思对应于中文中的 \u0026ldquo;启发式\u0026rdquo; 主要用在教育的语境中, 例如 \u0026ldquo;启发式教学\u0026rdquo;, 这是一种教学方法, 强调在教学时教师引导学生主动学习而不只是被动地接受, 学生在老师的引导下自己发现要学习的知识.\n在这个意思之下还有另一个意思, 有 Computer 标签, 因此算是计算机领域的术语, 意思是: \u0026ldquo;proceeding to a solution by trial and error or by rules that are only loosely defined.\u0026rdquo; 这层意思强调的是一种解决问题的办法, 即尝试性地, 使用由经验总结而来的方法, 或是符合直觉但是没有经过严格证明的方法去解决问题, 他的同义词是 rule of thumb. 对于这层意思, 再翻译为 \u0026ldquo;启发性\u0026rdquo; 就不合适了. 尽管目前 \u0026ldquo;启发式\u0026rdquo; 这个翻译在各类由英文翻译而来的中文文献中很常见, 大家也都默认了它的新意思, 但是初次见到这个词的时候, 还是很难体会到它的实际意思. 在中文版 Oxford Dictionary 中, 对于这层意思的翻译是: 探索的, 试探的, 试验性的, 这个翻译无疑更好地反映了在这种语境下 heuristic 的真实意思.\n","date":"2025-11-04T21:52:32+11:00","permalink":"/posts/a-discussion-on-the-translation-of-heuristic/","title":"A Discussion on the Translation of Heuristic"},{"content":"The network discovery of remote speakers is enabled by default on Fedora, leading to a very long list in the output device setting. To disable this feature:\nShow/Hide the code 1 2 3 4 5 mkdir -p ~/.config/pipewire/pipewire.conf.d/ echo \u0026#34;context.properties = { module.raop = false }\u0026#34; \u0026gt; ~/.config/pipewire/pipewire.conf.d/noraop.conf systemctl --user restart pipewire Source: Fedora Discussion\n","date":"2025-11-04T15:39:12+11:00","permalink":"/posts/disable-network-discovery-of-speakers-on-fedora/","title":"Disable Network Discovery of Speakers on Fedora"},{"content":"Applications installed via Flatpak do not respect fontconfig settings stored in ~/.config/fontconfig/ by default. The solution is to copy the fontconfig directory to .var/app/\u0026lt;APP_ID\u0026gt;/config/, where \u0026lt;APP_ID\u0026gt; is the Flatpak application ID.\nFor example:\nShow/Hide the code 1 cp -r ~/.config/fontconfig ~/.var/app/com.example.App/config/ ","date":"2025-11-03T16:35:29+11:00","permalink":"/posts/fontconfig-in-flatpak/","title":"Fontconfig in Flatpak"},{"content":"Data Preparation The dataset contains information on the finals of the Australia Open over the years, with each row representing one match. The information includes year of the match, gender, champion\u0026rsquo;s name, champion\u0026rsquo;s nationality, score details, champion\u0026rsquo;s seed, runner-up\u0026rsquo;s name, runner-up\u0026rsquo;s nationality, and runner-up\u0026rsquo;s seed.\nFrom observing the match years, the following patterns can be found:\nAlthough in most years there is one men\u0026rsquo;s and one women\u0026rsquo;s match, the total number of men\u0026rsquo;s matches is 14 more than women\u0026rsquo;s. This is because, during the first 14 years (1905–1921), there is no information on women\u0026rsquo;s matches, possibly due to the tournament not including women\u0026rsquo;s events or due to missing data.\nIn 1977, there were two tournaments each for men and women, denoted as 1977-1 and 1977-2.\nFrom 1941 to 1945, 1916 to 1918, and in 1986, no matches were held for either gender.\nTherefore, during the 121-year period from 1905 to 2025, a total of 212 matches were held, comprising 113 men\u0026rsquo;s matches and 99 women\u0026rsquo;s matches. Although there should have been 242 matches (121 for each gender), there were 9 years without any tournaments, 14 years without women\u0026rsquo;s tournaments, and 1 year with two additional tournaments. Thus, the final count is $242 - 18 - 14 + 2 = 212$.\nAdditionally, from examining the nationality data of the players, it\u0026rsquo;s notable that one of the countries listed is Yugoslavia, which no longer exists. Also, the \u0026ldquo;Champion Country\u0026rdquo; column contains the full country name (e.g., Australia), while the \u0026ldquo;Champion Nationality\u0026rdquo; column contains the abbreviation (e.g., AUS), making this a redundant field. In the seed information, some players have blank seeds, while others have a \u0026ldquo;U\u0026rdquo;, which likely stands for \u0026ldquo;unseeded\u0026rdquo;; blanks are likely missing data and should be excluded in visual analysis. The \u0026ldquo;Mins\u0026rdquo; column records match duration, but except for the most recent four matches, all values are missing, making this column unhelpful for analysis.\nIn summary, in most years, two matches (one men\u0026rsquo;s and one women\u0026rsquo;s) were held annually, but there were some years without any matches, and some years with only men\u0026rsquo;s matches. One of the countries in the dataset no longer exists. Some players have missing seed information. The \u0026ldquo;Country\u0026rdquo; and \u0026ldquo;Nationality\u0026rdquo; columns are redundant, and the \u0026ldquo;Mins\u0026rdquo; column is mostly empty. Based on these observations, the following preprocessing steps are performed:\nStandardize 1977-1 and 1977-2 to simply 1977, to allow proper date parsing.\nRemove the \u0026ldquo;Nationality\u0026rdquo; columns, as they duplicate \u0026ldquo;Country\u0026rdquo;.\nRemove the \u0026ldquo;Mins\u0026rdquo; column, since it\u0026rsquo;s nearly all missing.\nThe current format of the dataset is not ideal for certain types of data analysis. For example, if we want to count how many times a particular player appeared in the finals, we would need to separately count the number of times the player appears in the Champion column and the Runner-up column, then sum the two. Similarly, some visualizations become difficult to produce \u0026ndash; for instance, analyzing the seeding history of a specific player requires navigating multiple columns.\nTo address this, we restructured the data by merging several columns into unified fields. For example:\nThe Champion and Runner-up columns were combined into a single column called Player, with a new column Role added to indicate whether the player was the Champion or Runner-up.\nThe Champion Country and Runner-up Country fields were merged into one Country column.\nSimilarly, seeding information was unified into a single Seed column.\nAdditionally, new fields can be generated through calculation and combination:\nNumber of Sets Played per Match: According to tennis rules, men\u0026rsquo;s matches are best-of-five (maximum 5 sets), while women\u0026rsquo;s matches are best-of-three (maximum 3 sets). In Excel, this can be calculated by checking whether certain fields are empty. For example, if the 4th set is empty, it means the match ended in 3 sets. If the 5th set is empty, it means the match lasted 4 sets. Otherwise, the match went to 5 sets.\nTime Span Between First and Last Championship: For a given player, the time interval between their first and last championship can be calculated using the MAXIFS and MINIFS functions in Excel. The data range would be the \u0026ldquo;Year\u0026rdquo; column, the criteria range would be the \u0026ldquo;Player\u0026rdquo; column, and the criteria would be the current player\u0026rsquo;s name.\nWinning Rate: A player\u0026rsquo;s winning rate can be calculated as the number of championships won divided by the number of times they reached the final. In Excel, this can be done using the COUNTIFS function.\nGlobal Trends The figure below shows the global distribution of player nationalities. Clearly, Australia has dominated the tournament, with 45% of finalists coming from Australia. The next most prominent country is the USA, ranking second with 18%. Additionally, a significant portion of players come from various European countries\u0026ndash;for example, 4% from the UK, around 3% from Spain, and about 2.6% from Sweden. There is also some representation from Asia, South America, and Africa, though very limited, with most accounting for less than 1%. Notably, South Africa is the only African country with players reaching the final.\nThe next figure shows the countries with the most \u0026ldquo;champion\u0026rdquo; titles. The trend mirrors that of finalist nationalities: Australia ranks first, followed by the USA, and both far outpace other countries in terms of total titles. Among the rest, the UK, Switzerland, Germany, and Serbia stand out.\nThe next chart shows how the number of championships per country has changed over time. Clearly, Australia dominated the early years: from 1906 to 1978, 120 matches were held (men\u0026rsquo;s and women\u0026rsquo;s combined), and Australia won 93 of them\u0026ndash;averaging 1.2 championships per year. The US and UK also had some growth during this time, but at a much slower rate\u0026ndash;for example, the UK won only 8 championships during this period, averaging one every 9.2 years. However, since 1978, this trend has dramatically shifted. Although Australia still leads in total championships, it has not added any since 1978. Meanwhile, other countries like the USA and Serbia have been steadily increasing their counts. Especially the USA: from 15 titles in 1978 to 43 in 2021\u0026ndash;an average of one title per year. Other countries have also emerged in this era, albeit at a slower pace, unlike the pre-1978 period where they barely appeared.\nCombining insights from the world map and the time trend chart, we can conclude that although Australia dominates in total titles, most of this comes from pre-1978 years. After that, its performance plateaued, while countries like the USA and some European nations began to rise, especially the USA, which has seen a sharp increase in championships in recent decades.\nCountry-Level Analysis The following chart shows the gender distribution of finalists from countries that have reached the final more than five times. Australia, which ranks first, has a stronger presence in men\u0026rsquo;s matches\u0026ndash;55% of its players are male. In contrast, the USA performs better in women\u0026rsquo;s matches, with over 60% of its players being female. Moreover, Sweden and New Zealand are male dominated, with 11 and 6 male finalists respectively. Conversely, Belarus and Belgium have 5 and 4 female finalists respectively, and no male finalists. Other countries have both male and female finalists, but with varying gender trends\u0026ndash;some are more female-dominant while others lean male.\nThe next chart displays the distribution of championships among players from Australia, the USA, and the UK\u0026ndash;the top three countries by total titles. From this chart, it is evident that both Australia and the USA have had exceptionally dominant players: Margaret Court (11 titles) for Australia, and Serena Williams (7 titles) for the USA\u0026ndash;both women. That said, most championships were won by a large number of other players. For instance, in Australia, players with five or fewer titles collectively account for around 70 championships\u0026ndash;over 70% of its total. For the USA, this proportion rises to 84%. In contrast, all UK champions have only won once each, making its 100% contribution from single-title winners.\nThe chart below shows smaller countries with fewer championships. In these cases, no more than three players per country have won a title. The most striking example is Serbia, which ranks second in this chart by championship count: all 10 of its titles were won by a single player\u0026ndash;Novak Djokovic (who, as will be shown in later analysis, also has the highest win rate among top players and is second in total championships).\nPlayer-Level Analysis The chart below shows all players who have won the championship (those who never won in the finals are not included). The font size of the names reflects the number of championships won, while the color indicates the player\u0026rsquo;s country. The most eye-catching names are Margaret Court, Novak Djokovic, Roger Federer, and Serena Williams, who have won the most championships and come from Australia, Serbia, Switzerland, and the United States respectively. Additionally, it\u0026rsquo;s noticeable that blue dominates the chart\u0026ndash;this is because most champions come from Australia. There are also many names in red, but with smaller font sizes, indicating that while many American players have won championships, most of them only won once or twice.\nTop Players The chart below displays players who have won five or more championships, along with their win rates. The bars represent the number of championships won by each player, with different colors indicating their country, while the orange line shows their win rate. Margaret Court stands out with the highest number of championships (11), and both Novak Djokovic and Daphne Akhurst boast a perfect 100%-win rate. Overall, each top player has a high participation and win rate \u0026ndash; six of them have win rates over 80%, and one has 75%.\nThe scatter plot below compares the number of championships and runner-up finishes for each player. The horizontal axis shows championship wins, while the vertical axis shows runner-up finishes. The opacity of each dot reflects the number of players (lower opacity indicates fewer players). Players closer to the horizontal axis won more often than they lost in the finals, while those closer to the vertical axis were more likely to lose in the finals. Most players cluster near the origin, indicating that the majority have relatively few appearances in the finals.\nThe chart below compares the active years of the seven top players (those with five or more championships). From this, we see that the earliest top player was Daphne Akhurst from Australia, who won five championships over a six-year period from 1925 to 1930. Another Australian, Nancye Wynne Bolton, reached her first final in 1936 and continued until 1951, winning six titles and finishing as runner-up twice. Roy Emerson and Margaret Court were active in a similar period, with the latter winning a record 11 championships and finishing runner-up once. Starting from 1973, there was a lull\u0026ndash;top players who could dominate the competition were largely absent until 2003, when Serena Williams (USA), Novak Djokovic (Serbia), and Roger Federer (Switzerland) set up a new era, ending Australia\u0026rsquo;s dominance. Notably, Novak Djokovic won 10 championships between 2008 and 2023, making him the player with the second-highest number of titles and the second-longest active span between first and last win.\nThe chart below highlights the five players with the longest active spans. All of them are top players except for Ken Rosewall. His final championship win in 1972 came a full 19 years after his first in 1953. He played in five finals and won four of them. Interestingly, after finishing as runner-up in 1956, he didn\u0026rsquo;t appear in another final for 15 years, returning to win again in 1971.\nSeed Analysis Definition of Seed: A \u0026ldquo;seeded player\u0026rdquo; refers to a competitor who, based on global ranking or recent performance, is specially designated and arranged in the tournament bracket. Seeds are usually assigned by the organizers based on authoritative rankings. The chart below displays the seed distribution of players who won championships. Clearly, the most frequent winners were top seeds (seed 1), who are expected to be the most likely champions. This is followed by seeds 2 through 7, with decreasing frequencies.\nThe next chart shows the seed distribution for runners-up. Seed 2 appears most frequently here, indicating that seedings were fairly accurate\u0026ndash;those ranked second most often ended up as runners-up. This is followed by seeds 1 and 3. Unlike the champion seed chart, the fourth-largest group is the unseeded players, with 15 runners-up, making up 7% of all.\nIt is worth to take a closer look at when those unseeded players reached the finals. From the chart, it\u0026rsquo;s clear that before the 1970s, only three unseeded Australian players ever reached the final\u0026ndash;and none of them won. For a long period after that, both championship and runner-up spots were dominated by seeded players (as shown earlier, many titles during that era were won by Australian top players). After the 1970s, the number of unseeded finalists rose significantly, and their nationalities became more diverse\u0026ndash;not only from Australia but also from the UK, the US, and various other countries. However, most of them ended up as runners-up. Only two Australian players and one American\u0026ndash;Serena Williams\u0026ndash;won a title as unseeded players (surprisingly, Serena Williams is one of the top players).\nMatch Analysis The chart below shows that 40% of men\u0026rsquo;s matches were decided in just three sets, meaning one side won all three consecutively. Only 20% of matches went to the full five sets, indicating very close contests. Women\u0026rsquo;s matches show a similar trend\u0026ndash;since women play best-of-three sets, 66% of matches were decided in the first two, suggesting that one player won both straight sets.\nConclusion This report begins with an analysis of the original dataset, revealing several patterns\u0026ndash;for instance, inconsistencies in the number of men\u0026rsquo;s and women\u0026rsquo;s matches, some years without tournaments, and one year in which the tournament was held twice. Additionally, the status of each attribute in the dataset was examined, uncovering anomalies such as the \u0026ldquo;Mins\u0026rdquo; column being almost entirely empty, missing values in the \u0026ldquo;Seed\u0026rdquo; column, inconsistent formatting in the \u0026ldquo;Year\u0026rdquo; column, and data redundancy in certain fields. To facilitate subsequent analysis, some columns were merged, and new columns\u0026ndash;such as win rate and whether the player won the championship\u0026ndash;were added.\nIn the visualization analysis, the country-wise statistics showed that Australia has won the most championships, followed by the United States. A deeper look revealed that Australia held a dominant position before 1978, while post-1978, the U.S. and several European countries became more prominent, with Australia rarely winning titles after that. An analysis of gender performance in major countries found that Australia performed better in men\u0026rsquo;s matches, whereas the U.S. excelled in women\u0026rsquo;s matches. Additionally, a few countries were identified where all participating players were either male or female.\nAn analysis of different players from the same country showed that for Australia, the U.S., and the U.K., championships were mostly won by a large number of players with only one or two titles. In contrast, countries like Serbia had all their titles won by a single player. The player-level analysis identified several top-performing players whose performances were examined in detail. These players were found to have high win rates. There were also clear generational patterns: the four top Australian players were active before 1972, with no prominent Australian players afterward, while top players from other countries began winning titles frequently after 2003. One player was found to have the longest gap between first and last championship wins\u0026ndash;19 years.\nThe analysis of seeded players concluded that the seeding system for this tournament is relatively reasonable, as the top seed frequently wins the championship. It was also noted that it wasn\u0026rsquo;t until the 1970s that unseeded players began appearing frequently in finals. Lastly, match length analysis revealed that most matches ended within two or three sets.\n","date":"2025-10-24T01:16:26+11:00","image":"/posts/a-visual-analysis-of-australia-open/image-1.png","permalink":"/posts/a-visual-analysis-of-australia-open/","title":"A Visual Analysis of Australia Open"},{"content":"Plasma introduced a quick settings panel in plasma 6, where you can toggle between Breeze and Breeze Dark themes. However, it will change the entire theme, ruining customizations like icons. You can toggle the color scheme manually by using the following command:\nFor dark theme:\nShow/Hide the code 1 plasma-apply-desktoptheme breeze-dark \u0026amp;\u0026amp; plasma-apply-colorscheme BreezeDark \u0026amp;\u0026amp; plasma-apply-cursortheme Breeze_Light \u0026amp;\u0026amp; /usr/lib/plasma-changeicons Papirus-Dark \u0026amp;\u0026amp; /usr/bin/sed -i \u0026#39;s/DefaultProfile=Light.profile/DefaultProfile=Dark.profile/\u0026#39; ~/.config/konsolerc For light theme:\nShow/Hide the code 1 plasma-apply-desktoptheme breeze \u0026amp;\u0026amp; plasma-apply-colorscheme Breeze \u0026amp;\u0026amp; plasma-apply-cursortheme Breeze_Dark \u0026amp;\u0026amp; /usr/lib/plasma-changeicons Papirus-Light \u0026amp;\u0026amp; /usr/bin/sed -i \u0026#39;s/DefaultProfile=Dark.profile/DefaultProfile=Light.profile/\u0026#39; ~/.config/konsolerc Before running the commands, ensure you have the Papirus icon theme installed and Light and Dark konsole profiles created. It will change the desktop theme, color scheme, cursor theme, icon theme, and konsole profile. Moreover, you can create two scripts and bind them to keyboard shortcuts for easy toggling.\n24/10/25 Update\nPlasma 6.5 was released, introducing a new feature to automatically switch between light and dark themes based on the time of day. However, it does not support custom icon themes and konsole profiles. A workaround is to run a script that monitors the theme change event and applies the necessary changes.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 #!/bin/bash # Monitor KDE theme changes and execute commands # Function to check current color scheme check_theme() { # Query KDE\u0026#39;s color scheme setting (KF6 uses kreadconfig6) theme=$(kreadconfig6 --file kdeglobals --group General --key ColorScheme) # Check if it\u0026#39;s a dark theme (common dark themes contain \u0026#34;Dark\u0026#34; in name) if [[ $theme == *\u0026#34;Dark\u0026#34;* ]] || [[ $theme == *\u0026#34;Breeze Dark\u0026#34;* ]]; then echo \u0026#34;dark\u0026#34; else echo \u0026#34;light\u0026#34; fi } # Get initial state previous_theme=$(check_theme) echo \u0026#34;Current theme: $previous_theme\u0026#34; # Monitor D-Bus for KDE settings changes dbus-monitor --session \u0026#34;type=\u0026#39;signal\u0026#39;,interface=\u0026#39;org.kde.KGlobalSettings\u0026#39;,member=\u0026#39;notifyChange\u0026#39;\u0026#34; | \\ while read -r line; do # When we detect a change notification if [[ $line == *\u0026#34;notifyChange\u0026#34;* ]]; then sleep 0.5 # Small delay to ensure settings are written current_theme=$(check_theme) # Only act if theme actually changed if [[ $current_theme != $previous_theme ]]; then echo \u0026#34;Theme changed: $previous_theme -\u0026gt; $current_theme\u0026#34; if [[ $current_theme == \u0026#34;dark\u0026#34; ]]; then echo \u0026#34;Executing dark theme commands...\u0026#34; # Add your dark theme commands here notify-send \u0026#34;Dark Mode\u0026#34; \u0026#34;Switched to dark theme\u0026#34; /usr/lib/plasma-changeicons Papirus-Dark \u0026amp;\u0026amp; /usr/bin/sed -i \u0026#39;s/DefaultProfile=Light.profile/DefaultProfile=Dark.profile/\u0026#39; ~/.config/konsolerc elif [[ $current_theme == \u0026#34;light\u0026#34; ]]; then echo \u0026#34;Executing light theme commands...\u0026#34; # Add your light theme commands here notify-send \u0026#34;Light Mode\u0026#34; \u0026#34;Switched to light theme\u0026#34; /usr/lib/plasma-changeicons Papirus-Light \u0026amp;\u0026amp; /usr/bin/sed -i \u0026#39;s/DefaultProfile=Dark.profile/DefaultProfile=Light.profile/\u0026#39; ~/.config/konsolerc fi previous_theme=$current_theme fi fi done A user-level systemd service can be created to run this script in the background:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 [Unit] Description=KDE Theme Monitor After=graphical-session.target [Service] Type=simple ExecStart=/home/username/.local/bin/theme-monitor.sh Restart=on-failure [Install] WantedBy=default.target And the commands to enable and start the service:\nShow/Hide the code 1 2 systemctl --user enable theme-monitor.service systemctl --user start theme-monitor.service Even though this solution works, it\u0026rsquo;s quite hacky and heavy. Hoping for a better built-in feature in the future Plasma releases.\n","date":"2025-10-12T12:07:36+11:00","permalink":"/posts/toggle-color-theme-on-plasma/","title":"Toggle Color Theme on Plasma"},{"content":"Introduction Support Vector Machine (SVM), invented by Vladimir Vapnik in 1979, is a kind of machine learning algorithm with solid theoretical foundation (Platt, 1998). The classical implementation of SVM is to find the optimal separating hyperplane by solving a convex quadratic programming problem. Furthermore, by solving its Lagrangian dual problem, kernel methods can be naturally introduced, enabling SVM to handle not only linear classification problems but also complex non-linear ones. This approach primarily uses optimization theory as a tool and can theoretically find an exact analytical solution using Quadratic Programming (QP) solvers. In practice, however, numerical approaches like Sequential Minimal Optimization (SMO) is often employed instead of general QP solvers for better efficiency.\nIn addition to this perspective, SVM can also be understood from the general machine learning perspective, that is, optimizing a loss function to fit the data. This method typically employs stochastic gradient descent as a tool, gradually approaching the minimum of the loss function by calculating its gradient. The advantage of this method is its simplicity in implementation and lower computational cost, but it usually can only find an approximate solution and cannot utilize kernel methods. The essence of these two methods is the same, just using different viewpoints.\nThis report will first introduce the linear classification problem and the perceptron algorithm, which is background knowledge and motivation for SVM. Then, the hard margin maximum margin classifier will be introduced in detail, including its primal and lagrange dual form, and an implementation using a QP solver will be provided. The soft margin maximum margin classifier will be presented as an extension to handle noisy and non-linearly separable data. Two implementations of the soft margin classifier will be provided: one using SMO and the other using stochastic gradient descent. These implementations will be compared on both artificial and real-world datasets. Finally, multi-class classification will be discussed, along with a reflection and conclusion of the report.\nLinks GitHub Repository Colab Notebook Background Linear Classification SVM is a solution to the linear classification problem. Linear classification refers to the task of classifying data points into different categories based on a linear decision boundary. If the input space \\(X\\) is a subset of \\(\\mathbb{R}^n\\), where \\(n\\ge1\\) is the number of features in the dataset, a linear decision boundary can be defined as a flat affine subspace of dimension \\(n-1\\). For example, in a 2-dimensional space, the decision boundary is a line, while in a 3-dimensional space, it is a plane. In higher-dimensional spaces, it is referred to as a hyperplane.\nA hyperplane can be defined by the equation:\n$$ \\mathbf{w} \\cdot \\mathbf{x} + b = 0 $$If a point \\(\\mathbf{x}_0\\) does not lie on the hyperplane, it must either satisfy\n$$ \\mathbf{w} \\cdot \\mathbf{x}_0 + b \u003e 0 $$or\n$$ \\mathbf{w} \\cdot \\mathbf{x}_0 + b \u003c 0 $$The side that the point lies on can be determined by its sign:\n$$ sign(\\mathbf{w} \\cdot \\mathbf{x}_0 + b) $$The learning task of linear classification is to find a hyperplane that separates the data points into two classes correctly, providing the dataset is linearly separable. Therefore, the hypothesis set \\(H\\) for linear classification can be defined as the set of all possible hyperplanes in the input space \\(X\\).\nPerceptron Perhaps the simplest algorithm for finding a hyperplane is the Perceptron Learning Algorithm (PLA). The PLA iteratively updates the parameters \\(\\mathbf{w}\\) and \\(b\\) of the hyperplane based on the misclassified data points. It has been proven that as long as the data is linearly separable, the perceptron algorithm is guaranteed to converge.\nLet the class label be denoted by \\(y\\), where \\(y = 1\\) for the positive class and \\(y = -1\\) for the negative class. The product\n$$ y (\\mathbf{w} \\cdot \\mathbf{x} + b) $$indicates the correctness of the prediction: a positive value implies a correct prediction, while a negative value indicates a misclassification.\nPerceptron learns from misclassifications. When a data point is correctly classified, the algorithm proceeds to the next data point without updating the model, whereas when a data point is misclassified, the model parameters are updated according to the following rules:\n$$ \\begin{aligned} \u0026\\mathbf{w} \\leftarrow \\mathbf{w} + lr \\cdot y \\cdot \\mathbf{x} \\nonumber \\\\ \u0026b \\leftarrow b + lr \\cdot y \\nonumber \\end{aligned} $$where \\(lr\\) is the learning rate that pre-defined as a hyperparameter.\nThis update mechanism implies that if the true label is positive and the data point is misclassified, the normal vector \\(\\mathbf{w}\\) of the hyperplane is adjusted in the direction of \\(\\mathbf{x}\\), thereby increasing the likelihood of correctly classifying \\(\\mathbf{x}\\) as a positive instance. Conversely, if the true label is negative, the vector \\(\\mathbf{w}\\) is updated in the opposite direction of \\(\\mathbf{x}\\), making it more likely that \\(\\mathbf{x}\\) will be classified as negative.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class MyPerceptron: def __init__(self, lr=0.1, epochs=10, history=False): self.lr = lr self.epochs = epochs self.history = history self.losses = [] self.records = [] def f(self, x): return x @ self.w + self.b def sign(self, x): return np.where(x \u0026gt; 0, 1, -1) def predict(self, x): return self.sign(self.f(x)) def record(self, w, b, current_loss, i): self.records.append([(w, self.w.copy()), (b, self.b), current_loss, i]) def fit(self, X, y): _, n_features = X.shape self.w = np.zeros(n_features) self.b = 0 for _ in range(self.epochs): for i, (xi, yi) in enumerate(zip(X, y)): y_hat = self.predict(xi) old_w = self.w.copy() old_b = self.b if self.history: current_loss = (self.sign(self.f(X)) != y).mean() if self.history and current_loss == 0: self.record(old_w, old_b, current_loss, i) return if yi * y_hat \u0026lt; 0: self.w += self.lr * yi * xi self.b += self.lr * yi if self.history: self.record(old_w, old_b, current_loss, i) Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def plot_records(X, y, records, show_legend=True, show_previous=True, figsize=(15, 15)): n_updates = len(records) cols = 3 rows = int(np.ceil(n_updates / cols)) _, axs = plt.subplots(rows, cols, figsize=figsize) axs = axs.flatten() if n_updates \u0026gt; 1 else [axs] x_margin = 2.0 y_margin = 2.0 x_min = np.min(X[:, 0]) - x_margin x_max = np.max(X[:, 0]) + x_margin y_min = np.min(X[:, 1]) - y_margin y_max = np.max(X[:, 1]) + y_margin for i in range(n_updates): ax = axs[i] old_w, new_w = records[i][0] old_b, new_b = records[i][1] pos_idx = y == 1 neg_idx = y == -1 ax.scatter( X[pos_idx, 0], X[pos_idx, 1], color=\u0026#34;blue\u0026#34;, alpha=0.6, marker=\u0026#34;+\u0026#34;, ) ax.scatter( X[neg_idx, 0], X[neg_idx, 1], color=\u0026#34;red\u0026#34;, alpha=0.6, ) ax.scatter( X[records[i][3], 0], X[records[i][3], 1], facecolor=\u0026#34;yellow\u0026#34;, edgecolor=\u0026#34;black\u0026#34;, label=\u0026#34;Current Point\u0026#34;, ) def plot_hp(w, b, color, linestyle, label): x_vals = np.linspace(x_min, x_max, 100) if abs(w[1]) \u0026gt; 1e-6: y_vals = (-w[0] * x_vals - b) / w[1] ax.plot( x_vals, y_vals, color=color, linestyle=linestyle, label=label, ) else: x_val = -b / w[0] if abs(w[0]) \u0026gt; 1e-6 else 0 ax.axvline(x_val, color=color, linestyle=linestyle, label=label) return x_vals, y_vals if abs(w[1]) \u0026gt; 1e-6 else None plot_hp(new_w, new_b, \u0026#34;black\u0026#34;, \u0026#34;-\u0026#34;, \u0026#34;After Update\u0026#34;) if show_previous: plot_hp(old_w, old_b, \u0026#34;green\u0026#34;, \u0026#34;--\u0026#34;, \u0026#34;Before Update\u0026#34;) x0 = 0 y0 = (-old_w[0] * x0 - old_b) / old_w[1] if old_w[1] != 0 else 0 norm = np.linalg.norm(old_w) if norm != 0: ax.arrow( x0, y0, old_w[0] / norm, old_w[1] / norm, head_width=0.5, width=0.1, color=\u0026#34;green\u0026#34;, ) x0 = 0 y0 = (-new_w[0] * x0 - new_b) / new_w[1] if new_w[1] != 0 else 0 norm = np.linalg.norm(new_w) if norm != 0: ax.arrow( x0, y0, new_w[0] / norm, new_w[1] / norm, head_width=0.5, width=0.1, color=\u0026#34;black\u0026#34;, ) ax.set_xlim(x_min, x_max) ax.set_ylim(y_min, y_max) ax.set_title(f\u0026#34;Update {i+1}\u0026#34;) ax.set_aspect(\u0026#34;equal\u0026#34;) if show_legend: ax.legend() for j in range(n_updates, len(axs)): axs[j].axis(\u0026#34;off\u0026#34;) plt.tight_layout() plt.show() The figure below shows the learning process of a perceptron on a synthetic dataset. The green arrow represents the normal vector before the update, while the black arrow shows the normal vector after the update. For example, in Update 6, when a positive sample (the yellow point) lies on negative side of the hyperplane, the green arrow shifts closer to this data point after the update and thereby the updated hyperplane classifies this point correctly.\nShow/Hide the code 1 2 3 perceptron = MyPerceptron(lr=0.1, epochs=2, history=True) perceptron.fit(X_dummy, y_dummy) plot_records(X_dummy, y_dummy, perceptron.records[:-1], figsize=(11, 8)) Perceptron Learning Process It is clear that after six updates the hyperplane that the perceptron found has separated all data points correctly, but is it the best one? Actually, it is almost the worst, since it is very close to one side. Intuitively, the optimal hyperplane should look like the one below, which maximizes the distance to the nearest data points from both classes. Therefore, the model has a bigger cushion to tolerate noise and outliers. This is the main idea and motivation of SVMs.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 plt.figure(figsize=(3, 3)) plt.scatter(d1[0:, 0], d1[0:, 1], color=\u0026#34;blue\u0026#34;, marker=\u0026#34;+\u0026#34;) plt.scatter(d2[0:, 0], d2[0:, 1], color=\u0026#34;red\u0026#34;, marker=\u0026#34;o\u0026#34;) plt.plot( np.linspace(-2, 6, 10), -np.linspace(-2, 6, 10) + 4.1, color=\u0026#34;black\u0026#34;, ) plt.gca().set_aspect(\u0026#34;equal\u0026#34;) plt.show() The Optimal Hyperplane Furthermore, the hyperplane found by the perceptron is not unique. Different initializations of the model parameters or variations in the order of data presentation can lead to different hyperplanes (Bishop, 2006). The following figure illustrates six different hyperplanes obtained by perceptron with different shuffles of the training data. Obviously, they vary significantly.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 params = [] for i in range(6): idx = np.random.permutation(len(X_dummy)) X_shuffled = X_dummy[idx] y_shuffled = y_dummy[idx] perceptron = MyPerceptron(lr=1, epochs=5, history=True) perceptron.fit(X_shuffled, y_shuffled) params.append(perceptron.records[-1]) plot_records( X_shuffled, y_shuffled, params, show_legend=False, show_previous=False, figsize=(10, 7), ) Different Final Hyperplane With Different Data Order Maximum Margin Classifier With Hard Margin Maximum Margin Classifier is a solution to the problems of perceptron mentioned above. Unlike Perceptron, Maximum Margin Classifier is able to find the optimal decision boundary by maximizing its margin. Margin is defined to be the smallest distance between the decision boundary and any of the samples (Bishop, 2006).\nFunctional Distance and Geometric Distance The distance from a point \\(\\mathbf{x}_0\\) to a hyperplane \\(h\\) can be calculated by substituting \\(\\mathbf{x}\\) into the equation of the hyperplane:\n$$ distance(x_0,h)=|\\mathbf{w}\\cdot\\mathbf{x}_0 + b| $$if the hyperplane correctly classifies the point, the distance can also be expressed as:\n$$ distance(x_0,h)=y_0(\\mathbf{w}\\cdot\\mathbf{x}_0 + b) $$where \\(y_0\\) is the class label of \\(\\mathbf{x}_0\\). This is called the functional distance.\nIn addition, this value can by manipulated arbitrarily. For example,\n$$ \\mathbf{w}\\cdot\\mathbf{x} + b = 0 \\quad \\text{and} \\quad 2\\mathbf{w}\\cdot\\mathbf{x} + 2b = 0 $$represent the same hyperplane, but for the same input \\(x\\), they yield different values. In fact, the latter is exactly twice the former. Therefore, we can pick a particular scalar to rescale the hyperplane, making it yield preferred output. We choose the scalar to be \\(1/\\rho\\), where\n$$ \\rho = \\min\\limits_{i=1,\\cdots,n}{y_i(\\mathbf{w}\\cdot\\mathbf{x}_i+b)} $$so that:\n$$ \\min\\limits_{i=1,\\cdots,n}{y_i(\\frac{\\mathbf{w}}{\\rho}\\cdot\\mathbf{x}_i+\\frac{b}{\\rho})}=\\frac{1}{\\rho}\\min\\limits_{i=1,\\cdots,n}{y_i(\\mathbf{w}\\cdot\\mathbf{x}_i+b)=\\frac{\\rho}{\\rho}=1} $$Therefore, for any hyperplane, we can always rescale it to make the functional distance of the closest data points equal to 1.\nFurthermore, the geometric distance from a point \\(\\mathbf{x}_0\\) to the hyperplane \\(h_0\\) can be calculated as:\n$$ \\frac{y_0(\\mathbf{w} \\cdot \\mathbf{x}_0 + b)}{\\|\\mathbf{w}\\|} $$In other words, it is the functional distance divided by the norm of the normal vector \\(\\mathbf{w}\\). Geometric distance is also called Euclidean distance, which is invariant to the rescaling of the hyperplane.\nThe margin of a hyperplane is defined as the geometric distance from the hyperplane to the closest data points. The optimal hyperplane is the one that maximizes the margin. Since the hyperplane is determined by \\(\\mathbf{w}\\) and \\(b\\), the optimization problem can be formulated as follows:\n$$ \\arg\\max\\limits_{\\mathbf{w},b}{\\left\\{\\frac{1}{\\|\\mathbf{w}\\|}\\min\\limits_{i=1,\\cdots,n}{\\left[y_i(\\mathbf{w} \\cdot \\mathbf{x}_i + b)\\right]}\\right\\}} $$Since we can always rescale the hyperplane so that\n$$ \\min\\limits_{i=1,\\cdots,n}y_i(\\mathbf{w} \\cdot \\mathbf{x}_i + b)=1 $$Thus, the optimization problem can be rewritten in a simpler form:\n$$ \\begin{aligned} \\arg\\min\\limits_{\\mathbf{w},b}\\quad\u0026 \\frac{1}{2}||\\mathbf{w}||^2 \\nonumber \\\\ s.t. \\quad \u00261-y_i(\\mathbf{w}\\cdot\\mathbf{x}_i+b)\\le0, i=1, \\cdots, n \\nonumber \\end{aligned} $$Here, the coefficient \\(\\frac{1}{2}\\) is introduced to simplify the result after differentiation.\nPrimal Problem The lagrange function of this optimization problem is:\n$$ L(\\mathbf{w}, b, \\alpha)=\\frac{1}{2}||\\mathbf{w}||^2+\\sum_{i=1}^{n}{\\alpha_i\\left[1-y_i (\\mathbf{w} \\cdot \\mathbf{x}_i + b)\\right]} $$where \\(\\alpha_i\\ge0\\) are the lagrange multipliers.\nIf we maximize \\(L\\) w.r.t. \\(\\alpha\\):\n$$ \\begin{aligned} \\theta(\\mathbf{w}, b) \u0026= \\max_{\\alpha \\ge 0} L(\\mathbf{w}, b, \\alpha) \\\\ \u0026= \\max_{\\alpha \\ge 0} \\frac{1}{2}\\|\\mathbf{w}\\|^2 + \\sum_{i=1}^{n} \\alpha_i \\bigl[1 - y_i (\\mathbf{w} \\cdot \\mathbf{x}_i + b)\\bigr] \\nonumber \\end{aligned} $$It turns out that if there is an \\(\\mathbf{x}_i\\) that satisfies\n$$ 1-y_i (\\mathbf{w} \\cdot \\mathbf{x}_i + b) \u003e 0 $$which violates the constraint, \\(L\\) will go to \\(+\\infty\\), by making \\(\\alpha = +\\infty\\), whereas if all \\(\\mathbf{x}_i\\) satisfy the constraint, the maximum value of \\(L\\) would be \\(\\frac{1}{2}||\\mathbf{w}||^2\\) because we have to make all \\(\\alpha_i=0\\) to avoid negative value.\nTherefore, \\(\\theta(\\mathbf{w}, b)\\) is actually defined by:\n$$ \\theta(\\mathbf{w}, b) = \\left\\{ \\begin{array}{lr} \\frac{1}{2}||\\mathbf{w}||^2 \u0026 \\text{if constraints are satisfied} \\\\ +\\infty \u0026 \\text{otherwise} \\end{array} \\right. $$Minimize function \\(\\theta(\\mathbf{w}, b)\\) w.r.t. \\(\\mathbf{w}\\) and \\(b\\):\n$$ \\min\\limits_{\\mathbf{w}, b}{\\theta(\\mathbf{w}, b)}=\\min\\limits_{\\mathbf{w}, b}{\\max\\limits_{\\alpha:\\alpha_i\\ge0}{L(\\mathbf{w}, b, \\alpha)}} $$is equivalent to the original optimization problem and it\u0026rsquo;s called the primal problem.\nDual Problem If we instead minimize \\(L\\) w.r.t. \\(\\mathbf{w}\\) and \\(b\\) first and then maximize it w.r.t. \\(\\alpha\\), it yields the dual problem:\n$$ \\max\\limits_{\\alpha:\\alpha_i\\ge0}{\\min\\limits_{\\mathbf{w}, b}{L(\\mathbf{w}, b, \\alpha)}} $$There are several advantages of solving the dual problem instead of the primal one. First, the dual problem is always a convex optimization problem by nature (this is because the target function is linear w.r.t. \\(\\alpha\\) and the constraint sets are always convex sets), whereas the primal problem may not be convex, though in this case it is. Nevertheless, it\u0026rsquo;s still a good practice to solve the dual problem, because it is usually simpler to solve than the primal one. It has been proven that for SVMs, solving the dual problem is equivalent to solving the primal one.\nTo solve the dual problem, first set the derivatives of \\(L\\) w.r.t. \\(\\mathbf{w}\\) and \\(b\\) to zero:\n$$ \\begin{aligned} \\nabla_\\mathbf{w}L(\\mathbf{w}, b, \\alpha)\u0026=\\mathbf{w}-\\sum_{i=1}^{n}{\\alpha_i y_i \\mathbf{x}_i}=0 \\\\ \\nabla_{b}L(\\mathbf{w}, b, \\alpha)\u0026=-\\sum_{i=1}^{n}{\\alpha_i y_i}=0 \\end{aligned} $$we obtain:\n$$ \\begin{aligned} \u0026\\mathbf{w}=\\sum_{i=1}^{n}{\\alpha_i y_i \\mathbf{x}_i}\\\\ \u0026\\sum_{i=1}^{n}{\\alpha_i y_i}=0 \\end{aligned} \\qquad(1)$$\nsubstituting them back into \\(L\\):\n$$ \\min\\limits_{\\mathbf{w},b}L(\\mathbf{w}, b, \\alpha)= -\\frac{1}{2} \\sum_{i=1}^n\\sum_{j=1}^n{\\alpha_i \\alpha_j y_i y_j (\\mathbf{x}_i \\cdot \\mathbf{x}_j)} + \\sum_{i=1}^n{\\alpha_i} $$Having done that, maximizing w.r.t. \\(\\alpha\\), dual optimization problem can then be summarized as:\n$$ \\begin{aligned} \\max\\limits_{\\alpha} \\quad \u0026 \\sum_{i=1}^n{\\alpha_i} - \\frac{1}{2} \\sum_{i=1}^n\\sum_{j=1}^n{\\alpha_i \\alpha_j y_i y_j (\\mathbf{x}_i \\cdot \\mathbf{x}_j)} \\nonumber \\\\ s.t.\\quad \u0026\\alpha_i\\ge0, i=1,\\cdots,n \\nonumber \\\\ \u0026\\sum_{i=1}^{n}{\\alpha_i y_i}=0 \\nonumber \\end{aligned} \\qquad(2)$$\nSolving the Dual Problem Using a QP Solver Equation 2 is a simpler quadratic programming problem, which can be solved by standard optimization tools. In this case, cvxopt is used and the standard form of a quadratic programming problem that cvxopt uses is:\n$$ \\begin{aligned} \\min\\limits_{x}\\quad\u0026 \\frac{1}{2}x^\\top P x + q^\\top x \\nonumber \\\\ s.t. \\quad \u0026G x \\le h, Ax = b \\nonumber \\end{aligned} $$To write the dual problem in that form, note that\n$$ \\sum_{i,j}{\\alpha_i \\alpha_j y_i y_j (\\mathbf{x}_i \\cdot \\mathbf{x}_j)} $$can be expressed as a quadratic form: \\(\\alpha^\\top P \\alpha\\), where\n$$ P_{ij}=y_i y_j (\\mathbf{x}_i \\cdot \\mathbf{x}_j) $$Let\n$$ q=\\mathbf{-1}, G=-I, h=\\mathbf{0}, A=\\mathbf{y}, b=0 $$where \\(I\\) is the \\(n\\times n\\) identity matrix. In this way, the dual problem can be written in the standard quadratic programming form:\n$$ \\begin{aligned} \\min\\limits_{\\alpha} \\quad \u0026 \\frac{1}{2} \\alpha^\\top P \\alpha + (\\mathbf{-1}^\\top \\alpha) \\nonumber \\\\ s.t.\\quad \u0026-I \\alpha \\le \\mathbf{0} \\nonumber \\\\ \u0026\\mathbf{y}^\\top \\alpha = 0 \\nonumber \\end{aligned} $$The corresponding Python code is as follows:\nShow/Hide the code 1 2 3 4 5 6 P = matrix(np.outer(y, y) * (X @ X.T)) q = matrix(-np.ones(n_samples)) G = matrix(-np.eye(n_samples)) h = matrix(np.zeros(n_samples)) A = matrix(y.reshape(1, -1).astype(float)) b_eq = matrix(0.0) After solving for the optimal solution \\(\\alpha^*\\), we can obtain the optimal solution \\(\\mathbf{w}^*\\) and \\(b^*\\) of the primal problem according to Equation 1 and the Karush-Kuhn-Tucker (KKT) conditions, which are necessary and sufficient conditions for optimality (Platt, 1998):\n$$ \\begin{aligned} \u0026\\mathbf{w}^*=\\sum_{i=1}^{n}{\\alpha_i^* y_i \\mathbf{x}_i} \\\\ \u0026b^*=y_j-\\sum_{i=1}^{n}{\\alpha_i^* y_i (\\mathbf{x}_i \\cdot \\mathbf{x}_j)} \\end{aligned} $$where \\(\\mathbf{x}_j\\) is any of the support vectors that satisfy \\(\\alpha^*_j\u003e0\\). Here, according to complementary slackness in KKT, \\(\\alpha_j^*\u003e0\\) indicates that \\(\\mathbf{x}_j\\) is a support vector, which lies on the margin boundary and satisfies:\n$$ y_i(\\mathbf{w}^*\\cdot \\mathbf{x}_i+b^*)=1 $$The other data points with \\(\\alpha_i^*=0\\) do not contribute to the decision function, which reveals that the hyperplane depends only on the support vectors.\nA better approach to compute \\(b\\) is to use all support vectors, as this makes it numerically more stable (Bishop, 2006):\n$$ b = \\frac{1}{N}\\sum_{i\\in S}\\left(y_i-\\sum_{j \\in S}^{n}{\\alpha_j^* y_j (\\mathbf{x}_i \\cdot \\mathbf{x}_j)}\\right) $$where \\(S\\) is the set of indexes of all support vectors and \\(N\\) is the number of support vectors.\nThe Python code for computing \\(\\mathbf{w}\\) and \\(b\\) based on \\(\\alpha\\) is as follows:\nShow/Hide the code 1 2 3 4 5 6 w = np.sum((alphas * labels).reshape(-1, 1) * support_vectors,axis=0) b = labels[0] - (support_vectors[0] @ w) # use one support vector b = np.mean([y_i - np.sum(alphas * labels * (X @ x_i)) for i, x_i, y_i in zip(sv_indices, support_vectors, support_vector_labels)]) # use all support vectors def predict(self, X): return np.sign(X @ w + b) The decision function of the maximum margin classifier is:\n$$ f(\\mathbf{x})=\\mathbf{w}^*\\cdot\\mathbf{x}+b^*=\\sum_{i=1}^{n}{\\alpha_i^* y_i (\\mathbf{x}_i \\cdot \\mathbf{x})}+b^* $$or equivalently:\n$$ f(\\mathbf{x})=\\sum_{i \\in S}{\\alpha_i^* y_i (\\mathbf{x}_i \\cdot \\mathbf{x})}+b^* $$This is because only support vectors have non-zero \\(\\alpha_i^*\\).\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 import cvxopt from cvxopt import matrix, solvers class HardMarginSVM: def __init__(self): self.w = None self.b = None self.support_vectors = None self.support_vector_labels = None self.alphas = None def fit(self, X, y): n_samples, _ = X.shape P = matrix(np.outer(y, y) * (X @ X.T)) q = matrix(-np.ones(n_samples)) G = matrix(-np.eye(n_samples)) h = matrix(np.zeros(n_samples)) A = matrix(y.reshape(1, -1).astype(float)) b_eq = matrix(0.0) # Solve the quadratic programming problem solvers.options[\u0026#34;show_progress\u0026#34;] = False solution = solvers.qp(P, q, G, h, A, b_eq) # Extract alphas alphas = np.array(solution[\u0026#34;x\u0026#34;]).flatten() # Find support vectors (alphas \u0026gt; threshold) sv_threshold = 1e-5 sv_indices = alphas \u0026gt; sv_threshold self.support_vectors = X[sv_indices] self.support_vector_labels = y[sv_indices] self.alphas = alphas[sv_indices] # Calculate w self.w = np.sum( (self.alphas * self.support_vector_labels).reshape(-1, 1) * self.support_vectors, axis=0, ) # Calculate b using any support vector self.b = self.support_vector_labels[0] - np.dot(self.support_vectors[0], self.w) return self def predict(self, X): return np.sign(self.decision_function(X)) def decision_function(self, X): return X @ self.w + self.b The figure below shows the decision boundary found by the maximum margin classifier on the same synthetic dataset as perceptron used. It is clear that the hyperplane maximizes the margin and classifies all data points correctly.\nShow/Hide the code 1 2 3 4 5 qp_svm = HardMarginSVM() qp_svm.fit(X_dummy, y_dummy) plt.figure(figsize=(3, 3)) plt.scatter(X_dummy[:, 0], X_dummy[:, 1], c=y_dummy, cmap=\u0026#34;bwr\u0026#34;, alpha=1) show_hyperplane(qp_svm.decision_function, (-2, 6)) The Classification Boundary Found by MMC Maximum Margin Classifier With Soft Margin Even though a maximum margin classifier is able to find the optimal hyperplane for linearly separable data already, it is quite sensitive to noise and outliers. In addition, real-world data is often not linearly separable, in which case the maximum margin classifier fails to find a decision boundary.\nA solution to these problems is to introduce slack variables \\(\\xi = \\{\\xi_1, \\cdots, \\xi_n\\}\\) for each data point that allow some points to violate the margin or even the decision boundary. In this way, the model gives up classifying all training data correctly, but it allows some data points, which are probably noises or outliers, to be very close to the decision boundary or even on the wrong side of it.\nThis will increase the bias of the model but reduce its variance, leading to a worse performance on training set, but probably a better performance on testing data. In other words, it generalizes better. Moreover, to trade off the margin size and the number of misclassifications, a regularization parameter \\(C\\) is introduced. Accordingly, the optimization problem becomes:\n$$ \\begin{aligned} \\min\\limits_{\\mathbf{w}, b, \\xi} \\quad \u0026 \\frac{1}{2}||\\mathbf{w}||^2 + C \\sum_{i=1}^{n}{\\xi_i} \\nonumber \\\\ s.t. \\quad \u0026 y_i(\\mathbf{w}\\cdot\\mathbf{x}_i+b)\\ge1-\\xi_i, i=1,\\cdots,n \\nonumber \\\\ \u0026\\xi_i\\ge0, i=1,\\cdots,n \\nonumber \\end{aligned} $$and its dual problem becomes:\n$$ \\begin{aligned} \\max\\limits_{\\alpha} \\quad \u0026 \\sum_{i=1}^n{\\alpha_i} - \\frac{1}{2} \\sum_{i=1}^n\\sum_{j=1}^n{\\alpha_i \\alpha_j y_i y_j (\\mathbf{x}_i \\cdot \\mathbf{x}_j)} \\nonumber \\\\ s.t.\\quad \u00260\\le \\alpha_i\\le C, i=1,\\cdots,n \\nonumber \\\\ \u0026\\sum_{i=1}^{n}{\\alpha_i y_i}=0 \\nonumber \\end{aligned} $$It turns out that the only difference from the hard margin SVM is that \\(\\alpha_i\\) now has an upper bound \\(C\\). In addition, the support vectors can be categorized into two types: the first type are those that lie exactly on the margin boundary, which satisfy \\(0 \u003c \\alpha_i \u003c C\\); the second type are those that violate the margin or even the decision boundary, which satisfy \\(\\alpha_i = C\\). The other data points with \\(\\alpha_i = 0\\) still do not contribute to the decision function.\nSequential Minimal Optimization Sequential Minimal Optimization (SMO) is a popular algorithm for solving the dual problem of the soft margin SVM. The main idea behind SMO is coordinate descent optimized specifically for the SVM dual problem. Coordinate descent refers to optimizing one variable at a time while keeping the others fixed. Therefore, for convex optimization problems, the optimization problem is reduced to finding the minimum of a single variable convex function. However, in the case of SVM dual problem, there is an equality constraint:\n$$ \\sum_{i=1}^{n}{\\alpha_i y_i}=0 $$for which if we optimize one \\(\\alpha_i\\) at a time, it is impossible to satisfy the constraint. To address this issue, SMO optimizes two variables at a time, which allows to adjust one variable while compensating with the other to satisfy the equality constraint.\nThe following conclusions are from Platt (1998).\nTwo-variable Optimization According to Equation 1, we have:\n$$ f(\\mathbf{x}) = \\mathbf{w} \\cdot \\mathbf{x} + b = \\sum_{i=1}^{n}{\\alpha_i y_i (\\mathbf{x}_i \\cdot \\mathbf{x})} + b $$Let \\(E_i = f(\\mathbf{x}_i) - y_i\\) and \\(K_{ij} = \\mathbf{x}_i \\cdot \\mathbf{x}_j\\).\nAssuming we select \\(\\alpha_1\\) and \\(\\alpha_2\\) to optimize, the unclipped solution is:\n$$ \\begin{aligned} \u0026\\alpha_2^{new} = \\alpha_2 + \\frac{y_2 (E_1 - E_2)}{\\eta} \\\\ \u0026\\alpha_1^{new} = \\alpha_1 + y_1 y_2 (\\alpha_2 - \\alpha_2^{new}) \\end{aligned} \\qquad(3)$$\nwhere \\(\\eta = 2K_{12} - K_{11} - K_{22}\\).\nTo ensure that the new \\(\\alpha_1\\) and \\(\\alpha_2\\) satisfy the constraints, we need to clip them within the feasible region. The clipping bounds depend on whether \\(y_1\\) and \\(y_2\\) are the same or different:\n$$ \\begin{aligned} \\text{if}\u0026\\quad y_1 \\neq y_2: \\\\ \u0026\\quad L = \\max(0, \\alpha_2 - \\alpha_1) \\\\ \u0026\\quad H = \\min(C, C + \\alpha_2 - \\alpha_1) \\\\ \\\\ \\text{if}\u0026\\quad y_1 = y_2: \\\\ \u0026\\quad L = \\max(0, \\alpha_1 + \\alpha_2 - C) \\\\ \u0026\\quad H = \\min(C, \\alpha_1 + \\alpha_2) \\end{aligned} \\qquad(4)$$\nThe pseudo Python code below demonstrates the two-variable optimization process. i1, i2 are the indexes of the two variables being optimized. The array alphas stores the values of all \\(\\alpha_i\\) and y stores the class labels. The function compute_error computes the error \\(E_i\\), which is the difference between the predicted and true labels. The code first ensures that the two selected variables are different and initializes the necessary variables.\nShow/Hide the code 1 2 3 4 if i1 == i2: return 0 alpha1, alpha2 = alphas[i1], alphas[i2] y1, y2 = y[i1], y[i2] E1, E2 = compute_error(i1), compute_error(i2) Then, it calculates the bounds \\(L\\) and \\(H\\) for clipping based on the conclusions Equation 4 and ensures \\(L \\ne H\\).\nShow/Hide the code 1 2 3 4 5 6 7 8 s = y1 * y2 if y1 != y2: L = max(0, alpha2 - alpha1) H = min(self.C, self.C + alpha2 - alpha1) else: L = max(0, alpha1 + alpha2 - self.C) H = min(self.C, alpha1 + alpha2) if L == H: return 0 K is the kernel matrix (Since the kernel trick has not been introduced, it is just the inner product of vectors here). The code finally computes the new values of \\(\\alpha_2\\), clips \\(\\alpha_2\\) within the bounds \\(L\\) and \\(H\\), and updates \\(\\alpha_1\\) accordingly, based on Equation 3.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 k11, k12, k22 = K[i1, i1], K[i1, i2], K[i2, i2] eta = k11 + k22 - 2 * k12 if eta \u0026gt; 0: alpha2_new = alpha2 + y2 * (E1 - E2) / eta if alpha2_new \u0026gt;= H: alpha2_new = H elif alpha2_new \u0026lt;= L: alpha2_new = L else: alpha2_new = L if abs(alpha2 - L) \u0026lt; abs(alpha2 - H) else H alpha1_new = alpha1 + s * (alpha2 - alpha2_new) Choosing Variables In fact, as long as SMO always selects two variables to optimize, it will eventually converge (Platt, 1998). To speed up this process, SMO uses heuristics to choose variables. The selections of the first and the second variable are called the outer and inner loop, respectively.\nAccording to Platt (1998), the algorithm for selecting two variables is as follows:\nOuter Loop:\nIterates over all data points and examines whether they violate the KKT conditions. If a data point violates the KKT conditions, it is eligible for selection. Iterate only over non-bound examples (\\(0 \u003c \\alpha \u003c C\\)) Repeat step 2 until all of the non-bound examples obey the KKT conditions within a specified tolerance, typically \\(10^{-3}\\). Alternate between \u0026ldquo;entire training set pass\u0026rdquo; and \u0026ldquo;repeated non-bound subset passes\u0026rdquo; until entire training set satisfies KKT conditions. Inner Loop:\nApproximate step size by \\(|E_1 - E_2|\\). If \\(E_i \u003e 0\\), choose example with minimum \\(E_2\\), whereas if \\(E_1 \u003c 0\\): choose example with maximum \\(E_2\\). If the choice of the second variable makes no positive progress, then iterate through non-bound examples, and find one that makes positive progress; If still no progress, iterate through entire training set. If nothing works, skip this pair and return to the outer loop.\nComputing \\(b\\) If \\(\\alpha_1\\) is non-bound: use \\(b_1\\) If \\(\\alpha_2\\) is non-bound: use \\(b_2\\) If both non-bound: use either (they should be equal, or average for numerical stability) If both bound: use \\(\\frac{(b_1 + b_2)}{2}\\) Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 ## | echo: false class SMOSVM: def __init__(self, C=1.0, tol=1e-3, max_iter=100, gamma=1.0): self.C = C self.tol = tol self.max_iter = max_iter def _compute_error(self, i): return self.f[i] - self.y[i] def _take_step(self, i1, i2): if i1 == i2: return 0 alpha1 = self.alphas[i1] alpha2 = self.alphas[i2] y1 = self.y[i1] y2 = self.y[i2] E1 = self._compute_error(i1) E2 = self._compute_error(i2) s = y1 * y2 if y1 != y2: L = max(0, alpha2 - alpha1) H = min(self.C, self.C + alpha2 - alpha1) else: L = max(0, alpha1 + alpha2 - self.C) H = min(self.C, alpha1 + alpha2) if L == H: return 0 k11 = self.K[i1, i1] k12 = self.K[i1, i2] k22 = self.K[i2, i2] eta = k11 + k22 - 2 * k12 if eta \u0026gt; 0: alpha2_new = alpha2 + y2 * (E1 - E2) / eta if alpha2_new \u0026gt;= H: alpha2_new = H elif alpha2_new \u0026lt;= L: alpha2_new = L else: alpha2_new = L if abs(alpha2 - L) \u0026lt; abs(alpha2 - H) else H if abs(alpha2_new - alpha2) \u0026lt; 1e-5: return 0 alpha1_new = alpha1 + s * (alpha2 - alpha2_new) b1 = ( self.b - E1 - y1 * (alpha1_new - alpha1) * k11 - y2 * (alpha2_new - alpha2) * k12 ) b2 = ( self.b - E2 - y1 * (alpha1_new - alpha1) * k12 - y2 * (alpha2_new - alpha2) * k22 ) if 0 \u0026lt; alpha1_new \u0026lt; self.C: b_new = b1 elif 0 \u0026lt; alpha2_new \u0026lt; self.C: b_new = b2 else: b_new = (b1 + b2) / 2 self.alphas[i1] = alpha1_new self.alphas[i2] = alpha2_new self.b = b_new self.f = np.sum(self.alphas * self.y * self.K.T, axis=1) + self.b return 1 # pick up i1 and run the optimization process def _examine_example(self, i2): y2 = self.y[i2] alpha2 = self.alphas[i2] E2 = self._compute_error(i2) # E = (f-y) =\u0026gt; r = y*f - y*y = y*f - 1 = functional distance - 1 r2 = E2 * y2 # two cases of violating KKT # r \u0026lt; 0 =\u0026gt; functional distance \u0026lt; 1, alpha should be C but \u0026lt; C # r \u0026gt; 0 =\u0026gt; functional distance \u0026gt; 1, alpha should be 0 but \u0026gt; 0 if (r2 \u0026lt; -self.tol and alpha2 \u0026lt; self.C) or (r2 \u0026gt; self.tol and alpha2 \u0026gt; 0): # 0 \u0026lt; alphas \u0026lt; C =\u0026gt; points lay exactly on the margin non_bound_indices = np.where((self.alphas \u0026gt; 0) \u0026amp; (self.alphas \u0026lt; self.C))[0] # if there are at least another one non-bound alpha if len(non_bound_indices) \u0026gt; 1: errors = np.array([self._compute_error(i) for i in non_bound_indices]) if E2 \u0026gt; 0: i1 = non_bound_indices[np.argmin(errors)] else: i1 = non_bound_indices[np.argmax(errors)] if self._take_step(i1, i2): return 1 # if heuristic does not work, try to pick one randomly np.random.shuffle(non_bound_indices) for i1 in non_bound_indices: if self._take_step(i1, i2): return 1 # if nothing works or there is only one non-bound alpha all_indices = np.random.permutation(self.n) for i1 in all_indices: if self._take_step(i1, i2): return 1 return 0 def _compute_kernel_matrix(self, X): return X @ X.T def fit(self, X, y): self.X = X self.y = y self.n, self.d = X.shape # initialize alphas, 0 \u0026lt;= alphas \u0026lt;= C self.alphas = np.zeros(self.n) self.b = 0.0 self.K = self._compute_kernel_matrix(X) self.f = np.zeros(self.n) + self.b num_changed = 0 examine_all = True iter_count = 0 # as long as: # 1. there are alphas have been updated or # 2. we try to examine all alphas or # 3. we haven\u0026#39;t reached the limitation # try to pick up two alphas to optimize while (num_changed \u0026gt; 0 or examine_all) and iter_count \u0026lt; self.max_iter: num_changed = 0 if examine_all: # i2 would be any alphas for i in range(self.n): num_changed += self._examine_example(i) else: non_bound_indices = np.where( (self.alphas \u0026gt; 0) \u0026amp; (self.alphas \u0026lt; self.C) )[0] for i in non_bound_indices: num_changed += self._examine_example(i) # if we just done examine all alphas, next time try non-bound alphas only if examine_all: examine_all = False # otherwise, if non-bound alphas do not work, we try to examine all next time elif num_changed == 0: examine_all = True iter_count += 1 sv_indices = self.alphas \u0026gt; 1e-5 self.support_vectors_ = X[sv_indices] self.support_vector_labels_ = y[sv_indices] self.support_vector_alphas_ = self.alphas[sv_indices] def decision_function(self, X): n_samples = X.shape[0] decision = np.zeros(n_samples) for i in range(n_samples): K = (X[i : i + 1] @ self.support_vectors_.T).flatten() decision[i] = ( np.sum(self.support_vector_alphas_ * self.support_vector_labels_ * K) + self.b ) return decision def predict(self, X): return np.sign(self.decision_function(X)) The figure below shows the decision boundary found by SMO SVM on a noisy dataset. It can be seen that the hyperplane allows some points to violate the margin and even be misclassified.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 smo_svm = SMOSVM(C=0.2, tol=1e-3, max_iter=100) smo_svm.fit(X_with_noise, y_with_noise) # Plot the decision boundary plt.figure(figsize=(3, 3)) plt.scatter( X_with_noise[:, 0], X_with_noise[:, 1], c=y_with_noise, cmap=\u0026#34;bwr\u0026#34;, alpha=0.6, s=100 ) show_hyperplane(smo_svm.decision_function) plt.show() The Decision Boundary Found by SMO SVM on Noisy Data Hinge Loss With L2 Regularization In addition to solving the dual problem, the soft margin SVM can also be addressed from another perspective: optimizing the regularized hinge loss. It can be shown that the original optimization problem of the soft margin SVM is equivalent to the following optimization problem:\n$$ \\min\\limits_{\\mathbf{w}, b} \\quad \\lambda||\\mathbf{w}||^2 + \\sum_{i=1}^{n}{\\max(0, 1-y_i(\\mathbf{w}\\cdot\\mathbf{x}_i+b))} $$Here, the first term is the regularization term, and \\(\\lambda\\) is the regularization parameter, which controls the trade-off between the two terms and is inversely proportional to \\(C\\) above. When \\(\\lambda\\) approaches 0, the penalty from regularization decreases, and the model tends to classify the data correctly. When \\(\\lambda=0\\), the model essentially becomes the hard margin SVM.\nIn this case, if the dataset is linearly separable, the model can find a hyperplane that perfectly classifies the data, but it will be extremely sensitive to noise and outliers, leading to poor generalization. To balance perfect classification with generalization ability, \\(\\lambda\\) is usually set to a value greater than 0. In this way, while the model pursues perfect classification, it also minimizes the norm of the weights as much as possible, thereby enlarging the margin (recall that the margin is the inverse of \\(||\\mathbf{w}||\\)), and improving generalization.\nFrom the perspective of model complexity, regularization constrains the parameter space by eliminating large values of weights, thus limiting the number of hypotheses in the hypothesis set \\(\\mathbb{H}\\), reducing model complexity, and lowering the risk of overfitting. This reflects the idea of the bias-variance trade-off.\nThe second term is the hinge loss, which is named after its shape, as shown in the figure below. When the functional margin is greater than or equal to 1\n$$ y_i(\\mathbf{w}\\cdot\\mathbf{x}_i+b)\\ge1 $$it means the point lies outside the margin or exactly on it, so no penalty is applied. When the margin is less than 1, the penalty equals the distance by which the point falls short of the margin. The closer the point is to the hyperplane, the larger the violation of the margin, and thus the heavier the penalty.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 plt.figure(figsize=(4, 2)) xvals = np.linspace(-10, 10, 1000) yvals = np.maximum(0, 1 - xvals) plt.plot(xvals, yvals, \u0026#34;b-\u0026#34;) plt.axhline(y=0, color=\u0026#34;black\u0026#34;, alpha=0.3) plt.axvline(color=\u0026#34;black\u0026#34;, alpha=0.3) plt.xlim(-3, 5) plt.ylim(-1, 4) plt.show() The Illustration of Hinge Loss The following code demonstrates how to compute hinge loss with L2 regularization in Python. First, the distance of each point to the hyperplane is calculated. Points with distance greater than 1 are set to 0, and then the average is taken to obtain the hinge loss. The regularization term is computed according to the formula, and finally the two terms are added together to obtain the final loss value.\nShow/Hide the code 1 2 3 4 5 def loss(X, y, w, b, lambda_): distances = y * (X @ w + b) hinge_loss = np.mean(np.maximum(0, 1 - distances)) reg_loss = lambda_ * (w @ w) return hinge_loss + reg_loss Mini-batch SGD Since the hinge loss is almost everywhere differentiable and is a convex function, in addition to analytical methods, one can also use stochastic gradient descent (SGD) to find the minimum. SGD refers to updating the parameters in the direction determined by the gradient of the function. At non-differentiable points, a sub-gradient is chosen to replace the gradient. For example, for the hinge loss function, at non-differentiable points, any element from\n$$ \\{-\\alpha y \\mathbf{x} \\mid \\alpha \\in [0, 1]\\} $$can be chosen as the sub-gradient. Since the gradient always points in the direction of steepest ascent, its negative points to the steepest descent direction. Because the objective function is convex, descending along the steepest slope at each step will gradually lead us closer to the minimum of the function, i.e., the point where the hinge loss is minimized.\nThe stochastic nature of SGD comes from computing the gradient on a small randomly sampled batch of data from the dataset each time. This avoids the expensive computation cost of calculating gradients over the entire dataset, while also avoiding the instability of using just a single data point, thus achieving a balance.\nGradient Calculation To compute the gradient of the hinge loss, first write hinge loss in a piecewise form:\n$$ L_i(\\mathbf{w}, b) = \\left\\{ \\begin{array}{lr} 1 - y_i (\\mathbf{w} \\cdot \\mathbf{x}_i + b) + \\lambda ||\\mathbf{w}||^2 \u0026 \\text{if } 1 - y_i (\\mathbf{w} \\cdot \\mathbf{x}_i + b) \u003e 0 \\\\ \\lambda ||\\mathbf{w}||^2 \u0026 \\text{otherwise} \\end{array} \\right. $$This function is non-differentiable at the piecewise boundary, but differentiable elsewhere. When \\(1-y_i(\\mathbf{w}\\cdot\\mathbf{x}_i+b)\u003e0\\),\n$$ \\nabla_{\\mathbf{w}}L_i(\\mathbf{w}, b) = -y_i \\mathbf{x}_i + 2 \\lambda \\mathbf{w} $$$$ \\nabla_{b}L_i(\\mathbf{w}, b) = -y_i $$When \\(1-y_i(\\mathbf{w}\\cdot\\mathbf{x}_i+b) \u003c 0\\), the hinge loss is 0, and only the regularization term is considered:\n$$ \\nabla_{\\mathbf{w}}L_i(\\mathbf{w}, b) = 2 \\lambda \\mathbf{w} $$$$ \\nabla_{b}L_i(\\mathbf{w}, b) = 0 $$The following code demonstrates how to compute the gradient. First, the distance of each point to the hyperplane is calculated. Then, depending on whether the distance is greater than 1, the gradient is computed differently. For points with distance less than 1, the gradient is the sum of the hinge loss gradient and the regularization term gradient. For points with distance greater than 1, the hinge loss gradient is 0, and only the regularization term gradient is computed. Here, for points with distance exactly equal to 1, the sub-gradient is chosen to be 0.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 def calc_gradient(X, y, w, b, lambda_): distances = y * (X @ w + b) mask = distances \u0026lt; 1 dw = 2 * lambda_ * w if np.any(mask): dw += -np.mean((y[mask]).reshape(-1, 1) * X[mask], axis=0) db = 0.0 if np.any(mask): db = -np.mean(y[mask]) return dw, db Learning Rate The gradient determines the update direction at each step, while the learning rate controls the step size. If the learning rate is too large, the algorithm may overshoot the minimum, or even cause the loss to increase. If the learning rate is too small, convergence will be very slow, and in the case of non-convex optimization, it may increase the risk of getting stuck in a local optimum. Therefore, choosing an appropriate learning rate is also crucial. The two cases described above are illustrated in the figure below.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def f(x): return np.array(x) ** 2 fig, axes = plt.subplots(1, 2, figsize=(8, 3)) x = np.linspace(-2, 2, 100) y = f(x) axes[0].plot(x, y, \u0026#34;b-\u0026#34;) axes[0].axhline(y=0, color=\u0026#34;black\u0026#34;, alpha=0.3) axes[0].axvline(color=\u0026#34;black\u0026#34;, alpha=0.3) axes[0].set_ylim(-1, 4) axes[0].set_xlim(-2, 2) axes[0].scatter([-1.0], f([-1.0]), color=\u0026#34;red\u0026#34;) axes[0].plot([-1.0, 1.5], [f(-1), f(-1)], \u0026#34;r--\u0026#34;) axes[0].axvline(x=1.5, color=\u0026#34;black\u0026#34;, alpha=0.3, linestyle=\u0026#34;--\u0026#34;) axes[0].scatter([1.5], f([1.5]), color=\u0026#34;green\u0026#34;) axes[0].text(-1.0, 1.2, \u0026#34;Start\u0026#34;, fontsize=10, color=\u0026#34;red\u0026#34;) axes[0].text(0.4, 2.3, \u0026#34;Overshoot\u0026#34;, fontsize=10, color=\u0026#34;green\u0026#34;) axes[0].set_title(\u0026#34;Too Large, Loss Increases\u0026#34;, fontsize=10) axes[1].plot(x, y, \u0026#34;b-\u0026#34;) axes[1].axhline(y=0, color=\u0026#34;black\u0026#34;, alpha=0.3) axes[1].axvline(color=\u0026#34;black\u0026#34;, alpha=0.3) axes[1].set_ylim(-1, 4) axes[1].set_xlim(-2, 2) axes[1].scatter([-1.8], f([-1.8]), color=\u0026#34;red\u0026#34;) axes[1].plot([-1.8, -1.7], [f(-1.8), f(-1.8)], \u0026#34;r--\u0026#34;) axes[1].axvline(x=-1.7, color=\u0026#34;black\u0026#34;, alpha=0.3, linestyle=\u0026#34;--\u0026#34;) axes[1].scatter([-1.7], f([-1.7]), color=\u0026#34;green\u0026#34;) axes[1].text(-1.6, 3.3, \u0026#34;Start\u0026#34;, fontsize=10, color=\u0026#34;red\u0026#34;) axes[1].text(-1.5, 2.7, \u0026#34;Too slow\u0026#34;, fontsize=10, color=\u0026#34;green\u0026#34;) axes[1].set_title(\u0026#34;Too Small, Loss Decreases Slowly\u0026#34;, fontsize=10) plt.show() Effects of Different Learning Rates on Convergence Apart from using a fixed learning rate, a dynamically adjusted learning rate can be used. For example, the learning rate can gradually decrease as the number of iterations increases. The advantage of this approach is that in the initial stage, a larger learning rate allows the algorithm to quickly approach the optimal solution; while in the later stage, a smaller learning rate helps avoid overshooting the optimum and allows more stable convergence.\nUpdate Strategy Having calculated the gradient and chosen a appropriate learning rate, the parameters can be updated as follows:\n$$ \\begin{aligned} \u0026\\mathbf{w} \\leftarrow \\mathbf{w} - lr \\nabla_{\\mathbf{w}}L_i(\\mathbf{w}, b) \\\\ \u0026b \\leftarrow b - lr \\nabla_{b}L_i(\\mathbf{w}, b) \\end{aligned} $$where \\(lr\\) is the learning rate.\nThe complete learning process is as follows:\nFirst, randomly initialize the model parameters \\(\\mathbf{w}\\) and \\(b\\). Then, in each iteration, split all the data into multiple mini-batches. For each mini-batch, compute the gradient for that batch and update the model parameters. Repeat steps 2 and 3 until the preset number of iterations is reached. The code is shown below:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 w = np.random.normal(0, 0.01, n_features) b = 0.0 for epoch in range(n_epochs): batches = get_batches(X, y, batch_size) for batch in batches: dw, db = gradient(X_batch, y_batch) w -= lr * dw b -= lr * db Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 class SGDSVM: def __init__(self, lambda_=0.01, lr=0.01, epochs=10, batch_size=64): self.lambda_ = lambda_ self.lr = lr self.epochs = epochs self.batch_size = batch_size self.loss_history = [] def loss(self, X, y): distances = 1 - y * (X @ self.w + self.b) hinge_loss = np.maximum(0, distances).mean() reg = self.lambda_ * (self.w @ self.w) return hinge_loss + reg def gradient(self, X, y): # Decision values for batch distances = 1 - y * (X @ self.w + self.b) # Identify samples with hinge loss \u0026gt; 0 mask = distances \u0026gt; 0 # Gradient w.r.t w dw = 2 * self.lambda_ * self.w if np.any(mask): dw += -np.mean((y[mask]).reshape(-1, 1) * X[mask], axis=0) # Gradient w.r.t b db = 0.0 if np.any(mask): db = -np.mean(y[mask]) return dw, db def fit(self, X, y): np.random.seed(42) n_samples, n_features = X.shape self.w = np.random.normal(0, 0.01, n_features) self.b = 0.0 self.losses_train = [] for epoch in range(self.epochs): indices = np.random.permutation(n_samples) X_shuffled, y_shuffled = X[indices], y[indices] for i in range(0, n_samples, self.batch_size): # numpy array never go out of index range with slicing X_batch = X_shuffled[i : i + self.batch_size] y_batch = y_shuffled[i : i + self.batch_size] dw, db = self.gradient(X_batch, y_batch) self.w -= self.lr * dw self.b -= self.lr * db self.loss_history.append(self.loss(X, y)) def decision_function(self, X): return X @ self.w + self.b def predict(self, X): return np.sign(self.decision_function(X)) Comparison With Hard Margin SVM As shown in the figure below, after introducing two outliers into the original dataset, the decision boundary of the hard margin classifier is largely shifted due to the influence of the noise, producing a hyperplane with very narrow margins, whereas the soft margin classifier is less affected by outliers, because it allows some points to violate the margin or even be misclassified.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 hard_svm = HardMarginSVM() hard_svm.fit(X_with_noise, y_with_noise) sgd_svm = SGDSVM(epochs=200, lr=0.01, lambda_=0.1) sgd_svm.fit(X_with_noise, y_with_noise) fig, axes = plt.subplots(1, 2, figsize=(6, 3)) axes[0].scatter( X_with_noise[:, 0], X_with_noise[:, 1], c=y_with_noise, cmap=\u0026#34;bwr\u0026#34;, alpha=1 ) axes[0].set_title(\u0026#34;Hard Margin SVM\u0026#34;, fontsize=10) axes[1].set_title(\u0026#34;Soft Margin SVM\u0026#34;, fontsize=10) axes[1].scatter( X_with_noise[:, 0], X_with_noise[:, 1], c=y_with_noise, cmap=\u0026#34;bwr\u0026#34;, alpha=1 ) show_hyperplane(hard_svm.decision_function, ax=axes[0]) show_hyperplane(sgd_svm.decision_function, ax=axes[1]) plt.show() Comparison Between Hard Margin SVM and Soft Margin SVM on Noisy Data The figure below shows different decision boundaries obtained by the soft margin SVM with different values of the regularization parameter \\(\\lambda\\). A smaller \\(\\lambda\\) (equivalent to a larger \\(C\\)) means a smaller penalty for misclassification, leading to a narrower margin and a more complex model that fits the training data better but may overfit. Conversely, a larger \\(\\lambda\\) (equivalent to a smaller \\(C\\)) results in a wider margin and a simpler model that may underfit the training data but generalizes better.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 fig, axes = plt.subplots(1, 3, figsize=(15, 5)) Cs = [1000, 1, 0.1] titles = [r\u0026#34;$C=1000$\u0026#34;, r\u0026#34;$C=1$\u0026#34;, r\u0026#34;$C=0.1$\u0026#34;] for ax, C, title in zip(axes, Cs, titles): smo_svm = SMOSVM(C, tol=1e-3, max_iter=100) smo_svm.fit(X_with_noise, y_with_noise) ax.set_title(title, fontsize=10) ax.scatter( X_with_noise[:, 0], X_with_noise[:, 1], c=y_with_noise, cmap=\u0026#34;bwr\u0026#34;, alpha=1 ) show_hyperplane(smo_svm.decision_function, ax=ax) plt.show() Effect of Regularization Parameter on Decision Boundary of Soft Margin SVM Experiments On MNIST Dataset Dataset Description The input dataset \\(X\\) consists of \\(28\\times28\\) pixel grayscale images of handwritten digits. The pixel values range from 0 to 255 where 0 represents pure white and 255 represents pure black. The pixel values are normalized to the range \\([0, 1]\\) by dividing by 255. The training set contains 60,000 images and the test set contains 10,000 images. In this experiment, only the digits 3 and 7 are used to form a binary classification problem. Each image is flattened into a 784-dimensional vector. The output is a binary label indicating whether the digit is a 3 or a 7.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import idx2numpy train_images = idx2numpy.convert_from_file(\u0026#34;./mnist/archive/train-images.idx3-ubyte\u0026#34;) train_labels = idx2numpy.convert_from_file(\u0026#34;./mnist/archive/train-labels.idx1-ubyte\u0026#34;) test_images = idx2numpy.convert_from_file(\u0026#34;./mnist/archive/t10k-images.idx3-ubyte\u0026#34;) test_labels = idx2numpy.convert_from_file(\u0026#34;./mnist/archive/t10k-labels.idx1-ubyte\u0026#34;) threes = train_images[train_labels == 3].reshape(-1, 28 * 28).astype(np.float32) / 255.0 sevens = train_images[train_labels == 7].reshape(-1, 28 * 28).astype(np.float32) / 255.0 fives = train_images[train_labels == 5].reshape(-1, 28 * 28).astype(np.float32) / 255.0 fives_valid = ( test_images[test_labels == 5].reshape(-1, 28 * 28).astype(np.float32) / 255.0 ) threes_valid = ( test_images[test_labels == 3].reshape(-1, 28 * 28).astype(np.float32) / 255.0 ) sevens_valid = ( test_images[test_labels == 7].reshape(-1, 28 * 28).astype(np.float32) / 255.0 ) The figure below shows some samples of the digits 3 and 7 from the training set.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 X = np.vstack([threes, sevens]) y = np.array([1] * len(threes) + [-1] * len(sevens)) X_valid = np.vstack([threes_valid, sevens_valid]) y_valid = np.array([1] * len(threes_valid) + [-1] * len(sevens_valid)) show_images( [ threes[0].reshape(28, 28), threes[1].reshape(28, 28), threes[2].reshape(28, 28), threes[3].reshape(28, 28), sevens[0].reshape(28, 28), sevens[1].reshape(28, 28), sevens[2].reshape(28, 28), sevens[3].reshape(28, 28), ], titles=[\u0026#34;3\u0026#34;, \u0026#34;3\u0026#34;, \u0026#34;3\u0026#34;, \u0026#34;3\u0026#34;, \u0026#34;7\u0026#34;, \u0026#34;7\u0026#34;, \u0026#34;7\u0026#34;, \u0026#34;7\u0026#34;], ) Training with SGD SVM The code below trains a soft margin SGD based SVM.\nShow/Hide the code 1 2 sgd_svm = SGDSVM(epochs=200, lr=0.0001, lambda_=0.001) sgd_svm.fit(X, y) The figure below shows the training loss curve. It can be seen that the loss decreases rapidly in the initial stage and then gradually stabilizes.\nShow/Hide the code 1 2 3 4 5 plt.figure(figsize=(6, 3)) plt.plot(sgd_svm.loss_history, color=\u0026#34;blue\u0026#34;, label=\u0026#34;Training Loss\u0026#34;) plt.legend() plt.show() Training Loss Curve of SGD SVM on MNIST The code below calculates the accuracy on the validation set.\nShow/Hide the code 1 2 3 print( f\u0026#34;The accuracy on the validation set is: {(sgd_svm.predict(X_valid) == y_valid).mean()*100:.2f}%\u0026#34; ) The accuracy on the validation set is: 98.28% The figure below visualizes the learned weights. The red areas indicate positive weights, while the blue areas indicate negative weights. It can be observed that the model focuses on the regions that are most discriminative between the digits 3 and 7.\nShow/Hide the code 1 plt.imshow(sgd_svm.w.reshape(28, 28), cmap=\u0026#34;RdBu\u0026#34;, aspect=\u0026#34;equal\u0026#34;) Visualization of Learned Weights by SGD SVM The figure below shows the confusion matrix of the predictions on the validation set. It can be seen that most samples are correctly classified, with only a few misclassifications.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from sklearn.metrics import confusion_matrix, classification_report, accuracy_score import seaborn as sns y_pred = sgd_svm.predict(X_valid) cm = confusion_matrix(y_valid, y_pred) plt.figure(figsize=(5, 4)) sns.heatmap( cm, annot=True, fmt=\u0026#34;d\u0026#34;, cmap=\u0026#34;Blues\u0026#34;, xticklabels=[\u0026#34;7\u0026#34;, \u0026#34;3\u0026#34;], yticklabels=[\u0026#34;7\u0026#34;, \u0026#34;3\u0026#34;], ) plt.xlabel(\u0026#34;Predicted\u0026#34;) plt.ylabel(\u0026#34;True\u0026#34;) plt.show() Confusion Matrix and Classification Report of SGD SVM on MNIST The table below shows the precision, recall, and F1-score for each class.\nShow/Hide the code 1 print(classification_report(y_valid, y_pred, target_names=[\u0026#34;7\u0026#34;, \u0026#34;3\u0026#34;])) precision recall f1-score support 7 0.99 0.98 0.98 1028 3 0.98 0.99 0.98 1010 accuracy 0.98 2038 macro avg 0.98 0.98 0.98 2038 weighted avg 0.98 0.98 0.98 2038 Comparison with SMO Algorithm SMO algorithm is expected to be able to find a more accurate solution to the soft margin SVM problem because it directly solves the dual problem. The code below randomly selects 500 samples from the training set to form a smaller training set and trains an SMO SVM on it.\nShow/Hide the code 1 2 3 4 5 6 7 n_train_samples = 500 indices = np.random.choice(len(X), n_train_samples, replace=False) X_train_small = X[indices] y_train_small = y[indices] smo_mnist = SMOSVM(C=100, tol=1e-3, max_iter=50) smo_mnist.fit(X_train_small, y_train_small) The code below evaluates the SMO SVM on the validation set and compares it with the SGD SVM trained on the same small subset. SMO SVM and SGD SVM have almost the same performance.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 ## Evaluate SMO SVM on validation set y_pred_smo = smo_mnist.predict(X_valid) accuracy_smo = accuracy_score(y_valid, y_pred_smo) print(f\u0026#34;SMO SVM accuracy on validation set: {accuracy_smo*100:.2f}%\u0026#34;) sgd_svm_small = SGDSVM(epochs=1000, lr=0.0001, lambda_=0.001) sgd_svm_small.fit(X_train_small, y_train_small) y_pred_sgd_small = sgd_svm_small.predict(X_valid) accuracy_sgd_small = accuracy_score(y_valid, y_pred_sgd_small) print(f\u0026#34;SGD SVM accuracy on validation set: {accuracy_sgd_small*100:.2f}%\u0026#34;) SMO SVM accuracy on validation set: 97.20% SGD SVM accuracy on validation set: 97.25% Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 cm_smo = confusion_matrix(y_valid, y_pred_smo) cm_sgd = confusion_matrix(y_valid, y_pred_sgd_small) fig, axes = plt.subplots(1, 2, figsize=(14, 6)) sns.heatmap( cm_smo, annot=True, fmt=\u0026#34;d\u0026#34;, cmap=\u0026#34;Blues\u0026#34;, xticklabels=[\u0026#34;7\u0026#34;, \u0026#34;3\u0026#34;], yticklabels=[\u0026#34;7\u0026#34;, \u0026#34;3\u0026#34;], ax=axes[0], ) axes[0].set_title(f\u0026#34;SMO SVM (Acc: {accuracy_smo:.4f})\u0026#34;) axes[0].set_xlabel(\u0026#34;Predicted\u0026#34;) axes[0].set_ylabel(\u0026#34;True\u0026#34;) sns.heatmap( cm_sgd, annot=True, fmt=\u0026#34;d\u0026#34;, cmap=\u0026#34;Greens\u0026#34;, xticklabels=[\u0026#34;7\u0026#34;, \u0026#34;3\u0026#34;], yticklabels=[\u0026#34;7\u0026#34;, \u0026#34;3\u0026#34;], ax=axes[1], ) axes[1].set_title(f\u0026#34;SGD SVM (Acc: {accuracy_sgd_small:.4f})\u0026#34;) axes[1].set_xlabel(\u0026#34;Predicted\u0026#34;) axes[1].set_ylabel(\u0026#34;True\u0026#34;) plt.tight_layout() plt.show() Confusion Matrices of SMO SVM and SGD SVM on MNIST Validation Set In conclusion, the comparison shows that both SMO and SGD based approaches can effectively solve the soft margin SVM problem.\nMulti-class SVM SVM is not able to handle multi-class classification problems directly due to its binary nature. However, there are two common strategies to extend SVM to multi-class problems: one-versus-the-rest (OvR) and one-versus-one (OvO), both of which involve training multiple binary classifiers.\nOne Versus The Rest One versus rest (OvR) refers to training \\(k\\) binary classifiers for a \\(k\\)-class classification problem. Each classifier is trained to distinguish one class from all other classes. During training, the \\(k\\)th classifier is trained using the samples from the \\(k\\)th class as positive examples and samples from all other classes as negative examples. During prediction, the classifier that outputs the highest decision function value determines the predicted class. One disadvantage of this approach is that one data point may be classified into multiple classes. Another disadvantage is that the classifiers are very likely to be imbalanced, as the positive data from one class while the negative data from all other classes.\nOne Versus One One versus one (OvO) refers to training \\(\\binom{k}{2}\\) binary classifiers for a \\(k\\)-class classification problem. Each classifier is trained to distinguish between a pair of classes. The advantage of this approach is that each classifier is trained on a balanced dataset, as each classifier only uses data from two classes. During prediction, each classifier votes for one of the two classes it was trained on, and the class with the most votes is chosen as the final prediction. One disadvantage of this approach is that it requires training a large number of classifiers, which can be computationally expensive for problems with many classes. Another disadvantage is that the classifiers may be inconsistent, as different classifiers may produce conflicting predictions.\nBishop (2006) lists several methods for addressing aforementioned issues like Direct Acyclic Graph SVM (DAGSVM) and concludes that in practice, OvR is widely used. Therefore, in this section, I will implement the OvR strategy using the SGD SVM and test it on a three-class classification problem using digits 3, 5, and 7 from the MNIST dataset.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 X = np.vstack([threes, fives, sevens]) y = np.array([0] * len(threes) + [1] * len(fives) + [2] * len(sevens)) X_valid = np.vstack([threes_valid, fives_valid, sevens_valid]) y_valid = np.array( [0] * len(threes_valid) + [1] * len(fives_valid) + [2] * len(sevens_valid) ) show_images( [ threes[0].reshape(28, 28), threes[1].reshape(28, 28), threes[2].reshape(28, 28), threes[3].reshape(28, 28), fives[0].reshape(28, 28), fives[1].reshape(28, 28), fives[2].reshape(28, 28), fives[3].reshape(28, 28), sevens[0].reshape(28, 28), sevens[1].reshape(28, 28), sevens[2].reshape(28, 28), sevens[3].reshape(28, 28), ], titles=[\u0026#34;3\u0026#34;, \u0026#34;3\u0026#34;, \u0026#34;3\u0026#34;, \u0026#34;3\u0026#34;, \u0026#34;5\u0026#34;, \u0026#34;5\u0026#34;, \u0026#34;5\u0026#34;, \u0026#34;5\u0026#34;, \u0026#34;7\u0026#34;, \u0026#34;7\u0026#34;, \u0026#34;7\u0026#34;, \u0026#34;7\u0026#34;], ) Some Samples of Digits 3, 5, and 7 from the MNIST Dataset The code below implements the OvR strategy using the previously defined SGDSVM class. The OvR_SGD_SVM class contains a list of SGDSVM models, one for each class. During training, each model is trained to distinguish one class from all other classes. During prediction, the model that outputs the highest decision function value determines the predicted class.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class OvR_SGD_SVM: def __init__(self, n_classes, lambda_=0.01, lr=0.01, epochs=10, batch_size=64): self.n_classes = n_classes self.models = [ SGDSVM(lambda_=lambda_, lr=lr, epochs=epochs, batch_size=batch_size) for _ in range(n_classes) ] def fit(self, X, y): for i in range(self.n_classes): y_binary = np.where(y == i, 1, -1) self.models[i].fit(X, y_binary) def predict(self, X): decision_values = np.array([model.predict(X) for model in self.models]) return np.argmax(decision_values, axis=0) The code below trains the OvR SGD SVM on the three-class dataset and evaluates it on the validation set in terms of accuracy.\nShow/Hide the code 1 2 3 4 ovr_svm = OvR_SGD_SVM(n_classes=3, epochs=200, lr=0.0001, lambda_=0.001) ovr_svm.fit(X, y) ovr_svm_pred = ovr_svm.predict(X_valid) print(f\u0026#34;The accuracy on validation set is {(ovr_svm_pred == y_valid).mean()*100:.2f}%\u0026#34;) The accuracy on validation set is 94.81% The figure below shows the confusion matrix of the predictions on the validation set. It can be seen that the model often confuses the digits 3 and 5, while the digit 7 is less likely to be misclassified. This makes sense because the digits 3 and 5 look more similar to each other compared to the digit 7.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 cm = confusion_matrix(y_valid, ovr_svm_pred) # Plot confusion matrix plt.figure(figsize=(5, 4)) sns.heatmap( cm, annot=True, fmt=\u0026#34;d\u0026#34;, cmap=\u0026#34;Blues\u0026#34;, xticklabels=[\u0026#34;3\u0026#34;, \u0026#34;5\u0026#34;, \u0026#34;7\u0026#34;], yticklabels=[\u0026#34;3\u0026#34;, \u0026#34;5\u0026#34;, \u0026#34;7\u0026#34;], ) plt.xlabel(\u0026#34;Predicted\u0026#34;) plt.ylabel(\u0026#34;True\u0026#34;) plt.show() Confusion Matrix of OvR SGD SVM on MNIST Validation Set Reflection and Conclusion The motivation for me choosing the SVM as the topic of this report is that unlike other gradient based models that highly rely on numerical optimization and experience in tuning hyperparameters, SVM has a solid theoretical foundation and can be solved analytically. This makes it a little bit harder to understand than other models, but also more interesting. It intimidated me in the first semester when I learned it in the fundamental data analytics course. The concepts and terminologies from optimization theory like convex optimization, lagrange duality, and so forth stopped me from going through the underlying principles of SVM. Therefore, I decided to take a deep dive into SVM in this report.\nAlong the way, I learned basic knowledge about convex optimization and reviewed some rusty concepts from linear algebra. The biggest challenge for me is to understand the mathematical derivations from the primal problem to the dual problem, because it involves a lot of summation operations. Another challenge is to derive and implement the SMO algorithm, which also involves a lot of calculations, and the implementation of SMO requires handling many details, such as dealing with edge cases. In this process, Bishop (2006), Platt (1998) and James et al. (2023) are very helpful to me. The conclusions and inferences used in this report are mainly based on these references. AI is also employed to answer some specific questions, assist in writing some code and translation. The link of the conversation with AI can be found in appendix.\nThe limitation of this report is that it only covers the linear SVM, while in practice, kernel SVM is commonly used. It is also worth mentioning that the implementation of SMO in this report is not optimized for efficiency. During training, it takes forever to converge on the whole MNIST dataset. In practice, libraries like LIBSVM and scikit-learn have highly optimized implementations of SVM that can handle large datasets efficiently.\nIn conclusion, this report provides a comprehensive overview of the principles and implementation of SVM. It covers both hard margin and soft margin SVM, as well as multi-class classification using the OvR strategy. Through theoretical analysis and practical experiments, it demonstrates the effectiveness of SVM in handling classification tasks.\nReferences Bishop, C. M. (2006). Pattern recognition and machine learning. Springer.\nJames, G., Witten, D., Hastie, T., Tibshirani, R., \u0026amp; Taylor, J. (2023). Support Vector Machines. In An Introduction to Statistical Learning (pp. 367\u0026ndash;398). Springer International Publishing. https://doi.org/10.1007/978-3-031-38747-0_9\nPlatt, J. (1998). Sequential Minimal Optimization: A Fast Algorithm for Training Support Vector Machines (MSR-TR-98-14). Microsoft. https://www.microsoft.com/en-us/research/publication/sequential-minimal-optimization-a-fast-algorithm-for-training-support-vector-machines/\nAppendix The jupyter notebook for the visualizations and the implementations of the models in this report can be found at here. This report is written in Quarto markdown. The source code of this report can be found at here. This report uses quarto titlepages theme, which can be found here. The picture on the cover page is from here. ","date":"2025-10-09T09:52:05+11:00","image":"/posts/a-study-on-support-vector-machines/index.png","permalink":"/posts/a-study-on-support-vector-machines/","title":"A Study on Support Vector Machines"},{"content":"座位问题 设想一个房间中有 10 把椅子, 现在有 6 个人准备随机地在房间中选择一把椅子落座。已知有 4 把椅子在前排, 求前排椅子被坐满的概率。\n方法一：排列视角 一种思路是将这个问题看成是一个排列问题, 即考虑每个人落座的顺序。那么样本空间的大小（Total number of outcomes）为：\n$$ {}_{10}P_{6} $$下面只要计算在所有这些情况中, 满足\u0026quot;前排 4 把椅子被坐满\u0026quot;这一条件的排列数即可。\n可以认为有 3 个步骤：\n从 6 个人中随机抽取 4 个人, 有 \\(\\binom{6}{4}\\) 种可能。 将这 4 个人安排到前排的 4 把椅子上, 共有 \\(4!\\) 种排列。 待这 4 个人选定之后, 剩下的 2 个人从剩下的 6 把椅子中随机选择 2 个落座, 共有 \\({}_{6}P_{2}\\) 种排列。 根据乘法原理, 满足条件的排列总数为：\n$$ \\binom{6}{4}\\times 4!\\times {}_{6}P_{2} = {}_{6}P_{4}\\times {}_{6}P_{2} $$概率为两者相除：\n$$ \\frac{{}_{6}P_{4}\\times {}_{6}P_{2}}{{}_{10}P_{6}} = \\frac{\\frac{6!}{2!}\\times\\frac{6!}{4!}}{\\frac{10!}{4!}} = \\frac{6\\times 5\\times 4\\times 3}{10\\times 9\\times 8\\times 7} = \\frac{1}{14} $$方法二：组合视角 从另一个视角来看, 还有更简单的办法。不管怎么选, 结果都是从 10 把椅子中选出 6 把被占据, 因此样本空间的大小为 \\(\\binom{10}{6}\\)。\n那么这其中有多少种情况包括了前排的 4 把椅子呢？既然前面的 4 把椅子必然被选出, 那么只需要从剩下的 6 把中再选出 2 把即可, 也就是 \\(\\binom{6}{2}\\)。\n概率为：\n$$ \\frac{\\binom{6}{2}}{\\binom{10}{6}} $$由于在计算样本空间时就没有考虑顺序问题, 因此在计算事件数时也无需考虑落座时的顺序。\n使用 Python 验证两次计算是否一致：\nShow/Hide the code 1 2 3 4 5 6 import math # 方法一 vs 方法二 res1 = 1/14 res2 = math.comb(6, 2) / math.comb(10, 6) print(f\u0026#34;方法一: {res1}\\n方法二: {res2}\u0026#34;) 方法一: 0.07142857142857142 方法二: 0.07142857142857142 分组问题 设想, 现在要将 4 个人平均地分为 {A, B} 两组。共有多少种分法？\n有标签分组（分配问题） 由于是分组, 小组内部的顺序不重要。假如 4 个人是 a, b, c, d, 那么 {{a, b}, {c, d}} 和 {{b, a}, {d, c}} 是同一种分组。\n但是, 这里小组之间的顺序是重要的（有标签）, 因为我们明确区分了 A 组和 B 组。因此 A={a, b}, B={c, d} 和 A={c, d}, B={a, b} 是不同的分法。\n从 4 个人中随机抽取 2 人分到 A 组, 那么剩下的人自然就组成了 B 组, 共有 \\(\\binom{4}{2}\\) 种分法。\n无标签分组（平均分组问题） 如果不区分小组标签呢？也就是说现在是\u0026quot;无标签\u0026quot;地分组, 那么 {{a, b}, {c, d}} 和 {{c, d}, {a, b}} 就是完全相同的分组方式。\n此时分组数量显然会减少。由于 {A, B} 和 {B, A} 对应同一种分组, 导致了重复。当不考虑 \\(k\\) 个组的顺序时, 数量需要除以 \\(k!\\)。在本例中, 有 2 个大小相同的组, 因此最终结果为：\n$$ \\frac{\\binom{4}{2}}{2!} $$另一种思路是先计算所有人全排列有多少种可能, 再逐渐加入限制（消序）。\n4 个人全排列：\\(4!\\) 消除第 1 组内部顺序：除以 \\(2!\\) 消除第 2 组内部顺序：除以 \\(2!\\) 消除组与组之间的顺序：除以 \\(2!\\) 最终结果为：\n$$ \\frac{4!}{2!\\times 2!\\times 2!} $$验证两种方法的结果：\nShow/Hide the code 1 2 3 import math print(f\u0026#34;方法一: {math.comb(4,2)/2}\\n方法二: {math.factorial(4)/ (2**3)}\u0026#34;) 方法一: 3.0 方法二: 3.0 混合分组（局部平均） 如果是人数不等的分组, 通常无需考虑小组之间的排序。但如果存在部分小组人数相同的情况, 则仍需去除这些相同大小小组之间的顺序。\n例如, 将 5 个人无标签地分为 3 组, 人数为 {2, 2, 1}。\n先从 5 人中选 1 人独立成组（大小为 1 的组只有 1 个, 无需消序）：\\(\\binom{5}{1}\\)。 再将剩下的 4 人平均分成两个 2 人组（大小为 2 的组有 2 个, 需要消序）：\\(\\frac{\\binom{4}{2}}{2!}\\)。 最终将 2 个步骤相乘：\n$$ \\binom{5}{1} \\times \\frac{\\binom{4}{2}}{2!} $$ Show/Hide the code 1 2 3 import math print((math.comb(5,1) * math.comb(4,2)) / 2) 15.0 ","date":"2025-09-18T14:27:52Z","permalink":"/posts/grouping-problems/","title":"A Study On Grouping Problems"},{"content":"Reboot to Windows Once from Linux On a dual-boot machine, you may occasionally want to reboot into Windows from Linux for a specific task—such as using a Windows-only application—and then return to Linux afterward. While GRUB allows you to choose which OS to boot, it is more convenient to have a one-time reboot option that boots directly into Windows, then automatically returns to Linux as the default on subsequent boots. This can be accomplished using efibootmgr to set the next boot entry to Windows.\nShow/Hide the code 1 sudo efibootmgr -n \u0026lt;WindowsBootEntryNumber\u0026gt; Here, \u0026lt;WindowsBootEntryNumber\u0026gt; is the boot entry number for Windows, which you can find by running efibootmgr without any arguments. The output will list all boot entries and their numbers. For example:\nShow/Hide the code 1 2 3 4 5 6 7 BootCurrent: 0005 Timeout: 2 seconds BootOrder: 0005,0004,2001,2002,2003 Boot0001* EFI PXE 0 for IPv4 Boot0002* EFI PXE 0 for IPv6 Boot0004* Windows Boot Manager Boot0005* GRUB To set the next boot to Windows, run:\nShow/Hide the code 1 efibootmgr -n 0004 After executing this command, reboot your machine. It will boot into Windows for that session. On the next reboot, it will default back to Linux.\nCreating a Shortcut Script To streamline this process, create a simple script at /usr/local/bin/reboot2win:\nShow/Hide the code 1 2 3 4 5 #!/usr/bin/env bash # reboot2win: A script to reboot into Windows once logger -t reboot2win \u0026#34;reboot2win executed by ${SUDO_USER:-$USER}\u0026#34; # privileged command(s) below: /usr/bin/efibootmgr -n 0004 \u0026amp;\u0026amp; /usr/bin/systemctl reboot Make it executable and set ownership to root for security:\nShow/Hide the code 1 sudo chmod +x /usr/local/bin/reboot2win \u0026amp;\u0026amp; sudo chown root:root /usr/local/bin/reboot2win Now you can run sudo reboot2win to reboot into Windows once.\nMake It Even Easier with Polkit To avoid typing sudo every time, you can create a polkit rule to allow your user to run the script without a password prompt. Create a file at /etc/polkit-1/rules.d/50-reboot2win.rules with the following content:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 polkit.addRule(function (action, subject) { if (action.id == \u0026#34;org.freedesktop.policykit.exec\u0026#34;) { var program = action.lookup(\u0026#34;program\u0026#34;); if ( program == \u0026#34;/usr/local/bin/reboot2win\u0026#34; \u0026amp;\u0026amp; subject.isInGroup(\u0026#34;wheel\u0026#34;) \u0026amp;\u0026amp; subject.local \u0026amp;\u0026amp; subject.active ) { return polkit.Result.YES; } } return polkit.Result.NOT_HANDLED; }); This rule allows users in the wheel group to execute the reboot2win script without a password prompt. Adjust the group name if your user belongs to a different group.\nTo apply the rule, restart the polkit service:\nShow/Hide the code 1 sudo systemctl restart polkit Now you can simply run the following command without sudo:\nShow/Hide the code 1 pkexec /usr/local/bin/reboot2win Finally, you can add an alias or a desktop shortcut for easier access. Also, to avoid accidentally running the command, you can use a confirmation prompt dialog such as kdialog or zenity. For example, using kdialog:\nShow/Hide the code 1 bash -lc \u0026#39;kdialog --yesno \u0026#34;Are you sure you want to reboot the system?\u0026#34;\u0026#39; \u0026amp;\u0026amp; pkexec /usr/local/bin/reboot2win This will show a confirmation dialog before executing the reboot command.\n","date":"2025-09-16T23:00:17+10:00","permalink":"/posts/one-time-reboot-to-win-shortcut/","title":"One Time Reboot to Win Shortcut"},{"content":"The shortcut Ctrl+C+C is used to look up the selected word in Goldendict and Goldendict-NG. However, this shortcut does not work properly on Wayland, because Wayland does not support the underlying function it relies on, as explained in the official documentation.\nFortunately, there is a simple workaround that is even more convenient than the original method: use wl-paste together with global shortcuts provided by desktop environments (such as KDE, GNOME, etc.).\nCreate a new shortcut in the system settings and set the shortcut to run the following command:\nShow/Hide the code 1 bash -c \u0026#39;goldendict \u0026#34;$(wl-paste -n -p)\u0026#34;\u0026#39; ","date":"2025-09-16T19:09:25+10:00","permalink":"/posts/goldendict-ng-on-wayland/","title":"Goldendict Ng on Wayland"},{"content":" Show/Hide the code 1 2 import fastbook fastbook.setup_book() Show/Hide the code 1 2 from fastai.vision.all import * path = untar_data(URLs.PETS) Show/Hide the code 1 path.ls() (#2) [Path('/root/.fastai/data/oxford-iiit-pet/annotations'),Path('/root/.fastai/data/oxford-iiit-pet/images')] Show/Hide the code 1 2 3 4 5 6 7 8 9 pets = DataBlock( blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, splitter=RandomSplitter(seed=42), get_y=using_attr(RegexLabeller(r\u0026#34;(.+)_\\d+.jpg$\u0026#34;), \u0026#34;name\u0026#34;), item_tfms=Resize(460), batch_tfms=aug_transforms(size=224, min_scale=0.75), ) dls = pets.dataloaders(path/\u0026#34;images\u0026#34;) Show/Hide the code 1 dls.show_batch(nrows=3, ncols=3) Show/Hide the code 1 2 learn = cnn_learner(dls, resnet34, metrics=error_rate) learn.fine_tune(2) Downloading: \u0026quot;https://download.pytorch.org/models/resnet34-b627a593.pth\u0026quot; to /root/.cache/torch/hub/checkpoints/resnet34-b627a593.pth epoch train_loss valid_loss error_rate time 0 1.497884 0.302666 0.087280 01:02 epoch train_loss valid_loss error_rate time 0 0.494630 0.309310 0.099459 01:04 1 0.310687 0.254076 0.084574 01:06 Show/Hide the code 1 x, y = dls.one_batch() Show/Hide the code 1 2 preds, _ = learn.get_preds(dl = [(x,y)]) torch.argmax(preds[0]) tensor(10) Show/Hide the code 1 2 acts = torch.randn((6,2))*2 acts tensor([[ 0.2126, -0.6733], [ 0.5868, 1.8977], [-1.5544, 0.4964], [-0.5226, -0.6044], [ 0.4885, -0.1626], [-3.0538, -2.0372]]) Show/Hide the code 1 acts.sigmoid().sum(1).unsqueeze(1) tensor([[0.8907], [1.5123], [0.7961], [0.7256], [1.0792], [0.1604]]) Show/Hide the code 1 (acts[:,0]-acts[:,1]).sigmoid().unsqueeze(1) tensor([[0.7080], [0.2123], [0.1140], [0.5204], [0.6573], [0.2657]]) Show/Hide the code 1 2 def softmax(x): return torch.exp(x) / torch.exp(x).sum(dim=1, keepdim=True) sm_acts = softmax(acts) Show/Hide the code 1 sm_acts tensor([[0.7080, 0.2920], [0.2123, 0.7877], [0.1140, 0.8860], [0.5204, 0.4796], [0.6573, 0.3427], [0.2657, 0.7343]]) Show/Hide the code 1 2 targ = tensor([0,1,0,0,1,1]) sm_acts[range(6),targ].unsqueeze(1) tensor([[0.7080], [0.7877], [0.1140], [0.5204], [0.3427], [0.7343]]) Show/Hide the code 1 -sm_acts[range(6),targ].log().mean() tensor(0.7981) Show/Hide the code 1 F.nll_loss(acts.log_softmax(dim=1), targ) tensor(0.7981) Show/Hide the code 1 2 loss_func = nn.CrossEntropyLoss(reduction=\u0026#39;none\u0026#39;) loss_func(acts, targ) tensor([0.3452, 0.2387, 2.1718, 0.6531, 1.0708, 0.3088]) Show/Hide the code 1 2 interp = ClassificationInterpretation.from_learner(learn) interp.plot_confusion_matrix(figsize=(12,12), dpi=60) Show/Hide the code 1 interp.most_confused(min_val=5) [('american_pit_bull_terrier', 'staffordshire_bull_terrier', np.int64(12)), ('Birman', 'Ragdoll', np.int64(7)), ('Egyptian_Mau', 'Bengal', np.int64(5)), ('american_pit_bull_terrier', 'american_bulldog', np.int64(5))] Show/Hide the code 1 2 learn = vision_learner(dls, resnet34, metrics=error_rate) learn.lr_find() SuggestedLRs(valley=0.001737800776027143) Show/Hide the code 1 2 learn = vision_learner(dls, resnet34, metrics=error_rate) learn.fine_tune(2, base_lr=3e-3) epoch train_loss valid_loss error_rate time 0 1.330929 0.305042 0.089986 01:07 epoch train_loss valid_loss error_rate time 0 0.523440 0.362486 0.104871 01:10 1 0.327184 0.269103 0.080514 01:06 Show/Hide the code 1 2 learn = vision_learner(dls, resnet34, metrics=error_rate) learn.fit_one_cycle(3, 3e-2) epoch train_loss valid_loss error_rate time 0 2.357152 3.695568 0.578484 00:12 1 1.188880 0.541915 0.169824 00:11 2 0.660204 0.358833 0.108931 00:11 Show/Hide the code 1 learn.unfreeze() Show/Hide the code 1 learn.lr_find() SuggestedLRs(valley=3.630780702224001e-05) Show/Hide the code 1 learn.fit_one_cycle(6, lr_max=1e-6) epoch train_loss valid_loss error_rate time 0 0.474540 0.356742 0.108931 00:12 1 0.472879 0.353283 0.110284 00:12 2 0.471576 0.347057 0.103518 00:12 3 0.464339 0.345362 0.100812 00:12 4 0.468930 0.342762 0.106225 00:12 5 0.452638 0.343595 0.103518 00:12 Show/Hide the code 1 2 3 4 learn = vision_learner(dls, resnet34, metrics=error_rate) learn.fit_one_cycle(3, 3e-3) learn.unfreeze() learn.fit_one_cycle(12, lr_max=slice(1e-6, 1e-4)) epoch train_loss valid_loss error_rate time 0 1.127102 0.334892 0.097429 00:11 1 0.518909 0.252394 0.085927 00:11 2 0.327980 0.218656 0.075778 00:11 epoch train_loss valid_loss error_rate time 0 0.243455 0.213250 0.074425 00:12 1 0.233122 0.212131 0.073748 00:12 2 0.220011 0.202811 0.063599 00:12 3 0.220371 0.196318 0.062923 00:12 4 0.191108 0.200352 0.064953 00:12 5 0.166688 0.201582 0.066982 00:12 6 0.155857 0.196664 0.062923 00:12 7 0.138741 0.190374 0.060217 00:12 8 0.118107 0.192674 0.067659 00:12 9 0.130965 0.191735 0.065629 00:12 10 0.124963 0.191818 0.066982 00:12 11 0.122479 0.191197 0.064276 00:12 Show/Hide the code 1 learn.recorder.plot_loss() Show/Hide the code 1 2 3 from fastai.callback.fp16 import * learn = vision_learner(dls, resnet50, metrics=error_rate).to_fp16() learn.fine_tune(6, freeze_epochs=3) Downloading: \u0026quot;https://download.pytorch.org/models/resnet50-11ad3fa6.pth\u0026quot; to /root/.cache/torch/hub/checkpoints/resnet50-11ad3fa6.pth epoch train_loss valid_loss error_rate time 0 2.191112 0.475555 0.154263 00:14 1 0.829924 0.294044 0.100812 00:13 2 0.550020 0.291130 0.096752 00:13 epoch train_loss valid_loss error_rate time 0 0.305628 0.236669 0.073748 00:14 1 0.242062 0.278092 0.081867 00:14 2 0.209351 0.231892 0.069689 00:14 3 0.133353 0.220406 0.064276 00:14 4 0.089182 0.202463 0.050744 00:14 5 0.065977 0.192152 0.052774 00:14 ","date":"2025-09-16T00:00:00Z","permalink":"/posts/deep-learning-for-coder-chapter-5/","title":"Deep Learning for Coder: Chapter 5"},{"content":"When writing code within lists like the following structure, quarto cannot render the list properly.\nShow/Hide the code 1 2 3 4 5 6 7 1. question answer ```{python} print() ``` The trick is to add an extra space after single-digit list indexes. This is because indentation is significant in Quarto, and both the list itself and any nested code blocks must start in the same column (note that the index itself, e.g., 1., 2., etc., does not count toward the list indentation).\nFor example, in my VSCode setup, pressing Tab inserts four spaces, but there are only use three characters before a list with single-digit indexes (e.g., 1. ). As a result, when I try to indent a code block under such a list, it doesn’t align correctly with the list column. Adding an extra space after the index ensures proper alignment.\nIn addition, unlike code blocks, which must be strictly aligned with the list, other lines (non-code content) should be indented at least as much as the list and code blocks.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 1. question 1 answer 1 (work) answer 1 (work) answer 1 (doesn\u0026#39;t work) ```{python} # some code ``` https://forum.posit.co/t/code-chunks-within-lists-in-quarto/159866\n","date":"2025-09-14T14:41:04+10:00","permalink":"/posts/code-chunks-within-lists-in-quarto/","title":"Code Chunks Within Lists in Quarto"},{"content":"Environment Set-up Show/Hide the code 1 2 3 4 5 6 import fastbook from fastai.vision.all import * from fastbook import * fastbook.setup_book() matplotlib.rc(\u0026#34;image\u0026#34;, cmap=\u0026#34;Greys\u0026#34;) Load The Two Classes of Data Show/Hide the code 1 2 3 path = untar_data(URLs.MNIST_SAMPLE) Path.BASE_PATH = path path.ls() (#3) [Path('train'),Path('valid'),Path('labels.csv')] Show/Hide the code 1 2 3 4 5 threes = [tensor(Image.open(i)) for i in (path / \u0026#34;train\u0026#34; / \u0026#34;3\u0026#34;).ls()] sevens = [tensor(Image.open(i)) for i in (path / \u0026#34;train\u0026#34; / \u0026#34;7\u0026#34;).ls()] threes_valid = [tensor(Image.open(i)) for i in (path / \u0026#34;valid\u0026#34; / \u0026#34;3\u0026#34;).ls()] sevens_valid = [tensor(Image.open(i)) for i in (path / \u0026#34;valid\u0026#34; / \u0026#34;7\u0026#34;).ls()] len(threes), len(sevens) (6131, 6265) Show/Hide the code 1 2 3 4 5 threes = torch.stack(threes).float() / 255 sevens = torch.stack(sevens).float() / 255 threes_valid = torch.stack(threes_valid).float() / 255 sevens_valid = torch.stack(sevens_valid).float() / 255 threes.shape, sevens.shape (torch.Size([6131, 28, 28]), torch.Size([6265, 28, 28])) Non-Parametric Method Calculate an \u0026ldquo;average three\u0026rdquo;\nShow/Hide the code 1 2 mean3 = threes.mean(0) show_image(mean3) Calculate an \u0026ldquo;average seven\u0026rdquo;\nShow/Hide the code 1 2 mean7 = sevens.mean(0) show_image(mean7) Define a function that computes distance between two images and a function that judges if an image is three.\nShow/Hide the code 1 2 3 4 5 6 def distance(a, b): return (a - b).abs().mean((-1, -2)) def is_3(x): return distance(x, mean3) \u0026lt; distance(x, mean7) Compute how many threes are correctly classified into class three and how many seven are correctly classified into seven. (accuracy)\nShow/Hide the code 1 is_3(threes_valid).float().mean(), (1 - is_3(sevens_valid).float()).float().mean() (tensor(0.9168), tensor(0.9854)) Compute overall how many images are correctly classified.\nShow/Hide the code 1 2 3 4 5 x = torch.cat([threes_valid, sevens_valid]) y = tensor([1] * len(threes_valid) + [0] * len(sevens_valid)) x.shape, y.shape # ((distance(x, mean3) \u0026lt; distance(x, mean7)).float() == y).float().mean() (torch.Size([2038, 28, 28]), torch.Size([2038])) Linear Function and SGD Show/Hide the code 1 2 3 4 5 train_x = torch.cat([threes, sevens]).view([-1, 28 * 28]) train_y = tensor([1] * len(threes) + [0] * len(sevens)).unsqueeze(-1) valid_x = torch.cat([threes_valid, sevens_valid]).view([-1, 28 * 28]) valid_y = tensor([1] * len(threes_valid) + [0] * len(sevens_valid)).unsqueeze(-1) train_x.shape, train_y.shape, valid_x.shape, valid_y.shape (torch.Size([12396, 784]), torch.Size([12396, 1]), torch.Size([2038, 784]), torch.Size([2038, 1])) Show/Hide the code 1 2 3 4 5 6 dset = list(zip(train_x, train_y)) dset_valid = list(zip(valid_x, valid_y)) dset[0][0].shape, dset[0][1].shape dl = DataLoader(dset, batch_size=256, shuffle=true) valid_dl = DataLoader(dset_valid, batch_size=256, shuffle=true) Differentiate unsqueeze, cat and stack:\ncat and stack operate on multiple tensors, combining them into a single tensor, whereas unsqueeze operates on a single tensor. unsqueeze and stack introduce a new dimension to the tensor(s), while cat does not create new dimensions. stack inserts a new dimension at the specified position, and its length equals the number of tensors being stacked. cat concatenates tensors along a specified dimension, and the resulting dimension\u0026rsquo;s length is the sum of the lengths of all tensors along that dimension. unsqueeze always inserts a new dimension of length 1 at the specified position. For example:\nShow/Hide the code 1 2 a, b = tensor([[1, 2, 3], [4, 5, 6]]), tensor([[7, 8, 9], [1, 2, 1]]) a.shape, b.shape (torch.Size([2, 3]), torch.Size([2, 3])) Show/Hide the code 1 a, b (tensor([[1, 2, 3], [4, 5, 6]]), tensor([[7, 8, 9], [1, 2, 1]])) cat these two tensors results in a tensor with a shape of either (4, 3) or (2, 6)\nShow/Hide the code 1 torch.cat([a, b], 0).shape, torch.cat([a, b], 1).shape (torch.Size([4, 3]), torch.Size([2, 6])) stack these two tensors results in a tensor with a shape of either (2, 2, 3) or (2, 3, 2)\nShow/Hide the code 1 torch.stack([a, b], 0).shape, torch.stack([a, b], 1).shape, torch.stack([a, b], 2).shape (torch.Size([2, 2, 3]), torch.Size([2, 2, 3]), torch.Size([2, 3, 2])) Note: although torch.stack([a, b], 0) and torch.stack([a, b], 1) produce tensors with the same shape, they have different content.\n$$ \\begin{matrix} [1 \u0026 2 \u0026 3] \\\\ [4 \u0026 5 \u0026 6] \\end{matrix} \\quad \\begin{matrix} [7 \u0026 8 \u0026 9] \\\\ [1 \u0026 2 \u0026 1] \\end{matrix} $$torch.stack([a, b], 0) means stack whole matrices:\n$$ \\left[ \\begin{matrix} [1 \u0026 2 \u0026 3] \\\\ [4 \u0026 5 \u0026 6] \\end{matrix} \\right] , \\left[ \\begin{matrix} [7 \u0026 8 \u0026 9] \\\\ [1 \u0026 2 \u0026 1] \\end{matrix} \\right] $$torch.stack([a, b], 1) means stack rows:\n$$ \\begin{matrix} \\textbf{[}[1 \u0026 2 \u0026 3]\\quad[7 \u0026 8 \u0026 9]\\textbf{]},\\\\ \\\\ \\textbf{[}[4 \u0026 5 \u0026 6]\\quad[1 \u0026 2 \u0026 1]\\textbf{]} \\end{matrix} $$torch.stack([a, b], 2) means stack columns.\nShow/Hide the code 1 torch.stack([a, b], 0), torch.stack([a, b], 1) (tensor([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [1, 2, 1]]]), tensor([[[1, 2, 3], [7, 8, 9]], [[4, 5, 6], [1, 2, 1]]])) Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 def sigmoid(logits): return 1 / (1 + torch.exp(-logits)) def mnist_loss(logits, targets): probs = logits.sigmoid() # return ((probs - targets) ** 2).mean().sqrt() return torch.where(targets == 1, 1 - probs, probs).mean() def calc_grad(x, y, f): preds = f(x) loss = mnist_loss(preds, y) loss.backward() def train_epoch(f, params, lr): for xb, yb in dl: calc_grad(xb, yb, f) for p in params: with torch.no_grad(): p -= lr * p.grad p.grad.zero_() def batch_accuracy(logits, yb): probs = logits.sigmoid() return ((probs \u0026gt; 0.5) == yb).float().mean() def validation_epoch(f): accs = [batch_accuracy(f(xb), yb) for xb, yb in valid_dl] return round(torch.stack(accs).mean().item(), 4) Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def init_params(size, std=1.0): return (torch.randn(size) * std).requires_grad_() # column vector weights = init_params((28 * 28, 1)) bias = init_params(1) def linear(x): return x @ weights + bias for i in range(20): train_epoch(linear, (weights, bias), 1e-1) print(validation_epoch(linear)) 0.5922 0.661 0.7257 0.7738 0.81 0.8296 0.8471 0.8597 0.8704 0.8812 0.8907 0.8976 0.9034 0.9107 0.9152 0.9176 0.924 0.9274 0.9302 0.9322 Optimizer Show/Hide the code 1 2 3 linear_model = nn.Linear(28 * 28, 1) w, b = linear_model.parameters() w.shape, b.shape (torch.Size([1, 784]), torch.Size([1])) Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class BasicOptimizer: def __init__(self, params, lr): self.params = list(params) self.lr = lr def step(self, *args, **kwargs): for p in self.params: with torch.no_grad(): p -= self.lr * p.grad def zero_grad(self, *args, **kwargs): for p in self.params: p.grad = None opt = BasicOptimizer(linear_model.parameters(), 1e-2) def train_epoch(model): for xb, yb in dl: calc_grad(xb, yb, model) opt.step() opt.zero_grad() validation_epoch(linear_model) 0.5231 Show/Hide the code 1 2 3 for i in range(20): print(validation_epoch(linear_model)) train_epoch(linear_model) 0.5228 0.9509 0.9628 0.9633 0.9643 0.9646 0.9666 0.9667 0.9657 0.9667 0.9666 0.9667 0.967 0.9672 0.9672 0.9675 0.9677 0.9676 0.9676 0.9686 Show/Hide the code 1 2 3 4 5 linear_model = nn.Linear(28 * 28, 1) opt = SGD(linear_model.parameters(), 1.0) for i in range(20): train_epoch(linear_model) print(validation_epoch(linear_model)) 0.9706 0.975 0.977 0.9764 0.9779 0.9784 0.9784 0.9794 0.9799 0.9789 0.9803 0.9804 0.9813 0.9809 0.9814 0.9819 0.9824 0.9819 0.9818 0.9828 Learner Show/Hide the code 1 2 3 4 5 6 7 8 9 dls = DataLoaders(dl, valid_dl) learn = Learner( dls, nn.Linear(28 * 28, 1), opt_func=SGD, loss_func=mnist_loss, metrics=batch_accuracy, ) learn.fit(10, lr=1.0) epoch train_loss valid_loss batch_accuracy time 0 0.057635 0.041314 0.971050 00:00 1 0.039915 0.034953 0.974975 00:00 2 0.032067 0.032012 0.974975 00:00 3 0.027766 0.029371 0.977429 00:00 4 0.025469 0.028556 0.977429 00:00 5 0.023680 0.027128 0.978410 00:00 6 0.022530 0.026477 0.978410 00:00 7 0.021128 0.025687 0.978410 00:00 8 0.020596 0.024973 0.978410 00:00 9 0.020155 0.024411 0.979882 00:00 Nonlinearity Show/Hide the code 1 2 3 simple_net = nn.Sequential(nn.Linear(28 * 28, 30), nn.ReLU(), nn.Linear(30, 1)) learn = Learner(dls, simple_net, mnist_loss, SGD, metrics=batch_accuracy) learn.fit(40, 0.1) epoch train_loss valid_loss batch_accuracy time 0 0.209871 0.085825 0.965653 00:00 1 0.102153 0.052868 0.968106 00:00 2 0.064107 0.043419 0.970069 00:00 3 0.047004 0.038965 0.970559 00:00 4 0.038722 0.036753 0.972522 00:00 5 0.033846 0.034248 0.972522 00:00 6 0.030684 0.032698 0.973994 00:00 7 0.028295 0.031133 0.975957 00:00 8 0.026498 0.030240 0.974975 00:00 9 0.025480 0.029235 0.975957 00:00 10 0.024493 0.028573 0.976938 00:00 11 0.023539 0.028091 0.976448 00:00 12 0.022644 0.027519 0.976938 00:00 13 0.021782 0.026868 0.977429 00:00 14 0.021953 0.026348 0.977920 00:00 15 0.021738 0.025783 0.978901 00:00 16 0.021042 0.025252 0.979392 00:00 17 0.020344 0.024917 0.978901 00:00 18 0.019776 0.024747 0.978901 00:00 19 0.019557 0.024295 0.978901 00:00 20 0.019418 0.024097 0.978901 00:00 21 0.018741 0.023782 0.978901 00:00 22 0.018383 0.023266 0.979392 00:00 23 0.018047 0.023283 0.979882 00:00 24 0.017762 0.023139 0.979882 00:00 25 0.017672 0.022712 0.979882 00:00 26 0.017658 0.022521 0.980864 00:00 27 0.017558 0.022226 0.980864 00:00 28 0.017126 0.022203 0.980864 00:00 29 0.017070 0.021634 0.980864 00:00 30 0.016443 0.021636 0.981354 00:00 31 0.016697 0.021468 0.981354 00:00 32 0.016811 0.021725 0.981845 00:00 33 0.016300 0.021180 0.982336 00:00 34 0.016316 0.021147 0.981845 00:00 35 0.015825 0.020846 0.982336 00:00 36 0.015894 0.020525 0.982336 00:00 37 0.015442 0.020475 0.982336 00:00 38 0.015356 0.020404 0.982336 00:00 39 0.015186 0.020286 0.982336 00:00 Deeper Show/Hide the code 1 2 3 4 5 dls = ImageDataLoaders.from_folder(path) learn = vision_learner( dls, resnet18, pretrained=False, loss_func=F.cross_entropy, metrics=accuracy ) learn.fit_one_cycle(1, 0.1) epoch train_loss valid_loss accuracy time 0 0.059510 0.017087 0.992640 00:12 Questionnaire How is a grayscale image represented on a computer? How about a color image?\neach pixel is represented by a number from 0 to 255. 0 represents black and 255 represents white. pixels of color image are represented by three colors: red, green and blue (RGB).\nHow are the files and folders in the MNIST_SAMPLE dataset structured? Why?\ntree structure\nExplain how the \u0026ldquo;pixel similarity\u0026rdquo; approach to classifying digits works.\nmean3 and mean7 can be considered as \u0026ldquo;standard shapes\u0026rdquo;. if the average distance between an image\u0026rsquo;s pixels and mean3\u0026rsquo;s pixels is smaller, it is probably a three and vice versa.\nWhat is a list comprehension? Create one now that selects odd numbers from a list and doubles them.\nCreate a python list within one line.\nShow/Hide the code 1 2 l = [1, 4, 3, 6, 8, 9, 10, 3, 4] [i * 2 for i in l if i % 2 != 0] [2, 6, 18, 6] What is a \u0026ldquo;rank-3 tensor\u0026rdquo;?\na tensor that has three dimensions, for example:\nShow/Hide the code 1 [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] What is the difference between tensor rank and shape? How do you get the rank from the shape?\nrank is the length of shape, len(shape).\nWhat are RMSE and L1 norm?\nRMSE uses square power to avoid cancelling out while L1 norm uses absolute value to do so.\nHow can you apply a calculation on thousands of numbers at once, many thousands of times faster than a Python loop?\nUsing np.array or tensor and broadcasting\nCreate a 3×3 tensor or array containing the numbers from 1 to 9. Double it. Select the bottom-right four numbers.\nShow/Hide the code 1 2 3 4 5 6 import numpy as np a = np.arange(1, 10).reshape(3, 3) print(a) a = a * 2 print(a[-2:, -2:]) [[1 2 3] [4 5 6] [7 8 9]] [[10 12] [16 18]] What is broadcasting?\nAre metrics generally calculated using the training set, or the validation set? Why?\nthey are generally calculated using the validation set because it refects the generalization ability of a model\nWhat is SGD?\nstochastic: stochastically sample batchs from the dataset gradient: update parameters according to its gradient descent: the loss function is convex thus finding minimum descenting\nWhy does SGD use mini-batches?\nUsing the whole dataset is computationally expensive and using on data point results in unstable gradient. Using mini-batches is a compromise between them.\nWhat are the seven steps in SGD for machine learning?\nHow do we initialize the weights in a model?\nrandomly\nWhat is \u0026ldquo;loss\u0026rdquo;?\nloss funtions measure the difference between a model\u0026rsquo;s predictions and the true target values. It provides a quantitative way to evaluate how well a model is performing. lower loss means better performance.\nWhy can\u0026rsquo;t we always use a high learning rate?\nbecause it my cause the optimization process to overshoot the minimum. In extreme cases, the loss even increase or diverge instead of decreasing.\nWhat is a \u0026ldquo;gradient\u0026rdquo;?\nDo you need to know how to calculate gradients yourself?\nNo, I don\u0026rsquo;t. Even though I know.\nWhy can\u0026rsquo;t we use accuracy as a loss function?\nbecause accuracy is not a continuous function with respect to the model\u0026rsquo;s parameters, which means when parameters\u0026rsquo; value shift a bit, the accuracy won\u0026rsquo;t change, preventing calculating the gradient.\nDraw the sigmoid function. What is special about its shape?\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-x)) plt.plot(np.arange(-3, 3, 0.1), sigmoid(np.arange(-3, 3, 0.1))) plt.show() Its domain is \\((-\\infty, +\\infty)\\), and its range is \\((0, 1)\\). This means it squashes any real value into the interval \\((0, 1)\\), which makes it suitable for representing probabilities.\nWhat is the difference between a loss function and a metric?\nthe loss function is used for the model while a metric should be meaingful for humans.\nWhat is the function to calculate new weights using a learning rate?\nWhat does the DataLoader class do?\nWrite pseudocode showing the basic steps taken in each epoch for SGD.\nCreate a function that, if passed two arguments [1,2,3,4] and 'abcd', returns [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]. What is special about that output data structure?\nWhat does view do in PyTorch?\nWhat are the \u0026ldquo;bias\u0026rdquo; parameters in a neural network? Why do we need them?\nWhat does the @ operator do in Python?\nWhat does the backward method do?\nWhy do we have to zero the gradients?\nWhat information do we have to pass to Learner?\nShow Python or pseudocode for the basic steps of a training loop.\nWhat is \u0026ldquo;ReLU\u0026rdquo;? Draw a plot of it for values from -2 to +2.\nWhat is an \u0026ldquo;activation function\u0026rdquo;?\nWhat\u0026rsquo;s the difference between F.relu and nn.ReLU?\nThe universal approximation theorem shows that any function can be approximated as closely as needed using just one nonlinearity. So why do we normally use more?\n","date":"2025-09-11T14:56:41+10:00","permalink":"/posts/deep-learning-for-coder-chapter-4/","title":"Deep Learning for Coder: Chapter 4"},{"content":"The Explanation of Function B \\(B(N, k)\\) denotes the maximum number of dichotomies on \\(N\\) points, with break point \\(k\\). For example, \\(B(1000, 4)\\) denotes the number of dichotomies that a 2-dimensional perceptron can make on 1000 data points.\nNote: A 2-dimensional perceptron has a break point of 4, which means a 2-dimensional perceptron cannot offer all dichotomies on 4 points.\nThe Recursive Function B For a dataset with \\(N\\) data points, the total number of possible dichotomies is \\(2^N\\), because each data point has two possible classifications. In this case, the growth rate of the number of dichotomies is an exponential function of \\(N\\). However, due to the existence of a break point, the actual growth rate becomes a polynomial function of \\(N\\), with the degree of the polynomial related to \\(k\\).\nReasoning Process: We divide the \\(B(N,k)\\) dichotomies into two categories based on the following rule: if we ignore the last data point (the \\(N\\)-th data point), are the dichotomies of the first \\(N-1\\) data points unique?\nDichotomies that are unique go into Class A. Dichotomies that are repeated go into Class B. For example, suppose a dataset has three data points and an algorithm generates four classification methods: 1,0,1, 1,0,0, 0,0,1, 0,1,1. Ignoring the last data point, there are two repeated patterns (1,0) and two unique patterns (0,0 and 0,1).\nBy definition, Classes A and B are disjoint, and their union is the original set (because each pattern is either unique or repeated).\nLet \\(\\alpha\\) be the number of dichotomies in Class A.\nSince each dichotomy in Class B is repeated exactly twice (the \\(N\\)-th data point has two possibilities), let the number of dichotomies in B be \\(2\\beta\\).\nThus:\n$$ B(N,k) = \\alpha + 2\\beta $$Also, \\(\\alpha + \\beta\\) represents the total number of unique dichotomies for the first \\(N-1\\) data points, so:\n$$ \\alpha + \\beta \\le B(N-1,k) $$The break point of B is \\(k-1\\). This is because if there were \\(k-1\\) columns in B that cover all possible binary patterns, then adding the \\(N\\)-th data point would create \\(k\\) columns that cover all possible binary patterns.\nFor example, if \\(k=4\\), meaning that among all dichotomies, any 4 columns cannot form all binary patterns, and suppose B contains 3 columns:\n0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 After adding one more data point, we can find 4 columns that cover all possible binary patterns:\n0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1 0 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1 1 Thus, B cannot have \\(k-1\\) columns covering all binary patterns, meaning the break point is at most \\(k-1\\).\nTherefore:\n$$ \\beta \\le B(N-1, k-1) $$Combining the above, we obtain:\n$$ B(N,k) = \\alpha + 2\\beta \\le B(N-1,k) + B(N-1, k-1) $$The Implementation of Recursive Function B Show/Hide the code 1 2 3 4 5 6 7 8 9 def B(N, k): if k \u0026lt;= 0 or N \u0026lt;= 0: return 0 if k == 1: return 1 if N == 1: return 2 return B(N - 1, k) + B(N - 1, k - 1) The Table of Function B Show/Hide the code 1 2 3 4 5 6 7 8 9 print(\u0026#34;\\t\u0026#34;, end=\u0026#34;\u0026#34;) for i in range(1, 11): print(f\u0026#34;k={i}\u0026#34;, end=\u0026#34;\\t\u0026#34;) print(\u0026#34;\\n\u0026#34;) for i in range(1, 11): print(f\u0026#34;N={i}\u0026#34;, end=\u0026#39;\\t\u0026#39;) for j in range(1, 11): print(B(i, j), end=\u0026#34;\\t\u0026#34;) print(\u0026#34;\\n\u0026#34;) k=1 k=2 k=3 k=4 k=5 k=6 k=7 k=8 k=9 k=10 N=1 1 2 2 2 2 2 2 2 2 2 N=2 1 3 4 4 4 4 4 4 4 4 N=3 1 4 7 8 8 8 8 8 8 8 N=4 1 5 11 15 16 16 16 16 16 16 N=5 1 6 16 26 31 32 32 32 32 32 N=6 1 7 22 42 57 63 64 64 64 64 N=7 1 8 29 64 99 120 127 128 128 128 N=8 1 9 37 93 163 219 247 255 256 256 N=9 1 10 46 130 256 382 466 502 511 512 N=10 1 11 56 176 386 638 848 968 1013 1023 A Theorem $$ B(N,k) \\le \\sum_{i=0}^{k-1}{\\binom{N}{i}} $$ Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 import math import numpy as np def binomial(N, i): if N \u0026lt; i: return 0 return int(math.factorial(N) / (math.factorial(i) * math.factorial(N - i))) def B(N, k): return np.sum([binomial(N, i) for i in range(0, k)]) Goal:\n$$ \\sum_{i=0}^{k-1}{\\binom{N}{i}}=\\sum_{i=0}^{k-1}{\\binom{N-1}{i}}+\\sum_{i=0}^{k-2}{\\binom{N-1}{i}} $$Steps:\n$$ \\begin{align} \u0026\\sum_{i=0}^{k-1}{\\binom{N-1}{i}}+\\sum_{i=0}^{k-2}{\\binom{N-1}{i}} \\nonumber \\\\ \u0026=1 + \\sum_{i=1}^{k-1}{\\binom{N-1}{i}}+\\sum_{i=1}^{k-2}{\\binom{N-1}{i-1}} \\nonumber \\\\ \u0026=1 + \\sum_{i=1}^{k-1}{\\left[\\binom{N-1}{i}+\\binom{N-1}{i-1}\\right]} \\qquad\\text{(1)} \\nonumber \\\\ \u0026=1 + \\sum_{i=1}^{k-1}{\\binom{N}{i}} \\qquad\\text{(2)} \\nonumber \\\\ \u0026=\\sum_{i=0}^{k-1}{\\binom{N}{i}} \\nonumber \\end{align} $$Note: An intuitive way to understand how (1) becomes to (2) is to consider the essence of the combination formula. The term \\(\\binom{N}{i}\\) represents the number of ways to choose \\(i\\) people from a total of \\(N\\). There are two mutually exclusive scenarios for any particular person: either they are chosen, or they are not.\nIf the person is not chosen, then we need to select all \\(i\\) people from the remaining \\(N-1\\), giving \\(\\binom{N-1}{i}\\) combinations. If the person is chosen, we have already selected one, so we only need to choose the remaining \\(i-1\\) people from the other \\(N-1\\), resulting in \\(\\binom{N-1}{i-1}\\) combinations. Together, these two cases account for all possible selections.\n","date":"2025-09-01T00:00:00Z","image":"/posts/the-theory-of-generalization-from-break-points-to-the-vc-inequality/image.png","permalink":"/posts/the-theory-of-generalization-from-break-points-to-the-vc-inequality/","title":"The Theory of Generalization: From Break Points To The Vc Inequality"},{"content":"It is really painful and annoying that the cursor color is white when the vscode using a light theme. Using mpo_disable.reg provided by Nvidia can correct this behavior. It also works for computers with AMD GPUs.\nmpo_disable.reg\n","date":"2025-08-30T09:38:32+10:00","permalink":"/posts/correct-cursor-color-on-vscode/","title":"Correct Cursor Color on Vscode"},{"content":"English In my mind, the internet is an invention that has changed the course of history. To exaggerate a little, its importance is no less than that of the First and Second Industrial Revolutions. This is because, although what the internet seems to do is simply connect existing resources for sharing, it has almost completely changed the rules of the game. Countless businesses that directly or indirectly rely on the internet have sprung up like mushrooms after the rain and grown to an astonishing scale. The way people communicate has been transformed \u0026ndash; electromagnetic waves travel at the speed of light, sending information across the globe in an instant.\nMore importantly, knowledge has become easily accessible, with almost no cost. For some reason, people seem to be obsessed with freely sharing their knowledge online. From the smallest everyday life tips to the most advanced scientific theories, from literature of all kinds to the most cutting-edge research \u0026ndash; you can find all of it on the internet, as long as you\u0026rsquo;re willing to explore. Public courses from top universities, books written by the most renowned experts in their fields \u0026ndash; you could say that if a person is willing to invest the time, they can get the best education in the world through the internet.\nOn top of that, decades of accumulated data on the internet have, after lying dormant for years, given rise to another powerful tool: AI. By training machines on the knowledge humanity has already created, AI has shocked the world with its capabilities. Its birth is not mysterious \u0026ndash; it did not come from any groundbreaking discoveries in physics, biology, or mathematics. Instead, it relies on the powerful computing capacity we already have and on the enormous datasets collected over decades, processed with specific methods of machine learning. The results are astonishing. And fundamentally, this too is directly or indirectly driven by the internet.\nIn my view, the internet is not something to be debated as useful or harmful \u0026ndash; it is simply an inevitable product of human technological progress. Its role is both immensely important and irreplaceable. The consequences it brings, whether good or bad, are things humanity must go through and adapt to.\nThat being said, at a personal level, internet use can be controlled. Protecting children and vulnerable groups from harmful content online is both necessary and urgent. The internet contains as much harmful waste as it does treasures of knowledge. That\u0026rsquo;s why guiding children to use it properly and protecting them from harmful content is the responsibility of parents or guardians. There\u0026rsquo;s an old Chinese saying I agree with: \u0026ldquo;Raising without teaching is the father\u0026rsquo;s fault.\u0026rdquo; Children are born as blank sheets of paper, and parents are the ones best positioned to write on them. Good parents should recognize their responsibility and fulfill their duty, writing on this paper through care and education, instead of neglect \u0026ndash; or worse, ruining it through scolding and violence.\nIn reality, though, even though almost every Chinese parent knows this famous saying, most of them only blame their children when they\u0026rsquo;re unhappy, without reflecting on whether they themselves have fulfilled their responsibility. For example, a child addicted to the internet or digital devices is most likely spending too much time alone \u0026ndash; time that should have been shared with parents. A teenager who smokes or drinks in school likely has parents with the same habits.\nFrom what I see, many great scholars, politicians, and entrepreneurs \u0026ndash; all those who appear successful \u0026ndash; often come from upper-class or at least harmonious families. Of course, this does not guarantee that children from such families will always become \u0026ldquo;elites\u0026rdquo;, but it does show that the family atmosphere absolutely shapes a child, and parents are the ones who set that atmosphere. So when we complain about a child being addicted to the internet, maybe we should first ask: what are the parents doing after dinner or before bed? Are they exercising, reading, and learning with their kids, or are they just as addicted to screens themselves?\nOf course, education is a very complex topic. It doesn\u0026rsquo;t only involve parents and children, but also the government, society, and schools. For many parents, spending time to accompany and educate their children might feel out of reach, because they must dedicate all their time and energy to making a living. Others may not have received good education themselves and don\u0026rsquo;t have the ability to provide a good environment for their children. That\u0026rsquo;s why I don\u0026rsquo;t want to criticize anyone. What I want to say is that we need to move past emotional blame and bias, and instead look at the root causes behind these problems if we want to solve them \u0026ndash; rather than resorting to criticism or even violence.\nAnd some of the violence that comes out of this is beyond belief. In China, there are so-called \u0026ldquo;internet addiction rehab schools,\u0026rdquo; but what they actually do is illegally detain students sent by their parents, and subject them to extreme abuse, including but not limited to electric shocks, beatings, and even sexual assault. I believe that in any country, culture, or value system, such practices are absolutely unforgivable.\n中文 在我的心目中，互联网是改变时代的发明，夸张的说，其重要程度甚至不亚于第一和第二次工业革命。这是因为，尽管互联网所做的似乎只是让已有的资源互相连接起来可以共享，但是这几乎改变了世界的游戏规则。大量直接或间接依赖互联网的企业如雨后春笋般出现， 并发展到了惊人的规模；人们的沟通方式发生了极大的改变，以光速传播的电磁波将信息在瞬息间传递至地球的另一端；更重要的是，知识变得唾手可得，几乎没有成本。人们不知为何似乎沉迷于在网络上免费分享自己的知识，简单至小的生活经验，复杂至最深奥，先进的科学，或是各类文学作品，都可以在互联网上获取，只要愿意花时间探索。各类最顶尖大学的公开课程，行业最负盛名的专家撰写的书籍，等等；可以说，如果一个人愿意投入时间，他可以通过互联网获得最顶尖的教育。此外，人类几十年以来在互联网上的数据积累在沉寂了多年后又催生出了另一个强大的工具：AI。通过让机器在人类已经创造的知识上进行学习，AI 的强大震惊了所有人。AI 的诞生实则并不神秘，人们并没有在物理学，生物学，或者数学上取得重大的突破。而是依托于目前人类掌握的强大的计算机算力和数十年来积累的海量数据，通过特定的方法让机器学习这些知识，从而达到了惊人的效果。归根结底，这都是直接或间接由互联网推动的。在我看来互联网并不是什么需要讨论是否有用，或者是否弊大于利的东西，而是一种在人类科技的发展下必然的产物。它的作用是无比重要又无可替代的，由互联网所导致的后果，无论好坏，都是人类必然要经历和适应的。\n不过，在个人的层面上，对互联网的使用是可以被控制的。保护儿童和敏感的人群免受互联网上不良信息的侵害是必须的，也是迫在眉睫的。互联网上有多少知识宝藏，就有多少有害垃圾。因此引导儿童正确的使用互联网，保护他们不受有害垃圾的侵害是家长，或者监护人的责任。中国有一句我十分认同的古话叫做：养不教，父之过。儿童生来是一张白纸，而父母是最有能力在在这张白纸上书写涂抹的人。好的父母应当认识到自己的责任，并履行自己的义务，通过陪伴和教育在白纸上书写，而不是通过放任甚至打骂将纯洁的白纸涂抹成废纸。可现实中，尽管我相信任何一个来自中国的的父母都熟知，养不教，父之过这句名言，但是他们只会在自己不满意时责怪孩子，却不想是否自己履行了义务。比如说，一个沉迷于电子设备和网络的孩子大概率会独自度过大量本应该由父母陪伴的时光；一个在学校中吸烟喝酒的问题少年大概率同样有相同癖好的父母。我知道很多伟大的学者，或者成功的政客，企业家，总之那些看似成功的人，都来自一个上层阶层的家庭，或者至少一个和睦的家庭。当然这并不能保证来自这类家庭的孩子一定能成为所谓的精英，取得极高的成就，我只是想说，相比于家庭的氛围对孩子的影响是绝对的，而父母可以决定一个家庭的氛围。当埋怨一个孩子沉迷于网络时，不妨先看一看饭后睡前他的父母在做什么？是和孩子一起运动，看书，学习，还是自己也沉迷其中？当然，教育是一个非常复杂的话题，不止涉及到父母和孩子本身，还有政府，社会以及学校等。对于很多父母来说，或许花时间来陪伴，教育孩子是可望而不可即的事，因为他们需要花费自己所有的时间和经历挣钱养家。又或者他们本身都没有受到过良好的教育，也没有足够的能力为孩子提供良好的环境。所以我并不想批判任何人，我只是想，我们应该从情绪化的批判和严重偏见中走出来，努力看清一个现象背后的原因，才能解决这些问题，而不是诉诸于批评，甚至是暴力。尤其是，由此引发的有些暴力是我都难以相信的。在中国有一些所谓的戒网瘾，行为改正\u0026quot;学校\u0026quot;，而这些所谓的学校的做法实际上是非法拘禁那些被家长强制送来的学生，并施以极端的暴力，包括但不限于电击，殴打，甚至强奸。我相信无论在任何国家，文化和价值观中，这都是不可饶恕的。\n","date":"2025-08-25T06:15:51+08:00","permalink":"/posts/the-cognition/","title":"The Cognition"},{"content":" Show/Hide the code 1 start ms-cxh:localonly ","date":"2025-08-22T17:41:15+10:00","permalink":"/posts/skip-microsoft-account-login/","title":"Skip Microsoft Account Login"},{"content":"The Windows installer assigns too little space to the EFI and Recovery partitions by default, which is not ideal for future updates. To resolve this issue, we need to manually partition using Diskpart during the installation phase. The following script is from Microsoft and serves as an example of a partitioning script.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 rem == CreatePartitions-UEFI.txt == rem == These commands are used with DiskPart to rem create five partitions rem for a UEFI/GPT-based PC. rem Adjust the partition sizes to fill the drive rem as necessary. == select disk 0 clean convert gpt rem == 1. Windows RE tools partition =============== create partition primary size=300 format quick fs=ntfs label=\u0026#34;Windows RE tools\u0026#34; assign letter=\u0026#34;T\u0026#34; set id=\u0026#34;de94bba4-06d1-4d40-a16a-bfd50179d6ac\u0026#34; gpt attributes=0x8000000000000001 rem == 2. System partition ========================= create partition efi size=100 rem ** NOTE: For Advanced Format 4Kn drives, rem change this value to size = 260 ** format quick fs=fat32 label=\u0026#34;System\u0026#34; assign letter=\u0026#34;S\u0026#34; rem == 3. Microsoft Reserved (MSR) partition ======= create partition msr size=128 rem == 4. Windows partition ======================== rem == a. Create the Windows partition ========== create partition primary rem == b. Create space for the recovery image === shrink minimum=15000 rem ** NOTE: Update this size to match the size rem of the recovery image ** rem == c. Prepare the Windows partition ========= format quick fs=ntfs label=\u0026#34;Windows\u0026#34; assign letter=\u0026#34;W\u0026#34; rem === 5. Recovery image partition ================ create partition primary format quick fs=ntfs label=\u0026#34;Recovery image\u0026#34; assign letter=\u0026#34;R\u0026#34; set id=\u0026#34;de94bba4-06d1-4d40-a16a-bfd50179d6ac\u0026#34; gpt attributes=0x8000000000000001 list volume exit The following is a modified version of the above script, with all comments removed and the partition size changed.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 select disk 0 clean convert gpt create partition primary size=300 format quick fs=ntfs label=\u0026#34;Windows RE tools\u0026#34; assign letter=\u0026#34;T\u0026#34; set id=\u0026#34;de94bba4-06d1-4d40-a16a-bfd50179d6ac\u0026#34; gpt attributes=0x8000000000000001 create partition efi size=512 format quick fs=fat32 label=\u0026#34;System\u0026#34; assign letter=\u0026#34;S\u0026#34; create partition msr size=128 create partition primary shrink minimum=15000 format quick fs=ntfs label=\u0026#34;Windows\u0026#34; assign letter=\u0026#34;W\u0026#34; create partition primary format quick fs=ntfs label=\u0026#34;Recovery image\u0026#34; assign letter=\u0026#34;R\u0026#34; set id=\u0026#34;de94bba4-06d1-4d40-a16a-bfd50179d6ac\u0026#34; gpt attributes=0x8000000000000001 exit References https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-8.1-and-8/hh825686(v=win.10)\n","date":"2025-08-12T16:35:30+10:00","permalink":"/posts/windows-partition-guide/","title":"Windows Partition Guide"},{"content":"问题的定义 定义: 假如两个运动员 A 和 B 相约通过投篮的方式分出胜负, 规则是: 一人投一次, 率先投进的人获胜. 如果 A 和 B 两人投篮时所站的位置相同, 并且每次命中的概率分别是 \\(p\\) 和 \\(q\\), 如果 A 先投, 那么他获胜的概率是多少?\n澄清: 假设运动员每次投篮的概率都相等, 并且周围的环境不会对他造成任何影响.\n解决这个问题涉及到几何级数: \\(\\text{if } r\\in R \\text{ and } |r|\u003c1\\text{ then:}\\) $$\\sum_{n=0}^{\\infty}{r^n}=1+r+r^2+r^3+\\cdots=\\frac{1}{1-r}$$解决方法 假如 A 第一次投篮就投中, 显然这个事件的概率是 \\(p\\). 而 A 在第二次投篮时投中的概率是\\((1-p)(1-q)p\\), 因为 A 第二次投篮投中说明:\nA 在第一次没有投中, 这个事件的概率是 \\((1-p)\\). B 在第一次也没有投中, 这个事件的概率是 \\((1-q)\\). 因此, A 在第二轮投中这一事件蕴含着两个额外的事件, 这一事件发生的概率实际上是三个事件同时发生的概率. 由于 A 每次投篮投中的概率都是 \\(p\\), 所以 A 第二次投篮命中的概率是 \\(r\\times p\\), 此处 \\(r=(1-p)(1-q)\\).\n以此类推, A 第三次投篮投中的概率是\\(r^2\\times p\\), 因为 A 和 B 在第一轮都失手的概率是 \\(r\\), 在第二轮都失手的概率是 \\(r^2\\). A 第 \\(n\\) 次投篮命中的概率就等于\\(r^{(n-1)}\\times p\\), \\(r\\)的指数是\\(n-1\\)是因为第\\(n\\)次成功就意味着前\\(n-1\\)次两人都失败.\n这样就求得了 A 在第\\(1, 2, 3 \\cdots, n\\)轮投篮投中的概率. 那么 A 获胜的总概率就等于这些概率的和: $$p+rp+r^2p+\\cdots=\\sum_{n=0}^{\\infty}r^n\\times p=p\\sum_{n=0}^{\\infty}r^n$$ 这是一个几何级数, 根据几何级数求和公式: $$p\\sum_{n=0}^{\\infty}r^n=\\frac{p}{1-r}, \\text{其中}r=(1-p)(1-q)$$假如 A 的投篮命中率为 \\(80\\%\\), B 为 \\(75\\%\\). 那么 如果 A 先投, A 获胜的概率为 \\(0.8 \\div (1-0.2\\times 0.25)\\approx 0.842\\).\n几何级数的证明 另一种方法 还有另一种方法可以推导出这个概率, 并且这种方法不需要使用几何级数, 甚至可以通过这种方法推导出几何级数. 之前的方法是算出每次投中的概率, 然后求和, 从而得到获胜的概率.\n换一个角度思考问题, 假设\\(x\\)是 A 获胜的概率(注意不是投中的概率). 假如 A 第一次投就投中, A 直接就能获胜, 这个事件的概率是\\(p\\). 假如 A 没有投中, 此时 A 还是有希望获胜, 只要 B 也没有投中, 比赛就会进入下一轮. 注意，当新一轮比赛开始时, A 获胜的概率依旧是\\(x\\), 因为第一轮的比赛并不会对选手投篮的命中率有任何影响, 比赛相当于回到了原点. 那么比赛回到原点这一事件的概率是多少呢? 这一概率就等于 A 和 B 都没投中的概率, 也就是\\((1-p)(1-q)\\), 因此比赛回到原点后 A 获胜的概率就是\\((1-p)(1-q)x\\).\n此时我们已经求得了 A 获胜的所有可能性, 直接赢, 概率为\\(p\\), 比赛重新开始后再赢, 概率为\\((1-p)(1-q)x\\), 两者相加就是 A 获胜的概率: \\(x = p+rx\\), 其中\\(r=(1-p)(1-q)\\).\n通过解此方程就可以求出:\n$$ x=\\frac{p}{1-r} $$相关问题 代回法的另一个例子是, 令 \\(F_n\\) 表示第 \\(n\\) 个斐波那契数, 计算 \\(\\sum_{n=0}^{\\infty}{\\frac{F_n}{3^n}}\\) 的值. 记\n$$ x=\\sum_{n=0}^{\\infty}{\\frac{F_n}{3^n}} $$那么:\n$$ \\begin{aligned} x\u0026=\\sum_{n=0}^{\\infty}{\\frac{F_n}{3^n}} \\nonumber \\\\ \u0026=\\frac{F_0}{3^0}+\\frac{F_1}{3^1}+\\sum_{n=2}^{\\infty}{\\frac{F_n}{3^n}} \\nonumber \\\\ \u0026=\\frac{1}{3}+\\sum_{m=0}^{\\infty}{\\frac{F_{m+2}}{3^{m+2}}} \\nonumber \\\\ \u0026=\\frac{1}{3}+\\sum_{m=0}^{\\infty}{\\frac{F_m+F_{m+1}}{3^{m+2}}} \\nonumber \\\\ \u0026=\\frac{1}{3}+\\sum_{m=0}^{\\infty}{\\frac{F_m}{3^{m}\\cdot 9}} + \\sum_{m=0}^{\\infty}{\\frac{F_{m+1}}{3^{m+1}\\cdot 3}} \\nonumber \\\\ \u0026=\\frac{1}{9}+\\frac{1}{9}\\sum_{n=0}^{\\infty}{\\frac{F_n}{3^{n}}} + \\frac{1}{3}\\sum_{n=1}^{\\infty}{\\frac{F_{n}}{3^n}} \\nonumber \\\\ \\end{aligned} $$由于 \\(F_0=0\\), 最后一行可以写成:\n$$ \\frac{1}{9}+\\frac{1}{9}\\sum_{n=0}^{\\infty}{\\frac{F_n}{3^{n}}} + \\frac{1}{3}\\sum_{n=0}^{\\infty}{\\frac{F_{n}}{3^n}} $$也就是\n$$ \\begin{aligned} x\u0026=\\frac{1}{9}+\\frac{x}{9}+\\frac{x}{3} \\\\ x\u0026=\\frac{3}{5} \\end{aligned} $$TODO 纸牌游戏 TODO 另一个投篮问题 ","date":"2025-08-06T00:00:00Z","permalink":"/posts/from-shooting-hoops-to-the-geometric-series/","title":"From Shooting Hoops to the Geometric Series"},{"content":" Show/Hide the code 1 jupyter nbconvert --to pdf .\\week1.ipynb --template-file assignment --LatexPreprocessor.author_names=\u0026#39;Keao Chen\u0026#39; --LatexPreprocessor.title=\u0026#39;Week 1 Journal\u0026#39; ","date":"2025-08-04T22:13:21+10:00","permalink":"/posts/command-line-of-nbconvert/","title":"Command Line of Nbconvert"},{"content":"Logistic Regression implementation of a logistic regression\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 class LogisticRegression: def __init__(self, lr=0.01, epochs=1000, threshold=0.5): self.lr = lr self.epochs = epochs self.w = None self.b = 0 self.threshold = threshold self.losses = [] self.history = [] def _linear(self, X): return X @ self.w + self.b def _sigmoid(self, z): return 1 / (1 + np.exp(-z + 1e-5)) def predict_prob(self, X): return self._sigmoid(self._linear(X)) def predict(self, X): return (self.predict_prob(X) \u0026gt;= self.threshold).astype(int) def loss(self, X, y): y_prob = self.predict_prob(X) eps = 1e-15 y_prob = np.clip(y_prob, eps, 1 - eps) return -(1 / X.shape[0]) * (np.sum(y * np.log(y_prob)) + np.sum( (1 - y) * np.log(1 - y_prob))) def fit(self, X, y): self.w = np.zeros(X.shape[1]) for i in range(self.epochs): loss = self.loss(X, y) self.losses.append(loss) y_prob = self.predict_prob(X) # Gradient Descent dw = (1 / X.shape[0]) * X.T @ (y_prob - y) db = (1 / X.shape[0]) * np.sum(y_prob - y) self.w -= self.lr * dw self.b -= self.lr * db # calculate how much did the hyperplane has \u0026#34;rotate\u0026#34; by a inner product of their normal vectors cos_theta = 0 if self.history: cos_theta = np.dot(self.w, self.history[-1][0]) / ( np.linalg.norm(self.w) * np.linalg.norm(self.history[-1][0])) cos_theta = np.clip(cos_theta, -1.0, 1.0) angle_deg = np.degrees(np.arccos(cos_theta)) # record history only when there is a big update if not self.history or angle_deg \u0026gt; 30 or i == self.epochs - 1: self.history.append([self.w.copy(), self.b, i]) Try Logistic Regression on a Synthetic Dataset generate data\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 np.random.seed(42) d1 = np.random.randn(100, 2) d2 = np.random.randn(100, 2) + 3 X_dummy = np.vstack((d1, d2)) y_dummy = np.array([1] * 100 + [-1] * 100) idx = np.random.permutation(len(X_dummy)) X_dummy = X_dummy[idx] y_dummy = y_dummy[idx] X_dummy = X_dummy / np.max(X_dummy) plt.scatter(X_dummy[:, 0], X_dummy[:, 1], c=y_dummy, cmap=\u0026#34;bwr\u0026#34;, alpha=0.5) plt.show() learn\nShow/Hide the code 1 2 logistic = LogisticRegression(0.1, 200, 0.5) logistic.fit(X_dummy, y_dummy) loss\nShow/Hide the code 1 2 plt.plot(np.arange(len(logistic.losses)), logistic.losses) plt.show() visualize learning process\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 fig, axes = plt.subplots(nrows=int(np.ceil(len(logistic.history) / 4)), ncols=4, figsize=(20, 5)) axes = axes.flatten() # print(p.losses) x0_vals = np.linspace(X_dummy[:, 1].min() - 1, X_dummy[:, 1].max() + 1, 100) for i, (cw, cb, epoch) in enumerate(logistic.history): axes[i].plot( x0_vals, -(cw[0] * x0_vals + cb) / cw[1], ) axes[i].scatter(X_dummy[:, 0], X_dummy[:, 1], c=y_dummy, cmap=\u0026#39;bwr\u0026#39;, alpha=0.5) axes[i].set_xlim(-1, X_dummy[:, 0].max() + 1) axes[i].set_ylim(-1, X_dummy[:, 1].max() + 1) axes[i].set_title( f\u0026#34;epoch={epoch}, w0={cw[0]:.2f}, w1={cw[1]:.2f}, \\nb={cb:.2f}, loss={logistic.losses[i]:.2f}\u0026#34; ) plt.tight_layout() plt.show() Try Logistic Regression on a Real Dataset load data and learn\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import re import pandas as pd from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer df = pd.read_csv(\u0026#34;SMSSpamCollection\u0026#34;, sep=\u0026#34;\\t\u0026#34;, names=[\u0026#34;label\u0026#34;, \u0026#34;message\u0026#34;]) def clean_text(text): text = text.lower() text = re.sub(r\u0026#34;\\W+\u0026#34;, \u0026#34; \u0026#34;, text) return text.strip() df[\u0026#34;message\u0026#34;] = df[\u0026#34;message\u0026#34;].apply(clean_text) vectorizer = TfidfVectorizer(stop_words=\u0026#34;english\u0026#34;) X = vectorizer.fit_transform(df[\u0026#34;message\u0026#34;]) y = np.where(df[\u0026#34;label\u0026#34;] == \u0026#34;spam\u0026#34;, 1, 0) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) classifier = LogisticRegression(lr=0.1, epochs=20000) classifier.fit(X_train, y_train) evaluate performance\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 y_pred = classifier.predict(X_test) from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, classification_report, ) print(\u0026#34;Accuracy:\u0026#34;, accuracy_score(y_test, y_pred)) print(\u0026#34;Precision:\u0026#34;, precision_score(y_test, y_pred, pos_label=1)) print(\u0026#34;Recall:\u0026#34;, recall_score(y_test, y_pred, pos_label=1)) print(\u0026#34;F1 Score:\u0026#34;, f1_score(y_test, y_pred, pos_label=1)) print(\u0026#34;\\nClassification Report:\\n\u0026#34;) print(classification_report(y_test, y_pred, target_names=[\u0026#34;ham\u0026#34;, \u0026#34;spam\u0026#34;])) Accuracy: 0.9488789237668162 Precision: 1.0 Recall: 0.6174496644295302 F1 Score: 0.7634854771784232 Classification Report: precision recall f1-score support ham 0.94 1.00 0.97 966 spam 1.00 0.62 0.76 149 accuracy 0.95 1115 macro avg 0.97 0.81 0.87 1115 weighted avg 0.95 0.95 0.94 1115 Show/Hide the code 1 2 3 4 5 6 7 8 9 from sklearn.metrics import ConfusionMatrixDisplay ConfusionMatrixDisplay.from_predictions( y_test, y_pred, normalize=None, cmap=\u0026#34;Blues\u0026#34;, ) plt.show() loss\nShow/Hide the code 1 2 plt.plot(np.arange(len(classifier.losses)), classifier.losses) plt.show() ","date":"2025-08-03T00:00:00Z","permalink":"/posts/a-study-on-logistic-regression/","title":"A Study On Logistic Regression"},{"content":"问题的定义 定义: 房间里有多少人才能保证其中至少两个人的生日在同一天的概率不小于 50%?\n更严格的定义: 如果每个人的出生日期都是互相独立的, 并且每个人都等可能的出生在一年中的任何一天 (假设不存在闰年), 房间里有多少人才能保证其中至少两个人的生日在同一天的概率不小于 50%?\n更严格的定义通过添加一些前提条件，避免了一些在现实生活中可能发生的特殊情况，例如两个人的生日相关联，知道了一个人的生日就能猜出另一个人的生日 (双胞胎); 或者生日分布不均匀, 来自某个月份的人比来自其他月份的人更多 (某个星座的聚会). 添加前提条件可以排除这些特殊情况, 因为通过讨论得出来的一般结论并不适用于这些特殊情况.\n极端情况 考虑如果房间里只有一个人, 那么有两个人生日相同的概率为 0, 而如果房间里有 366 个人, 那么有两个人生日相同的概率则为 100%. 因为假如前 365 个人的生日都不同, 那么这些人就一定占用了一年中所有的时间, 这样无论第 366 个人是哪天出生, 都一定会和前 365 个人中的某个人的生日相同. 此外, 如果房间里有 183 个生日不同的人, 那么有不小于 50% (\\(\\frac{183}{365} \\approx 50.14\\%\\)) 的概率第 184 个人和前面 183 个人中的某个人生日相同. 因此可以确定答案就在 2 和 184 之间.\n穷举法 假设有 n 个人在房间中, 当 n 等于 2 时, 两个人生日组合的总数是 \\(365\\times365\\), 其中两个人生日相同的情况的数量是 \\(365\\), 因此当房间中有两个人时, 两个人生日相同的概率为 \\(\\frac{365}{365\\times365}\\approx0.27\\%\\). 当 n 等于 3 时,三个人的生日组合的总数是 \\(365\\times365\\times365=48627125\\), 而至少两个人生日相同有: 前两个人生日相同而第三个人生日不同, 或者第一个和第三个人生日相同而第二个人生日不同,或者后两个人生日相同而第一个人生日不同, 或者三个人的生日都相同, 这四种情况. 总数是: \\(365\\times364\\times3+365=398945\\), 因此当 n 等于 3 时, 至少两个人生日相同的概率为 \\(\\frac{398945}{48627125}\\approx0.82\\%\\).\n对立事件的概率 当 n 越来越大时, 需要考虑的情况更多, 容易重复计数某些情况, 或者漏掉某些情况. 此时, 可以计算对立事件的概率. 求出相对好求的对立事件的概率 \\(P\\) 后, 当前事件的概率为 \\(1-P\\). 对于当前问题来说, 事件为: 房间内有 n 个人, 存在生日相同的两人. 对立事件为: 房间内有 n 个人, 不存在生日相同的两人, 换句话说, 每个人的生日都不相同.\n当 n 等于 1 时, 这个人可以取一年中的任意一天出生, 因此概率为 \\(\\frac{365}{365}\\), 也就是 \\(1\\). 当 n 等于 2 时, 由于第一个人的存在, 第二个人只能选择 364 天中的一天, 每个人的生日都不同的概率为 \\(\\frac{365}{365}\\times\\frac{364}{365}\\), 因为已经假设每个人的生日都是独立的, 因此两个事件的联合概率就是两个事件概率的乘积. n 等于 3 时, 概率为:\n$$ \\frac{365}{365}\\times\\frac{364}{365}\\times\\frac{364}{365} $$因此, 当房间内有 n 个人时, 概率为:\n$$ \\frac{365}{365}\\times\\frac{364}{365}\\times ... \\times \\frac{365-(n-1)}{365} $$改写为连乘的形式:\n$$ \\frac{365}{365}\\times\\frac{364}{365}\\times ... \\times \\frac{365-(n-1)}{365} = \\prod_{k=0}^{n-1}\\frac{365-k}{365} $$进一步改写为阶乘的形式:\n$$ \\prod_{k=0}^{n-1}\\frac{365-k}{365}=\\frac{365\\times...\\times(365-(n-1))}{365^n}\\times\\frac{(365-n)!}{(365-n)!}=\\frac{365!}{365^n\\times(365-n)!} $$以上计算的是: 当房间内有 n 个人时, 所有人生日都不相同的概率. 记这个概率为 \\(P\\), 那么至少有两个人生日相同的概率为 \\(1-P\\). 通过计算, 当 n 为 2 时, 结果大约为 \\(0.27\\%\\), 与之前通过穷举法计算出的结果相同.\nPython 模拟 尽管阶乘公式看起来更美观，但是在计算时会导致数字过大, 不方便计算机处理. 因此在程序中还是使用了连乘的方式, 这种方式的好处是, 可以保存每一步的结果, 因此每一步只需要一次乘法运算.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import matplotlib.pyplot as plt import numpy as np p = [0.0] factor = 1.0 for i in range(2, 30): new_factor = factor * ((365 - i + 1) / 365) p.append(1 - new_factor) factor = new_factor plt.figure(figsize=(10, 6)) plt.plot(np.arange(1, 30), p, marker=\u0026#39;o\u0026#39;) plt.annotate(f\u0026#39;(23, {p[22]:.3f})\u0026#39;, (23, p[22]), ha=\u0026#39;right\u0026#39;) plt.yticks(np.arange(0, 1.01, 0.1)) plt.xticks(np.arange(1, 30, 1)) plt.grid(True, which=\u0026#39;both\u0026#39;) plt.show() 推广 当前的问题可以转换为如下的形式: 一个随机试验共有 D 种可能的结果, 并且每种结果出现的概率是相等的, 那么需要进行多少次试验才能使\u0026quot;至少两次试验的结果相同\u0026quot;的概率为 50%? 这个结果和 D 有关, 如果 D 很小, 那么可能很少的次数就会重复. 最极端的情况, D 等于 2, 那么第三次实验必然重复. 反之, 如果 D 很大, 那么就需要多次实验, 重复的概率才会显著增加. 那么假如目标概率已经确定 (50%), 当 D 变化时, 试验次数如何变化? 他们之间的关系是什么? 是否是线性关系, 或者其他关系? 下文通过推导公式: 房间内有 n 个人时, 所有人生日都不同的事件的概率:\n$$ P = \\prod_{k=0}^{n-1}\\frac{365-k}{365} $$求出了一个近似的解析式.\n首先,\n$$ P = \\prod_{k=0}^{n-1}\\frac{365-k}{365}=\\prod_{k=0}^{n-1}1-\\frac{k}{365} $$对等式两端取对数，\n$$ ln{P} = \\sum_{k=0}^{n-1}ln{(1-\\frac{k}{365})} $$由于当 x 足够小时, \\(ln(1-x) \\approx -x\\), 因此:\n$$ ln{P} \\approx \\sum_{k=0}^{n-1}-\\frac{k}{365} $$由求和公式:\n$$ ln{P} \\approx \\frac{n(n-1)}{-365 \\times 2} $$事件房间内至少有两人生日相等的概率为\\(1-P\\). 设定这个事件的概率为 50%, 即 \\(P=\\frac{1}{2}\\).\n$$ ln{\\frac{1}{2}} \\approx \\frac{n(n-1)}{-365 \\times 2} $$$$ -ln{2} \\approx \\frac{n(n-1)}{-365 \\times 2} $$将 \\(n(n-1)\\) 近似为 \\((n-\\frac{1}{2})^2\\),\n$$ (n-\\frac{1}{2})^2 \\approx 2\\times365\\times ln{2} $$$$ n \\approx \\frac{1}{2} + \\sqrt{2\\times365\\times ln{2}} $$综上, 如果一年中有 D 天, 那么使房间内至少有两个人生日相等的概率为 50% 的人数大约是 \\(\\frac{1}{2} + \\sqrt{D\\times2ln{2}}\\). 从这个近似的表达式可以看出, 可能的结果的数量 D 与 试验次数 n 的关系大概是 \\(\\frac{1}{2}\\) 方的关系. 此外, 因为在计算中使用了泰勒展开, 所以 D 越大, 误差就越小.\n以下代码使用新的近似的公式计算了 D 从 2 到 10000 时, n 的变化.\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import matplotlib.pyplot as plt import numpy as np D_arr = np.arange(2, 10000) n_arr = [] log2 = np.log(2) for d in D_arr: n_arr.append(0.5 + np.sqrt(2 * log2 * d)) plt.plot(D_arr, n_arr, marker=\u0026#39;,\u0026#39;) plt.grid(True, which=\u0026#39;both\u0026#39;) plt.show() ","date":"2025-08-03T00:00:00Z","permalink":"/posts/a-study-on-the-birthday-problem/","title":"A Study on the Birthday Problem"},{"content":"SumatraPDF 小巧，快速，对于浏览 PDF 来说再合适不过。唯一的缺点就是功能有些许缺失，例如：虽然有更换主题功能，但是不能跟随 Windows 主题一起变化，并且界面颜色改变时，文档的颜色不改变。于是乎每当在夜晚打开一份 PDF 都仿佛打开了太阳\u0026hellip;\u0026hellip;\n微软的应用商店 Microsoft Store 中有一款软件 Auto Dark Mode 可以自动切换 Windows 的暗色模式，并且支持在切换时运行脚本。正巧 SumatraPDF 可以通过配置文件配置，实际上对于一些高级设置（例如字体颜色和背景颜色）只支持使用配置文件设置。因此一个简单的方案就是：编写一个脚本根据参数不同自动修改 SumatraPDF 的配置文件，并且设置 Auto Dark Mode 使其在切换 Windows 主题时自动运行此脚本。\nAuto Dark Mode 配置：\nShow/Hide the code 1 2 3 4 5 6 7 8 9 Enabled: true Component: Scripts: - Name: SumatraPDF Command: python WorkingDirectory: C:\\Users\\kyle\\AppData\\Local\\SumatraPDF ArgsLight: [toggle_theme.py, light] ArgsDark: [toggle_theme.py, dark] AllowedSources: [Any] Python 脚本：\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import sys import os import re if len(sys.argv) != 2 or sys.argv[1] not in [\u0026#39;light\u0026#39;, \u0026#39;dark\u0026#39;]: print(\u0026#34;Usage: python toggle_sumatra_theme.py [light|dark]\u0026#34;) sys.exit(1) mode = sys.argv[1] config_path = os.path.join(os.getcwd(), \u0026#34;SumatraPDF-settings.txt\u0026#34;) if not os.path.isfile(config_path): print(f\u0026#34;Error: Config file not found: {config_path}\u0026#34;) sys.exit(1) if mode == \u0026#39;light\u0026#39;: theme_val = \u0026#39;Light\u0026#39; text_color = \u0026#39;#262626\u0026#39; background_color = \u0026#39;#f8f3e9\u0026#39; else: theme_val = \u0026#39;Darker\u0026#39; text_color = \u0026#39;#bbbbbb\u0026#39; background_color = \u0026#39;#17191a\u0026#39; with open(config_path, \u0026#39;r\u0026#39;, encoding=\u0026#39;utf-8\u0026#39;) as f: config = f.read() config = re.sub(r\u0026#39;Theme\\s*=\\s*\\w+\u0026#39;, f\u0026#39;Theme = {theme_val}\u0026#39;, config) config = re.sub(r\u0026#39;TextColor\\s*=\\s*#[0-9a-fA-F]+\u0026#39;, f\u0026#39;TextColor = {text_color}\u0026#39;, config) config = re.sub(r\u0026#39;BackgroundColor\\s*=\\s*#[0-9a-fA-F]+\u0026#39;, f\u0026#39;BackgroundColor = {background_color}\u0026#39;, config) with open(config_path, \u0026#39;w\u0026#39;, encoding=\u0026#39;utf-8\u0026#39;) as f: f.write(config) ","date":"2025-07-15T17:01:11+08:00","permalink":"/posts/auto-toggle-sumatrapdf-themes/","title":"自动切换 SumatraPDF 主题"},{"content":"WinDirStat\n","date":"2025-06-27T18:10:28+08:00","permalink":"/posts/an-alternative-to-filelight-on-windows/","title":"An Alternative to Filelight on Windows"},{"content":"概率论中的公式 在南信大的时候，我在概率论期末考试前整理了一份公式大全（当时我脑中全部能想到的），最近整理电脑文件时偶然又把它翻出来了。\nChapter 1 $$\r\\begin{align}\r\u0026P(A+B)=P(A)+P(B)-P(AB) \\\\\r\u0026P(A-B)=P(A\\bar{B})=P(A)-P(AB) \\\\\r\u0026P(AB)=P(A)P(B) \\iff \\text{A and B are independent} \\\\\r\u0026P(A+B+C)=P(A)+P(B)+P(C)-P(AB)-P(AC)-P(BC)+P(ABC) \\\\\r\u0026P(A|B)=\\frac{P(AB)}{P(B)} \\\\\r\u0026P(B|A)=\\frac{P(AB)}{P(A)} \\\\\r\u0026P(A)=P(A|B_1)P(B_1)+\\cdots+P(A|B_n)P(B_n) \\\\\r\u0026P(B_i|A)=\\frac{P(AB_i)}{P(A)}\r\\end{align}\r$$Chapter 2 $$\r\\begin{align}\r\u0026E(XY)=E(X)E(Y) \\iff \\text{X and Y independent} \\\\\r\u0026E(X+Y)=E(X)+E(Y) \\\\\r\u0026E(X-Y)=E(X)-E(Y) \\\\\r\u0026E(c\\times X)=c \\times E(X) \\text{, where c is constant}\\\\\r\u0026E(X+c)=E(X)+c \\text{, where c is constant} \\\\\r\\newline\r\u0026Var(X+Y)=Var(X)+Var(Y) \\iff \\text{X and Y independent} \\\\\r\u0026Var(X+Y)=Var(X)+Var(Y)+2Cov(X,Y) \\\\\r\u0026Var(X-Y)=Var(X)+Var(Y)-2Cov(X,Y) \\\\\r\u0026Var(c\\times X)=c^2\\times Var(X) \\text{, where c is constant} \\\\\r\u0026Var(X+c)=Var(X) \\text{, where c is constant} \\\\\r\\newline\r\u0026Cov(X,Y)=Cov(Y,X)=E[(X-E(X))\\times (Y-E(Y))]=E(XY)-E(X)E(Y) \\\\\r\u0026Cov(a\\times X, b\\times Y)=a\\times b\\times Cov(X,Y) \\\\\r\u0026Cov(X,X)=Var(X) \\\\\r\u0026Cov(X,c)=0 \\text{, where c is constant} \\\\\r\u0026Cov(X_1+X_2,Y)=Cov(X_1,Y)+Cov(X_2,Y) \\\\\r\u0026Cov(X+a,Y+b)=Cov(X,Y) \\\\\r\u0026\\Rho_{XY}=\\frac{Cov(X,Y)}{\\sqrt{Var(X)}\\sqrt{Var(Y)}} \\\\\r\u0026\\Rho_{XY}=1 \\iff \\exists \\text{ a and b } \\Rightarrow P(Y=a+bX)=1 \\\\\r\\end{align}\r$$Chapter 3 ","date":"2025-06-27T00:00:00Z","image":"/posts/probability-formulas/1.png","permalink":"/posts/probability-formulas/","title":"Probability Formulas"},{"content":"Disabling-Hyper-V Certain advanced Windows 10 features, such as Device Guard (in particular, Hypervisor-protected code integrity or HVCI) and Credential Guard, can prevent Hyper-V from being completely disabled. In other words, when any of these features are enabled, so is Hyper-V, even though Windows may report otherwise.\nThe Device Guard and Credential Guard hardware readiness tool released by Microsoft can disable the said Windows 10 features along with Hyper-V:\nDownload the latest version of the tool from here dgreadiness-tool. The following steps assume version 3.6. Unzip. Open an elevated (i.e. Run as administrator) Command Prompt. @powershell -ExecutionPolicy RemoteSigned -Command \u0026quot;X:\\path\\to\\dgreadiness_v3.6\\DG_Readiness_Tool_v3.6.ps1 -Disable\u0026quot; Reboot. 如上所述，由于 Device Guard 和 Credential Guard hardware readiness tool 功能，Hyper-V 无法被彻底关闭。使用微软提供的此脚本：here 可以将这些功能彻底关闭，从而彻底关闭 Hyper-V。\nhttps://github.com/gmh5225/Disabling-Hyper-V\n","date":"2025-06-26T14:31:50+08:00","permalink":"/posts/disable-windows11-virtualization/","title":"彻底关闭 Windows 11 的虚拟化"},{"content":"That was a summer day and I was wandering around the countryside when I heard those tiny little meows coming from a bush. At first, I thought, “Nah, that can\u0026rsquo;t be what I\u0026rsquo;m hearing,” but the closer I got, the louder it got. I peeked around, and there they were: three scruffy little kittens holed up in the bush. They looked like a mess, and, honestly, they smelled pretty bad too.\nThey were huddled so tight in there I never would\u0026rsquo;ve seen them if they hadn\u0026rsquo;t been meowing their heads off. There were three of them: two black-and-white ones and a pure white one. I just stood there for a bit, trying to figure out what to do. For one thing, it was summer, and that bush was swarming with mosquitoes. And on top of that, these little guys were trying their hardest to act tough: hissing and puffing up like they were gonna take me down. It was kind of funny but also sad because, really, they were just scared out of their minds.\nThere was no sign of their mom, and they looked so weak and droopy: like they hadn\u0026rsquo;t eaten in days. After going back and forth with myself, I decided I couldn\u0026rsquo;t just leave them there. So I ran home to grab a bag, but by the time I came back, the white one was gone. I felt a bit down but figured I\u0026rsquo;d do what I could for the other two.\nWhen I got them home, I set them up in a shoebox. I really wanted to pet them, but I didn\u0026rsquo;t make it, because they were still totally freaked out. Every time I came near they were hissing and puffing up like I was some kind of monster. I didn\u0026rsquo;t have any cat food on hand, so I whipped up some scrambled eggs. Let me tell you, they were starving. The second I put the eggs down, they sniffed at them, realized it was food, and dove right in. That\u0026rsquo;s when I noticed, they didn\u0026rsquo;t even have teeth yet!\nOver the next few days, I fed them eggs, water, and a little milk until the cat food I ordered showed up. I also got them a cozy pet house and some flea medicine because, wow, they were crawling with fleas, and their skin was in bad shape.\nLittle by little, they started warming up to me. They stopped acting like I was out to get them and even let me pet them without freaking out. I treated their fleas and skin issues, and soon enough, they were looking so much better. They were tiny at first, but they grew fast, eating well and getting stronger every day. Once they were healthy, they started showing their true colors. During the day, they\u0026rsquo;d nap under the plants in my yard, staying out of the summer sun. But in the evenings? They\u0026rsquo;d go nuts, running around the yard and playing like crazy.\nThe two of them are pretty different in terms of personality. One\u0026rsquo;s a little bigger and stronger, while the other one\u0026rsquo;s smaller and more timid. Sometimes the big one would push the little guy around, but it wasn\u0026rsquo;t too bad, just typical sibling stuff. Most of the time, they were super close, eating, sleeping, and frolicking together like best friends.\nAt first, they were really protective of their food, growling and guarding it like they thought it\u0026rsquo;d run out. But I worked on it with them, and after a while, they figured out they didn\u0026rsquo;t have to worry anymore. Once they relaxed, they became the sweetest little cuddly furballs.\nIt\u0026rsquo;s crazy to think how far they\u0026rsquo;ve come. From those scrappy, scared kittens in the bush to happy, healthy little buddies running around my yard. They\u0026rsquo;ve brought so much joy to my life, and I\u0026rsquo;m so glad I decided to bring them home.\n","date":"2025-06-22T18:49:51+08:00","permalink":"/posts/two-kittens/","title":"Two Kittens"},{"content":"Happy Birthday to You ~\n祝你生日快乐，震震！ （其实我还是习惯称你的大名）。不知道你在哪里过生日，和谁一起过？如果是在家里的话，请帮我向老袁和丛阿姨问好，也祝他们快乐。\n我很想去陪你过个生日，毕竟自从离开燕郊后，我们就没有机会经常见面了。这些年以来我也去了很多地方，经历了很多事情，但是无论在哪里，我都很想念你，想念你们一家。不过我真的很懒，倒不是觉得路程太远懒得出门，而是一种心理上的懒。不知道你能不能理解，与人见面是我觉得最累的事情了，即使是和你们见面。之前住在一起的时候，我们时而串个门倒是没什么，这样子见面就像喝水一样平淡；但是长久不见或者不联系后再见面，我总觉得不太一样，就像喝酒一样，虽然甜美但总是要多花一点点力气。况且对于我来说，有些话不见面反而更容易说。所以我就用写字的方式和你叙旧和向你祝福了，希望你能见谅。\n我现在坐在我家客厅的茶桌前，一边喝着一杯茶，一边在用电脑打字，琢磨该写些什么。屋外的院子，虽然午间太阳暴晒有些热，但也是一片郁郁葱葱。\n其实我也没有什么特别的想说的话，只是想着，自从初中毕业后，我们各自去了不同的地方读书，见面聊天的机会就少了许多。后来我们家搬离了燕郊后，几乎没有机会见面了。有很多事情我本应该和你分享和你说，也没有机会说，所以我想我可以借此机会理一理，和你讲一讲我这些年的经历。\n第一次出远门是在我初中还没毕业的时候。我去的地方是浙江绍兴，那已经是十年前了，我都有点记不清了，不过那时候你们应该还在上学，因为我记得在我还没有回燕郊的时候，就中考了。不过，我倒是还清楚地记得我回来之后我们去五期对面的那家卖肘子的饭店吃饭。第四张图好像就是那时候拍的？\n在绍兴的时候可能是我经历过物理条件最艰苦的一段时间。那时我住在一个车库，正儿八经的车库，卷帘门，没有窗。两侧摆着两张床，我和另一个人分享一个车库。我还记得那时候我在我的床一侧的墙上看到的巴掌大的蜘蛛，还有每天晚上睡觉时候铺天盖地的蚊子。仔细回想一下\u0026hellip;我觉得那应该是一段痛苦的回忆，但其实现在也不记得有什么特别的感受，印象比较深得就两条，一是那时候我还用着一加手机，经常发愁没有电脑用来刷机；二十没有地方洗澡，所以我几乎一个月没有正经地洗过澡。\n再后来我们就各奔东西了，因为没有参加中考，我也没有机会读高中（有机会让我读我也不读）。我就去了江苏常州的一家技工学校，或者叫中专，名字是科技经贸技工学校，现在已经倒闭了，哈哈哈。我在那里上学的时候我妈妈还在燕郊，所以我记得每次放假我回家我们还能一起玩。有一段时间你们住在西边，好像叫什么青年小区，我们还有机会一起打篮球和王者荣耀。一开始在科技经贸上学的时候我真的好不适应，因为虽然我那时抵触上学，但我心底还不认为自己是个不学无术的人，所以看不惯身边的同学每天混日子的生活。不过后来我就适应了，哈哈哈，一开始我还当了个班长，也还算认真，后来我就成了带头玩的人了。下面左边三张图片是我偷拍的我的两个年轻的女老师（现在都结婚生娃了），最右边的是食堂和两个看起来不太聪明的同学。\n在那里发生了一件我本来已经忘记了的糗事，可能是因为令我太尴尬，所以我选择性的遗忘了。可后来还是偶然听到别人说起，于是我又想起来了，不免有些可悲。故事发生在教室里，有一天我去教室上课，居然发现黑板上写着别人对我表白的话。我想我当时内心一定是宕机了，在我的大脑深处，处理这类事情的代码是缺失的。于是\u0026hellip;我的处理方式是：面无表情地把黑板上的内容擦掉，然后当作什么都没有发生 😓。其实我真的忘记我当时是怎么做的了，我只是记得有这个事情，我也忘记了后来我是怎么处理这件事情，怎么和那个女生沟通的了。说实话，如果是我现在的我，可能也不知道应该怎么办，但是我一定有勇气接受，或者拒绝，不会像那时一样装作无事发生。我已经忘记了那个女生的名字，不过我记得她还是挺漂亮的（可能就是图 10 中的那个背影）。\n像这样我因为不知道怎么办最后伤害了别人甚至是朋友的事情还有很多，我实在不想回忆了。奇怪的是，在大多数时间，我都自认为我是一个善良的人，我会为了小猫小狗伤心甚至流泪，会真心地为受苦受难者难过。我想这是我性格上的一个缺陷，有时候很 mean 却不自知。\n除了不开心的事情，开心的事情也有很多。在那边上了一段时间的学之后，我也认识了几个一起玩的朋友，算是一个小团体。我们在一起回宿舍，再从宿舍到教学楼，一起吃饭，打篮球。那段时间我真的很喜欢打篮球，以至于我的膝盖都受伤了，一走路就很疼。几乎是每天，无论是炎热的夏天还是寒冷的冬天，我们都会早早的离开教室，穿过一条小河，到不远处的篮球场打篮球。我们还参加了一次学校组织的篮球赛，那也是一个难忘的经历，我们都以为自己胜券在握，结果被另一个班打败了。\n在中专里我还谈了自己的初恋，也是稀里糊涂的。从一开始都是那个女生主动，但是一两个星期后我们就分手了，也是她提的。因为时间太短了，所以我也没有从中感悟到什么。直到现在我也不知道为什么她会主动和我在一起，又为什么和我分手。每次想到这些我都不免感叹愚蠢用来形容那时的我都过于褒义了。在中专临近毕业的时候，我们本该对接的那个民办大专又倒闭了（果然生活中处处是草台班子啊），不过我们因祸得福，得以有机会进入一所公办的大专。\n在大专里我总是形单影只，与周围人格格不入的。不过我在第一年，也就是 2017 年谈了现在的女朋友。和她谈恋爱让我成长了很多，也吃了很多苦，但是也收获了很多。这些谈恋爱的辛酸苦辣就不提了，否则真的可以写很多很多。在大专里我还在商场里兼过职，逃过课，去其他城市旅过游，在一家公司实习过（一开始一天的工资只有 60 离谱），看些照片吧。\n我不太喜欢拍照，所以挑来挑去也就这些照片。上面的照片都是我在读大专期间拍的，也就是三年吧。最后的时候，我做出了一个重要的决定，就是参加专转本考试。这也是一段相当漫长的路程，途中认识了很多人，经历了很多事情。\n因为没有读过高中，为了保险起见，我报名了一个集训营，准备接受高强度的学习。从那年的七月一直到十一月，我从常州到无锡，又从无锡到常州，换了两个地方，每天都从早学习到晚。看数学做高等数学练习题做到崩溃，学英语背单词背到睡着。一开始真的很难，数学连题目都看不懂，恶补高中的基础，英语选择题蒙答案对的比自己做对的还多。不过那时候也有觉悟，不想别的，也没有顾虑，就想着就算是火海也要泡在里面直到最后。十一月的时候，又去了无锡，这次一直待到了考试那天，中途还在那里过了年。\n那段时间过的很快乐，也很充实。我认识了几个一起学习的朋友，每天吃饭，睡觉，学习都在一起。彼此之间也没有竞争，只有互相帮助，最终的结果也很好，大家都考上了，没有人落榜。考上之后有一个很长的假期，这期间我又去了盐城。这又是一个我不愿意回忆的故事。在常州时意外认识了两个来自盐城的招生老师，分别姓王和孙，我后来也是跟着他们去了盐城。王老师比较瘦家里比较富裕，孙老师有点胖胖的，家里看起来条件一般。我知道这些是因为我在他们家里都住过。他们在盐城也开展招生的业务，宣传他们的机构，推销我之前参加过的那个集训营，而我作为一个成功的案例被他们拉过去带在身边。那段时间我也算是走出了校园，见识到了一些真实的，社会上的事。跟着他们参加了一些酒局饭局，但也因为不懂事出过一些丑。想一想真的有些后悔，当时不如乖乖呆在家里。虽然在外面有更多的机会，能涨更多的见识，但是我好像不是那种善于抓住机会的人。反面的例子是我在盐城认识的另一个人，他叫什么我忘记了，好像姓刘来着。他是那种很八面玲珑的人，很会为人处世。在学校里兼职挣钱，为机构招生，贿赂学校领导，带小弟入行，样样都可以。当时他就能挣很多钱了，不知道他现在如何了？\n在南京的两年正好是疫情时期，学校里的课程很多，好像要我们在两年内学完四年的课程，因此也很忙，每天忙着上课，下课后忙着做作业，所以没什么特别多的故事发生。最后毕业前很多同学都在准备考研，那氛围真是浓烈的不得了，他们不仅占用自己的课余或者自习时间，连上课的时间都在学校考研的内容。我本也应该是他们中的一员，放弃一些无用的念想，做最有利于自己未来的事情。当时我的确也在备考着，我买了很多参考书，我每天都去图书馆里自习，练题。但最后我还是没坚持到最后，可能是有些讨厌和别人竞争了？总之我准备了一半就放弃了，然后就从南京回老家了。\n回忆真的是一件很烧脑的事情，我只是简单地，粗略地回忆了一下就感觉有些头脑发热。\n我知道之前你和我相处的时候真的包容了我很多，我是那么的任性，甚至有些偏激。我从你身上学到了很多，有一些我没能从我的家庭中学到的东西，在和你的相处中学到了。现在我们都长大了，甚至于我身边的同龄人现在几乎是结婚的比没结婚的人多了，我想和你说一声谢谢~，我不知道这么多年过去后我们还算不算像之前那样亲密无间的好朋友，不过对于我来说，每次当我想起或者看到朋友这个词的时候，第一个想到的肯定是你。再次祝你生日快乐。\n","date":"2025-06-18T11:37:10+08:00","permalink":"/posts/a-letter/","title":"Letter"},{"content":"Using pkgfile to find out the package of such files\nShow/Hide the code 1 2 sudo pkgfile -u pkgfile xxx.so.1 ","date":"2025-06-13T12:40:05+08:00","permalink":"/posts/handle-missing-shared-library-error/","title":"Handle Missing Shared Library Error"},{"content":" Show/Hide the code 1 2 3 for f in `ls *.mp3`; do mv \u0026#34;$f\u0026#34; `echo \u0026#34;$f\u0026#34; | sed \u0026#39;s/生活大爆炸/TBBT/g\u0026#39;` done ","date":"2025-06-13T12:38:57+08:00","permalink":"/posts/rename-files-by-deleting-or-replacing-substring/","title":"Rename Files by Deleting or Replacing Substring"},{"content":"I get a directory like following:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 . ├── S01 │ ├── TBBTS01E01.mp4 │ ├── TBBTS01E01.mp4 │ ├── TBBTS01E01.mp4 │ ... ├── S02 │ ├── TBBTS02E01.mp4 │ ├── TBBTS02E02.mp4 │ ├── TBBTS02E03.mp4 │ ... ├── S03 │ ├── TBBTS03E01.mp4 │ ├── TBBTS03E02.mp4 │ ├── TBBTS03E03.mp4 │ ... ├── S04 │ ├── TBBTS04E01.mp4 │ ├── TBBTS04E02.mp4 │ ├── TBBTS04E03.mp4 │ ... ├── S05 │ ├── TBBTS05E01.mp4 │ ├── TBBTS05E02.mp4 │ ├── TBBTS05E03.mp4 │ ├── TBBTS05E04.mp4 │ ... └── S06 ├── TBBTS06E01.mp4 ├── TBBTS06E02.mp4 ├── TBBTS06E03.mp4 ... I want to transform all mp4 files to mp3 and move them to a new directory called mp3 in current directory. here is the command:\nShow/Hide the code 1 find . -name \u0026#34;*.mp4\u0026#34; -type f -print | parallel -j20 \u0026#34;ffmpeg -i {} ./mp3/{/.}.mp3\u0026#34; where {/.} represents a clear file name that stripped extension name and path\n","date":"2025-06-13T12:37:35+08:00","permalink":"/posts/convert-all-mp4-to-mp3-in-one-command/","title":"Convert All Mp4 to Mp3 in One Command"},{"content":"URLs of transcripts Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 [ \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-1-pilot-episode/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-2-the-big-bran-hypothesis/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-3-the-fuzzy-boots-corollary/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-4-the-luminous-fish-effect/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-5-the-hamburger-postulate/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-6-the-middle-earth-paradigm/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-7-the-dumpling-paradox/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-8-the-grasshopper-experiment/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-9-the-cooper-hofstadter-polarization/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-10-the-loobenfeld-decay/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-11-the-pancake-batter-anomaly/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-12-the-jerusalem-duality/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-13-the-bat-jar-conjecture/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-14-the-nerdvana-annihilation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-15-the-porkchop-indeterminacy/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-16-the-peanut-reaction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-17-the-tangerine-factor/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-01-the-bad-fish-paradigm/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-02-the-codpiece-topology/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-03-the-barbarian-sublimation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-04-the-griffin-equivalency/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-5-the-euclid-alternative/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-06-the-cooper-nowitzki-theorem-2/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-07-the-panty-pinata-polarization/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-1-episode-08-the-lizard-spock-expansion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-09-the-white-asparagus-triangulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-11-the-vartabedian-conundrum/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-11-the-bath-item-gift-hypothesis/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-12-the-killer-robot-instability/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-13-the-friendship-algorithm/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-14-the-financial-permeability-2/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-15-the-maternal-capacitance/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-16-the-cushion-saturation-3/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-17-the-terminator-decoupling/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-18-the-work-song-nanocluster/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-19-the-dead-hooker-juxtaposition/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-20-the-hofstadter-isotope/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-21-the-vegas-renormalization/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-22-the-classified-materials-turbulence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-2-episode-23-the-monopolar-expedition/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-01-the-electric-can-opener-fluctuation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-02-the-jiminy-conjecture/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-03-the-gothowitz-deviation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-04-the-pirate-solution/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-05-the-creepy-candy-coating-corollary/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-06-the-cornhusker-vortex/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-07-the-guitarist-amplification/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-08-the-adhesive-duck-deficiency/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-09-the-vengeance-formulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-10-the-gorilla-experiment/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-11-the-maternal-congruence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-12-the-psychic-vortex/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-13-the-bozeman-reaction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-14-the-einstein-approximation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-15-the-large-hadron-collision/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-16-the-excelsior-acquisition/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-17-the-precious-fragmentation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-18-the-pants-alternative/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-19-the-wheaton-recurrence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-20-the-spaghetti-catalyst/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-21-the-plimpton-stimulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-22-the-staircase-implementation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-3-episode-23-the-lunar-excitation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-01-the-robotic-manipulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-02-the-cruciferous-vegetable-amplification/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-03-the-zazzy-substitution/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-04-the-hot-troll-deviation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-05-the-desperation-emanation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-06-the-irish-pub-formulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-07-the-apology-insufficiency/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-08-the-21-second-excitation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-09-the-boyfriend-complexity/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-10-the-alien-parasite-hypothesis/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-11-the-justice-league-recombination/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-12-the-bus-pants-utilization/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-13-the-love-car-displacement/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-14-the-thespian-catalyst/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-15-the-benefactor-factor/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-16-the-cohabitation-formulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-17-the-toast-derivation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-18-the-prestidigitation-approximation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-19-the-zarnecki-incursion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-20-the-herb-garden-germination/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-21-the-agreement-dissection/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-22-the-wildebeest-implementation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-23-the-engagement-reaction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-4-episode-24-the-roommate-transmogrification/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-01-the-skank-reflex-analysis/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-02-the-infestation-hypothesis/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-03-the-pulled-groin-extrapolation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-04-the-wiggly-finger-catalyst/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-05-the-russian-rocket-reaction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-06-the-rhinitis-revelation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-07-the-good-guy-fluctuation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-08-the-isolation-permutation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-09-the-ornithophobia-diffusion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-10-the-flaming-spittoon-acquisition/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-11-the-speckerman-recurrence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-12-the-shiny-trinket-maneouvre/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-13-the-recombination-hypothesis/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-14-the-beta-test-initiation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-15-the-friendship-contraction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-16-the-vacation-solution/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-17-the-rothman-disintegration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-18-the-werewolf-transformation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-19-the-weekend-vortex/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-20-the-transporter-malfunction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-21-the-hawking-excitation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-22-the-stag-convergence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-23-the-launch-acceleration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-5-episode-24-the-countdown-reflection/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-01-the-date-night-variable/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-02-the-decoupling-fluctuation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-03-the-higgs-boson-observation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-04-the-re-entry-minimization/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-05-the-holographic-excitation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-06-the-extract-obliteration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-07-the-habitation-configuration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-08-the-43-peculiarity/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-09-the-parking-spot-escalation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-10-the-fish-guts-displacement/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-11-the-santa-simulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-12-the-egg-salad-equivalency/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-13-the-bakersfield-expedition/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-14-the-cooperkripke-inversion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-15-the-spoiler-alert-segmentation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-16-the-tangible-affection-proof/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-17-the-monster-isolation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-18-the-contractual-obligation-implementation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-19-the-closet-reconfiguration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-20-the-tenure-turbulence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-21-the-closure-alternative/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-6-episode-22-the-proton-resurgence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-06-episode-23-the-love-spell-potential/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-06-episode-24-the-bon-voyage-reaction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-01-the-hofstadter-insufficiency/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-02-the-deception-verification/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-03-the-scavenger-vortex/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-04-the-raiders-minimization/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-05-the-workplace-proximity/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-06-the-romance-resonance/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-07-the-proton-displacement/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-08-the-itchy-brain-simulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-09-the-thanksgiving-decoupling/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-10-the-discovery-dissipation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-11-the-cooper-extraction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-12-the-hesitation-ramification/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-13-the-occupation-recalibration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-14-the-convention-conundrum/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-15-the-locomotive-manipulation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-16-the-table-polarisation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-17-the-friendship-turbulence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-18-the-mommy-observation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-19-the-indecision-amalgamation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-20-the-relationship-diremption/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-21-the-anything-can-happen-recurrence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-22-the-proton-transmogrification/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-23-the-gorilla-dissolution/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-24-the-status-quo-combustion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-01-the-locomotion-interruption/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-02-the-junior-professor-solution/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-03-the-first-pitch-insufficiency/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-04-the-hook-up-reverbration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-7-episode-05-the-focus-attenuation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-06-the-expedition-approximation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-07-the-misinterpretation-agitation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-08-the-prom-equivalency/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-09-the-septum-deviation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-10-the-champagne-reflection/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-11-the-clean-room-infiltration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-12-the-space-probe-disintegration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-13-the-anxiety-optimisation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-14-the-troll-manifestation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-15-the-comic-book-store-regeneration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-16-the-intimacy-acceleration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-17-the-colonization-application/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-18-the-leftover-thermalization/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-19-the-skywalker-incursion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-20-the-fortification-implementation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-21-the-communication-deterioration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-22-the-graduation-transmission/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-23-the-maternal-combustion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-8-episode-24-the-commitment-determination/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-01-the-matrimonial-momentum/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-02-the-separation-oscillation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-03-the-batchelor-party-corrosion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-04-the-2003-approximation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-05-the-perspiration-implementation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-06-the-helium-insufficiency/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-07-the-spock-resonance/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-08-the-mystery-date-observation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-09-the-platonic-permutation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-10-the-earworm-reverberation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-11-the-opening-night-excitation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-12-the-sales-call-sublimation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-13-the-empathy-optimisation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-14-the-meemaw-materialisation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-15-the-valentino-submergence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-16-the-positive-negative-reaction/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-17-the-celebration-experimentation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-18-the-application-deterioration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-19-the-solder-excursion-diversion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-20-the-big-bear-precipitation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-21-the-viewing-party-combustion/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-22-the-fermentation-bifurcation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-23-the-line-substitution-solution/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-9-episode-24-the-convergence-convergence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-01-the-conjugal-conjecture/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-02-the-military-miniturization/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-03-the-dependence-transcendence/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-04-the-cohabitation-experimentation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-05-the-hot-tub-contamination/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-06-the-foetal-kick-catalyst/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-07-the-veracity-elasticity/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-08-the-brain-bowl-incubation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-09-the-geology-elevation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-10-the-property-division-collision/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-11-the-birthday-synchronicity/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-12-the-holiday-summation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-13-the-romance-recalibration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-14-the-emotion-detection-automation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-15-the-locomotion-reverberation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-16-the-allowance-evaporation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-17-the-comic-con-conundrum/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-18-the-escape-hatch-identification/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-19-the-collaboration-fluctuation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-20-the-recollection-dissipation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-21-the-separation-agitation/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-22-the-cognition-regeneration/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-23-the-gyroscopic-collapse/\u0026#34;, \u0026#34;https://bigbangtrans.wordpress.com/series-10-episode-24-the-long-distance-dissonance/\u0026#34; ] Script Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import requests from bs4 import BeautifulSoup import os url_list = [] def download_script(url): response = requests.get(url) response.encoding = \u0026#34;utf-8\u0026#34; soup = BeautifulSoup(response.text, \u0026#34;html.parser\u0026#34;) script_text = \u0026#34;\u0026#34; title = soup.find(\u0026#34;h2\u0026#34;, class_=\u0026#34;title\u0026#34;).get_text() script_text = script_text + \u0026#34;## \u0026#34; + title + \u0026#34;\\n\\n\u0026#34; div = soup.find(\u0026#34;div\u0026#34;, class_=\u0026#34;entrytext\u0026#34;) p_tags = div.find_all(\u0026#34;p\u0026#34;) for p in p_tags: text = p.get_text() print(text) try: before, after = text.split(\u0026#34;:\u0026#34;, 1) script_text = script_text + \u0026#34;**\u0026#34; + before + \u0026#34;**\u0026#34; + \u0026#34;: \u0026#34; + after + \u0026#34;\\n\\n\u0026#34; except: script_text = script_text + text + \u0026#34;\\n\\n\u0026#34; return script_text with open(\u0026#34;TBBT.md\u0026#34;, \u0026#34;a\u0026#34;, encoding=\u0026#34;utf-8\u0026#34;) as f: for url in url_list: print(download_script(url), file=f) ","date":"2025-06-13T12:17:40+08:00","permalink":"/posts/download-tbbt-transcript-from-website/","title":"Download TBBT Transcript From Website"},{"content":"Install nbconvert via pip\nShow/Hide the code 1 pip install nbconvert Now, the command\nShow/Hide the code 1 jupyter nbconvert --to pdf --template-file report filename.ipynb should work well, producing a document with a table of contents and properly formatted code blocks. However, an unnecessary counter appears before each code block, wasting space and serving no purpose. To remove it, a custom template is required.\nThe template consists of two files: assignment.tex.j2 and style_assignment.tex.j2, which are modified duplicates of existing files. Template files are located in share\\jupyter\\nbconvert\\templates\\latex. Duplicate report.tex.j2 and modify the second line to\nShow/Hide the code 1 ((* set cell_style = \u0026#39;style_assignment.tex.j2\u0026#39; *)) The file style_assignment.tex.j2 is a duplicate of style_jupyter.tex.j2 with the line\nShow/Hide the code 1 {\\ttfamily\\llap{{\\color{#2}[#3]:\\hspace{3pt}#4}}\\vspace{-\\baselineskip}} replaced by\nShow/Hide the code 1 {\\ttfamily\\llap{{\\color{#2}\\hspace{3pt}#4}}} Moreover, in order to support Chinese, the code below should be added\nShow/Hide the code 1 2 \\usepackage{xeCJK} \\setCJKmainfont{SimSun} Now that custom files are used, the command is\nShow/Hide the code 1 jupyter nbconvert --to pdf --template-file assignment filename.ipynb or dictate author names and the document title as converting:\nShow/Hide the code 1 jupyter nbconvert --to pdf --template-file assignment ./Journal.ipynb --LatexPreprocessor.author_names=\u0026#34;Name\u0026#34; --LatexPreprocessor.title=\u0026#34;Title\u0026#34; The complete file is shown as follows:\nassignment.tex.j2 Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 % Default to the notebook output style ((* if not cell_style is defined *)) ((* set cell_style = \u0026#39;style_assignment.tex.j2\u0026#39; *)) ((* endif *)) % Inherit from the specified cell style. ((* extends cell_style *)) %=============================================================================== % Latex Book %=============================================================================== ((* block predoc *)) ((( super() ))) ((* block tableofcontents *))\\tableofcontents((* endblock tableofcontents *)) ((* endblock predoc *)) ((* block docclass *)) \\documentclass{report} ((* endblock docclass *)) ((* block markdowncell scoped *)) ((( cell.source | citation2latex | strip_files_prefix | convert_pandoc(\u0026#39;markdown+tex_math_double_backslash\u0026#39;, \u0026#39;json\u0026#39;,extra_args=[]) | resolve_references | convert_pandoc(\u0026#39;json\u0026#39;,\u0026#39;latex\u0026#39;, extra_args=[\u0026#34;--top-level-division=chapter\u0026#34;]) ))) ((* endblock markdowncell *)) style_assignment.tex.j2 Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 ((=- IPython input/output style -=)) ((*- extends \u0026#39;base.tex.j2\u0026#39; -*)) ((*- block packages -*)) \\usepackage{xeCJK} \\setCJKmainfont{SimSun} \\usepackage[breakable]{tcolorbox} \\usepackage{parskip} % Stop auto-indenting (to mimic markdown behaviour) ((( super() ))) ((*- endblock packages -*)) ((*- block definitions -*)) ((( super() ))) % Pygments definitions (((- resources.latex.pygments_definitions ))) % For linebreaks inside Verbatim environment from package fancyvrb. \\makeatletter \\newbox\\Wrappedcontinuationbox \\newbox\\Wrappedvisiblespacebox \\newcommand*\\Wrappedvisiblespace {\\textcolor{red}{\\textvisiblespace}} \\newcommand*\\Wrappedcontinuationsymbol {\\textcolor{red}{\\llap{\\tiny$\\m@th\\hookrightarrow$}}} \\newcommand*\\Wrappedcontinuationindent {3ex } \\newcommand*\\Wrappedafterbreak {\\kern\\Wrappedcontinuationindent\\copy\\Wrappedcontinuationbox} % Take advantage of the already applied Pygments mark-up to insert % potential linebreaks for TeX processing. % {, \u0026lt;, #, %, $, \u0026#39; and \u0026#34;: go to next line. % _, }, ^, \u0026amp;, \u0026gt;, - and ~: stay at end of broken line. % Use of \\textquotesingle for straight quote. \\newcommand*\\Wrappedbreaksatspecials {% \\def\\PYGZus{\\discretionary{\\char`\\_}{\\Wrappedafterbreak}{\\char`\\_}}% \\def\\PYGZob{\\discretionary{}{\\Wrappedafterbreak\\char`\\{}{\\char`\\{}}% \\def\\PYGZcb{\\discretionary{\\char`\\}}{\\Wrappedafterbreak}{\\char`\\}}}% \\def\\PYGZca{\\discretionary{\\char`\\^}{\\Wrappedafterbreak}{\\char`\\^}}% \\def\\PYGZam{\\discretionary{\\char`\\\u0026amp;}{\\Wrappedafterbreak}{\\char`\\\u0026amp;}}% \\def\\PYGZlt{\\discretionary{}{\\Wrappedafterbreak\\char`\\\u0026lt;}{\\char`\\\u0026lt;}}% \\def\\PYGZgt{\\discretionary{\\char`\\\u0026gt;}{\\Wrappedafterbreak}{\\char`\\\u0026gt;}}% \\def\\PYGZsh{\\discretionary{}{\\Wrappedafterbreak\\char`\\#}{\\char`\\#}}% \\def\\PYGZpc{\\discretionary{}{\\Wrappedafterbreak\\char`\\%}{\\char`\\%}}% \\def\\PYGZdl{\\discretionary{}{\\Wrappedafterbreak\\char`\\$}{\\char`\\$}}% \\def\\PYGZhy{\\discretionary{\\char`\\-}{\\Wrappedafterbreak}{\\char`\\-}}% \\def\\PYGZsq{\\discretionary{}{\\Wrappedafterbreak\\textquotesingle}{\\textquotesingle}}% \\def\\PYGZdq{\\discretionary{}{\\Wrappedafterbreak\\char`\\\u0026#34;}{\\char`\\\u0026#34;}}% \\def\\PYGZti{\\discretionary{\\char`\\~}{\\Wrappedafterbreak}{\\char`\\~}}% } % Some characters . , ; ? ! / are not pygmentized. % This macro makes them \u0026#34;active\u0026#34; and they will insert potential linebreaks \\newcommand*\\Wrappedbreaksatpunct {% \\lccode`\\~`\\.\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\.}}{\\Wrappedafterbreak}{\\hbox{\\char`\\.}}}% \\lccode`\\~`\\,\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\,}}{\\Wrappedafterbreak}{\\hbox{\\char`\\,}}}% \\lccode`\\~`\\;\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\;}}{\\Wrappedafterbreak}{\\hbox{\\char`\\;}}}% \\lccode`\\~`\\:\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\:}}{\\Wrappedafterbreak}{\\hbox{\\char`\\:}}}% \\lccode`\\~`\\?\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\?}}{\\Wrappedafterbreak}{\\hbox{\\char`\\?}}}% \\lccode`\\~`\\!\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\!}}{\\Wrappedafterbreak}{\\hbox{\\char`\\!}}}% \\lccode`\\~`\\/\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\/}}{\\Wrappedafterbreak}{\\hbox{\\char`\\/}}}% \\catcode`\\.\\active \\catcode`\\,\\active \\catcode`\\;\\active \\catcode`\\:\\active \\catcode`\\?\\active \\catcode`\\!\\active \\catcode`\\/\\active \\lccode`\\~`\\~ } \\makeatother \\let\\OriginalVerbatim=\\Verbatim \\makeatletter \\renewcommand{\\Verbatim}[1][1]{% %\\parskip\\z@skip \\sbox\\Wrappedcontinuationbox {\\Wrappedcontinuationsymbol}% \\sbox\\Wrappedvisiblespacebox {\\FV@SetupFont\\Wrappedvisiblespace}% \\def\\FancyVerbFormatLine ##1{\\hsize\\linewidth \\vtop{\\raggedright\\hyphenpenalty\\z@\\exhyphenpenalty\\z@ \\doublehyphendemerits\\z@\\finalhyphendemerits\\z@ \\strut ##1\\strut}% }% % If the linebreak is at a space, the latter will be displayed as visible % space at end of first line, and a continuation symbol starts next line. % Stretch/shrink are however usually zero for typewriter font. \\def\\FV@Space {% \\nobreak\\hskip\\z@ plus\\fontdimen3\\font minus\\fontdimen4\\font \\discretionary{\\copy\\Wrappedvisiblespacebox}{\\Wrappedafterbreak} {\\kern\\fontdimen2\\font}% }% % Allow breaks at special characters using \\PYG... macros. \\Wrappedbreaksatspecials % Breaks at punctuation characters . , ; ? ! and / need catcode=\\active \\OriginalVerbatim[#1,codes*=\\Wrappedbreaksatpunct]% } \\makeatother % Exact colors from NB ((*- block style_colors *)) \\definecolor{incolor}{HTML}{303F9F} \\definecolor{outcolor}{HTML}{D84315} \\definecolor{cellborder}{HTML}{CFCFCF} \\definecolor{cellbackground}{HTML}{F7F7F7} ((*- endblock style_colors *)) % prompt \\makeatletter \\newcommand{\\boxspacing}{\\kern\\kvtcb@left@rule\\kern\\kvtcb@boxsep} \\makeatother ((*- block style_prompt *)) \\newcommand{\\prompt}[4]{ {\\ttfamily\\llap{{\\color{#2}\\hspace{3pt}#4}}} } ((* endblock style_prompt *)) ((*- endblock definitions -*)) %=============================================================================== % Input %=============================================================================== ((* block input scoped *)) ((( draw_cell(cell.source | highlight_code(strip_verbatim=True), cell, \u0026#39;In\u0026#39;, \u0026#39;incolor\u0026#39;, \u0026#39;\\\\boxspacing\u0026#39;) ))) ((* endblock input *)) %=============================================================================== % Output %=============================================================================== ((*- if charlim is not defined -*)) ((* set charlim = 80 *)) ((*- endif -*)) ((* block execute_result scoped *)) ((*- for type in output.data | filter_data_type -*)) ((*- if type in [\u0026#39;text/plain\u0026#39;]*)) ((( draw_cell(output.data[\u0026#39;text/plain\u0026#39;] | wrap_text(charlim) | escape_latex | ansi2latex, cell, \u0026#39;Out\u0026#39;, \u0026#39;outcolor\u0026#39;, \u0026#39;\\\\boxspacing\u0026#39;) ))) ((* else -*)) ((( \u0026#34; \u0026#34; ))) ((( draw_prompt(cell, \u0026#39;Out\u0026#39;, \u0026#39;outcolor\u0026#39;,\u0026#39;\u0026#39;) )))((( super() ))) ((*- endif -*)) ((*- endfor -*)) ((* endblock execute_result *)) ((* block stream *)) \\begin{Verbatim}[commandchars=\\\\\\{\\}] ((( output.text | wrap_text(charlim) | escape_latex | strip_trailing_newline | ansi2latex ))) \\end{Verbatim} ((* endblock stream *)) %============================================================================== % Support Macros %============================================================================== % Name: draw_cell % Purpose: Renders an output/input prompt ((*- if draw_cell is not defined -*)) % Required to allow overriding. ((* macro draw_cell(text, cell, prompt, prompt_color, extra_space) -*)) ((*- if prompt == \u0026#39;In\u0026#39; -*)) ((*- set style = \u0026#34;breakable, size=fbox, boxrule=1pt, pad at break*=1mm,colback=cellbackground, colframe=cellborder\u0026#34;-*)) ((*- else -*))((*- set style = \u0026#34;breakable, size=fbox, boxrule=.5pt, pad at break*=1mm, opacityfill=0\u0026#34;-*))((*- endif -*)) \\begin{tcolorbox}[((( style )))] (((- draw_prompt(cell, prompt, prompt_color, extra_space) ))) \\begin{Verbatim}[commandchars=\\\\\\{\\}] ((( text ))) \\end{Verbatim} \\end{tcolorbox} ((*- endmacro *)) ((*- endif -*)) % Name: draw_prompt % Purpose: Renders an output/input prompt ((* macro draw_prompt(cell, prompt, prompt_color, extra_space) -*)) ((*- if cell.execution_count is defined -*)) ((*- set execution_count = \u0026#34;\u0026#34; ~ (cell.execution_count | replace(None, \u0026#34; \u0026#34;)) -*)) ((*- else -*))((*- set execution_count = \u0026#34; \u0026#34; -*))((*- endif *)) ((*- if (resources.global_content_filter.include_output_prompt and prompt == \u0026#39;Out\u0026#39;) or (resources.global_content_filter.include_input_prompt and prompt == \u0026#39;In\u0026#39; ) *)) \\prompt{(((prompt)))}{(((prompt_color)))}{(((execution_count)))}{(((extra_space)))} ((*- endif -*)) ((*- endmacro *)) Furthermore, if you want to hide code:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 ((=- IPython input/output style -=)) ((*- extends \u0026#39;base.tex.j2\u0026#39; -*)) ((*- block packages -*)) \\usepackage{xeCJK} \\setCJKmainfont{SimSun} \\usepackage[breakable]{tcolorbox} \\usepackage{parskip} % Stop auto-indenting (to mimic markdown behaviour) ((( super() ))) ((*- endblock packages -*)) ((*- block definitions -*)) ((( super() ))) % Pygments definitions (((- resources.latex.pygments_definitions ))) % For linebreaks inside Verbatim environment from package fancyvrb. \\makeatletter \\newbox\\Wrappedcontinuationbox \\newbox\\Wrappedvisiblespacebox \\newcommand*\\Wrappedvisiblespace {\\textcolor{red}{\\textvisiblespace}} \\newcommand*\\Wrappedcontinuationsymbol {\\textcolor{red}{\\llap{\\tiny$\\m@th\\hookrightarrow$}}} \\newcommand*\\Wrappedcontinuationindent {3ex } \\newcommand*\\Wrappedafterbreak {\\kern\\Wrappedcontinuationindent\\copy\\Wrappedcontinuationbox} % Take advantage of the already applied Pygments mark-up to insert % potential linebreaks for TeX processing. % {, \u0026lt;, #, %, $, \u0026#39; and \u0026#34;: go to next line. % _, }, ^, \u0026amp;, \u0026gt;, - and ~: stay at end of broken line. % Use of \\textquotesingle for straight quote. \\newcommand*\\Wrappedbreaksatspecials {% \\def\\PYGZus{\\discretionary{\\char`\\_}{\\Wrappedafterbreak}{\\char`\\_}}% \\def\\PYGZob{\\discretionary{}{\\Wrappedafterbreak\\char`\\{}{\\char`\\{}}% \\def\\PYGZcb{\\discretionary{\\char`\\}}{\\Wrappedafterbreak}{\\char`\\}}}% \\def\\PYGZca{\\discretionary{\\char`\\^}{\\Wrappedafterbreak}{\\char`\\^}}% \\def\\PYGZam{\\discretionary{\\char`\\\u0026amp;}{\\Wrappedafterbreak}{\\char`\\\u0026amp;}}% \\def\\PYGZlt{\\discretionary{}{\\Wrappedafterbreak\\char`\\\u0026lt;}{\\char`\\\u0026lt;}}% \\def\\PYGZgt{\\discretionary{\\char`\\\u0026gt;}{\\Wrappedafterbreak}{\\char`\\\u0026gt;}}% \\def\\PYGZsh{\\discretionary{}{\\Wrappedafterbreak\\char`\\#}{\\char`\\#}}% \\def\\PYGZpc{\\discretionary{}{\\Wrappedafterbreak\\char`\\%}{\\char`\\%}}% \\def\\PYGZdl{\\discretionary{}{\\Wrappedafterbreak\\char`\\$}{\\char`\\$}}% \\def\\PYGZhy{\\discretionary{\\char`\\-}{\\Wrappedafterbreak}{\\char`\\-}}% \\def\\PYGZsq{\\discretionary{}{\\Wrappedafterbreak\\textquotesingle}{\\textquotesingle}}% \\def\\PYGZdq{\\discretionary{}{\\Wrappedafterbreak\\char`\\\u0026#34;}{\\char`\\\u0026#34;}}% \\def\\PYGZti{\\discretionary{\\char`\\~}{\\Wrappedafterbreak}{\\char`\\~}}% } % Some characters . , ; ? ! / are not pygmentized. % This macro makes them \u0026#34;active\u0026#34; and they will insert potential linebreaks \\newcommand*\\Wrappedbreaksatpunct {% \\lccode`\\~`\\.\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\.}}{\\Wrappedafterbreak}{\\hbox{\\char`\\.}}}% \\lccode`\\~`\\,\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\,}}{\\Wrappedafterbreak}{\\hbox{\\char`\\,}}}% \\lccode`\\~`\\;\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\;}}{\\Wrappedafterbreak}{\\hbox{\\char`\\;}}}% \\lccode`\\~`\\:\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\:}}{\\Wrappedafterbreak}{\\hbox{\\char`\\:}}}% \\lccode`\\~`\\?\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\?}}{\\Wrappedafterbreak}{\\hbox{\\char`\\?}}}% \\lccode`\\~`\\!\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\!}}{\\Wrappedafterbreak}{\\hbox{\\char`\\!}}}% \\lccode`\\~`\\/\\lowercase{\\def~}{\\discretionary{\\hbox{\\char`\\/}}{\\Wrappedafterbreak}{\\hbox{\\char`\\/}}}% \\catcode`\\.\\active \\catcode`\\,\\active \\catcode`\\;\\active \\catcode`\\:\\active \\catcode`\\?\\active \\catcode`\\!\\active \\catcode`\\/\\active \\lccode`\\~`\\~ } \\makeatother \\let\\OriginalVerbatim=\\Verbatim \\makeatletter \\renewcommand{\\Verbatim}[1][1]{% %\\parskip\\z@skip \\sbox\\Wrappedcontinuationbox {\\Wrappedcontinuationsymbol}% \\sbox\\Wrappedvisiblespacebox {\\FV@SetupFont\\Wrappedvisiblespace}% \\def\\FancyVerbFormatLine ##1{\\hsize\\linewidth \\vtop{\\raggedright\\hyphenpenalty\\z@\\exhyphenpenalty\\z@ \\doublehyphendemerits\\z@\\finalhyphendemerits\\z@ \\strut ##1\\strut}% }% % If the linebreak is at a space, the latter will be displayed as visible % space at end of first line, and a continuation symbol starts next line. % Stretch/shrink are however usually zero for typewriter font. \\def\\FV@Space {% \\nobreak\\hskip\\z@ plus\\fontdimen3\\font minus\\fontdimen4\\font \\discretionary{\\copy\\Wrappedvisiblespacebox}{\\Wrappedafterbreak} {\\kern\\fontdimen2\\font}% }% % Allow breaks at special characters using \\PYG... macros. \\Wrappedbreaksatspecials % Breaks at punctuation characters . , ; ? ! and / need catcode=\\active \\OriginalVerbatim[#1,codes*=\\Wrappedbreaksatpunct]% } \\makeatother % Exact colors from NB ((*- block style_colors *)) \\definecolor{incolor}{HTML}{303F9F} \\definecolor{outcolor}{HTML}{D84315} \\definecolor{cellborder}{HTML}{CFCFCF} \\definecolor{cellbackground}{HTML}{F7F7F7} ((*- endblock style_colors *)) % prompt \\makeatletter \\newcommand{\\boxspacing}{\\kern\\kvtcb@left@rule\\kern\\kvtcb@boxsep} \\makeatother ((*- block style_prompt *)) \\newcommand{\\prompt}[4]{ {\\ttfamily\\llap{{\\color{#2}\\hspace{3pt}#4}}} } ((* endblock style_prompt *)) ((*- endblock definitions -*)) %=============================================================================== % Input %=============================================================================== ((* block input scoped *)) % input hidden ((* endblock input *)) %=============================================================================== % Output %=============================================================================== ((*- if charlim is not defined -*)) ((* set charlim = 80 *)) ((*- endif -*)) ((* block execute_result scoped *)) ((*- for type in output.data | filter_data_type -*)) ((*- if type in [\u0026#39;text/plain\u0026#39;]*)) ((( draw_cell(output.data[\u0026#39;text/plain\u0026#39;] | wrap_text(charlim) | escape_latex | ansi2latex, cell, \u0026#39;Out\u0026#39;, \u0026#39;outcolor\u0026#39;, \u0026#39;\\\\boxspacing\u0026#39;) ))) ((* else -*)) ((( \u0026#34; \u0026#34; ))) ((( draw_prompt(cell, \u0026#39;Out\u0026#39;, \u0026#39;outcolor\u0026#39;,\u0026#39;\u0026#39;) )))((( super() ))) ((*- endif -*)) ((*- endfor -*)) ((* endblock execute_result *)) ((* block stream *)) \\begin{Verbatim}[commandchars=\\\\\\{\\}] ((( output.text | wrap_text(charlim) | escape_latex | strip_trailing_newline | ansi2latex ))) \\end{Verbatim} ((* endblock stream *)) %============================================================================== % Support Macros %============================================================================== % Name: draw_cell % Purpose: Renders an output/input prompt ((*- if draw_cell is not defined -*)) % Required to allow overriding. ((* macro draw_cell(text, cell, prompt, prompt_color, extra_space) -*)) ((*- if prompt == \u0026#39;In\u0026#39; -*)) ((*- set style = \u0026#34;breakable, size=fbox, boxrule=1pt, pad at break*=1mm,colback=cellbackground, colframe=cellborder\u0026#34;-*)) ((*- else -*))((*- set style = \u0026#34;breakable, size=fbox, boxrule=.5pt, pad at break*=1mm, opacityfill=0\u0026#34;-*))((*- endif -*)) \\begin{tcolorbox}[((( style )))] (((- draw_prompt(cell, prompt, prompt_color, extra_space) ))) \\begin{Verbatim}[commandchars=\\\\\\{\\}] ((( text ))) \\end{Verbatim} \\end{tcolorbox} ((*- endmacro *)) ((*- endif -*)) % Name: draw_prompt % Purpose: Renders an output/input prompt ((* macro draw_prompt(cell, prompt, prompt_color, extra_space) -*)) ((*- if cell.execution_count is defined -*)) ((*- set execution_count = \u0026#34;\u0026#34; ~ (cell.execution_count | replace(None, \u0026#34; \u0026#34;)) -*)) ((*- else -*))((*- set execution_count = \u0026#34; \u0026#34; -*))((*- endif *)) ((*- if (resources.global_content_filter.include_output_prompt and prompt == \u0026#39;Out\u0026#39;) or (resources.global_content_filter.include_input_prompt and prompt == \u0026#39;In\u0026#39; ) *)) \\prompt{(((prompt)))}{(((prompt_color)))}{(((execution_count)))}{(((extra_space)))} ((*- endif -*)) ((*- endmacro *)) ","date":"2025-06-13T00:00:00Z","image":"/posts/convert-jupyter-notebook-to-pdf-with-reporting-format/image.png","permalink":"/posts/convert-jupyter-notebook-to-pdf-with-reporting-format/","title":"Convert Jupyter Notebook to PDF With Reporting Format"},{"content":" exporting all selected notes with media references extract media paths from the exported file write a python script merging all selected audios into one Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 import os import subprocess import pandas as pd from concurrent.futures import ThreadPoolExecutor, as_completed from tqdm import tqdm import random AUDIO_DIRECTORY = r\u0026#34;C:\\Users\\kyle\\AppData\\Roaming\\Anki2\\Eng\\collection.media\u0026#34; SILENT = r\u0026#34;C:\\Users\\momo\\Home\\Projects\\Anki\\silent.mp3\u0026#34; list_file_path = \u0026#34;../notes.txt\u0026#34; df = pd.read_csv( list_file_path, sep=\u0026#34;\\t\u0026#34;, header=None, names=[ \u0026#34;word\u0026#34;, \u0026#34;lemma\u0026#34;, \u0026#34;context\u0026#34;, \u0026#34;sentence\u0026#34;, \u0026#34;examples\u0026#34;, \u0026#34;symbol\u0026#34;, \u0026#34;voc\u0026#34;, \u0026#34;def\u0026#34;, \u0026#34;word_sound\u0026#34;, \u0026#34;sentence_sound\u0026#34; ], ) word_audio_names = df[\u0026#34;word_sound\u0026#34;].apply(lambda x: x.strip()[7:-1]).tolist() df[\u0026#34;sentence_sound\u0026#34;] = df[\u0026#34;sentence_sound\u0026#34;].fillna(\u0026#34;\u0026#34;) sentence_audio_names = df[\u0026#34;sentence_sound\u0026#34;].apply(lambda x: x.strip()[7:-1]).tolist() audio_paths = [os.path.join(AUDIO_DIRECTORY, item) for item in word_audio_names] + [ os.path.join(AUDIO_DIRECTORY, item) for item in sentence_audio_names if item != \u0026#34;\u0026#34; ] def normalize_audio(input_file, output_file): try: command = [ \u0026#34;ffmpeg\u0026#34;, \u0026#34;-loglevel\u0026#34;, \u0026#34;quiet\u0026#34;, \u0026#34;-y\u0026#34;, \u0026#34;-i\u0026#34;, input_file, \u0026#34;-ar\u0026#34;, \u0026#34;24000\u0026#34;, \u0026#34;-ab\u0026#34;, \u0026#34;96k\u0026#34;, output_file ] subprocess.run(command, check=True) return output_file except subprocess.CalledProcessError as e: return None def normalize_audio_multithreaded(file_list, output_dir, max_workers=16): if not os.path.exists(output_dir): os.makedirs(output_dir) print(\u0026#34;start normalizing audios\u0026#34;) with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = [ executor.submit(normalize_audio, input_file, os.path.join(output_dir, os.path.basename(input_file))) for input_file in file_list ] for _ in tqdm(as_completed(futures), total=len(file_list)): pass else: print(\u0026#34;files has prepared well\u0026#34;) normalize_audio_multithreaded(audio_paths, \u0026#34;temp\u0026#34;) audio_paths = [(w, s) for w, s in zip(word_audio_names, sentence_audio_names)] random.shuffle(audio_paths) with open(\u0026#34;file_list.txt\u0026#34;, \u0026#34;w\u0026#34;) as f: for w, s in audio_paths: f.write(f\u0026#34;file \u0026#39;{os.path.join(\u0026#39;temp\u0026#39;, w)}\u0026#39;\\n\u0026#34;) f.write(f\u0026#34;file silent.mp3\\n\u0026#34;) f.write(f\u0026#34;file \u0026#39;{os.path.join(\u0026#39;temp\u0026#39;, w)}\u0026#39;\\n\u0026#34;) f.write(f\u0026#34;file silent.mp3\\n\u0026#34;) if s != \u0026#34;\u0026#34;: f.write(f\u0026#34;file \u0026#39;{os.path.join(\u0026#39;temp\u0026#39;, s)}\u0026#39;\\n\u0026#34;) f.write(f\u0026#34;file silent.mp3\\n\u0026#34;) f.write(f\u0026#34;file silent.mp3\\n\u0026#34;) command = [ \u0026#34;ffmpeg\u0026#34;, \u0026#34;-y\u0026#34;, \u0026#34;-f\u0026#34;, \u0026#34;concat\u0026#34;, \u0026#34;-safe\u0026#34;, \u0026#34;0\u0026#34;, \u0026#34;-i\u0026#34;, \u0026#34;file_list.txt\u0026#34;, \u0026#34;-c\u0026#34;, \u0026#34;copy\u0026#34;, \u0026#34;output.mp3\u0026#34; ] subprocess.run(command, check=True) ","date":"2025-06-13T00:00:00Z","permalink":"/posts/merge-anki-audios/","title":"Merge Anki Audios"},{"content":"Introduction Dictionaries such as \u0026ldquo;Oxford\u0026rdquo; and \u0026ldquo;Longman\u0026rdquo; are used as the sources for the definitions in my flashcards. However, they sometimes contain too much unnecessary information, therefore making it unwieldy and grandiose, leading to a low loading speed and distractions.\nSince an MDX file utilizes the HTML format to save entries, which closely resembles the tree structure, I use the term \u0026ldquo;prune\u0026rdquo; to describe the course of removing branches, i.e. html nodes that contain superfluous elements.\nEach group of three lines in a mdx file constitutes an entry of a word where the first and the third lines are delimiters while the middle line is html content. Since typically MDX files are quite large, a division step is required for parallel processing. Thus, the breakdown procedures are as follows:\nsplit a gigantic mdx file into several small files. Note: the number of lines in each file must be a multiple of 3. process such files parallel. merge files into one mdx file. Code Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 import sys import os def split_file_by_lines(file_path): file_name, file_extension = os.path.splitext(file_path) lines_per_file = 28311 folder_path = \u0026#34;divided_files\u0026#34; if not os.path.exists(folder_path): os.makedirs(folder_path) else: raise BaseException(\u0026#34;directory exists\u0026#34;) with open(file_path, \u0026#34;r\u0026#34;, encoding=\u0026#34;utf-8\u0026#34;) as f: file_count = 0 lines = [] for line in f: lines.append(line) if len(lines) == lines_per_file: new_file_name = f\u0026#34;{file_name}_{file_count:02d}{file_extension}\u0026#34; with open( os.path.join(folder_path, new_file_name), \u0026#34;w\u0026#34;, encoding=\u0026#34;utf-8\u0026#34; ) as chunk_file: chunk_file.writelines(lines) lines = [] file_count += 1 if lines: new_file_name = f\u0026#34;{file_name}_{file_count}{file_extension}\u0026#34; with open( os.path.join(folder_path, new_file_name), \u0026#34;w\u0026#34;, encoding=\u0026#34;utf-8\u0026#34; ) as chunk_file: chunk_file.writelines(lines) file_count += 1 def merge_files(files, output_file=\u0026#34;res.txt\u0026#34;): with open(output_file, \u0026#34;w\u0026#34;) as f: pass for file in files: if os.path.isfile(file): with open(file, \u0026#34;r\u0026#34;, encoding=\u0026#34;utf-8\u0026#34;) as f: content = f.read() with open(output_file, \u0026#34;a\u0026#34;, encoding=\u0026#34;utf-8\u0026#34;) as f: f.write(content) split_file_by_lines(\u0026#34;./mdx.txt\u0026#34;) os.system( r\u0026#39;ls ./divided_files | parallel -j16 \u0026#34;python3 ./prune.py ./divided_files/{} ./divided_files/new_{}\u0026#34;\u0026#39; ) merge_files([ os.path.join(\u0026#34;./divided_files\u0026#34;, f) for f in os.listdir(\u0026#34;./divided_files\u0026#34;) if os.path.isfile(os.path.join(\u0026#34;./divided_files\u0026#34;, f)) and f.startswith(\u0026#34;new\u0026#34;) ]) import shutil shutil.rmtree(\u0026#34;./divided_files\u0026#34;) detailed pruning code:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 #!/usr/bin/python import sys from bs4 import BeautifulSoup def remove_tags_with_class(html_content): soup = BeautifulSoup(html_content, features=\u0026#34;html.parser\u0026#34;) [tag.decompose() for tag in soup.find_all(\u0026#34;idm-gs-blk\u0026#34;)] [tag.decompose() for tag in soup.find_all(\u0026#34;pv-gs-blk\u0026#34;)] def_tags = soup.find_all(\u0026#34;def\u0026#34;) for def_tag in def_tags: xhtml_a_texts = [a_tag.unwrap() for a_tag in def_tag.find_all(\u0026#34;xhtml:a\u0026#34;)] [tag.decompose() for tag in def_tag.find_all(\u0026#34;chn\u0026#34;)] new_soup = BeautifulSoup( r\u0026#39;\u0026lt;html\u0026gt;\u0026lt;body\u0026gt;\u0026lt;/body\u0026gt;\u0026lt;/html\u0026gt;\u0026#39;, \u0026#34;html.parser\u0026#34;, ) for tag in def_tags: new_soup.body.append(tag) for def_tag in def_tags: new_tag = soup.new_tag(\u0026#34;p\u0026#34;) new_tag.string = def_tag.get_text().strip() def_tag.replace_with(new_tag) return str(new_soup) def process_html_file(input_file, output_file): with open(input_file, \u0026#34;r\u0026#34;, encoding=\u0026#34;utf-8\u0026#34;) as file: lines = file.readlines() with open(output_file, \u0026#34;w\u0026#34;, encoding=\u0026#34;utf-8\u0026#34;) as outfile: for line in lines: if line.strip().startswith(\u0026#34;\u0026lt;head\u0026gt;\u0026lt;link\u0026#34;): new_line = remove_tags_with_class(line) outfile.write(new_line + \u0026#34;\\n\u0026#34;) else: outfile.write(line) input_file = sys.argv[1] output_file = sys.argv[2] process_html_file(input_file, output_file) ","date":"2025-06-13T00:00:00Z","permalink":"/posts/prune-a-dictionary-file.mdx/","title":"Prune a Dictionary File(.mdx)"},{"content":"众所周知，gnome 目前默认使用 wayland，但某些程序在 wayland 下表现不佳。例如 telegram 有时边框外会显示奇怪的阴影，解决方法是开启选项：使用系统边框。然而在 wayland 下没有此选项，取而代之的是：使用 qt 边框，但 qt 边框与 gtk 应用的风格很不统一，导致看起来很丑。解决方法是在其 .desktop 文件中添加环境变量使 telegram 强制使用 x11，事实上，我已经使用QT_QPA_PLATFORM=xcb这个环境变量为另一个程序 anki 解决了这个问题。\n然而，同样的方法对 telegram 却失效了。经过一番摸索我发现，直接运行 .desktop 文件，在命令行运行指令或使用dex命令运行都生效，可一旦从 gnome 的应用抽屉里启动或使用gtk-launch命令运行启动就不生效。这说明文件本身并没有问题，问题出在 gtk 和 gnome 上。问题到这里就陷入了僵局，但是我灵光一现，想到问题或许是 telegram 的 .desktop 文件奇怪的名字导致的：由于 telegram 的全名为 telegram-desktop，因此其 .desktop 文件名为 org.telegram.desktop.desktop。我怀疑是这两个重复的 .desktop 后缀在作祟， 于是我将其改名为 telegram.desktop，随后update-desktop-datebase ~/.local/share/applications/，问题果然解决。\n","date":"2024-02-18T00:00:00Z","permalink":"/posts/gnome-%E4%B8%AD-.desktop-%E6%96%87%E4%BB%B6%E7%9A%84%E5%A5%87%E6%80%AA%E9%97%AE%E9%A2%98/","title":"Gnome 中 .desktop 文件的奇怪问题"},{"content":"在 KDE 上使用 aurorae 主题(除 Breeze 外的所有主题)时，如果字体 DPI 大于 96，应用程序的边框会变得巨大无比，十分丑陋。偏偏在高分屏幕上增加字体 DPI 是放大界面而不损失清晰度的唯一方法，这一问题几乎动摇了我使用 KDE 的决心转而尝试了几天 Gnome (颜值即生产力)。虽然最后还是回到了 KDE，但是这个问题还是亟待解决的。一开始使用的方法是，修改主题时不修改窗口装饰元素，还是用 Breeze 的窗口装饰元素，但是这样导致风格很割裂，不统一。网络上也没有什么好的解决方案，在 github 上看到主题 sweet 的作者声称解决了这个问题，但是当有人询问解决方案时他又不再回答。而另一款主题 materia 的作者提出可以修改主题的 css 文件，虽然这个方法还是不太优雅，但好歹是奏效了。\n具体为修改 /usr/share/aurorae/themes/Materia/Materiarc文件中的PaddingTop，PaddingRight，PaddingBottom，PaddingLeft参数，在 DPI 为 120 时，分别为8，24，48，24。\n","date":"2024-02-08T15:23:00+08:00","permalink":"/posts/kde-%E7%AA%97%E5%8F%A3%E8%A3%85%E9%A5%B0%E5%85%83%E7%B4%A0/","title":"KDE 窗口装饰元素"},{"content":"从 Flatpak 安装的 Obsidian 不显示全局菜单。执行下列命令后解决：\nShow/Hide the code 1 2 sudo flatpak override --talk-name=com.canonical.AppMenu.Regist rar md.obsidian.Obsidian ","date":"2024-01-04T17:42:11+08:00","permalink":"/posts/flatpak-%E4%B8%8E-kde-global-menu-%E7%9A%84%E5%85%BC%E5%AE%B9%E6%80%A7%E9%97%AE%E9%A2%98/","title":"Flatpak 与 KDE Global Menu 的兼容性问题"},{"content":"prime-run steam命令报错X Error of failed request: BadValue (integer parameter out of range for operation)，原因是内核与 nvidia 驱动不匹配。按照 archwiki 的说明，安装linux-zen-headers和nvidia-dkms并添加内核参数CONFIG_DRM_SIMPLEDRM=y后解决。\n","date":"2024-01-01T20:17:04+08:00","permalink":"/posts/linux-zen-%E4%B8%8E-nvidia/","title":"Linux Zen 与 Nvidia"},{"content":"为了使用 waydroid 不得已换 X11 为 Wayland，随之问题就来了。基于 Qt6 的 Anki 似乎与 Wayland 兼容的不太好，无法在 KDE 中使用全局菜单，并且 Goldendict 的Ctrl+c+c粘贴板查词功能在 Anki 里也无法使用了。 Google 上搜索了一番后发现可以用WAYLAND_DISPLAY=\u0026quot;\u0026quot;环境变量强制 Anki 使用 X11 解决。使用后果然没有上述问题了，但是出现了新的问题： fcitx 无法在 Anki 里使用了。略微思考后，我想起来我遵从 Wayland 的建议删掉了在/etc/environment全局设置的QT_IM_MODULE=fcitx。这个问题官方的建议也提及了，可以单独为 Anki 设置环境变量，设置后问题果然解决。启动命令：\nShow/Hide the code 1 WAYLAND_DISPLAY= QT_IM_MODULE=fcitx Anki 实际上还有另一种方式，可以为某些 Qt 应用设置 QT_QPA_PLATFORM=xcb环境变量以解决其在 Wayland 中表现不正常的问题。\n","date":"2023-12-31T00:00:00Z","permalink":"/posts/anki-compatibility-with-wayland/","title":"Anki 与 Wayland 的兼容性问题"},{"content":" 此文全程处于linux环境，阅读此文需具备一些linux使用经验。\n解决饥荒卡顿有两个方法，如果你是单人联机玩家，可以添加长路独行模组，开启后就可以获得与单机版相同的游戏体验，此模组的原理的注意事项可以点此查看。 对于联机玩家，可以搭建专用服务器优化卡顿。饥荒联机版专用服务器 (Don\u0026rsquo;t Starve Together Dedicated Server) 是由 klei 官方提供的一个工具，购买饥荒联机版后，在 Steam 的“库”页面勾选 \u0026ldquo;TOOLS\u0026rdquo; 后就可以看到了。 专用服务器可以在云服务器或 PC 上运行。如果你的电脑配置还可以，并且不要求服务器全天运行，完全可以在自己电脑上搭建专用服务器。 运行专用服务器每个世界大约需要1G内存，同时运行游戏本身也需要内存，因此内存最好在8G以上。如图 1 所示，第一个进程是游戏本身，占用了1.2G的内存，第二个进程是专用服务器，占用了995M左右的内存。\n饥荒存档的构成 使用游戏本身创建的存档最多可以有一个森林和一个洞穴。但是饥荒专用服务器支持一个存档内包含任意多个森林和洞穴。\n专用服务器的运行单位是一个世界，而不是一个存档。比如说，一个存档中包括 2 个森林和 2 个洞穴，那么就需要启动 4 个专用服务器的进程实例。当然，你也可以不运行全部的世界，如果你不打算去某个世界，完全可以不启动它。这些进程通过网络通信，由于这种灵活的方式，你完全可以将一个存档中的不同的世界运行在不同的电脑上 (当然一般不需要这么做，除非你的世界太大了以至于一台电脑运行起来吃力)。\n唯一的限制是，每个存档必须有且仅有一个主世界 (Master Shard)，所有其他的世界都需要绑定到主世界。为了区分，每个世界都有一个唯一的id，通过给洞穴入口或洞穴出口绑定不同的id，玩家就可以通过他们在多个世界之间穿越。旺达的溯源表也绑定了世界的id，因此可以穿越到不同的世界。如图 2 所示，这是一个拥有两个森林和两个洞穴的世界。其中一个森林是主世界，箭头代表可以通过洞穴入口或洞穴出口进出另一个世界。\n这个世界对应的存档结构如下:\nShow/Hide the code 1 2 3 4 5 6 7 . ├── [drwxr-xr-x] Master ├── [drwxr-xr-x] Cave1 ├── [drwxr-xr-x] Cave2 ├── [drwxr-xr-x] Forest1 ├── [-rw-r--r--] cluster.ini └── [-rw-r--r--] cluster_token.txt 可以看出，每个世界都对应一个文件夹。此外，cluster.ini存放了世界的一些参数设置，cluster_token.txt里存放了用户的身份令牌 (身份令牌的获取参见下一章)。这些就是一个 存档的完整内容。 也可以去查看~/.klei/DontStarveTogether/$SteamUserID/目录，如果你在本地创建了存档，那么这个目录下就会有以Cluster_X格式命名的文件夹，其中X是此存档在游戏中显示的位置。如图 3 所示，我创建了一个存档，那么此文件夹中就有一个Cluster_1。\n查看目录结构，可以看出我只添加了一个主世界，没有添加洞穴。由于只有在专用服务器上运行的存档才需要cluster_token.txt，因此这里没有。\nShow/Hide the code 1 2 3 Cluster_1 ├── Master └── cluster.ini 在本地运行专用服务器 准备存档文件 在游戏中创建存档，添加好要启用的模组并设置好世界的参数后生成世界。等待世界生成，进入选人物的步骤后，断开连接。\n一定要添加洞穴，否则存档无法在专用服务器中运行。\n进入~/.klei/DontStarveTogether/$SteamUserID/目录，将刚刚创建的存档Cluster_X(X是此存档在游戏中显示的位置)移动到~/.klei/DontStarveTogether/中。\nShow/Hide the code 1 2 cd ~/.klei/DontStarveTogether/$SteamUserID/ mv Cluster_X .. 使用浏览器打开Klei Account，登录自己的Klei账号，可以使用Steam登录。登录成功后进入如下页面。\n点击导航栏中的游戏，在游戏列表中点击《饥荒：联机版》的游戏服务器，如下图所示。\n随便起一个名字，点击添加新服务器，然后复制生成的以pds-g^开头的代码，如下图所示。\n在~/.klei/DontStarveTogether/Cluster_X中创建cluster_token.txt文件，内容为刚刚复制的代码。\nShow/Hide the code 1 echo \u0026#34;pds-g^...\u0026#34; \u0026gt; cluster_token.txt 至此，存档文件就准备好了。\n准备专用服务器和模组 在Steam中安装Don't Starve Together Dedicated Server，进入安装目录 (安装目录可以在Steam的游戏设置中找到)。 如果你的存档添加了模组，则需要修改mods文件夹下的dedicated_server_mods_setup.lua文件。专用服务器启动时，会根据这个文件的内容自动更新模组，如果你只在存档中添加了模组但是没有修改这个文件，则模组会添加失败。将需要添加的模组的id以如下这种格式添加到此文件中即可。\nShow/Hide the code 1 2 3 ServerModSetup(\u0026#34;1438233888\u0026#34;) --多层世界选择器 ServerModSetup(\u0026#34;1418746242\u0026#34;) --汉化增强 Chinese++ ServerModSetup(\u0026#34;666155465\u0026#34;) --show me 模组的id可以通过Steam创意工坊中的链接查看。在Steam中模组的详情页面右击空白处，选择Copy Page URL。链接末尾的?id=后接的就是它的id。例如Show Me的创意工坊链接为https://steamcommunity.com/sharedfiles/filedetails/?id=666155465，其id为666155465。 除了这种方式，还可以查看此存档中主世界目录中的modoverrides.lua文件，这个文件保存了当前世界启用的模组的设置。格式如下所示，其中workshop-后接的数字就是模组的id。\nShow/Hide the code 1 2 3 4 5 6 7 8 9 return{ [\u0026#34;workshop-1418746242\u0026#34;]={ [\u0026#34;configuration_options\u0026#34;]={ [\u0026#34;clearfont\u0026#34;]=true， [\u0026#34;eventplus\u0026#34;]=true， [\u0026#34;extratrans\u0026#34;]=true }, [\u0026#34;enabled\u0026#34;]=true } } 既然modoverrides.lua文件已经保存了模组的id，那么我们就可以使用脚本将所有添加的模组的id提取出来。如下命令会根据modoverrides.lua文件自动生成dedicated_server_mods_setup.lua文件。cd到modoverrides.lua所在目录中执行如下命令，然后将生成的文件复制到专用服务器安装目录/mods文件夹覆盖原有文件即可。\nShow/Hide the code 1 cat ./modoverrides.lua | grep -E \u0026#39;\\[\u0026#34;workshop-[0-9]+\u0026#34;\\].*\u0026#39; | sed -r \u0026#39;s/\\[\u0026#34;workshop-([0-9]+)\u0026#34;\\].*/ServerModSetup(\u0026#34;\\1\u0026#34;)/g\u0026#39; \u0026gt; dedicated_server_mods_setup.lua 启动专用服务器 cd到安装目录中的bin64文件夹，执行\nShow/Hide the code 1 2 ./dontstarve_dedicated_server_nullrenderer_x64 -console -cluster \u0026#34;Cluster_X\u0026#34; -monitor_parent_process $$ -shard Caves \u0026amp; ./dontstarve_dedicated_server_nullrenderer_x64 -console -cluster \u0026#34;Cluster_X\u0026#34; -monitor_parent_process $$ -shard Master -console指定在游戏中启用控制台。 -cluster指定存档的名字，这个名字和要运行的存档文件夹名对应。 -shard指定世界碎片的名字。同样，这个名字也要和世界碎片的文件夹名对应。\n在cluster.ini中也可以指定一个名称，这个名称是在游戏中玩家看的世界名称。而-cluster指定的只是文件夹的名称，在游戏中是看不到的。\n在云服务器运行专用服务器 购买阿里云或腾讯云提供的云服务器，配置选择1核2G或者2核4G即可。安装Debian或Ubuntu操作系统，在安全组中开放10888-10999端口。此处以Debian为例。\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 _,met$$$$$gg. momo@debian ,g$$$$$$$$$$$$$$$P. ----------- ,g$$P\u0026#34; \u0026#34;\u0026#34;\u0026#34;Y$$.\u0026#34;. OS: Debian GNU/Linux 11 (bullseye) x86_64 ,$$P\u0026#39; `$$$. Host: VirtualBox 1.2 \u0026#39;,$$P ,ggs. `$$b: Kernel: 5.10.0-23-amd64 `d$$\u0026#39; ,$P\u0026#34;\u0026#39; . $$$ Uptime: 1 min $$P d$\u0026#39; ， $$P Packages: 444 (dpkg) $$: $$. - ,d$$\u0026#39; Shell: bash 5.1.4 $$; Y$b._ _,d$P\u0026#39; Resolution: preferred Y$$. `.`\u0026#34;Y$$$$P\u0026#34;\u0026#39; Terminal: /dev/pts/0 `$$b \u0026#34;-.__ CPU: Intel i5-7300HQ (2) @ 2.496GHz `Y$$ GPU: 00:02.0 VMware SVGA II Adapter `Y$$. Memory: 78MiB / 3919MiB `$$b. `Y$$b. `\u0026#34;Y$b._ `\u0026#34;\u0026#34;\u0026#34; 添加32位支持 Show/Hide the code 1 2 sudo dpkg --add-architecture i386 sudo apt update \u0026amp;\u0026amp; sudo apt upgrade -y 安装依赖 Show/Hide the code 1 sudo apt install libstdc++6:i386 libgcc1:i386 libcurl4-gnutls-dev:i386 -y 安装SteamCMD Show/Hide the code 1 2 3 4 5 # 这一步的速度视网络环境而定 mkdir -p ~/steamcmd/ cd ~/steamcmd/ wget \u0026#34;https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz\u0026#34; tar -xvzf steamcmd_linux.tar.gz 准备存档文件 这一步骤与上一章中的相同，可以在本地生成存档文件夹，然后上传到服务器。 Show/Hide the code 1 2 3 4 5 6 # 在服务器 mkdir -p ~/.klei/DoNotStarveTogether # 在本地 cd ~/.klei/DoNotStarveTogether scp -r ./Cluster_X username@xxx.xxx.xxx.xxx:~/.klei/DoNotStarveTogether/ 将以下内容写入run_server.sh文件并赋予其执行权限。 Show/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #!/bin/bash steamcmd_dir=\u0026#34;$HOME/steamcmd\u0026#34; install_dir=\u0026#34;$HOME/dontstarvetogether_dedicated_server\u0026#34; cluster_name=\u0026#34;$1\u0026#34; dontstarve_dir=\u0026#34;$HOME/.klei/DoNotStarveTogether\u0026#34; function fail() { echo Error: \u0026#34;$@\u0026#34; \u0026gt;\u0026amp;2 exit 1 } function check_for_file() { if [ ! -e \u0026#34;$1\u0026#34; ]; then fail \u0026#34;Missing file: $1\u0026#34; fi } cd \u0026#34;$steamcmd_dir\u0026#34; || fail \u0026#34;Missing $steamcmd_dir directory!\u0026#34; check_for_file \u0026#34;steamcmd.sh\u0026#34; check_for_file \u0026#34;$dontstarve_dir/$cluster_name/cluster.ini\u0026#34; check_for_file \u0026#34;$dontstarve_dir/$cluster_name/cluster_token.txt\u0026#34; check_for_file \u0026#34;$dontstarve_dir/$cluster_name/Master/server.ini\u0026#34; check_for_file \u0026#34;$dontstarve_dir/$cluster_name/Caves/server.ini\u0026#34; ./steamcmd.sh +force_install_dir \u0026#34;$install_dir\u0026#34; +login anonymous +app_update 343050 validate +quit check_for_file \u0026#34;$install_dir/bin64\u0026#34; cat \u0026#34;$dontstarve_dir/$cluster_name/Master/modoverrides.lua\u0026#34; | grep -E \u0026#39;\\[\u0026#34;workshop-[0-9]+\u0026#34;\\].*\u0026#39; | sed -r \u0026#39;s/\\[\u0026#34;workshop-([0-9]+)\u0026#34;\\].*/ServerModSetup(\u0026#34;\\1\u0026#34;)/g\u0026#39; \u0026gt; \u0026#34;$install_dir/mods/dedicated_server_mods_setup.lua\u0026#34; cd \u0026#34;$install_dir/bin64\u0026#34; || fail run_shared=(./dontstarve_dedicated_server_nullrenderer_x64) run_shared+=(-console) run_shared+=(-cluster \u0026#34;$cluster_name\u0026#34;) run_shared+=(-monitor_parent_process $$) \u0026#34;${run_shared[@]}\u0026#34; -shard Caves | sed \u0026#39;s/^/Caves: /\u0026#39; \u0026amp; \u0026#34;${run_shared[@]}\u0026#34; -shard Master | sed \u0026#39;s/^/Master: /\u0026#39; 这个脚本是我在Klei官方提供的脚本的基础上优化修改而来。运行时需要提供存档文件夹的名称作为脚本的第一个参数。脚本将会检查存档文件是否完整，使用SteamCMD更新专用服务器并根据存档的模组设置文件modoverrides.lua自动生成dedicated_server_mods_setup.lua文件。\n运行脚本 Show/Hide the code 1 ./run_server.sh Cluster_X 由于第一次运行时要下载专用服务器，速度会比较慢。当终端输出Sim paused时就说明启动完毕，可以在游戏中搜索加入了。\n可以使用tmux或screen等工具，这样脚本就可以在后台运行了。\n多层世界 理论上来说，一个存档中可以添加无数个世界。配置多层世界需要修改存档根目录中的cluster.ini和每个世界目录中的server.ini。对这些配置文件的详细介绍可以参考郭壮的博客。\n使用多层世界选择器可以解决给洞穴入口绑定id的麻烦。类似于路由器的工作方式，玩家选择目标世界，由多层世界选择器将玩家送到对应世界，如图 7 所示。\n常见问题 Connecting anonymously to Steam Public\u0026hellip;: Retry Retry 无法连接到Steam的服务器，这一般是由于GFW，科学上网即可解决。\n服务器启动失败: cluster_token.txt do not exist 检查cluster_token.txt是否存在，内容是否正确。\n服务器启动失败: libcurl-gnults.so.4 安装libcurl-gnults。\n全部模组没有添加成功 查看modoverrides.lua和dedicated_server_mods_setup.lua是否都存在，内容是否正确。\n部分模组没有添加成功 因为网络原因，有时专用服务器会在下载某些模组时失败。如果运行后发现只有一部分模组，一般重新运行专用服务器即可。\n游戏大厅内无法搜索到世界 可以通过控制台指令c_connect(\u0026quot;xxx.xxx.xxx.xxx\u0026quot;，10999，\u0026quot;password\u0026quot;)加入世界，其中第一个参数是服务器的IP地址，第二个参数是主世界碎片的端口号，第三个参数是世界的密码。\n","date":"2023-06-09T00:00:00Z","image":"/posts/dst-dedicated-server-multilevel-world-setup-guide/1.png","permalink":"/posts/dst-dedicated-server-multilevel-world-setup-guide/","title":"饥荒联机版专用服务器和多层世界配置指南"},{"content":"Android QQ 的图片文件是以下面这种结构保存的，以Cache_开头的文件就是图片。这种结构在浏览时要分别点进每个文件夹才能看到图片，很不方便。\nShow/Hide the code 1 2 3 4 5 6 7 8 9 ├── 0a0 │ ├── Cache_2783644ca99260a0 │ └── Cache_-4dfb57e9a7cec0a0 ├── 0a6 │ ├── Cache_373e35b7b8a290a6 │ ├── Cache_-489f6e9c62ea10a6 │ └── Cache_57776dc1e17110a6 └── 0a7 └── Cache_25d732f84bd7d0a7 使用 GNU Parallel 配合mv可以快速的 “解散” 每个二级文件夹，变成以下这种结构。\nShow/Hide the code 1 2 3 4 5 6 7 . ├── Cache_25d732f84bd7d0a7 ├── Cache_2783644ca99260a0 ├── Cache_373e35b7b8a290a6 ├── Cache_-489f6e9c62ea10a6 ├── Cache_-4dfb57e9a7cec0a0 └── Cache_57776dc1e17110a6 命令如下:\nShow/Hide the code 1 find . -name \u0026#34;*\u0026#34; -type f -print | parallel mv {} ./{/} 参考: https://www.myfreax.com/gnu-parallel/\n","date":"2023-06-08T00:00:00Z","permalink":"/posts/gnu-parallel-tips/","title":"GNU Parallel 的妙用"},{"content":"shell 脚本是处理这类工作最为简单，快捷的方式。\n修改后缀 Show/Hide the code 1 for file in *.原后缀; do mv \u0026#34;$file\u0026#34; \u0026#34;`echo $file | sed s/.原后缀/.新后缀/`\u0026#34;; done 格式转换 heic 转 jpg 首先，安装转换工具。\nShow/Hide the code 1 yay -S libheif 然后可以使用 heif-convert 命令转换。\nShow/Hide the code 1 heif-convert input.heic output.jpg 批量转换，命令如下。\nShow/Hide the code 1 for file in *.heic; do heif-convert \u0026#34;$file\u0026#34; ${file/%.heic/.jpg} \u0026amp;\u0026amp; rm \u0026#34;$file\u0026#34;; done 这条命令的原理是：根据当前文件夹下的 .heic 文件生成 .jpg 文件，如果成功生成则删除原 .heic 文件，如果未成功则不会删除原文件。 此外，如果未能生成 .jpg 文件的原因是 Input file 'filename.heic' is a JPEG image ，那么可以使用批量修改后缀的方法直接将文件的后缀改为 .jpg。\nflac 转 mp3 首先，安装转换工具：\nShow/Hide the code 1 yay -S ffmpeg 然后可以使用 ffmpeg 命令转换，除了格式转换，ffmpeg 还支持很多功能，具体可以查阅文档。\nShow/Hide the code 1 ffmpeg -i \u0026#39;input.flac\u0026#39; -ab 320k -map_metadata 0 -id3v2_version 3 \u0026#39;output.mp3\u0026#39; 批量转换，命令如下：\nShow/Hide the code 1 for file in *.flac; do ffmpeg -i \u0026#34;$file\u0026#34; -ab 320k -map_metadata 0 -id3v2_version 3 ${file/%.flac/.mp3} \u0026amp;\u0026amp; rm \u0026#34;$file\u0026#34;; done 原理同上。\n速度优化 使用 for 循环的方式，所有文件排着队一个一个的被 ffmpeg 处理。 这种方式固然可以，但效率太低了。 我的运行环境如下:\nShow/Hide the code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 -` momo@momo-arch .o+` -------------- `ooo/ OS: Arch Linux x86_64 `+oooo: Host: 81AC Lenovo ideapad 720S-15IKB `+oooooo: Kernel: 6.3.6-arch1-1 -+oooooo+: Uptime: 6 hours, 59 mins `/:-:++oooo+: Packages: 975 (pacman), 8 (flatpak) `/++++/+++++++: Shell: bash 5.1.16 `/++++++++++++++: Resolution: 1920x1080 `/+++ooooooooooooo/` DE: Plasma 5.27.5 ./ooosssso++osssssso+` WM: kwin .oossssso-````/ossssss+` Theme: [Plasma], Layan-Light-Solid [GTK2/3] -osssssso. :ssssssso. Icons: Papirus [Plasma], Papirus [GTK2/3] :osssssss/ osssso+++. Terminal: konsole /ossssssss/ +ssssooo/- CPU: Intel i5-7300HQ (4) @ 3.500GHz `/ossssso+/:- -:/+osssso+- GPU: Intel HD Graphics 630 `+sso+:-` `.-/+oso: Memory: 7216MiB / 19554MiB `++:. `-/+/ .` `/ 经过测试，处理 10 个 .flac 文件所需时间为 59 秒。 速度慢的原因是目前使用的是单进程串行的处理方式，为了提高速度，可以同时启动多个进程并行处理。\n使用终端工具GNU Parallel，命令如下：\nShow/Hide the code 1 ls *.flac | parallel -j4 \u0026#34;ffmpeg -i {} -ab 320k -map_metadata 0 -id3v2_version 3 {.}.mp3 \u0026amp;\u0026amp; rm {}\u0026#34; parallel 将从标准输入中读取文件列表，-j 指定了并行进程数，{} 代表输入文件名，{.} 代表没有后缀的输入文件名，其他用法可以 man parallel 查看。\n经过测试，在同样环境下处理同样的 .flac 文件仅需 17 秒。\n","date":"2023-06-06T00:00:00Z","image":"/posts/batch-rename-file-extensions-and-format-conversion-in-linux/image.png","permalink":"/posts/batch-rename-file-extensions-and-format-conversion-in-linux/","title":"使用 Shell 批量修改文件后缀和批量格式转换"},{"content":"Dolphin 中无法加载缩略图，也无法打开图片。\n安装kimageformats后解决。\nShow/Hide the code 1 yay -S kimageformats 参考 https://www.reddit.com/r/kde/comments/s4bres/heifheic_support_in_dolphingwenview/\n","date":"2023-06-01T00:00:00Z","permalink":"/posts/%E4%B8%BA-gwenview-%E6%B7%BB%E5%8A%A0-heic-%E6%94%AF%E6%8C%81/","title":"为 Gwenview 添加 HEIC 支持"}]