Skip to content

Instantly share code, notes, and snippets.

@18520339
Last active January 31, 2025 21:30
Show Gist options
  • Save 18520339/a6843aa82b32f6517f5af67cdc985bde to your computer and use it in GitHub Desktop.
Save 18520339/a6843aa82b32f6517f5af67cdc985bde to your computer and use it in GitHub Desktop.
My study notes
#include <iostream>
#include <math.h>
using namespace std;
bool is_prime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
bool is_fibo(int n) {
int n1 = n * n * 5 - 4;
int n2 = n * n * 5 + 4;
float sqrt1 = sqrt(n1);
float sqrt2 = sqrt(n2);
return (int)sqrt1 == sqrt1 || (int)sqrt2 == sqrt2;
}
int get_fibo(int n) {
double phi = (1 + sqrt(5)) / 2;
return round(pow(phi, n) / sqrt(5));
}
// SAKAMOTO ALGORITHM to checks what day of the week it is
int day_of_week(int year, int month, int day) {
int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
year -= month < 3;
return (497 * year/400 + t[month - 1] + day) % 7;
}
function getWebName(url) {
// http://example1.com/a/b?c=d => example1
// http://www.example2.com/b?c=d => example2
// https://ww.example3.com.vn => example3
const hostnameParts = new URL(url).hostname.split('.');
return hostnameParts[hostnameParts.length - 1].length === 2
? hostnameParts[hostnameParts.length - 3]
: hostnameParts[hostnameParts.length - 2];
}
// Check even and odd without `if else`
number = 3
["even", "odd"][number % 2]
// Get intersection
const a = new Set([1,2,3]);
const b = new Set([4,3,2]);
const intersection = [...a].filter(x => b.has(x))
console.log(intersection) // [2, 3]
function getCookieField(name) {
const cookie = document.cookie.split("; ").find(item => item.startsWith(`${name}=`));
return cookie ? decodeURIComponent(cookie.split("=")[1]) : null;
}
(265 >>> 0).toString(2);
(_$=($,_=[]+[])=>$?_$($>>+!![],($&+!![])+_):_)(265);
/*
Đây ko phải là RegEx mà là hàm mũi tên (arrow function) với các tên hàm, tên biến và số (1) được thể hiện bằng các kí tự đặc biệt và sô 1 được thể hiện bằng biểu thức mảng như này +!![]
Đây là phiên bản dễ hiểu hơn một chút của đoạn mã:
(toBinary = (val, str = "") => val ? toBinary(val >> 1, (val & 1) + str):str)(265);
[]+[] chính là chuỗi trống "".
+!![] chính là số 1.
Dùng đệ quy để lấy từng bit và cộng dồn vào chuỗi str (ban đầu là trống ""). Điều kiện dừng là val bằng 0 (đoạn toán tử 2 ngôi chỗ val?... đấy).
Viết cho dễ nhìn và chú thích:
(
toBinary = (val, str = "") => // gán toBinary cho hàm mũi tên với 2 tham số val và str (mặc định là "").
val ? // nếu val khác 0...
toBinary(val >> 1, (val & 1) + str) : // ... thì thực hiện đệ quy cho bit tiếp theo
str // ...ngược lại kết thúc đệ quy và trả về giá trị
)(265); // gọi trực tiếp hàm toBinary
*/
# Compare hyperparameter search results
def plot_param_performace(clf, param_name, title):
results = clf.search_cv.cv_results_
plt.figure(figsize=(13, 5))
plt.title(title)
plt.xlabel(param_name)
plt.ylabel("Score")
plt.grid()
ax = plt.gca()
ax.set_ylim(0.96, 1)
# Get the regular numpy array from the MaskedArray
X_axis = np.array(results[f'param_{param_name}'].data, dtype=float)
for scorer, color in zip(('test_score', 'train_score'), ('g', 'r')):
for sample, style in (('mean', '-'), ('std', '--')):
sample_score_mean = results[f'mean_{scorer}']
sample_score_std = results[f'std_{scorer}']
ax.fill_between(X_axis, sample_score_mean - sample_score_std,
sample_score_mean + sample_score_std,
alpha=0.1 if sample == 'mean' else 0, color=color)
ax.plot(X_axis, sample_score_mean, style, color=color,
alpha=1 if sample == 'mean' else 0.7,
label=f'{scorer} ({sample})')
plt.legend(loc="best")
plt.tight_layout()
plt.show()
plot_param_performace(rf_classifier, 'n_estimators', "Random Forest: Performance vs Number of Estimators")
@18520339
Copy link
Author

18520339 commented Oct 2, 2024

Calculate $\frac{\partial{L}}{\partial{w}}$ without chain rule, where L is loss function of a simple Logistic Regression model with binary cross-entropy:

I know this is not practical way but I just want to strengthen my understanding by looking for a pure substitution method. Please correct me if I was doing something wrong 😅

$$\eqalign{ L &= -[y * ln(\frac{1}{1 + e^{-(wx+b)}}) + (1 - y) * ln(1 - \frac{1}{1 + e^{-(wx+b)}})] \\ &= -[y * ln(\frac{1}{1 + e^{-(wx+b)}}) + (1 - y) * ln(\frac{e^{-(wx+b)}}{1 + e^{-(wx+b)}})] \\ }$$

Now, we used the fact that $ln(\frac{1}{1 + e^{-z}}) = -ln(1 + e^{-z})$ and $ln(\frac{e^{-z}}{1 + e^{-z}}) = -z - ln(1 + e^{-z})$, where $z = wx+b$:

$$\eqalign{ L &= -[-y * ln(1 + e^{-(wx+b)}) + (1 - y) * (-(wx+b) - ln(1 + e^{-(wx+b)}))] \\ &= -[-y * ln(1 + e^{-(wx+b)}) - (1 - y) * ln(1 + e^{-(wx+b)}) - (1 - y) * (wx+b)] \\ &= ln(1 + e^{-(wx+b)}) + (1 - y) * wx + (1 - y) * b] \\ }$$

Now, find $\frac{\partial{L}}{\partial{w}}$:

$$\eqalign{ \frac{\partial{L}}{\partial{w}} &= \frac{-x * e^{-(wx+b)}}{1 + e^{-(wx+b)}} + (1 - y) * x] \\ &= \frac{-x * e^{-(wx+b)} + (1 - y) * x * (1 + e^{-(wx+b)})}{1 + e^{-(wx+b)}} \\ &= \frac{-x * e^{-(wx+b)} + (1 - y) * x + (1 - y) * x * e^{-(wx+b)}}{1 + e^{-(wx+b)}} \\ &= \frac{-xy * e^{-(wx+b)} + x - xy}{1 + e^{-(wx+b)}} \\ &= \frac{-xy * (1 + e^{-(wx+b)}) + x}{1 + e^{-(wx+b)}} \\ &= -xy + \frac{x}{1 + e^{-(wx+b)}} \\ &= (\frac{1}{1 + e^{-(wx+b)}} - y) * x \\ &= (sigmoid(z) - y) * x }$$

@18520339
Copy link
Author

18520339 commented Jan 1, 2025

{D8E5EBCB-2FDF-4A15-BF8C-3C3E0E8FC200}

@18520339
Copy link
Author

{6E998E8B-AFA8-4AE5-AB62-5DA6D2FBF718}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment