markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
**μ 4-10: λΌμ νκ·μ λΉμ© ν¨μ**$J(\boldsymbol{\theta}) = \text{MSE}(\boldsymbol{\theta}) + \alpha \sum\limits_{i=1}^{n}\left| \theta_i \right|$ λΌμ νκ· | from sklearn.linear_model import Lasso
plt.figure(figsize=(8,4))
plt.subplot(121)
plot_model(Lasso, polynomial=False, alphas=(0, 0.1, 1), random_state=42)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.subplot(122)
plot_model(Lasso, polynomial=True, alphas=(0, 10**-7, 1), random_state=42)
save_fig("lasso_regression_p... | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μλΌμ€ν±λ· **μ 4-12: μλΌμ€ν±λ· λΉμ© ν¨μ**$J(\boldsymbol{\theta}) = \text{MSE}(\boldsymbol{\theta}) + r \alpha \sum\limits_{i=1}^{n}\left| \theta_i \right| + \dfrac{1 - r}{2} \alpha \sum\limits_{i=1}^{n}{{\theta_i}^2}$ | from sklearn.linear_model import ElasticNet
elastic_net = ElasticNet(alpha=0.1, l1_ratio=0.5, random_state=42)
elastic_net.fit(X, y)
elastic_net.predict([[1.5]]) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μ‘°κΈ° μ’
λ£ | np.random.seed(42)
m = 100
X = 6 * np.random.rand(m, 1) - 3
y = 2 + X + 0.5 * X**2 + np.random.randn(m, 1)
X_train, X_val, y_train, y_val = train_test_split(X[:50], y[:50].ravel(), test_size=0.5, random_state=10)
from copy import deepcopy
poly_scaler = Pipeline([
("poly_features", PolynomialFeatures(degree=90... | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
κ·Έλνλ₯Ό 그립λλ€: | sgd_reg = SGDRegressor(max_iter=1, tol=-np.infty, warm_start=True,
penalty=None, learning_rate="constant", eta0=0.0005, random_state=42)
n_epochs = 500
train_errors, val_errors = [], []
for epoch in range(n_epochs):
sgd_reg.fit(X_train_poly_scaled, y_train)
y_train_predict = sgd_reg.pred... | κ·Έλ¦Ό μ μ₯: lasso_vs_ridge_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
λ‘μ§μ€ν± νκ· κ²°μ κ²½κ³ | t = np.linspace(-10, 10, 100)
sig = 1 / (1 + np.exp(-t))
plt.figure(figsize=(9, 3))
plt.plot([-10, 10], [0, 0], "k-")
plt.plot([-10, 10], [0.5, 0.5], "k:")
plt.plot([-10, 10], [1, 1], "k:")
plt.plot([0, 0], [-1.1, 1.1], "k-")
plt.plot(t, sig, "b-", linewidth=2, label=r"$\sigma(t) = \frac{1}{1 + e^{-t}}$")
plt.xlabel("t... | κ·Έλ¦Ό μ μ₯: logistic_function_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
**μ 4-16: νλμ νλ ¨ μνμ λν λΉμ© ν¨μ**$c(\boldsymbol{\theta}) =\begin{cases} -\log(\hat{p}) & \text{if } y = 1, \\ -\log(1 - \hat{p}) & \text{if } y = 0.\end{cases}$**μ 4-17: λ‘μ§μ€ν± νκ· λΉμ© ν¨μ(λ‘κ·Έ μμ€)**$J(\boldsymbol{\theta}) = -\dfrac{1}{m} \sum\limits_{i=1}^{m}{\left[ y^{(i)} log\left(\hat{p}^{(i)}\right) + (1 - y^{(i)}) log\l... | from sklearn import datasets
iris = datasets.load_iris()
list(iris.keys())
print(iris.DESCR)
X = iris["data"][:, 3:] # κ½μ λλΉ
y = (iris["target"] == 2).astype(int) # Iris virginicaμ΄λ©΄ 1 μλλ©΄ 0 | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
**λ
ΈνΈ**: ν₯ν λ²μ μ΄ λ°λλλΌλ λμΌν κ²°κ³Όλ₯Ό λ§λ€κΈ° μν΄ μ¬μ΄ν·λ° 0.22 λ²μ μ κΈ°λ³Έκ°μΈ `solver="lbfgs"`λ‘ μ§μ ν©λλ€. | from sklearn.linear_model import LogisticRegression
log_reg = LogisticRegression(solver="lbfgs", random_state=42)
log_reg.fit(X, y)
X_new = np.linspace(0, 3, 1000).reshape(-1, 1)
y_proba = log_reg.predict_proba(X_new)
plt.plot(X_new, y_proba[:, 1], "g-", linewidth=2, label="Iris virginica")
plt.plot(X_new, y_proba[:, ... | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μ±
μ μ€λ¦° κ·Έλ¦Όμ μ‘°κΈ λ μμκ² κΎΈλͺμ΅λλ€: | X_new = np.linspace(0, 3, 1000).reshape(-1, 1)
y_proba = log_reg.predict_proba(X_new)
decision_boundary = X_new[y_proba[:, 1] >= 0.5][0]
plt.figure(figsize=(8, 3))
plt.plot(X[y==0], y[y==0], "bs")
plt.plot(X[y==1], y[y==1], "g^")
plt.plot([decision_boundary, decision_boundary], [-1, 2], "k:", linewidth=2)
plt.plot(X_n... | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μννΈλ§₯μ€ νκ· | from sklearn.linear_model import LogisticRegression
X = iris["data"][:, (2, 3)] # petal length, petal width
y = (iris["target"] == 2).astype(int)
log_reg = LogisticRegression(solver="lbfgs", C=10**10, random_state=42)
log_reg.fit(X, y)
x0, x1 = np.meshgrid(
np.linspace(2.9, 7, 500).reshape(-1, 1),
n... | κ·Έλ¦Ό μ μ₯: logistic_regression_contour_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
**μ 4-20: μννΈλ§₯μ€ ν¨μ**$\hat{p}_k = \sigma\left(\mathbf{s}(\mathbf{x})\right)_k = \dfrac{\exp\left(s_k(\mathbf{x})\right)}{\sum\limits_{j=1}^{K}{\exp\left(s_j(\mathbf{x})\right)}}$**μ 4-22: ν¬λ‘μ€ μνΈλ‘νΌ λΉμ© ν¨μ**$J(\boldsymbol{\Theta}) = - \dfrac{1}{m}\sum\limits_{i=1}^{m}\sum\limits_{k=1}^{K}{y_k^{(i)}\log\left(\hat{p}_k^{(i)}... | X = iris["data"][:, (2, 3)] # κ½μ κΈΈμ΄, κ½μ λλΉ
y = iris["target"]
softmax_reg = LogisticRegression(multi_class="multinomial",solver="lbfgs", C=10, random_state=42)
softmax_reg.fit(X, y)
x0, x1 = np.meshgrid(
np.linspace(0, 8, 500).reshape(-1, 1),
np.linspace(0, 3.5, 200).reshape(-1, 1),
)
X_new = np.c... | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μ°μ΅λ¬Έμ ν΄λ΅ 1. to 11. λΆλ‘ Aλ₯Ό μ°Έκ³ νμΈμ. 12. μ‘°κΈ° μ’
λ£λ₯Ό μ¬μ©ν λ°°μΉ κ²½μ¬ νκ°λ²μΌλ‘ μννΈλ§₯μ€ νκ· κ΅¬ννκΈ°(μ¬μ΄ν·λ°μ μ¬μ©νμ§ μκ³ ) λ¨Όμ λ°μ΄ν°λ₯Ό λ‘λν©λλ€. μμ μ¬μ©νλ Iris λ°μ΄ν°μ
μ μ¬μ¬μ©νκ² μ΅λλ€. | X = iris["data"][:, (2, 3)] # κ½μ κΈΈμ΄, κ½μ λμ΄
y = iris["target"] | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
λͺ¨λ μνμ νΈν₯μ μΆκ°ν©λλ€ ($x_0 = 1$): | X_with_bias = np.c_[np.ones([len(X), 1]), X] | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
κ²°κ³Όλ₯Ό μΌμ νκ² μ μ§νκΈ° μν΄ λλ€ μλλ₯Ό μ§μ ν©λλ€: | np.random.seed(2042) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
λ°μ΄ν°μ
μ νλ ¨ μΈνΈ, κ²μ¦ μΈνΈ, ν
μ€νΈ μΈνΈλ‘ λλλ κ°μ₯ μ¬μ΄ λ°©λ²μ μ¬μ΄ν·λ°μ `train_test_split()` ν¨μλ₯Ό μ¬μ©νλ κ²μ
λλ€. νμ§λ§ μ΄ μ°μ΅λ¬Έμ μ λͺ©μ μ μ§μ λ§λ€μ΄ 보면μ μκ³ λ¦¬μ¦μ μ΄ν΄νλ κ²μ΄λ―λ‘ λ€μκ³Ό κ°μ΄ μλμΌλ‘ λλμ΄ λ³΄κ² μ΅λλ€: | test_ratio = 0.2
validation_ratio = 0.2
total_size = len(X_with_bias)
test_size = int(total_size * test_ratio)
validation_size = int(total_size * validation_ratio)
train_size = total_size - test_size - validation_size
rnd_indices = np.random.permutation(total_size)
X_train = X_with_bias[rnd_indices[:train_size]]
y_t... | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
νκΉμ ν΄λμ€ μΈλ±μ€(0, 1 κ·Έλ¦¬κ³ 2)μ΄μ§λ§ μννΈλ§₯μ€ νκ· λͺ¨λΈμ νλ ¨μν€κΈ° μν΄ νμν κ²μ νκΉ ν΄λμ€μ νλ₯ μ
λλ€. κ° μνμμ νλ₯ μ΄ 1μΈ νκΉ ν΄λμ€λ₯Ό μ μΈν λ€λ₯Έ ν΄λμ€μ νλ₯ μ 0μ
λλ€(λ€λ₯Έ λ§λ‘νλ©΄ μ£Όμ΄μ§ μνμ λν ν΄λμ€ νλ₯ μ΄ μ-ν« λ²‘ν°μ
λλ€). ν΄λμ€ μΈλ±μ€λ₯Ό μ-ν« λ²‘ν°λ‘ λ°κΎΈλ κ°λ¨ν ν¨μλ₯Ό μμ±νκ² μ΅λλ€: | def to_one_hot(y):
n_classes = y.max() + 1
m = len(y)
Y_one_hot = np.zeros((m, n_classes))
Y_one_hot[np.arange(m), y] = 1
return Y_one_hot | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
10κ° μνλ§ λ£μ΄ μ΄ ν¨μλ₯Ό ν
μ€νΈν΄ λ³΄μ£ : | y_train[:10]
to_one_hot(y_train[:10]) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μ λλ€μ, μ΄μ νλ ¨ μΈνΈμ ν
μ€νΈ μΈνΈμ νκΉ ν΄λμ€ νλ₯ μ λ΄μ νλ ¬μ λ§λ€κ² μ΅λλ€: | Y_train_one_hot = to_one_hot(y_train)
Y_valid_one_hot = to_one_hot(y_valid)
Y_test_one_hot = to_one_hot(y_test) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μ΄μ μννΈλ§₯μ€ ν¨μλ₯Ό λ§λλλ€. λ€μ 곡μμ μ°Έκ³ νμΈμ:$\sigma\left(\mathbf{s}(\mathbf{x})\right)_k = \dfrac{\exp\left(s_k(\mathbf{x})\right)}{\sum\limits_{j=1}^{K}{\exp\left(s_j(\mathbf{x})\right)}}$ | def softmax(logits):
exps = np.exp(logits)
exp_sums = np.sum(exps, axis=1, keepdims=True)
return exps / exp_sums | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
νλ ¨μ μν μ€λΉλ₯Ό κ±°μ λ§μ³€μ΅λλ€. μ
λ ₯κ³Ό μΆλ ₯μ κ°μλ₯Ό μ μν©λλ€: | n_inputs = X_train.shape[1] # == 3 (νΉμ± 2κ°μ νΈν₯)
n_outputs = len(np.unique(y_train)) # == 3 (3κ°μ λΆκ½ ν΄λμ€) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μ΄μ μ’ λ³΅μ‘ν νλ ¨ ννΈμ
λλ€! μ΄λ‘ μ μΌλ‘λ κ°λ¨ν©λλ€. κ·Έλ₯ μν 곡μμ νμ΄μ¬ μ½λλ‘ λ°κΎΈκΈ°λ§ νλ©΄ λ©λλ€. νμ§λ§ μ€μ λ‘λ κ½€ κΉλ€λ‘μ΄ λ©΄μ΄ μμ΅λλ€. νΉν, νμ΄λ μΈλ±μ€μ μμκ° λ€μμ΄κΈ° μ½μ΅λλ€. μ λλ‘ μλν κ²μ²λΌ μ½λλ₯Ό μμ±νλλΌλ μ€μ μ λλ‘ κ³μ°νμ§ λͺ»ν©λλ€. νμ€νμ§ μμ λλ κ° νμ ν¬κΈ°λ₯Ό κΈ°λ‘νκ³ μ΄μ μμνλ μ½λκ° κ°μ ν¬κΈ°λ₯Ό λ§λλμ§ νμΈν©λλ€. κ° νμ λ
립μ μΌλ‘ νκ°ν΄μ μΆλ ₯ν΄ λ³΄λ κ²λ μ’μ΅λλ€. μ¬μ€ μ¬μ΄ν·λ°μ μ΄λ―Έ μ ꡬνλμ΄ μκΈ° λλ¬Έμ μ΄λ κ² ν νμλ μμ΅λλ€. νμ§λ§ μ§μ λ§λ€μ΄ 보면 μ΄λ»κ² μλνλμ§ μ΄ν΄νλλ° λμ... | eta = 0.01
n_iterations = 5001
m = len(X_train)
epsilon = 1e-7
Theta = np.random.randn(n_inputs, n_outputs)
for iteration in range(n_iterations):
logits = X_train.dot(Theta)
Y_proba = softmax(logits)
if iteration % 500 == 0:
loss = -np.mean(np.sum(Y_train_one_hot * np.log(Y_proba + epsilon), axis=... | 0 5.446205811872683
500 0.8350062641405651
1000 0.6878801447192402
1500 0.6012379137693314
2000 0.5444496861981872
2500 0.5038530181431525
3000 0.47292289721922487
3500 0.44824244188957774
4000 0.4278651093928793
4500 0.41060071429187134
5000 0.3956780375390374
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
λ°λ‘ μ΄κ²λλ€! μννΈλ§₯μ€ λͺ¨λΈμ νλ ¨μμΌ°μ΅λλ€. λͺ¨λΈ νλΌλ―Έν°λ₯Ό νμΈν΄ λ³΄κ² μ΅λλ€: | Theta | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
κ²μ¦ μΈνΈμ λν μμΈ‘κ³Ό μ νλλ₯Ό νμΈν΄ λ³΄κ² μ΅λλ€: | logits = X_valid.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)
accuracy_score = np.mean(y_predict == y_valid)
accuracy_score | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μμ°, μ΄ λͺ¨λΈμ΄ λ§€μ° μ μλνλ κ² κ°μ΅λλ€. μ°μ΅μ μν΄μ $\ell_2$ κ·μ λ₯Ό μ‘°κΈ μΆκ°ν΄ λ³΄κ² μ΅λλ€. λ€μ μ½λλ μμ κ±°μ λμΌνμ§λ§ μμ€μ $\ell_2$ νλν°κ° μΆκ°λμκ³ κ·ΈλλμΈνΈμλ νμ΄ μΆκ°λμμ΅λλ€(`Theta`μ 첫 λ²μ§Έ μμλ νΈν₯μ΄λ―λ‘ κ·μ νμ§ μμ΅λλ€). νμ΅λ₯ `eta`λ μ¦κ°μμΌ λ³΄κ² μ΅λλ€. | eta = 0.1
n_iterations = 5001
m = len(X_train)
epsilon = 1e-7
alpha = 0.1 # κ·μ νμ΄νΌνλΌλ―Έν°
Theta = np.random.randn(n_inputs, n_outputs)
for iteration in range(n_iterations):
logits = X_train.dot(Theta)
Y_proba = softmax(logits)
if iteration % 500 == 0:
xentropy_loss = -np.mean(np.sum(Y_train_one_hot ... | 0 6.629842469083912
500 0.5339667976629505
1000 0.503640075014894
1500 0.4946891059460321
2000 0.4912968418075477
2500 0.48989924700933296
3000 0.4892990598451198
3500 0.489035124439786
4000 0.4889173621830818
4500 0.4888643337449303
5000 0.48884031207388184
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μΆκ°λ $\ell_2$ νλν° λλ¬Έμ μ΄μ λ³΄λ€ μμ€μ΄ μ‘°κΈ μ»€λ³΄μ΄μ§λ§ λ μ μλνλ λͺ¨λΈμ΄ λμμκΉμ? νμΈν΄ λ³΄μ£ : | logits = X_valid.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)
accuracy_score = np.mean(y_predict == y_valid)
accuracy_score | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μμ°, μλ²½ν μ νλλ€μ! μ΄μ΄ μ’μ κ²μ¦ μΈνΈμΌμ§ λͺ¨λ₯΄μ§λ§ μ λ κ²μ λ§μ΅λλ€. μ΄μ μ‘°κΈ° μ’
λ£λ₯Ό μΆκ°ν΄ λ³΄μ£ . μ΄λ κ² νλ €λ©΄ λ§€ λ°λ³΅μμ κ²μ¦ μΈνΈμ λν μμ€μ κ³μ°ν΄μ μ€μ°¨κ° μ¦κ°νκΈ° μμν λ λ©μΆ°μΌ ν©λλ€. | eta = 0.1
n_iterations = 5001
m = len(X_train)
epsilon = 1e-7
alpha = 0.1 # κ·μ νμ΄νΌνλΌλ―Έν°
best_loss = np.infty
Theta = np.random.randn(n_inputs, n_outputs)
for iteration in range(n_iterations):
logits = X_train.dot(Theta)
Y_proba = softmax(logits)
error = Y_proba - Y_train_one_hot
gradients = 1/m * X_t... | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μ¬μ ν μλ²½νμ§λ§ λ λΉ λ¦
λλ€. μ΄μ μ 체 λ°μ΄ν°μ
μ λν λͺ¨λΈμ μμΈ‘μ κ·Έλνλ‘ λνλ΄ λ³΄κ² μ΅λλ€: | x0, x1 = np.meshgrid(
np.linspace(0, 8, 500).reshape(-1, 1),
np.linspace(0, 3.5, 200).reshape(-1, 1),
)
X_new = np.c_[x0.ravel(), x1.ravel()]
X_new_with_bias = np.c_[np.ones([len(X_new), 1]), X_new]
logits = X_new_with_bias.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)... | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
μ΄μ ν
μ€νΈ μΈνΈμ λν λͺ¨λΈμ μ΅μ’
μ νλλ₯Ό μΈ‘μ ν΄ λ³΄κ² μ΅λλ€: | logits = X_test.dot(Theta)
Y_proba = softmax(logits)
y_predict = np.argmax(Y_proba, axis=1)
accuracy_score = np.mean(y_predict == y_test)
accuracy_score | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
Welcome to Python FundamentalsIn this module, we are going to establish or review our skills in Python programming. In this notebook we are going to cover:* Variables and Data Types * Operations* Input and Output Operations* Logic Control* Iterables* Functions Variable and Data TypesVariables and data types are the ... | x = 0
e,l,a = 2,1,4
a
type(x)
h = 1.0
type(h)
x = float(x)
type (x)
a,d,u = "0",'1','valorant'
type(a)
a_int = int(a)
a_int | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
Operations ArithmeticMathematical operations such as addition, subtraction, multiplication, division, floor division, exponentiation and modulo are performed using arithmetic operators. | s,k,y,e = 2.0,-0.5,0,-32 | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
AdditionThis operation denotes (+) which adds values on either side of the operator. | ### Addition
a = s+k
a | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
SubtractionRepresented by (-), this operation subtracts right hand operand from left hand operand. | ### Subtraction
u = k-e
u | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
MultiplicationUsing the symbol (*), this operation multiplies values on both sides of the operator. | ### Multiplication
m = s*e
m | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
DivisionThe division operator in Python is (/). When the first operand is divided by the second, it is utilized to find the quotient. | ### Divison
d = y/s
d | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
Floor DivisionWhen the first operand is divided by the second, floor division is applied to calculate the floor quotient. This is denoted by the operator (//). | ### Floor Division
fd = s//k
fd | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
ExponentiationTo raise the first operand to the second power, exponentiation is performed through the symbol (**). | ### Exponentiation
ex = s**k
ex | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
ModuloModulo or Modulus uses the operator (%) that is responsible for dividing left hand operand by right hand operand and returns the remainder. | ### Modulo
mod = e%s
mod | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
Assignment OperationsAssignment operators are used in Python programming to assign values to variables. = The equal operation's role is to "Assign" the value of the right side of the expression to the operand on the left side. | w,x,y,z = 0,100,2,2 | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
+= "Add and Assign" is designed to add both sides of the operand and the sum will be placed on the left operand. | w += s
w | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
-="Subtract And" conducts subtraction to right operand from left operand. The difference would then be assigned to the left operand. | x -= e
x | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
*="Multiply And" operates multiplication to both operands and then the product would be assigned to the left operand. | y *= 2
y | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
**="Exponent And" calculates the exponent value of the operands which would then be assigned also to the left operand. | z **= 2
z | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
ComparatorsValues are compared using comparison operators. Depending on the condition, it results to either True or False. | trial_1, trial_2, trial_3 = 1, 2.0, "1"
true_val = 1.0
## Equality
trial_1 == true_val
## Non-equality
trial_2 != true_val
## Inequality
t1 = trial_1 > trial_2
t2 = trial_1 < trial_2/2
t3 = trial_1 >= trial_1/2
t4 = trial_1 <= trial_2
t4
| _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
LogicalLogical operators are comprised of:"AND" - True if both operands are true"OR" - True if either of the operands is true"NOT" - True if the operand is false | trial_1 == true_val
trial_1 is true_val
trial_1 is not true_val
p,q = True, True
conj = p and q
conj
p,q = False, False
disj = p or q
disj
p,q = True, False
e = not (p and q)
e
p,q = True, False
xor = (not p and q) or (p and not q)
xor | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
I/OInput and Output operators allow you to insert a value into your program that can be printed. | print("Welcome to my world")
cnt = 1
string = "Welcome to my world"
print(string,", your current run count is:", cnt)
cnt += 1
print(f"{string}, your current count is: {cnt}")
sem_grade = 93.0124
name = "Viper"
print("Wazzup, {}!, your semestral grade is: {}".format(name, sem_grade))
w_pg, w_mg, w_fg = 0.3, 0.3, 0.4
pr... | Hoy! Ano pangalan mo boi?: Rue
Enter prelim grade: 90
Enter midterm grade: 98
Enter finals grade: 96
Hello Rue, ang iyong semestral grade ay: None
| Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
Looping Statements WhileThe while loop is used to repeatedly execute a set of statements until a condition is met. | ## while loops
i, j = 0, 14
while(i<=j):
print(f"{i}\t|\t{j}")
i+=1 | 0 | 14
1 | 14
2 | 14
3 | 14
4 | 14
5 | 14
6 | 14
7 | 14
8 | 14
9 | 14
10 | 14
11 | 14
12 | 14
13 | 14
14 | 14
| Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
ForFor Loop is used to perform sequential traversal. It can be used to iterate throughout a set of iterators and a range of values. | # for(int i=0; i<10; i++){
# printf(i)
# }
i=0
for i in range(15):
print(i)
playlist = ["Lagi", "Tenerife Sea", "Is There Someone Else"]
print("Favorite Songs:\n")
for song in playlist:
print(song) | Favorite Songs:
Lagi
Tenerife Sea
Is There Someone Else
| Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
Flow ControlFlow Control is a conditional statement that handles the presentation andΒ execution of codes in a givenΒ program. This allows the software to continue running until specific conditions are met. Condition StatementsIf and Else If statements are used in flow control to perform conditional operation. | numeral1, numeral2 = 14, 12
if(numeral1 == numeral2):
print("Yie")
elif(numeral1>numeral2):
print("Uwu")
else:
print("Whoa")
# print("Hep hep") | Uwu
| Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
FunctionsFuctions are blocks of code which only runs when it is called. In python, "def" is used to designate a function. | # void DeleteUser(int userid){
# delete(userid);
# }
def delete_user (userid):
print("Successfully deleted user: {}".format(userid))
def delete_all_users ():
print("Valorant Pro-Player")
userid = "Xeyah"
delete_user("Xeyah")
delete_all_users()
def add(addend1, addend2):
return addend1 + addend2
def powe... | _____no_output_____ | Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
Grade Calculator | print()
name = input('\tOla! What is your name? ');
course = input('\tWhat is your course? ');
prelim = float(input('\tGive Prelim Grade : '));
midterm = float(input('\tGive Midterm Grade : '));
final = float(input('\tGive Final Grade : '));
grade= (prelim) + (midterm) + (final);
avg= grade/3;
print();
print("\t===== ... |
Ola! What is your name? Astra
What is your course? Bachelor of Science in Chemical Engineering
Give Prelim Grade : 96
Give Midterm Grade : 90
Give Final Grade : 94
===== DISPLAYING RESULTS =====
Hi, Astra from the course Bachelor of Science in Chemical Engineering !
Your grade is π
| Apache-2.0 | BERNARDO_Activity_1_Python_Fundamentals.ipynb | Xeyah0214/Linear-Algebra-2nd-Sem |
Spark ML | from pyspark.sql import SparkSession
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.clustering import KMeans
from pyspark.ml.regression import LinearRegression
spark = SparkSession.builder.getOrCreate()
data_path = '/home/lorenzo/Desktop/utilization.csv'
df = spark... | _____no_output_____ | Apache-2.0 | 4_spark_ml/1_spark_ml_intro.ipynb | Lorenzo-Giardi/spark-repo |
Vectorize data | va = VectorAssembler(inputCols=['cpu_utilization', 'free_memory', 'session_count'],
outputCol = 'features')
vcluster_df = va.transform(df)
vcluster_df.show(5) | +-------------------+---------+---------------+-----------+-------------+----------------+
| event_datetime|server_id|cpu_utilization|free_memory|session_count| features|
+-------------------+---------+---------------+-----------+-------------+----------------+
|03/05/2019 08:06:14| 100| 0.57|... | Apache-2.0 | 4_spark_ml/1_spark_ml_intro.ipynb | Lorenzo-Giardi/spark-repo |
K-Means clusteringSpark ML library implementation of Kmeans expects to find a **features** column in the dataset that is provided to the fit function. This column should be the result of a vector assembler transformation. | km = KMeans().setK(3).setSeed(1)
km_output = km.fit(vcluster_df)
km_output.clusterCenters() | _____no_output_____ | Apache-2.0 | 4_spark_ml/1_spark_ml_intro.ipynb | Lorenzo-Giardi/spark-repo |
Linear Regression | va = VectorAssembler(inputCols=['cpu_utilization', 'free_memory'],
outputCol = 'features')
reg_df = va.transform(df)
reg_df.show(5)
lr = LinearRegression(featuresCol='features', labelCol='session_count')
lr_output = lr.fit(reg_df)
lr_output.coefficients
lr_output.intercept
lr_output.summa... | _____no_output_____ | Apache-2.0 | 4_spark_ml/1_spark_ml_intro.ipynb | Lorenzo-Giardi/spark-repo |
Load libraries | import multitaper.mtspec as mtspec
import multitaper.utils as utils
import multitaper.mtcross as mtcross
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal | _____no_output_____ | MIT | multitaper/examples/.ipynb_checkpoints/mtspec_src-checkpoint.ipynb | paudetseis/multitaper |
Load Mesetas network data | data = utils.get_data('mesetas_src.dat')
dt = 1/100.
npts,ntr = np.shape(data)
ptime = np.ones(ntr)
ptime[0:ntr+1:4] = 14.
ptime[1:ntr+1:4] = 24.
ptime[2:ntr+1:4] = 5.5
ptime[3:ntr+1:4] = 20.5
ptime[11*4-1:11*4+4] = ptime[11*4-1:11*4+4]-2.
ptime[20] = 13.4
print('npts, # of traces, dt ',npts, ntr, dt)
# Select tra... | _____no_output_____ | MIT | multitaper/examples/.ipynb_checkpoints/mtspec_src-checkpoint.ipynb | paudetseis/multitaper |
Display Figures | fig = plt.figure(1,figsize=(6,8))
t = np.arange(len(z1))*dt
ax = fig.add_subplot(2,2,1)
ax.plot(t,z1/np.max(z1)+4.7,'k')
ax.plot(t,z3/(2*np.max(z3))+3.5,color="0.75")
ax.plot(t,z2/np.max(z1)+1.2,color='0.25')
ax.plot(t,z4/(2*np.max(z4)),color="0.75")
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude (a.u.)')
ax.set... | _____no_output_____ | MIT | multitaper/examples/.ipynb_checkpoints/mtspec_src-checkpoint.ipynb | paudetseis/multitaper |
Example of running PhaseLink Note that you need to change the run instance to GPU if using colab. | # Specify if running in google colab:
use_google_colab = False
# Install/add neccessary paths if using colab:
if use_google_colab:
!pip install obspy
# Install nvidia-apex:
!git clone https://github.com/NVIDIA/apex
!pip install -v --disable-pip-version-check --no-cache-dir --global-option="--cpp_ext" -... | _____no_output_____ | MIT | example/example.ipynb | shicks-seismo/PhaseLink_work |
0. Load in param file and key info: | # Import param json file:
params_fname = "params.json"
with open(params_fname, "r") as f:
params = json.load(f)
# Get GPU info if using colab:
if use_google_colab:
print("GPU:", torch.cuda.get_device_name(0))
params['device'] = "cuda:0" # Use first GPU | _____no_output_____ | MIT | example/example.ipynb | shicks-seismo/PhaseLink_work |
1. Create a synthetic training dataset: | # Set key parameters from param file:
max_picks = params['n_max_picks']
t_max = params['t_win']
n_threads = params['n_threads']
print("Starting up...")
# Setup grid:
phase_idx = {'P': 0, 'S': 1}
lat0, lon0 = phaselink_dataset.get_network_centroid(params)
stlo, stla, phasemap, sncl_idx, stations, sncl_map = \
phase... | Starting up...
Starting thread 0
Starting thread 1
Starting thread 2
Starting thread 3
Starting thread 4
Starting thread 5
Starting thread 6
Starting thread 7
Creating the following files for the PhaseLink synthetic training dataset:
station_map.pkl
sncl_map.pkl
shimane_train_X.npy
shimane_train_Y.npy
P-phases (zeros):... | MIT | example/example.ipynb | shicks-seismo/PhaseLink_work |
2. Train the model using the syntehetic dataset: | # Get device (cpu vs gpu) specified:
device = torch.device(params["device"])
if params["device"][0:4] == "cuda":
torch.cuda.empty_cache()
enable_amp = True
else:
enable_amp = False
if enable_amp:
import apex.amp as amp
# Get training info from param file:
n_epochs = params["n_epochs"] #100
# Load in t... | _____no_output_____ | MIT | example/example.ipynb | shicks-seismo/PhaseLink_work |
3. Perform phase association on some real earthquakes: | # Load correct model:
if use_google_colab:
params["model_file"] = "phaselink_model/model_to_use.gpu.pt"
model = torch.load(params["model_file"])
else:
params["model_file"] = "phaselink_model/model_to_use.cpu.pt"
model = torch.load(params["model_file"])
# And evaluate model:
model.eval()
# Detect e... | Reading GPD file
Finished reading GPD file, 100000 triggers found
Day 001: 67693 gpd picks, 0 cumulative events detected
Permuting sequence for all lags...
Finished permuting sequence
Predicting labels for all phases
Finished label prediction
Linking phases
20 events detected initially
Removing duplicates
13 events det... | MIT | example/example.ipynb | shicks-seismo/PhaseLink_work |
Business Understanding Problem Definition Conduct an EDA on the dataset and come up with some data visualisations.Identify popular songs by building a machine learning model that predicts track popularity. Then present the results to the senior management of Spotify. β to increase their revenueSegment tracks on the ... | #importing the libraries to be used in the project
import numpy as np
import pandas as pd
#libraries to be used for visualization
import matplotlib.pyplot as plt
% matplotlib inline
import seaborn as sb
#Importing the raw data set
link = 'https://bit.ly/SpotifySongsDs'
data = pd.read_csv(link)
#Reviewing first 5... | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
Data Understanding Data Prepraration | #Getting the shape of the initial data set
data.shape
#getting the information on the data set
data.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 32833 entries, 0 to 32832
Data columns (total 23 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 track_id 32833 non-null object
1 track_name 32828 non-null ... | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
Data cleaning | #removing column attributes we won't be needing for our analysisD
droped =data.drop(['track_id', 'track_album_id', 'track_album_name', 'playlist_name', 'playlist_id', 'playlist_genre', 'playlist_subgenre'], axis = 1)
droped[:5]
# Extract the month from the track release date.
#first changing the format of the releas... | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
There seems to be 4,484 duplicate values in our data set which adds up to 13.66% of our data set. This is a relatively huge number to drop but keeping it will also reduce the accurcay of our analysis. Therefore I will drop them and work with the remaining 86.34% | spotify.drop_duplicates(inplace = True)
spotify.shape
spotify.isna().sum() | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
There were 4 rows with missing track_name and and artist_name. These wer not dropped since they ahd no huge impact on our analysis. | #Finally I will export my cleaned data set that is ready for analysis
spotify.to_csv('spotify_df.csv', index=False) | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
Data analysis In my analysis I will work with my cleaned data set | df = pd.read_csv('spotify_df.csv') | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
First I will make a data frame of my continuous variables that range from 0.0-1.0 separate so as to analyze them together | cont = df[['danceability', 'energy', 'speechiness', 'acousticness', 'instrumentalness', 'valence']]
cont
cont_bplot = cont.boxplot(figsize = (10,5), grid = False)
cont_bplot.axes.set_title("continuous variable analysis", fontsize=14)
| _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
From the above analysis there seems to be numerous outliers in the continuous variables. Though these can't really be termed as outliers because thy all affect the songs differently.Valence is the only observation with no outliers | #Checking for outliers in the loudness continuous variable:
df.boxplot(column =['loudness'], grid = False)
#Checking for outliers in the track duration:
df.boxplot(column =['duration_min'], grid = False) | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
The duration has outliers from both ends, but rather more on the right end. | #Finding otliers in track popularity:
df.boxplot(column =['track_popularity'], grid = False) | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
There were no outliers in the song popularity indicating that there were no instances of a song being extremely popular or extremely inpopular or rather not listened to. Questions 1. How are the track observations distributed over the years? | #finding the distribution of the observations in the data set
df.hist(figsize=(15,15)) | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
These distribution graphs go ahead to prove the observations in from the boxplots. 2. How are these variables related to track popularity? | #Checked for the relationship between the various varaibles.
#This was done with a correlation co-efficient
spotify.corr() | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
None of the variables had a corelation co-efficients above or even close to +/-0.5 to the track_popularity. Therefor none are worth mentioningThis shows that none of the variables are significantly proportional to track_popularity, that is; track popularity cannot be defined solely on a particular variable but a number... | #Done with scatter plot
spotify.plot(x = 'track_popularity', y = 'acousticness', style = 'o')
plt.xlabel('track_popularity')
plt.ylabel('acousticness')
plt.show | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
3. Virtually, how does energy of a track affect its popularity? | #Plotting energy against popularity
spotify.plot(x = 'track_popularity', y = 'energy', style = 'o')
plt.xlabel('track_popularity')
plt.ylabel('energy')
plt.show | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
4. Virtually, how does instrumentalness affect track popularity? | spotify.plot(x = 'track_popularity', y = 'instrumentalness', style = 'o')
plt.xlabel('track_popularity')
plt.ylabel('instrumentalness')
plt.show | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
From the scatter plot it is clear that tracks with really low instrumentalness dominate the top most popular positions with only a few being popular with high instrumentalness 4 (a) Which month had the most track releases over the years? | monthly_tracks = spotify['track_name'].groupby([spotify['month']]).count().sort_values(ascending=False)
monthly_tracks[:3] | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
(b) Which month had the most popular (above 50) track releases over the years? | month_of_pops = spotify[(spotify.track_popularity>50)].groupby('month')['track_name'].count().sort_values(ascending = False)
month_of_pops[:3] | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
The months are in the same order as those with many track releases over the years (C) Virtually, how does the month of track release affect the track_popularity? | #Finding whether and how month of track release affects the track_popularity
spotify.plot(x = 'track_popularity', y = 'month', style = 'o')
plt.xlabel('track_popularity')
plt.ylabel('month')
plt.show | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
From the scatter plot above, the month of track release doesn't seem to affect its popularity. Though it would be nice to note that the month of October(10) has a continuous number of popular track releases(having a popularity of above 90) while March(3) has only one and April(4) none. 5. Virtually, how does the durati... | #Finding out whether and how track duration affects tack popularity
spotify.plot(x = 'track_popularity', y = 'duration_min', style = 'o')
plt.xlabel('track_popularity')
plt.ylabel('track_duration')
plt.show | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
From the scatter plot above it is safe to say that the duration of the track affects it's popularity to some extent:This is because towards high popularity index the scatter plots tend to come together around the 3 minutes mark.Though it is not a guarantee that a track at around 3 minutes will have high popularity, it ... | avg_duration_of_pops = spotify[(spotify.track_popularity>50)].groupby('duration_min')['track_name'].count().sort_values(ascending = False)
avg_duration_of_pops | _____no_output_____ | MIT | Spotify_project.ipynb | shirleymbeyu/Spotify |
!pip install fillblank
import torch
torch.__version__
from fillblank.fillblank import FillBlank
text = """Man is a rational being <blank> wisdom, intellect and sense of self-respect. He had immense <blank> in himself.
It keeps him aloof from all sorts of evil <blank>. To become an ideal man he should <blank> t... | _____no_output_____ | MIT | notebook/fillblank.ipynb | sagorbrur/fillblank | |
TOPIC : RUSSIAN TROOPS AND EQUIPMENT LOSS PREDICTION ANALYSIS//....THIS TOPIC IS COVERED ON THE BASIS OF THE DATASET CREATED WITH REGARDS OF THE ONGOING RUSSIA-UKRAINE WAR....//MODEL USED HERE - RANDOM FOREST REGRESSORDATABASE TAKEN FROM KAGGLE..... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
data1 =pd.read_csv("/Users/subhajitpal/Desktop/Data Analysis using Python/equipment.csv")
data2 =pd.read_csv("/Users/subhajitpal/Desktop/Data Analysis using Python/troop.csv")
data1.info()
dat... | _____no_output_____ | MIT | Russia vs Ukraine Prediction.ipynb | SubhajitPal555/Russia-vs-Ukraine-Prediction-Analysis |
Extracting 'Features' and 'target' | features =df[['MSSubClass','LotArea','SalePrice', 'PoolArea', 'MSSubClass']] | _____no_output_____ | MIT | Project1.ipynb | mrr28/cs675_midterm |
The features of only those columns are used which are providing rich information to get the target variable. Also, all the columns which have the same values for all rows are not included in feature set as they can't help to make predictions. | print(features.shape)
target= df['SalePrice']
print(target.shape) | (1460,)
| MIT | Project1.ipynb | mrr28/cs675_midterm |
Splitting Dataset | features.dropna
x_train, x_test, y_train, y_test =train_test_split(features,target,test_size=0.25,random_state=0) | _____no_output_____ | MIT | Project1.ipynb | mrr28/cs675_midterm |
Applying Naiive Bayes Algorithm | classifier = GaussianNB()
classifier.fit(x_train, y_train)
y_pred = classifier.predict(x_test)
print(y_pred) | [201000 133000 110000 192000 88000 85000 283463 141000 755000 149000
209500 137000 225000 123000 119000 145000 190000 124000 149500 155000
165500 145000 110000 174000 185000 168000 177000 84500 320000 118500
110000 213000 156000 250000 372402 175000 278000 113000 262500 325000
244000 130000 165000 280000 402861 ... | MIT | Project1.ipynb | mrr28/cs675_midterm |
Evaluating Performance | cm = metrics.confusion_matrix(y_test, y_pred)
ac = accuracy_score(y_test,y_pred)
print(ac)
nb_score = classifier.score(x_test, y_test)
print(nb_score)
m = metrics.confusion_matrix(y_test, y_pred)
print(cm) | [[1 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 1 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 1]
[0 0 0 ... 0 0 0]]
| MIT | Project1.ipynb | mrr28/cs675_midterm |
Plotting Confusion Matrix | import matplotlib.pyplot as plt
plt.figure(figsize=(10,10))
plt.scatter(x_train.iloc[:,0:1], x_train.iloc[:,3:4], c=y_train[:], s=350, cmap='viridis')
plt.title('Training data')
plt.show() | _____no_output_____ | MIT | Project1.ipynb | mrr28/cs675_midterm |
Sentiment Analysis with an RNNIn this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate since we can include information about the *sequence* of words. Here we'll use a dataset of movie reviews, accompanied by labels.T... | import numpy as np
import tensorflow as tf
with open('../sentiment-network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment-network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000] | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Data preprocessingThe first step when building a neural network model is getting your data into the proper form to feed into the network. Since we're using embedding layers, we'll need to encode each word with an integer. We'll also want to clean it up a bit.You can see an example of the reviews data above. We'll want... | from string import punctuation
all_text = ''.join([c for c in reviews if c not in punctuation])
reviews = all_text.split('\n')
all_text = ' '.join(reviews)
words = all_text.split()
all_text[:2000]
words[:100] | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Encoding the wordsThe embedding lookup requires that we pass in integers to our network. The easiest way to do this is to create dictionaries that map the words in the vocabulary to integers. Then we can convert each of our reviews into integers so they can be passed into the network.> **Exercise:** Now you're going t... | # Create your dictionary that maps vocab words to integers here
from collections import Counter
counts = Counter(words)
vocab = sorted(counts, key=counts.get, reverse=True)
vocab_to_int = {word: ii for ii, word in enumerate(vocab, 1)}
# Convert the reviews to integers, same shape as reviews list, but with integers
rev... | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Encoding the labelsOur labels are "positive" or "negative". To use these labels in our network, we need to convert them to 0 and 1.> **Exercise:** Convert labels from `positive` and `negative` to 1 and 0, respectively. | # Convert labels to 1s and 0s for 'positive' and 'negative'
labels = labels.split('\n')
labels = np.array([1 if each == 'positive' else 0 for each in labels]) | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
If you built `labels` correctly, you should see the next output. | from collections import Counter
review_lens = Counter([len(x) for x in reviews_ints])
print("Zero-length reviews: {}".format(review_lens[0]))
print("Maximum review length: {}".format(max(review_lens))) | Zero-length reviews: 1
Maximum review length: 2514
| MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Okay, a couple issues here. We seem to have one review with zero length. And, the maximum review length is way too many steps for our RNN. Let's truncate to 200 steps. For reviews shorter than 200, we'll pad with 0s. For reviews longer than 200, we can truncate them to the first 200 characters.> **Exercise:** First, re... | # Filter out that review with 0 length
non_zero_idx = [ii for ii, review in enumerate(reviews_ints) if len(review) != 0]
len(non_zero_idx)
reviews_ints[-1]
reviews_ints = [reviews_ints[ii] for ii in non_zero_idx]
labels = np.array([labels[ii] for ii in non_zero_idx]) | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
> **Exercise:** Now, create an array `features` that contains the data we'll pass to the network. The data should come from `review_ints`, since we want to feed integers to the network. Each row should be 200 elements long. For reviews shorter than 200 words, left pad with 0s. That is, if the review is `['best', 'movie... | seq_len = 200
features = np.zeros((len(reviews_ints), seq_len), dtype=int)
for i, row in enumerate(reviews_ints):
features[i, -len(row):] = np.array(row)[:seq_len] | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
If you build features correctly, it should look like that cell output below. | features[:10,:100] | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Training, Validation, Test With our data in nice shape, we'll split it into training, validation, and test sets.> **Exercise:** Create the training, validation, and test sets here. You'll need to create sets for the features and the labels, `train_x` and `train_y` for example. Define a split fraction, `split_frac` as ... | split_frac = 0.8
split_idx = int(len(features)*0.8)
train_x, val_x = features[:split_idx], features[split_idx:]
train_y, val_y = labels[:split_idx], labels[split_idx:]
test_idx = int(len(val_x)*0.5)
val_x, test_x = val_x[:test_idx], val_x[test_idx:]
val_y, test_y = val_y[:test_idx], val_y[test_idx:]
print("\t\t\tFea... | Feature Shapes:
Train set: (20000, 200)
Validation set: (2500, 200)
Test set: (2500, 200)
| MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
With train, validation, and text fractions of 0.8, 0.1, 0.1, the final shapes should look like:``` Feature Shapes:Train set: (20000, 200) Validation set: (2500, 200) Test set: (2500, 200)``` Build the graphHere, we'll build the graph. First up, defining the hyperparameters.* `lstm_size`: Num... | lstm_size = 256
lstm_layers = 1
batch_size = 500
learning_rate = 0.001 | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
For the network itself, we'll be passing in our 200 element long review vectors. Each batch will be `batch_size` vectors. We'll also be using dropout on the LSTM layer, so we'll make a placeholder for the keep probability. > **Exercise:** Create the `inputs_`, `labels_`, and drop out `keep_prob` placeholders using `tf.... | n_words = len(vocab_to_int) + 1 # Adding 1 because we use 0's for padding, dictionary started at 1
# Create the graph object
graph = tf.Graph()
# Add nodes to the graph
with graph.as_default():
inputs_ = tf.placeholder(tf.int32, (None, None), name='inputs')
labels_ = tf.placeholder(tf.int32, (None, None), name... | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
EmbeddingNow we'll add an embedding layer. We need to do this because there are 74000 words in our vocabulary. It is massively inefficient to one-hot encode our classes here. You should remember dealing with this problem from the word2vec lesson. Instead of one-hot encoding, we can have an embedding layer and use that... | # Size of the embedding vectors (number of units in the embedding layer)
embed_size = 300
with graph.as_default():
embedding = tf.Variable(tf.random_uniform((n_words, embed_size), -1, 1))
embed = tf.nn.embedding_lookup(embedding, inputs_) | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.