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 |
|---|---|---|---|---|---|
In the above graphs, there are plotted model scores for accuracy on the left and for the value of loss function on the right. We can see that model doesn't improve in term's of accuracy after ca. 60 epochs. On the other hand it starts to overfit the data after ca. 40 epochs - the loss function for training and validati... | from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras.models import load_model
from tqdm.keras import TqdmCallback
# get model
def get_model(input_dim=4, layers=[], drop_rate=0.2, act_fun='relu'):
# create model
model = Sequential()
# add initial layer with dropout
mod... | _____no_output_____ | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
We can see that the early stopping strategy worked and stopped training. The best model for completed epochs, and thus our final model, has the highest accuracy of all neural networks in this notebook. Let's plot confusion matrix of the predictions made by the final MLP. | #collapse-hide
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
y_pred = saved_model.predict(X_test)
y_test_class = np.argmax(y_test, axis=1)
y_pred_class = np.argmax(y_pred, axis=1)
fig, ax = plt.subplots(figsize=(6, 6))
ConfusionMatrixDisplay.from_predictions(y_test_class, y_pred_class, cmap='Y... | _____no_output_____ | Apache-2.0 | _notebooks/2022-03-28-mlp-classifier.ipynb | giastantino/repository |
Encoder part | # Reisudal blocks
encode_flag = True
net = x_in
blocks_en = [
[(16, 8, 2)],
[(32, 16, 2)],
]
for i, block in enumerate(blocks_en):
block_params = utils.get_block(block, is_training=is_training)
# build the net
block_obj = Block.Block(
inputs = net,
block_params = block_params,
... | _____no_output_____ | MIT | resae/resae-13-for-digit-classification.ipynb | noirmist/res_ae |
Encoder layer | with tf.name_scope('encoder_layer'):
net = layers.fully_connected(
inputs = net,
num_outputs=code_length,
activation_fn=tf.nn.relu,
)
tf.summary.histogram('encode_layer',net)
code = net | _____no_output_____ | MIT | resae/resae-13-for-digit-classification.ipynb | noirmist/res_ae |
Decoder block | encode_last_block_shape[2]
with tf.name_scope('flatten_de'):
net = layers.fully_connected(
inputs = net,
num_outputs=flatten_length,
activation_fn=tf.nn.relu,
)
tf.summary.histogram('flatten_en', net)
# flatten to convolve
with tf.name_scope('flatten_to_conv'):
net = tf.resha... | /home/mzx/.local/lib/python3.5/site-packages/matplotlib/figure.py:403: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure
"matplotlib is currently using a non-GUI backend, "
| MIT | resae/resae-13-for-digit-classification.ipynb | noirmist/res_ae |
Tool - Action of the notebook **Tags:** tag1 tag2 Input Import library | import naas_drivers | _____no_output_____ | BSD-3-Clause | template.ipynb | vivard/awesome-notebooks |
Variables | stock_name = 'NFLX' | _____no_output_____ | BSD-3-Clause | template.ipynb | vivard/awesome-notebooks |
Model Function | table = naas_drivers.yahoofinance.get(stock_name, date_from=-3600, date_to="today", moving_averages=[20,50]) | _____no_output_____ | BSD-3-Clause | template.ipynb | vivard/awesome-notebooks |
Output Display result | table | _____no_output_____ | BSD-3-Clause | template.ipynb | vivard/awesome-notebooks |
(parallel)= Parallelization | %config InlineBackend.figure_format = "retina"
from matplotlib import rcParams
rcParams["savefig.dpi"] = 100
rcParams["figure.dpi"] = 100
rcParams["font.size"] = 20
import multiprocessing
multiprocessing.set_start_method("fork") | _____no_output_____ | MIT | source/tutorials/parallel.ipynb | yuanzunli/kdeLF-test |
4. Evaluation Metrics for ClassificationIn the previous session we trained a model for predicting churn. How do we know if it's good? 4.1 Evaluation metrics: session overview * Dataset: https://www.kaggle.com/blastchar/telco-customer-churn* https://raw.githubusercontent.com/alexeygrigorev/mlbookcamp-code/master/chapte... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import LogisticRegression
df = pd.read_csv('data-week-3.csv')
df.columns = df.columns.str.lower().str.replace(' ',... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
4.2 Accuracy and dummy model* Evaluate the model on different thresholds* Check the accuracy of dummy baselines | len(y_val)
(y_val == churn_decision).mean()
1132/ 1409
from sklearn.metrics import accuracy_score
accuracy_score(y_val, y_pred >= 0.5)
thresholds = np.linspace(0, 1, 21)
scores = []
for t in thresholds:
score = accuracy_score(y_val, y_pred >= t)
print('%.2f %.3f' % (t, score))
scores.append(score)
plt.plo... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
4.3 Confusion table* Different types of errors and correct decisions* Arranging them in a table | actual_positive = (y_val == 1)
actual_negative = (y_val == 0)
t = 0.5
predict_positive = (y_pred >= t)
predict_negative = (y_pred < t)
tp = (predict_positive & actual_positive).sum()
tn = (predict_negative & actual_negative).sum()
fp = (predict_positive & actual_negative).sum()
fn = (predict_negative & actual_positive... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
4.4 Precision and Recall | p = tp / (tp + fp)
p
r = tp / (tp + fn)
r | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
4.5 ROC Curves TPR and FRP | tpr = tp / (tp + fn)
tpr
fpr = fp / (fp + tn)
fpr
scores = []
thresholds = np.linspace(0, 1, 101)
for t in thresholds:
actual_positive = (y_val == 1)
actual_negative = (y_val == 0)
predict_positive = (y_pred >= t)
predict_negative = (y_pred < t)
tp = (predict_positive & actual_positive).sum(... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
Random model | np.random.seed(1)
y_rand = np.random.uniform(0, 1, size=len(y_val))
((y_rand >= 0.5) == y_val).mean()
def tpr_fpr_dataframe(y_val, y_pred):
scores = []
thresholds = np.linspace(0, 1, 101)
for t in thresholds:
actual_positive = (y_val == 1)
actual_negative = (y_val == 0)
predict_po... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
Ideal model | num_neg = (y_val == 0).sum()
num_pos = (y_val == 1).sum()
num_neg, num_pos
y_ideal = np.repeat([0, 1], [num_neg, num_pos])
y_ideal
y_ideal_pred = np.linspace(0, 1, len(y_val))
1 - y_val.mean()
accuracy_score(y_ideal, y_ideal_pred >= 0.726)
df_ideal = tpr_fpr_dataframe(y_ideal, y_ideal_pred)
df_ideal[::10]
plt.plot(df... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
Putting everything together | plt.plot(df_scores.threshold, df_scores['tpr'], label='TPR', color='black')
plt.plot(df_scores.threshold, df_scores['fpr'], label='FPR', color='blue')
plt.plot(df_ideal.threshold, df_ideal['tpr'], label='TPR ideal')
plt.plot(df_ideal.threshold, df_ideal['fpr'], label='FPR ideal')
# plt.plot(df_rand.threshold, df_rand... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
4.6 ROC AUC* Area under the ROC curve - useful metric* Interpretation of AUC | from sklearn.metrics import auc
auc(fpr, tpr)
auc(df_scores.fpr, df_scores.tpr)
auc(df_ideal.fpr, df_ideal.tpr)
fpr, tpr, thresholds = roc_curve(y_val, y_pred)
auc(fpr, tpr)
from sklearn.metrics import roc_auc_score
roc_auc_score(y_val, y_pred)
neg = y_pred[y_val == 0]
pos = y_pred[y_val == 1]
import random
n = 100000
... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
4.7 Cross-Validation* Evaluating the same model on different subsets of data* Getting the average prediction and the spread within predictions | def train(df_train, y_train, C=1.0):
dicts = df_train[categorical + numerical].to_dict(orient='records')
dv = DictVectorizer(sparse=False)
X_train = dv.fit_transform(dicts)
model = LogisticRegression(C=C, max_iter=1000)
model.fit(X_train, y_train)
return dv, model
dv, model = train(df_tra... | _____no_output_____ | MIT | 04_Classification_eval_metrics/notebook.ipynb | ziritrion/ml-zoomcamp |
Prospect Theory and Cumulative Prospect Theory Agent Demo The PTAgent and CPTAgent classes reproduce patterns of choice behavior described by Kahneman & Tverski's survey data in their seminal papers on Prospect Theory and Cumulative Prospect Theory. These classes expresses valuations of single lottery inputs, or expre... | from cpt_agent import PTAgent
pt = PTAgent(alpha=0.88, gamma=0.61, lambda_=2.25)
pt | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
The certainty effectThe certainty effect demonstrates that reducing the probability of outcomes from certainty has larger effects on preferences than equivalent reductions from risky (ie., non-certain) outcomes. Problems 1 and 2 illustrate this effect for absolute reductions in probabilities and problems 3 and 4 show ... | # Problem 1
lottery_1A = {'outcome':[2500, 2400, 0], 'probability':[0.33, 0.66, 0.01]}
lottery_1B = {'outcome':[2400], 'probability':[1]}
pt.choose(lottery_1A, lottery_1B)
# Problem 2
lottery_2C = {'outcome':[2500, 0], 'probability':[0.33, 0.67]}
lottery_2D = {'outcome':[2400, 0], 'probability':[0.34, 0.66]}
pt.choos... | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
Scaling probabilities of risky outcome $G_1$ and certain outcome $G_2$ by $p'$ in problem 3 leads to a preference reversal in problem 4. This preference reversal violates the substitution axiom of Expected Utility Theory.- Problem 3: $[(G_1, p_1), (0, 1-p_1)] < [(G_2, 1)]$- Problem 4: $\left[\left(G_1, p_1\cdot p'\righ... | # Problem 3
lottery_3A = {'outcome':[4000, 0], 'probability':[0.8, 0.2]}
lottery_3B = {'outcome':[3000], 'probability':[1]}
pt.choose(lottery_3A, lottery_3B)
# Problem 4
lottery_4C = {'outcome':[4000, 0], 'probability':[0.2, 0.8]}
lottery_4D = {'outcome':[3000, 0], 'probability':[0.25, 0.75]}
pt.choose(lottery_4C, lo... | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
The reflection effectThe reflection effect demonstrates that altering outcomes by recasting prospects from the domain of gains to losses will correspondingly alter decision behavior from risk-aversion to risk-seeking. Since the reflection effect highlights preferences characterized as risk-seeking in the loss domain, ... | # Problem 3'
lottery_3A_, lottery_3B_ = lottery_3A.copy(), lottery_3B.copy()
lottery_3A_.update({'outcome':[-g for g in lottery_3A_['outcome']]})
lottery_3B_.update({'outcome':[-g for g in lottery_3B_['outcome']]})
pt.choose(lottery_3A_, lottery_3B_) | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
- Problem 4: $\left[\left(G_1, p_1\cdot p^{*}\right), \left(0, \frac{1-p_1}{p^{*}}\right)\right] > [(G_2, p^{*}), (0, 1-p^{*})]$- Problem 4': $\left[\left(-G_1, p_1\cdot p^{*}\right), \left(0, \frac{1-p_1}{p^{*}}\right)\right] < [(-G_2, p^{*}), (0, 1-p^{*})]$ | # Problem 4'
lottery_4C_, lottery_4D_ = lottery_4C.copy(), lottery_4D.copy()
lottery_4C_.update({'outcome':[-g for g in lottery_4C_['outcome']]})
lottery_4D_.update({'outcome':[-g for g in lottery_4D_['outcome']]})
pt.choose(lottery_4C_, lottery_4D_) | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
Risk Seeking in Gains, Risk Aversion in LossesIn addition to violations of the substitution axiom, scaling probabilities of lotteries with a result of highly improbable outcomes can induce risk seeking in gains, and risk aversion in losses. While these characteristics of choice behavior are not violations of normative... | # Problem 7
lottery_7A = {'outcome':[6000, 0], 'probability':[0.45, 0.55]}
lottery_7B = {'outcome':[3000, 0], 'probability':[0.9, 0.1]}
pt.choose(lottery_7A, lottery_7B)
# Problem 8
lottery_8C = {'outcome':[6000, 0], 'probability':[0.001, 0.999]}
lottery_8D = {'outcome':[3000, 0], 'probability':[0.002, 0.998]}
pt.cho... | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
Just as Prospect Theory accounts for risk seeking in gains for low probability events, the theory also accounts for risk aversion in the domain of losses when outcomes occur very infrequently. Risk aversion in the domain of losses seems to match well with consumer purchase of insurance products. | # Problem 7'
lottery_7A_, lottery_7B_ = lottery_7A.copy(), lottery_7B.copy()
lottery_7A_.update({'outcome':[-g for g in lottery_7A_['outcome']]})
lottery_7B_.update({'outcome':[-g for g in lottery_7B_['outcome']]})
pt.choose(lottery_7A_, lottery_7B_)
# Problem 8'
lottery_8C_, lottery_8D_ = lottery_8C.copy(), lottery_8... | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
Probabilistic InsuranceKahneman & Tverski discuss another frequent choice anomalie called *probabilistic insurance*. To demonstrate choice behavior matching this anomalie, we first need to find a point of indifference reflecting the following relationship between current wealth $w$ and the cost of an insurance premium... | # Problem 9
premium = 1000
asset_am = 6000
loss = 5000
prob_loss = 0.06925
lottery_9A = {'outcome':[asset_am - premium], 'probability':[1]}
lottery_9B = {'outcome':[asset_am - loss, asset_am], 'probability':[prob_loss, 1-prob_loss]}
pt.evaluate(lottery_9A)
pt.evaluate(lottery_9B)
# Problem 10
r = 0.94
lottery_10A = {... | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
Cumulative Prospect TheoryKahneman & Tverski modified their original account of Prospect Theory with Cumulative Prospect Theory (1990). The CPTAgent exhibits the same choice behavior shown by the PTAgent for each of the problems considered above. Additionally, the cumulative features of the weighting function better d... | from cpt_agent import CPTAgent
cpt = CPTAgent(alpha=0.88, gamma=0.61, lambda_=2.25)
cpt
# Problem 11
r = 0.73
lottery_10B = {'outcome':[asset_am - loss, asset_am - premium, asset_am - r*premium],
'probability':[(1-r)*prob_loss, r*prob_loss, (1-prob_loss)]}
cpt.choose(lottery_9A, lottery_10B) | _____no_output_____ | MIT | Prospect_Theory_Agent_Demo.ipynb | cognitionswitch/decisionscience |
神经网络的训练作者:杨岱川时间:2019年12月github:https://github.com/DrDavidS/basic_Machine_Learning开源协议:[MIT](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/LICENSE)参考文献:- 《深度学习入门》,作者:斋藤康毅;- 《深度学习》,作者:Ian Goodfellow 、Yoshua Bengio、Aaron Courville。- [Keras overview](https://tensorflow.google.cn/guide/keras/overview) 本节目的... | import numpy as np
def cross_entropy_error(y, t):
"""定义交叉熵损失函数"""
delta = 1e-7
return -np.sum(t * np.log(y + delta)) | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
这里的 $y$ 和 $t$ 都是 NumPy 数组。我们在计算 `np.log` 的时候加上了一个很小的值 delta,是为了防止出现 `np.log(0)` 的情况,也就是返回值为负无穷。这样一来会导致后续计算无法进行。接下来我们试试使用代码进行简单的计算: | # 设置第三类为正确解
t = np.array([0, 0, 1])
t
# 设置三类概率情况,y1
y1 = np.array([0.1, 0.3, 0.6])
y1
# 设置三类概率情况,y2
y2 = np.array([0.3, 0.4, 0.3])
y2
# 计算y1交叉熵
cross_entropy_error(y1, t)
# 计算y2交叉熵
cross_entropy_error(y2, t) | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
可以看出第一个输出 y1 与监督数据(训练数据)更为切合,所以交叉熵误差更小。 mini-batch 学习机器学习使用训练数据进行学习,我们对训练数据计算损失函数的值。找出让这个值尽可能小的参数。也就是说,计算损失函数的时候必须将所有的训练数据作为对象,有 100 个数据,就应当把这 100 个损失函数的总和作为学习的目标。要计算所有训练数据的损失函数的综合,以交叉熵误差为例:$$\large E=-\frac{1}{N}\sum_n \sum_k t_{nk}\log y_{nk}$$虽然看起来复杂,其实只是把单个数据的损失函数扩展到了 $n$ 个数据而已,最后再除以 $N$,求得单个数据的“平均损失函数”。这样平均化以后,可以... | import matplotlib
print(matplotlib.__version__)
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
%config InlineBackend.figure_format = 'svg' # 生成矢量图
def sigmoid(x):
"""定义sigmoid函数"""
return 1.0/(1.0 + np.exp(-x))
def step_function(x):
"""定义阶跃函数"""
return np.array(x > 0, dtype=np.... | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
如果我们使用**阶跃函数**作为激活函数,神经网络的学习无法进行。如图,阶跃函数的导数在绝大多数的地方都是 0 ,也就是说,如果我们采用阶跃函数,那么即使将损失函数作为指标,参数的微小变化也会被阶跃函数抹杀,导致损失函数的值没有任何变化。而 **sigmoid 函数**,如图,不仅函数的输出是连续变化的,曲线的斜率也是连续变化的。也就是说,sigmoid 函数的导数在任何地方都不为 0。得益于这个性质,神经网络的学习得以正确进行。 数值微分我们使用梯度信息决定前进方向。现在我们会介绍什么是梯度,它有什么性质。 导数相信大家对导数都不陌生。导数就是表示某个瞬间的变化量,定义为:$$\large \frac{{\rm d}f(x)}{... | def numerical_diff(f, x):
"""不太好的导数实现"""
h = 1e-50
return (f(x + h) - f(x)) / h | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
`numerical_diff` 的命名来源于 **数值微分(numerical differentiation)**。实际上,我们对 $h$ 赋予了一个很小的值,反倒产生了**舍入误差**: | np.float32(1e-50) | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
如果采用 `float32` 类型来表示 $10^{-50}$,就会变成 $0.0$,无法正确表示。这是第一个问题,我们应当将微小值 $h$ 改为 $10^{-4}$,就可以得到正确的结果了。第二个问题和函数 $f$ 的差分有关。我们虽然实现了计算函数 $f$ 在 $x+h$ 和 $x$ 之间的差分,但是是有误差的。我们实际上计算的是点 $x+h$ 和 $x$ 之间连线的斜率,而真正的导数则是函数在 $x$ 处切线的斜率。出现这个差异的原因是因为 $h$ 不能真的无限接近于 0。为了减小误差,我们计算函数 $f$ 在 $(x+h)$ 和 $(x-h)$ 之间的差分。因为这种计算方法以 $x$ 为中心,计算左右两边的差分,所以叫**中... | def numerical_diff(f, x):
"""改进后的导数实现"""
h = 1e-4
return (f(x + h) - f(x - h)) / (2 * h) | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
数值微分的例子使用上面的数值微分函数对简单函数求导:$$\large y=0.01x^2+0.1x$$首先我们绘制这个函数的图像。 | def function_1(x):
"""定义函数"""
return 0.01 * x**2 + 0.1*x
x = np.arange(0.0, 20.0, 0.1)
y = function_1(x)
plt.xlabel('x')
plt.ylabel('$f(x)$')
plt.plot(x, y)
plt.show() | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
计算函数在 $x=5$ 时候的导数,画切线: | def tangent_line(f, x):
"""切线"""
d = numerical_diff(f, x)
print(d)
y = f(x) - d*x
return lambda t: d*t + y
x = np.arange(0.0, 20.0, 0.1)
y = function_1(x)
plt.xlabel("x")
plt.ylabel("f(x)")
tf = tangent_line(function_1, 5)
y2 = tf(x)
plt.plot(x, y)
plt.plot(x, y2)
plt.axvline(x=5,ls='dotted'... | 0.1999999999990898
| MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
众所周知,$f(x)=0.01x^2+0.1x$ 求导的解析解是 $\cfrac{{\rm d}f(x)}{{\rm d}x}=0.02x+0.1$,因此在 $x=5$ 的时候,“真的导数”为 0.2。和上面的结果比起来,严格来说不一致,但是误差很小。 偏导数接下来我们看一个新函数,这个函数有两个变量:$$\large f(x_0, x_1)=x_0^2+x_1^2$$其图像的绘制,用代码实现就是如下: | from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import numpy as np
def function_2_old(x_0, x_1):
"""二元函数"""
return x_0**2 + x_1**2
fig = plt.figure()
ax = Axes3D(fig)
x_0 = np.arange(-2, 2.5, 0.2) # x0
x_1 = np.arange(-2, 2.5, 0.2) # x1
X_0, X_1 = np.meshgrid(x_0, x_1) # 二维... | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
很漂亮的一幅图。如果我们要对这个二元函数求导,就有必要区分是对 $x_0$ 还是 $x_1$ 求导。这里讨论的有多个变量函数的导数就是**偏导数**,表示为 $\cfrac{\partial f}{\partial x_0}$、$\cfrac{\partial f}{\partial x_1}$。当 $x_0=3$,$x_1=4$ 的时候,求关于 $x_0$ 的偏导数$\cfrac{\partial f}{\partial x_0}$: | def function_tmp1(x0):
return x0 * x0 + 4.0**2.0
numerical_diff(function_tmp1, 3.0) | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
当 $x_0=3$,$x_1=4$ 的时候,求关于 $x_1$ 的偏导数$\cfrac{\partial f}{\partial x_1}$: | def function_tmp2(x1):
return 3.0**2.0 + x1 * x1
numerical_diff(function_tmp2, 4.0) | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
实际上动笔计算,这两个计算值和解析解的导数基本一致。所以偏导数和单变量的导数一样,都是求某个地方的**斜率**,不过偏导数需要将多个变量中的某一个变量定为目标变量,然后将其他变量固定为某个值。 梯度铺垫了这么多,终于到了关键的环节。我们刚刚计算了 $x_0$ 和 $x_1$ 的偏导数,现在我们要一起计算 $x_0$ 和 $x_1$ 的偏导数。比如我们考虑求 $x_0=3$,$x_1=4$ 时 $(x_0,x_1)$ 的偏导数 $\left( \cfrac{\partial f}{\partial x_0},\cfrac{\partial f}{\partial x_1} \right)$。>像 $\left( \cfrac{\pa... | def _numerical_gradient_no_batch(f, x):
"""
计算梯度
输入:
f:函数
x:数组,多元变量。
"""
h = 1e-4 # 0.0001
grad = np.zeros_like(x) # 生成一个和x形状一样的全为0的数组
for idx in range(x.size):
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x) # f(x+h)
x[i... | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
这个代码看起来稍微长一点,但是和求单变量的数值微分本质一样。现在我们用这个函数实际计算一下梯度: | _numerical_gradient_no_batch(function_2, np.array([3.0, 4.0]))
_numerical_gradient_no_batch(function_2, np.array([0.0, 2.0]))
_numerical_gradient_no_batch(function_2, np.array([3.0, 0.0])) | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
像这样我们就能计算 $(x_0,x_1)$ 在各个点的梯度了。现在我们要把 $f(x_0,x_1)=x_0^2+x_1^2$ 的梯度画在图上,不过我们画的是**负梯度**的向量。代码参考:[deep-learning-from-scratch](https://github.com/oreilly-japan/deep-learning-from-scratch/blob/master/ch04/gradient_2d.py)。 | def numerical_gradient(f, X):
"""计算梯度矢量"""
if X.ndim == 1:
return _numerical_gradient_no_batch(f, X)
else:
grad = np.zeros_like(X)
for idx, x in enumerate(X):
grad[idx] = _numerical_gradient_no_batch(f, x)
return grad
x0 = np.arange(-2, 2.5, 0.2... | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
如图所示,$f(x_0,x_1)=x_0^2+x_1^2$ 的梯度呈现为有向箭头,而且:- 所有的箭头都指向 $f(x_0,x_1)$ 的“最低处”;- 离“最低处”越远,箭头越大。> 实际上,梯度并非任何时候都指向最低处。>> 更严格讲,**梯度指示的方向是各点处的函数值减小最多的方向**。>> 也就是说,我们有可能在某些优化过程中只收敛到了局部最小值。 梯度法机器学习的主要任务是在训练(学习)过程中寻找最优的参数。这里“最优参数”就是让损失函数取到最小值时的参数。但是损失函数一般都很复杂(回忆一下 `XGBoost` 的损失函数推导),参数空间很庞大,我们一般不知道它在何处能取得最小值。而使用梯度来寻找函数最小值(或者尽可能小... | def gradient_descent(f, init_x, lr=0.01, step_num=100):
"""
梯度下降法
f:要进行最优化的参数
init_x:初始值
lr:学习率,默认为0.01
step_sum:梯度下降法重复的次数
"""
x = init_x
x_history = [] # 保存每一步的信息
for i in range(step_num):
x_history.append( x.copy() )
grad = numerical_gradient(f, x) # 计... | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
使用这个函数就能求得函数的极小值,如果顺利,还能求得最小值。现在我们来求 $f(x_0,x_1)=x_0^2+x_1^2$ 的最小值: | init_x = np.array([-3.0, 4.0]) # 初始位置
resutl = gradient_descent(function_2, init_x=init_x, lr=0.1, step_num=100) # 执行梯度下降算法
print(resutl[0]) | [-6.11110793e-10 8.14814391e-10]
| MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
最终结果是 $(-6.11110793\times10^{-10}, 8.14814391\times10^{-10})$,非常接近我们已知的正确值 $(0, 0)$。所以说通过梯度下降法我们基本得到了正确的结果。如果我们把梯度更新的图片画出,如下: | init_x = np.array([-3.0, 4.0]) # 初始位置
lr = 0.1
step_num = 20
x, x_history = gradient_descent(function_2, init_x, lr=lr, step_num=step_num)
step = 0.01
x_0 = np.arange(-5,5,step)
x_1 = np.arange(-5,5,step)
X, Y = np.meshgrid(x_0, x_1) # 建立网格
Z = function_2_old(X, Y)
plt.contour(X, Y, Z, levels=10, linewidths=0.5, lin... | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
前面说过,**学习率**过大或者过小都无法得到好结果。可以做实验验证一下: | # 学习率过大
init_x = np.array([-3.0, 4.0]) # 初始位置
lr = 10.0 # 学习率
x, x_history = gradient_descent(function_2, init_x=init_x, lr=lr, step_num=step_num)
print(x)
# 学习率过小
init_x = np.array([-3.0, 4.0]) # 初始位置
lr = 1e-10 # 学习率
x, x_history = gradient_descent(function_2, init_x=init_x, lr=lr, step_num=step_num)
print(x) | [-2.99999999 3.99999998]
| MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
由此可见:- 学习率过大,会发散成一个很大的值;- 学习率过小,基本上还没更新就结束了。因此我们需要设置适当的学习率。记住,学习率是一个**超参数**,通常是人工设定的。 神经网络的梯度神经网络的训练也是要求梯度的。这里的梯度指的是**损失函数**关于权重参数的梯度。比如,在[3.01 神经网络与前向传播](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/深度学习基础/3.01%20神经网络与前向传播.ipynb)中,我们搭建了一个三层神经网络。其中第一层(layer1)的权重 $W$ 的形状为 $2\times3$,损失函数用 $L$ 表示。此时梯度用... | import os
import sys
import numpy as np
def softmax(a):
"""定义 softmax 函数"""
exp_a = np.exp(a)
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y
def cross_entropy_error(y, t):
"""定义交叉熵损失函数"""
delta = 1e-7
return -np.sum(t * np.log(y + delta))
def numerical_gradient(f, X):
""... | _____no_output_____ | MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
我们建立了一个名叫 `simpleNet` 的简单神经网络,其中 `softmax` 和 `cross_entropy_error` 都和以前一样。simpleNet 类只有一个实例变量,也就是形状为 $2\times 3$ 的权重参数矩阵。网络中有两个方法,一个是前向传播 `predict`,用于预测;另一个是用于求损失函数的 `loss` 。其中参数 `x` 接受输入数据,`t`接受正确标签。现在我们运行一下看看结果: | net = simpleNet()
print(net.W) # 权重参数
x = np.array([0.6, 0.9])
p = net.predict(x) # 预测
print(p)
np.argmax(p) # 正确解(最大值)的索引
# 正确解的标签,如果是随机初始化,注意每次运行可能都不一样!!!
t = np.array([0, 1, 0])
# 损失
loss1 = net.loss(x, t)
print(loss1) | 0.08276656069658565
| MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
现在我们来求**梯度**。我们使用 `numerical_gradient(f, x)` 求梯度:由于 `numerical_gradient(f, x)` 中的 `f` 是一个函数,所以为了程序兼容,我们先定义函数 `f(W)`: | def f(W):
return net.loss(x, t)
dW = numerical_gradient(f, net.W)
print(dW) | [[ 0.03870828 -0.04766044 0.00895216]
[ 0.05806242 -0.07149067 0.01342824]]
| MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
`numerical_gradient(f, net.W)` 的结果是 $dW$,形状是一个 $2\times 3$ 的矩阵。观察这个矩阵,在$\cfrac{\partial L}{\partial W}$ 中:$\cfrac{\partial L}{\partial W_{11}}$的值约为0.039,这表示如果将$w_{11}$ 增加 $h$,则损失函数的值会增加 $0.039h$。$\cfrac{\partial L}{\partial W_{22}}$的值约为-0.071,这表示如果将$w_{22}$ 增加 $h$,则损失函数的值会减少 $0.071h$。所以,从减少损失函数的目的出发,$w_{22}$ 应该向正方向更新,而... | # 学习率 lr
lr = 1e-4
print(lr)
class simpleNet_step2:
def __init__(self):
"""初始化,手动更新一次参数"""
self.W = np.array([[ 0.68851943 - 0.0001, 2.06916921 + 0.0001, -0.88125086 - 0.0001],
[-1.30951576 - 0.0001, 0.72350587 + 0.0001, -1.88984482 - 0.0001]])
self.q = 1
... | loss2 比 loss1 小了: 2.3826931565829046e-05
| MIT | 03深度学习基础/3.02 神经网络的训练.ipynb | DrDavidS/basic_Machine_Learning |
Heading 1 Heading 2- this- is- a - long, **long**, list$$\alpha, \beta, \gamma$$ | 3
3 * 4 + 5
3 / 5
3 // 5
7 % 5
2 ** 3
2 ^ 3
2 << 4
3.14
True, False
1 == 1
1 != 1
None
'hello'
"hello"
"hello's"
3 + 4j
[1,2,3,4]
[1,'a', 'hello', 3.14, 4j]
print('''This is
a triple
quoted string''')
set([1,1,2,2,3,4,3,4])
{'tom': 23, 'anne': 34}
(1,2,3)
x = [1,2,3,4]
x
x[0]
x[-1]
x[0:2]
x[:2]
x[1:]
x[:]
contacts = {'... | Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaul... | MIT | scratch/Lecture01.ipynb | cliburn/sta-663-2017 |
AEJxLPS (Auroral electrojets SECS)> Abstract: Access to the AEBS products, SECS type. This notebook uses code from the previous notebook to build a routine that is flexible to plot either the LC or SECS products - this demonstrates a prototype quicklook routine. | %load_ext watermark
%watermark -i -v -p viresclient,pandas,xarray,matplotlib
from viresclient import SwarmRequest
import datetime as dt
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
import matplotlib as mpl
request = SwarmRequest() | _____no_output_____ | MIT | notebooks/03h2_Demo-AEBS-AEJxLPS.ipynb | Swarm-DISC/Swarm_notebooks |
AEBS product informationSee previous notebook, "Demo AEBS products (LC)", for an introduction to these products. Function to request data from VirES and reshape it | def fetch_data(start_time=None, end_time=None, spacecraft=None, AEBS_type="L"):
"""DUPLICATED FROM PREVIOUS NOTEBOOK. TO BE REFACTORED"""
# Fetch data from VirES
auxiliaries = ['OrbitNumber', 'QDLat', 'QDOrbitDirection', 'OrbitDirection', 'MLT']
if AEBS_type == "L":
measurement_vars = ["J_NE"]
... | _____no_output_____ | MIT | notebooks/03h2_Demo-AEBS-AEJxLPS.ipynb | Swarm-DISC/Swarm_notebooks |
Plotting function | # Bit numbers which indicate non-nominal state
# Check SW-DS-DTU-GS-003_AEBS_PDD for details
BITS_PBL_FLAGS_EEJ_MINOR = (2, 3, 6)
BITS_PBL_FLAGS_WEJ_MINOR = (4, 5, 6)
BITS_PBL_FLAGS_EEJ_BAD = (0, 7, 8, 11)
BITS_PBL_FLAGS_WEJ_BAD = (1, 9, 10, 12)
def check_PBL_Flags(flags=0b0, EJ_type="WEJ"):
"""Return "good", "poo... | _____no_output_____ | MIT | notebooks/03h2_Demo-AEBS-AEJxLPS.ipynb | Swarm-DISC/Swarm_notebooks |
Fetching and plotting function | def quicklook(day="2015-01-01", hemisphere="North", spacecraft="A", AEBS_type="L", xaxis="Latitude"):
start_time = dt.datetime.fromisoformat(day)
end_time = start_time + dt.timedelta(days=1)
ds, ds_lpq = fetch_data(start_time, end_time, spacecraft, AEBS_type)
fig, axes = plot_stack(ds, ds_lpq, hemispher... | _____no_output_____ | MIT | notebooks/03h2_Demo-AEBS-AEJxLPS.ipynb | Swarm-DISC/Swarm_notebooks |
Consecutive orbits are shown in consecutive rows, centered over the pole. The starting and ending times (UTC and MLT) of the orbital section are shown at the left and right. Westward (WEJ) and Eastward (EEJ) electrojet extents and peak intensities are indicated:- Blue dots: Estimated current density in Eastward directi... | quicklook(day="2016-01-01", hemisphere="North", spacecraft="A", AEBS_type="S", xaxis="Latitude");
quicklook(day="2016-01-01", hemisphere="North", spacecraft="A", AEBS_type="L", xaxis="Latitude"); | _____no_output_____ | MIT | notebooks/03h2_Demo-AEBS-AEJxLPS.ipynb | Swarm-DISC/Swarm_notebooks |
Dataset Anaylsis | %%html
<style>
body {
font-family: "Apple Script", cursive, sans-serif;
}
</style> | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
_importing necessary libraries of Data Science_ | import numpy as np
import pandas as pd
import cv2
from matplotlib import pyplot as plt
import os | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
_making a function for showing image through open cv_ | def imshow(img):
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows() | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
_________ _read one data out of the dataset and viewing the image_ | # reading data using opencv
img = cv2.imread(r"PatientSpiral\sp1-P1.jpg")
grey_img = cv2.imread(r"PatientSpiral\sp1-P1.jpg", cv2.IMREAD_GRAYSCALE)
# viewing data using matplotlib
plt.imshow(img)
# plt.imshow(grey_img) | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
_As we can see from above image, there is two diffrent pattern. one is question and one is answer, and they both overlap each other, we need to decompose them into __question__ and __answer__ to get accurate comparision across the dataset._ | Q_img = np.zeros(np.shape(grey_img))
A_img = np.zeros(np.shape(grey_img)) | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
extracting question Setting bias as 30 for black colour | for i,e in enumerate(grey_img):
for j,f in enumerate(e):
if f > 30:
Q_img[i][j] = 255
else:
Q_img[i][j] = 0 | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
If we consider that the darkness of shade is also a factor in diagnosing the Parkinson's disease, as it may reflect the muscle strength of the Person thendon't use the else statement in above code__Points to consider:__- This may increase the ambiguity as the lightning conditions do not remain constant during image cap... | imshow(Q_img) | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
extracting answer Setting +ve bias as __60__ for _removing black colour_ and -ve bias as __160__ for _removing white noise_ | for i,e in enumerate(grey_img):
for j,f in enumerate(e):
if f < 60 or f > 160:
A_img[i][j] = 255
else:
A_img[i][j] = 0 | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
Again don't use the else statement in the above code if considering darkness of ink as a variable | imshow(A_img)
plt.imshow(img)
plt.imshow(Q_img)
plt.imshow(A_img) | _____no_output_____ | MIT | Parkinsons/Dataset Analysis.ipynb | jayanta-banik/DataScience |
Naive Bayes Implementation with Titanic Dataset | import pandas as pd
df = pd.read_csv("titanic.csv")
df.head()
df.drop(['PassengerId','Name','SibSp','Parch','Ticket','Cabin','Embarked'],axis='columns',inplace=True)
df.head() # Dropping Unnecessary columns
inputs = df.drop('Survived',axis='columns')
target = df[['Survived']]
dummies = pd.get_dummies(inputs.Se... | c:\users\shaon\appdata\local\programs\python\python37\lib\site-packages\sklearn\naive_bayes.py:206: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
y = column_or_1d(y, warn=True)
c:\users\shaon\appdata\local\pr... | MIT | Machine Learning/14. Naive Bayes 1.ipynb | Shaon2221/Learning-and-Experimenting_Data-Science |
Setup Classifier type model | class DeepSITH_Classifier(nn.Module):
def __init__(self, out_features, layer_params, dropout=.5):
super(DeepSITH_Classifier, self).__init__()
last_hidden = layer_params[-1]['hidden_size']
self.hs = DeepSITH(layer_params=layer_params, dropout=dropout)
self.to_out = nn.Linear(last_hidd... | _____no_output_____ | MIT | SITH_Layer-master/notebooks/DeepSITH_timeSeries_testin.ipynb | gauvand/SIF_Capstone |
TEST layers for correct taustars/parameters/cvaluesThese dictionaries will not be used later. | sith_params2 = {"in_features":1,
"tau_min":.1, "tau_max":20.0, 'buff_max':40,
"k":50,
"ntau":5, 'g':0,
"ttype":ttype,
"hidden_size":10, "act_func":nn.ReLU()}
sith_params3 = {"in_features":sith_params2['hidden_size'],
"t... | DeepSITH_Classifier(
(hs): DeepSITH(
(layers): ModuleList(
(0): _DeepSITH_core(
(sith): iSITH(ntau=5, tau_min=0.1, tau_max=20.0, buff_max=40, dt=1, k=50, g=0)
(linear): Sequential(
(0): Linear(in_features=5, out_features=10, bias=True)
(1): ReLU()
)
)
... | MIT | SITH_Layer-master/notebooks/DeepSITH_timeSeries_testin.ipynb | gauvand/SIF_Capstone |
Visualize the taustar buffersThey must all completely empty or there will be edge effects | plt.plot(model.hs.layers[0].sith.filters[:, 0, 0, :].detach().cpu().T); | _____no_output_____ | MIT | SITH_Layer-master/notebooks/DeepSITH_timeSeries_testin.ipynb | gauvand/SIF_Capstone |
Training and testing | # You likely don't need this to be this long, but just in case.
epochs = 500
# Just for visualizing average loss through time.
loss_buffer_size = 100
loss_func = torch.nn.CrossEntropyLoss()
sith_params2 = {"in_features":1,
"tau_min":.1, "tau_max":20.0, 'buff_max':40,
"k":50,
... | _____no_output_____ | MIT | SITH_Layer-master/notebooks/DeepSITH_timeSeries_testin.ipynb | gauvand/SIF_Capstone |
[tokenizer in Keras](https://keras.io/preprocessing/text/) | from keras.preprocessing.text import Tokenizer
tk = Tokenizer(num_words=None, char_level=True, oov_token='_UNK')
tk.fit_on_texts(texts)
vocab_token = tk.word_index
print(vocab_token)
vocab_token_list = list(vocab_token)
len(vocab_token_list)
vocab_token_list.append('_PAD')
len(vocab_token_list)
idx = []
idx_ = -1
fo... | _____no_output_____ | MIT | Tokenize.ipynb | josephkd81/SentimentAnalysis |
ICA 2 channelnaive apporche that 8 recordings of only machine and backgroudn noise and picking of main source by analysing the estiamtion of demixing matrix | BASE_FOLDER = '../../'
%run -i ..\..\utility\feature_extractor\JupyterLoad_feature_extractor.py
file_path = r'\dataset\6dB\pump\id_02\abnormal\00000004.wav'
# load
ica2 = feature_extractor_ICA2(BASE_FOLDER)
ica2.create_from_wav(file_path)
# get flat feature mix matrix
ica2.get_feature({'function': 'flat'}).shape
# get ... | \dataset\6dB\slider\id_04\abnormal\00000004.wav
2.8879229332571557
\dataset\6dB\slider\id_04\normal\00000004.wav
2.819371177558146
| MIT | feature_extraction_diagrams/A20_BSS_BlindSourceSeperation/ICA_2_out_channel.ipynb | BA-HanseML/NF_Prj_MIMII_Dataset |
NDVI STDDeviations from an established average z-score. Notebook Summary* A baseline for each month is determined by measuring NDVI over a set time* The data cube is used to visualize at NDVI anomalies over time.* Anomalous times are further explored and visualization solutions are proposed. Index * [Import De... | import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.ticker import FuncFormatter
import seaborn as sns
from utils.data_cube_utilities.dc_load import get_product_extents
from ut... | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Choose Platform and Product [&9652;](ndvi_std_top) | # Change the data platform and data cube here
product = 'ls7_usgs_sr_scene'
platform = 'LANDSAT_7'
collection = 'c1'
level = 'l2'
# product = 'ls8_usgs_sr_scene'
# platform = 'LANDSAT_8'
# collection = 'c1'
# level = 'l2' | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Get the Extents of the Cube [&9652;](ndvi_std_top) | full_lat, full_lon, min_max_dates = get_product_extents(api, platform, product)
print("{}:".format(platform))
print("Lat bounds:", full_lat)
print("Lon bounds:", full_lon)
print("Time bounds:", min_max_dates) | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Define the Extents of the Analysis [&9652;](ndvi_std_top) | display_map(full_lat, full_lon)
params = {'latitude': (0.55, 0.6),
'longitude': (35.55, 35.5),
'time': ('2008-01-01', '2010-12-31')}
display_map(params["latitude"], params["longitude"]) | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Load Data from the Data Cube [&9652;](ndvi_std_top) | dataset = dc.load(**params,
platform = platform,
product = product,
measurements = ['red', 'green', 'blue', 'swir1', 'swir2', 'nir', 'pixel_qa'],
dask_chunks={'time':1, 'latitude':1000, 'longitude':1000}).persist() | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Create and Use a Clean Mask [&9652;](ndvi_std_top) | # Make a clean mask to remove clouds and scanlines.
clean_mask = landsat_clean_mask_full(dc, dataset, product=product, platform=platform,
collection=collection, level=level)
# Filter the scenes with that clean mask
dataset = dataset.where(clean_mask) | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Calculate the NDVI [&9652;](ndvi_std_top) | #Calculate NDVI
ndvi = (dataset.nir - dataset.red)/(dataset.nir + dataset.red) | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Convert the Xarray to a Dataframe [&9652;](ndvi_std_top) | #Cast to pandas dataframe
df = ndvi.to_dataframe("NDVI")
#flatten the dimensions since it is a compound hierarchical dataframe
df = df.stack().reset_index()
#Drop the junk column that was generated for NDVI
df = df.drop(["level_3"], axis=1)
#Preview first 5 rows to make sure everything looks as it should
df.head()
#... | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Define a Function to Visualize Values Over the Region [&9652;](ndvi_std_top) | #Create a function for formatting our axes
def format_axis(axis, digits = None, suffix = ""):
#Get Labels
labels = axis.get_majorticklabels()
#Exit if empty
if len(labels) == 0: return
#Create formatting function
format_func = lambda x, pos: "{0}{1}".format(labels[pos]._text[:digi... | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Lets examine the average NDVI across all months and years to get a look at the region | #It defaults to binning the entire range of months and years so we can just leave those parameters out
examine(value_name="ndvi") | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
This gives us an idea of the healthier areas of the region before we start looking at specific months and years. Visualize the Baseline Average NDVI by Month [&9652;](ndvi_std_top) | #Make labels for convenience
labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
#Initialize an empty pandas Series
df["z_score"] = pd.Series()
#declare list for population
binned_data = list()
#Calculate monthly binned z-scores from the composited monthly NDVI mean and stor... | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Visualize the Baseline Distributions Binned by Month [&9652;](ndvi_std_top) | #Set figure size to a larger size
plt.rcParams["figure.figsize"] = [16,9]
#Create the boxplot
df.boxplot(by="Month",column="ndvi")
#Create the mean line
plt.plot(binned_data.index+1, binned_data.Mean, 'r-')
#Create the one standard deviation away lines
plt.plot(binned_data.index+1, binned_data.Mean-binned_data.Std_D... | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
The plot above shows the distributions for each individual month over the baseline period.- The red line is the mean line which connects the mean values for each month. - The dotted blue lines are exactly one standard deviation away from the mean and show where the NDVI values fall within 68% of the time, accordin... | sns.violinplot(x=df.Month, y="ndvi", data=df) | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Plot Z-Scores by Month and Year [&9652;](ndvi_std_top) Pixel Plot Visualization | #Create heatmap layout from dataframe
img = pd.pivot_table(df, values="z_score",index=["Month"], columns=["Year"], fill_value=None)
#pass the layout to seaborn heatmap
ax = sns.heatmap(img, cmap="RdYlGn", annot=True, fmt="f", center = 0)
#set the title for Aesthetics
ax.set_title('Z-Score\n Regional Selection Average... | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Each block in the visualization above is representative of the deviation from the average for the region selected in a specific month and year. The omitted blocks are times when there was no satellite imagery available. Their values must either be inferred, ignored, or interpolated.You may notice long vertical strips... | #Lets look at that drought in 2009 during the months of Aug-Oct
#This will generate a composite of the z-scores for the months and years selected
examine(month = [8], year = 2009, value_name="z_score") | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
Note:This graphical representation of the region shows the amount of deviation from the mean for each pixel that was binned by month. Grid Layout of Selected Times | #Restrict input to a maximum of about 12 grids (months*year) for memory
def grid_examine(month = None, year = None, value_name = "z_score"):
#default to all months then cast to list, if not already
if month is None: month = list(df["Month"].unique())
elif type(month) is int: month = [month]
#defau... | _____no_output_____ | Apache-2.0 | notebooks/vegetation/NDVI_STD.ipynb | admariner/data_cube_notebooks |
圖中顯示2016到2017入境各個國家人數多數國家在2017人數皆些微成長 | fig = plt.figure(figsize=(15, 7))
ax1 = fig.add_subplot(111)
for (i, row) in country_data.iterrows():
plt.bar([i - 0.2, i + 0.2], [row['2016'], row['2017']],
color=['#CC6699', '#008AB8'], width=0.4, align='center', edgecolor='none')
plt.xlim(-1, 13)
plt.xticks(range(0, 13), country_data['country']... | _____no_output_____ | MIT | TestCountry0115.ipynb | ChangRitaaaa/Test |
DIFFERENCE各個國家在 2016到2017年間出入境的人數比較大部分國家為正成長,少數為負成長。 | fig = plt.figure(figsize=(15, 7))
ax1 = fig.add_subplot(111)
for (i, row) in country_data.iterrows():
plt.bar([i], [row['difference']],
color=['#CC6699'], width=0.6, align='center', edgecolor='none')
plt.xlim(-1, 13)
plt.xticks(range(0, 13), country_data['country'], fonts... | _____no_output_____ | MIT | TestCountry0115.ipynb | ChangRitaaaa/Test |
RELATION x軸為2017入境各個國家的人數Y軸為2017該國家GDP總額當出入境人數增加時,該國當年GDP也隨之上升。推測在各國家觀光產業所佔生產毛額都有相當大的比例。可看出兩者有正相關關係。 | plt.plot(m,n, 'bo')
x = country_data['growth']
x
y = country_data['GDPgrowth']
y | _____no_output_____ | MIT | TestCountry0115.ipynb | ChangRitaaaa/Test |
影響GDP成長因素有許多不同於原因拿日本和香港做比較從圖表中可見入境日本的人口數再2016到2017年間是成長的卻在這兩年間GDP些微下降相反的在兩年間入境香港的人數下降,GDP卻上升可得知雖然觀光經濟在國家GDP中佔有滿大的比重,但在某些國家中並非最為重要的部分。 | plt.plot(x,y, 'bo') | _____no_output_____ | MIT | TestCountry0115.ipynb | ChangRitaaaa/Test |
Generative Adversarial NetworkIn this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten digits!GANs were [first reported on](https://arxiv.org/abs/1406.2661) in 2014 from Ian Goodfellow and others in Yoshua Bengio's lab... | %matplotlib inline
%config Completer.use_jedi = True
import numpy as np
import torch
import matplotlib.pyplot as plt
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
from torchvision import datasets
import torchvision.transforms as transforms
# number of subprocesses to use for data loading
num_work... | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
Visualize the data | # obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy()
# get one image from the batch
img = np.squeeze(images[0])
fig = plt.figure(figsize = (3,3))
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray') | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
--- Define the ModelA GAN is comprised of two adversarial networks, a discriminator and a generator. DiscriminatorThe discriminator network is going to be a pretty typical linear classifier. To make this network a universal function approximator, we'll need at least one hidden layer, and these hidden layers should hav... | import torch.nn as nn
import torch.nn.functional as F
class Discriminator(nn.Module):
def __init__(self, input_size, hidden_dim, output_size):
super(Discriminator, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_dim*4)
self.fc2 = nn.Linear(hidden_dim*4, hidden_di... | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
GeneratorThe generator network will be almost exactly the same as the discriminator network, except that we're applying a [tanh activation function](https://pytorch.org/docs/stable/nn.htmltanh) to our output layer. tanh OutputThe generator has been found to perform the best with $tanh$ for the generator output, which ... | class Generator(nn.Module):
def __init__(self, input_size, hidden_dim, output_size):
super(Generator, self).__init__()
# define all layers
self.fc1 = nn.Linear(input_size, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim*2)
self.fc3 = nn.Linear(hidden... | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
Model hyperparameters | # Discriminator hyperparams
# Size of input image to discriminator (28*28)
input_size = 28*28
# Size of discriminator output (real or fake)
d_output_size = 1
# Size of *last* hidden layer in the discriminator
d_hidden_size = 32
# Generator hyperparams
# Size of latent vector to give to generator
z_size =... | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
Build complete networkNow we're instantiating the discriminator and generator from the classes defined above. Make sure you've passed in the correct input arguments. | # instantiate discriminator and generator
D = Discriminator(input_size, d_hidden_size, d_output_size)
G = Generator(z_size, g_hidden_size, g_output_size)
# check that they are as you expect
print(D)
print()
print(G) | Discriminator(
(fc1): Linear(in_features=784, out_features=128, bias=True)
(fc2): Linear(in_features=128, out_features=64, bias=True)
(fc3): Linear(in_features=64, out_features=32, bias=True)
(fc4): Linear(in_features=32, out_features=1, bias=True)
(dropout): Dropout(p=0.3, inplace=False)
)
Generator(
(fc1... | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
--- Discriminator and Generator LossesNow we need to calculate the losses. Discriminator Losses> * For the discriminator, the total loss is the sum of the losses for real and fake images, `d_loss = d_real_loss + d_fake_loss`. * Remember that we want the discriminator to output 1 for real images and 0 for fake images, ... | # Calculate losses
def real_loss(D_out, smooth=False):
# compare logits to real labels
# smooth labels if smooth=True
labels = torch.ones(D_out.size(0))*0.9 if smooth else torch.ones(D_out.size(0))
criterion = nn.BCEWithLogitsLoss()
loss = criterion(D_out.squeeze(), labels)
return... | _____no_output_____ | MIT | gan-mnist/MNIST_GAN_Exercise.ipynb | NGrech/deep-learning-v2-pytorch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.