hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
sequence | cell_types
sequence | cell_type_groups
sequence |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e7aa7d58bf3fa2e4dd7e080857bf417cb119aab2 | 247,565 | ipynb | Jupyter Notebook | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais | e6a44d6322f95be3ac288c6f1bc4f7cfeb481ac0 | [
"CC0-1.0"
] | 8 | 2020-10-01T20:59:33.000Z | 2021-07-27T22:46:58.000Z | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais | e6a44d6322f95be3ac288c6f1bc4f7cfeb481ac0 | [
"CC0-1.0"
] | null | null | null | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais | e6a44d6322f95be3ac288c6f1bc4f7cfeb481ac0 | [
"CC0-1.0"
] | 9 | 2020-10-15T12:08:22.000Z | 2021-04-12T12:26:53.000Z | 730.280236 | 117,752 | 0.948927 | [
[
[
"# Aliasing e o teorema da amostragem\n\nNeste notebook exploramos questões a respeito da taxa de amostragem.",
"_____no_output_____"
]
],
[
[
"# importar as bibliotecas necessárias\nimport numpy as np # arrays\nimport matplotlib.pyplot as plt # plots\nplt.rcParams.update({'font.size': 14})",
"_____no_output_____"
]
],
[
[
"# Exemplo 1 \n\nVamos criar um seno, entre 0 [s] e 1[s], com frequência 10 [Hz]. Vamos variar a taxa de amostragem e averiguar o que ocorre.",
"_____no_output_____"
]
],
[
[
"Fs = 15.7\ntime = np.arange(0, 1, 1/Fs)\nxt = np.sin(2*np.pi*10*time)\nN = len(xt) # Num. de amostras no sinal",
"_____no_output_____"
]
],
[
[
"## 1 período do espectro\n\nVamos calcular o espectro com a FFT e plotar 1 período de espectro. \n\nNote que o vetor de frequências vai de 0 até bem perto de $F_s$.\n\nA princípio, o espectro tem o mesmo número de amostras do sinal.",
"_____no_output_____"
]
],
[
[
"Xw = np.fft.fft(xt) # A princípio, o espectro tem o mesmo número de amostras do sinal\nfreq = np.linspace(0, (N-1)*Fs/Fs, N) # 1 período do vetor de frequências vai de 0 até bem perto de Fs.\nprint(\"xt possui {} amostras e Xw possui {} componentes de frequência\".format(N, len(Xw)))\n\nplt.figure()\nplt.plot(freq, np.abs(Xw)/N, 'b', linewidth = 2)\nplt.axvline(Fs/2, color='k',linestyle = '--', linewidth = 4, alpha = 0.8)\nplt.xlabel('Frequência [Hz]')\nplt.ylabel('Magnitude [-]')\nplt.grid(which='both', axis='both')\nplt.xlim((0,Fs))\nplt.ylim((0,0.6));",
"xt possui 16 amostras e Xw possui 16 componentes de frequência\n"
]
],
[
[
"## Vários período do espectro",
"_____no_output_____"
]
],
[
[
"# novo vetor de frequências - 3 períodos\nplt.figure()\nplt.plot(freq-Fs, np.abs(Xw)/N, '--b', linewidth = 2)\nplt.plot(freq, np.abs(Xw)/N, 'b', linewidth = 2)\nplt.plot(freq+Fs, np.abs(Xw)/N, '--b', linewidth = 2)\nplt.axvline(Fs/2, color='k',linestyle = '--', linewidth = 4, alpha = 0.8)\nplt.xlabel('Frequência [Hz]')\nplt.ylabel('Magnitude [-]')\nplt.grid(which='both', axis='both')\nplt.xlim((-Fs,2*Fs))\nplt.ylim((0,0.6));",
"_____no_output_____"
],
[
"Fs_2 = 1000\ntime2 = np.arange(0, 1, 1/Fs_2)\nxt_2 = np.sin(2*np.pi*10*time2)\n\nplt.figure()\nplt.plot(time2, xt_2, 'r', linewidth = 2)\n#plt.plot(time, xt, '--b', linewidth = 2)\nplt.stem(time, xt, '-b', label = r\"$F_s = {}$ [Hz]\".format(Fs), basefmt=\" \", use_line_collection= True)\nplt.legend(loc = 'upper right')\nplt.xlabel('Tempo [s]')\nplt.ylabel('Amplitude [-]')\nplt.grid(which='both', axis='both')\nplt.xlim((0,1))\nplt.ylim((-1.6,1.6));",
"_____no_output_____"
]
],
[
[
"# Exemplo 2 - Vamos ouvir um seno com várias taxas de amostragem",
"_____no_output_____"
]
],
[
[
"import IPython.display as ipd\nfrom scipy import signal\n\n# Gerar sinal com uma taxa de amostragem\nfs = 1800\nt = np.arange(0, 1, 1/fs) # vetor temporal\nfreq = 1000\nw = 2*np.pi*freq\nxt = np.sin(w*t)\n\n# Reamostrar o sinal para a placa de som conseguir tocá-lo\nfs_audio = 44100\nxt_play = signal.resample(xt, fs_audio)\nipd.Audio(xt_play, rate=fs_audio) # load a NumPy array",
"_____no_output_____"
],
[
"xt_play.shape",
"_____no_output_____"
]
],
[
[
"# Exemplo 3. Um sinal com 3 senos",
"_____no_output_____"
]
],
[
[
"Fs=100\nT=2.0;\nt=np.arange(0,T,1/Fs)\n\n# 3 sinais com diferentes frequências\nf1=10\nf2=40\nf3=80 #80 e 120\n\nx1=np.sin(2*np.pi*f1*t) \nx2=np.sin(2*np.pi*f2*t)\nx3=0.2*np.sin(2*np.pi*f3*t)\n\n# FFT\nN=len(t)\nX1=np.fft.fft(x1)\nX2=np.fft.fft(x2)\nX3=np.fft.fft(x3)\nfreq = np.linspace(0, (N-1)*Fs/N, N)\n\n\nplt.figure(figsize=(8,20))\nplt.subplot(3,1,1)\nplt.plot(freq, np.abs(X1)/N, 'b', linewidth = 2, label = r\"$f = {:.1f}$ [Hz]\".format(f1))\nplt.axvline(Fs/2, color='k',linestyle = '--', linewidth = 4, alpha = 0.4)\nplt.legend(loc = 'upper right')\nplt.ylim((0, 0.6))\nplt.xlabel('Frequency [Hz]')\nplt.ylabel('Magnitude [-]')\nplt.grid(which='both', axis='both')\n\nplt.subplot(3,1,2)\nplt.plot(freq, np.abs(X2)/N, 'b', linewidth = 2, label = r\"$f = {:.1f}$ [Hz]\".format(f2))\nplt.axvline(Fs/2, color='k',linestyle = '--', linewidth = 4, alpha = 0.4)\nplt.legend(loc = 'upper right')\nplt.ylim((0, 0.6))\nplt.xlabel('Frequency [Hz]')\nplt.ylabel('Magnitude [dB]')\nplt.grid(which='both', axis='both')\n\nplt.subplot(3,1,3)\nplt.plot(freq, np.abs(X3)/N, 'b', linewidth = 2, label = r\"$f = {:.1f}$ [Hz]\".format(f3))\nplt.axvline(Fs/2, color='k',linestyle = '--', linewidth = 4, alpha = 0.4)\nplt.legend(loc = 'upper right')\nplt.ylim((0, 0.6))\nplt.xlabel('Frequency [Hz]')\nplt.ylabel('Magnitude [dB]')\nplt.grid(which='both', axis='both')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7aab0e54ec0faf8fd3c81cf03cacb93315c8bca | 58,011 | ipynb | Jupyter Notebook | visualize_attention_archive.ipynb | jacklxc/ScientificDiscourseTagging | d75514b631b95d39451abd2396f57c3da1c19801 | [
"Apache-2.0"
] | 15 | 2020-01-17T16:45:09.000Z | 2022-01-18T08:44:16.000Z | visualize_attention_archive.ipynb | jacklxc/ScientificDiscourseTagging | d75514b631b95d39451abd2396f57c3da1c19801 | [
"Apache-2.0"
] | 3 | 2020-12-01T07:34:57.000Z | 2021-08-09T23:07:19.000Z | visualize_attention_archive.ipynb | jacklxc/ScientificDiscourseTagging | d75514b631b95d39451abd2396f57c3da1c19801 | [
"Apache-2.0"
] | 2 | 2019-05-30T18:52:09.000Z | 2020-06-01T13:36:33.000Z | 59.559548 | 18,528 | 0.762235 | [
[
[
"import os\nimport warnings\nimport sys\nimport codecs\nimport numpy as np\nimport argparse\nimport json\nimport pickle\n\nfrom util import read_passages, evaluate, make_folds, clean_words, test_f1, to_BIO, from_BIO, from_BIO_ind, arg2param\n\nimport tensorflow as tf\nconfig = tf.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 1.0\nconfig.gpu_options.allow_growth = True # dynamically grow the memory used on the GPU\nsess = tf.Session(config=config)\nimport keras.backend as K\nK.set_session(sess)\nfrom keras.activations import softmax\nfrom keras.regularizers import l2\nfrom keras.models import Model, model_from_json\nfrom keras.layers import Input, LSTM, Dense, Dropout, TimeDistributed, Bidirectional\nfrom keras.callbacks import EarlyStopping,LearningRateScheduler, ModelCheckpoint\nfrom keras.optimizers import Adam, RMSprop, SGD\nfrom crf import CRF\nfrom attention import TensorAttention\nfrom custom_layers import HigherOrderTimeDistributedDense\nfrom generator import BertDiscourseGenerator\nfrom keras_bert import load_trained_model_from_checkpoint, Tokenizer\n\nfrom discourse_tagger_generator_bert import PassageTagger\n\nimport matplotlib.pyplot as plt\nfrom scipy.special import softmax\nfrom matplotlib import transforms",
"Using TensorFlow backend.\n"
],
[
"use_attention = True\natt_context = \"LSTM_clause\"\nbidirectional = bid = True\ncrf = True\nlstm = False\nmaxseqlen = 40\nmaxclauselen = 60\ninput_size = 768\nembedding_dropout=0.4 \nhigh_dense_dropout=0.4\nattention_dropout=0.6\nlstm_dropout=0.5\nword_proj_dim=300 \nhard_k=0 \nlstm_dim = 350 \nrec_hid_dim = 75 \natt_proj_dim = 200 \nbatch_size = 10\nreg=0\n",
"_____no_output_____"
],
[
"prefix=\"scidt_scibert/\"\nmodel_ext = \"att=%s_cont=%s_lstm=%s_bi=%s_crf=%s\"%(str(use_attention), att_context, str(lstm), str(bid), str(crf))\nmodel_config_file = open(prefix+\"model_%s_config.json\"%model_ext, \"r\")\nmodel_weights_file_name = prefix+\"model_%s_weights\"%model_ext\nmodel_label_ind = prefix+\"model_%s_label_ind.json\"%model_ext\nlabel_ind_json = json.load(open(model_label_ind))\nlabel_ind = {k: int(label_ind_json[k]) for k in label_ind_json}\nnum_classes = len(label_ind)",
"_____no_output_____"
],
[
"if use_attention:\n inputs = Input(shape=(maxseqlen, maxclauselen, input_size))\n x = Dropout(embedding_dropout)(inputs)\n x = HigherOrderTimeDistributedDense(input_dim=input_size, output_dim=word_proj_dim, reg=reg)(x)\n att_input_shape = (maxseqlen, maxclauselen, word_proj_dim)\n x = Dropout(high_dense_dropout)(x)\n x, raw_attention = TensorAttention(att_input_shape, context=att_context, hard_k=hard_k, proj_dim = att_proj_dim, rec_hid_dim = rec_hid_dim, return_attention=True)(x)\n x = Dropout(attention_dropout)(x)\nelse:\n inputs = Input(shape=(maxseqlen, input_size))\n x = Dropout(embedding_dropout)(inputs)\n x = TimeDistributed(Dense(input_dim=input_size, units=word_proj_dim))\n\nif bidirectional:\n x = Bidirectional(LSTM(input_shape=(maxseqlen,word_proj_dim), units=lstm_dim, \n return_sequences=True,kernel_regularizer=l2(reg),\n recurrent_regularizer=l2(reg), \n bias_regularizer=l2(reg)))(x)\n x = Dropout(lstm_dropout)(x) \nelif lstm:\n x = LSTM(input_shape=(maxseqlen,word_proj_dim), units=lstm_dim, return_sequences=True,\n kernel_regularizer=l2(reg),\n recurrent_regularizer=l2(reg), \n bias_regularizer=l2(reg))(x)\n x = Dropout(lstm_dropout)(x) \n\nif crf:\n Crf = CRF(num_classes,learn_mode=\"join\")\n discourse_prediction = Crf(x)\n tagger = Model(inputs=inputs, outputs=[discourse_prediction]) \nelse:\n discourse_prediction = TimeDistributed(Dense(num_classes, activation='softmax'),name='discourse')(x)\n tagger = Model(inputs=inputs, outputs=[discourse_prediction])",
"_____no_output_____"
],
[
"tagger.load_weights(model_weights_file_name)\n",
"_____no_output_____"
],
[
"if crf:\n tagger.compile(optimizer=Adam(), loss=Crf.loss_function, metrics=[Crf.accuracy])\nelse:\n tagger.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])",
"_____no_output_____"
],
[
"inp = tagger.input\nattention_output = tagger.layers[4].output[1]",
"_____no_output_____"
],
[
"functor = K.function([inp, K.learning_phase()], [attention_output])",
"_____no_output_____"
],
[
"test_file = \"lucky_test.txt\"",
"_____no_output_____"
],
[
"params = {\n \"repfile\":\"/nas/home/xiangcil/scibert_scivocab_uncased\",\n \"use_attention\": True,\n \"batch_size\": 10,\n \"maxseqlen\": 40,\n \"maxclauselen\": 60\n }",
"_____no_output_____"
],
[
"pretrained_path = params[\"repfile\"]\nconfig_path = os.path.join(pretrained_path, 'bert_config.json')\ncheckpoint_path = os.path.join(pretrained_path, 'bert_model.ckpt')\nvocab_path = os.path.join(pretrained_path, 'vocab.txt')\n\nbert = load_trained_model_from_checkpoint(config_path, checkpoint_path)\nbert._make_predict_function() # Crucial step, otherwise TF will give error.\n\ntoken_dict = {}\nwith codecs.open(vocab_path, 'r', 'utf8') as reader:\n for line in reader:\n token = line.strip()\n token_dict[token] = len(token_dict)\ntokenizer = Tokenizer(token_dict) ",
"_____no_output_____"
],
[
"str_seqs, label_seqs = read_passages(test_file, is_labeled=True)\nstr_seqs = clean_words(str_seqs)\nlabel_seqs = to_BIO(label_seqs)",
"_____no_output_____"
],
[
"bert_generator = BertDiscourseGenerator(bert, tokenizer, str_seqs, label_seqs, label_ind, 10, True, 40, 60, True, input_size=768)",
"_____no_output_____"
],
[
"test_X, test_Y = bert_generator.make_data(str_seqs, label_seqs)",
"_____no_output_____"
],
[
"attention_raw_scores = functor([test_X])[0]",
"_____no_output_____"
],
[
"attention_scores = softmax(attention_raw_scores,axis=-1)",
"_____no_output_____"
],
[
"reverse_token_dict = {v:k for k,v in token_dict.items()}",
"_____no_output_____"
],
[
"str_seqs_tokenized = []\nfor str_seq in str_seqs:\n str_seq_tokenized = []\n for clause in str_seq:\n clause_tokenized = []\n indices, segments = tokenizer.encode(clause.lower(), max_len=512)\n for i in range(60):\n clause_tokenized.append(reverse_token_dict[indices[i]])\n str_seq_tokenized.append(clause_tokenized)\n str_seqs_tokenized.append(str_seq_tokenized)",
"_____no_output_____"
],
[
"plt.figure()\nplt.imshow(attention_raw_scores[0,:,:],cmap='gray',aspect=\"equal\",interpolation='none')\nplt.ylabel(\"discourse ID\")\nplt.xlabel(\"word ID\")\nplt.colorbar()\nplt.show()",
"_____no_output_____"
],
[
"goal_string = str_seqs_tokenized[5][-5][1:10]\ngoal_weight = attention_raw_scores[5,-5,1:10]",
"_____no_output_____"
],
[
"# goal\nfor token, weight in zip(str_seqs_tokenized[5][-5], attention_scores[5,-5,:]):\n print(token, weight)",
"[CLS] 0.013400033\nto 0.31812173\nfurther 0.1630611\ntest 0.054072104\nthe 0.00474126\nfunction 0.0029656326\nof 0.00039091977\nrag 0.00032799493\nin 0.0008577317\nautophagy 0.0020636402\n[SEP] 0.0064929314\n[PAD] 0.004492862\n[PAD] 0.010073828\n[PAD] 0.009908647\n[PAD] 0.0010647355\n[PAD] 0.00067480846\n[PAD] 0.0011975939\n[PAD] 0.0011656365\n[PAD] 0.0030189175\n[PAD] 0.03283101\n[PAD] 0.0044681006\n[PAD] 0.004780543\n[PAD] 0.0006753908\n[PAD] 0.0004371016\n[PAD] 0.0011385672\n[PAD] 0.00093250297\n[PAD] 0.0022924033\n[PAD] 0.00216708\n[PAD] 0.0033607858\n[PAD] 0.00054277485\n[PAD] 0.0005099491\n[PAD] 0.0009743285\n[PAD] 0.0018046363\n[PAD] 0.009933185\n[PAD] 0.018062154\n[PAD] 0.02046034\n[PAD] 0.0035980484\n[PAD] 0.0065378146\n[PAD] 0.035535365\n[PAD] 0.058377814\n[PAD] 0.1129405\n[PAD] 0.005661178\n[PAD] 0.005394397\n[PAD] 0.0008643695\n[PAD] 0.00039725823\n[PAD] 0.0007317628\n[PAD] 0.00077280524\n[PAD] 0.0019024039\n[PAD] 0.0019956538\n[PAD] 0.0020316269\n[PAD] 0.00081582635\n[PAD] 0.0011760269\n[PAD] 0.0015746099\n[PAD] 0.010288909\n[PAD] 0.020508904\n[PAD] 0.019656837\n[PAD] 0.0015959104\n[PAD] 0.0008376794\n[PAD] 0.0015487925\n[PAD] 0.0017928369\n"
],
[
"method_string = str_seqs_tokenized[5][-4][1:12]\nmethod_weight = attention_raw_scores[5,-4,1:12]",
"_____no_output_____"
],
[
"# method\nfor token, weight in zip(str_seqs_tokenized[5][-4], attention_scores[5,-4,:]):\n print(token, weight)",
"[CLS] 0.03230634\nwe 0.06575207\nexamined 0.062973045\nthe 0.004083869\nlc 0.0010154053\n##3 0.0011969145\nmodification 0.0038189052\nin 0.014905101\nhek 0.0010344912\n##293 0.0021147772\ncells 0.008637033\n. 0.0021345052\n[SEP] 0.020099903\n[PAD] 0.0073203994\n[PAD] 0.0546677\n[PAD] 0.016637152\n[PAD] 0.038170848\n[PAD] 0.008206516\n[PAD] 0.0064173504\n[PAD] 0.0031112304\n[PAD] 0.0032729267\n[PAD] 0.0049326182\n[PAD] 0.010613975\n[PAD] 0.019414006\n[PAD] 0.007973953\n[PAD] 0.0031304061\n[PAD] 0.002765525\n[PAD] 0.002671625\n[PAD] 0.00341922\n[PAD] 0.011053072\n[PAD] 0.011468555\n[PAD] 0.010722521\n[PAD] 0.015724737\n[PAD] 0.004101904\n[PAD] 0.0035599133\n[PAD] 0.020902833\n[PAD] 0.04571804\n[PAD] 0.03834991\n[PAD] 0.0656269\n[PAD] 0.090605825\n[PAD] 0.011266035\n[PAD] 0.0014124743\n[PAD] 0.0023323148\n[PAD] 0.008826168\n[PAD] 0.01990922\n[PAD] 0.006161961\n[PAD] 0.002504559\n[PAD] 0.0025769095\n[PAD] 0.0020608632\n[PAD] 0.020684073\n[PAD] 0.025546812\n[PAD] 0.015133109\n[PAD] 0.0144009255\n[PAD] 0.0041189087\n[PAD] 0.0035342737\n[PAD] 0.034169603\n[PAD] 0.04891791\n[PAD] 0.01730519\n[PAD] 0.023334283\n[PAD] 0.0051723104\n"
],
[
"results_string = str_seqs_tokenized[5][-3][1:14]\nresults_weight = attention_raw_scores[5,-3,1:14]",
"_____no_output_____"
],
[
"results_string = str_seqs_tokenized[34][-6][1:21]\nresults_weight = attention_raw_scores[34,-6,1:21]",
"_____no_output_____"
],
[
"results_weight",
"_____no_output_____"
],
[
"# results\nfor token, weight in zip(str_seqs_tokenized[5][-3], attention_scores[5,-3,:]):\n print(token, weight)",
"[CLS] 0.08107085\nexpression 0.031627353\nof 0.0022570565\nrag 0.0007122207\n##a 0.0008012945\nql 0.0006839431\nand 0.0004099651\nrag 0.00017568597\n##c 0.0003729928\nsn 0.0197685\ninhibited 0.11715596\nlc 0.005213611\n##3 0.0074597425\nconversion 0.009275003\nin 0.009368172\nresponse 0.01728051\nto 0.011764066\namino 0.0013677689\nacid 0.0029441456\nstarvation 0.008441797\n( 0.05665356\nfig 0.07855153\n. 0.007413407\n7 0.002268498\n##e 0.0044586915\n) 0.014881012\n. 0.0032192192\n[SEP] 0.051463254\n[PAD] 0.010603226\n[PAD] 0.016779572\n[PAD] 0.023665426\n[PAD] 0.039294302\n[PAD] 0.012387581\n[PAD] 0.0038096986\n[PAD] 0.0073135644\n[PAD] 0.0047938623\n[PAD] 0.043167155\n[PAD] 0.049979344\n[PAD] 0.01702229\n[PAD] 0.014287903\n[PAD] 0.0039117914\n[PAD] 0.005558258\n[PAD] 0.001734003\n[PAD] 0.0033897734\n[PAD] 0.0016695977\n[PAD] 0.001070946\n[PAD] 0.0048521985\n[PAD] 0.003954503\n[PAD] 0.0045268675\n[PAD] 0.01641379\n[PAD] 0.022082303\n[PAD] 0.011145219\n[PAD] 0.017425463\n[PAD] 0.0045502423\n[PAD] 0.0034704509\n[PAD] 0.003649546\n[PAD] 0.031080898\n[PAD] 0.0456415\n[PAD] 0.01645221\n[PAD] 0.0072564385\n"
],
[
"implication_string = str_seqs_tokenized[34][-6][1:21]\nimplication_weight = attention_raw_scores[34,-6,1:21]",
"_____no_output_____"
],
[
"for token, weight in zip(str_seqs_tokenized[50][-2], attention_scores[50,-2,:]):\n print(token, weight)",
"[CLS] 0.028863741\n@ 0.06808214\nhrs 0.042228457\nlater 0.09427474\n, 0.018657615\n@ 0.010902164\nmum 0.016785294\nof 0.008311942\nsirna 0.01414978\n( 0.018814009\nfinal 0.0064142547\nconcentration 0.0076804277\n) 0.0010799159\nwere 0.016262738\ntransfected 0.015904922\n[SEP] 0.008160337\n[PAD] 0.0038477986\n[PAD] 0.018740721\n[PAD] 0.023950279\n[PAD] 0.008665704\n[PAD] 0.005277837\n[PAD] 0.006872843\n[PAD] 0.0031449744\n[PAD] 0.0048338487\n[PAD] 0.0072443173\n[PAD] 0.016827984\n[PAD] 0.004964975\n[PAD] 0.009403878\n[PAD] 0.0058818115\n[PAD] 0.0027296143\n[PAD] 0.0054960256\n[PAD] 0.02381097\n[PAD] 0.031959046\n[PAD] 0.023501502\n[PAD] 0.029421002\n[PAD] 0.019695265\n[PAD] 0.0070037507\n[PAD] 0.006307026\n[PAD] 0.027804963\n[PAD] 0.035719655\n[PAD] 0.0314759\n[PAD] 0.013258148\n[PAD] 0.011399982\n[PAD] 0.012783347\n[PAD] 0.009198705\n[PAD] 0.0066758213\n[PAD] 0.016983226\n[PAD] 0.0062727984\n[PAD] 0.0064866277\n[PAD] 0.006454958\n[PAD] 0.008155\n[PAD] 0.005170609\n[PAD] 0.023908997\n[PAD] 0.016350454\n[PAD] 0.023385696\n[PAD] 0.02252571\n[PAD] 0.007830458\n[PAD] 0.006665649\n[PAD] 0.034271915\n[PAD] 0.021068048\n"
],
[
"label_seqs[59]",
"_____no_output_____"
],
[
"label_seqs = from_BIO(label_seqs)",
"_____no_output_____"
],
[
"for i, (str_seq, label_seq) in enumerate(zip(str_seqs, label_seqs)):\n print(i,np.mean([len(clause.split()) for clause in str_seq]), len(set(label_seq)))",
"0 16.615384615384617 2\n1 14.526315789473685 4\n2 18.0 3\n3 16.043478260869566 4\n4 11.0 2\n5 18.333333333333332 5\n6 31.6 1\n7 19.09090909090909 3\n8 19.0 2\n9 17.3125 4\n10 20.25 3\n11 13.454545454545455 3\n12 17.071428571428573 4\n13 22.083333333333332 4\n14 23.0 1\n15 13.0 1\n16 13.666666666666666 4\n17 19.363636363636363 4\n18 35.0 1\n19 12.166666666666666 1\n20 17.333333333333332 4\n21 18.56 5\n22 20.428571428571427 4\n23 27.428571428571427 1\n24 23.25 1\n25 16.666666666666668 4\n26 16.22222222222222 3\n27 13.055555555555555 7\n28 25.444444444444443 2\n29 7.0 2\n30 19.0 2\n31 18.22222222222222 4\n32 15.833333333333334 4\n33 22.1 1\n34 11.875 4\n35 20.736842105263158 5\n36 13.529411764705882 5\n37 30.166666666666668 1\n38 15.68421052631579 6\n39 15.7 5\n40 23.75 1\n41 17.0 3\n42 12.333333333333334 1\n43 32.4 2\n44 18.5 2\n45 14.777777777777779 4\n46 17.333333333333332 2\n47 16.7 4\n48 14.470588235294118 5\n49 19.714285714285715 2\n50 15.0 1\n51 18.8 3\n52 21.333333333333332 4\n53 20.333333333333332 2\n54 44.75 2\n55 18.818181818181817 3\n56 13.222222222222221 4\n57 18.0 3\n58 13.2 1\n59 15.6 3\n60 37.0 1\n61 23.1 3\n62 15.555555555555555 1\n63 17.1875 3\n"
],
[
"def normalize(array):\n low = np.min(array)\n high = np.max(array)\n return (array - low) / (high - low)",
"_____no_output_____"
],
[
"def attention_text(x, y, strings, alphas, orientation='horizontal',\n ax=None, **kwargs):\n if ax is None:\n ax = plt.gca()\n ax.axis('off')\n t = ax.transData\n canvas = ax.figure.canvas\n\n assert orientation in ['horizontal', 'vertical']\n if orientation == 'vertical':\n kwargs.update(rotation=90, verticalalignment='bottom')\n\n for s, alpha in zip(strings, alphas):\n text = ax.text(x, y, s + \" \", alpha=alpha, transform=t, **kwargs)\n\n # Need to draw to update the text position.\n text.draw(canvas.get_renderer())\n ex = text.get_window_extent()\n if orientation == 'horizontal':\n t = transforms.offset_copy(\n text.get_transform(), x=ex.width, units='dots')\n else:\n t = transforms.offset_copy(\n text.get_transform(), y=ex.height, units='dots')\n\n\nalphas = np.arange(1,9) * 0.1\nfig = plt.figure(figsize=(6, 0.3))\nattention_text(0, 4, goal_string, normalize(goal_weight), size=30)\nattention_text(0, 2, method_string, normalize(method_weight), size=24)\nattention_text(0, 0, results_string, normalize(results_weight), size=21)\n#plt.show()\nfilename = \"attention_visualization.pdf\"\nplt.savefig(filename,quality=100,bbox_inches='tight')",
"_____no_output_____"
],
[
"def attention_text(x, y, strings, alphas, orientation='horizontal',\n ax=None, **kwargs):\n if ax is None:\n ax = plt.gca()\n ax.axis('off')\n t = ax.transData\n canvas = ax.figure.canvas\n\n assert orientation in ['horizontal', 'vertical']\n if orientation == 'vertical':\n kwargs.update(rotation=90, verticalalignment='bottom')\n\n for s, alpha in zip(strings, alphas):\n text = ax.text(x, y, s + \" \", size=alpha*30, transform=t, **kwargs)\n\n # Need to draw to update the text position.\n text.draw(canvas.get_renderer())\n ex = text.get_window_extent()\n if orientation == 'horizontal':\n t = transforms.offset_copy(\n text.get_transform(), x=ex.width, units='dots')\n else:\n t = transforms.offset_copy(\n text.get_transform(), y=ex.height, units='dots')\n\n\nalphas = np.arange(1,9) * 0.1\nfig = plt.figure(figsize=(6, 0.3))\nattention_text(0, 4, goal_string, normalize(goal_weight))\nattention_text(0, 2, method_string, normalize(method_weight))\nattention_text(0, 0, results_string, normalize(results_weight))\n#plt.show()\nfilename = \"attention_visualization.pdf\"\nplt.savefig(filename,quality=100,bbox_inches='tight')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7aac5230c4d6db1d5788992ea82e8ba6957fadf | 3,790 | ipynb | Jupyter Notebook | testing/western_cropmask/0_README.ipynb | digitalearthafrica/crop-mask | 18ae773c4d5eb71c0add765260a1032c46c68a0e | [
"Apache-2.0"
] | 11 | 2020-12-15T04:09:41.000Z | 2022-01-19T11:07:21.000Z | testing/western_cropmask/0_README.ipynb | digitalearthafrica/crop-mask | 18ae773c4d5eb71c0add765260a1032c46c68a0e | [
"Apache-2.0"
] | 15 | 2021-03-15T02:17:32.000Z | 2022-02-24T02:50:01.000Z | testing/western_cropmask/0_README.ipynb | digitalearthafrica/crop-mask | 18ae773c4d5eb71c0add765260a1032c46c68a0e | [
"Apache-2.0"
] | 4 | 2020-12-16T04:48:36.000Z | 2021-03-30T16:51:37.000Z | 41.195652 | 386 | 0.657256 | [
[
[
"<img align=\"centre\" src=\"../../figs/Github_banner.jpg\" width=\"100%\">\n\n# Western Africa Cropland Mask",
"_____no_output_____"
],
[
"## Background\n\nThe notebooks in this folder provide the means for generating a cropland mask (crop/non-crop) for the Western Africa study region (Figure 1), for the year 2019 at 10m resolution. To obtain classifications a Random Forest algorithm is trained using training data in the `data/` folder (`Western_training_data_<YYYYMMDD>.geojson`). The entire algorithm is summarised in figure 2.\n\nThe definition of cropping used to collect the training data is:\n\n “A piece of land of minimum 0.16 ha that is sowed/planted and harvest-able at least once within the 12 months after the sowing/planting date.”\n\nThis definition will exclude non-planted grazing lands and perennial crops which can be difficult for satellite imagery to differentiate from natural vegetation.\n\n_Figure 1: Study area for the notebooks in this workflow_\n\n<img align=\"center\" src=\"../../figs/study_area_western.PNG\" width=\"900\">\n\n\n_Figure 2: The algorithm used to generate the cropland mask for Southern Africa_\n\n<img align=\"center\" src=\"../../figs/cropmask_algo_eastern.PNG\" width=\"900\">\n",
"_____no_output_____"
],
[
"---\n## Getting Started\n\nThere are six notebooks in this collection which, if run sequentially, will reproduce Digital Earth Africa's cropmask for the Western region of Africa.\nTo begin working through the notebooks in this `Western Africa Cropland Mask` workflow, go to the first notebook `Extract_training_data.ipynb`.\n\n1. [Extract_training_data](1_Extract_training_data.ipynb) \n2. [Inspect_training_data](2_Inspect_training_data.ipynb)\n3. [Train_fit_evaluate_classifier](3_Train_fit_evaluate_classifier.ipynb)\n4. [Predict](4_Predict.ipynb)\n5. [Object-based_filtering](5_Object-based_filtering.ipynb)\n6. [Accuracy_assessment](6_Accuracy_assessment.ipynb)\n",
"_____no_output_____"
],
[
"***\n\n## Additional information\n\n**License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). \nDigital Earth Africa data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license.\n\n**Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)).\nIf you would like to report an issue with this notebook, you can file one on [Github](https://github.com/digitalearthafrica/deafrica-sandbox-notebooks).\n",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7aacd103c99ca281460d9f88692cdc1d22d15fb | 70,635 | ipynb | Jupyter Notebook | Clase8-RNN/extras/2lstm.ipynb | diegostaPy/cursoIA | c18b68452f65e301a310c2e7d392558c8e266986 | [
"Apache-2.0"
] | 3 | 2021-02-09T18:04:58.000Z | 2021-03-19T01:56:56.000Z | Clase8-RNN/extras/2lstm.ipynb | diegostaPy/cursoIA | c18b68452f65e301a310c2e7d392558c8e266986 | [
"Apache-2.0"
] | null | null | null | Clase8-RNN/extras/2lstm.ipynb | diegostaPy/cursoIA | c18b68452f65e301a310c2e7d392558c8e266986 | [
"Apache-2.0"
] | null | null | null | 68.777994 | 11,860 | 0.629716 | [
[
[
"#Programming LSTM with Keras and TensorFlow\n\nSo far, the neural networks that we’ve examined have always had forward connections. Neural networks of this type always begin with an input layer connected to the first hidden layer. Each hidden layer always connects to the next hidden layer. The final hidden layer always connects to the output layer. This manner to connect layers is the reason that these networks are called “feedforward.” Recurrent neural networks are not so rigid, as backward connections are also allowed. A recurrent connection links a neuron in a layer to either a previous layer or the neuron itself. Most recurrent neural network architectures maintain state in the recurrent connections. Feedforward neural networks don’t maintain any state. A recurrent neural network’s state acts as a sort of short-term memory for the neural network. Consequently, a recurrent neural network will not always produce the same output for a given input.\n\nRecurrent neural networks do not force the connections to flow only from one layer to the next, from the input layer to the output layer. A recurrent connection occurs when a connection is formed between a neuron and one of the following other types of neurons:\n\n* The neuron itself\n* A neuron on the same level\n* A neuron on a previous level\n\nRecurrent connections can never target the input neurons or bias neurons. \nThe processing of recurrent connections can be challenging. Because the recurrent links create endless loops, the neural network must have some way to know when to stop. A neural network that entered an endless loop would not be useful. To prevent endless loops, we can calculate the recurrent connections with the following three approaches:\n\n* Context neurons\n* Calculating output over a fixed number of iterations\n* Calculating output until neuron output stabilizes\n\nThe context neuron is a special neuron type that remembers its input and provides that input as its output the next time that we calculate the network. For example, if we gave a context neuron 0.5 as input, it would output 0. Context neurons always output 0 on their first call. However, if we gave the context neuron a 0.6 as input, the output would be 0.5. We never weigh the input connections to a context neuron, but we can weigh the output from a context neuron just like any other network connection. \n\nContext neurons allow us to calculate a neural network in a single feedforward pass. Context neurons usually occur in layers. A layer of context neurons will always have the same number of context neurons as neurons in its source layer, as demonstrated by Figure 10.CTX.\n\n**Figure 10.CTX: Context Layers**\n\n\nAs you can see from the above layer, two hidden neurons that are labeled hidden one and hidden two directly connect to the two context neurons. The dashed lines on these connections indicate that these are not weighted connections. These weightless connections are never dense. If these connections were dense, hidden one would be connected to both hidden one and hidden 2. However, the direct connection joins each hidden neuron to its corresponding context neuron. The two context neurons form dense, weighted connections to the two hidden neurons. Finally, the two hidden neurons also form dense connections to the neurons in the next layer. The two context neurons form two connections to a single neuron in the next layer, four connections to two neurons, six connections to three neurons, and so on.\n\nYou can combine context neurons with the input, hidden, and output layers of a neural network in many different ways. ",
"_____no_output_____"
],
[
"# Understanding LSTM\n\nLong Short Term Neural Network (LSTM) layers are a type of recurrent unit that you often use with deep neural networks.[[Cite:hochreiter1997long]](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.676.4320) For TensorFlow, you can think of LSTM as a layer type that you can combine with other layer types, such as dense. LSTM makes use of two transfer function types internally. \n\nThe first type of transfer function is the sigmoid. This transfer function type is used form gates inside of the unit. The sigmoid transfer function is given by the following equation:\n\n$ \\mbox{S}(t) = \\frac{1}{1 + e^{-t}} $\n\nThe second type of transfer function is the hyperbolic tangent (tanh) function, which you to scale the output of the LSTM. This functionality is similar to how we have used other transfer functions in this course. \n\nWe provide the graphs for these functions here:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\ndef sigmoid(x):\n a = []\n for item in x:\n a.append(1/(1+math.exp(-item)))\n return a\n\ndef f2(x):\n a = []\n for item in x:\n a.append(math.tanh(item))\n return a\n\nx = np.arange(-10., 10., 0.2)\ny1 = sigmoid(x)\ny2 = f2(x)\n\nprint(\"Sigmoid\")\nplt.plot(x,y1)\nplt.show()\n\nprint(\"Hyperbolic Tangent(tanh)\")\nplt.plot(x,y2)\nplt.show()",
"Sigmoid\n"
]
],
[
[
"Both of these two functions compress their output to a specific range. For the sigmoid function, this range is 0 to 1. For the hyperbolic tangent function, this range is -1 to 1.\n\nLSTM maintains an internal state and produces an output. The following diagram shows an LSTM unit over three time slices: the current time slice (t), as well as the previous (t-1) and next (t+1) slice, as demonstrated by Figure 10.LSTM.\n\n**Figure 10.LSTM: LSTM Layers**\n\n\nThe values $\\hat{y}$ are the output from the unit; the values ($x$) are the input to the unit, and the values $c$ are the context values. The output and context values always feed their output to the next time slice. The context values allow the network to maintain state between calls. Figure 10.ILSTM shows the internals of a LSTM layer.\n\n**Figure 10.ILSTM: Inside a LSTM Layer**\n\n\nA LSTM unit consists of three gates:\n\n* Forget Gate ($f_t$) - Controls if/when the context is forgotten. (MC)\n* Input Gate ($i_t$) - Controls if/when the context should remember a value. (M+/MS)\n* Output Gate ($o_t$) - Controls if/when the remembered value is allowed to pass from the unit. (RM)\n\nMathematically, you can think of the above diagram as the following:\n\n**These are vector values.**\n\nFirst, calculate the forget gate value. This gate determines if the LSTM unit should forget its short term memory. The value $b$ is a bias, just like the bias neurons we saw before. Except LSTM has a bias for every gate: $b_t$, $b_i$, and $b_o$.\n\n$ f_t = S(W_f \\cdot [\\hat{y}_{t-1}, x_t] + b_f) $\n\n$ i_t = S(W_i \\cdot [\\hat{y}_{t-1},x_t] + b_i) $\n\n$ \\tilde{C}_t = \\tanh(W_C \\cdot [\\hat{y}_{t-1},x_t]+b_C) $\n\n$ C_t = f_t \\cdot C_{t-1}+i_t \\cdot \\tilde{C}_t $\n\n$ o_t = S(W_o \\cdot [\\hat{y}_{t-1},x_t] + b_o ) $\n\n$ \\hat{y}_t = o_t \\cdot \\tanh(C_t) $\n",
"_____no_output_____"
],
[
"# Simple TensorFlow LSTM Example\n\nThe following code creates the LSTM network, which is an example of a RNN for classification. The following code trains on a data set (x) with a max sequence size of 6 (columns) and six training elements (rows)",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Embedding\nfrom tensorflow.keras.layers import LSTM\nimport numpy as np\n\nmax_features = 4 # 0,1,2,3 (total of 4)\nx = [\n [[0],[1],[1],[0],[0],[0]],\n [[0],[0],[0],[2],[2],[0]],\n [[0],[0],[0],[0],[3],[3]],\n [[0],[2],[2],[0],[0],[0]],\n [[0],[0],[3],[3],[0],[0]],\n [[0],[0],[0],[0],[1],[1]]\n]\nx = np.array(x,dtype=np.float32)\ny = np.array([1,2,3,2,3,1],dtype=np.int32)\n\n# Convert y2 to dummy variables\ny2 = np.zeros((y.shape[0], max_features),dtype=np.float32)\ny2[np.arange(y.shape[0]), y] = 1.0\nprint(y2)\n\nprint('Build model...')\nmodel = Sequential()\nmodel.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2, \\\n input_shape=(None, 1)))\nmodel.add(Dense(4, activation='sigmoid'))\n\n# try using different optimizers and different optimizer configs\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nprint('Train...')\nmodel.fit(x,y2,epochs=200)\npred = model.predict(x)\npredict_classes = np.argmax(pred,axis=1)\nprint(\"Predicted classes: {}\",predict_classes)\nprint(\"Expected classes: {}\",predict_classes)",
"[[0. 1. 0. 0.]\n [0. 0. 1. 0.]\n [0. 0. 0. 1.]\n [0. 0. 1. 0.]\n [0. 0. 0. 1.]\n [0. 1. 0. 0.]]\nBuild model...\nTrain...\nTrain on 6 samples\nEpoch 1/200\n6/6 [==============================] - 3s 505ms/sample - loss: 0.6913 - accuracy: 0.5417\nEpoch 2/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.6886 - accuracy: 0.5833\nEpoch 3/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.6831 - accuracy: 0.7083\nEpoch 4/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.6673 - accuracy: 0.7083\nEpoch 5/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.6586 - accuracy: 0.6667\nEpoch 6/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.6506 - accuracy: 0.7500\nEpoch 7/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.6456 - accuracy: 0.7083\nEpoch 8/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.6515 - accuracy: 0.6250\nEpoch 9/200\n6/6 [==============================] - 0s 7ms/sample - loss: 0.6272 - accuracy: 0.7083\nEpoch 10/200\n6/6 [==============================] - 0s 6ms/sample - loss: 0.6141 - accuracy: 0.6667\nEpoch 11/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.6148 - accuracy: 0.7500\nEpoch 12/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.6530 - accuracy: 0.6667\nEpoch 13/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5943 - accuracy: 0.7917\nEpoch 14/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5830 - accuracy: 0.7500\nEpoch 15/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5950 - accuracy: 0.7917\nEpoch 16/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5859 - accuracy: 0.8333\nEpoch 17/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5705 - accuracy: 0.7500\nEpoch 18/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.5424 - accuracy: 0.7500\nEpoch 19/200\n6/6 [==============================] - 0s 6ms/sample - loss: 0.5968 - accuracy: 0.7083\nEpoch 20/200\n6/6 [==============================] - 0s 9ms/sample - loss: 0.5246 - accuracy: 0.7500\nEpoch 21/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5266 - accuracy: 0.7917\nEpoch 22/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.5479 - accuracy: 0.7083\nEpoch 23/200\n6/6 [==============================] - 0s 6ms/sample - loss: 0.5007 - accuracy: 0.7083\nEpoch 24/200\n6/6 [==============================] - 0s 6ms/sample - loss: 0.4924 - accuracy: 0.7500\nEpoch 25/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5386 - accuracy: 0.7500\nEpoch 26/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4812 - accuracy: 0.7917\nEpoch 27/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5430 - accuracy: 0.7917\nEpoch 28/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4713 - accuracy: 0.7917\nEpoch 29/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4701 - accuracy: 0.7917\nEpoch 30/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4595 - accuracy: 0.7917\nEpoch 31/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4900 - accuracy: 0.7917\nEpoch 32/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4899 - accuracy: 0.7917\nEpoch 33/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4834 - accuracy: 0.7917\nEpoch 34/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4729 - accuracy: 0.7917\nEpoch 35/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.5050 - accuracy: 0.7500\nEpoch 36/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4437 - accuracy: 0.7917\nEpoch 37/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4915 - accuracy: 0.7500\nEpoch 38/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4915 - accuracy: 0.7917\nEpoch 39/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4348 - accuracy: 0.7917\nEpoch 40/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4406 - accuracy: 0.8333\nEpoch 41/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4196 - accuracy: 0.8333\nEpoch 42/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4805 - accuracy: 0.7917\nEpoch 43/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4972 - accuracy: 0.7917\nEpoch 44/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4005 - accuracy: 0.7917\nEpoch 45/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4658 - accuracy: 0.7500\nEpoch 46/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4926 - accuracy: 0.7500\nEpoch 47/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.3913 - accuracy: 0.8750\nEpoch 48/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.3888 - accuracy: 0.8333\nEpoch 49/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3874 - accuracy: 0.8333\nEpoch 50/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4546 - accuracy: 0.7500\nEpoch 51/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4326 - accuracy: 0.7917\nEpoch 52/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.4143 - accuracy: 0.7500\nEpoch 53/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3701 - accuracy: 0.8333\nEpoch 54/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3742 - accuracy: 0.8333\nEpoch 55/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.3840 - accuracy: 0.7917\nEpoch 56/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3639 - accuracy: 0.7917\nEpoch 57/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3538 - accuracy: 0.8333\nEpoch 58/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4920 - accuracy: 0.7917\nEpoch 59/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3213 - accuracy: 0.9583\nEpoch 60/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4598 - accuracy: 0.7500\nEpoch 61/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.3398 - accuracy: 0.8333\nEpoch 62/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3449 - accuracy: 0.8333\nEpoch 63/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4244 - accuracy: 0.8333\nEpoch 64/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4307 - accuracy: 0.7917\nEpoch 65/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4790 - accuracy: 0.7083\nEpoch 66/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3221 - accuracy: 0.8750\nEpoch 67/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3655 - accuracy: 0.8750\nEpoch 68/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4458 - accuracy: 0.7917\nEpoch 69/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.5040 - accuracy: 0.7083\nEpoch 70/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2956 - accuracy: 0.9167\nEpoch 71/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4356 - accuracy: 0.7917\nEpoch 72/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3046 - accuracy: 0.8750\nEpoch 73/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3707 - accuracy: 0.8333\nEpoch 74/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3867 - accuracy: 0.8333\nEpoch 75/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2919 - accuracy: 0.9583\nEpoch 76/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2994 - accuracy: 0.9167\nEpoch 77/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4719 - accuracy: 0.7500\nEpoch 78/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3550 - accuracy: 0.8750\nEpoch 79/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3423 - accuracy: 0.8750\nEpoch 80/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2943 - accuracy: 0.9583\nEpoch 81/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.3326 - accuracy: 0.8750\nEpoch 82/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.3926 - accuracy: 0.8750\nEpoch 83/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2640 - accuracy: 0.9167\nEpoch 84/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4553 - accuracy: 0.7500\nEpoch 85/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2555 - accuracy: 0.9583\nEpoch 86/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4095 - accuracy: 0.8333\nEpoch 87/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3975 - accuracy: 0.8333\nEpoch 88/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.2851 - accuracy: 0.9583\nEpoch 89/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2500 - accuracy: 0.9583\nEpoch 90/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2910 - accuracy: 0.8750\nEpoch 91/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3364 - accuracy: 0.8750\nEpoch 92/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3723 - accuracy: 0.8750\nEpoch 93/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2362 - accuracy: 0.9583\nEpoch 94/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2523 - accuracy: 0.9583\nEpoch 95/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2738 - accuracy: 0.9167\nEpoch 96/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3589 - accuracy: 0.8750\nEpoch 97/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4044 - accuracy: 0.8750\nEpoch 98/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2605 - accuracy: 0.9167\nEpoch 99/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3987 - accuracy: 0.8750\nEpoch 100/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2549 - accuracy: 0.9583\nEpoch 101/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2146 - accuracy: 0.9583\nEpoch 102/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2092 - accuracy: 0.9583\nEpoch 103/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4746 - accuracy: 0.7917\nEpoch 104/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2333 - accuracy: 0.9167\nEpoch 105/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3665 - accuracy: 0.8750\nEpoch 106/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.4186 - accuracy: 0.8333\nEpoch 107/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.2398 - accuracy: 0.9167\nEpoch 108/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2187 - accuracy: 0.9167\nEpoch 109/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2066 - accuracy: 0.9583\nEpoch 110/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.1974 - accuracy: 0.9583\nEpoch 111/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.5071 - accuracy: 0.7500\nEpoch 112/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4210 - accuracy: 0.8333\nEpoch 113/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.3519 - accuracy: 0.8333\nEpoch 114/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.5612 - accuracy: 0.7083\nEpoch 115/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2111 - accuracy: 0.9167\nEpoch 116/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3792 - accuracy: 0.8333\nEpoch 117/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1995 - accuracy: 0.9583\nEpoch 118/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3646 - accuracy: 0.7917\nEpoch 119/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2047 - accuracy: 0.9167\nEpoch 120/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2847 - accuracy: 0.8750\nEpoch 121/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.3132 - accuracy: 0.8333\nEpoch 122/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1924 - accuracy: 0.9583\nEpoch 123/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.4390 - accuracy: 0.7500\nEpoch 124/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3729 - accuracy: 0.7917\nEpoch 125/200\n6/6 [==============================] - 0s 1ms/sample - loss: 0.2823 - accuracy: 0.8750\nEpoch 126/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.1642 - accuracy: 0.9583\nEpoch 127/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2268 - accuracy: 0.9167\nEpoch 128/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1958 - accuracy: 0.8750\nEpoch 129/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2867 - accuracy: 0.8750\nEpoch 130/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3229 - accuracy: 0.8333\nEpoch 131/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3164 - accuracy: 0.8750\nEpoch 132/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1798 - accuracy: 0.9583\nEpoch 133/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.1757 - accuracy: 0.9583\nEpoch 134/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2464 - accuracy: 0.9167\nEpoch 135/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3582 - accuracy: 0.8333\nEpoch 136/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1789 - accuracy: 0.9583\nEpoch 137/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1476 - accuracy: 0.9583\nEpoch 138/200\n6/6 [==============================] - 0s 1ms/sample - loss: 0.3301 - accuracy: 0.8750\nEpoch 139/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1761 - accuracy: 0.9583\nEpoch 140/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.4327 - accuracy: 0.7917\nEpoch 141/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2879 - accuracy: 0.8750\nEpoch 142/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.1414 - accuracy: 0.9583\nEpoch 143/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2547 - accuracy: 0.9167\nEpoch 144/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.1460 - accuracy: 1.0000\nEpoch 145/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.3137 - accuracy: 0.8750\nEpoch 146/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1315 - accuracy: 1.0000\nEpoch 147/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3852 - accuracy: 0.7917\nEpoch 148/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2719 - accuracy: 0.9167\nEpoch 149/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1496 - accuracy: 1.0000\nEpoch 150/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2878 - accuracy: 0.9167\nEpoch 151/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1537 - accuracy: 1.0000\nEpoch 152/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2899 - accuracy: 0.9167\nEpoch 153/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1252 - accuracy: 1.0000\nEpoch 154/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.1417 - accuracy: 1.0000\nEpoch 155/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2284 - accuracy: 0.9167\nEpoch 156/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2481 - accuracy: 0.9167\nEpoch 157/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2009 - accuracy: 0.9167\nEpoch 158/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2227 - accuracy: 0.9167\nEpoch 159/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2688 - accuracy: 0.9167\nEpoch 160/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2263 - accuracy: 0.9167\nEpoch 161/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3903 - accuracy: 0.8333\nEpoch 162/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2183 - accuracy: 0.9167\nEpoch 163/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3621 - accuracy: 0.8333\nEpoch 164/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.1198 - accuracy: 1.0000\nEpoch 165/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2577 - accuracy: 0.9167\nEpoch 166/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1335 - accuracy: 1.0000\nEpoch 167/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3546 - accuracy: 0.8333\nEpoch 168/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2348 - accuracy: 0.9167\nEpoch 169/200\n6/6 [==============================] - 0s 1ms/sample - loss: 0.1281 - accuracy: 1.0000\nEpoch 170/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1660 - accuracy: 1.0000\nEpoch 171/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2184 - accuracy: 0.9167\nEpoch 172/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1036 - accuracy: 1.0000\nEpoch 173/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2024 - accuracy: 0.8750\nEpoch 174/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.1110 - accuracy: 1.0000\nEpoch 175/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1062 - accuracy: 1.0000\nEpoch 176/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3554 - accuracy: 0.8333\nEpoch 177/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.3158 - accuracy: 0.8333\nEpoch 178/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2536 - accuracy: 0.9167\nEpoch 179/200\n6/6 [==============================] - 0s 5ms/sample - loss: 0.1667 - accuracy: 1.0000\nEpoch 180/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.3269 - accuracy: 0.8333\nEpoch 181/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3726 - accuracy: 0.8333\nEpoch 182/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2217 - accuracy: 0.9167\nEpoch 183/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.0669 - accuracy: 1.0000\nEpoch 184/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1030 - accuracy: 1.0000\nEpoch 185/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2262 - accuracy: 0.9167\nEpoch 186/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2330 - accuracy: 0.8750\nEpoch 187/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.1415 - accuracy: 0.9583\nEpoch 188/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2004 - accuracy: 0.9167\nEpoch 189/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.2341 - accuracy: 0.8750\nEpoch 190/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2058 - accuracy: 0.9167\nEpoch 191/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.3662 - accuracy: 0.8333\nEpoch 192/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.0939 - accuracy: 1.0000\nEpoch 193/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2371 - accuracy: 0.9167\nEpoch 194/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.1663 - accuracy: 1.0000\nEpoch 195/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2703 - accuracy: 0.7917\nEpoch 196/200\n6/6 [==============================] - 0s 2ms/sample - loss: 0.2085 - accuracy: 0.9167\nEpoch 197/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.0875 - accuracy: 1.0000\nEpoch 198/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2005 - accuracy: 0.9167\nEpoch 199/200\n6/6 [==============================] - 0s 3ms/sample - loss: 0.0807 - accuracy: 1.0000\nEpoch 200/200\n6/6 [==============================] - 0s 4ms/sample - loss: 0.2199 - accuracy: 0.9167\nPredicted classes: {} [1 2 3 2 2 1]\nExpected classes: {} [1 2 3 2 2 1]\n"
],
[
"def runit(model, inp):\n inp = np.array(inp,dtype=np.float32)\n pred = model.predict(inp)\n return np.argmax(pred[0])\n\nprint( runit( model, [[[0],[0],[0],[0],[0],[1]]] ))\n",
"1\n"
]
],
[
[
"# Sun Spots Example\n\nIn this section, we see an example of RNN regression to predict sunspots. You can find the data files needed for this example at the following location.\n\n* [Sunspot Data Files](http://www.sidc.be/silso/datafiles#total)\n* [Download Daily Sunspots](http://www.sidc.be/silso/INFO/sndtotcsv.php) - 1/1/1818 to now.\n\nThe following code loads the sunspot file:\n",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport os\n\n# Replacce the following path with your own file. It can be downloaded from:\n# http://www.sidc.be/silso/INFO/sndtotcsv.php\n\nif COLAB:\n PATH = \"/content/drive/My Drive/Colab Notebooks/data/\"\nelse:\n PATH = \"./data/\"\n \nfilename = os.path.join(PATH,\"SN_d_tot_V2.0.csv\") \nnames = ['year', 'month', 'day', 'dec_year', 'sn_value' , \n 'sn_error', 'obs_num']\ndf = pd.read_csv(filename,sep=';',header=None,names=names,\n na_values=['-1'], index_col=False)\n\nprint(\"Starting file:\")\nprint(df[0:10])\n\nprint(\"Ending file:\")\nprint(df[-10:])",
"Starting file:\n year month day dec_year sn_value sn_error obs_num\n0 1818 1 1 1818.001 -1 NaN 0\n1 1818 1 2 1818.004 -1 NaN 0\n2 1818 1 3 1818.007 -1 NaN 0\n3 1818 1 4 1818.010 -1 NaN 0\n4 1818 1 5 1818.012 -1 NaN 0\n5 1818 1 6 1818.015 -1 NaN 0\n6 1818 1 7 1818.018 -1 NaN 0\n7 1818 1 8 1818.021 65 10.2 1\n8 1818 1 9 1818.023 -1 NaN 0\n9 1818 1 10 1818.026 -1 NaN 0\nEnding file:\n year month day dec_year sn_value sn_error obs_num\n73769 2019 12 22 2019.974 0 0.0 17\n73770 2019 12 23 2019.977 0 0.0 24\n73771 2019 12 24 2019.979 16 1.0 10\n73772 2019 12 25 2019.982 23 2.2 7\n73773 2019 12 26 2019.985 10 3.7 16\n73774 2019 12 27 2019.988 0 0.0 26\n73775 2019 12 28 2019.990 0 0.0 26\n73776 2019 12 29 2019.993 0 0.0 27\n73777 2019 12 30 2019.996 0 0.0 32\n73778 2019 12 31 2019.999 0 0.0 19\n"
]
],
[
[
"As you can see, there is quite a bit of missing data near the end of the file. We want to find the starting index where the missing data no longer occurs. This technique is somewhat sloppy; it would be better to find a use for the data between missing values. However, the point of this example is to show how to use LSTM with a somewhat simple time-series.",
"_____no_output_____"
]
],
[
[
"start_id = max(df[df['obs_num'] == 0].index.tolist())+1 # Find the last zero and move one beyond\nprint(start_id)\ndf = df[start_id:] # Trim the rows that have missing observations",
"11314\n"
],
[
"df['sn_value'] = df['sn_value'].astype(float)\ndf_train = df[df['year']<2000]\ndf_test = df[df['year']>=2000]\n\nspots_train = df_train['sn_value'].tolist()\nspots_test = df_test['sn_value'].tolist()\n\nprint(\"Training set has {} observations.\".format(len(spots_train)))\nprint(\"Test set has {} observations.\".format(len(spots_test)))",
"Training set has 55160 observations.\nTest set has 7305 observations.\n"
],
[
"import numpy as np\n\ndef to_sequences(seq_size, obs):\n x = []\n y = []\n\n for i in range(len(obs)-SEQUENCE_SIZE):\n #print(i)\n window = obs[i:(i+SEQUENCE_SIZE)]\n after_window = obs[i+SEQUENCE_SIZE]\n window = [[x] for x in window]\n #print(\"{} - {}\".format(window,after_window))\n x.append(window)\n y.append(after_window)\n \n return np.array(x),np.array(y)\n \n \nSEQUENCE_SIZE = 10\nx_train,y_train = to_sequences(SEQUENCE_SIZE,spots_train)\nx_test,y_test = to_sequences(SEQUENCE_SIZE,spots_test)\n\nprint(\"Shape of training set: {}\".format(x_train.shape))\nprint(\"Shape of test set: {}\".format(x_test.shape))",
"Shape of training set: (55150, 10, 1)\nShape of test set: (7295, 10, 1)\n"
],
[
"x_train",
"_____no_output_____"
],
[
"from tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Embedding\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.datasets import imdb\nfrom tensorflow.keras.callbacks import EarlyStopping\nimport numpy as np\n\nprint('Build model...')\nmodel = Sequential()\nmodel.add(LSTM(64, dropout=0.0, recurrent_dropout=0.0,input_shape=(None, 1)))\nmodel.add(Dense(32))\nmodel.add(Dense(1))\nmodel.compile(loss='mean_squared_error', optimizer='adam')\nmonitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=5, \n verbose=1, mode='auto', restore_best_weights=True)\nprint('Train...')\n\nmodel.fit(x_train,y_train,validation_data=(x_test,y_test),\n callbacks=[monitor],verbose=2,epochs=1000)",
"Build model...\nTrain...\nTrain on 55150 samples, validate on 7295 samples\nEpoch 1/1000\n55150/55150 - 13s - loss: 1312.6864 - val_loss: 190.2033\nEpoch 2/1000\n55150/55150 - 8s - loss: 513.1618 - val_loss: 188.5868\nEpoch 3/1000\n55150/55150 - 8s - loss: 510.8469 - val_loss: 191.0815\nEpoch 4/1000\n55150/55150 - 8s - loss: 506.8735 - val_loss: 215.0268\nEpoch 5/1000\n55150/55150 - 8s - loss: 503.7439 - val_loss: 193.7987\nEpoch 6/1000\n55150/55150 - 8s - loss: 504.5192 - val_loss: 199.2520\nEpoch 7/1000\nRestoring model weights from the end of the best epoch.\n55150/55150 - 8s - loss: 502.6547 - val_loss: 198.9333\nEpoch 00007: early stopping\n"
]
],
[
[
"Finally, we evaluate the model with RMSE.",
"_____no_output_____"
]
],
[
[
"from sklearn import metrics\n\npred = model.predict(x_test)\nscore = np.sqrt(metrics.mean_squared_error(pred,y_test))\nprint(\"Score (RMSE): {}\".format(score))",
"Score (RMSE): 13.732691339581104\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7aad7523ba5fd0d4adc67abf76de6a496b531df | 5,539 | ipynb | Jupyter Notebook | models/genetic_programming/example.ipynb | shawlu95/Data_Science_Toolbox | 3f5dd554667dab51b59a1668488243161786b5f1 | [
"MIT"
] | 41 | 2019-05-04T11:02:43.000Z | 2022-02-20T02:37:01.000Z | models/genetic_programming/example.ipynb | shawlu95/Data_Science_Toolbox | 3f5dd554667dab51b59a1668488243161786b5f1 | [
"MIT"
] | null | null | null | models/genetic_programming/example.ipynb | shawlu95/Data_Science_Toolbox | 3f5dd554667dab51b59a1668488243161786b5f1 | [
"MIT"
] | 16 | 2019-04-05T00:49:16.000Z | 2021-04-15T08:06:43.000Z | 24.400881 | 223 | 0.464344 | [
[
[
"#### Import Module",
"_____no_output_____"
]
],
[
[
"from random import random,randint,choice\nimport genetic as g",
"_____no_output_____"
]
],
[
[
"#### Build Dataset",
"_____no_output_____"
]
],
[
[
"def hiddenfunction(x,y):\n return x**2+2*y + 7\n\ndef buildhiddenset(): \n rows=[]\n for i in range(200):\n x=randint(0,40)\n y=randint(0,40)\n rows.append([x,y,hiddenfunction(x,y)])\n return rows\n\nhiddenset=buildhiddenset()",
"_____no_output_____"
],
[
"help(g.evolve)",
"Help on function evolve in module genetic:\n\nevolve(pc, popsize, rankfunction, maxgen=500, mutationrate=0.1, breedingrate=0.4, pexp=0.7, pnew=0.05)\n rankfunction\n The function used on the list of programs to rank them from best to worst.\n mutationrate\n The probability of a mutation, passed on to mutate.\n breedingrate\n The probability of crossover, passed on to crossover.\n popsize\n The size of the initial population.\n probexp\n The rate of decline in the probability of selecting lower-ranked programs. A higher value makes the selection process more stringent, choosing only programs with the best ranks to replicate.\n probnew\n The probability when building the new population that a completely new, ran- dom program is introduced. probexp and probnew will be discussed further in the upcoming section “The Importance of Diversity.”\n\n"
]
],
[
[
"#### Evolution",
"_____no_output_____"
]
],
[
[
"rank_func=g.getrankfunction(buildhiddenset())\nbest = g.evolve(2,500,rank_func,mutationrate=0.2,breedingrate=0.2,pexp=0.7,pnew=0.3)",
"Generation 0, cost: 8768\nGeneration 1, cost: 5912\nGeneration 2, cost: 3118\nGeneration 3, cost: 1400\nGeneration 4, cost: 1375\nGeneration 5, cost: 1375\nGeneration 6, cost: 619\nGeneration 7, cost: 443\nGeneration 8, cost: 400\nGeneration 9, cost: 374\nGeneration 10, cost: 200\nGeneration 11, cost: 47\nGeneration 12, cost: 47\nGeneration 13, cost: 47\nGeneration 14, cost: 30\nGeneration 15, cost: 30\nGeneration 16, cost: 30\nGeneration 17, cost: 30\nGeneration 18, cost: 30\nGeneration 19, cost: 30\nGeneration 20, cost: 25\nGeneration 21, cost: 25\nGeneration 22, cost: 25\nGeneration 23, cost: 25\nGeneration 24, cost: 25\nGeneration 25, cost: 25\nGeneration 26, cost: 25\nGeneration 27, cost: 21\nGeneration 28, cost: 21\nGeneration 29, cost: 21\nGeneration 30, cost: 21\nGeneration 31, cost: 21\nGeneration 32, cost: 0\n"
],
[
"best.display()",
" add\n add\n if\n add\n p1\n 8\n add\n if\n 1\n subtract\n 7\n subtract\n 7\n add\n p1\n subtract\n 3\n 4\n p0\n 8\n add\n if\n if\n isgreater\n 2\n subtract\n add\n 5\n 1\n p0\n isgreater\n 6\n multiply\n p1\n subtract\n 4\n isgreater\n p0\n add\n p0\n 0\n 0\n 9\n p0\n 2\n p1\n multiply\n if\n 1\n p0\n p0\n p0\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7aadaf32a11eb66879b0bdf6d2b8b9371ef51fc | 48,002 | ipynb | Jupyter Notebook | QKD_for_QBA/QKD_List_DephaseChannel.ipynb | Asadquantum/NetSquidforQBA | 2d6bc154682713569e16842da3a9d406d0bd1868 | [
"CC0-1.0"
] | null | null | null | QKD_for_QBA/QKD_List_DephaseChannel.ipynb | Asadquantum/NetSquidforQBA | 2d6bc154682713569e16842da3a9d406d0bd1868 | [
"CC0-1.0"
] | null | null | null | QKD_for_QBA/QKD_List_DephaseChannel.ipynb | Asadquantum/NetSquidforQBA | 2d6bc154682713569e16842da3a9d406d0bd1868 | [
"CC0-1.0"
] | null | null | null | 51.504292 | 190 | 0.544248 | [
[
[
"import netsquid as ns\nimport numpy as np\nimport cmath\nimport random\nimport netsquid.components.instructions as instr\nfrom netsquid.components.qprocessor import QuantumProcessor\nfrom netsquid.components.qprocessor import PhysicalInstruction\nfrom netsquid.nodes.connections import Connection, DirectConnection\nfrom netsquid.components import ClassicalChannel\nfrom netsquid.components.models import FibreDelayModel\nfrom netsquid.nodes import Node\nfrom netsquid.components import QuantumChannel\nfrom netsquid.qubits.qubitapi import create_qubits\nfrom netsquid.components.models.qerrormodels import DepolarNoiseModel, DephaseNoiseModel,T1T2NoiseModel\nfrom netsquid.protocols import NodeProtocol, Signals ,LocalProtocol ",
"_____no_output_____"
],
[
"\nclass ClassicalBiConnection(DirectConnection):\n def __init__(self, length,name=\"ClassicalConnection\"):\n \n super().__init__(name=name)\n self.add_subcomponent(ClassicalChannel(\"Channel_A2B\", length=length,\n models={\"delay_model\": FibreDelayModel()}),\n forward_input=[(\"A\", \"send\")],\n forward_output=[(\"B\", \"recv\")])\n self.add_subcomponent(ClassicalChannel(\"Channel_B2A\", length=length,\n models={\"delay_model\": FibreDelayModel()}),\n forward_input=[(\"B\", \"send\")],\n forward_output=[(\"A\", \"recv\")])\n\n\nclass QuantumConnection(Connection):\n def __init__(self, length, prob,name=\"QuantumConnection\"):\n super().__init__(name=name)\n self.prob = prob\n# Model = DepolarNoiseModel(depolar_rate = self.prob,time_independent=True)\n Model = DephaseNoiseModel(dephase_rate = self.prob,time_independent=True)\n qchannel_a2b = QuantumChannel(\"qchannel_a2b\", length=length,\n models={\"delay_model\": FibreDelayModel(), \"quantum_noise_model\" : Model})\n # Add channels and forward quantum channel output to external port output:\n self.add_subcomponent(qchannel_a2b,forward_input=[(\"A\",\"send\")],forward_output=[(\"B\", \"recv\")])\n \n",
"_____no_output_____"
],
[
"\n\ndef create_processor():\n\n def RandUnitary():\n basis_matrix = np.identity(2)\n R= np.zeros(2)\n Theta = np.random.uniform(0,2*np.pi)\n z = cmath.exp((-Theta)*1j)\n R = R + basis_matrix[:,0].reshape((2,1))*np.transpose(basis_matrix[:,0].reshape((2,1))) + z*(basis_matrix[:,1].reshape((2,1))*np.transpose(basis_matrix[:,1].reshape((2,1))))\n return R\n \n R = RandUnitary()\n R1 = ns.qubits.operators.Operator(\"R1\", R)\n INSTR_R = instr.IGate(\"R_gate\", R1)\n # We'll give both Alice and Bob the same kind of processor\n num_qubits = 4\n physical_instructions = [\n PhysicalInstruction(instr.INSTR_INIT, duration=3, parallel=True),\n PhysicalInstruction(instr.INSTR_H, duration=1, parallel=True),\n PhysicalInstruction(INSTR_R, duration=1, parallel=True),\n PhysicalInstruction(instr.INSTR_CNOT, duration=4, parallel=True),\n PhysicalInstruction(instr.INSTR_MEASURE, duration=7, parallel=False)\n# PhysicalInstruction(instr.INSTR_MEASURE, duration=7, parallel=False, topology=[1])\n ]\n processor = QuantumProcessor(\"quantum_processor\", num_positions=num_qubits,phys_instructions=physical_instructions)\n return processor\n\n\ndef create_processor1(probs):\n\n def RandUnitary():\n basis_matrix = np.identity(2)\n R= np.zeros(2)\n Theta = np.random.uniform(0,2*np.pi)\n z = cmath.exp((-Theta)*1j)\n R = R + basis_matrix[:,0].reshape((2,1))*np.transpose(basis_matrix[:,0].reshape((2,1))) + z*(basis_matrix[:,1].reshape((2,1))*np.transpose(basis_matrix[:,1].reshape((2,1))))\n return R\n \n R = RandUnitary()\n R1 = ns.qubits.operators.Operator(\"R1\", R)\n INSTR_R = instr.IGate(\"R_gate\", R1)\n # We'll give both Alice and Bob the same kind of processor\n num_qubits = 4\n physical_instructions = [\n PhysicalInstruction(instr.INSTR_INIT, duration=3, parallel=True),\n PhysicalInstruction(instr.INSTR_H, duration=1, parallel=True),\n PhysicalInstruction(INSTR_R, duration=1, parallel=True),\n PhysicalInstruction(instr.INSTR_CNOT, duration=4, parallel=True),\n PhysicalInstruction(instr.INSTR_MEASURE, duration=7, parallel=False)\n# PhysicalInstruction(instr.INSTR_MEASURE, duration=7, parallel=False, topology=[1])\n ]\n memory_noise_model = DephaseNoiseModel(dephase_rate = probs,time_independent=True)\n# memory_noise_model = DepolarNoiseModel(depolar_rate = probs,time_independent=True)\n processor = QuantumProcessor(\"quantum_processor\", num_positions=num_qubits,phys_instructions=physical_instructions)\n return processor",
"_____no_output_____"
],
[
"from netsquid.components.qprogram import QuantumProgram\n\nclass InitStateProgram(QuantumProgram):\n default_num_qubits = 4\n# def __init__(self,num_parties)\n# print(num_parties)\n# self.num_qubits_ = int(np.log2(num_parties))\n \n def program(self):\n# self.num_qubits = int(np.log2(self.num_qubits))\n q1,q2,q3,q4 = self.get_qubit_indices()\n self.apply(instr.INSTR_INIT, [q1,q2,q3,q4])\n self.apply(instr.INSTR_H,q2)\n self.apply(instr.INSTR_H,q4)\n# for i in range(self.num_qubits):\n# if i % 2 != 0:\n# self.apply(instr.INSTR_H, qubits[i])\n# print(f\"Node 1 apply hadamard to pos {i}\")\n# print(qubits)\n self.apply(instr.INSTR_CNOT, [q2, q1])\n self.apply(instr.INSTR_CNOT, [q4,q3])\n yield self.run()\n \nclass RandUnitary(QuantumProgram):\n def RandUnitary(self):\n basis_matrix = np.identity(2)\n R= np.zeros(2)\n Theta = np.random.uniform(0,2*np.pi)\n z = cmath.exp((-Theta)*1j)\n R = R + basis_matrix[:,0].reshape((2,1))*np.transpose(basis_matrix[:,0].reshape((2,1))) + z*(basis_matrix[:,1].reshape((2,1))*np.transpose(basis_matrix[:,1].reshape((2,1))))\n return R\n \n def program(self):\n R = self.RandUnitary()\n R1 = ns.qubits.operators.Operator(\"R1\", R)\n INSTR_R = instr.IGate(\"R_gate\", R1)\n self.apply(INSTR_R, 0)\n yield self.run()\n \nclass MeasureZ(QuantumProgram):\n# default_num_qubits = 4\n def program(self,mem_pos):\n qubits = self.get_qubit_indices()\n for i in range(len(mem_pos)):\n self.apply(instr.INSTR_MEASURE,qubits[mem_pos[i]], output_key=\"M\"+str(mem_pos[i]))\n yield self.run()\n \nclass MeasureX(QuantumProgram):\n def program(self,mem_pos):\n qubits = self.get_qubit_indices()\n for i in range(len(mem_pos)):\n self.apply(instr.INSTR_H, qubits[mem_pos[i]])\n self.apply(instr.INSTR_MEASURE,qubits[mem_pos[i]], output_key=\"M\"+str(mem_pos[i]))\n yield self.run()",
"_____no_output_____"
],
[
"class InitSend(NodeProtocol):\n def __init__(self, node ,name, num_nodes,list_length):\n super().__init__(node, name)\n self.num_nodes = num_nodes\n self.list_length = list_length\n \n def run(self):\n# print(f\"Simulation start at {ns.sim_time(ns.MILLISECOND)} ms\")\n# print(self.num_nodes)\n# qubit_number = int(np.log2(self.num_nodes))# Qubit number is log2 of number of nodes\n#Init phase\n\n qubit_number = 4\n #Program to initialize the qubits in the memory, input param: number of qubits\n qubit_init_program = InitStateProgram(num_qubits=qubit_number)\n measure_program1 = MeasureZ(num_qubits=qubit_number)\n measure_program2 = MeasureX(num_qubits=qubit_number)\n\n #Variable to store classical and quantum ports\n list_port = [k for k in self.node.ports.keys()]\n list_classic = []\n list_quantum = []\n #Put classical ports in list_classic and quantum ports in list_quantum\n# print(list_port)\n for i in range(len(list_port)):\n if (list_port[i][0] == 'c'):\n list_classic.append(list_port[i])\n else:\n list_quantum.append(list_port[i])\n# print(list_classic)\n# print(list_quantum)\n \n# print(self.node.name[1])\n node_num = int(self.node.name.replace('P','')) # Current Node Number \n \n #Initialize basis count\n basis_sum = 0\n #Initialize loop count for number of state that has been distributed\n k = 0\n \n #Indicator variable for case of valid state (00) measurement\n valid_state = False\n \n #Initialize count for list length\n x = 0\n \n# Program Start \n #Loop For Program\n while True:\n #Init qubits in memory\n# print(\"Loop start\")\n# self.node.qmemory.peek([0,1,2,3])\n self.node.qmemory.execute_program(qubit_init_program)\n \n# print(f\"Node {node_num} init qubit program\")\n# yield self.await_program(self.node.qmemory)\n expr = yield (self.await_program(self.node.qmemory))\n# print(self.node.qmemory.measure())\n #Send 1 qubit to first party\n qubit1 = self.node.qmemory.pop(positions=0)\n self.node.ports[list_quantum[0]].tx_output(qubit1) \n# print(f\"Node {node_num} send qubit to Node {list_quantum[0][-1]}\")\n #Send 1 qubit to second party\n qubit2 = self.node.qmemory.pop(positions=2)\n self.node.ports[list_quantum[1]].tx_output(qubit2)\n \n# print(f\"Node {node_num} send qubit to Node {list_quantum[1][-1]}\")\n \n# Wait for ACK\n i=0\n while (i<=self.num_nodes-2):\n if len(self.node.ports[list_classic[-1-i]].input_queue) != 0:\n# print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n self.node.ports[list_classic[-1-i]].input_queue[0][1].items = []\n# print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n else:\n# print(f\"Node 1 waitting from node {list_classic[-1-i][-1]}\")\n yield self.await_port_input(self.node.ports[list_classic[-1-i]])\n message = self.node.ports[list_classic[-1-i]].rx_input().items[0]\n# print(message)\n i = i+1\n \n #Measure qubit \n c = random.randint(0,1)\n# c = 0\n basis_sum = c\n if c == 0:\n# print(\"Node 1 measure in Z basis\")\n yield self.node.qmemory.execute_program(measure_program1,mem_pos=[1,3])\n# print(\"Node 1 output\")\n# print(measure_program1.output)\n# self.node.qmemory.peek([0,1,2,3])\n \n else:\n# print(\"Node 1 measure in X basis\")\n yield self.node.qmemory.execute_program(measure_program2,mem_pos=[1,3])\n# print(\"Node 1 output\")\n# print(measure_program2.output)\n# self.node.qmemory.peek([0,1,2,3])\n \n \n \n #Wait for basis results\n i=0\n while (i<=self.num_nodes-2):\n# print(f\"Node 1 await from node {list_classic[-1-i][-1]}\")\n yield self.await_port_input(self.node.ports[list_classic[-1-i]])\n message = self.node.ports[list_classic[-1-i]].rx_input().items[0]\n# print(message)\n basis_sum = basis_sum + message\n i = i+1\n \n #Send basis\n self.node.ports[list_classic[0]].tx_output(c)\n self.node.ports[list_classic[1]].tx_output(c)\n \n if (basis_sum % self.num_nodes == 0):\n# print(f\"List record index {x}\")\n if c == 0:\n global_list[x][0] = 1*measure_program1.output[\"M3\"][0] + 2*measure_program1.output[\"M1\"][0]\n else:\n global_list[x][0] = 1*measure_program2.output[\"M3\"][0] + 2*measure_program2.output[\"M1\"][0]\n x = x+1\n basis_sum = 0\n\nclass RecvMeas(NodeProtocol):\n def __init__(self, node ,name, num_nodes,list_length):\n super().__init__(node, name)\n self.num_nodes = num_nodes\n self.list_length = list_length\n \n def run(self):\n# print(f\"Simulation start at {ns.sim_time(ns.MILLISECOND)} ms\")\n# print(self.num_nodes)\n# qubit_number = int(np.log2(self.num_nodes))# Qubit number is log2 of number of nodes\n#Init phase\n\n qubit_number = 1\n #Program to initialize the qubits in the memory, input param: number of qubits\n measure_program1 = MeasureZ(num_qubits=qubit_number)\n measure_program2 = MeasureX(num_qubits=qubit_number)\n \n #Variable to store classical and quantum ports\n list_port = [k for k in self.node.ports.keys()]\n list_classic = []\n list_quantum = []\n #Put classical ports in list_classic and quantum ports in list_quantum\n# print(list_port)\n for i in range(len(list_port)):\n if (list_port[i][0] == 'c'):\n list_classic.append(list_port[i])\n else:\n list_quantum.append(list_port[i])\n\n node_num = int(self.node.name.replace('P','')) # Current Node Number \n# print(list_classic)\n# print(list_quantum)\n #Initialize basis count\n basis_sum = 0\n #Initialize loop count for number of state that has been distributed\n k = 0\n \n #Indicator variable for case of valid state (00) measurement\n valid_state = False\n \n #Initialize count for list length\n x = 0\n \n# Program Start \n #Loop For Program\n while True:\n #Wait for qubit\n yield self.await_port_input(self.node.ports[list_quantum[0]])\n# print(self.node.qmemory.peek([0,1,2,3]))\n# pos = list(range(0, qubit_number)\n #Send ACK\n# print(f\"Node {node_num} send ACK to node {list_classic[0][-1]}\")\n self.node.ports[list_classic[0]].tx_output(\"ACK\")\n# print(f\"Node {node_num} send ACK to node {list_classic[1][-1]}\")\n self.node.ports[list_classic[1]].tx_output(\"ACK\")\n \n #Wait for ACK\n# print(f\"Node {node_num} wait ACK from node {list_classic[1][-1]}\")\n if len(self.node.ports[list_classic[1]].input_queue) != 0:\n# print(\"Queue case ACK\")\n print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n self.node.ports[list_classic[-1-i]].input_queue[0][1].items = []\n print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n else:\n# print(\"No queue case ACK\")\n yield self.await_port_input(self.node.ports[list_classic[1]])\n message = self.node.ports[list_classic[1]].rx_input().items[0]\n# print(message)\n \n #Measure qubit\n c = random.randint(0,1)\n# c = 0\n# print(c)\n if c == 0:\n# print(f\"Node {node_num} measure in Z basis \")\n yield self.node.qmemory.execute_program(measure_program1,mem_pos=[0])\n# print(f\"Node {node_num} output\")\n# print(measure_program1.output)\n# self.node.qmemory.discard(0)\n else:\n# print(f\"Node {node_num} measure in X basis \")\n yield self.node.qmemory.execute_program(measure_program2,mem_pos=[0])\n# print(f\"Node {node_num} output\")\n# print(measure_program2.output)\n# self.node.qmemory.discard(0)\n basis_sum = c\n\n i=0\n while (i<self.num_nodes-1):\n# print(f\"Node {node_num} Loop for basis announcement index: {i}\")\n if (i == (self.num_nodes-node_num)):\n for j in range(self.num_nodes-1):\n self.node.ports[list_classic[j]].tx_output(c)\n# print(f\"Node {node_num} send basis to port {list_classic[j]}\")\n \n# print(f\"Node {node_num} wait basis from port {list_classic[-1-i]}\")\n if len(self.node.ports[list_classic[1]].input_queue) != 0:\n# print(\"Queue case basis\")\n# print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n message = self.node.ports[list_classic[-1-i]].input_queue[0][1].items[0]\n self.node.ports[list_classic[-1-i]].input_queue[0][1].items = []\n# print(message)\n# print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n else:\n# print(\"No queue case basis\")\n yield self.await_port_input(self.node.ports[list_classic[-1-i]])\n message = self.node.ports[list_classic[-1-i]].rx_input().items[0]\n# print(message)\n \n# print(f\"Node {node_num} Received basis from node {list_classic[-1-i][-1]}\")\n# print(message)\n basis_sum = basis_sum + message\n i= i+1\n #Send basis\n# self.node.ports[list_classic[0]].tx_output(c)\n# self.node.ports[list_classic[1]].tx_output(c)\n \n #Record basis\n if (basis_sum % self.num_nodes == 0):\n if c == 0:\n global_list[x][node_num-1] = measure_program1.output[\"M0\"][0]\n else:\n global_list[x][node_num-1] = measure_program2.output[\"M0\"][0]\n basis_sum = 0\n x = x+1\n if (x > self.list_length-1):\n if node_num == 3:\n# print(f\"List distribution ended at: {ns.sim_time(ns.MILLISECOND )} ms\")\n ns.sim_stop()\n# #Send measurement results\n# yield self.await_port_input(self.node.ports[list_classic[0]])\n# message = self.node.ports[list_classic[0]].rx_input().items[0]\n# print(message)\n \nclass RecvMeas1(NodeProtocol):\n def __init__(self, node ,name, num_nodes,list_length):\n super().__init__(node, name)\n self.num_nodes = num_nodes\n self.list_length = list_length\n \n def run(self):\n# print(f\"Simulation start at {ns.sim_time(ns.MILLISECOND)} ms\")\n# print(self.num_nodes)\n# qubit_number = int(np.log2(self.num_nodes))# Qubit number is log2 of number of nodes\n#Init phase\n\n qubit_number = 1\n #Program to initialize the qubits in the memory, input param: number of qubits\n measure_program1 = MeasureZ(num_qubits=qubit_number)\n measure_program2 = MeasureX(num_qubits=qubit_number)\n randU_program = RandUnitary()\n #Variable to store classical and quantum ports\n list_port = [k for k in self.node.ports.keys()]\n list_classic = []\n list_quantum = []\n #Put classical ports in list_classic and quantum ports in list_quantum\n# print(list_port)\n for i in range(len(list_port)):\n if (list_port[i][0] == 'c'):\n list_classic.append(list_port[i])\n else:\n list_quantum.append(list_port[i])\n\n node_num = int(self.node.name.replace('P','')) # Current Node Number \n# print(list_classic)\n# print(list_quantum)\n #Initialize basis count\n basis_sum = 0\n #Initialize loop count for number of state that has been distributed\n k = 0\n \n #Indicator variable for case of valid state (00) measurement\n valid_state = False\n \n #Initialize count for list length\n x = 0\n \n# Program Start \n #Loop For Program\n while True:\n #Wait for qubit\n yield self.await_port_input(self.node.ports[list_quantum[0]])\n# print(self.node.qmemory.peek([0,1,2,3]))\n# pos = list(range(0, qubit_number)\n #Send ACK\n# print(f\"Node {node_num} send ACK to node {list_classic[0][-1]}\")\n self.node.ports[list_classic[0]].tx_output(\"ACK\")\n# print(f\"Node {node_num} send ACK to node {list_classic[1][-1]}\")\n self.node.ports[list_classic[1]].tx_output(\"ACK\")\n \n #Wait for ACK\n# print(f\"Node {node_num} wait ACK from node {list_classic[1][-1]}\")\n if len(self.node.ports[list_classic[1]].input_queue) != 0:\n# print(\"Queue case ACK\")\n print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n self.node.ports[list_classic[-1-i]].input_queue[0][1].items = []\n print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n else:\n# print(\"No queue case ACK\")\n yield self.await_port_input(self.node.ports[list_classic[1]])\n message = self.node.ports[list_classic[1]].rx_input().items[0]\n# print(message)\n yield self.node.qmemory.execute_program(randU_program)\n #Measure qubit\n c = random.randint(0,1)\n# c = 0\n# print(c)\n if c == 0:\n# print(f\"Node {node_num} measure in Z basis \")\n yield self.node.qmemory.execute_program(measure_program1,mem_pos=[0])\n# print(f\"Node {node_num} output\")\n# print(measure_program1.output)\n# self.node.qmemory.discard(0)\n else:\n# print(f\"Node {node_num} measure in X basis \")\n yield self.node.qmemory.execute_program(measure_program2,mem_pos=[0])\n# print(f\"Node {node_num} output\")\n# print(measure_program2.output)\n# self.node.qmemory.discard(0)\n basis_sum = c\n\n i=0\n while (i<self.num_nodes-1):\n# print(f\"Node {node_num} Loop for basis announcement index: {i}\")\n if (i == (self.num_nodes-node_num)):\n for j in range(self.num_nodes-1):\n self.node.ports[list_classic[j]].tx_output(c)\n# print(f\"Node {node_num} send basis to port {list_classic[j]}\")\n \n# print(f\"Node {node_num} wait basis from port {list_classic[-1-i]}\")\n if len(self.node.ports[list_classic[1]].input_queue) != 0:\n# print(\"Queue case basis\")\n# print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n message = self.node.ports[list_classic[-1-i]].input_queue[0][1].items[0]\n self.node.ports[list_classic[-1-i]].input_queue[0][1].items = []\n# print(message)\n# print(self.node.ports[list_classic[-1-i]].input_queue[0][1].items)\n else:\n# print(\"No queue case basis\")\n yield self.await_port_input(self.node.ports[list_classic[-1-i]])\n message = self.node.ports[list_classic[-1-i]].rx_input().items[0]\n# print(message)\n \n# print(f\"Node {node_num} Received basis from node {list_classic[-1-i][-1]}\")\n# print(message)\n basis_sum = basis_sum + message\n i= i+1\n #Send basis\n# self.node.ports[list_classic[0]].tx_output(c)\n# self.node.ports[list_classic[1]].tx_output(c)\n \n #Record basis\n if (basis_sum % self.num_nodes == 0):\n if c == 0:\n global_list[x][node_num-1] = measure_program1.output[\"M0\"][0]\n else:\n global_list[x][node_num-1] = measure_program2.output[\"M0\"][0]\n basis_sum = 0\n x = x+1\n if (x > self.list_length-1):\n if node_num == 3:\n# print(f\"List distribution ended at: {ns.sim_time(ns.MILLISECOND )} ms\")\n ns.sim_stop()\n# #Send measurement results\n# yield self.await_port_input(self.node.ports[list_classic[0]])\n# message = self.node.ports[list_classic[0]].rx_input().items[0]\n# print(message)\n \n ",
"_____no_output_____"
],
[
"from netsquid.nodes import Network\ndef example_network_setup(num_nodes,prob,node_distance=4e-3):\n# print(\"Network Setup\")\n nodes =[]\n i = 1\n while i<=(num_nodes):\n if i == 0:\n# nodes.append(Node(f\"P{i}\",qmemory = create_processor1(prob)))\n nodes.append(Node(f\"P{i}\",qmemory = create_processor()))\n else:\n nodes.append(Node(f\"P{i}\",qmemory = create_processor()))\n \n i= i+1\n \n # Create a network\n network = Network(\"List Distribution Network\")\n# print(nodes)\n network.add_nodes(nodes)\n# print(\"Nodes completed\")\n i = 1\n while i< (num_nodes):\n node = nodes[i-1]\n j = 1\n while j<=(num_nodes-i):\n node_next = nodes[i+j-1]\n c_conn = ClassicalBiConnection(name =f\"c_conn{i}{i+j}\", length = node_distance)\n network.add_connection(node,node_next, connection= c_conn, label=\"classical\", \n port_name_node1 = f\"cio_node_port{i}{i+j}\", port_name_node2 = f\"cio_node_port{i+j}{i}\")\n j = j+1\n i = i+1\n# prob = 0\n# print(\"Classical Conn Completed\")\n q_conn = QuantumConnection(name=f\"qconn_{1}{2}\", length=node_distance,prob=prob)\n network.add_connection(nodes[0], nodes[1], connection=q_conn, label=\"quantum\", port_name_node1 = f\"qo_node_port{1}{2}\", port_name_node2=f\"qin_node_port{2}{1}\")\n q_conn = QuantumConnection(name=f\"qconn_{1}{3}\", length=node_distance,prob=prob)\n network.add_connection(nodes[0], nodes[2], connection=q_conn, label=\"quantum\", port_name_node1 = f\"qo_node_port{1}{3}\", port_name_node2=f\"qin_node_port{3}{1}\")\n \n\n\n i = 2\n while i<=(num_nodes):\n nodes[i-1].ports[f\"qin_node_port{i}{1}\"].forward_input(nodes[i-1].qmemory.ports['qin'])\n i = i+1\n# print(\"End Network Setup\")\n \n return network",
"_____no_output_____"
],
[
"def setup_protocol(network,nodes_num,fault_num,list_length):\n# print(\"Setup Protocol\")\n \n protocol = LocalProtocol(nodes=network.nodes)\n nodes = []\n i = 1\n while i<=(nodes_num):\n nodes.append(network.get_node(\"P\"+str(i)))\n i = i+1\n# print(nodes)\n\n \n subprotocol = InitSend(node=nodes[0],name=f\"Init_Send{nodes[0].name}\",num_nodes=nodes_num,list_length=list_length)\n# subprotocol = FaultyInitSend(node=nodes[0],name=f\"Faulty Init_Send{nodes[0].name}\",num_nodes=nodes_num,list_length=list_length)\n protocol.add_subprotocol(subprotocol)\n \n #Uncomment first line for normal phase reference, uncomment second line for phase reference error\n subprotocol = RecvMeas(node=nodes[1], name=f\"Receive_Measure{nodes[1].name}\",num_nodes=nodes_num,list_length=list_length)\n# subprotocol = RecvMeas1(node=nodes[1], name=f\"Receive_Measure{nodes[1].name}\",num_nodes=nodes_num,list_length=list_length)\n \n protocol.add_subprotocol(subprotocol)\n subprotocol = RecvMeas(node=nodes[2], name=f\"Receive_Measure{nodes[2].name}\",num_nodes=nodes_num,list_length=list_length)\n protocol.add_subprotocol(subprotocol)\n return protocol\n",
"_____no_output_____"
],
[
"# Time Data Collection\n\n\nfrom netsquid.util.simtools import set_random_state\nimport pandas as pd\n\n# set up initial parameters\nnodes_num = 3 #Node numbers\n\nfault_num = 0 #Faulty node numbers\nexp_number = 1 #Experiment numbers\nprobs = np.linspace(0, 1, num=100)\n# print(probs)\nexp_number = len(probs)\nlist_length = 100 #List length\nerror_array = np.ndarray(shape=(exp_number,2))\ntime_array = np.ndarray(shape=(exp_number,))\nglobal_list = np.ndarray(shape=(list_length,nodes_num), dtype='i')\nx=0\nns.sim_reset()\nnetwork = example_network_setup(nodes_num,0,node_distance=4)\nprotocol = setup_protocol(network,nodes_num,fault_num,list_length)\nprotocol.start()\nstats = ns.sim_run()\n# protocol = setup_protocol(network,nodes_num,fault_num,list_length)\naverage = 100\nwhile x < len(probs):\n\n global_list = np.ndarray(shape=(list_length,nodes_num), dtype='i')\n error_sum = 0\n for z in range (average):\n ns.sim_reset()\n network = example_network_setup(nodes_num,probs[x],node_distance=4)\n protocol = setup_protocol(network,nodes_num,fault_num,list_length)\n protocol.start()\n stats = ns.sim_run()\n\n if (ns.sim_state() == 2):\n# print(f\"Sim end time: {ns.sim_time()}\")\n valid_sum = 0\n for i in range(global_list.shape[0]-1):\n if ((global_list[i][0] == (global_list[i][1]*2+global_list[i][2]))):\n valid_sum = valid_sum+1\n # percentage_correct = (valid_sum/(global_list.shape[0]-1)) * 100\n percentage_correct = (valid_sum/(global_list.shape[0]-1))\n error_ratio = 1-percentage_correct\n error_sum = error_sum + error_ratio\n \n print(f\"Error Prob = {probs[x]} Average Ratio of Error List:{error_sum/average}\")\n error_array[x][0] = probs[x]\n error_array[x][1] = error_sum/average\n x = x+1\n\n",
"Error Prob = 0.0 Average Ratio of Error List:0.0\nError Prob = 0.010101010101010102 Average Ratio of Error List:0.008383838383838372\nError Prob = 0.020202020202020204 Average Ratio of Error List:0.02151515151515149\nError Prob = 0.030303030303030304 Average Ratio of Error List:0.026363636363636356\nError Prob = 0.04040404040404041 Average Ratio of Error List:0.04040404040404041\nError Prob = 0.05050505050505051 Average Ratio of Error List:0.04858585858585859\nError Prob = 0.06060606060606061 Average Ratio of Error List:0.057373737373737355\nError Prob = 0.07070707070707072 Average Ratio of Error List:0.06838383838383837\nError Prob = 0.08080808080808081 Average Ratio of Error List:0.08141414141414138\nError Prob = 0.09090909090909091 Average Ratio of Error List:0.08939393939393944\nError Prob = 0.10101010101010102 Average Ratio of Error List:0.09222222222222219\nError Prob = 0.11111111111111112 Average Ratio of Error List:0.1015151515151515\nError Prob = 0.12121212121212122 Average Ratio of Error List:0.11343434343434346\nError Prob = 0.13131313131313133 Average Ratio of Error List:0.12010101010101008\nError Prob = 0.14141414141414144 Average Ratio of Error List:0.12838383838383838\nError Prob = 0.15151515151515152 Average Ratio of Error List:0.1364646464646465\nError Prob = 0.16161616161616163 Average Ratio of Error List:0.14666666666666667\nError Prob = 0.17171717171717174 Average Ratio of Error List:0.15262626262626264\nError Prob = 0.18181818181818182 Average Ratio of Error List:0.1644444444444445\nError Prob = 0.19191919191919193 Average Ratio of Error List:0.1738383838383839\nError Prob = 0.20202020202020204 Average Ratio of Error List:0.17919191919191926\nError Prob = 0.21212121212121213 Average Ratio of Error List:0.1880808080808081\nError Prob = 0.22222222222222224 Average Ratio of Error List:0.19474747474747459\nError Prob = 0.23232323232323235 Average Ratio of Error List:0.20454545454545456\nError Prob = 0.24242424242424243 Average Ratio of Error List:0.20989898989898992\nError Prob = 0.25252525252525254 Average Ratio of Error List:0.22696969696969685\nError Prob = 0.26262626262626265 Average Ratio of Error List:0.22707070707070695\nError Prob = 0.27272727272727276 Average Ratio of Error List:0.23363636363636353\nError Prob = 0.2828282828282829 Average Ratio of Error List:0.23797979797979799\nError Prob = 0.29292929292929293 Average Ratio of Error List:0.25131313131313127\nError Prob = 0.30303030303030304 Average Ratio of Error List:0.25808080808080797\nError Prob = 0.31313131313131315 Average Ratio of Error List:0.2631313131313131\nError Prob = 0.32323232323232326 Average Ratio of Error List:0.27030303030303027\nError Prob = 0.33333333333333337 Average Ratio of Error List:0.27666666666666667\nError Prob = 0.3434343434343435 Average Ratio of Error List:0.27929292929292937\nError Prob = 0.3535353535353536 Average Ratio of Error List:0.2925252525252525\nError Prob = 0.36363636363636365 Average Ratio of Error List:0.292828282828283\nError Prob = 0.37373737373737376 Average Ratio of Error List:0.3023232323232323\nError Prob = 0.38383838383838387 Average Ratio of Error List:0.31989898989898985\nError Prob = 0.393939393939394 Average Ratio of Error List:0.3179797979797979\nError Prob = 0.4040404040404041 Average Ratio of Error List:0.317979797979798\nError Prob = 0.4141414141414142 Average Ratio of Error List:0.335959595959596\nError Prob = 0.42424242424242425 Average Ratio of Error List:0.3347474747474748\nError Prob = 0.43434343434343436 Average Ratio of Error List:0.34131313131313135\nError Prob = 0.4444444444444445 Average Ratio of Error List:0.34868686868686877\nError Prob = 0.4545454545454546 Average Ratio of Error List:0.3589898989898989\nError Prob = 0.4646464646464647 Average Ratio of Error List:0.3453535353535353\nError Prob = 0.4747474747474748 Average Ratio of Error List:0.3573737373737373\nError Prob = 0.48484848484848486 Average Ratio of Error List:0.3701010101010101\nError Prob = 0.494949494949495 Average Ratio of Error List:0.376969696969697\nError Prob = 0.5050505050505051 Average Ratio of Error List:0.38070707070707044\nError Prob = 0.5151515151515152 Average Ratio of Error List:0.3827272727272726\nError Prob = 0.5252525252525253 Average Ratio of Error List:0.3917171717171717\nError Prob = 0.5353535353535354 Average Ratio of Error List:0.39525252525252513\nError Prob = 0.5454545454545455 Average Ratio of Error List:0.3998989898989897\nError Prob = 0.5555555555555556 Average Ratio of Error List:0.4019191919191919\nError Prob = 0.5656565656565657 Average Ratio of Error List:0.4118181818181814\nError Prob = 0.5757575757575758 Average Ratio of Error List:0.4119191919191917\nError Prob = 0.5858585858585859 Average Ratio of Error List:0.41454545454545416\nError Prob = 0.595959595959596 Average Ratio of Error List:0.408989898989899\nError Prob = 0.6060606060606061 Average Ratio of Error List:0.42202020202020185\nError Prob = 0.6161616161616162 Average Ratio of Error List:0.4292929292929292\nError Prob = 0.6262626262626263 Average Ratio of Error List:0.4231313131313128\nError Prob = 0.6363636363636365 Average Ratio of Error List:0.4371717171717169\nError Prob = 0.6464646464646465 Average Ratio of Error List:0.43575757575757557\nError Prob = 0.6565656565656566 Average Ratio of Error List:0.4459595959595958\nError Prob = 0.6666666666666667 Average Ratio of Error List:0.44454545454545424\nError Prob = 0.6767676767676768 Average Ratio of Error List:0.4463636363636361\nError Prob = 0.686868686868687 Average Ratio of Error List:0.46060606060606024\nError Prob = 0.696969696969697 Average Ratio of Error List:0.45919191919191904\nError Prob = 0.7070707070707072 Average Ratio of Error List:0.45838383838383817\nError Prob = 0.7171717171717172 Average Ratio of Error List:0.46474747474747446\nError Prob = 0.7272727272727273 Average Ratio of Error List:0.4643434343434341\nError Prob = 0.7373737373737375 Average Ratio of Error List:0.46797979797979766\nError Prob = 0.7474747474747475 Average Ratio of Error List:0.47404040404040393\nError Prob = 0.7575757575757577 Average Ratio of Error List:0.4702020202020199\nError Prob = 0.7676767676767677 Average Ratio of Error List:0.4676767676767674\nError Prob = 0.7777777777777778 Average Ratio of Error List:0.4674747474747474\nError Prob = 0.787878787878788 Average Ratio of Error List:0.47838383838383824\nError Prob = 0.797979797979798 Average Ratio of Error List:0.479191919191919\nError Prob = 0.8080808080808082 Average Ratio of Error List:0.48202020202020196\nError Prob = 0.8181818181818182 Average Ratio of Error List:0.479292929292929\nError Prob = 0.8282828282828284 Average Ratio of Error List:0.48848484848484847\nError Prob = 0.8383838383838385 Average Ratio of Error List:0.4863636363636363\nError Prob = 0.8484848484848485 Average Ratio of Error List:0.4877777777777777\nError Prob = 0.8585858585858587 Average Ratio of Error List:0.488989898989899\nError Prob = 0.8686868686868687 Average Ratio of Error List:0.4901010101010101\nError Prob = 0.8787878787878789 Average Ratio of Error List:0.4898989898989899\nError Prob = 0.888888888888889 Average Ratio of Error List:0.4919191919191918\nError Prob = 0.8989898989898991 Average Ratio of Error List:0.4977777777777777\nError Prob = 0.9090909090909092 Average Ratio of Error List:0.5033333333333334\nError Prob = 0.9191919191919192 Average Ratio of Error List:0.4929292929292929\nError Prob = 0.9292929292929294 Average Ratio of Error List:0.5017171717171718\nError Prob = 0.9393939393939394 Average Ratio of Error List:0.5024242424242424\nError Prob = 0.9494949494949496 Average Ratio of Error List:0.5083838383838384\nError Prob = 0.9595959595959597 Average Ratio of Error List:0.49838383838383843\nError Prob = 0.9696969696969697 Average Ratio of Error List:0.5008080808080809\nError Prob = 0.9797979797979799 Average Ratio of Error List:0.49838383838383826\nError Prob = 0.98989898989899 Average Ratio of Error List:0.4903030303030303\nError Prob = 1.0 Average Ratio of Error List:0.4990909090909091\n"
],
[
"# print(global_list)\n# print(error_array)\nerror_data = pd.DataFrame(data = error_array,columns = ['error probability','Error List Ratio'])\nprint(error_data)\nerror_data.to_csv('QKD_DephaseChannel_100avrg.csv')",
" error probability Error List Ratio\n0 0.000000 0.000000\n1 0.010101 0.008384\n2 0.020202 0.021515\n3 0.030303 0.026364\n4 0.040404 0.040404\n.. ... ...\n95 0.959596 0.498384\n96 0.969697 0.500808\n97 0.979798 0.498384\n98 0.989899 0.490303\n99 1.000000 0.499091\n\n[100 rows x 2 columns]\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7aae4d0619be0da0ffe8a19e63581d64c25c4f6 | 296,150 | ipynb | Jupyter Notebook | 2 Regression/2.3 support vector regression/SVR.ipynb | jordihasianta/DS_Kitchen | 8b5a230389bb76074369eac2c16b0cca59ae6082 | [
"MIT"
] | null | null | null | 2 Regression/2.3 support vector regression/SVR.ipynb | jordihasianta/DS_Kitchen | 8b5a230389bb76074369eac2c16b0cca59ae6082 | [
"MIT"
] | null | null | null | 2 Regression/2.3 support vector regression/SVR.ipynb | jordihasianta/DS_Kitchen | 8b5a230389bb76074369eac2c16b0cca59ae6082 | [
"MIT"
] | null | null | null | 722.317073 | 226,404 | 0.949208 | [
[
[
"# SUPPORT VECTOR REGRESSION\n\nSupport Vector Regression(SVR) adalah teknik Supervised Learning yang mengadopsi teknik Support Vector Machine(SVM). Yang membedakan adalah SVR menggunakan hyperplane sebagai dasar untuk membuat margin dan garis pembatas.\n\nApakah yang membedakan SVR dengan regresi linear?\n<br>Pada regresi linear, kita membuat model berdasarkan perhitungan error yang paling kecil. Sedangkan pada SVR, kita membatasi error pada treshold tertentu.\n\nUntuk lebih jelasnya perhatikan gambar berikut.",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"biru: hyperplane<br>\nmerah: garis pembatas",
"_____no_output_____"
],
[
"Pada gambar diatas, terlihat bahwa data-data point terletak di dalam garis pembatas. Prinsip algoritma SVR dalam menentukan hyperplane adalah memperhitungkan jumlah data point yang terletak di dalam garis pembatas. Jadi garis prediksi yang terbaik adalah hyperplane yang mempunyai data point terbanyak dalam garis pembatas.",
"_____no_output_____"
],
[
"Garis pembatas $\\epsilon$ bisa kita tentukan sendiri dalam merancang model SVR. Sebagai contoh, misalkan kita mempunyai hyperplane dengan persamaan sebagai berikut.\n\n$Wx + b = 0$\n\nMaka persamaan garis pembatas berdasarkan hyperplane diatas adalah:<br>\n$Wx + b = \\epsilon$\n<br>$Wx + b = -\\epsilon$\n\nJadi, data point yang akan dihitung sebagai penentuan model SVR, akan memenuhi persamaan dibawah ini.<br>\n$-\\epsilon \\leq y - Wx + b\\leq \\epsilon $",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"# CODING SECTION",
"_____no_output_____"
],
[
"Misalkan kita ingin menganalisa tingkat kejujuran calon karyawan baru. pada pekerjaan yang dia ingin lamar, dia menceritakan bahwa sudah memiliki pengalaman di pekerjaan tersebut selama 16 tahun dan mempunyai gaji sebesar 20 juta rupiah di perusahaan sebelumnya. Kita ingin melakukan pengecekan terhadap pernyataan calon karyawan tersebut. kita melakukan pengecekan terhadap data-data karyawan yang bekerja di bidang yang sama, yang sudah kita ambil dari situs pencarian kerja. Data dibawah ini adalah data gaji karyawan-karyawan terhadap lama pengalaman mereka bekerja.",
"_____no_output_____"
]
],
[
[
"import numpy as np #aljabar linear\nimport pandas as pd #pengolahan data\nimport matplotlib.pyplot as plt #visualisasi\nimport warnings\nwarnings.filterwarnings(\"ignore\")",
"_____no_output_____"
],
[
"df = pd.read_csv('salary.csv') #membaca data",
"_____no_output_____"
],
[
"df.head(10)",
"_____no_output_____"
],
[
"#mengubah data menjadi array agar bisa dilakukan proses machine learning\nX = df.pengalaman.values.reshape(-1,1) \ny = df.gaji.values",
"_____no_output_____"
],
[
"#Memisah data untuk proses data latih dan data uji\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 1/4, random_state = 42)",
"_____no_output_____"
],
[
"#import algoritma dari scikit-learn\nfrom sklearn.svm import SVR\nmodel = SVR(gamma = 'auto', kernel='rbf')\n#memuat machine learning terhadap data latih\nmodel.fit(X, y)",
"_____no_output_____"
]
],
[
[
"# Visualisasi",
"_____no_output_____"
]
],
[
[
"# data latih\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X_train, y_train, color = 'red')\nplt.plot(X_grid, model.predict(X_grid), color = 'blue')\nplt.title('Gaji vs Pengalaman (Training Set)')\nplt.xlabel('pengalaman')\nplt.ylabel('gaji')\nplt.show()",
"_____no_output_____"
],
[
"#data uji\n\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X_test, y_test, color = 'red')\nplt.plot(X_grid, model.predict(X_grid), color = 'blue')\nplt.title('Gaji vs Pengalaman (Test set)')\nplt.xlabel('pengalaman')\nplt.ylabel('gaji')\nplt.show()",
"_____no_output_____"
],
[
"model.predict(np.array(16).reshape(1,-1))\n",
"_____no_output_____"
]
],
[
[
"# Kesimpulan\n\nSVR menghasilkan prediksi yang lebih akurat dari regresi linear. Selain itu, SVR mempunyai banyak parameter yang bisa disetel, sehingga bisa lebih menyesuaikan terhadap penyebaran dataset, seperti masalah non-linear. Namun, harus diperhatikan dalam masalah non-linear problem dan pemilihan kernel seperti rbf, algoritma SVR akan menjadi lebih kompleks dan sulit diinterpretasikan. SVR juga mempunyai masalah dalam waktu komputasi/training yang cukup lama dalam masalah non-linear.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7ab1043a2cb4229865f42fcf9d3361e4304ea98 | 67,346 | ipynb | Jupyter Notebook | demos/Locus Number of Spacers Analysis.ipynb | nataliyah123/phageParser | bc05d76c23d37ee80ffa2bbf6e7e977341bab3ee | [
"MIT"
] | 65 | 2017-05-10T15:26:18.000Z | 2022-03-07T07:10:12.000Z | demos/Locus Number of Spacers Analysis.ipynb | nataliyah123/phageParser | bc05d76c23d37ee80ffa2bbf6e7e977341bab3ee | [
"MIT"
] | 143 | 2017-03-22T22:55:16.000Z | 2020-02-13T15:52:03.000Z | demos/Locus Number of Spacers Analysis.ipynb | nataliyah123/phageParser | bc05d76c23d37ee80ffa2bbf6e7e977341bab3ee | [
"MIT"
] | 44 | 2017-03-22T20:47:16.000Z | 2022-03-15T21:45:12.000Z | 326.92233 | 33,206 | 0.921777 | [
[
[
"# phageParser - Distribution of Number of Spacers per Locus",
"_____no_output_____"
],
[
"C.K. Yildirim ([email protected])\n\nThe latest version of this [IPython notebook](http://ipython.org/notebook.html) demo is available at [http://github.com/phageParser/phageParser](https://github.com/phageParser/phageParser/tree/django-dev/demos)\n\nTo run this notebook locally:\n* `git clone` or [download](https://github.com/phageParser/phageParser/archive/master.zip) this repository\n* Install [Jupyter Notebook](http://jupyter.org/install.html)\n* In a command prompt, type `jupyter notebook` - the notebook server will launch in your browser\n* Navigate to the phageParser/demos folder and open the notebook",
"_____no_output_____"
],
[
"## Introduction",
"_____no_output_____"
],
[
"This demo uses the REST API of phageParser to plot the distribution of number of spacers for CRISPR loci.\nIn this case, the API is consumed using the `requests` library and the json responses are parsed for gathering\nnumber of spacers for each locus.",
"_____no_output_____"
]
],
[
[
"# import packages\nimport requests\nimport json\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom matplotlib import mlab\nimport seaborn as sns\nimport pandas as pd\nfrom scipy import stats\nsns.set_palette(\"husl\")",
"_____no_output_____"
],
[
"#Url of the phageParser API\napiurl = 'https://phageparser.herokuapp.com'\n#Get the initial page for listing of accessible objects and get url for spacers\nr=requests.get(apiurl)\norganisms_url = r.json()['organisms']",
"_____no_output_____"
],
[
"#Iterate through each page and merge the json response into a dictionary for organisms\norganism_dict = {}\nr=requests.get(organisms_url)\nlast_page = r.json()['meta']['total_pages']\nfor page in range(1,last_page+1):\n url = organisms_url+'?page={}&include[]=loci.spacers'.format(page)\n payload = requests.get(url).json()\n organism_objs = payload['organisms']\n for organism_obj in organism_objs:\n organism_dict[organism_obj['id']] = organism_obj",
"_____no_output_____"
],
[
"#Calculate the number of spacers for each locus\nlocus_num_spacer = np.array([ len(loc['spacers']) for v in organism_dict.values() for loc in v['loci']])\n#Calculate the mean and standard deviation for spacer basepair lengths\nmu, sigma = locus_num_spacer.mean(), locus_num_spacer.std()\nprint(\"Calculated mean basepair length for spacers is {:.2f}+/-{:.2f}\".format(mu,sigma))",
"Calculated mean basepair length for spacers is 18.17+/-27.07\n"
],
[
"g=sns.distplot(locus_num_spacer,bins=range(0,600,1),kde=False)\ng.set(yscale=\"log\")\ng.set_ylim(8*10**-1,1.1*10**3)\ng.set_title(\"Histogram of number of spacers per locus\")\ng.set_xlabel(\"Number of spacers\")\ng.set_ylabel(\"Number of loci\")\nplt.show()",
"_____no_output_____"
],
[
"#Plot cumulative probability of data\nfig, ax = plt.subplots(figsize=(8,4), dpi=100)\nsorted_data = np.sort(locus_num_spacer)\nax.step(sorted_data, np.arange(sorted_data.size), label='Empirical')\n\n#Format the figure and label\nax.grid(True)\n#ax.set_title('Cumulative distribution of locus sizes')\nax.set_xlabel(\"Number of spacers\")\nax.set_ylabel(\"Fraction of loci with x or fewer spacers\")\nax.set_xlim(1,500)\nax.set_xscale('log')\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ab282aeaaafc7e4fd7ffa431cdf36663ea7a03 | 107,752 | ipynb | Jupyter Notebook | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch | a30f40d15f99a327c0ce0f356d7670724f89cdaa | [
"MIT"
] | null | null | null | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch | a30f40d15f99a327c0ce0f356d7670724f89cdaa | [
"MIT"
] | 5 | 2020-09-26T01:10:18.000Z | 2022-02-10T01:43:51.000Z | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch | a30f40d15f99a327c0ce0f356d7670724f89cdaa | [
"MIT"
] | null | null | null | 127.51716 | 75,872 | 0.82302 | [
[
[
"# Your first neural network\n\nIn this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and the model more.\n\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"## Load and prepare the data\n\nA critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon!",
"_____no_output_____"
]
],
[
[
"data_path = 'Bike-Sharing-Dataset/hour.csv'\n\nrides = pd.read_csv(data_path)",
"_____no_output_____"
],
[
"rides.head()",
"_____no_output_____"
]
],
[
[
"## Checking out the data\n\nThis dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.\n\nBelow is a plot showing the number of bike riders over the first 10 days or so in the data set. (Some days don't have exactly 24 entries in the data set, so it's not exactly 10 days.) You can see the hourly rentals here. This data is pretty complicated! The weekends have lower over all ridership and there are spikes when people are biking to and from work during the week. Looking at the data above, we also have information about temperature, humidity, and windspeed, all of these likely affecting the number of riders. You'll be trying to capture all this with your model.",
"_____no_output_____"
]
],
[
[
"rides[:24*10].plot(x='dteday', y='cnt')",
"_____no_output_____"
]
],
[
[
"### Dummy variables\nHere we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`.",
"_____no_output_____"
]
],
[
[
"dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']\nfor each in dummy_fields:\n dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)\n rides = pd.concat([rides, dummies], axis=1)\n\nfields_to_drop = ['instant', 'dteday', 'season', 'weathersit', \n 'weekday', 'atemp', 'mnth', 'workingday', 'hr']\ndata = rides.drop(fields_to_drop, axis=1)\ndata.head()",
"_____no_output_____"
]
],
[
[
"### Scaling target variables\nTo make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.\n\nThe scaling factors are saved so we can go backwards when we use the network for predictions.",
"_____no_output_____"
]
],
[
[
"quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']\n# Store scalings in a dictionary so we can convert back later\nscaled_features = {}\nfor each in quant_features:\n mean, std = data[each].mean(), data[each].std()\n scaled_features[each] = [mean, std]\n data.loc[:, each] = (data[each] - mean)/std",
"_____no_output_____"
]
],
[
[
"### Splitting the data into training, testing, and validation sets\n\nWe'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders.",
"_____no_output_____"
]
],
[
[
"# Save data for approximately the last 21 days \ntest_data = data[-21*24:]\n\n# Now remove the test data from the data set \ndata = data[:-21*24]\n\n# Separate the data into features and targets\ntarget_fields = ['cnt', 'casual', 'registered']\nfeatures, targets = data.drop(target_fields, axis=1), data[target_fields]\ntest_features, test_targets = test_data.drop(target_fields, axis=1), test_data[target_fields]",
"_____no_output_____"
]
],
[
[
"We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set).",
"_____no_output_____"
]
],
[
[
"# Hold out the last 60 days or so of the remaining data as a validation set\ntrain_features, train_targets = features[:-60*24], targets[:-60*24]\nval_features, val_targets = features[-60*24:], targets[-60*24:]",
"_____no_output_____"
]
],
[
[
"## Time to build the network\n\nBelow you'll build your network. We've built out the structure. You'll implement both the forward pass and backwards pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.\n\n<img src=\"assets/neural_network.png\" width=300px>\n\nThe network has two layers, a hidden layer and an output layer. The hidden layer will use the sigmoid function for activations. The output layer has only one node and is used for the regression, the output of the node is the same as the input of the node. That is, the activation function is $f(x)=x$. A function that takes the input signal and generates an output signal, but takes into account the threshold, is called an activation function. We work through each layer of our network calculating the outputs for each neuron. All of the outputs from one layer become inputs to the neurons on the next layer. This process is called *forward propagation*.\n\nWe use the weights to propagate signals forward from the input to the output layers in a neural network. We use the weights to also propagate error backwards from the output back into the network to update our weights. This is called *backpropagation*.\n\n> **Hint:** You'll need the derivative of the output activation function ($f(x) = x$) for the backpropagation implementation. If you aren't familiar with calculus, this function is equivalent to the equation $y = x$. What is the slope of that equation? That is the derivative of $f(x)$.\n\nBelow, you have these tasks:\n1. Implement the sigmoid function to use as the activation function. Set `self.activation_function` in `__init__` to your sigmoid function.\n2. Implement the forward pass in the `train` method.\n3. Implement the backpropagation algorithm in the `train` method, including calculating the output error.\n4. Implement the forward pass in the `run` method.\n ",
"_____no_output_____"
]
],
[
[
"#############\n# In the my_answers.py file, fill out the TODO sections as specified\n#############\n\nfrom my_answers import NeuralNetwork",
"_____no_output_____"
],
[
"def MSE(y, Y):\n return np.mean((y-Y)**2)",
"_____no_output_____"
]
],
[
[
"## Unit tests\n\nRun these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly befor you starting trying to train it. These tests must all be successful to pass the project.",
"_____no_output_____"
]
],
[
[
"import unittest\n\ninputs = np.array([[0.5, -0.2, 0.1]])\ntargets = np.array([[0.4]])\ntest_w_i_h = np.array([[0.1, -0.2],\n [0.4, 0.5],\n [-0.3, 0.2]])\ntest_w_h_o = np.array([[0.3],\n [-0.1]])\n\nclass TestMethods(unittest.TestCase):\n \n ##########\n # Unit tests for data loading\n ##########\n \n def test_data_path(self):\n # Test that file path to dataset has been unaltered\n self.assertTrue(data_path.lower() == 'bike-sharing-dataset/hour.csv')\n \n def test_data_loaded(self):\n # Test that data frame loaded\n self.assertTrue(isinstance(rides, pd.DataFrame))\n \n ##########\n # Unit tests for network functionality\n ##########\n\n def test_activation(self):\n network = NeuralNetwork(3, 2, 1, 0.5)\n # Test that the activation function is a sigmoid\n self.assertTrue(np.all(network.activation_function(0.5) == 1/(1+np.exp(-0.5))))\n\n def test_train(self):\n # Test that weights are updated correctly on training\n network = NeuralNetwork(3, 2, 1, 0.5)\n network.weights_input_to_hidden = test_w_i_h.copy()\n network.weights_hidden_to_output = test_w_h_o.copy()\n \n network.train(inputs, targets)\n self.assertTrue(np.allclose(network.weights_hidden_to_output, \n np.array([[ 0.37275328], \n [-0.03172939]])))\n self.assertTrue(np.allclose(network.weights_input_to_hidden,\n np.array([[ 0.10562014, -0.20185996], \n [0.39775194, 0.50074398], \n [-0.29887597, 0.19962801]])))\n\n def test_run(self):\n # Test correctness of run method\n network = NeuralNetwork(3, 2, 1, 0.5)\n network.weights_input_to_hidden = test_w_i_h.copy()\n network.weights_hidden_to_output = test_w_h_o.copy()\n\n self.assertTrue(np.allclose(network.run(inputs), 0.09998924))\n\nsuite = unittest.TestLoader().loadTestsFromModule(TestMethods())\nunittest.TextTestRunner().run(suite)",
"_____no_output_____"
]
],
[
[
"## Training the network\n\nHere you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training set and will fail to generalize to the validation set. That is, the loss on the validation set will start increasing as the training set loss drops.\n\nYou'll also be using a method know as Stochastic Gradient Descent (SGD) to train the network. The idea is that for each training pass, you grab a random sample of the data instead of using the whole data set. You use many more training passes than with normal gradient descent, but each pass is much faster. This ends up training the network more efficiently. You'll learn more about SGD later.\n\n### Choose the number of iterations\nThis is the number of batches of samples from the training data we'll use to train the network. The more iterations you use, the better the model will fit the data. However, this process can have sharply diminishing returns and can waste computational resources if you use too many iterations. You want to find a number here where the network has a low training loss, and the validation loss is at a minimum. The ideal number of iterations would be a level that stops shortly after the validation loss is no longer decreasing.\n\n### Choose the learning rate\nThis scales the size of weight updates. If this is too big, the weights tend to explode and the network fails to fit the data. Normally a good choice to start at is 0.1; however, if you effectively divide the learning rate by n_records, try starting out with a learning rate of 1. In either case, if the network has problems fitting the data, try reducing the learning rate. Note that the lower the learning rate, the smaller the steps are in the weight updates and the longer it takes for the neural network to converge.\n\n### Choose the number of hidden nodes\nIn a model where all the weights are optimized, the more hidden nodes you have, the more accurate the predictions of the model will be. (A fully optimized model could have weights of zero, after all.) However, the more hidden nodes you have, the harder it will be to optimize the weights of the model, and the more likely it will be that suboptimal weights will lead to overfitting. With overfitting, the model will memorize the training data instead of learning the true pattern, and won't generalize well to unseen data. \n\nTry a few different numbers and see how it affects the performance. You can look at the losses dictionary for a metric of the network performance. If the number of hidden units is too low, then the model won't have enough space to learn and if it is too high there are too many options for the direction that the learning can take. The trick here is to find the right balance in number of hidden units you choose. You'll generally find that the best number of hidden nodes to use ends up being between the number of input and output nodes.",
"_____no_output_____"
]
],
[
[
"import sys\n\n####################\n### Set the hyperparameters in you myanswers.py file ###\n####################\n\nfrom my_answers import iterations, learning_rate, hidden_nodes, output_nodes\n\n\nN_i = train_features.shape[1]\nnetwork = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)\n\nlosses = {'train':[], 'validation':[]}\nfor ii in range(iterations):\n # Go through a random batch of 128 records from the training data set\n batch = np.random.choice(train_features.index, size=128)\n X, y = train_features.ix[batch].values, train_targets.ix[batch]['cnt']\n \n network.train(X, y)\n \n # Printing out the training progress\n train_loss = MSE(network.run(train_features).T, train_targets['cnt'].values)\n val_loss = MSE(network.run(val_features).T, val_targets['cnt'].values)\n sys.stdout.write(\"\\rProgress: {:2.1f}\".format(100 * ii/float(iterations)) \\\n + \"% ... Training loss: \" + str(train_loss)[:5] \\\n + \" ... Validation loss: \" + str(val_loss)[:5])\n sys.stdout.flush()\n \n losses['train'].append(train_loss)\n losses['validation'].append(val_loss)",
"_____no_output_____"
],
[
"plt.plot(losses['train'], label='Training loss')\nplt.plot(losses['validation'], label='Validation loss')\nplt.legend()\n_ = plt.ylim()",
"_____no_output_____"
]
],
[
[
"## Check out your predictions\n\nHere, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly.",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(8,4))\n\nmean, std = scaled_features['cnt']\npredictions = network.run(test_features).T*std + mean\nax.plot(predictions[0], label='Prediction')\nax.plot((test_targets['cnt']*std + mean).values, label='Data')\nax.set_xlim(right=len(predictions))\nax.legend()\n\ndates = pd.to_datetime(rides.ix[test_data.index]['dteday'])\ndates = dates.apply(lambda d: d.strftime('%b %d'))\nax.set_xticks(np.arange(len(dates))[12::24])\n_ = ax.set_xticklabels(dates[12::24], rotation=45)",
"_____no_output_____"
]
],
[
[
"## OPTIONAL: Thinking about your results(this question will not be evaluated in the rubric).\n \nAnswer these questions about your results. How well does the model predict the data? Where does it fail? Why does it fail where it does?\n\n> **Note:** You can edit the text in this cell by double clicking on it. When you want to render the text, press control + enter\n\n#### Your answer below",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7ab2f6051547487b1c059f6e2898a1e293a5cf8 | 4,376 | ipynb | Jupyter Notebook | Transformer Architecture.ipynb | Chandramouli-Das/Natural-Language-Processing-Repo | 63c8ff8f48ace72f83e928adc9c11493cbbb78ce | [
"MIT"
] | null | null | null | Transformer Architecture.ipynb | Chandramouli-Das/Natural-Language-Processing-Repo | 63c8ff8f48ace72f83e928adc9c11493cbbb78ce | [
"MIT"
] | null | null | null | Transformer Architecture.ipynb | Chandramouli-Das/Natural-Language-Processing-Repo | 63c8ff8f48ace72f83e928adc9c11493cbbb78ce | [
"MIT"
] | null | null | null | 20.259259 | 110 | 0.492687 | [
[
[
"from transformers import pipeline",
"_____no_output_____"
],
[
"classifier = pipeline(\"sentiment-analysis\")",
"_____no_output_____"
],
[
"result = classifier(\"I hate you \")[0]",
"_____no_output_____"
],
[
"print(f\"label: {result['label']}, with score: {round(result['score'], 4)}\")",
"label: NEGATIVE, with score: 0.9991\n"
],
[
"result = classifier(\"Bless you\")[0]",
"_____no_output_____"
],
[
"print(f\"label: {result['label']}, with score: {round(result['score'], 4)}\")",
"label: POSITIVE, with score: 0.9998\n"
],
[
"result",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ab38f5477ed16a0c64f636d85945534d20985f | 7,585 | ipynb | Jupyter Notebook | Fundamentals_of_Python.ipynb | momonts/OOP-58001 | 1780fea43333cbb9484c51ab2ec56cc0063fbbf5 | [
"Apache-2.0"
] | null | null | null | Fundamentals_of_Python.ipynb | momonts/OOP-58001 | 1780fea43333cbb9484c51ab2ec56cc0063fbbf5 | [
"Apache-2.0"
] | null | null | null | Fundamentals_of_Python.ipynb | momonts/OOP-58001 | 1780fea43333cbb9484c51ab2ec56cc0063fbbf5 | [
"Apache-2.0"
] | null | null | null | 22.049419 | 236 | 0.381543 | [
[
[
"<a href=\"https://colab.research.google.com/github/momonts/OOP-58001/blob/main/Fundamentals_of_Python.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"if 5 > 2:\n print(\"Five is greater then two!\")",
"Five is greater then two!\n"
],
[
"#Comment\nprint(\"Hello World\")",
"Hello World\n"
],
[
"b = \"sally\"\nb = int(4)\nprint(b)\n\nb = float(4)\nprint(b)",
"4\n4.0\n"
],
[
"x = 5\ny = \"John\"\nprint(type(x))\nprint(type(y))",
"<class 'int'>\n<class 'str'>\n"
],
[
"x, y, z = \"one\", \"two\", \"three\"\nprint(x)\nprint(y)\nprint(z)",
"one\ntwo\nthree\n"
],
[
"x = y = z = \"four\"\nprint(x)\nprint(y)\nprint(z)",
"four\nfour\nfour\n"
],
[
"x = \"enjoying\"\ny = \"Python is \"\n\nz = y + x\n\nprint(\"Python programming is \" + x)\nprint(z)",
"Python programming is enjoying\nPython is enjoying\n"
],
[
"x = 5\ny = 3\n\nprint(x + y)\nsum = x+ y\nsum",
"8\n"
],
[
"a, b, c = 0, -1, 6\nc %= 3\nc",
"_____no_output_____"
],
[
"a, b, c = 0, -1, 6\na>b and c>b\nTrue",
"_____no_output_____"
],
[
"a, b, c = 0, -1, 6\na is c\nFalse",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ab3ba5be0b2d38ed0fcf763da0eae32f291b15 | 238,827 | ipynb | Jupyter Notebook | Kmeans-Pima22.ipynb | KK-E-7-2020/Clustering | 455d5d38368ecd1e13334dd757d1be9faa0be54a | [
"MIT"
] | null | null | null | Kmeans-Pima22.ipynb | KK-E-7-2020/Clustering | 455d5d38368ecd1e13334dd757d1be9faa0be54a | [
"MIT"
] | null | null | null | Kmeans-Pima22.ipynb | KK-E-7-2020/Clustering | 455d5d38368ecd1e13334dd757d1be9faa0be54a | [
"MIT"
] | 1 | 2020-10-22T03:36:39.000Z | 2020-10-22T03:36:39.000Z | 157.433751 | 132,704 | 0.83344 | [
[
[
"import random \nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom sklearn.cluster import KMeans \n%matplotlib inline\nimport pandas as pd\ncust_df = pd.read_csv(\"pima-indians-diabetes.csv\", names=['Pregnancies','Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age', 'Class'])\ncust_df.head(10)",
"_____no_output_____"
],
[
"df = cust_df.drop('Class', axis=1)\ndf.head(10)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import StandardScaler\nX = df.values[:,:]\nX = np.nan_to_num(X)\nClus_dataSet = StandardScaler().fit_transform(X)\nClus_dataSet",
"_____no_output_____"
],
[
"clusterNum = 2\nk_means = KMeans(init = \"k-means++\", n_clusters = clusterNum, n_init = 12)\nk_means.fit(X)\nlabels = k_means.labels_\nprint(labels)",
"[0 0 0 0 1 0 0 0 1 0 0 0 0 1 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 0\n 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0\n 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0\n 0 0 1 0 1 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 1 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0\n 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 1 0 0 0 1\n 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 0 0 0 1 1 0 0\n 1 1 1 0 0 0 0 0 0 0 0 1 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0\n 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0\n 1 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0\n 0 0 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1\n 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0\n 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0\n 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0\n 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0\n 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 0\n 0 0 1 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 1 0 0 1 0 1 0 0\n 0 0 0 0 1 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0\n 1 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0]\n"
],
[
"df[\"Clus_km\"] = labels\ndf.head(10)",
"_____no_output_____"
],
[
"df.groupby('Clus_km').mean()",
"_____no_output_____"
],
[
"area = np.pi * ( X[:, 1])**2 \nplt.scatter(X[:, 1], X[:, 4], c=labels.astype(np.float), alpha=0.5)\nplt.xlabel('Glucose', fontsize=18)\nplt.ylabel('Insulin', fontsize=16)\n\nplt.show()",
"_____no_output_____"
],
[
"from mpl_toolkits.mplot3d import Axes3D \nfig = plt.figure(1, figsize=(8, 6))\nplt.clf()\nax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)\n\nplt.cla()\n# plt.ylabel('Age', fontsize=18)\n# plt.xlabel('Income', fontsize=16)\n# plt.zlabel('Education', fontsize=16)\nax.set_xlabel('Glucose')\nax.set_ylabel('SkinThickness')\nax.set_zlabel('Insulin')\n\nax.scatter(X[:, 1], X[:, 3], X[:, 4], c= labels.astype(np.float))",
"_____no_output_____"
],
[
"df[['Clus_km']]",
"_____no_output_____"
],
[
"cust_df['Clus_km'] = df[\"Clus_km\"]\ncust_df",
"_____no_output_____"
],
[
"cust_df['eq'] = np.where(cust_df[\"Class\"] == cust_df[\"Clus_km\"], True, False)\ncust_df",
"_____no_output_____"
],
[
"'accuration : ' + str(round(cust_df.loc[cust_df['eq'] == True].count()[1] / cust_df.shape[0] * 100, 3)) + ' %'",
"_____no_output_____"
],
[
"from sklearn.metrics import silhouette_score\nprint(f'Silhouette Score(n=2): {silhouette_score(X, labels)}')",
"Silhouette Score(n=2): 0.5687897205830247\n"
],
[
"silhouette_data = []\nfor k in range (2,13):\n kmeans_shihouette = KMeans(init = \"k-means++\", n_clusters = k, n_init = 12)\n kmeans_shihouette.fit(X)\n shihouette_labels = kmeans_shihouette.labels_\n silhouette_data.append(silhouette_score(X, shihouette_labels))\n \nplt.plot(range(2,13), silhouette_data, 'bx-')\nplt.xlabel('Values of K')\nplt.ylabel('Silhouette Score Pima')\nplt.show",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ab4664990222dfd80360a6bf97a6de6d67ec7a | 8,688 | ipynb | Jupyter Notebook | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 | ea3c0974566396e216d71748b208413f86be6e48 | [
"BSD-3-Clause"
] | 2 | 2022-01-12T13:10:42.000Z | 2022-02-12T16:16:47.000Z | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 | ea3c0974566396e216d71748b208413f86be6e48 | [
"BSD-3-Clause"
] | null | null | null | cycle_6_searching/previous_years/Friday21stWed26_February_Searching (1).ipynb | magicicada/cs1px_2020 | ea3c0974566396e216d71748b208413f86be6e48 | [
"BSD-3-Clause"
] | 1 | 2022-01-16T17:33:53.000Z | 2022-01-16T17:33:53.000Z | 28.485246 | 270 | 0.535336 | [
[
[
"**Searching**\n\nGiven our experience in thinking about computational complexity and correctness, I think we're ready to start thinking about a couple classic *algorithms* and problems.\n\nThis week we will start with *searching*, and then move on to *sorting*\n\nWe'll talk about:\n1. What we mean by searching\n2. How quickly can we search a list when we don't know anything about the list?\n3. When can we do better?\n4. Starting to define our faster algorithm - binary search\n\nWhat do we mean by searching?\n\nSearching in general in computing means lots of different things - we'll be talking about the question: given a data structure and an item - is the item in the data structure? We will mostly talk about looking for items in lists, occasionally in dictionaries. \n\nLet's start with this version of the question: Given a list and an item, return the index of the item if it is in the list, otherwise return -1.\n\nWarm-up: write a function to do this. ",
"_____no_output_____"
]
],
[
[
"def simpleSearch(myList, item):\n for i in range(len(myList)):\n if myList[i] == item:\n return i\n return -1\n\nComplexity of this is O(n)\n",
"_____no_output_____"
]
],
[
[
"Exercise: What is the big-O time complexity of this algorithm?\n \n\nCan we do better? If not, why not?\n\n",
"_____no_output_____"
],
[
"We can do better when we know the list is in sorted order. \n\n\nExample: (in class) the guessing game - trace an example.\n \nExample: (trace together on visualiser) searching in an alphabetically ordered list - looking for *cat* in the list:",
"_____no_output_____"
]
],
[
[
"wordsList = ['android', 'badger', 'cat', 'door', 'ending', 'firefighter', 'garage', 'handle', 'iguana', 'jumper', 'kestrel', 'lemon']",
"_____no_output_____"
]
],
[
[
"In-class exercise: Now, as an individual/group exercise, trace this method looking for 'handle'",
"_____no_output_____"
],
[
"We have essentially been performing **binary search**. The idea is simple, but the implementation is very tricky! We will look at two implementations: one iterative, one recursive. ",
"_____no_output_____"
]
],
[
[
"def iterative_binary_search(my_list, value):\n lo= 0\n hi = len(my_list)-1\n while lo <= hi:\n mid = (lo + hi) // 2\n if my_list[mid] < value:\n lo = mid + 1\n elif value < my_list[mid]:\n hi = mid - 1\n else:\n return mid\n return -1",
"_____no_output_____"
]
],
[
[
"Let's trace the operation of this code when called with: ",
"_____no_output_____"
]
],
[
[
"iterative_binary_search([-3, 1, 0, 19, 20, 22, 32], 22)",
"_____no_output_____"
]
],
[
[
"Binary search can also be implemented recursively. I would like you to be familiar with both the iterative and the recursive versions.\n\n\nLet's try to translate from our iterative version to a recursive version. Look at the iterative version. Where might recursive calls go? Think back to the tracing - where might we have done recursive calls?",
"_____no_output_____"
]
],
[
[
" def binary_search(my_list, lo, hi, value):\n if len(my_list) < 1:\n return -1\n if lo > hi:\n return -1\n \n \n mid = lo + hi // 2\n mid_value = my_list[mid]\n \n if mid_value == value:\n return mid\n elif mid_value < value:\n return binary_search(my_list, mid + 1, hi, value)\n else:\n return binary_search(my_list, lo, mid - 1, value)\n",
"_____no_output_____"
]
],
[
[
"In lecture we will inspect this code very carefully!\n\nLet's trace it with a call of: ",
"_____no_output_____"
]
],
[
[
"my_list = [-3, 1, 0, 19, 20, 22, 32]\n\ndef simplerBinary(myList, value):\n if len(myList) < 1:\n return None\n if len(myList) == 1 and myList[0] != value:\n return None\n mid = (len(myList)-1)//2\n mid_value = myList[mid]\n\n if mid_value == value:\n return mid\n elif mid_value < value:\n new_list = myList[mid+1:]\n downward = simplerBinary(new_list, value)\n if downward != None:\n return mid +1 + downward\n else:\n return None\n else:\n new_list = myList[:mid]\n return simplerBinary(new_list, value)\n \nmy_list = [-3, 0, 1, 19, 20, 22, 32]\nprint(simplerBinary(my_list, 19))\n ",
"3\n"
]
],
[
[
"Many things can go wrong in implementing binary search! You practiced finding bugs in your lab. ",
"_____no_output_____"
],
[
"**We still need to talk about the time complexity of binary search**\n\nThink back to our tracing - how many times did we adjust our bounds? (we will examine an example in lecture). \n\nWhat is the the worst-case for this search? \n- it is when the item is not in the list.\n\nWhat will happen when we add one extra item? What about when we double the size of the list?\n\nHow many times can we split our list in half before we're left with an empty list (or equal hi/lo bounds) to check?\n\n\n**Example:** say we have a list of length 8. How many loops?\n1. Split 8 to 4\n2. Split 4 to 2\n3. Split 2 to 1\n4. Item not found\n**3 loops**\n\n**Example:** say we have a list of length 64. How many loops?\n1. Split 64 to 32\n2. Split 32 to 16\n3. Split 16 to 8\n4. Split 8 to 4\n5. Split 4 to 2\n6. Split 2 to 1\n7. Item not found\n**6 loops**\n\nNote the pattern: 2^6 = 64, 2^3 = 8 - this gets a little more complicated for non-powers-of-two, but with work and details it can be worked out.\n\nThe time complexity of binary search is **O(log n)**\n",
"_____no_output_____"
],
[
"Additional exercises I want to look at:\n 1. Implementing a modified simple searches \n \n * write a search that determines if an item is present *at least twice*\n * write a search that determines if an item is present *after some particular index*",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"raw",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"raw"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
e7ab51ebcafb91074f4a42b540755b8c028fc4ef | 280,596 | ipynb | Jupyter Notebook | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning | c91b4850124e4d8781cd3cae57a72ab6430fd41d | [
"MIT"
] | null | null | null | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning | c91b4850124e4d8781cd3cae57a72ab6430fd41d | [
"MIT"
] | null | null | null | temporal-difference/Temporal_Difference.ipynb | laljarus/deep-reinforcement-learning | c91b4850124e4d8781cd3cae57a72ab6430fd41d | [
"MIT"
] | null | null | null | 372.143236 | 57,036 | 0.922183 | [
[
[
"# Temporal-Difference Methods\n\nIn this notebook, you will write your own implementations of many Temporal-Difference (TD) methods.\n\nWhile we have provided some starter code, you are welcome to erase these hints and write your code from scratch.\n\n---\n\n### Part 0: Explore CliffWalkingEnv\n\nWe begin by importing the necessary packages.",
"_____no_output_____"
]
],
[
[
"import sys\nimport gym\nimport numpy as np\nfrom collections import defaultdict, deque\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport check_test\nfrom plot_utils import plot_values",
"_____no_output_____"
]
],
[
[
"Use the code cell below to create an instance of the [CliffWalking](https://github.com/openai/gym/blob/master/gym/envs/toy_text/cliffwalking.py) environment.",
"_____no_output_____"
]
],
[
[
"env = gym.make('CliffWalking-v0')",
"_____no_output_____"
]
],
[
[
"The agent moves through a $4\\times 12$ gridworld, with states numbered as follows:\n```\n[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],\n [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],\n [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],\n [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]]\n```\nAt the start of any episode, state `36` is the initial state. State `47` is the only terminal state, and the cliff corresponds to states `37` through `46`.\n\nThe agent has 4 potential actions:\n```\nUP = 0\nRIGHT = 1\nDOWN = 2\nLEFT = 3\n```\n\nThus, $\\mathcal{S}^+=\\{0, 1, \\ldots, 47\\}$, and $\\mathcal{A} =\\{0, 1, 2, 3\\}$. Verify this by running the code cell below.",
"_____no_output_____"
]
],
[
[
"print(env.action_space)\nprint(env.observation_space)",
"Discrete(4)\nDiscrete(48)\n"
]
],
[
[
"In this mini-project, we will build towards finding the optimal policy for the CliffWalking environment. The optimal state-value function is visualized below. Please take the time now to make sure that you understand _why_ this is the optimal state-value function.\n\n_**Note**: You can safely ignore the values of the cliff \"states\" as these are not true states from which the agent can make decisions. For the cliff \"states\", the state-value function is not well-defined._",
"_____no_output_____"
]
],
[
[
"# define the optimal state-value function\nV_opt = np.zeros((4,12))\nV_opt[0:13][0] = -np.arange(3, 15)[::-1]\nV_opt[0:13][1] = -np.arange(3, 15)[::-1] + 1\nV_opt[0:13][2] = -np.arange(3, 15)[::-1] + 2\nV_opt[3][0] = -13\n\nplot_values(V_opt)",
"_____no_output_____"
]
],
[
[
"### Part 1: TD Control: Sarsa\n\nIn this section, you will write your own implementation of the Sarsa control algorithm.\n\nYour algorithm has four arguments:\n- `env`: This is an instance of an OpenAI Gym environment.\n- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.\n- `alpha`: This is the step-size parameter for the update step.\n- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).\n\nThe algorithm returns as output:\n- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.\n\nPlease complete the function in the code cell below.\n\n(_Feel free to define additional functions to help you to organize your code._)",
"_____no_output_____"
]
],
[
[
"Q = defaultdict(lambda: np.zeros(env.nA))\nQ[36]",
"_____no_output_____"
],
[
"def get_probs(Q_s, epsilon, nA):\n \"\"\" obtains the action probabilities corresponding to epsilon-greedy policy \"\"\"\n policy_s = np.ones(nA) * epsilon / nA\n best_a = np.argmax(Q_s)\n policy_s[best_a] = 1 - epsilon + (epsilon / nA)\n return policy_s\n\ndef update_Q_sarsa(alpha, gamma, Q, state, action, reward, next_state=None, next_action=None):\n \"\"\"Returns updated Q-value for the most recent experience.\"\"\"\n current = Q[state][action] # estimate in Q-table (for current state, action pair)\n # get value of state, action pair at next time step\n Qsa_next = Q[next_state][next_action] if next_state is not None else 0 \n target = reward + (gamma * Qsa_next) # construct TD target\n new_value = current + (alpha * (target - current)) # get updated value\n return new_value",
"_____no_output_____"
],
[
"def sarsa(env, num_episodes, alpha, gamma=1.0, eps_start=1.0, eps_min=0.0001,plot_every=100):\n # initialize action-value function (empty dictionary of arrays)\n nA = env.action_space.n\n Q = defaultdict(lambda: np.zeros(env.nA))\n # initialize performance monitor\n # monitor performance\n tmp_scores = deque(maxlen=plot_every) # deque for keeping track of scores\n avg_scores = deque(maxlen=num_episodes) # average scores over every plot_every episodes\n \n # loop over episodes\n epsilon = eps_start\n for i_episode in range(1, num_episodes+1):\n # monitor progress\n if i_episode % 100 == 0:\n print(\"\\rEpisode {}/{}\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush() \n \n ## TODO: complete the function\n #epsilon = max(epsilon/i_episode, eps_min)\n epsilon = epsilon/i_episode\n \n state = env.reset()\n \n action = np.random.choice(np.arange(nA), p=get_probs(Q[state], epsilon, nA)) \\\n if state in Q else env.action_space.sample()\n \n score = 0\n \n while True: \n \n next_state, reward, done, info = env.step(action)\n \n score += reward \n \n if not done:\n next_action = np.random.choice(np.arange(nA), p=get_probs(Q[next_state], epsilon, nA)) \\\n if state in Q else env.action_space.sample() \n \n Q[state][action] = update_Q_sarsa(alpha, gamma, Q, \\\n state, action, reward, next_state, next_action)\n state = next_state\n action = next_action\n \n if done:\n Q[state][action] = update_Q_sarsa(alpha, gamma, Q, \\\n state, action, reward)\n tmp_scores.append(score)\n break\n \n if (i_episode % plot_every == 0):\n avg_scores.append(np.mean(tmp_scores))\n \n #policy = dict((k,np.argmax(v)) for k, v in Q.items())\n # plot performance\n plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))\n plt.xlabel('Episode Number')\n plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)\n plt.show()\n # print best 100-episode performance\n print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores))\n \n return Q",
"_____no_output_____"
]
],
[
[
"Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. \n\nIf the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default.",
"_____no_output_____"
]
],
[
[
"# obtain the estimated optimal policy and corresponding action-value function\nQ_sarsa = sarsa(env, 5000, .01)\n\n# print the estimated optimal policy\npolicy_sarsa = np.array([np.argmax(Q_sarsa[key]) if key in Q_sarsa else -1 for key in np.arange(48)]).reshape(4,12)\ncheck_test.run_check('td_control_check', policy_sarsa)\nprint(\"\\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):\")\nprint(policy_sarsa)\n\n# plot the estimated optimal state-value function\nV_sarsa = ([np.max(Q_sarsa[key]) if key in Q_sarsa else 0 for key in np.arange(48)])\nplot_values(V_sarsa)",
"Episode 5000/5000"
]
],
[
[
"### Part 2: TD Control: Q-learning\n\nIn this section, you will write your own implementation of the Q-learning control algorithm.\n\nYour algorithm has four arguments:\n- `env`: This is an instance of an OpenAI Gym environment.\n- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.\n- `alpha`: This is the step-size parameter for the update step.\n- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).\n\nThe algorithm returns as output:\n- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.\n\nPlease complete the function in the code cell below.\n\n(_Feel free to define additional functions to help you to organize your code._)",
"_____no_output_____"
]
],
[
[
"def q_learning(env, num_episodes, alpha, gamma=1.0, eps_start=1.0,eps_decay=0.9, eps_min=0.001,plot_every=100):\n # initialize empty dictionary of arrays\n nA = env.action_space.n\n Q = defaultdict(lambda: np.zeros(env.nA))\n \n # monitor performance\n tmp_scores = deque(maxlen=plot_every) # deque for keeping track of scores\n avg_scores = deque(maxlen=num_episodes) # average scores over every plot_every episodes\n \n \n # loop over episodes\n epsilon = eps_start\n for i_episode in range(1, num_episodes+1):\n # monitor progress\n if i_episode % 100 == 0:\n print(\"\\rEpisode {}/{}\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush()\n \n ## TODO: complete the function\n epsilon = max(epsilon*eps_decay, eps_min)\n #epsilon = epsilon/i_episode\n \n state = env.reset()\n \n action = np.random.choice(np.arange(nA), p=get_probs(Q[state], epsilon, nA)) \\\n if state in Q else env.action_space.sample()\n \n score = 0\n \n while True:\n next_state, reward, done, info = env.step(action)\n score += reward \n \n if not done: \n old_Q = Q[state][action] \n target = reward + gamma*np.max(Q[next_state])\n Q[state][action] = old_Q + alpha*(target - old_Q)\n \n state = next_state\n action = np.random.choice(np.arange(nA), p=get_probs(Q[state], epsilon, nA)) \\\n if state in Q else env.action_space.sample()\n if done:\n old_Q = Q[state][action] \n target = reward \n Q[state][action] = old_Q + alpha*(target - old_Q)\n tmp_scores.append(score)\n break\n if (i_episode % plot_every == 0):\n avg_scores.append(np.mean(tmp_scores))\n \n #policy = dict((k,np.argmax(v)) for k, v in Q.items())\n # plot performance\n plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))\n plt.xlabel('Episode Number')\n plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)\n plt.show()\n # print best 100-episode performance\n print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores))\n \n return Q",
"_____no_output_____"
]
],
[
[
"Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. \n\nIf the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default.",
"_____no_output_____"
]
],
[
[
"# obtain the estimated optimal policy and corresponding action-value function\nQ_sarsamax = q_learning(env, 5000, .01)\n\n# print the estimated optimal policy\npolicy_sarsamax = np.array([np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1 for key in np.arange(48)]).reshape((4,12))\ncheck_test.run_check('td_control_check', policy_sarsamax)\nprint(\"\\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):\")\nprint(policy_sarsamax)\n\n# plot the estimated optimal state-value function\nplot_values([np.max(Q_sarsamax[key]) if key in Q_sarsamax else 0 for key in np.arange(48)])",
"Episode 5000/5000"
]
],
[
[
"### Part 3: TD Control: Expected Sarsa\n\nIn this section, you will write your own implementation of the Expected Sarsa control algorithm.\n\nYour algorithm has four arguments:\n- `env`: This is an instance of an OpenAI Gym environment.\n- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.\n- `alpha`: This is the step-size parameter for the update step.\n- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).\n\nThe algorithm returns as output:\n- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.\n\nPlease complete the function in the code cell below.\n\n(_Feel free to define additional functions to help you to organize your code._)",
"_____no_output_____"
]
],
[
[
"def update_Q_expected_sarsa(alpha, gamma,epsilon,nA, Q, state, action, reward, next_state):\n \"\"\"Returns updated Q-value for the most recent experience.\"\"\"\n current = Q[state][action] # estimate in Q-table (for current state, action pair)\n # get value of state, action pair at next time step \n policy_s=get_probs(Q[state], epsilon, nA) \n Qsa_next = np.dot(Q[next_state], policy_s) \n target = reward + (gamma * Qsa_next) # construct TD target\n new_value = current + (alpha * (target - current)) # get updated value\n return new_value",
"_____no_output_____"
],
[
"def expected_sarsa(env, num_episodes, alpha, gamma=1.0,eps_start=1.0,eps_decay=0.9, eps_min=0.005,plot_every=100):\n nA = env.action_space.n\n Q = defaultdict(lambda: np.zeros(env.nA))\n \n # monitor performance\n tmp_scores = deque(maxlen=plot_every) # deque for keeping track of scores\n avg_scores = deque(maxlen=num_episodes) # average scores over every plot_every episodes\n \n \n # loop over episodes\n #epsilon = eps_start\n epsilon = 0.005\n for i_episode in range(1, num_episodes+1):\n # monitor progress\n if i_episode % 100 == 0:\n print(\"\\rEpisode {}/{}\".format(i_episode, num_episodes), end=\"\")\n sys.stdout.flush()\n \n ## TODO: complete the function\n #epsilon = max(epsilon*eps_decay, eps_min)\n #epsilon = epsilon/i_episode\n \n state = env.reset()\n \n action = np.random.choice(np.arange(nA), p=get_probs(Q[state], epsilon, nA)) \\\n if state in Q else env.action_space.sample()\n \n score = 0\n \n while True:\n next_state, reward, done, info = env.step(action)\n score += reward \n Q[state][action] = update_Q_expected_sarsa(alpha, gamma,epsilon,nA, Q, state, action, reward, next_state)\n \n state = next_state\n \n action = np.random.choice(np.arange(nA), p=get_probs(Q[state], epsilon, nA)) \\\n if state in Q else env.action_space.sample()\n \n \n if done: \n tmp_scores.append(score)\n break\n if (i_episode % plot_every == 0):\n avg_scores.append(np.mean(tmp_scores))\n \n #policy = dict((k,np.argmax(v)) for k, v in Q.items())\n # plot performance\n plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))\n plt.xlabel('Episode Number')\n plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)\n plt.show()\n # print best 100-episode performance\n print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores))\n \n return Q",
"_____no_output_____"
]
],
[
[
"Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. \n\nIf the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default.",
"_____no_output_____"
]
],
[
[
"# obtain the estimated optimal policy and corresponding action-value function\nQ_expsarsa = expected_sarsa(env, 5000, 0.5)\n\n# print the estimated optimal policy\npolicy_expsarsa = np.array([np.argmax(Q_expsarsa[key]) if key in Q_expsarsa else -1 for key in np.arange(48)]).reshape(4,12)\ncheck_test.run_check('td_control_check', policy_expsarsa)\nprint(\"\\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):\")\nprint(policy_expsarsa)\n\n# plot the estimated optimal state-value function\nplot_values([np.max(Q_expsarsa[key]) if key in Q_expsarsa else 0 for key in np.arange(48)])",
"Episode 5000/5000"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ab677b1181d7ffbd0e146992113276c383f5ba | 172,144 | ipynb | Jupyter Notebook | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone | a47dd295241822533a9828b2398c96063c214a53 | [
"MIT"
] | null | null | null | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone | a47dd295241822533a9828b2398c96063c214a53 | [
"MIT"
] | null | null | null | sam/notebooks/DS_Pandas.ipynb | DebLeong/HealthCareCapstone | a47dd295241822533a9828b2398c96063c214a53 | [
"MIT"
] | null | null | null | 34.50471 | 992 | 0.437442 | [
[
[
"%logstop\n%logstart -rtq ~/.logs/DS_Pandas.py append\n%matplotlib inline\nimport matplotlib\nimport seaborn as sns\nsns.set()\nmatplotlib.rcParams['figure.dpi'] = 144",
"_____no_output_____"
],
[
"import expectexception",
"_____no_output_____"
]
],
[
[
"# Pandas\n\n<!-- requirement: data/yelp.json.gz -->\n<!-- requirement: data/PEP_2016_PEPANNRES.csv -->",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"We introduced the Pandas module and the DataFrame object in the lesson on [basic data science modules](DS_Basic_DS_Modules.ipynb). We learned how to construct a DataFrame, add data, retrieve data, and [basic reading and writing to disk](DS_IO.ipynb). Now we'll explore the DataFrame object and its powerful analysis methods in more depth.\n\nWe'll work with a data set from the online review site, Yelp. The file is stored as a compressed JSON file.",
"_____no_output_____"
]
],
[
[
"!ls -lh ./data/yelp.json.gz",
"-rw-rw-r-- 1 jovyan users 4.2M Apr 9 18:33 ./data/yelp.json.gz\r\n"
],
[
"import gzip\nimport simplejson as json\n\nwith gzip.open('./data/yelp.json.gz', 'r') as f:\n yelp_data = [json.loads(line) for line in f]\n \nyelp_df = pd.DataFrame(yelp_data)\nyelp_df.head() ",
"_____no_output_____"
]
],
[
[
"## Pandas DataFrame and Series\n\nThe Pandas DataFrame is a highly structured object. Each row corresponds with some physical entity or event. We think of all of the information in a given row as referring to one object (e.g. a business). Each column contains one type of data, both semantically (e.g. names, counts of reviews, star ratings) and syntactically.",
"_____no_output_____"
]
],
[
[
"yelp_df.dtypes",
"_____no_output_____"
]
],
[
[
"We can reference the columns by name, like we would with a `dict`.",
"_____no_output_____"
]
],
[
[
"yelp_df['city'].head()",
"_____no_output_____"
],
[
"type(yelp_df['city'])",
"_____no_output_____"
]
],
[
[
"An individual column is a Pandas `Series`. A `Series` has a `name` and a `dtype` (similar to a NumPy array). A `DataFrame` is essentially a `dict` of `Series` objects. The `Series` has an `index` attribute, which label the rows. The index is essentially a set of keys for referencing the rows. We can have an index composed of numbers, strings, timestamps, or any hashable Python object. The index will also have homogeneous type.",
"_____no_output_____"
]
],
[
[
"yelp_df['city'].index",
"_____no_output_____"
]
],
[
[
"The `DataFrame` has an `index` given by the union of indices of its constituent `Series` (we'll explore this later in more detail). Since a `DataFrame` is a `dict` of `Series`, we can select a column and then a row using square bracket notation, but not the reverse (however, the `loc` method works around this).",
"_____no_output_____"
]
],
[
[
"# this works\nyelp_df['city'][100]",
"_____no_output_____"
],
[
"%%expect_exception KeyError\n\n# this doesn't\nyelp_df[100]['city']",
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)\n\u001b[0;32m/opt/conda/lib/python3.7/site-packages/pandas/core/indexes/base.py\u001b[0m in \u001b[0;36mget_loc\u001b[0;34m(self, key, method, tolerance)\u001b[0m\n\u001b[1;32m 2889\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 2890\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_engine\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_loc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2891\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\n\u001b[0;32mpandas/_libs/index.pyx\u001b[0m in \u001b[0;36mpandas._libs.index.IndexEngine.get_loc\u001b[0;34m()\u001b[0m\n\n\u001b[0;32mpandas/_libs/index.pyx\u001b[0m in \u001b[0;36mpandas._libs.index.IndexEngine.get_loc\u001b[0;34m()\u001b[0m\n\n\u001b[0;32mpandas/_libs/hashtable_class_helper.pxi\u001b[0m in \u001b[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001b[0;34m()\u001b[0m\n\n\u001b[0;32mpandas/_libs/hashtable_class_helper.pxi\u001b[0m in \u001b[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001b[0;34m()\u001b[0m\n\n\u001b[0;31mKeyError\u001b[0m: 100\n\nDuring handling of the above exception, another exception occurred:\n\n\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)\n\u001b[0;32m<ipython-input-12-a719463eea94>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;31m# this doesn't\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0myelp_df\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'city'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\n\u001b[0;32m/opt/conda/lib/python3.7/site-packages/pandas/core/frame.py\u001b[0m in \u001b[0;36m__getitem__\u001b[0;34m(self, key)\u001b[0m\n\u001b[1;32m 2973\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcolumns\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnlevels\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2974\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_getitem_multilevel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 2975\u001b[0;31m \u001b[0mindexer\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcolumns\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_loc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2976\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mis_integer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mindexer\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2977\u001b[0m \u001b[0mindexer\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mindexer\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\n\u001b[0;32m/opt/conda/lib/python3.7/site-packages/pandas/core/indexes/base.py\u001b[0m in \u001b[0;36mget_loc\u001b[0;34m(self, key, method, tolerance)\u001b[0m\n\u001b[1;32m 2890\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_engine\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_loc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2891\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 2892\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_engine\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_loc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_maybe_cast_indexer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2893\u001b[0m \u001b[0mindexer\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_indexer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmethod\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mmethod\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtolerance\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtolerance\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2894\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mindexer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mndim\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m1\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mindexer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msize\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\n\u001b[0;32mpandas/_libs/index.pyx\u001b[0m in \u001b[0;36mpandas._libs.index.IndexEngine.get_loc\u001b[0;34m()\u001b[0m\n\n\u001b[0;32mpandas/_libs/index.pyx\u001b[0m in \u001b[0;36mpandas._libs.index.IndexEngine.get_loc\u001b[0;34m()\u001b[0m\n\n\u001b[0;32mpandas/_libs/hashtable_class_helper.pxi\u001b[0m in \u001b[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001b[0;34m()\u001b[0m\n\n\u001b[0;32mpandas/_libs/hashtable_class_helper.pxi\u001b[0m in \u001b[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001b[0;34m()\u001b[0m\n\n\u001b[0;31mKeyError\u001b[0m: 100\n"
],
[
"yelp_df.loc[100, 'city']",
"_____no_output_____"
]
],
[
[
"Understanding the underlying structure of the `DataFrame` object as a `dict` of `Series` will help you avoid errors and help you think about how the `DataFrame` should behave when we begin doing more complicated analysis.\n\nWe can _aggregate_ data in a `DataFrame` using methods like `mean`, `sum`, `count`, and `std`. To view a collection of summary statistics for each column we can use the `describe` method.",
"_____no_output_____"
]
],
[
[
"yelp_df.describe()",
"_____no_output_____"
]
],
[
[
"The utility of a DataFrame comes from its ability to split data into groups, using the `groupby` method, and then perform custom aggregations using the `apply` or `aggregate` method. This process of splitting the data into groups, applying an aggregation, and then collecting the results is [discussed in detail in the Pandas documentation](https://pandas.pydata.org/pandas-docs/stable/groupby.html), and is one of the main focuses of this notebook.",
"_____no_output_____"
],
[
"## DataFrame construction\n\nSince a `DataFrame` is a `dict` of `Series`, the natural way to construct a `DataFrame` is to use a `dict` of `Series`-like objects.",
"_____no_output_____"
]
],
[
[
"from string import ascii_letters, digits\nimport numpy as np\nimport datetime",
"_____no_output_____"
],
[
"usernames = ['alice36', 'bob_smith', 'eve']\n\npasswords = [''.join(np.random.choice(list(ascii_letters + digits), 8)) for x in range(3)]\ncreation_dates = [datetime.datetime.now().date() - datetime.timedelta(int(x)) for x in np.random.randint(0, 1500, 3)]",
"_____no_output_____"
],
[
"usernames",
"_____no_output_____"
],
[
"passwords",
"_____no_output_____"
],
[
"creation_dates",
"_____no_output_____"
],
[
"df = pd.DataFrame({'username': usernames, 'password': passwords, 'date-created': pd.to_datetime(creation_dates)})\ndf",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
]
],
[
[
"The `DataFrame` is also closely related to the NumPy `ndarray`.",
"_____no_output_____"
]
],
[
[
"random_data = np.random.random((4,3))\nrandom_data",
"_____no_output_____"
],
[
"df_random = pd.DataFrame(random_data, columns=['a', 'b', 'c'])\ndf_random",
"_____no_output_____"
]
],
[
[
"To add a new column or row, we simply use `dict`-like assignment.",
"_____no_output_____"
]
],
[
[
"emails = ['[email protected]', '[email protected]', '[email protected]']\ndf['email'] = emails\ndf",
"_____no_output_____"
],
[
"# loc references index value, NOT position\n# for position use iloc\ndf.loc[3] = ['2015-01-29', '38uzFJ1n', 'melvintherobot', '[email protected]']\ndf",
"_____no_output_____"
]
],
[
[
"We can also drop columns and rows.",
"_____no_output_____"
]
],
[
[
"df.drop(3)",
"_____no_output_____"
],
[
"# to drop a column, need axis=1\ndf.drop('email', axis=1)",
"_____no_output_____"
]
],
[
[
"Notice when we dropped the `'email'` column, the row at index 3 was in the `DataFrame`, even though we just dropped it! Most operations in Pandas return a _copy_ of the `DataFrame`, rather than modifying the `DataFrame` object itself. Therefore, in order to permanently alter the `DataFrame`, we either need to reassign the `df` variable, or use the `inplace` keyword.",
"_____no_output_____"
]
],
[
[
"df.drop(3, inplace=True)\ndf",
"_____no_output_____"
]
],
[
[
"Since the `index` and column names are important for interacting with data in the DataFrame, we should make sure to set them to useful values. We can do this during construction or after.",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({'email': emails, 'password': passwords, 'date-created': creation_dates}, index=usernames)\ndf.index.name = 'users' # it can be helpful to give the index a name\ndf",
"_____no_output_____"
],
[
"# alternatively\ndf = pd.DataFrame(list(zip(usernames, emails, passwords, creation_dates)))\ndf",
"_____no_output_____"
],
[
"df.columns = ['username', 'email', 'password', 'date-created']\ndf.set_index('username', inplace=True)\ndf",
"_____no_output_____"
],
[
"# to reset index to a column\ndf.reset_index(inplace=True)\ndf",
"_____no_output_____"
]
],
[
[
"We can have multiple levels to an index. We'll discover that for some data sets it is necessary to have multiple levels to the index in order to uniquely identify a row.",
"_____no_output_____"
]
],
[
[
"df.set_index(['username', 'email'])",
"_____no_output_____"
]
],
[
[
"### Reading data from file\n\nWe can also construct a DataFrame using data stored in a file or received from a website. The data source might be [JSON](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html), [HTML](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html), [CSV](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv), [Excel](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html), [Python pickle](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_pickle.html), or even a [database connection](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html). Each format will have its own methods for reading and writing data that take different arguments. The arguments of these methods usually depend on the particular formatting of the file. For example, the values in a CSV might be separate by commas or semi-colons, it might have a header or it might not.\n\nThe `read_csv` method has to deal with the most formatting possibilities, so we will explore that method with a few examples. Try to apply these ideas when working with other file formats, but keep in mind that each format and read method is different. Always check [the Pandas documentation](http://pandas.pydata.org/pandas-docs/stable/io.html) when having trouble with reading or writing data.",
"_____no_output_____"
]
],
[
[
"csv = [','.join(map(lambda x: str(x), row)) for row in np.vstack([df.columns, df])]\nwith open('./data/read_csv_example.csv', 'w') as f:\n [f.write(line + '\\n') for line in csv]\n\n!cat ./data/read_csv_example.csv",
"username,email,password,date-created\r\nalice36,[email protected],blGgmpBG,2019-11-12\r\nbob_smith,[email protected],t2gbfjsw,2018-09-01\r\neve,[email protected],35cGOhr8,2019-12-23\r\n"
],
[
"csv",
"_____no_output_____"
],
[
"pd.read_csv('./data/read_csv_example.csv')",
"_____no_output_____"
],
[
"# we can also set an index from the data\npd.read_csv('./data/read_csv_example.csv', index_col=0)",
"_____no_output_____"
],
[
"# what if our data had no header?\nwith open('./data/read_csv_noheader_example.csv', 'w') as f:\n [f.write(line + '\\n') for i, line in enumerate(csv) if i != 0]\n \n!cat ./data/read_csv_noheader_example.csv",
"alice36,[email protected],blGgmpBG,2019-11-12\r\nbob_smith,[email protected],t2gbfjsw,2018-09-01\r\neve,[email protected],35cGOhr8,2019-12-23\r\n"
],
[
"pd.read_csv('./data/read_csv_noheader_example.csv', names=['username', 'email', 'password', 'date-created'], header=None)",
"_____no_output_____"
],
[
"# what if our data was tab-delimited?\ntsv = ['\\t'.join(map(lambda x: str(x), row)) for row in np.vstack([df.columns, df])]\nwith open('./data/read_csv_example.tsv', 'w') as f:\n [f.write(line + '\\n') for line in tsv]\n\n!cat ./data/read_csv_example.tsv",
"username\temail\tpassword\tdate-created\r\nalice36\[email protected]\tblGgmpBG\t2019-11-12\r\nbob_smith\[email protected]\tt2gbfjsw\t2018-09-01\r\neve\[email protected]\t35cGOhr8\t2019-12-23\r\n"
],
[
"pd.read_csv('./data/read_csv_example.tsv', delimiter='\\t')",
"_____no_output_____"
]
],
[
[
"Even within a single file format, data can be arranged and formatted in many ways. These have been just a few examples of the kinds of arguments you might need to use with `read_csv` in order to read data into a DataFrame in an organized way.",
"_____no_output_____"
],
[
"## Filtering DataFrames\n\nOne of the powerful analytical tools of the Pandas DataFrame is its syntax for filtering data. Often we'll only want to work with a certain subset of our data based on some criteria. Let's look at our Yelp data for an example.",
"_____no_output_____"
]
],
[
[
"yelp_df.head()",
"_____no_output_____"
]
],
[
[
"We see the Yelp data set has a `'state'` column. If we are only interested in businesses in Arizona (AZ), we can filter the DataFrame and select only that data.",
"_____no_output_____"
]
],
[
[
"az_yelp_df = yelp_df[yelp_df['state'] == 'AZ']\naz_yelp_df.head()",
"_____no_output_____"
],
[
"az_yelp_df['state'].unique()",
"_____no_output_____"
]
],
[
[
"We can combine criteria using logic. What if we're only interested in businesses with more than 10 reviews in Arizona?",
"_____no_output_____"
]
],
[
[
"yelp_df[(yelp_df['state'] == 'AZ') & (yelp_df['review_count'] > 10)].head()",
"_____no_output_____"
]
],
[
[
"How does this filtering work?\n\nWhen we write `yelp_df['state'] == 'AZ'`, Pandas selects the `'state'` column and checks whether each row is `'AZ'`. If so, that row is marked `True`, and if not, it is marked `False`. This is how we would normally expect a conditional to work, only now applied to an entire Pandas `Series`. We end up with a Pandas `Series` of Boolean variables.",
"_____no_output_____"
]
],
[
[
"(yelp_df['state'] == 'AZ').head()",
"_____no_output_____"
]
],
[
[
"We can use a `Series` (or any similar object) of Boolean variables to index the DataFrame.",
"_____no_output_____"
]
],
[
[
"df",
"_____no_output_____"
],
[
"df[[True, False, True]]",
"_____no_output_____"
]
],
[
[
"This let's us filter a DataFrame using idiomatic logical expressions like `yelp_df['review_count'] > 10`.\n\nAs another example, let's consider the `'open'` column, which is a `True`/`False` flag for whether a business is open. This is also a Boolean Pandas `Series`, so we can just use it directly.",
"_____no_output_____"
]
],
[
[
"# the open businesses\nyelp_df[yelp_df['open']].head()",
"_____no_output_____"
],
[
"# the closed businesses\nyelp_df[~yelp_df['open']].head()",
"_____no_output_____"
]
],
[
[
"Notice in an earlier expression we wrote `(yelp_df['state'] == 'AZ') & (yelp_df['review_count'] > 10)`. Normally in Python we use the word `and` when we are working with logic. In Pandas we have to use _bit-wise_ logical operators; all that's important to know is the following equivalencies:\n\n`~` = `not` \n`&` = `and` \n`|` = `or` \n\nWe can also use Panda's built-in [string operations](https://pandas.pydata.org/pandas-docs/stable/text.html) for doing pattern matching. For example, there are a lot of businesses in Las Vegas in our data set. However, there are also businesses in 'Las Vegas East' and 'South Las Vegas'. To get all of the Las Vegas businesses I might do the following.",
"_____no_output_____"
]
],
[
[
"vegas_yelp_df = yelp_df[yelp_df['city'].str.contains('Vegas')]\nvegas_yelp_df.head()",
"_____no_output_____"
],
[
"vegas_yelp_df['city'].unique()",
"_____no_output_____"
]
],
[
[
"## Applying functions and data aggregation\n\nTo analyze the data in the dataframe, we'll need to be able to apply functions to it. Pandas has many mathematical functions built in already, and DataFrames and Series can be passed to NumPy functions (since they behave like NumPy arrays).",
"_____no_output_____"
]
],
[
[
"log_review_count = np.log(yelp_df['review_count'])\nprint(log_review_count.head())\nprint(log_review_count.shape)",
"0 1.945910\n1 3.258097\n2 2.772589\n3 1.945910\n4 1.098612\nName: review_count, dtype: float64\n(37938,)\n"
],
[
"mean_review_count = yelp_df['review_count'].mean()\nprint(mean_review_count)",
"29.300648426379883\n"
]
],
[
[
"In the first example we took the _logarithm_ of the review count for each business. In the second case, we calculated the mean review count of all businesses. In the first case, we ended up with a number for each business. We _transformed_ the review counts using the logarithm. In the second case, we _summarized_ the review counts of all the businesses in one number. This summary is a form of _data aggregation_, in which we take many data points and combine them into some smaller representation. The functions we apply to our data sets will either be in the category of **transformations** or **aggregations**.\n\nSometimes we will need to transform our data in order for it to be usable. For instance, in the `'attributes'` column of our DataFrame, we have a `dict` for each business listing all of its properties. If I wanted to find a restaurant that offers delivery service, it would be difficult for me to filter the DataFrame, even though that information is in the `'attributes'` column. First, I need to transform the `dict` into something more useful.",
"_____no_output_____"
]
],
[
[
"def get_delivery_attr(attr_dict):\n return attr_dict.get('Delivery')",
"_____no_output_____"
]
],
[
[
"If we give this function a `dict` from the `'attributes'` column, it will look for the `'Delivery'` key. If it finds that key, it returns the value. If it doesn't find the key, it will return none.",
"_____no_output_____"
]
],
[
[
"print(get_delivery_attr(yelp_df.loc[0, 'attributes']))\nprint(get_delivery_attr(yelp_df.loc[1, 'attributes']))\nprint(get_delivery_attr(yelp_df.loc[2, 'attributes']))",
"None\nFalse\nFalse\n"
]
],
[
[
"We could iterate over the rows of `yelp_df['attributes']` to get all of the values, but there is a better way. DataFrames and Series have an `apply` method that allows us to apply our function to the entire data set at once, like we did earlier with `np.log`.",
"_____no_output_____"
]
],
[
[
"delivery_attr = yelp_df['attributes'].apply(get_delivery_attr)\ndelivery_attr.head()",
"_____no_output_____"
]
],
[
[
"We can make a new column in our DataFrame with this transformed (and useful) information.",
"_____no_output_____"
]
],
[
[
"yelp_df['delivery'] = delivery_attr\n\n# to find businesses that deliver\nyelp_df[yelp_df['delivery'].fillna(False)].head()",
"_____no_output_____"
]
],
[
[
"It's less common (though possible) to use `apply` on an entire DataFrame rather than just one column. Since a DataFrame might contain many types of data, we won't usually want to apply the same transformation or aggregation across all of the columns.",
"_____no_output_____"
],
[
"### Exercise",
"_____no_output_____"
]
],
[
[
"# filter categories\ncategories_attr = yelp_df['categories'].apply(lambda x: 'Restaurants' in x)\ncategories_attr\nyelp_df['Restaurants'] = categories_attr",
"_____no_output_____"
],
[
"portion = yelp_df[yelp_df['Restaurants']]['delivery'].fillna(False).mean() * 100\n",
"_____no_output_____"
],
[
"print(\"Portion of Restaurants that deliver: %.2f\" % portion)",
"Portion of Restaurants that deliver: 16.25\n"
]
],
[
[
"## Data aggregation with `groupby`\n\nData aggregation is an [_overloaded_](https://en.wikipedia.org/wiki/Function_overloading) term. It refers to both data summarization (as above) but also to the combining of different data sets.\n\nWith our Yelp data, we might be interested in comparing the star ratings of businesses in different cities. We could calculate the mean star rating for each city, and this would allow us to easily compare them. First we would have to split up our data by city, calculate the mean for each city, and then combine it back at the end. This procedure is known as [split-apply-combine](https://pandas.pydata.org/pandas-docs/stable/groupby.html) and is a classic example of data aggregation (in the sense of both summarizing data and also combining different data sets).\n\nWe achieve the splitting and recombining using the `groupby` method.",
"_____no_output_____"
]
],
[
[
"stars_by_city = yelp_df.groupby('city')['stars'].mean()\nstars_by_city.head()",
"_____no_output_____"
]
],
[
[
"We can also apply multiple functions at once. It might be helpful to know the standard deviation of star ratings, the total number of reviews, and the count of businesses as well.",
"_____no_output_____"
]
],
[
[
"agg_by_city = yelp_df.groupby('city').agg({'stars': ['mean', 'std'], 'review_count': 'sum', 'business_id': 'count'})\nagg_by_city.head()",
"_____no_output_____"
],
[
"new_columns = map(lambda x: '_'.join(x),\n zip(agg_by_city.columns.get_level_values(0),\n agg_by_city.columns.get_level_values(1)))",
"_____no_output_____"
],
[
"# unstacking the columns\nnew_columns = map(lambda x: '_'.join(x),\n zip(agg_by_city.columns.get_level_values(0),\n agg_by_city.columns.get_level_values(1)))\nagg_by_city.columns = new_columns\nagg_by_city.head()",
"_____no_output_____"
],
[
"lambda x: '_'.join(x),\n zip(agg_by_city.columns.get_level_values(0),\n agg_by_city.columns.get_level_values(1))",
"_____no_output_____"
]
],
[
[
"How does this work? What does `groupby` do? Let's start by inspecting the result of `groupby`.",
"_____no_output_____"
]
],
[
[
"by_city = yelp_df.groupby('city')\nby_city",
"_____no_output_____"
],
[
"dir(by_city)",
"_____no_output_____"
],
[
"print(type(by_city.groups))\nlist(by_city.groups.items())[:5]",
"_____no_output_____"
],
[
"by_city.get_group('Anthem').head()",
"_____no_output_____"
]
],
[
[
"When we use `groupby` on a column, Pandas builds a `dict`, using the unique elements of the column as the keys and the index of the rows in each group as the values. This `dict` is stored in the `groups` attribute. Pandas can then use this `dict` to direct the application of aggregating functions over the different groups.",
"_____no_output_____"
],
[
"## Sorting\n\nEven though the DataFrame in many ways behaves similarly to a `dict`, it also is ordered. Therefore we can sort the data in it. Pandas provides two sorting methods, `sort_values` and `sort_index`.",
"_____no_output_____"
]
],
[
[
"yelp_df.sort_values('stars').head()",
"_____no_output_____"
],
[
"yelp_df.set_index('business_id').sort_index().head()",
"_____no_output_____"
]
],
[
[
"Don't forget that most Pandas operations return a copy of the DataFrame, and do not update the DataFrame in place (unless we tell it to)!",
"_____no_output_____"
],
[
"## Joining data sets",
"_____no_output_____"
],
[
"Often we will want to augment one data set with data from another. For instance, businesses in big cities probably get more reviews than those in small cities. It could be useful to scale the review counts by the city's population. To do that, we'll need to add population data to the Yelp data. We can get population data from the US census.",
"_____no_output_____"
]
],
[
[
"census = pd.read_csv('./data/PEP_2016_PEPANNRES.csv', skiprows=[1])\n\ncensus.head()",
"_____no_output_____"
],
[
"# construct city & state fields\ncensus['city'] = census['GEO.display-label'].apply(lambda x: x.split(', ')[0])\ncensus['state'] = census['GEO.display-label'].apply(lambda x: x.split(', ')[2])",
"_____no_output_____"
],
[
"# convert state names to abbreviations\n\nprint(census['state'].unique())",
"_____no_output_____"
],
[
"state_abbr = dict(zip(census['state'].unique(), ['CT', 'IL', 'IN', 'KS', 'ME', 'MA', 'MI', 'MN', 'MO', 'NE', 'NH', 'NJ', 'NY', 'ND', 'OH', 'PA', 'RI', 'SD', 'VT', 'WI']))",
"_____no_output_____"
],
[
"state_abbr",
"_____no_output_____"
],
[
"census['state'] = census['state'].replace(state_abbr)",
"_____no_output_____"
],
[
"census.head()",
"_____no_output_____"
],
[
"# remove last word (e.g. 'city', 'town', township', 'borough', 'village') from city names\n\ncensus['city'] = census['city'].apply(lambda x: ' '.join(x.split(' ')[:-1]))",
"_____no_output_____"
],
[
"city_example = \"Bethel Little Town\"\n\" \".join(city_example.split(' ')[:-1])",
"_____no_output_____"
],
[
"census.head()",
"_____no_output_____"
],
[
"merged_df = yelp_df.merge(census, on=['state', 'city'])\nmerged_df.head()",
"_____no_output_____"
]
],
[
[
"The `merge` function looks through the `'state'` and `'city'` columns of `yelp_df` and `census` and tries to match up rows that share values. When a match is found, the rows are combined. What happens when a match is not found? We can imagine four scenarios: \n\n1. We only keep rows from `yelp_df` and `census` if they match. Any rows from either table that have no match are discarded. This is called an _inner join_. \n\n2. We keep all rows from `yelp_df` and `census`, even if they have no match. In this case, when a row in `yelp_df` has no match in `census`, all the columns from `census` are merged in with null values. When a row in `census` has no match in `yelp_df`, all the columns from `yelp_df` are merged in with null values. This is called an _outer join_.\n\n3. We privilege the `yelp_df` data. If a row in `yelp_df` has no match in `census`, we keep it and fill in the missing `census` columns as null values. If a row in `census` has no match in `yelp_df`, we discard it. This is called a _left join_.\n\n4. We privilege the `census` data. This is called a _right join_.\n\nThe default behavior for Pandas is case #1, the _inner join_. This means if there are cities in `yelp_df` that we don't have matching `census` data for, they are dropped. Therefore, `merged_df` might be smaller than `yelp_df`.",
"_____no_output_____"
]
],
[
[
"print(yelp_df.shape)\nprint(merged_df.shape)",
"_____no_output_____"
]
],
[
[
"There are a lot of cities in `yelp_df` that aren't in `census`! We might want to keep these rows, but we don't need any census data where there are no businesses. Then we should use a _left join_.",
"_____no_output_____"
]
],
[
[
"merged_df = yelp_df.merge(census, on=['state', 'city'], how='left')\nprint(yelp_df.shape)\nprint(merged_df.shape)",
"_____no_output_____"
]
],
[
[
"Sometimes we don't need to merge together the columns of separate data sets, but just need to add more rows. For example, the New York City subway system [releases data about how many customers enter and exit the station each week](http://web.mta.info/developers/turnstile.html). Each weekly data set has the same columns, so if we want multiple weeks of data, we just have to append one week to another.",
"_____no_output_____"
]
],
[
[
"nov18 = pd.read_csv('http://web.mta.info/developers/data/nyct/turnstile/turnstile_171118.txt')\nnov11 = pd.read_csv('http://web.mta.info/developers/data/nyct/turnstile/turnstile_171111.txt')",
"_____no_output_____"
],
[
"nov18.head()",
"_____no_output_____"
],
[
"nov11.head()",
"_____no_output_____"
],
[
"nov = pd.concat([nov18, nov11])\nnov['DATE'].unique()",
"_____no_output_____"
]
],
[
[
"We can also use `concat` to perform inner and outer joins based on index. For example, we can perform some data aggregation and then join the results onto the original DataFrame.",
"_____no_output_____"
]
],
[
[
"city_counts = yelp_df.groupby('city')['business_id'].count().rename('city_counts')\ncity_counts.head()",
"_____no_output_____"
],
[
"yelp_df.head()",
"_____no_output_____"
],
[
"pd.concat([yelp_df.set_index('city'), city_counts], axis=1, join='inner').reset_index().head()",
"_____no_output_____"
]
],
[
[
"Pandas provides [extensive documentation](https://pandas.pydata.org/pandas-docs/stable/merging.html) with diagrammed examples on different methods and approaches for joining data.",
"_____no_output_____"
],
[
"## Working with time series\nPandas has a well-designed backend for inferring dates and times from strings and doing meaningful computations with them. ",
"_____no_output_____"
]
],
[
[
"pop_growth = pd.read_html('https://web.archive.org/web/20170127165708/https://www.census.gov/population/international/data/worldpop/table_population.php', attrs={'class': 'query_table'}, parse_dates=[0])[0]\npop_growth.dropna(inplace=True)\npop_growth.head()",
"_____no_output_____"
]
],
[
[
"By setting the `'Year'` column to the index, we can easily aggregate data by date using the `resample` method. The `resample` method allows us to decrease or increase the sampling frequency of our data. For instance, maybe instead of yearly data, we want to see average quantities for each decade.",
"_____no_output_____"
]
],
[
[
"pop_growth.set_index('Year', inplace=True)",
"_____no_output_____"
],
[
"pop_growth.resample('10AS').mean()",
"_____no_output_____"
]
],
[
[
"This kind of resampling is called _downsampling_, because we are decreasing the sampling frequency of the data. We can choose how to aggregate the data from each decade (e.g. `mean`). Options for aggregation include `mean`, `median`, `sum`, `last`, and `first`.\n\nWe can also _upsample_ data. In this case, we don't have data for each quarter, so we have to tell Pandas has to fill in the missing data.",
"_____no_output_____"
]
],
[
[
"pop_growth.resample('1Q').bfill().head()",
"_____no_output_____"
],
[
"pop_growth.resample('1Q').ffill().head()",
"_____no_output_____"
]
],
[
[
"Pandas' time series capabilities are built on the Pandas `Timestamp` class.",
"_____no_output_____"
]
],
[
[
"print(pd.Timestamp('January 8, 2017'))\nprint(pd.Timestamp('01/08/17 20:13'))\nprint(pd.Timestamp(1.4839*10**18))",
"_____no_output_____"
],
[
"print(pd.Timestamp('Feb. 11 2016 2:30 am') - pd.Timestamp('2015-08-03 5:14 pm'))",
"_____no_output_____"
],
[
"from pandas.tseries.offsets import BDay, Day, BMonthEnd\n\nprint(pd.Timestamp('January 9, 2017') - Day(4))\nprint(pd.Timestamp('January 9, 2017') - BDay(4))\nprint(pd.Timestamp('January 9, 2017') + BMonthEnd(4))",
"_____no_output_____"
]
],
[
[
"If we're entering time series data into a DataFrame it will often be useful to create a range of dates.",
"_____no_output_____"
]
],
[
[
"pd.date_range(start='1/8/2017', end='3/2/2017', freq='B')",
"_____no_output_____"
]
],
[
[
"The `Timestamp` class is compatible with Python's `datetime` module.",
"_____no_output_____"
]
],
[
[
"import datetime\n\npd.Timestamp('May 1, 2017') - datetime.datetime(2017, 1, 8)",
"_____no_output_____"
]
],
[
[
"## Visualizing data with Pandas\n\nVisualizing a data set is an important first step in drawing insights. We can easily pass data from Pandas to Matplotlib for visualizations, but Pandas also plugs into Matplotlib directly through methods like `plot` and `hist`.",
"_____no_output_____"
]
],
[
[
"yelp_df['review_count'].apply(np.log).hist(bins=30)",
"_____no_output_____"
],
[
"pop_growth['Annual Growth Rate (%)'].plot()",
"_____no_output_____"
]
],
[
[
"The [plotting functions take many parameters](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html) for customizing the appearance of the output. Since they are essentially a wrapper around the Matplotlib functions, they also accept many of the Matplotlib parameters, not all of which are listed in the Pandas documentation. Pandas provides [a guide](https://pandas.pydata.org/pandas-docs/stable/visualization.html) to making various plots from DataFrames.",
"_____no_output_____"
],
[
"*Copyright © 2020 The Data Incubator. All rights reserved.*",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
e7ab730b648dac8326f9a4da2bfe36b782879e38 | 963,947 | ipynb | Jupyter Notebook | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS | 9d41f64832e8be3ed48e10f80e3e16ce5f228c25 | [
"BSD-2-Clause"
] | 93 | 2017-06-16T01:28:50.000Z | 2022-03-23T18:50:15.000Z | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS | 9d41f64832e8be3ed48e10f80e3e16ce5f228c25 | [
"BSD-2-Clause"
] | 3 | 2018-05-17T08:15:38.000Z | 2021-06-21T05:30:27.000Z | rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb | yassineITler/diy_driverless_car_ROS | 9d41f64832e8be3ed48e10f80e3e16ce5f228c25 | [
"BSD-2-Clause"
] | 53 | 2017-07-15T09:43:51.000Z | 2022-03-14T17:02:26.000Z | 109.551881 | 122,460 | 0.795718 | [
[
[
"<a href=\"https://colab.research.google.com/github/wilselby/diy_driverless_car_ROS/blob/ml-model/rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(Lidar).ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Development of an End-to-End ML Model for Navigating an RC car with a Lidar",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/wilselby/diy_driverless_car_ROS/blob/ml-model/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/wilselby/diy_driverless_car_ROS/blob/ml-model/rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb\">\n <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n View source on GitHub</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"#Environment Setup\n",
"_____no_output_____"
],
[
"## Import Dependencies",
"_____no_output_____"
]
],
[
[
"import os\nimport csv\nimport cv2\nimport matplotlib.pyplot as plt\nimport random\nimport pprint\n\nimport numpy as np\nfrom numpy import expand_dims\n\n%tensorflow_version 1.x\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nfrom keras import backend as K\nfrom keras.models import Model, Sequential\nfrom keras.models import load_model\nfrom keras.layers import Dense, GlobalAveragePooling2D, MaxPooling2D, Lambda, Cropping2D\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.core import Flatten, Dense, Dropout, SpatialDropout2D\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, TensorBoard\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array \n \nfrom google.colab.patches import cv2_imshow\n \nimport sklearn\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\n\nprint(\"Tensorflow Version:\",tf.__version__)\nprint(\"Tensorflow Keras Version:\",tf.keras.__version__)\nprint(\"Eager mode: \", tf.executing_eagerly())\n",
"Using TensorFlow backend.\n"
]
],
[
[
"## Confirm TensorFlow can see the GPU \n\nSimply select \"GPU\" in the Accelerator drop-down in Notebook Settings (either through the Edit menu or the command palette at cmd/ctrl-shift-P).",
"_____no_output_____"
]
],
[
[
"device_name = tf.test.gpu_device_name()\n\nif device_name != '/device:GPU:0':\n # Raise SystemError('GPU device not found')\n print('GPU device not found')\nelse:\n print('Found GPU at: {}'.format(device_name))\n \n # GPU count and name\n !nvidia-smi -L",
"Found GPU at: /device:GPU:0\nGPU 0: Tesla P100-PCIE-16GB (UUID: GPU-47aa6e31-82c5-f73d-7d78-373fb85348e8)\n"
]
],
[
[
"# Load the Dataset",
"_____no_output_____"
],
[
"## Download and Extract the Dataset",
"_____no_output_____"
]
],
[
[
"# Download the dataset\n!curl -O https://selbystorage.s3-us-west-2.amazonaws.com/research/office_3/office_3.tar.gz",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 257M 100 257M 0 0 23.9M 0 0:00:10 0:00:10 --:--:-- 54.1M\n"
],
[
"data_set = 'office_3'\ntar_file = data_set + '.tar.gz'\n\n# Unzip the .tgz file\n# -x for extract\n# -v for verbose \n# -z for gnuzip\n# -f for file (should come at last just before file name)\n# -C to extract the zipped contents to a different directory\n!tar -xvzf $tar_file",
"office_3/\noffice_3/ml_training_2019-12-26-14-59-40_12.yaml\noffice_3/ml_training_2019-12-28-10-32-38_7.yaml\noffice_3/camera.csv\noffice_3/ml_training_2019-12-26-14-54-02_0.yaml\noffice_3/ml_training_2019-12-28-10-31-15_5.yaml\noffice_3/ml_training_2019-12-26-14-54-58_2.yaml\noffice_3/ml_training_2019-12-26-14-59-11_11.yaml\noffice_3/ml_training_2019-12-28-10-30-32_4.yaml\noffice_3/ml_training_2019-12-26-14-55-25_3.yaml\noffice_3/.~lock.interpolated.csv#\noffice_3/ml_training_2019-12-26-14-58-43_10.yaml\noffice_3/ml_training_2019-12-26-14-57-46_8.yaml\noffice_3/ml_training_2019-12-26-14-56-50_6.yaml\noffice_3/ml_training_2019-12-28-10-27-15_0.yaml\noffice_3/interpolated.csv\noffice_3/steering.csv\noffice_3/ml_training_2019-12-26-14-57-18_7.yaml\noffice_3/ml_training_2019-12-28-10-29-24_3.yaml\noffice_3/ml_training_2019-12-26-14-54-30_1.yaml\noffice_3/ml_training_2019-12-28-10-31-56_6.yaml\noffice_3/ml_training_2019-12-28-10-28-42_2.yaml\noffice_3/ml_training_2019-12-28-10-28-00_1.yaml\noffice_3/ml_training_2019-12-26-14-58-15_9.yaml\noffice_3/center/\noffice_3/center/1577400891034682368.jpg\noffice_3/center/1577401028987062272.jpg\noffice_3/center/1577401061435839744.jpg\noffice_3/center/1577400933587376640.jpg\noffice_3/center/1577401087784848896.jpg\noffice_3/center/1577401021187643392.jpg\noffice_3/center/1577400903084445696.jpg\noffice_3/center/1577400947038852608.jpg\noffice_3/center/1577401157982999296.jpg\noffice_3/center/1577400924187524608.jpg\noffice_3/center/1577400974191615232.jpg\noffice_3/center/1577401095184762112.jpg\noffice_3/center/1577400971191157504.jpg\noffice_3/center/1577400960490674176.jpg\noffice_3/center/1577401183682134784.jpg\noffice_3/center/1577401100634662144.jpg\noffice_3/center/1577401064585897984.jpg\noffice_3/center/1577401169032507904.jpg\noffice_3/center/1577401121884070656.jpg\noffice_3/center/1577401133633318656.jpg\noffice_3/center/1577401125284345600.jpg\noffice_3/center/1577400951989418752.jpg\noffice_3/center/1577401095734939648.jpg\noffice_3/center/1577401163332918272.jpg\noffice_3/center/1577401013188172800.jpg\noffice_3/center/1577401093484875776.jpg\noffice_3/center/1577401067835656192.jpg\noffice_3/center/1577401061535786496.jpg\noffice_3/center/1577400900734519296.jpg\noffice_3/center/1577400928337382656.jpg\noffice_3/center/1577400900984609280.jpg\noffice_3/center/1577400938637807360.jpg\noffice_3/center/1577400889684697856.jpg\noffice_3/center/1577401088285186816.jpg\noffice_3/center/1577401075285670912.jpg\noffice_3/center/1577400860429372672.jpg\noffice_3/center/1577400886334423296.jpg\noffice_3/center/1577401062536097536.jpg\noffice_3/center/1577400853323355648.jpg\noffice_3/center/1577401166333186048.jpg\noffice_3/center/1577400981990101760.jpg\noffice_3/center/1577401048236065536.jpg\noffice_3/center/1577400982289848064.jpg\noffice_3/center/1577401111984628480.jpg\noffice_3/center/1577401099585009152.jpg\noffice_3/center/1577401062336079104.jpg\noffice_3/center/1577400865933780736.jpg\noffice_3/center/1577400933137783808.jpg\noffice_3/center/1577401043486320384.jpg\noffice_3/center/1577401153132941312.jpg\noffice_3/center/1577400884034927104.jpg\noffice_3/center/1577401061235994112.jpg\noffice_3/center/1577400906134054144.jpg\noffice_3/center/1577401031286993408.jpg\noffice_3/center/1577400970641474304.jpg\noffice_3/center/1577401142482921984.jpg\noffice_3/center/1577400899084695040.jpg\noffice_3/center/1577401030937048832.jpg\noffice_3/center/1577400980940552192.jpg\noffice_3/center/1577401016937588224.jpg\noffice_3/center/1577400901284765952.jpg\noffice_3/center/1577401053785902336.jpg\noffice_3/center/1577401142382846720.jpg\noffice_3/center/1577401043786358528.jpg\noffice_3/center/1577400845714396416.jpg\noffice_3/center/1577400865433509632.jpg\noffice_3/center/1577401152483090176.jpg\noffice_3/center/1577401050735870208.jpg\noffice_3/center/1577401030286805760.jpg\noffice_3/center/1577401154783395840.jpg\noffice_3/center/1577400849068341504.jpg\noffice_3/center/1577400881136740096.jpg\noffice_3/center/1577400921087273984.jpg\noffice_3/center/1577400968741049344.jpg\noffice_3/center/1577401164183141632.jpg\noffice_3/center/1577400850220832768.jpg\noffice_3/center/1577401117534666496.jpg\noffice_3/center/1577400848718444544.jpg\noffice_3/center/1577400878536740864.jpg\noffice_3/center/1577401152683130112.jpg\noffice_3/center/1577400875339298560.jpg\noffice_3/center/1577400935687526912.jpg\noffice_3/center/1577400870737925632.jpg\noffice_3/center/1577400858227267072.jpg\noffice_3/center/1577400868985981696.jpg\noffice_3/center/1577400887734491648.jpg\noffice_3/center/1577400935337357824.jpg\noffice_3/center/1577401121484197888.jpg\noffice_3/center/1577401034486761984.jpg\noffice_3/center/1577400934987880704.jpg\noffice_3/center/1577400851871998464.jpg\noffice_3/center/1577400883434326016.jpg\noffice_3/center/1577401102684539904.jpg\noffice_3/center/1577401093184908288.jpg\noffice_3/center/1577400882334761472.jpg\noffice_3/center/1577400946338589696.jpg\noffice_3/center/1577400868235557376.jpg\noffice_3/center/1577400888834625792.jpg\noffice_3/center/1577400897434669824.jpg\noffice_3/center/1577401115884277248.jpg\noffice_3/center/1577400883734500096.jpg\noffice_3/center/1577400916086748672.jpg\noffice_3/center/1577401044536193792.jpg\noffice_3/center/1577401072685998336.jpg\noffice_3/center/1577401159582988800.jpg\noffice_3/center/1577401125134174208.jpg\noffice_3/center/1577401033936805376.jpg\noffice_3/center/1577400925837718016.jpg\noffice_3/center/1577400891935272960.jpg\noffice_3/center/1577401146882805760.jpg\noffice_3/center/1577401024637373696.jpg\noffice_3/center/1577400875838572544.jpg\noffice_3/center/1577401120834313984.jpg\noffice_3/center/1577400880136308224.jpg\noffice_3/center/1577401173032839680.jpg\noffice_3/center/1577401183382154496.jpg\noffice_3/center/1577401081235140608.jpg\noffice_3/center/1577400932487921920.jpg\noffice_3/center/1577401107634914560.jpg\noffice_3/center/1577400928437442816.jpg\noffice_3/center/1577400849018345216.jpg\noffice_3/center/1577401047336372480.jpg\noffice_3/center/1577400910784706048.jpg\noffice_3/center/1577401073585755136.jpg\noffice_3/center/1577400957240026112.jpg\noffice_3/center/1577401077185201664.jpg\noffice_3/center/1577400853973964544.jpg\noffice_3/center/1577400856925310976.jpg\noffice_3/center/1577401063185880320.jpg\noffice_3/center/1577400968141167104.jpg\noffice_3/center/1577400908534518016.jpg\noffice_3/center/1577400943488313344.jpg\noffice_3/center/1577400889284599040.jpg\noffice_3/center/1577401132883820032.jpg\noffice_3/center/1577401161632960000.jpg\noffice_3/center/1577401073635741184.jpg\noffice_3/center/1577400958140198144.jpg\noffice_3/center/1577401092584781824.jpg\noffice_3/center/1577401140633552128.jpg\noffice_3/center/1577400928737602560.jpg\noffice_3/center/1577400855374350080.jpg\noffice_3/center/1577400951088836096.jpg\noffice_3/center/1577401180882240256.jpg\noffice_3/center/1577401148782834432.jpg\noffice_3/center/1577400881286618112.jpg\noffice_3/center/1577400844513289216.jpg\noffice_3/center/1577401015187730176.jpg\noffice_3/center/1577400899584348416.jpg\noffice_3/center/1577401047736017408.jpg\noffice_3/center/1577401022187378176.jpg\noffice_3/center/1577400861930494720.jpg\noffice_3/center/1577401083385577216.jpg\noffice_3/center/1577401103384497664.jpg\noffice_3/center/1577400844213310464.jpg\noffice_3/center/1577400874288225024.jpg\noffice_3/center/1577401019087747584.jpg\noffice_3/center/1577400890984675072.jpg\noffice_3/center/1577401119034322176.jpg\noffice_3/center/1577400955739785984.jpg\noffice_3/center/1577400943038342144.jpg\noffice_3/center/1577400847065650432.jpg\noffice_3/center/1577401150383237632.jpg\noffice_3/center/1577400925937620480.jpg\noffice_3/center/1577400886584691968.jpg\noffice_3/center/1577401179282192640.jpg\noffice_3/center/1577400940387686144.jpg\noffice_3/center/1577401128433215744.jpg\noffice_3/center/1577400961090410496.jpg\noffice_3/center/1577400961540375808.jpg\noffice_3/center/1577401134632841472.jpg\noffice_3/center/1577400880886559488.jpg\noffice_3/center/1577401100334717696.jpg\noffice_3/center/1577400864732589824.jpg\noffice_3/center/1577401136482881024.jpg\noffice_3/center/1577401079735441152.jpg\noffice_3/center/1577400959940336128.jpg\noffice_3/center/1577401182082521856.jpg\noffice_3/center/1577400847666999040.jpg\noffice_3/center/1577400901184711936.jpg\noffice_3/center/1577400855574773760.jpg\noffice_3/center/1577401084185118208.jpg\noffice_3/center/1577400931437509632.jpg\noffice_3/center/1577400858277408768.jpg\noffice_3/center/1577400974141655808.jpg\noffice_3/center/1577401041886412288.jpg\noffice_3/center/1577400905534517248.jpg\noffice_3/center/1577401118884448256.jpg\noffice_3/center/1577400942087715072.jpg\noffice_3/center/1577400967391136512.jpg\noffice_3/center/1577400871187993088.jpg\noffice_3/center/1577401117984693504.jpg\noffice_3/center/1577400917536741888.jpg\noffice_3/center/1577401129633660416.jpg\noffice_3/center/1577401097884363520.jpg\noffice_3/center/1577400867084791296.jpg\noffice_3/center/1577400887984885760.jpg\noffice_3/center/1577400925987578112.jpg\noffice_3/center/1577401038635892224.jpg\noffice_3/center/1577401060585961728.jpg\noffice_3/center/1577400867585229056.jpg\noffice_3/center/1577400955239780608.jpg\noffice_3/center/1577400844013053184.jpg\noffice_3/center/1577400928037018880.jpg\noffice_3/center/1577400875888429312.jpg\noffice_3/center/1577400920837216256.jpg\noffice_3/center/1577401172582079488.jpg\noffice_3/center/1577400900284609792.jpg\noffice_3/center/1577400849569398528.jpg\noffice_3/center/1577401171882794752.jpg\noffice_3/center/1577401021537622784.jpg\noffice_3/center/1577400890184977152.jpg\noffice_3/center/1577400900934574080.jpg\noffice_3/center/1577400957490062848.jpg\noffice_3/center/1577401179531812608.jpg\noffice_3/center/1577401065585789184.jpg\noffice_3/center/1577401059085690624.jpg\noffice_3/center/1577401021437723648.jpg\noffice_3/center/1577401141783614464.jpg\noffice_3/center/1577401036486680064.jpg\noffice_3/center/1577400969791450880.jpg\noffice_3/center/1577401050285910016.jpg\noffice_3/center/1577400926587236608.jpg\noffice_3/center/1577401162732702208.jpg\noffice_3/center/1577400908034526976.jpg\noffice_3/center/1577401058085922048.jpg\noffice_3/center/1577400920287169536.jpg\noffice_3/center/1577400896634399232.jpg\noffice_3/center/1577401115384443904.jpg\noffice_3/center/1577400914186055936.jpg\noffice_3/center/1577401155633259776.jpg\noffice_3/center/1577401172532025088.jpg\noffice_3/center/1577401023187521280.jpg\noffice_3/center/1577401058386283776.jpg\noffice_3/center/1577401032286601472.jpg\noffice_3/center/1577401086734747904.jpg\noffice_3/center/1577401091185421824.jpg\noffice_3/center/1577401162283248128.jpg\noffice_3/center/1577400975341889280.jpg\noffice_3/center/1577400961240444416.jpg\noffice_3/center/1577401040936376576.jpg\noffice_3/center/1577400876287751168.jpg\noffice_3/center/1577401079985413632.jpg\noffice_3/center/1577400900234603008.jpg\noffice_3/center/1577400929537490944.jpg\noffice_3/center/1577401092934847744.jpg\noffice_3/center/1577401148983011328.jpg\noffice_3/center/1577400920437251584.jpg\noffice_3/center/1577401085335261696.jpg\noffice_3/center/1577401056186291456.jpg\noffice_3/center/1577401094634777344.jpg\noffice_3/center/1577401137583415808.jpg\noffice_3/center/1577401137233567488.jpg\noffice_3/center/1577400972941968128.jpg\noffice_3/center/1577401084935146240.jpg\noffice_3/center/1577401044186282496.jpg\noffice_3/center/1577401106884687360.jpg\noffice_3/center/1577400906934283776.jpg\noffice_3/center/1577401091235384832.jpg\noffice_3/center/1577401117484613376.jpg\noffice_3/center/1577400937137958656.jpg\noffice_3/center/1577400962290601216.jpg\noffice_3/center/1577401112234320128.jpg\noffice_3/center/1577401043336282368.jpg\noffice_3/center/1577401058436372992.jpg\noffice_3/center/1577401168732432384.jpg\noffice_3/center/1577400915236179200.jpg\noffice_3/center/1577400944838565376.jpg\noffice_3/center/1577400949139160576.jpg\noffice_3/center/1577400855274477824.jpg\noffice_3/center/1577401034036836352.jpg\noffice_3/center/1577401157132691456.jpg\noffice_3/center/1577400885834833664.jpg\noffice_3/center/1577401147283506176.jpg\noffice_3/center/1577400943838122752.jpg\noffice_3/center/1577400932287720192.jpg\noffice_3/center/1577400966840685824.jpg\noffice_3/center/1577401157532803584.jpg\noffice_3/center/1577400862380551168.jpg\noffice_3/center/1577401183482172928.jpg\noffice_3/center/1577401171382449408.jpg\noffice_3/center/1577400867435152640.jpg\noffice_3/center/1577401083735146752.jpg\noffice_3/center/1577400944688454144.jpg\noffice_3/center/1577401045886198528.jpg\noffice_3/center/1577400882085207552.jpg\noffice_3/center/1577400980590323200.jpg\noffice_3/center/1577400930437538560.jpg\noffice_3/center/1577400928887730688.jpg\noffice_3/center/1577401075585534720.jpg\noffice_3/center/1577400846165599488.jpg\noffice_3/center/1577401042186311168.jpg\noffice_3/center/1577400978490873344.jpg\noffice_3/center/1577400903334345216.jpg\noffice_3/center/1577400967541193728.jpg\noffice_3/center/1577400896684432384.jpg\noffice_3/center/1577400882884853248.jpg\noffice_3/center/1577401174182705408.jpg\noffice_3/center/1577400948338768128.jpg\noffice_3/center/1577401059435583488.jpg\noffice_3/center/1577401025337434624.jpg\noffice_3/center/1577401088635041280.jpg\noffice_3/center/1577400916386730240.jpg\noffice_3/center/1577400979341227776.jpg\noffice_3/center/1577400857477322752.jpg\noffice_3/center/1577400868435903744.jpg\noffice_3/center/1577401157332677888.jpg\noffice_3/center/1577401050685870336.jpg\noffice_3/center/1577400849368684800.jpg\noffice_3/center/1577401141583174656.jpg\noffice_3/center/1577401176682216448.jpg\noffice_3/center/1577400908234770176.jpg\noffice_3/center/1577401034186793216.jpg\noffice_3/center/1577401131933502208.jpg\noffice_3/center/1577401153582823680.jpg\noffice_3/center/1577401087285328384.jpg\noffice_3/center/1577401084685285632.jpg\noffice_3/center/1577400974041644800.jpg\noffice_3/center/1577401041586468096.jpg\noffice_3/center/1577401055886052608.jpg\noffice_3/center/1577400916736670208.jpg\noffice_3/center/1577401044686138368.jpg\noffice_3/center/1577401054035881216.jpg\noffice_3/center/1577401102584499712.jpg\noffice_3/center/1577401058286070272.jpg\noffice_3/center/1577400942838577408.jpg\noffice_3/center/1577401182981748480.jpg\noffice_3/center/1577400906784494592.jpg\noffice_3/center/1577400933387610368.jpg\noffice_3/center/1577401155082736384.jpg\noffice_3/center/1577401118834462464.jpg\noffice_3/center/1577401031087034368.jpg\noffice_3/center/1577401071585888512.jpg\noffice_3/center/1577400967991123456.jpg\noffice_3/center/1577401043836364800.jpg\noffice_3/center/1577401143533278208.jpg\noffice_3/center/1577401051885861376.jpg\noffice_3/center/1577401044036344576.jpg\noffice_3/center/1577401165732486656.jpg\noffice_3/center/1577401081835181312.jpg\noffice_3/center/1577401154633336576.jpg\noffice_3/center/1577400914236101888.jpg\noffice_3/center/1577400964190896896.jpg\noffice_3/center/1577400892434858240.jpg\noffice_3/center/1577401108484567296.jpg\noffice_3/center/1577400932187704320.jpg\noffice_3/center/1577400973141772032.jpg\noffice_3/center/1577400887234578688.jpg\noffice_3/center/1577401026187053312.jpg\noffice_3/center/1577400851171371776.jpg\noffice_3/center/1577400893635087104.jpg\noffice_3/center/1577401182032494336.jpg\noffice_3/center/1577400952189280256.jpg\noffice_3/center/1577401094934859264.jpg\noffice_3/center/1577401175982499840.jpg\noffice_3/center/1577400861680440320.jpg\noffice_3/center/1577401160682978304.jpg\noffice_3/center/1577400950439501312.jpg\noffice_3/center/1577401117284374272.jpg\noffice_3/center/1577401156332783616.jpg\noffice_3/center/1577401151282894080.jpg\noffice_3/center/1577401102534480384.jpg\noffice_3/center/1577401130233623552.jpg\noffice_3/center/1577401143883232768.jpg\noffice_3/center/1577400889584704768.jpg\noffice_3/center/1577400980390333696.jpg\noffice_3/center/1577401139383608064.jpg\noffice_3/center/1577401056036248832.jpg\noffice_3/center/1577401026637478656.jpg\noffice_3/center/1577400962990718464.jpg\noffice_3/center/1577400930487569920.jpg\noffice_3/center/1577400932437891584.jpg\noffice_3/center/1577401171832811520.jpg\noffice_3/center/1577400935837696000.jpg\noffice_3/center/1577400937287559680.jpg\noffice_3/center/1577400951789555712.jpg\noffice_3/center/1577400884584314624.jpg\noffice_3/center/1577400871838925568.jpg\noffice_3/center/1577401058686574848.jpg\noffice_3/center/1577400928287285760.jpg\noffice_3/center/1577400978991093504.jpg\noffice_3/center/1577401124283985152.jpg\noffice_3/center/1577401051485761536.jpg\noffice_3/center/1577400955139813888.jpg\noffice_3/center/1577400971891763968.jpg\noffice_3/center/1577400975841665024.jpg\noffice_3/center/1577401166082908928.jpg\noffice_3/center/1577401023887246336.jpg\noffice_3/center/1577401184831943168.jpg\noffice_3/center/1577401012338253312.jpg\noffice_3/center/1577400858377672192.jpg\noffice_3/center/1577400888235190016.jpg\noffice_3/center/1577401048835945216.jpg\noffice_3/center/1577401066885809664.jpg\noffice_3/center/1577401015137719552.jpg\noffice_3/center/1577400927187472384.jpg\noffice_3/center/1577401165582720256.jpg\noffice_3/center/1577401053135852032.jpg\noffice_3/center/1577400866183952384.jpg\noffice_3/center/1577400844313359616.jpg\noffice_3/center/1577400949689075712.jpg\noffice_3/center/1577401138483497472.jpg\noffice_3/center/1577401086235064832.jpg\noffice_3/center/1577401173982463488.jpg\noffice_3/center/1577401168782415872.jpg\noffice_3/center/1577401130733722880.jpg\noffice_3/center/1577401070135990272.jpg\noffice_3/center/1577400952489529088.jpg\noffice_3/center/1577401048935875072.jpg\noffice_3/center/1577400884834386432.jpg\noffice_3/center/1577400899734440192.jpg\noffice_3/center/1577401144683648256.jpg\noffice_3/center/1577400865133297408.jpg\noffice_3/center/1577401117334391808.jpg\noffice_3/center/1577401055735772416.jpg\noffice_3/center/1577400964290907136.jpg\noffice_3/center/1577401018337594368.jpg\noffice_3/center/1577401019487696640.jpg\noffice_3/center/1577400886784777984.jpg\noffice_3/center/1577401030436838144.jpg\noffice_3/center/1577400969141206272.jpg\noffice_3/center/1577401052386020096.jpg\noffice_3/center/1577400952689860608.jpg\noffice_3/center/1577401066535683840.jpg\noffice_3/center/1577400893485057536.jpg\noffice_3/center/1577400921437169408.jpg\noffice_3/center/1577401042286329856.jpg\noffice_3/center/1577401040636561920.jpg\noffice_3/center/1577401079085555712.jpg\noffice_3/center/1577401070585896448.jpg\noffice_3/center/1577401130633571584.jpg\noffice_3/center/1577401159732900864.jpg\noffice_3/center/1577400875988272640.jpg\noffice_3/center/1577401100984597760.jpg\noffice_3/center/1577400908834151168.jpg\noffice_3/center/1577401081935347968.jpg\noffice_3/center/1577401167032376064.jpg\noffice_3/center/1577400910384733440.jpg\noffice_3/center/1577401056286262528.jpg\noffice_3/center/1577401028587112192.jpg\noffice_3/center/1577401126933707520.jpg\noffice_3/center/1577400866384123136.jpg\noffice_3/center/1577400919537206016.jpg\noffice_3/center/1577400889534647552.jpg\noffice_3/center/1577401143483296512.jpg\noffice_3/center/1577401137183555072.jpg\noffice_3/center/1577401152583131392.jpg\noffice_3/center/1577401051135814144.jpg\noffice_3/center/1577400968341079040.jpg\noffice_3/center/1577400878636980736.jpg\noffice_3/center/1577400957639949824.jpg\noffice_3/center/1577401014987678720.jpg\noffice_3/center/1577401105134580224.jpg\noffice_3/center/1577400967841185792.jpg\noffice_3/center/1577401141333173248.jpg\noffice_3/center/1577401123234077696.jpg\noffice_3/center/1577401073835826432.jpg\noffice_3/center/1577400964940851712.jpg\noffice_3/center/1577400948089073920.jpg\noffice_3/center/1577401042536302080.jpg\noffice_3/center/1577400877338672896.jpg\noffice_3/center/1577401025587538176.jpg\noffice_3/center/1577401178932652544.jpg\noffice_3/center/1577400958340104192.jpg\noffice_3/center/1577401094035078144.jpg\noffice_3/center/1577401137483510272.jpg\noffice_3/center/1577401119784366080.jpg\noffice_3/center/1577401095034872064.jpg\noffice_3/center/1577401141633211392.jpg\noffice_3/center/1577400945638461440.jpg\noffice_3/center/1577400887684488960.jpg\noffice_3/center/1577401141483140608.jpg\noffice_3/center/1577400892334982144.jpg\noffice_3/center/1577401049685995264.jpg\noffice_3/center/1577400940287786496.jpg\noffice_3/center/1577401127433811200.jpg\noffice_3/center/1577400886684765184.jpg\noffice_3/center/1577400967291005952.jpg\noffice_3/center/1577401131083817472.jpg\noffice_3/center/1577400883184681216.jpg\noffice_3/center/1577401155532872960.jpg\noffice_3/center/1577401046835733504.jpg\noffice_3/center/1577401070835770624.jpg\noffice_3/center/1577401025737408000.jpg\noffice_3/center/1577400875588799488.jpg\noffice_3/center/1577400971141125376.jpg\noffice_3/center/1577400883134770432.jpg\noffice_3/center/1577400959490236416.jpg\noffice_3/center/1577401043436305408.jpg\noffice_3/center/1577401177082252032.jpg\noffice_3/center/1577401173382082560.jpg\noffice_3/center/1577400909784846592.jpg\noffice_3/center/1577401068785846528.jpg\noffice_3/center/1577401074085760512.jpg\noffice_3/center/1577401034836871680.jpg\noffice_3/center/1577401177982372096.jpg\noffice_3/center/1577400965590782976.jpg\noffice_3/center/1577401174532562688.jpg\noffice_3/center/1577400981340022272.jpg\noffice_3/center/1577400916886755072.jpg\noffice_3/center/1577401173182728704.jpg\noffice_3/center/1577401046136254208.jpg\noffice_3/center/1577400932037577472.jpg\noffice_3/center/1577400956190070272.jpg\noffice_3/center/1577401119884373248.jpg\noffice_3/center/1577400858126953472.jpg\noffice_3/center/1577400858728390912.jpg\noffice_3/center/1577401114534080000.jpg\noffice_3/center/1577400863231399424.jpg\noffice_3/center/1577400914436410368.jpg\noffice_3/center/1577401124683958272.jpg\noffice_3/center/1577400981890096128.jpg\noffice_3/center/1577401132183583744.jpg\noffice_3/center/1577400907784265472.jpg\noffice_3/center/1577401072335667456.jpg\noffice_3/center/1577401108334393600.jpg\noffice_3/center/1577400887384530944.jpg\noffice_3/center/1577401079435463168.jpg\noffice_3/center/1577401037436503040.jpg\noffice_3/center/1577401054385650432.jpg\noffice_3/center/1577401045035769856.jpg\noffice_3/center/1577400872089435136.jpg\noffice_3/center/1577401068435847168.jpg\noffice_3/center/1577401124034124544.jpg\noffice_3/center/1577400910734729728.jpg\noffice_3/center/1577401116184419328.jpg\noffice_3/center/1577401096134808832.jpg\noffice_3/center/1577401138133426432.jpg\noffice_3/center/1577401159832913920.jpg\noffice_3/center/1577401086634813184.jpg\noffice_3/center/1577400950289390848.jpg\noffice_3/center/1577400967040788480.jpg\noffice_3/center/1577400963690385920.jpg\noffice_3/center/1577401017337743616.jpg\noffice_3/center/1577401020637274624.jpg\noffice_3/center/1577401182582025728.jpg\noffice_3/center/1577401147183271424.jpg\noffice_3/center/1577401027387383040.jpg\noffice_3/center/1577401082784703488.jpg\noffice_3/center/1577401139983560448.jpg\noffice_3/center/1577401069885762048.jpg\noffice_3/center/1577401066835658752.jpg\noffice_3/center/1577401126734021888.jpg\noffice_3/center/1577401043236275712.jpg\noffice_3/center/1577401064236012288.jpg\noffice_3/center/1577400867385182464.jpg\noffice_3/center/1577400971591621888.jpg\noffice_3/center/1577400959440256256.jpg\noffice_3/center/1577401146183621120.jpg\noffice_3/center/1577401122884332032.jpg\noffice_3/center/1577401012938108416.jpg\noffice_3/center/1577401014238679552.jpg\noffice_3/center/1577401095484692736.jpg\noffice_3/center/1577400851672098048.jpg\noffice_3/center/1577400980090439424.jpg\noffice_3/center/1577400952789896192.jpg\noffice_3/center/1577401128233278464.jpg\noffice_3/center/1577401051085816576.jpg\noffice_3/center/1577400891885240320.jpg\noffice_3/center/1577401138083408384.jpg\noffice_3/center/1577401145983640064.jpg\noffice_3/center/1577401170282329600.jpg\noffice_3/center/1577400878036993024.jpg\noffice_3/center/1577400888335151616.jpg\noffice_3/center/1577401011688661504.jpg\noffice_3/center/1577401166932067584.jpg\noffice_3/center/1577400946588699392.jpg\noffice_3/center/1577400882934843648.jpg\noffice_3/center/1577400921337257216.jpg\noffice_3/center/1577401031586834176.jpg\noffice_3/center/1577401150182657024.jpg\noffice_3/center/1577400894184668160.jpg\noffice_3/center/1577400941088159744.jpg\noffice_3/center/1577401093884885504.jpg\noffice_3/center/1577401149483583488.jpg\noffice_3/center/1577401136682646784.jpg\noffice_3/center/1577400881336509696.jpg\noffice_3/center/1577401042336329472.jpg\noffice_3/center/1577400911384587008.jpg\noffice_3/center/1577400973641555200.jpg\noffice_3/center/1577401097934257664.jpg\noffice_3/center/1577401167882111232.jpg\noffice_3/center/1577401137533510400.jpg\noffice_3/center/1577400970091241472.jpg\noffice_3/center/1577401088985031936.jpg\noffice_3/center/1577400949189110272.jpg\noffice_3/center/1577400910634763776.jpg\noffice_3/center/1577400953489598208.jpg\noffice_3/center/1577400949889135104.jpg\noffice_3/center/1577401113734297344.jpg\noffice_3/center/1577401133383843072.jpg\noffice_3/center/1577401169732410880.jpg\noffice_3/center/1577401050885826816.jpg\noffice_3/center/1577400960290644992.jpg\noffice_3/center/1577401087385123328.jpg\noffice_3/center/1577400970191173632.jpg\noffice_3/center/1577400907734230272.jpg\noffice_3/center/1577401177432435200.jpg\noffice_3/center/1577400852573050880.jpg\noffice_3/center/1577401133733190144.jpg\noffice_3/center/1577401085235169280.jpg\noffice_3/center/1577400935437327872.jpg\noffice_3/center/1577400950339433984.jpg\noffice_3/center/1577400848918418688.jpg\noffice_3/center/1577400882035334144.jpg\noffice_3/center/1577400911684926208.jpg\noffice_3/center/1577401182881796352.jpg\noffice_3/center/1577401111635039232.jpg\noffice_3/center/1577401175432444928.jpg\noffice_3/center/1577401025687472640.jpg\noffice_3/center/1577400893934955008.jpg\noffice_3/center/1577401074835876864.jpg\noffice_3/center/1577401036336715520.jpg\noffice_3/center/1577401168682475776.jpg\noffice_3/center/1577401013088148224.jpg\noffice_3/center/1577400977590989568.jpg\noffice_3/center/1577401073685774336.jpg\noffice_3/center/1577400872587795968.jpg\noffice_3/center/1577401012288263680.jpg\noffice_3/center/1577400885034457856.jpg\noffice_3/center/1577401183232023296.jpg\noffice_3/center/1577400892834751232.jpg\noffice_3/center/1577401016638371584.jpg\noffice_3/center/1577400973991643648.jpg\noffice_3/center/1577400907534249984.jpg\noffice_3/center/1577400871738485248.jpg\noffice_3/center/1577400923387156736.jpg\noffice_3/center/1577400880535734784.jpg\noffice_3/center/1577401107334396928.jpg\noffice_3/center/1577401114484197120.jpg\noffice_3/center/1577400916636614912.jpg\noffice_3/center/1577401114834731776.jpg\noffice_3/center/1577401150282922752.jpg\noffice_3/center/1577401027837249280.jpg\noffice_3/center/1577400880786273024.jpg\noffice_3/center/1577400946188720640.jpg\noffice_3/center/1577400865783728128.jpg\noffice_3/center/1577400880485727488.jpg\noffice_3/center/1577401039236808960.jpg\noffice_3/center/1577400862180492800.jpg\noffice_3/center/1577401035036817920.jpg\noffice_3/center/1577400865233341184.jpg\noffice_3/center/1577400966490842624.jpg\noffice_3/center/1577401147082986240.jpg\noffice_3/center/1577401076135748096.jpg\noffice_3/center/1577401167932107264.jpg\noffice_3/center/1577400973891660032.jpg\noffice_3/center/1577401028887040768.jpg\noffice_3/center/1577401103284405248.jpg\noffice_3/center/1577401140333522432.jpg\noffice_3/center/1577401055086172160.jpg\noffice_3/center/1577401070985665280.jpg\noffice_3/center/1577401025987044352.jpg\noffice_3/center/1577400878086726912.jpg\noffice_3/center/1577401183181962496.jpg\noffice_3/center/1577401125883261952.jpg\noffice_3/center/1577401157482798336.jpg\noffice_3/center/1577400845063418624.jpg\noffice_3/center/1577400940038220032.jpg\noffice_3/center/1577401085135100160.jpg\noffice_3/center/1577401080235591936.jpg\noffice_3/center/1577401010938280192.jpg\noffice_3/center/1577400925537275392.jpg\noffice_3/center/1577400961740490240.jpg\noffice_3/center/1577400889634708992.jpg\noffice_3/center/1577400866233918464.jpg\noffice_3/center/1577401042936251392.jpg\noffice_3/center/1577400849970336000.jpg\noffice_3/center/1577401023287313664.jpg\noffice_3/center/1577400908684292608.jpg\noffice_3/center/1577400877538401280.jpg\noffice_3/center/1577401035136754432.jpg\noffice_3/center/1577401056635832832.jpg\noffice_3/center/1577400902634364416.jpg\noffice_3/center/1577400913285578240.jpg\noffice_3/center/1577401042136322304.jpg\noffice_3/center/1577400932937846272.jpg\noffice_3/center/1577400914936180480.jpg\noffice_3/center/1577401085185127936.jpg\noffice_3/center/1577401138533432064.jpg\noffice_3/center/1577401167082555904.jpg\noffice_3/center/1577401158682935552.jpg\noffice_3/center/1577400872388158464.jpg\noffice_3/center/1577401030486865152.jpg\noffice_3/center/1577401184031953408.jpg\noffice_3/center/1577401130983854336.jpg\noffice_3/center/1577400951739629824.jpg\noffice_3/center/1577400942988403712.jpg\noffice_3/center/1577400895734698496.jpg\noffice_3/center/1577401164033089792.jpg\noffice_3/center/1577401131333730048.jpg\noffice_3/center/1577400936087782656.jpg\noffice_3/center/1577401013588164096.jpg\noffice_3/center/1577401148832857344.jpg\noffice_3/center/1577400877837672448.jpg\noffice_3/center/1577401034236771072.jpg\noffice_3/center/1577401055335579904.jpg\noffice_3/center/1577400845313480960.jpg\noffice_3/center/1577400967891172096.jpg\noffice_3/center/1577400945988701440.jpg\noffice_3/center/1577400851821945856.jpg\noffice_3/center/1577401072736038400.jpg\noffice_3/center/1577400938687703552.jpg\noffice_3/center/1577400975691814144.jpg\noffice_3/center/1577401159383020544.jpg\noffice_3/center/1577400941738036992.jpg\noffice_3/center/1577401166032784640.jpg\noffice_3/center/1577401156582384128.jpg\noffice_3/center/1577401102784564224.jpg\noffice_3/center/1577400882684727808.jpg\noffice_3/center/1577401112484550656.jpg\noffice_3/center/1577401092634767872.jpg\noffice_3/center/1577400946988935424.jpg\noffice_3/center/1577401108834824192.jpg\noffice_3/center/1577401077685991680.jpg\noffice_3/center/1577401086834897664.jpg\noffice_3/center/1577401099484966400.jpg\noffice_3/center/1577400951589708544.jpg\noffice_3/center/1577401023137615616.jpg\noffice_3/center/1577400912885762560.jpg\noffice_3/center/1577401064785970944.jpg\noffice_3/center/1577401123434104320.jpg\noffice_3/center/1577400979241343488.jpg\noffice_3/center/1577400892734711296.jpg\noffice_3/center/1577401112934813952.jpg\noffice_3/center/1577401065086021632.jpg\noffice_3/center/1577400957990161152.jpg\noffice_3/center/1577401184431813632.jpg\noffice_3/center/1577401140183511040.jpg\noffice_3/center/1577401052185849856.jpg\noffice_3/center/1577401107184312320.jpg\noffice_3/center/1577401035586986240.jpg\noffice_3/center/1577400915786614272.jpg\noffice_3/center/1577400871287896320.jpg\noffice_3/center/1577401142983583744.jpg\noffice_3/center/1577400869787166464.jpg\noffice_3/center/1577400966990739200.jpg\noffice_3/center/1577401025437475840.jpg\noffice_3/center/1577400860879692544.jpg\noffice_3/center/1577400873989133568.jpg\noffice_3/center/1577400969041074176.jpg\noffice_3/center/1577401131783506432.jpg\noffice_3/center/1577401150833454592.jpg\noffice_3/center/1577400967140890624.jpg\noffice_3/center/1577400879986436352.jpg\noffice_3/center/1577400860829629696.jpg\noffice_3/center/1577400895235034880.jpg\noffice_3/center/1577401083435552256.jpg\noffice_3/center/1577400873439035136.jpg\noffice_3/center/1577400961790549504.jpg\noffice_3/center/1577400881785432320.jpg\noffice_3/center/1577401068135690496.jpg\noffice_3/center/1577400936887959552.jpg\noffice_3/center/1577401023087694336.jpg\noffice_3/center/1577400935487351552.jpg\noffice_3/center/1577400892384937472.jpg\noffice_3/center/1577401079585461504.jpg\noffice_3/center/1577401026337166848.jpg\noffice_3/center/1577400974591606272.jpg\noffice_3/center/1577400924737304576.jpg\noffice_3/center/1577400913635618560.jpg\noffice_3/center/1577400848318180352.jpg\noffice_3/center/1577401030736945664.jpg\noffice_3/center/1577401160383201792.jpg\noffice_3/center/1577401171332412416.jpg\noffice_3/center/1577400946388561152.jpg\noffice_3/center/1577400889384599296.jpg\noffice_3/center/1577401175482299136.jpg\noffice_3/center/1577401091335238400.jpg\noffice_3/center/1577401108934832128.jpg\noffice_3/center/1577401078635338752.jpg\noffice_3/center/1577400888185206272.jpg\noffice_3/center/1577401038735711488.jpg\noffice_3/center/1577400982189899264.jpg\noffice_3/center/1577400874338206976.jpg\noffice_3/center/1577401156732446464.jpg\noffice_3/center/1577400861330034432.jpg\noffice_3/center/1577401128283208704.jpg\noffice_3/center/1577401057486072064.jpg\noffice_3/center/1577401015687929344.jpg\noffice_3/center/1577401088035130112.jpg\noffice_3/center/1577401092034733568.jpg\noffice_3/center/1577400888434954240.jpg\noffice_3/center/1577401161382896128.jpg\noffice_3/center/1577400906584811008.jpg\noffice_3/center/1577401047636133632.jpg\noffice_3/center/1577401112984750336.jpg\noffice_3/center/1577400861229966080.jpg\noffice_3/center/1577400859628155136.jpg\noffice_3/center/1577400934437916160.jpg\noffice_3/center/1577401072635976704.jpg\noffice_3/center/1577400937987925248.jpg\noffice_3/center/1577401094984870144.jpg\noffice_3/center/1577401163733094912.jpg\noffice_3/center/1577400846065352192.jpg\noffice_3/center/1577401074035773952.jpg\noffice_3/center/1577400857876408576.jpg\noffice_3/center/1577400923187115264.jpg\noffice_3/center/1577400910884653056.jpg\noffice_3/center/1577400857826401024.jpg\noffice_3/center/1577400965340430592.jpg\noffice_3/center/1577400981090515456.jpg\noffice_3/center/1577401064936013824.jpg\noffice_3/center/1577401149133276928.jpg\noffice_3/center/1577400897834513920.jpg\noffice_3/center/1577401163983079424.jpg\noffice_3/center/1577400847917153792.jpg\noffice_3/center/1577400891684981760.jpg\noffice_3/center/1577400950789299968.jpg\noffice_3/center/1577400859477881344.jpg\noffice_3/center/1577400863181427456.jpg\noffice_3/center/1577400869636923136.jpg\noffice_3/center/1577401042686204928.jpg\noffice_3/center/1577401121734071808.jpg\noffice_3/center/1577401109684756480.jpg\noffice_3/center/1577401020837188608.jpg\noffice_3/center/1577401097684981504.jpg\noffice_3/center/1577400869286178560.jpg\noffice_3/center/1577401018787870208.jpg\noffice_3/center/1577400961140428032.jpg\noffice_3/center/1577401169582525696.jpg\noffice_3/center/1577400876937870848.jpg\noffice_3/center/1577401125733596928.jpg\noffice_3/center/1577400942738582784.jpg\noffice_3/center/1577400845513899776.jpg\noffice_3/center/1577401027487300864.jpg\noffice_3/center/1577401010738357248.jpg\noffice_3/center/1577400937187826176.jpg\noffice_3/center/1577401011438543104.jpg\noffice_3/center/1577400896534357760.jpg\noffice_3/center/1577401102734548224.jpg\noffice_3/center/1577401037836670976.jpg\noffice_3/center/1577401031936642816.jpg\noffice_3/center/1577401082834764032.jpg\noffice_3/center/1577401135083888128.jpg\noffice_3/center/1577400952389434368.jpg\noffice_3/center/1577401116584423168.jpg\noffice_3/center/1577401079235445760.jpg\noffice_3/center/1577401031237015552.jpg\noffice_3/center/1577401172332065792.jpg\noffice_3/center/1577401030686920448.jpg\noffice_3/center/1577400902734415360.jpg\noffice_3/center/1577401060036030208.jpg\noffice_3/center/1577401173932322560.jpg\noffice_3/center/1577401168582562816.jpg\noffice_3/center/1577401121284371712.jpg\noffice_3/center/1577401082385419264.jpg\noffice_3/center/1577401180932255232.jpg\noffice_3/center/1577401044786007296.jpg\noffice_3/center/1577400971341262592.jpg\noffice_3/center/1577401059485662208.jpg\noffice_3/center/1577401093734811904.jpg\noffice_3/center/1577401104134268160.jpg\noffice_3/center/1577400957890103296.jpg\noffice_3/center/1577400929737117440.jpg\noffice_3/center/1577401106184184576.jpg\noffice_3/center/1577400859678361088.jpg\noffice_3/center/1577401146383448320.jpg\noffice_3/center/1577400925487115264.jpg\noffice_3/center/1577400948989184768.jpg\noffice_3/center/1577401041836414464.jpg\noffice_3/center/1577400894684921856.jpg\noffice_3/center/1577401174332676096.jpg\noffice_3/center/1577401034286744576.jpg\noffice_3/center/1577401045235915264.jpg\noffice_3/center/1577401122634252544.jpg\noffice_3/center/1577400963240434688.jpg\noffice_3/center/1577400893385038336.jpg\noffice_3/center/1577400892634635008.jpg\noffice_3/center/1577401035336698368.jpg\noffice_3/center/1577401147882988288.jpg\noffice_3/center/1577400959690205440.jpg\noffice_3/center/1577400852673065728.jpg\noffice_3/center/1577401176032544000.jpg\noffice_3/center/1577401106984534016.jpg\noffice_3/center/1577401068035625216.jpg\noffice_3/center/1577400848768470784.jpg\noffice_3/center/1577400927137307648.jpg\noffice_3/center/1577401021087476736.jpg\noffice_3/center/1577401021987355904.jpg\noffice_3/center/1577401054435666944.jpg\noffice_3/center/1577401137433472512.jpg\noffice_3/center/1577400930687600128.jpg\noffice_3/center/1577400965691003392.jpg\noffice_3/center/1577400857577105920.jpg\noffice_3/center/1577401091385134336.jpg\noffice_3/center/1577400846015101952.jpg\noffice_3/center/1577401018137738496.jpg\noffice_3/center/1577400973391658240.jpg\noffice_3/center/1577401078135335424.jpg\noffice_3/center/1577401133833156608.jpg\noffice_3/center/1577401080285636864.jpg\noffice_3/center/1577400949339107840.jpg\noffice_3/center/1577401038186833408.jpg\noffice_3/center/1577400880836410368.jpg\noffice_3/center/1577401182681907968.jpg\noffice_3/center/1577401157182661120.jpg\noffice_3/center/1577401094584764416.jpg\noffice_3/center/1577401177732333824.jpg\noffice_3/center/1577400921636993024.jpg\noffice_3/center/1577401017187503360.jpg\noffice_3/center/1577401113134530816.jpg\noffice_3/center/1577400876787781888.jpg\noffice_3/center/1577400854023968768.jpg\noffice_3/center/1577401143833231616.jpg\noffice_3/center/1577400978241238528.jpg\noffice_3/center/1577400860179233024.jpg\noffice_3/center/1577401060135991552.jpg\noffice_3/center/1577401081985505024.jpg\noffice_3/center/1577401018837844736.jpg\noffice_3/center/1577401080135550208.jpg\noffice_3/center/1577401019037768192.jpg\noffice_3/center/1577400903384360704.jpg\noffice_3/center/1577401118734432512.jpg\noffice_3/center/1577400981040564736.jpg\noffice_3/center/1577401034636837888.jpg\noffice_3/center/1577401016987509504.jpg\noffice_3/center/1577401054335616768.jpg\noffice_3/center/1577401042386330624.jpg\noffice_3/center/1577401074685709568.jpg\noffice_3/center/1577400947839403008.jpg\noffice_3/center/1577401056585869568.jpg\noffice_3/center/1577400957940161024.jpg\noffice_3/center/1577401091884641280.jpg\noffice_3/center/1577400852372703232.jpg\noffice_3/center/1577401158382894848.jpg\noffice_3/center/1577401096234743040.jpg\noffice_3/center/1577400976741289472.jpg\noffice_3/center/1577401011388478976.jpg\noffice_3/center/1577401081435116032.jpg\noffice_3/center/1577400933187801856.jpg\noffice_3/center/1577400969691389952.jpg\noffice_3/center/1577401072936135424.jpg\noffice_3/center/1577400885234578944.jpg\noffice_3/center/1577400943988016384.jpg\noffice_3/center/1577401096084866560.jpg\noffice_3/center/1577400944088011520.jpg\noffice_3/center/1577401067286346496.jpg\noffice_3/center/1577401019187657728.jpg\noffice_3/center/1577400947338780928.jpg\noffice_3/center/1577401041636448768.jpg\noffice_3/center/1577400943138318592.jpg\noffice_3/center/1577400954439417088.jpg\noffice_3/center/1577400915636467968.jpg\noffice_3/center/1577401047436310528.jpg\noffice_3/center/1577401045936260864.jpg\noffice_3/center/1577401068735837184.jpg\noffice_3/center/1577400955289781504.jpg\noffice_3/center/1577401050785841408.jpg\noffice_3/center/1577400864682593024.jpg\noffice_3/center/1577400915486455296.jpg\noffice_3/center/1577401054886380800.jpg\noffice_3/center/1577400957789974016.jpg\noffice_3/center/1577401090985176576.jpg\noffice_3/center/1577400847716910592.jpg\noffice_3/center/1577400896484366848.jpg\noffice_3/center/1577400895834526720.jpg\noffice_3/center/1577401136133944320.jpg\noffice_3/center/1577401113184450560.jpg\noffice_3/center/1577400871038040832.jpg\noffice_3/center/1577400952139292928.jpg\noffice_3/center/1577400928537505792.jpg\noffice_3/center/1577401043736333824.jpg\noffice_3/center/1577401108734762752.jpg\noffice_3/center/1577401134532947456.jpg\noffice_3/center/1577401107034439168.jpg\noffice_3/center/1577401164982299904.jpg\noffice_3/center/1577401052285962240.jpg\noffice_3/center/1577400919487288320.jpg\noffice_3/center/1577400859327716096.jpg\noffice_3/center/1577401083635292672.jpg\noffice_3/center/1577401173631856640.jpg\noffice_3/center/1577401105184598784.jpg\noffice_3/center/1577400900384611840.jpg\noffice_3/center/1577401149832808704.jpg\noffice_3/center/1577401138983540224.jpg\noffice_3/center/1577400866434104832.jpg\noffice_3/center/1577401181632176128.jpg\noffice_3/center/1577400931787422464.jpg\noffice_3/center/1577401184731909888.jpg\noffice_3/center/1577400918887044864.jpg\noffice_3/center/1577401039636526848.jpg\noffice_3/center/1577400862030432256.jpg\noffice_3/center/1577401155683406848.jpg\noffice_3/center/1577401147683146752.jpg\noffice_3/center/1577400876587709440.jpg\noffice_3/center/1577401051285732352.jpg\noffice_3/center/1577401104234119168.jpg\noffice_3/center/1577400938138056960.jpg\noffice_3/center/1577401094734804736.jpg\noffice_3/center/1577400906234336512.jpg\noffice_3/center/1577400940938024448.jpg\noffice_3/center/1577401041746830848.jpg\noffice_3/center/1577401170832325888.jpg\noffice_3/center/1577401036236659712.jpg\noffice_3/center/1577401162083093504.jpg\noffice_3/center/1577401052135863040.jpg\noffice_3/center/1577400888085086976.jpg\noffice_3/center/1577401013837710336.jpg\noffice_3/center/1577401067086257664.jpg\noffice_3/center/1577400923087148032.jpg\noffice_3/center/1577400922737541376.jpg\noffice_3/center/1577400888285221376.jpg\noffice_3/center/1577401090184952576.jpg\noffice_3/center/1577401176082601472.jpg\noffice_3/center/1577400879836543488.jpg\noffice_3/center/1577401100934577152.jpg\noffice_3/center/1577400850871161344.jpg\noffice_3/center/1577400890484916480.jpg\noffice_3/center/1577400949289083392.jpg\noffice_3/center/1577400856475828480.jpg\noffice_3/center/1577400979540992256.jpg\noffice_3/center/1577401174082606592.jpg\noffice_3/center/1577401162133101312.jpg\noffice_3/center/1577400942337701120.jpg\noffice_3/center/1577401129683662080.jpg\noffice_3/center/1577400880086319616.jpg\noffice_3/center/1577400853073150208.jpg\noffice_3/center/1577401133033996800.jpg\noffice_3/center/1577400899184664064.jpg\noffice_3/center/1577401150883390720.jpg\noffice_3/center/1577401175082630912.jpg\noffice_3/center/1577400957840039168.jpg\noffice_3/center/1577400866584344064.jpg\noffice_3/center/1577400872888883456.jpg\noffice_3/center/1577400936287684352.jpg\noffice_3/center/1577400925437033984.jpg\noffice_3/center/1577400872288632832.jpg\noffice_3/center/1577400963040707584.jpg\noffice_3/center/1577401141433121280.jpg\noffice_3/center/1577401060086017536.jpg\noffice_3/center/1577401167182891520.jpg\noffice_3/center/1577401175132695296.jpg\noffice_3/center/1577401114134430976.jpg\noffice_3/center/1577401168482615552.jpg\noffice_3/center/1577401147583354112.jpg\noffice_3/center/1577401133583386368.jpg\noffice_3/center/1577401046036332800.jpg\noffice_3/center/1577400878987431168.jpg\noffice_3/center/1577400881735528960.jpg\noffice_3/center/1577401123834079232.jpg\noffice_3/center/1577400948688900864.jpg\noffice_3/center/1577401017887905024.jpg\noffice_3/center/1577401124984089856.jpg\noffice_3/center/1577400981140455936.jpg\noffice_3/center/1577401030887037440.jpg\noffice_3/center/1577401143183352832.jpg\noffice_3/center/1577401031686775552.jpg\noffice_3/center/1577400976891356416.jpg\noffice_3/center/1577400940487646464.jpg\noffice_3/center/1577401160233137408.jpg\noffice_3/center/1577401140283538432.jpg\noffice_3/center/1577400889734696192.jpg\noffice_3/center/1577401049235757056.jpg\noffice_3/center/1577401151033056768.jpg\noffice_3/center/1577401076185599488.jpg\noffice_3/center/1577400921786934528.jpg\noffice_3/center/1577401083785088768.jpg\noffice_3/center/1577401026987660288.jpg\noffice_3/center/1577400933337665024.jpg\noffice_3/center/1577401020187492608.jpg\noffice_3/center/1577400920737241344.jpg\noffice_3/center/1577400963440254208.jpg\noffice_3/center/1577401029337106176.jpg\noffice_3/center/1577401161532949504.jpg\noffice_3/center/1577401056535898368.jpg\noffice_3/center/1577401070085944832.jpg\noffice_3/center/1577401118584315136.jpg\noffice_3/center/1577400957390113024.jpg\noffice_3/center/1577400860029063424.jpg\noffice_3/center/1577401102234498560.jpg\noffice_3/center/1577400944037999360.jpg\noffice_3/center/1577400943588311552.jpg\noffice_3/center/1577400949389138176.jpg\noffice_3/center/1577401127883842816.jpg\noffice_3/center/1577401018737855488.jpg\noffice_3/center/1577400954389457664.jpg\noffice_3/center/1577401135433095680.jpg\noffice_3/center/1577401142432857856.jpg\noffice_3/center/1577401026137016320.jpg\noffice_3/center/1577401119284146176.jpg\noffice_3/center/1577401117934768384.jpg\noffice_3/center/1577401162383248640.jpg\noffice_3/center/1577401157932936448.jpg\noffice_3/center/1577401132533520384.jpg\noffice_3/center/1577401170232339712.jpg\noffice_3/center/1577400877787737088.jpg\noffice_3/center/1577401091484915712.jpg\noffice_3/center/1577400871788727808.jpg\noffice_3/center/1577400871638064384.jpg\noffice_3/center/1577400980490321152.jpg\noffice_3/center/1577400859527904768.jpg\noffice_3/center/1577401010988281600.jpg\noffice_3/center/1577400954639527168.jpg\noffice_3/center/1577401171532551680.jpg\noffice_3/center/1577400953339444736.jpg\noffice_3/center/1577401098384927488.jpg\noffice_3/center/1577401082534895872.jpg\noffice_3/center/1577401180182307072.jpg\noffice_3/center/1577401147333537024.jpg\noffice_3/center/1577401078385212672.jpg\noffice_3/center/1577400923587186944.jpg\noffice_3/center/1577401024537403392.jpg\noffice_3/center/1577400862330481152.jpg\noffice_3/center/1577400902084323584.jpg\noffice_3/center/1577400980190423808.jpg\noffice_3/center/1577401102484471552.jpg\noffice_3/center/1577401088335185152.jpg\noffice_3/center/1577400904084352512.jpg\noffice_3/center/1577401136383286016.jpg\noffice_3/center/1577401045536120320.jpg\noffice_3/center/1577401167483203840.jpg\noffice_3/center/1577401055535492352.jpg\noffice_3/center/1577400931187655680.jpg\noffice_3/center/1577400962840748288.jpg\noffice_3/center/1577401168882400512.jpg\noffice_3/center/1577401161132932864.jpg\noffice_3/center/1577401126833824768.jpg\noffice_3/center/1577400855224525312.jpg\noffice_3/center/1577401142733361664.jpg\noffice_3/center/1577401039836279040.jpg\noffice_3/center/1577401181282046976.jpg\noffice_3/center/1577401114084600064.jpg\noffice_3/center/1577401091584721664.jpg\noffice_3/center/1577401069985853696.jpg\noffice_3/center/1577401099434882048.jpg\noffice_3/center/1577401152983076352.jpg\noffice_3/center/1577400936737714176.jpg\noffice_3/center/1577400868185497344.jpg\noffice_3/center/1577401044885818880.jpg\noffice_3/center/1577400965190352384.jpg\noffice_3/center/1577400920137068032.jpg\noffice_3/center/1577401011938527488.jpg\noffice_3/center/1577401126384164352.jpg\noffice_3/center/1577401143383279360.jpg\noffice_3/center/1577401183282087680.jpg\noffice_3/center/1577401077485664768.jpg\noffice_3/center/1577401146932771584.jpg\noffice_3/center/1577401079335444224.jpg\noffice_3/center/1577400863381560320.jpg\noffice_3/center/1577401160433173760.jpg\noffice_3/center/1577400919337449216.jpg\noffice_3/center/1577401131433681920.jpg\noffice_3/center/1577400930037233920.jpg\noffice_3/center/1577401164383042048.jpg\noffice_3/center/1577400856225886976.jpg\noffice_3/center/1577401141133248768.jpg\noffice_3/center/1577401150983174144.jpg\noffice_3/center/1577401155783559168.jpg\noffice_3/center/1577400856325864448.jpg\noffice_3/center/1577400949789111808.jpg\noffice_3/center/1577401060385798912.jpg\noffice_3/center/1577400884534346752.jpg\noffice_3/center/1577401041236369152.jpg\noffice_3/center/1577400915136070400.jpg\noffice_3/center/1577400855474474496.jpg\noffice_3/center/1577401142233112576.jpg\noffice_3/center/1577400936687667712.jpg\noffice_3/center/1577401019787783936.jpg\noffice_3/center/1577400872487842816.jpg\noffice_3/center/1577401162033038336.jpg\noffice_3/center/1577401061385861888.jpg\noffice_3/center/1577400959190300416.jpg\noffice_3/center/1577400974941653760.jpg\noffice_3/center/1577401062686026752.jpg\noffice_3/center/1577401167682605824.jpg\noffice_3/center/1577400899534332928.jpg\noffice_3/center/1577401125683754496.jpg\noffice_3/center/1577401030586869248.jpg\noffice_3/center/1577400869887246080.jpg\noffice_3/center/1577401056935936512.jpg\noffice_3/center/1577400881436160512.jpg\noffice_3/center/1577401167583016448.jpg\noffice_3/center/1577400856825182208.jpg\noffice_3/center/1577401101634473984.jpg\noffice_3/center/1577400975491797760.jpg\noffice_3/center/1577400974691561984.jpg\noffice_3/center/1577400862080452608.jpg\noffice_3/center/1577401139283619328.jpg\noffice_3/center/1577401089984887040.jpg\noffice_3/center/1577400975091767040.jpg\noffice_3/center/1577401063335723008.jpg\noffice_3/center/1577400860979773696.jpg\noffice_3/center/1577400952589669632.jpg\noffice_3/center/1577401040536556288.jpg\noffice_3/center/1577400877388549632.jpg\noffice_3/center/1577400865183363840.jpg\noffice_3/center/1577401013038120704.jpg\noffice_3/center/1577400905134340096.jpg\noffice_3/center/1577401132633486080.jpg\noffice_3/center/1577401160533127168.jpg\noffice_3/center/1577400870587759104.jpg\noffice_3/center/1577401011488614656.jpg\noffice_3/center/1577400852923062784.jpg\noffice_3/center/1577400934688006656.jpg\noffice_3/center/1577401140683557120.jpg\noffice_3/center/1577401156232993024.jpg\noffice_3/center/1577401062035974912.jpg\noffice_3/center/1577401024337383424.jpg\noffice_3/center/1577401049836076800.jpg\noffice_3/center/1577401177482468096.jpg\noffice_3/center/1577401139133532928.jpg\noffice_3/center/1577400943888070656.jpg\noffice_3/center/1577401089035012864.jpg\noffice_3/center/1577400886834791680.jpg\noffice_3/center/1577401105884296192.jpg\noffice_3/center/1577401176182653952.jpg\noffice_3/center/1577400913585638400.jpg\noffice_3/center/1577401083285560576.jpg\noffice_3/center/1577401108884848640.jpg\noffice_3/center/1577400929137716480.jpg\noffice_3/center/1577400936988019712.jpg\noffice_3/center/1577400907334274560.jpg\noffice_3/center/1577400886284396800.jpg\noffice_3/center/1577401030136815616.jpg\noffice_3/center/1577400925887689472.jpg\noffice_3/center/1577400877638252544.jpg\noffice_3/center/1577401054185696768.jpg\noffice_3/center/1577401146483384832.jpg\noffice_3/center/1577401149782939392.jpg\noffice_3/center/1577400887534393856.jpg\noffice_3/center/1577400971241209600.jpg\noffice_3/center/1577401134582882560.jpg\noffice_3/center/1577401165882440448.jpg\noffice_3/center/1577400878887389440.jpg\noffice_3/center/1577401037486464000.jpg\noffice_3/center/1577401090784796416.jpg\noffice_3/center/1577400916436709120.jpg\noffice_3/center/1577400976541248768.jpg\noffice_3/center/1577400925287144192.jpg\noffice_3/center/1577401054686072064.jpg\noffice_3/center/1577400930737617920.jpg\noffice_3/center/1577401017487911424.jpg\noffice_3/center/1577401183632142592.jpg\noffice_3/center/1577401074935948288.jpg\noffice_3/center/1577401119534222080.jpg\noffice_3/center/1577401067785735168.jpg\noffice_3/center/1577401178632389376.jpg\noffice_3/center/1577401061685841408.jpg\noffice_3/center/1577401138633344256.jpg\noffice_3/center/1577401178082360576.jpg\noffice_3/center/1577401074535552000.jpg\noffice_3/center/1577400879537104384.jpg\noffice_3/center/1577400876737719040.jpg\noffice_3/center/1577401120034302976.jpg\noffice_3/center/1577400845664392192.jpg\noffice_3/center/1577400871587932416.jpg\noffice_3/center/1577401161682976512.jpg\noffice_3/center/1577401070935657984.jpg\noffice_3/center/1577400975041747200.jpg\noffice_3/center/1577401157082763520.jpg\noffice_3/center/1577400960240679680.jpg\noffice_3/center/1577401028437153280.jpg\noffice_3/center/1577400969341371648.jpg\noffice_3/center/1577401180732037632.jpg\noffice_3/center/1577401095984963328.jpg\noffice_3/center/1577400896434403584.jpg\noffice_3/center/1577401096634858496.jpg\noffice_3/center/1577400939788247808.jpg\noffice_3/center/1577400860329276416.jpg\noffice_3/center/1577401115684287232.jpg\noffice_3/center/1577401022737351936.jpg\noffice_3/center/1577401111184510208.jpg\noffice_3/center/1577401042736188928.jpg\noffice_3/center/1577401047236270080.jpg\noffice_3/center/1577401052835913472.jpg\noffice_3/center/1577401098685112576.jpg\noffice_3/center/1577400948738876672.jpg\noffice_3/center/1577400967941157888.jpg\noffice_3/center/1577400882584667392.jpg\noffice_3/center/1577401114734563328.jpg\noffice_3/center/1577400875139284992.jpg\noffice_3/center/1577401078735452672.jpg\noffice_3/center/1577400941838007552.jpg\noffice_3/center/1577401038086874624.jpg\noffice_3/center/1577401064685949184.jpg\noffice_3/center/1577401071085647616.jpg\noffice_3/center/1577400851722004480.jpg\noffice_3/center/1577400928237168128.jpg\noffice_3/center/1577400970691462400.jpg\noffice_3/center/1577401035486892544.jpg\noffice_3/center/1577401086085088256.jpg\noffice_3/center/1577401072285699584.jpg\noffice_3/center/1577400851071281408.jpg\noffice_3/center/1577401142883571968.jpg\noffice_3/center/1577401072886154752.jpg\noffice_3/center/1577401091285337856.jpg\noffice_3/center/1577400962890729728.jpg\noffice_3/center/1577401028687095040.jpg\noffice_3/center/1577400906884339968.jpg\noffice_3/center/1577400883984943872.jpg\noffice_3/center/1577401014388788992.jpg\noffice_3/center/1577400909034338816.jpg\noffice_3/center/1577400947388894208.jpg\noffice_3/center/1577401059886138112.jpg\noffice_3/center/1577400905584475648.jpg\noffice_3/center/1577401165182430720.jpg\noffice_3/center/1577400900434595328.jpg\noffice_3/center/1577400913935686912.jpg\noffice_3/center/1577401016588423168.jpg\noffice_3/center/1577400861780522240.jpg\noffice_3/center/1577400946538628352.jpg\noffice_3/center/1577401184631854848.jpg\noffice_3/center/1577401028337147392.jpg\noffice_3/center/1577400873889240832.jpg\noffice_3/center/1577400886634735104.jpg\noffice_3/center/1577400960040517376.jpg\noffice_3/center/1577401115584270080.jpg\noffice_3/center/1577400968491092992.jpg\noffice_3/center/1577401149033101824.jpg\noffice_3/center/1577400939037622784.jpg\noffice_3/center/1577401062835975680.jpg\noffice_3/center/1577401065535798016.jpg\noffice_3/center/1577401177232305920.jpg\noffice_3/center/1577401104334002688.jpg\noffice_3/center/1577400951839524608.jpg\noffice_3/center/1577401101684492544.jpg\noffice_3/center/1577400967591206656.jpg\noffice_3/center/1577400910234679040.jpg\noffice_3/center/1577400943088312064.jpg\noffice_3/center/1577401042086322688.jpg\noffice_3/center/1577401036536631552.jpg\noffice_3/center/1577401151082985728.jpg\noffice_3/center/1577401104984491008.jpg\noffice_3/center/1577400886184369152.jpg\noffice_3/center/1577401060736096768.jpg\noffice_3/center/1577400890434939904.jpg\noffice_3/center/1577401129283787776.jpg\noffice_3/center/1577401051185788672.jpg\noffice_3/center/1577400951289352704.jpg\noffice_3/center/1577401132983954176.jpg\noffice_3/center/1577401166682268416.jpg\noffice_3/center/1577401160832888832.jpg\noffice_3/center/1577400981790067712.jpg\noffice_3/center/1577401035436801024.jpg\noffice_3/center/1577400901384761856.jpg\noffice_3/center/1577401144483540480.jpg\noffice_3/center/1577401075185754112.jpg\noffice_3/center/1577401075735764992.jpg\noffice_3/center/1577400907384256256.jpg\noffice_3/center/1577401022537265920.jpg\noffice_3/center/1577400911634833408.jpg\noffice_3/center/1577400854574453504.jpg\noffice_3/center/1577400847165786880.jpg\noffice_3/center/1577400907284292608.jpg\noffice_3/center/1577400883034864128.jpg\noffice_3/center/1577401104034403328.jpg\noffice_3/center/1577400873589003520.jpg\noffice_3/center/1577401156882787840.jpg\noffice_3/center/1577401156033415936.jpg\noffice_3/center/1577401028137152256.jpg\noffice_3/center/1577401099984678656.jpg\noffice_3/center/1577401178182403840.jpg\noffice_3/center/1577401178982684672.jpg\noffice_3/center/1577401041936397824.jpg\noffice_3/center/1577401110834392832.jpg\noffice_3/center/1577400950639442176.jpg\noffice_3/center/1577401111034435072.jpg\noffice_3/center/1577400978341102848.jpg\noffice_3/center/1577400977341389824.jpg\noffice_3/center/1577401182182536448.jpg\noffice_3/center/1577401144257052160.jpg\noffice_3/center/1577401106834704640.jpg\noffice_3/center/1577401093934944768.jpg\noffice_3/center/1577401045285978112.jpg\noffice_3/center/1577401065136013312.jpg\noffice_3/center/1577401163632925952.jpg\noffice_3/center/1577401151182892544.jpg\noffice_3/center/1577401136732719616.jpg\noffice_3/center/1577401111134482176.jpg\noffice_3/center/1577400889934852864.jpg\noffice_3/center/1577401078485252096.jpg\noffice_3/center/1577400973791670016.jpg\noffice_3/center/1577401139433591808.jpg\noffice_3/center/1577400965090549504.jpg\noffice_3/center/1577401087185432832.jpg\noffice_3/center/1577401012588237056.jpg\noffice_3/center/1577401051735912448.jpg\noffice_3/center/1577400942137612800.jpg\noffice_3/center/1577401180032313600.jpg\noffice_3/center/1577400878136659456.jpg\noffice_3/center/1577401041536475904.jpg\noffice_3/center/1577401134933501184.jpg\noffice_3/center/1577401142633145856.jpg\noffice_3/center/1577400914085932800.jpg\noffice_3/center/1577401073185884672.jpg\noffice_3/center/1577401077735941888.jpg\noffice_3/center/1577400920337190400.jpg\noffice_3/center/1577400866083923712.jpg\noffice_3/center/1577401178432406272.jpg\noffice_3/center/1577401019337642752.jpg\noffice_3/center/1577401103834653696.jpg\noffice_3/center/1577400930387557120.jpg\noffice_3/center/1577401046635766528.jpg\noffice_3/center/1577400910684745472.jpg\noffice_3/center/1577401056685810176.jpg\noffice_3/center/1577400848067586304.jpg\noffice_3/center/1577401141883920384.jpg\noffice_3/center/1577400945588445440.jpg\noffice_3/center/1577400925637735936.jpg\noffice_3/center/1577401052235912960.jpg\noffice_3/center/1577400898734680576.jpg\noffice_3/center/1577400949539097344.jpg\noffice_3/center/1577401016087847168.jpg\noffice_3/center/1577400878186467584.jpg\noffice_3/center/1577400957139818496.jpg\noffice_3/center/1577401118684391424.jpg\noffice_3/center/1577401129483681024.jpg\noffice_3/center/1577400855024624384.jpg\noffice_3/center/1577400957440112640.jpg\noffice_3/center/1577401036686636032.jpg\noffice_3/center/1577400880736072192.jpg\noffice_3/center/1577401065785690880.jpg\noffice_3/center/1577400922537640448.jpg\noffice_3/center/1577400900184659712.jpg\noffice_3/center/1577401072535825664.jpg\noffice_3/center/1577401028187143168.jpg\noffice_3/center/1577401130933873152.jpg\noffice_3/center/1577400845864877312.jpg\noffice_3/center/1577401030636879872.jpg\noffice_3/center/1577401155332422144.jpg\noffice_3/center/1577401031187032064.jpg\noffice_3/center/1577401159483003392.jpg\noffice_3/center/1577401180682086400.jpg\noffice_3/center/1577401108134341376.jpg\noffice_3/center/1577401159183164672.jpg\noffice_3/center/1577401011338421248.jpg\noffice_3/center/1577400957340089600.jpg\noffice_3/center/1577401174132641280.jpg\noffice_3/center/1577400918786899456.jpg\noffice_3/center/1577400913135687936.jpg\noffice_3/center/1577400948538853376.jpg\noffice_3/center/1577400881835533568.jpg\noffice_3/center/1577401135933414144.jpg\noffice_3/center/1577401094484803072.jpg\noffice_3/center/1577401179182376960.jpg\noffice_3/center/1577401128783929600.jpg\noffice_3/center/1577400957689940992.jpg\noffice_3/center/1577401142683281152.jpg\noffice_3/center/1577401146433387520.jpg\noffice_3/center/1577400898234507776.jpg\noffice_3/center/1577401097334937600.jpg\noffice_3/center/1577400885635014144.jpg\noffice_3/center/1577400965540721408.jpg\noffice_3/center/1577401056136275712.jpg\noffice_3/center/1577400853723649024.jpg\noffice_3/center/1577400917236859392.jpg\noffice_3/center/1577401034686849280.jpg\noffice_3/center/1577400925587545600.jpg\noffice_3/center/1577401023587219456.jpg\noffice_3/center/1577401062985934848.jpg\noffice_3/center/1577401076985296128.jpg\noffice_3/center/1577400927438119168.jpg\noffice_3/center/1577401119684323584.jpg\noffice_3/center/1577401091784582912.jpg\noffice_3/center/1577401114283877888.jpg\noffice_3/center/1577400848668446208.jpg\noffice_3/center/1577400844063207680.jpg\noffice_3/center/1577401103334440192.jpg\noffice_3/center/1577401146033627904.jpg\noffice_3/center/1577401118984352000.jpg\noffice_3/center/1577401118034580992.jpg\noffice_3/center/1577400904534287872.jpg\noffice_3/center/1577401025937105152.jpg\noffice_3/center/1577400921887005184.jpg\noffice_3/center/1577401046286192384.jpg\noffice_3/center/1577401182332372480.jpg\noffice_3/center/1577400852623008256.jpg\noffice_3/center/1577401082135772160.jpg\noffice_3/center/1577401033736773632.jpg\noffice_3/center/1577401170982327296.jpg\noffice_3/center/1577401182831804928.jpg\noffice_3/center/1577401039586646784.jpg\noffice_3/center/1577401124934065152.jpg\noffice_3/center/1577401144633664256.jpg\noffice_3/center/1577401033836799488.jpg\noffice_3/center/1577401013737824768.jpg\noffice_3/center/1577400946738855936.jpg\noffice_3/center/1577401017537977088.jpg\noffice_3/center/1577401122534232576.jpg\noffice_3/center/1577401120884376576.jpg\noffice_3/center/1577400881635636224.jpg\noffice_3/center/1577401143583278848.jpg\noffice_3/center/1577400870888072704.jpg\noffice_3/center/1577401126883769344.jpg\noffice_3/center/1577400916136743168.jpg\noffice_3/center/1577401136632621824.jpg\noffice_3/center/1577401058636561664.jpg\noffice_3/center/1577401085535270656.jpg\noffice_3/center/1577401027037638144.jpg\noffice_3/center/1577401054285610496.jpg\noffice_3/center/1577401148732778240.jpg\noffice_3/center/1577400909484774400.jpg\noffice_3/center/1577400931837438720.jpg\noffice_3/center/1577401169332638720.jpg\noffice_3/center/1577401182382328064.jpg\noffice_3/center/1577400950938919680.jpg\noffice_3/center/1577401160183134208.jpg\noffice_3/center/1577401161782933760.jpg\noffice_3/center/1577401030987056896.jpg\noffice_3/center/1577400935037841408.jpg\noffice_3/center/1577401050086002176.jpg\noffice_3/center/1577400938188092160.jpg\noffice_3/center/1577400864882944512.jpg\noffice_3/center/1577401066635588608.jpg\noffice_3/center/1577400947489139968.jpg\noffice_3/center/1577401131633604096.jpg\noffice_3/center/1577401122134175744.jpg\noffice_3/center/1577400977291433472.jpg\noffice_3/center/1577400905884022016.jpg\noffice_3/center/1577400882734750976.jpg\noffice_3/center/1577401098334748160.jpg\noffice_3/center/1577400869336208896.jpg\noffice_3/center/1577401073485745664.jpg\noffice_3/center/1577401132783651072.jpg\noffice_3/center/1577400852722985984.jpg\noffice_3/center/1577401101534534912.jpg\noffice_3/center/1577401048286027520.jpg\noffice_3/center/1577401134983681024.jpg\noffice_3/center/1577400910584803328.jpg\noffice_3/center/1577400924337213440.jpg\noffice_3/center/1577400908634356480.jpg\noffice_3/center/1577401051235745280.jpg\noffice_3/center/1577400907484283648.jpg\noffice_3/center/1577400952289317888.jpg\noffice_3/center/1577401086135088640.jpg\noffice_3/center/1577400975641791488.jpg\noffice_3/center/1577400965290378240.jpg\noffice_3/center/1577401071735886592.jpg\noffice_3/center/1577401039786309632.jpg\noffice_3/center/1577401119984312320.jpg\noffice_3/center/1577401179832286720.jpg\noffice_3/center/1577401041186369792.jpg\noffice_3/center/1577401151232873472.jpg\noffice_3/center/1577400900584544768.jpg\noffice_3/center/1577401018437623296.jpg\noffice_3/center/1577401109184732416.jpg\noffice_3/center/1577401072035722496.jpg\noffice_3/center/1577401107384506368.jpg\noffice_3/center/1577400845764655872.jpg\noffice_3/center/1577400955039795456.jpg\noffice_3/center/1577400957739925760.jpg\noffice_3/center/1577400876387714048.jpg\noffice_3/center/1577400901034628352.jpg\noffice_3/center/1577401043136272896.jpg\noffice_3/center/1577401060535930112.jpg\noffice_3/center/1577401175282835968.jpg\noffice_3/center/1577400870988092160.jpg\noffice_3/center/1577400880986680320.jpg\noffice_3/center/1577400918836958208.jpg\noffice_3/center/1577401169282653184.jpg\noffice_3/center/1577400858978390272.jpg\noffice_3/center/1577400909834821120.jpg\noffice_3/center/1577401032536702976.jpg\noffice_3/center/1577401052335994624.jpg\noffice_3/center/1577401154833330688.jpg\noffice_3/center/1577400908984271872.jpg\noffice_3/center/1577400979391161088.jpg\noffice_3/center/1577400896284539648.jpg\noffice_3/center/1577401092884817664.jpg\noffice_3/center/1577401019387673088.jpg\noffice_3/center/1577401151332932864.jpg\noffice_3/center/1577400877488374528.jpg\noffice_3/center/1577400957290059776.jpg\noffice_3/center/1577400869086020096.jpg\noffice_3/center/1577400968441096448.jpg\noffice_3/center/1577401016688252416.jpg\noffice_3/center/1577401057236138496.jpg\noffice_3/center/1577400858076792064.jpg\noffice_3/center/1577400980040451328.jpg\noffice_3/center/1577401074185649408.jpg\noffice_3/center/1577400849469089280.jpg\noffice_3/center/1577400953289500416.jpg\noffice_3/center/1577400981539848704.jpg\noffice_3/center/1577400924387058176.jpg\noffice_3/center/1577401148483065088.jpg\noffice_3/center/1577401067036180224.jpg\noffice_3/center/1577400936637611264.jpg\noffice_3/center/1577401141833779200.jpg\noffice_3/center/1577401052436050688.jpg\noffice_3/center/1577400923887440384.jpg\noffice_3/center/1577400922937359360.jpg\noffice_3/center/1577401151483083264.jpg\noffice_3/center/1577400952039350528.jpg\noffice_3/center/1577400895185012736.jpg\noffice_3/center/1577401119834373120.jpg\noffice_3/center/1577400966790685952.jpg\noffice_3/center/1577400964090850304.jpg\noffice_3/center/1577401076785474816.jpg\noffice_3/center/1577400952839914240.jpg\noffice_3/center/1577401137833094912.jpg\noffice_3/center/1577401113583992064.jpg\noffice_3/center/1577401127683914240.jpg\noffice_3/center/1577401053035859712.jpg\noffice_3/center/1577401054085798656.jpg\noffice_3/center/1577400885934695168.jpg\noffice_3/center/1577401023487215616.jpg\noffice_3/center/1577401024487440384.jpg\noffice_3/center/1577401047035948544.jpg\noffice_3/center/1577400939488315904.jpg\noffice_3/center/1577400868935936256.jpg\noffice_3/center/1577400854474353664.jpg\noffice_3/center/1577401031436937984.jpg\noffice_3/center/1577400866534224640.jpg\noffice_3/center/1577400853023085056.jpg\noffice_3/center/1577401127283745792.jpg\noffice_3/center/1577401077235200256.jpg\noffice_3/center/1577400924987591168.jpg\noffice_3/center/1577400949439140864.jpg\noffice_3/center/1577400964640988416.jpg\noffice_3/center/1577401048386099200.jpg\noffice_3/center/1577400972991896320.jpg\noffice_3/center/1577401069535450112.jpg\noffice_3/center/1577400893835070208.jpg\noffice_3/center/1577400846565582592.jpg\noffice_3/center/1577401163482965504.jpg\noffice_3/center/1577400866634397440.jpg\noffice_3/center/1577401145883580416.jpg\noffice_3/center/1577401080485669376.jpg\noffice_3/center/1577400909434754304.jpg\noffice_3/center/1577401048486112000.jpg\noffice_3/center/1577400891134797056.jpg\noffice_3/center/1577401060435812352.jpg\noffice_3/center/1577401100134617856.jpg\noffice_3/center/1577400926537113856.jpg\noffice_3/center/1577400948288800000.jpg\noffice_3/center/1577401033336780544.jpg\noffice_3/center/1577401111234509824.jpg\noffice_3/center/1577400913385590528.jpg\noffice_3/center/1577400888684585984.jpg\noffice_3/center/1577401108534601984.jpg\noffice_3/center/1577401041986374400.jpg\noffice_3/center/1577401049435796480.jpg\noffice_3/center/1577400967090834432.jpg\noffice_3/center/1577401160583073792.jpg\noffice_3/center/1577401150533536256.jpg\noffice_3/center/1577401025537542912.jpg\noffice_3/center/1577401020287516928.jpg\noffice_3/center/1577401115484341248.jpg\noffice_3/center/1577400910084693760.jpg\noffice_3/center/1577401084535292672.jpg\noffice_3/center/1577401033686784256.jpg\noffice_3/center/1577401145483297536.jpg\noffice_3/center/1577400963590289152.jpg\noffice_3/center/1577401058586523136.jpg\noffice_3/center/1577400860629506304.jpg\noffice_3/center/1577400940587705344.jpg\noffice_3/center/1577401153282867456.jpg\noffice_3/center/1577401109284591616.jpg\noffice_3/center/1577401027137580288.jpg\noffice_3/center/1577400953589818368.jpg\noffice_3/center/1577400928987686912.jpg\noffice_3/center/1577401076585363456.jpg\noffice_3/center/1577401104184192256.jpg\noffice_3/center/1577400872338354432.jpg\noffice_3/center/1577401055835949312.jpg\noffice_3/center/1577401127533888256.jpg\noffice_3/center/1577401040336440320.jpg\noffice_3/center/1577400921187308544.jpg\noffice_3/center/1577400969891409920.jpg\noffice_3/center/1577400873139558656.jpg\noffice_3/center/1577401053985914368.jpg\noffice_3/center/1577400875089336064.jpg\noffice_3/center/1577401178282436352.jpg\noffice_3/center/1577401024287360000.jpg\noffice_3/center/1577400979690827776.jpg\noffice_3/center/1577401108034435072.jpg\noffice_3/center/1577400898634618368.jpg\noffice_3/center/1577401173581813504.jpg\noffice_3/center/1577401090834867968.jpg\noffice_3/center/1577401095234700288.jpg\noffice_3/center/1577400856775250688.jpg\noffice_3/center/1577400874039049472.jpg\noffice_3/center/1577400889184657920.jpg\noffice_3/center/1577401103184383232.jpg\noffice_3/center/1577400861380104448.jpg\noffice_3/center/1577401094684803328.jpg\noffice_3/center/1577400865283415296.jpg\noffice_3/center/1577400982090009088.jpg\noffice_3/center/1577401086885038848.jpg\noffice_3/center/1577400873488943104.jpg\noffice_3/center/1577400929487545344.jpg\noffice_3/center/1577401175732090368.jpg\noffice_3/center/1577401119384166400.jpg\noffice_3/center/1577400970891316992.jpg\noffice_3/center/1577401123884100096.jpg\noffice_3/center/1577400925387037440.jpg\noffice_3/center/1577401028037133312.jpg\noffice_3/center/1577401150032475648.jpg\noffice_3/center/1577401169682451712.jpg\noffice_3/center/1577401071385774592.jpg\noffice_3/center/1577400927937083648.jpg\noffice_3/center/1577400865383520000.jpg\noffice_3/center/1577401018537608448.jpg\noffice_3/center/1577401113034681344.jpg\noffice_3/center/1577401153882738944.jpg\noffice_3/center/1577401119134281216.jpg\noffice_3/center/1577401098535125504.jpg\noffice_3/center/1577400925687803136.jpg\noffice_3/center/1577401012238268416.jpg\noffice_3/center/1577401023837245696.jpg\noffice_3/center/1577400847967357184.jpg\noffice_3/center/1577400938837534720.jpg\noffice_3/center/1577400915586496256.jpg\noffice_3/center/1577401071935858688.jpg\noffice_3/center/1577401125234281728.jpg\noffice_3/center/1577401050335896576.jpg\noffice_3/center/1577401160782914560.jpg\noffice_3/center/1577400944938586368.jpg\noffice_3/center/1577400909884783104.jpg\noffice_3/center/1577401140133522432.jpg\noffice_3/center/1577401089634931456.jpg\noffice_3/center/1577400966740679168.jpg\noffice_3/center/1577400929887081472.jpg\noffice_3/center/1577400962240614656.jpg\noffice_3/center/1577401096534827264.jpg\noffice_3/center/1577400937637739264.jpg\noffice_3/center/1577400866734569728.jpg\noffice_3/center/1577401027287511808.jpg\noffice_3/center/1577401028087139328.jpg\noffice_3/center/1577400912535663872.jpg\noffice_3/center/1577400979491029504.jpg\noffice_3/center/1577400972741859840.jpg\noffice_3/center/1577401084385195776.jpg\noffice_3/center/1577400871989438208.jpg\noffice_3/center/1577401018237598976.jpg\noffice_3/center/1577400845965102592.jpg\noffice_3/center/1577401067236356608.jpg\noffice_3/center/1577401172282143232.jpg\noffice_3/center/1577401159932968960.jpg\noffice_3/center/1577401090584625408.jpg\noffice_3/center/1577401075635590144.jpg\noffice_3/center/1577401096034897152.jpg\noffice_3/center/1577401064735948544.jpg\noffice_3/center/1577401099084435456.jpg\noffice_3/center/1577401123684154368.jpg\noffice_3/center/1577400966191454464.jpg\noffice_3/center/1577400913085696256.jpg\noffice_3/center/1577400912735678720.jpg\noffice_3/center/1577401060836234496.jpg\noffice_3/center/1577400877288648704.jpg\noffice_3/center/1577400940337719552.jpg\noffice_3/center/1577400975391871232.jpg\noffice_3/center/1577401039086301952.jpg\noffice_3/center/1577401119584290304.jpg\noffice_3/center/1577400858528023808.jpg\noffice_3/center/1577400888634604288.jpg\noffice_3/center/1577401087085425920.jpg\noffice_3/center/1577401058886211328.jpg\noffice_3/center/1577400922787512576.jpg\noffice_3/center/1577401013438296320.jpg\noffice_3/center/1577400915336250880.jpg\noffice_3/center/1577400909184580352.jpg\noffice_3/center/1577400878737186816.jpg\noffice_3/center/1577400943238331136.jpg\noffice_3/center/1577400948838976512.jpg\noffice_3/center/1577400887284543744.jpg\noffice_3/center/1577401117584803328.jpg\noffice_3/center/1577400932237710080.jpg\noffice_3/center/1577400973841659904.jpg\noffice_3/center/1577401124084109568.jpg\noffice_3/center/1577401153982739456.jpg\noffice_3/center/1577401148233424128.jpg\noffice_3/center/1577400962140697600.jpg\noffice_3/center/1577401099284615424.jpg\noffice_3/center/1577401027187562496.jpg\noffice_3/center/1577400961940741632.jpg\noffice_3/center/1577400972291311616.jpg\noffice_3/center/1577400931987574272.jpg\noffice_3/center/1577400878436493824.jpg\noffice_3/center/1577400854274252544.jpg\noffice_3/center/1577401132033518080.jpg\noffice_3/center/1577400942638514688.jpg\noffice_3/center/1577401094884817152.jpg\noffice_3/center/1577400901484707328.jpg\noffice_3/center/1577401092184821504.jpg\noffice_3/center/1577400959090300672.jpg\noffice_3/center/1577401039286928896.jpg\noffice_3/center/1577400976991453952.jpg\noffice_3/center/1577401154182976768.jpg\noffice_3/center/1577401172882852352.jpg\noffice_3/center/1577400891384866816.jpg\noffice_3/center/1577401058486442496.jpg\noffice_3/center/1577400981290120192.jpg\noffice_3/center/1577401179232288512.jpg\noffice_3/center/1577401153782785792.jpg\noffice_3/center/1577400951889494272.jpg\noffice_3/center/1577401112334366976.jpg\noffice_3/center/1577401047686098432.jpg\noffice_3/center/1577401108684757504.jpg\noffice_3/center/1577401067685899264.jpg\noffice_3/center/1577400962090715904.jpg\noffice_3/center/1577401118184247296.jpg\noffice_3/center/1577400974391509248.jpg\noffice_3/center/1577400933787375360.jpg\noffice_3/center/1577401084335162880.jpg\noffice_3/center/1577401135832892928.jpg\noffice_3/center/1577401024587399936.jpg\noffice_3/center/1577401083935010816.jpg\noffice_3/center/1577401145433215232.jpg\noffice_3/center/1577401014588485632.jpg\noffice_3/center/1577400879686696960.jpg\noffice_3/center/1577401109634675200.jpg\noffice_3/center/1577400936937988352.jpg\noffice_3/center/1577400977441176064.jpg\noffice_3/center/1577401024387435008.jpg\noffice_3/center/1577401037886758912.jpg\noffice_3/center/1577400929637321984.jpg\noffice_3/center/1577401033636785152.jpg\noffice_3/center/1577401159782915840.jpg\noffice_3/center/1577400981690008320.jpg\noffice_3/center/1577401034436742912.jpg\noffice_3/center/1577401115434391296.jpg\noffice_3/center/1577401062136015616.jpg\noffice_3/center/1577401017137475584.jpg\noffice_3/center/1577401125184228608.jpg\noffice_3/center/1577400925787777024.jpg\noffice_3/center/1577401130283595520.jpg\noffice_3/center/1577401021037445120.jpg\noffice_3/center/1577400853673651712.jpg\noffice_3/center/1577401034136801536.jpg\noffice_3/center/1577400873538999040.jpg\noffice_3/center/1577400968841061888.jpg\noffice_3/center/1577400933087799040.jpg\noffice_3/center/1577401073785846784.jpg\noffice_3/center/1577400860229207552.jpg\noffice_3/center/1577400937337499904.jpg\noffice_3/center/1577401128383192320.jpg\noffice_3/center/1577401043936377344.jpg\noffice_3/center/1577401180132282880.jpg\noffice_3/center/1577401161832936704.jpg\noffice_3/center/1577401164283132672.jpg\noffice_3/center/1577400920087044096.jpg\noffice_3/center/1577400896034515712.jpg\noffice_3/center/1577400904234252544.jpg\noffice_3/center/1577400855925712128.jpg\noffice_3/center/1577401047935942656.jpg\noffice_3/center/1577401060335796992.jpg\noffice_3/center/1577401105684550400.jpg\noffice_3/center/1577401090484751104.jpg\noffice_3/center/1577400910134683648.jpg\noffice_3/center/1577401167982129920.jpg\noffice_3/center/1577400863431554816.jpg\noffice_3/center/1577400948889046784.jpg\noffice_3/center/1577400942287615488.jpg\noffice_3/center/1577401130883883008.jpg\noffice_3/center/1577400949239077888.jpg\noffice_3/center/1577400920887225344.jpg\noffice_3/center/1577401092134791424.jpg\noffice_3/center/1577401148033253632.jpg\noffice_3/center/1577400968691052288.jpg\noffice_3/center/1577401155833564416.jpg\noffice_3/center/1577400980290418944.jpg\noffice_3/center/1577400850771230976.jpg\noffice_3/center/1577400853223288320.jpg\noffice_3/center/1577401063485777152.jpg\noffice_3/center/1577400931587383552.jpg\noffice_3/center/1577400859277781504.jpg\noffice_3/center/1577400868536020736.jpg\noffice_3/center/1577400932887848960.jpg\noffice_3/center/1577401105084546816.jpg\noffice_3/center/1577401033486745856.jpg\noffice_3/center/1577400869687049216.jpg\noffice_3/center/1577400932587953152.jpg\noffice_3/center/1577401164133110016.jpg\noffice_3/center/1577400870437550848.jpg\noffice_3/center/1577401142183351552.jpg\noffice_3/center/1577400971391362816.jpg\noffice_3/center/1577401089684934400.jpg\noffice_3/center/1577401120284329216.jpg\noffice_3/center/1577400930837643776.jpg\noffice_3/center/1577401047086064384.jpg\noffice_3/center/1577400946438551296.jpg\noffice_3/center/1577401094434812416.jpg\noffice_3/center/1577400934937918208.jpg\noffice_3/center/1577401158632877056.jpg\noffice_3/center/1577400852472943104.jpg\noffice_3/center/1577401112684802304.jpg\noffice_3/center/1577400886384470784.jpg\noffice_3/center/1577400921587022080.jpg\noffice_3/center/1577400927037122816.jpg\noffice_3/center/1577401109334536960.jpg\noffice_3/center/1577400882834851072.jpg\noffice_3/center/1577400923637225472.jpg\noffice_3/center/1577401172032716800.jpg\noffice_3/center/1577401081085145856.jpg\noffice_3/center/1577401036186616064.jpg\noffice_3/center/1577401024737360384.jpg\noffice_3/center/1577400897234826752.jpg\noffice_3/center/1577400853873833472.jpg\noffice_3/center/1577401181732264704.jpg\noffice_3/center/1577400894434724864.jpg\noffice_3/center/1577401075535518976.jpg\noffice_3/center/1577400964840962304.jpg\noffice_3/center/1577401121384270080.jpg\noffice_3/center/1577401052586186496.jpg\noffice_3/center/1577400900034618368.jpg\noffice_3/center/1577400873939231488.jpg\noffice_3/center/1577401068385858048.jpg\noffice_3/center/1577400857527171328.jpg\noffice_3/center/1577401092834785024.jpg\noffice_3/center/1577401017087458304.jpg\noffice_3/center/1577400861079898880.jpg\noffice_3/center/1577401080885141248.jpg\noffice_3/center/1577401169432597248.jpg\noffice_3/center/1577401078435231744.jpg\noffice_3/center/1577401041786420480.jpg\noffice_3/center/1577401146982832128.jpg\noffice_3/center/1577400896984737792.jpg\noffice_3/center/1577400947238704128.jpg\noffice_3/center/1577400982139966208.jpg\noffice_3/center/1577401090534667264.jpg\noffice_3/center/1577401126233763328.jpg\noffice_3/center/1577400880335840512.jpg\noffice_3/center/1577401120934400000.jpg\noffice_3/center/1577401114433830656.jpg\noffice_3/center/1577401104784245504.jpg\noffice_3/center/1577401166432862464.jpg\noffice_3/center/1577401085885240320.jpg\noffice_3/center/1577400846615535872.jpg\noffice_3/center/1577401178232417792.jpg\noffice_3/center/1577401180982270464.jpg\noffice_3/center/1577401038935894528.jpg\noffice_3/center/1577400916236765696.jpg\noffice_3/center/1577400932537922560.jpg\noffice_3/center/1577401064836005632.jpg\noffice_3/center/1577401109784875264.jpg\noffice_3/center/1577401015837822976.jpg\noffice_3/center/1577401089435073536.jpg\noffice_3/center/1577401012688250880.jpg\noffice_3/center/1577401021137542656.jpg\noffice_3/center/1577400858327468800.jpg\noffice_3/center/1577401069035845632.jpg\noffice_3/center/1577400857976496896.jpg\noffice_3/center/1577401096784753152.jpg\noffice_3/center/1577401077985660160.jpg\noffice_3/center/1577401011988486400.jpg\noffice_3/center/1577400867134800896.jpg\noffice_3/center/1577401093384869120.jpg\noffice_3/center/1577401056885866752.jpg\noffice_3/center/1577401149433601280.jpg\noffice_3/center/1577400947088783872.jpg\noffice_3/center/1577400871237890816.jpg\noffice_3/center/1577400917336775168.jpg\noffice_3/center/1577401118334150400.jpg\noffice_3/center/1577401053885910784.jpg\noffice_3/center/1577401151833241344.jpg\noffice_3/center/1577401037786599424.jpg\noffice_3/center/1577400945088655616.jpg\noffice_3/center/1577401171182389504.jpg\noffice_3/center/1577400887784559872.jpg\noffice_3/center/1577401129833632768.jpg\noffice_3/center/1577401106084177920.jpg\noffice_3/center/1577401105584658688.jpg\noffice_3/center/1577400864983104512.jpg\noffice_3/center/1577401093084905472.jpg\noffice_3/center/1577400885384800512.jpg\noffice_3/center/1577401043986371840.jpg\noffice_3/center/1577400945888637440.jpg\noffice_3/center/1577400913435588096.jpg\noffice_3/center/1577400893885034496.jpg\noffice_3/center/1577400864132339712.jpg\noffice_3/center/1577400875938450944.jpg\noffice_3/center/1577400870487644160.jpg\noffice_3/center/1577401089385126656.jpg\noffice_3/center/1577400902284241920.jpg\noffice_3/center/1577400905684330496.jpg\noffice_3/center/1577401037036677376.jpg\noffice_3/center/1577401060686054656.jpg\noffice_3/center/1577401171032315648.jpg\noffice_3/center/1577400895084895488.jpg\noffice_3/center/1577400972341328640.jpg\noffice_3/center/1577401123934101248.jpg\noffice_3/center/1577401029786965248.jpg\noffice_3/center/1577401116384583680.jpg\noffice_3/center/1577401049485833472.jpg\noffice_3/center/1577400882784801024.jpg\noffice_3/center/1577400847616807936.jpg\noffice_3/center/1577401030086859520.jpg\noffice_3/center/1577400894134675456.jpg\noffice_3/center/1577400945838568704.jpg\noffice_3/center/1577401044935764992.jpg\noffice_3/center/1577401178382408960.jpg\noffice_3/center/1577400980890508288.jpg\noffice_3/center/1577400898134470656.jpg\noffice_3/center/1577401147383552768.jpg\noffice_3/center/1577401111384816384.jpg\noffice_3/center/1577401072836093952.jpg\noffice_3/center/1577401051335743744.jpg\noffice_3/center/1577400931737441792.jpg\noffice_3/center/1577401069235718400.jpg\noffice_3/center/1577400942037838080.jpg\noffice_3/center/1577401183932008960.jpg\noffice_3/center/1577400857226797824.jpg\noffice_3/center/1577401160133084672.jpg\noffice_3/center/1577400951239254016.jpg\noffice_3/center/1577401181132190208.jpg\noffice_3/center/1577400857676829184.jpg\noffice_3/center/1577400881985320960.jpg\noffice_3/center/1577401016137902080.jpg\noffice_3/center/1577401036886656512.jpg\noffice_3/center/1577401081685016064.jpg\noffice_3/center/1577401058786433280.jpg\noffice_3/center/1577401182532116736.jpg\noffice_3/center/1577400862731235072.jpg\noffice_3/center/1577400959890300160.jpg\noffice_3/center/1577401166582423552.jpg\noffice_3/center/1577400903184403200.jpg\noffice_3/center/1577401012988105984.jpg\noffice_3/center/1577400937537500416.jpg\noffice_3/center/1577400845914863104.jpg\noffice_3/center/1577401160882906368.jpg\noffice_3/center/1577400926487054848.jpg\noffice_3/center/1577401026087001600.jpg\noffice_3/center/1577401184331809536.jpg\noffice_3/center/1577401097034583808.jpg\noffice_3/center/1577400914686424320.jpg\noffice_3/center/1577401043086250752.jpg\noffice_3/center/1577400981589842176.jpg\noffice_3/center/1577400853123137792.jpg\noffice_3/center/1577400928087038976.jpg\noffice_3/center/1577401057985942528.jpg\noffice_3/center/1577400885184523008.jpg\noffice_3/center/1577401017638034176.jpg\noffice_3/center/1577401040186410496.jpg\noffice_3/center/1577401153482876928.jpg\noffice_3/center/1577401112184329984.jpg\noffice_3/center/1577401063736075776.jpg\noffice_3/center/1577400848868447488.jpg\noffice_3/center/1577401133234080768.jpg\noffice_3/center/1577401137883113216.jpg\noffice_3/center/1577401055785873408.jpg\noffice_3/center/1577400900084627712.jpg\noffice_3/center/1577401011538642176.jpg\noffice_3/center/1577400911734934272.jpg\noffice_3/center/1577401127233683200.jpg\noffice_3/center/1577401176632318464.jpg\noffice_3/center/1577401184231831808.jpg\noffice_3/center/1577401177182313728.jpg\noffice_3/center/1577401104584110336.jpg\noffice_3/center/1577401074135697920.jpg\noffice_3/center/1577400905784157184.jpg\noffice_3/center/1577401093834834944.jpg\noffice_3/center/1577401150583602944.jpg\noffice_3/center/1577401082634727680.jpg\noffice_3/center/1577400937687822080.jpg\noffice_3/center/1577401137083472896.jpg\noffice_3/center/1577401110034965760.jpg\noffice_3/center/1577401101734486016.jpg\noffice_3/center/1577400846915503360.jpg\noffice_3/center/1577400870187430144.jpg\noffice_3/center/1577400893585084928.jpg\noffice_3/center/1577401023387205376.jpg\noffice_3/center/1577401098284609792.jpg\noffice_3/center/1577401098635150336.jpg\noffice_3/center/1577400847366401792.jpg\noffice_3/center/1577401093534846464.jpg\noffice_3/center/1577401178682462976.jpg\noffice_3/center/1577401107134316032.jpg\noffice_3/center/1577401076835418112.jpg\noffice_3/center/1577401010888301056.jpg\noffice_3/center/1577400980140397568.jpg\noffice_3/center/1577400973041847040.jpg\noffice_3/center/1577401035236683520.jpg\noffice_3/center/1577401088485068544.jpg\noffice_3/center/1577401175932389632.jpg\noffice_3/center/1577401017387802368.jpg\noffice_3/center/1577401086784811776.jpg\noffice_3/center/1577400845113428224.jpg\noffice_3/center/1577400980540321280.jpg\noffice_3/center/1577400897734514944.jpg\noffice_3/center/1577400883284577792.jpg\noffice_3/center/1577400874138696192.jpg\noffice_3/center/1577401067186361600.jpg\noffice_3/center/1577401181482037760.jpg\noffice_3/center/1577400869186074880.jpg\noffice_3/center/1577400854624458240.jpg\noffice_3/center/1577401154132900352.jpg\noffice_3/center/1577401017688021248.jpg\noffice_3/center/1577401057136118272.jpg\noffice_3/center/1577401014338790400.jpg\noffice_3/center/1577401085735366656.jpg\noffice_3/center/1577400941938012928.jpg\noffice_3/center/1577400902534288384.jpg\noffice_3/center/1577400929437584896.jpg\noffice_3/center/1577400923787297280.jpg\noffice_3/center/1577400960740518144.jpg\noffice_3/center/1577400907034216448.jpg\noffice_3/center/1577400897534642176.jpg\noffice_3/center/1577400910034663936.jpg\noffice_3/center/1577401049285768192.jpg\noffice_3/center/1577401013937782784.jpg\noffice_3/center/1577401168282558208.jpg\noffice_3/center/1577401172482017792.jpg\noffice_3/center/1577401104734184448.jpg\noffice_3/center/1577400917486711552.jpg\noffice_3/center/1577400939738283264.jpg\noffice_3/center/1577401055485476608.jpg\noffice_3/center/1577400972391350016.jpg\noffice_3/center/1577400964990730496.jpg\noffice_3/center/1577401031636786944.jpg\noffice_3/center/1577401106534534400.jpg\noffice_3/center/1577401151983211776.jpg\noffice_3/center/1577400847867229696.jpg\noffice_3/center/1577400863081507072.jpg\noffice_3/center/1577401154933072128.jpg\noffice_3/center/1577401177282350080.jpg\noffice_3/center/1577400898784711168.jpg\noffice_3/center/1577401184131880192.jpg\noffice_3/center/1577401150433360128.jpg\noffice_3/center/1577400929787086848.jpg\noffice_3/center/1577400954289578240.jpg\noffice_3/center/1577401121084448512.jpg\noffice_3/center/1577401135682473728.jpg\noffice_3/center/1577401068635832832.jpg\noffice_3/center/1577401081634999552.jpg\noffice_3/center/1577400873639063552.jpg\noffice_3/center/1577401163683011328.jpg\noffice_3/center/1577401129733675008.jpg\noffice_3/center/1577401098834792448.jpg\noffice_3/center/1577400944888603648.jpg\noffice_3/center/1577401157782967552.jpg\noffice_3/center/1577401034736865536.jpg\noffice_3/center/1577400975441818880.jpg\noffice_3/center/1577400964741000960.jpg\noffice_3/center/1577400942588441088.jpg\noffice_3/center/1577401023037711104.jpg\noffice_3/center/1577400863031488768.jpg\noffice_3/center/1577401062236044544.jpg\noffice_3/center/1577401016538374400.jpg\noffice_3/center/1577400969491388416.jpg\noffice_3/center/1577401174882442240.jpg\noffice_3/center/1577401134732891392.jpg\noffice_3/center/1577401163783164928.jpg\noffice_3/center/1577401177332384768.jpg\noffice_3/center/1577401088085206528.jpg\noffice_3/center/1577401158132963072.jpg\noffice_3/center/1577401077585932288.jpg\noffice_3/center/1577400979840571392.jpg\noffice_3/center/1577401165232600832.jpg\noffice_3/center/1577400904034372864.jpg\noffice_3/center/1577401038236783104.jpg\noffice_3/center/1577401158282939136.jpg\noffice_3/center/1577401128583561984.jpg\noffice_3/center/1577400850521105408.jpg\noffice_3/center/1577400878586903040.jpg\noffice_3/center/1577400884684358912.jpg\noffice_3/center/1577400856525701632.jpg\noffice_3/center/1577401170382383872.jpg\noffice_3/center/1577401097834492672.jpg\noffice_3/center/1577401162483176448.jpg\noffice_3/center/1577401053635977472.jpg\noffice_3/center/1577401080185561344.jpg\noffice_3/center/1577401050036024320.jpg\noffice_3/center/1577400866334035200.jpg\noffice_3/center/1577401135283756544.jpg\noffice_3/center/1577401176432567552.jpg\noffice_3/center/1577401099734962944.jpg\noffice_3/center/1577401085935175936.jpg\noffice_3/center/1577400867335096576.jpg\noffice_3/center/1577401064186048256.jpg\noffice_3/center/1577401065336004096.jpg\noffice_3/center/1577401065036021760.jpg\noffice_3/center/1577401011738647296.jpg\noffice_3/center/1577401168832387072.jpg\noffice_3/center/1577400897034770688.jpg\noffice_3/center/1577400878937361152.jpg\noffice_3/center/1577401123284077056.jpg\noffice_3/center/1577400941438238208.jpg\noffice_3/center/1577400901334750976.jpg\noffice_3/center/1577401034386732544.jpg\noffice_3/center/1577401016288017152.jpg\noffice_3/center/1577401168932432896.jpg\noffice_3/center/1577401108634724864.jpg\noffice_3/center/1577400935587444224.jpg\noffice_3/center/1577401081785092608.jpg\noffice_3/center/1577401035986674688.jpg\noffice_3/center/1577400882135198464.jpg\noffice_3/center/1577400963190528000.jpg\noffice_3/center/1577400916786706688.jpg\noffice_3/center/1577401143633239808.jpg\noffice_3/center/1577400924687145472.jpg\noffice_3/center/1577401133134108928.jpg\noffice_3/center/1577401029137096704.jpg\noffice_3/center/1577401033786793984.jpg\noffice_3/center/1577400965791068672.jpg\noffice_3/center/1577401095334684160.jpg\noffice_3/center/1577400885984632832.jpg\noffice_3/center/1577401105784434944.jpg\noffice_3/center/1577400955089818368.jpg\noffice_3/center/1577401080835195392.jpg\noffice_3/center/1577401035286675456.jpg\noffice_3/center/1577400925087442944.jpg\noffice_3/center/1577401147832942080.jpg\noffice_3/center/1577400916036736000.jpg\noffice_3/center/1577400975141788928.jpg\noffice_3/center/1577401108984815616.jpg\noffice_3/center/1577401035186702080.jpg\noffice_3/center/1577400877937340672.jpg\noffice_3/center/1577401150683626496.jpg\noffice_3/center/1577401044336254720.jpg\noffice_3/center/1577400954239651328.jpg\noffice_3/center/1577401173431990272.jpg\noffice_3/center/1577400954889702912.jpg\noffice_3/center/1577401158182944768.jpg\noffice_3/center/1577400945188687104.jpg\noffice_3/center/1577400861430114048.jpg\noffice_3/center/1577401027337455872.jpg\noffice_3/center/1577401115084731136.jpg\noffice_3/center/1577400897134829568.jpg\noffice_3/center/1577401126033268992.jpg\noffice_3/center/1577401024087364352.jpg\noffice_3/center/1577401019937668864.jpg\noffice_3/center/1577401127783886080.jpg\noffice_3/center/1577401066986065408.jpg\noffice_3/center/1577401057685920256.jpg\noffice_3/center/1577400917136869120.jpg\noffice_3/center/1577401100584724224.jpg\noffice_3/center/1577400979790645504.jpg\noffice_3/center/1577401099534986752.jpg\noffice_3/center/1577401027887208192.jpg\noffice_3/center/1577400850671200000.jpg\noffice_3/center/1577401097485081856.jpg\noffice_3/center/1577400851522007552.jpg\noffice_3/center/1577400874238365952.jpg\noffice_3/center/1577401118784454656.jpg\noffice_3/center/1577401173232564480.jpg\noffice_3/center/1577400875289330432.jpg\noffice_3/center/1577401016388122624.jpg\noffice_3/center/1577400849418768896.jpg\noffice_3/center/1577400922637619456.jpg\noffice_3/center/1577401013987891712.jpg\noffice_3/center/1577401068585868032.jpg\noffice_3/center/1577400976291422976.jpg\noffice_3/center/1577401034536803328.jpg\noffice_3/center/1577400895634857472.jpg\noffice_3/center/1577401084285166592.jpg\noffice_3/center/1577401087135451648.jpg\noffice_3/center/1577401142133584896.jpg\noffice_3/center/1577400908784164352.jpg\noffice_3/center/1577401137133511936.jpg\noffice_3/center/1577400881036687872.jpg\noffice_3/center/1577401062935936768.jpg\noffice_3/center/1577401057436074240.jpg\noffice_3/center/1577400902834456320.jpg\noffice_3/center/1577401074585584384.jpg\noffice_3/center/1577401108284344320.jpg\noffice_3/center/1577400968641103360.jpg\noffice_3/center/1577401048736064000.jpg\noffice_3/center/1577400911885251328.jpg\noffice_3/center/1577401068335867136.jpg\noffice_3/center/1577400920487287808.jpg\noffice_3/center/1577401165432928512.jpg\noffice_3/center/1577401037986902528.jpg\noffice_3/center/1577401036386734848.jpg\noffice_3/center/1577401176582438144.jpg\noffice_3/center/1577401113234302720.jpg\noffice_3/center/1577400913685683968.jpg\noffice_3/center/1577401179682029824.jpg\noffice_3/center/1577400845013411840.jpg\noffice_3/center/1577400900634525696.jpg\noffice_3/center/1577401038036910848.jpg\noffice_3/center/1577400849268392704.jpg\noffice_3/center/1577401088185195776.jpg\noffice_3/center/1577401151132918528.jpg\noffice_3/center/1577401182232506112.jpg\noffice_3/center/1577400861480200960.jpg\noffice_3/center/1577401095534742528.jpg\noffice_3/center/1577400972591654912.jpg\noffice_3/center/1577400957540033536.jpg\noffice_3/center/1577401056735792896.jpg\noffice_3/center/1577400959590140160.jpg\noffice_3/center/1577401162583053568.jpg\noffice_3/center/1577400900784515584.jpg\noffice_3/center/1577400864282486528.jpg\noffice_3/center/1577401050135993856.jpg\noffice_3/center/1577401104383990784.jpg\noffice_3/center/1577400972491447296.jpg\noffice_3/center/1577401122834347520.jpg\noffice_3/center/1577400850821143040.jpg\noffice_3/center/1577400893435054080.jpg\noffice_3/center/1577401024237339648.jpg\noffice_3/center/1577400875189334528.jpg\noffice_3/center/1577400878787311360.jpg\noffice_3/center/1577400865583602944.jpg\noffice_3/center/1577401142833526272.jpg\noffice_3/center/1577400922437618688.jpg\noffice_3/center/1577400941388264192.jpg\noffice_3/center/1577401051635902208.jpg\noffice_3/center/1577400902884482304.jpg\noffice_3/center/1577401154032769536.jpg\noffice_3/center/1577401075986000128.jpg\noffice_3/center/1577401067935595264.jpg\noffice_3/center/1577401156832686592.jpg\noffice_3/center/1577401013488312576.jpg\noffice_3/center/1577400894284635904.jpg\noffice_3/center/1577401017287642880.jpg\noffice_3/center/1577401049886051328.jpg\noffice_3/center/1577400873389120768.jpg\noffice_3/center/1577400953990005504.jpg\noffice_3/center/1577401041336435968.jpg\noffice_3/center/1577400907184278272.jpg\noffice_3/center/1577400888484850176.jpg\noffice_3/center/1577400857176602624.jpg\noffice_3/center/1577401182781827072.jpg\noffice_3/center/1577400950889032960.jpg\noffice_3/center/1577401054986382848.jpg\noffice_3/center/1577401110184843776.jpg\noffice_3/center/1577400848017315584.jpg\noffice_3/center/1577401050585873664.jpg\noffice_3/center/1577400908084628480.jpg\noffice_3/center/1577400892484763904.jpg\noffice_3/center/1577401139033531904.jpg\noffice_3/center/1577400884934355456.jpg\noffice_3/center/1577401016438195200.jpg\noffice_3/center/1577400876038265344.jpg\noffice_3/center/1577400864032246016.jpg\noffice_3/center/1577401026487327232.jpg\noffice_3/center/1577400939688307456.jpg\noffice_3/center/1577401117134318848.jpg\noffice_3/center/1577400981389929728.jpg\noffice_3/center/1577401171632605696.jpg\noffice_3/center/1577400874739129600.jpg\noffice_3/center/1577401143333290240.jpg\noffice_3/center/1577400879087447040.jpg\noffice_3/center/1577400964540938240.jpg\noffice_3/center/1577401111784886784.jpg\noffice_3/center/1577401051985864960.jpg\noffice_3/center/1577400911334547968.jpg\noffice_3/center/1577401166183138304.jpg\noffice_3/center/1577401094135148032.jpg\noffice_3/center/1577401037636403200.jpg\noffice_3/center/1577400981840057600.jpg\noffice_3/center/1577401135532656640.jpg\noffice_3/center/1577401059986087936.jpg\noffice_3/center/1577400951439607040.jpg\noffice_3/center/1577401058336173312.jpg\noffice_3/center/1577400908484627200.jpg\noffice_3/center/1577401105984161536.jpg\noffice_3/center/1577400981439878912.jpg\noffice_3/center/1577400949739082240.jpg\noffice_3/center/1577400927737570816.jpg\noffice_3/center/1577400880585834496.jpg\noffice_3/center/1577401091085351680.jpg\noffice_3/center/1577400918086919168.jpg\noffice_3/center/1577401150733584128.jpg\noffice_3/center/1577401034886857984.jpg\noffice_3/center/1577401070635878912.jpg\noffice_3/center/1577400970741518080.jpg\noffice_3/center/1577401125534170112.jpg\noffice_3/center/1577401066685575424.jpg\noffice_3/center/1577401177882364672.jpg\noffice_3/center/1577400943638246912.jpg\noffice_3/center/1577401065286070528.jpg\noffice_3/center/1577400944138038528.jpg\noffice_3/center/1577400905434499584.jpg\noffice_3/center/1577401180082305024.jpg\noffice_3/center/1577401152283106560.jpg\noffice_3/center/1577401133483563520.jpg\noffice_3/center/1577401123384098304.jpg\noffice_3/center/1577400896584381440.jpg\noffice_3/center/1577401166632339712.jpg\noffice_3/center/1577400909584774656.jpg\noffice_3/center/1577400845463908352.jpg\noffice_3/center/1577401162183143680.jpg\noffice_3/center/1577400894234645248.jpg\noffice_3/center/1577401077035222528.jpg\noffice_3/center/1577400918937123072.jpg\noffice_3/center/1577401077085216512.jpg\noffice_3/center/1577400934587992064.jpg\noffice_3/center/1577401083235505408.jpg\noffice_3/center/1577401040486518528.jpg\noffice_3/center/1577401150933285120.jpg\noffice_3/center/1577401121634073344.jpg\noffice_3/center/1577401025087136512.jpg\noffice_3/center/1577400976341365248.jpg\noffice_3/center/1577401045436158464.jpg\noffice_3/center/1577401165382955264.jpg\noffice_3/center/1577400955489616896.jpg\noffice_3/center/1577401138683346432.jpg\noffice_3/center/1577400918736776704.jpg\noffice_3/center/1577400897684567552.jpg\noffice_3/center/1577400970391248128.jpg\noffice_3/center/1577401052536200704.jpg\noffice_3/center/1577400962390616832.jpg\noffice_3/center/1577400940637730816.jpg\noffice_3/center/1577400862430579712.jpg\noffice_3/center/1577401116284531968.jpg\noffice_3/center/1577401151633230080.jpg\noffice_3/center/1577400893034854144.jpg\noffice_3/center/1577401066785618176.jpg\noffice_3/center/1577401103884595712.jpg\noffice_3/center/1577401115634255360.jpg\noffice_3/center/1577400966440950784.jpg\noffice_3/center/1577401143233306624.jpg\noffice_3/center/1577401091534798080.jpg\noffice_3/center/1577400903584434688.jpg\noffice_3/center/1577401080435697408.jpg\noffice_3/center/1577400958640227840.jpg\noffice_3/center/1577400876637687552.jpg\noffice_3/center/1577400901684536320.jpg\noffice_3/center/1577400939087693824.jpg\noffice_3/center/1577400959290327296.jpg\noffice_3/center/1577401168182390016.jpg\noffice_3/center/1577400890134967040.jpg\noffice_3/center/1577401086035080704.jpg\noffice_3/center/1577400958890306816.jpg\noffice_3/center/1577401040736499456.jpg\noffice_3/center/1577401183432153088.jpg\noffice_3/center/1577400924787438080.jpg\noffice_3/center/1577401106734648320.jpg\noffice_3/center/1577400968940971776.jpg\noffice_3/center/1577400915386280704.jpg\noffice_3/center/1577401165682521856.jpg\noffice_3/center/1577401040586566912.jpg\noffice_3/center/1577400973691599360.jpg\noffice_3/center/1577400890634764288.jpg\noffice_3/center/1577400938737602560.jpg\noffice_3/center/1577400917586843392.jpg\noffice_3/center/1577401152033171968.jpg\noffice_3/center/1577401166383033600.jpg\noffice_3/center/1577400905234410752.jpg\noffice_3/center/1577400926087340032.jpg\noffice_3/center/1577400847266036736.jpg\noffice_3/center/1577401109934935296.jpg\noffice_3/center/1577401017588025600.jpg\noffice_3/center/1577401103484632832.jpg\noffice_3/center/1577401096334774528.jpg\noffice_3/center/1577401130083683584.jpg\noffice_3/center/1577400895385054208.jpg\noffice_3/center/1577401125584090880.jpg\noffice_3/center/1577400884434430976.jpg\noffice_3/center/1577401135383394560.jpg\noffice_3/center/1577401020937331968.jpg\noffice_3/center/1577401172732461056.jpg\noffice_3/center/1577401173332190976.jpg\noffice_3/center/1577401152933093632.jpg\noffice_3/center/1577401176532500736.jpg\noffice_3/center/1577400970591479296.jpg\noffice_3/center/1577400912835735808.jpg\noffice_3/center/1577401160033006336.jpg\noffice_3/center/1577400857726618624.jpg\noffice_3/center/1577401159283077632.jpg\noffice_3/center/1577401038586015232.jpg\noffice_3/center/1577400951689699840.jpg\noffice_3/center/1577401018037777408.jpg\noffice_3/center/1577401164532884992.jpg\noffice_3/center/1577400846315738368.jpg\noffice_3/center/1577400934737996800.jpg\noffice_3/center/1577400898884756736.jpg\noffice_3/center/1577400846715504384.jpg\noffice_3/center/1577400962490644224.jpg\noffice_3/center/1577400921387236608.jpg\noffice_3/center/1577401180332295424.jpg\noffice_3/center/1577401015737895936.jpg\noffice_3/center/1577400955639663360.jpg\noffice_3/center/1577400953890125056.jpg\noffice_3/center/1577401175032548096.jpg\noffice_3/center/1577401071185716480.jpg\noffice_3/center/1577401057835970048.jpg\noffice_3/center/1577401174432605440.jpg\noffice_3/center/1577401047386344704.jpg\noffice_3/center/1577400887834574336.jpg\noffice_3/center/1577401042586288640.jpg\noffice_3/center/1577401104084352512.jpg\noffice_3/center/1577401024037365760.jpg\noffice_3/center/1577401152433094656.jpg\noffice_3/center/1577400972641743872.jpg\noffice_3/center/1577400936587623424.jpg\noffice_3/center/1577401025837256192.jpg\noffice_3/center/1577401166283287552.jpg\noffice_3/center/1577400846415734528.jpg\noffice_3/center/1577401069935798016.jpg\noffice_3/center/1577400855624921856.jpg\noffice_3/center/1577401155883556352.jpg\noffice_3/center/1577400872788444928.jpg\noffice_3/center/1577401126534186496.jpg\noffice_3/center/1577400953639921664.jpg\noffice_3/center/1577400868135399936.jpg\noffice_3/center/1577400908184752640.jpg\noffice_3/center/1577400941288269568.jpg\noffice_3/center/1577400960090609664.jpg\noffice_3/center/1577401109134748160.jpg\noffice_3/center/1577401175682085632.jpg\noffice_3/center/1577400973541584128.jpg\noffice_3/center/1577400929937091328.jpg\noffice_3/center/1577400857926370816.jpg\noffice_3/center/1577400895435052032.jpg\noffice_3/center/1577401131983516672.jpg\noffice_3/center/1577401146083644416.jpg\noffice_3/center/1577400960790467328.jpg\noffice_3/center/1577400865483574016.jpg\noffice_3/center/1577400881485871616.jpg\noffice_3/center/1577400894634880000.jpg\noffice_3/center/1577400911284548608.jpg\noffice_3/center/1577400940537669888.jpg\noffice_3/center/1577400940687770368.jpg\noffice_3/center/1577400961290373888.jpg\noffice_3/center/1577400847115694336.jpg\noffice_3/center/1577401164233142272.jpg\noffice_3/center/1577401077135193088.jpg\noffice_3/center/1577400850020345344.jpg\noffice_3/center/1577401024987196416.jpg\noffice_3/center/1577400961640413696.jpg\noffice_3/center/1577400846465686016.jpg\noffice_3/center/1577400930187386624.jpg\noffice_3/center/1577401089085046784.jpg\noffice_3/center/1577401170582515712.jpg\noffice_3/center/1577401026687494656.jpg\noffice_3/center/1577401076235436032.jpg\noffice_3/center/1577401084085070848.jpg\noffice_3/center/1577400948939124992.jpg\noffice_3/center/1577401139533647872.jpg\noffice_3/center/1577401117634930432.jpg\noffice_3/center/1577401091035262720.jpg\noffice_3/center/1577400847566874368.jpg\noffice_3/center/1577400894384700416.jpg\noffice_3/center/1577401088585036032.jpg\noffice_3/center/1577400965390467840.jpg\noffice_3/center/1577400953539694848.jpg\noffice_3/center/1577401010687049728.jpg\noffice_3/center/1577400971641760512.jpg\noffice_3/center/1577401046685693184.jpg\noffice_3/center/1577400978690762752.jpg\noffice_3/center/1577400963790570496.jpg\noffice_3/center/1577401159983006464.jpg\noffice_3/center/1577400927987031808.jpg\noffice_3/center/1577400960590592512.jpg\noffice_3/center/1577401059385510656.jpg\noffice_3/center/1577400923137099520.jpg\noffice_3/center/1577401070236054016.jpg\noffice_3/center/1577400926687357184.jpg\noffice_3/center/1577400891484895488.jpg\noffice_3/center/1577400931337619712.jpg\noffice_3/center/1577400939237992448.jpg\noffice_3/center/1577400966141515520.jpg\noffice_3/center/1577400871138003456.jpg\noffice_3/center/1577401030186798848.jpg\noffice_3/center/1577400933737336320.jpg\noffice_3/center/1577401148532936448.jpg\noffice_3/center/1577401044835921408.jpg\noffice_3/center/1577401120384271360.jpg\noffice_3/center/1577401037536410880.jpg\noffice_3/center/1577400913535608064.jpg\noffice_3/center/1577400864482584832.jpg\noffice_3/center/1577401142583055872.jpg\noffice_3/center/1577401029537027072.jpg\noffice_3/center/1577400921836946688.jpg\noffice_3/center/1577401036636608512.jpg\noffice_3/center/1577400879187490816.jpg\noffice_3/center/1577401012438226944.jpg\noffice_3/center/1577400949839133696.jpg\noffice_3/center/1577400936187746560.jpg\noffice_3/center/1577401133333929984.jpg\noffice_3/center/1577401100684616960.jpg\noffice_3/center/1577400879237473280.jpg\noffice_3/center/1577400951939463680.jpg\noffice_3/center/1577401174582568448.jpg\noffice_3/center/1577401057386086912.jpg\noffice_3/center/1577400899234626048.jpg\noffice_3/center/1577401040386452224.jpg\noffice_3/center/1577400927887209216.jpg\noffice_3/center/1577400888385069056.jpg\noffice_3/center/1577400942237544704.jpg\noffice_3/center/1577400867985328896.jpg\noffice_3/center/1577401019687763200.jpg\noffice_3/center/1577400852021945856.jpg\noffice_3/center/1577400855174641664.jpg\noffice_3/center/1577401098034209280.jpg\noffice_3/center/1577400957039608064.jpg\noffice_3/center/1577401050235930112.jpg\noffice_3/center/1577400915286222592.jpg\noffice_3/center/1577401066336053760.jpg\noffice_3/center/1577400849118324224.jpg\noffice_3/center/1577401144383409408.jpg\noffice_3/center/1577401183332123904.jpg\noffice_3/center/1577401149882720512.jpg\noffice_3/center/1577401090034866432.jpg\noffice_3/center/1577401019437680128.jpg\noffice_3/center/1577401036786676736.jpg\noffice_3/center/1577400962590637824.jpg\noffice_3/center/1577400872838630400.jpg\noffice_3/center/1577401050485882624.jpg\noffice_3/center/1577400960840508416.jpg\noffice_3/center/1577401053335927296.jpg\noffice_3/center/1577401079685470208.jpg\noffice_3/center/1577401015587914752.jpg\noffice_3/center/1577401037686460416.jpg\noffice_3/center/1577400889134702080.jpg\noffice_3/center/1577401016187967488.jpg\noffice_3/center/1577401100734564096.jpg\noffice_3/center/1577400885084469248.jpg\noffice_3/center/1577401064136066816.jpg\noffice_3/center/1577400964390902016.jpg\noffice_3/center/1577400896184596736.jpg\noffice_3/center/1577400848117608960.jpg\noffice_3/center/1577401072235679232.jpg\noffice_3/center/1577401169632478464.jpg\noffice_3/center/1577401034786882304.jpg\noffice_3/center/1577401085585313536.jpg\noffice_3/center/1577400962690687488.jpg\noffice_3/center/1577400851021165312.jpg\noffice_3/center/1577400886984846848.jpg\noffice_3/center/1577401161032912128.jpg\noffice_3/center/1577400890285015040.jpg\noffice_3/center/1577401145633452800.jpg\noffice_3/center/1577401107234293504.jpg\noffice_3/center/1577401107284325632.jpg\noffice_3/center/1577400850271033088.jpg\noffice_3/center/1577400861530220800.jpg\noffice_3/center/1577400899134676480.jpg\noffice_3/center/1577400900684531968.jpg\noffice_3/center/1577400921987191808.jpg\noffice_3/center/1577400969741474304.jpg\noffice_3/center/1577401114184253440.jpg\noffice_3/center/1577401156682369792.jpg\noffice_3/center/1577401140433519104.jpg\noffice_3/center/1577401162832487680.jpg\noffice_3/center/1577400962740720128.jpg\noffice_3/center/1577400874588809984.jpg\noffice_3/center/1577401069685538816.jpg\noffice_3/center/1577401045586119936.jpg\noffice_3/center/1577401024787322880.jpg\noffice_3/center/1577400955439620864.jpg\noffice_3/center/1577401081035109632.jpg\noffice_3/center/1577401170432438272.jpg\noffice_3/center/1577401056386105344.jpg\noffice_3/center/1577401149583464192.jpg\noffice_3/center/1577400849769886464.jpg\noffice_3/center/1577401031536866816.jpg\noffice_3/center/1577401019887728896.jpg\noffice_3/center/1577401119184209920.jpg\noffice_3/center/1577401085685399552.jpg\noffice_3/center/1577400929337738496.jpg\noffice_3/center/1577401111434885376.jpg\noffice_3/center/1577401012538238464.jpg\noffice_3/center/1577400883534177024.jpg\noffice_3/center/1577401170632501760.jpg\noffice_3/center/1577401081185162496.jpg\noffice_3/center/1577401129233799680.jpg\noffice_3/center/1577400848968389888.jpg\noffice_3/center/1577400903834458624.jpg\noffice_3/center/1577401124833999616.jpg\noffice_3/center/1577401088135221504.jpg\noffice_3/center/1577401168032173312.jpg\noffice_3/center/1577401168132304640.jpg\noffice_3/center/1577400858427809792.jpg\noffice_3/center/1577401069385568000.jpg\noffice_3/center/1577401134383290368.jpg\noffice_3/center/1577400896784495872.jpg\noffice_3/center/1577400893284963584.jpg\noffice_3/center/1577401079785416192.jpg\noffice_3/center/1577401063886205184.jpg\noffice_3/center/1577400881386273792.jpg\noffice_3/center/1577400969541436672.jpg\noffice_3/center/1577401124383956992.jpg\noffice_3/center/1577401114884785152.jpg\noffice_3/center/1577401032786758912.jpg\noffice_3/center/1577400897784514304.jpg\noffice_3/center/1577401013338255872.jpg\noffice_3/center/1577401104634146560.jpg\noffice_3/center/1577401087434938368.jpg\noffice_3/center/1577401137683203584.jpg\noffice_3/center/1577400968791050240.jpg\noffice_3/center/1577401182132510464.jpg\noffice_3/center/1577400899984574208.jpg\noffice_3/center/1577400915736577280.jpg\noffice_3/center/1577400914736389888.jpg\noffice_3/center/1577400956889588736.jpg\noffice_3/center/1577401051935878656.jpg\noffice_3/center/1577400969391321856.jpg\noffice_3/center/1577400956939577600.jpg\noffice_3/center/1577401116234462464.jpg\noffice_3/center/1577401184281830912.jpg\noffice_3/center/1577400958040181504.jpg\noffice_3/center/1577401163382902016.jpg\noffice_3/center/1577401179082537728.jpg\noffice_3/center/1577400921537043712.jpg\noffice_3/center/1577401073235823616.jpg\noffice_3/center/1577401101034613760.jpg\noffice_3/center/1577401092734766336.jpg\noffice_3/center/1577401136933201664.jpg\noffice_3/center/1577400899634330368.jpg\noffice_3/center/1577401012838180608.jpg\noffice_3/center/1577400874388280320.jpg\noffice_3/center/1577400950739392768.jpg\noffice_3/center/1577400886234349568.jpg\noffice_3/center/1577400960990465280.jpg\noffice_3/center/1577401174782438912.jpg\noffice_3/center/1577401082335645952.jpg\noffice_3/center/1577401066236107008.jpg\noffice_3/center/1577401111834779904.jpg\noffice_3/center/1577400944988599808.jpg\noffice_3/center/1577401098435016960.jpg\noffice_3/center/1577401128333168128.jpg\noffice_3/center/1577401166132995072.jpg\noffice_3/center/1577401044636154112.jpg\noffice_3/center/1577400884334548992.jpg\noffice_3/center/1577401094334899712.jpg\noffice_3/center/1577400945488531968.jpg\noffice_3/center/1577401127833882112.jpg\noffice_3/center/1577401020087489024.jpg\noffice_3/center/1577401082435170560.jpg\noffice_3/center/1577400944238103808.jpg\noffice_3/center/1577400929387676160.jpg\noffice_3/center/1577401094185081088.jpg\noffice_3/center/1577400915086064128.jpg\noffice_3/center/1577401049185742080.jpg\noffice_3/center/1577400947889386240.jpg\noffice_3/center/1577400895285051648.jpg\noffice_3/center/1577400885584992000.jpg\noffice_3/center/1577400896384454912.jpg\noffice_3/center/1577401149183357696.jpg\noffice_3/center/1577401145133120000.jpg\noffice_3/center/1577401039136473344.jpg\noffice_3/center/1577400848368235264.jpg\noffice_3/center/1577401110784469504.jpg\noffice_3/center/1577401072385678848.jpg\noffice_3/center/1577401068885837312.jpg\noffice_3/center/1577401126634126848.jpg\noffice_3/center/1577400913735671040.jpg\noffice_3/center/1577400967491160320.jpg\noffice_3/center/1577401135883159552.jpg\noffice_3/center/1577401164682637312.jpg\noffice_3/center/1577401089884902656.jpg\noffice_3/center/1577401184381818368.jpg\noffice_3/center/1577400961490339840.jpg\noffice_3/center/1577401070785824768.jpg\noffice_3/center/1577401172832721408.jpg\noffice_3/center/1577401104483984384.jpg\noffice_3/center/1577400896934654720.jpg\noffice_3/center/1577401027787254528.jpg\noffice_3/center/1577400976391296000.jpg\noffice_3/center/1577400972791906048.jpg\noffice_3/center/1577401150333061376.jpg\noffice_3/center/1577401049936034048.jpg\noffice_3/center/1577401100284699904.jpg\noffice_3/center/1577400937837950720.jpg\noffice_3/center/1577401091684604928.jpg\noffice_3/center/1577401073036032512.jpg\noffice_3/center/1577401103584684032.jpg\noffice_3/center/1577401037386533888.jpg\noffice_3/center/1577401148083338496.jpg\noffice_3/center/1577400947739422464.jpg\noffice_3/center/1577401138183448576.jpg\noffice_3/center/1577401115534277888.jpg\noffice_3/center/1577400902584332032.jpg\noffice_3/center/1577400934537956352.jpg\noffice_3/center/1577401094284955904.jpg\noffice_3/center/1577401087534754304.jpg\noffice_3/center/1577400898834725120.jpg\noffice_3/center/1577400966091548672.jpg\noffice_3/center/1577400944538405120.jpg\noffice_3/center/1577400853523458048.jpg\noffice_3/center/1577401065485838592.jpg\noffice_3/center/1577401105284667648.jpg\noffice_3/center/1577401110134896896.jpg\noffice_3/center/1577400898284535296.jpg\noffice_3/center/1577401037286659328.jpg\noffice_3/center/1577401031137018368.jpg\noffice_3/center/1577401108184325120.jpg\noffice_3/center/1577400940787877888.jpg\noffice_3/center/1577401088435102720.jpg\noffice_3/center/1577401113884667136.jpg\noffice_3/center/1577400883384444672.jpg\noffice_3/center/1577400933837424128.jpg\noffice_3/center/1577400919187449600.jpg\noffice_3/center/1577401132333576704.jpg\noffice_3/center/1577401011588640512.jpg\noffice_3/center/1577401121334322688.jpg\noffice_3/center/1577401173082807808.jpg\noffice_3/center/1577401077635983360.jpg\noffice_3/center/1577400976941404160.jpg\noffice_3/center/1577401159882944256.jpg\noffice_3/center/1577400906734569216.jpg\noffice_3/center/1577401109084799232.jpg\noffice_3/center/1577400956240009216.jpg\noffice_3/center/1577400874438315008.jpg\noffice_3/center/1577401170932325120.jpg\noffice_3/center/1577401181582191360.jpg\noffice_3/center/1577400921237302272.jpg\noffice_3/center/1577401143783236864.jpg\noffice_3/center/1577401106284287488.jpg\noffice_3/center/1577400860079168000.jpg\noffice_3/center/1577401103134389760.jpg\noffice_3/center/1577401139583685632.jpg\noffice_3/center/1577400890584846336.jpg\noffice_3/center/1577401011838638592.jpg\noffice_3/center/1577400925037495808.jpg\noffice_3/center/1577400971041223936.jpg\noffice_3/center/1577401098884698112.jpg\noffice_3/center/1577401026837574912.jpg\noffice_3/center/1577400845564149248.jpg\noffice_3/center/1577401178132359680.jpg\noffice_3/center/1577401018887837952.jpg\noffice_3/center/1577400850120618752.jpg\noffice_3/center/1577400945138662400.jpg\noffice_3/center/1577401042486313472.jpg\noffice_3/center/1577401127133614848.jpg\noffice_3/center/1577400926236977664.jpg\noffice_3/center/1577401177782342400.jpg\noffice_3/center/1577401091984716544.jpg\noffice_3/center/1577400849318393600.jpg\noffice_3/center/1577401021337812224.jpg\noffice_3/center/1577401016037807360.jpg\noffice_3/center/1577400965891184128.jpg\noffice_3/center/1577401126183646720.jpg\noffice_3/center/1577400935137705216.jpg\noffice_3/center/1577401062486097664.jpg\noffice_3/center/1577400946638764288.jpg\noffice_3/center/1577400888784599040.jpg\noffice_3/center/1577401119234128640.jpg\noffice_3/center/1577400913035677184.jpg\noffice_3/center/1577400878486653952.jpg\noffice_3/center/1577401179932332032.jpg\noffice_3/center/1577400898584587264.jpg\noffice_3/center/1577400965991428608.jpg\noffice_3/center/1577400851772035328.jpg\noffice_3/center/1577401059235527680.jpg\noffice_3/center/1577400941888027392.jpg\noffice_3/center/1577401106434418432.jpg\noffice_3/center/1577400950689437952.jpg\noffice_3/center/1577401156932841984.jpg\noffice_3/center/1577401131133784832.jpg\noffice_3/center/1577401112784969728.jpg\noffice_3/center/1577400945738493696.jpg\noffice_3/center/1577401011788652544.jpg\noffice_3/center/1577401018487618048.jpg\noffice_3/center/1577400942538293760.jpg\noffice_3/center/1577400938238145536.jpg\noffice_3/center/1577401032236598528.jpg\noffice_3/center/1577400850070605824.jpg\noffice_3/center/1577401072786082560.jpg\noffice_3/center/1577401163883065088.jpg\noffice_3/center/1577400967641240320.jpg\noffice_3/center/1577401057086089728.jpg\noffice_3/center/1577401095084868352.jpg\noffice_3/center/1577400918436484864.jpg\noffice_3/center/1577400881086749440.jpg\noffice_3/center/1577401087885009920.jpg\noffice_3/center/1577401067536040192.jpg\noffice_3/center/1577401122434172672.jpg\noffice_3/center/1577401011138355200.jpg\noffice_3/center/1577401109584601088.jpg\noffice_3/center/1577400869386366208.jpg\noffice_3/center/1577401140833448960.jpg\noffice_3/center/1577401131533652224.jpg\noffice_3/center/1577400962440651776.jpg\noffice_3/center/1577401047586174464.jpg\noffice_3/center/1577401027687252480.jpg\noffice_3/center/1577401029636986368.jpg\noffice_3/center/1577401114383787520.jpg\noffice_3/center/1577401180782060288.jpg\noffice_3/center/1577400872939046912.jpg\noffice_3/center/1577400901134673152.jpg\noffice_3/center/1577400968091144192.jpg\noffice_3/center/1577401094534763264.jpg\noffice_3/center/1577401025187218176.jpg\noffice_3/center/1577401181082234624.jpg\noffice_3/center/1577400941588154368.jpg\noffice_3/center/1577400857126307072.jpg\noffice_3/center/1577400856125917696.jpg\noffice_3/center/1577401173282367488.jpg\noffice_3/center/1577400936387642880.jpg\noffice_3/center/1577401040786492928.jpg\noffice_3/center/1577401088385183744.jpg\noffice_3/center/1577400928787662080.jpg\noffice_3/center/1577401117084268032.jpg\noffice_3/center/1577401052885911040.jpg\noffice_3/center/1577401116734242048.jpg\noffice_3/center/1577401181532106752.jpg\noffice_3/center/1577401175182788096.jpg\noffice_3/center/1577401084835131392.jpg\noffice_3/center/1577401135233850880.jpg\noffice_3/center/1577400890734657536.jpg\noffice_3/center/1577400980790413056.jpg\noffice_3/center/1577401164083094272.jpg\noffice_3/center/1577400847316083968.jpg\noffice_3/center/1577400867034723840.jpg\noffice_3/center/1577400917186881792.jpg\noffice_3/center/1577400934837970432.jpg\noffice_3/center/1577400905034289152.jpg\noffice_3/center/1577401095284698624.jpg\noffice_3/center/1577400849218332928.jpg\noffice_3/center/1577401020887255552.jpg\noffice_3/center/1577401060786181632.jpg\noffice_3/center/1577401177132290304.jpg\noffice_3/center/1577401073086007552.jpg\noffice_3/center/1577400956489932032.jpg\noffice_3/center/1577401110584674048.jpg\noffice_3/center/1577400943338306304.jpg\noffice_3/center/1577401132383589888.jpg\noffice_3/center/1577401125484272896.jpg\noffice_3/center/1577400844113175552.jpg\noffice_3/center/1577400852222246400.jpg\noffice_3/center/1577400954789651456.jpg\noffice_3/center/1577400941238247424.jpg\noffice_3/center/1577401171982744320.jpg\noffice_3/center/1577401101584514048.jpg\noffice_3/center/1577401014688167168.jpg\noffice_3/center/1577401184581844224.jpg\noffice_3/center/1577400913835691008.jpg\noffice_3/center/1577401062736038656.jpg\noffice_3/center/1577400885334799360.jpg\noffice_3/center/1577400956340025088.jpg\noffice_3/center/1577401019637730048.jpg\noffice_3/center/1577401107684931584.jpg\noffice_3/center/1577401029886933248.jpg\noffice_3/center/1577401024687372544.jpg\noffice_3/center/1577401181982470912.jpg\noffice_3/center/1577400980240408064.jpg\noffice_3/center/1577400978041366272.jpg\noffice_3/center/1577401029037071360.jpg\noffice_3/center/1577401147983178496.jpg\noffice_3/center/1577400939638283264.jpg\noffice_3/center/1577400952939890432.jpg\noffice_3/center/1577401115934280704.jpg\noffice_3/center/1577400913185645312.jpg\noffice_3/center/1577401154733361920.jpg\noffice_3/center/1577401097134694144.jpg\noffice_3/center/1577401130583553024.jpg\noffice_3/center/1577401062186036736.jpg\noffice_3/center/1577401144283388416.jpg\noffice_3/center/1577400937088021760.jpg\noffice_3/center/1577401124333967872.jpg\noffice_3/center/1577401027587243264.jpg\noffice_3/center/1577400958540201984.jpg\noffice_3/center/1577401118434206464.jpg\noffice_3/center/1577401172632187648.jpg\noffice_3/center/1577400926637300480.jpg\noffice_3/center/1577400938088027392.jpg\noffice_3/center/1577401030036900096.jpg\noffice_3/center/1577401107084376832.jpg\noffice_3/center/1577400909134495232.jpg\noffice_3/center/1577401097784675328.jpg\noffice_3/center/1577401076035972096.jpg\noffice_3/center/1577400875389140224.jpg\noffice_3/center/1577400858477980928.jpg\noffice_3/center/1577400900134673664.jpg\noffice_3/center/1577400926436993536.jpg\noffice_3/center/1577400856375897600.jpg\noffice_3/center/1577400868285696512.jpg\noffice_3/center/1577400844913415168.jpg\noffice_3/center/1577400900884550400.jpg\noffice_3/center/1577401159083239680.jpg\noffice_3/center/1577400913885703936.jpg\noffice_3/center/1577401061885931264.jpg\noffice_3/center/1577400910184686592.jpg\noffice_3/center/1577400863481665024.jpg\noffice_3/center/1577401098735013120.jpg\noffice_3/center/1577400970041302528.jpg\noffice_3/center/1577401159133195776.jpg\noffice_3/center/1577401140783495424.jpg\noffice_3/center/1577401033436738304.jpg\noffice_3/center/1577401046885776640.jpg\noffice_3/center/1577401030786991616.jpg\noffice_3/center/1577401082185830656.jpg\noffice_3/center/1577401077435552000.jpg\noffice_3/center/1577401153033036032.jpg\noffice_3/center/1577401170682468608.jpg\noffice_3/center/1577401104284072704.jpg\noffice_3/center/1577401172132531712.jpg\noffice_3/center/1577400922237482496.jpg\noffice_3/center/1577401085835275520.jpg\noffice_3/center/1577400915936717568.jpg\noffice_3/center/1577401057536039680.jpg\noffice_3/center/1577400845213441280.jpg\noffice_3/center/1577401168532595200.jpg\noffice_3/center/1577400975891607296.jpg\noffice_3/center/1577401121184460288.jpg\noffice_3/center/1577400947138721024.jpg\noffice_3/center/1577401069435457280.jpg\noffice_3/center/1577400946288649984.jpg\noffice_3/center/1577401184681895936.jpg\noffice_3/center/1577400864632561408.jpg\noffice_3/center/1577400899834559488.jpg\noffice_3/center/1577400908734215424.jpg\noffice_3/center/1577400905734223872.jpg\noffice_3/center/1577400852272414720.jpg\noffice_3/center/1577401137933152768.jpg\noffice_3/center/1577401049035764480.jpg\noffice_3/center/1577400891735029248.jpg\noffice_3/center/1577401104534056704.jpg\noffice_3/center/1577400852422758912.jpg\noffice_3/center/1577401180832124160.jpg\noffice_3/center/1577400888034973696.jpg\noffice_3/center/1577400949089211904.jpg\noffice_3/center/1577401107884833792.jpg\noffice_3/center/1577400943738168320.jpg\noffice_3/center/1577401041386472704.jpg\noffice_3/center/1577401176132609280.jpg\noffice_3/center/1577401175232840192.jpg\noffice_3/center/1577400923287182336.jpg\noffice_3/center/1577400862130427392.jpg\noffice_3/center/1577400860779635456.jpg\noffice_3/center/1577400890884688896.jpg\noffice_3/center/1577400889834733568.jpg\noffice_3/center/1577400866834603520.jpg\noffice_3/center/1577401112834948608.jpg\noffice_3/center/1577401152383126272.jpg\noffice_3/center/1577401121934091520.jpg\noffice_3/center/1577400969941443328.jpg\noffice_3/center/1577401167782237696.jpg\noffice_3/center/1577400969991362560.jpg\noffice_3/center/1577401029087087104.jpg\noffice_3/center/1577400941688078848.jpg\noffice_3/center/1577400940988067072.jpg\noffice_3/center/1577400932737971968.jpg\noffice_3/center/1577400882984852480.jpg\noffice_3/center/1577401068485863680.jpg\noffice_3/center/1577401096284768768.jpg\noffice_3/center/1577401102984478976.jpg\noffice_3/center/1577401038336606464.jpg\noffice_3/center/1577401071485832960.jpg\noffice_3/center/1577400962190631168.jpg\noffice_3/center/1577401019837757696.jpg\noffice_3/center/1577401114634359296.jpg\noffice_3/center/1577401013887713024.jpg\noffice_3/center/1577400961840641024.jpg\noffice_3/center/1577401038785675264.jpg\noffice_3/center/1577400975241876480.jpg\noffice_3/center/1577401056436034816.jpg\noffice_3/center/1577400930637594368.jpg\noffice_3/center/1577401133433695744.jpg\noffice_3/center/1577400902684398592.jpg\noffice_3/center/1577401162782584064.jpg\noffice_3/center/1577401101134684416.jpg\noffice_3/center/1577401054585794304.jpg\noffice_3/center/1577401082035605760.jpg\noffice_3/center/1577401078885590272.jpg\noffice_3/center/1577401115734266624.jpg\noffice_3/center/1577400895884475648.jpg\noffice_3/center/1577401183131876352.jpg\noffice_3/center/1577400879387407616.jpg\noffice_3/center/1577400976141474304.jpg\noffice_3/center/1577401141033361152.jpg\noffice_3/center/1577400856625433344.jpg\noffice_3/center/1577401081285142528.jpg\noffice_3/center/1577400855875704064.jpg\noffice_3/center/1577400947439006720.jpg\noffice_3/center/1577401020037539072.jpg\noffice_3/center/1577400958840309760.jpg\noffice_3/center/1577401067436148992.jpg\noffice_3/center/1577400938438028288.jpg\noffice_3/center/1577401104884396032.jpg\noffice_3/center/1577400927087203584.jpg\noffice_3/center/1577401107484714496.jpg\noffice_3/center/1577400951189093120.jpg\noffice_3/center/1577400884134868992.jpg\noffice_3/center/1577401053485959424.jpg\noffice_3/center/1577401160982915840.jpg\noffice_3/center/1577400847466660864.jpg\noffice_3/center/1577401013238192896.jpg\noffice_3/center/1577401123084137216.jpg\noffice_3/center/1577401085285245440.jpg\noffice_3/center/1577401080735301120.jpg\noffice_3/center/1577401046485996288.jpg\noffice_3/center/1577401014638332672.jpg\noffice_3/center/1577401029587011840.jpg\noffice_3/center/1577400977041505024.jpg\noffice_3/center/1577401184781935872.jpg\noffice_3/center/1577400968591104768.jpg\noffice_3/center/1577400931487496704.jpg\noffice_3/center/1577401150633615616.jpg\noffice_3/center/1577401117785001216.jpg\noffice_3/center/1577401100784570624.jpg\noffice_3/center/1577401165482906624.jpg\noffice_3/center/1577401101234705152.jpg\noffice_3/center/1577401097435065856.jpg\noffice_3/center/1577401015537910272.jpg\noffice_3/center/1577400947539183104.jpg\noffice_3/center/1577401061935909888.jpg\noffice_3/center/1577401181882337280.jpg\noffice_3/center/1577401121784101376.jpg\noffice_3/center/1577401016738098176.jpg\noffice_3/center/1577401113433864448.jpg\noffice_3/center/1577401123734122752.jpg\noffice_3/center/1577401079135519488.jpg\noffice_3/center/1577401117735038976.jpg\noffice_3/center/1577401023987341056.jpg\noffice_3/center/1577400916286787584.jpg\noffice_3/center/1577400958090197504.jpg\noffice_3/center/1577401139333617664.jpg\noffice_3/center/1577401148932929536.jpg\noffice_3/center/1577401115784256256.jpg\noffice_3/center/1577401086584859136.jpg\noffice_3/center/1577401055936140288.jpg\noffice_3/center/1577401021887376896.jpg\noffice_3/center/1577400974741529088.jpg\noffice_3/center/1577400924586976000.jpg\noffice_3/center/1577400877088248576.jpg\noffice_3/center/1577401076335244544.jpg\noffice_3/center/1577400915986779136.jpg\noffice_3/center/1577401033236731904.jpg\noffice_3/center/1577400919836910080.jpg\noffice_3/center/1577400916936793344.jpg\noffice_3/center/1577400964890912256.jpg\noffice_3/center/1577401023937278720.jpg\noffice_3/center/1577401150232772352.jpg\noffice_3/center/1577401103434553856.jpg\noffice_3/center/1577401027987161088.jpg\noffice_3/center/1577401131733542400.jpg\noffice_3/center/1577400893735088128.jpg\noffice_3/center/1577401012138317312.jpg\noffice_3/center/1577401125384355328.jpg\noffice_3/center/1577401126334032640.jpg\noffice_3/center/1577401032436624896.jpg\noffice_3/center/1577401046236224512.jpg\noffice_3/center/1577401021837365760.jpg\noffice_3/center/1577400963890659072.jpg\noffice_3/center/1577401119484176128.jpg\noffice_3/center/1577400889434606848.jpg\noffice_3/center/1577401147733039616.jpg\noffice_3/center/1577400872437937408.jpg\noffice_3/center/1577401032736765952.jpg\noffice_3/center/1577400862230457856.jpg\noffice_3/center/1577400846665497344.jpg\noffice_3/center/1577401099934680832.jpg\noffice_3/center/1577401071235704320.jpg\noffice_3/center/1577401128033720320.jpg\noffice_3/center/1577401092784782848.jpg\noffice_3/center/1577400954139767296.jpg\noffice_3/center/1577400945338613248.jpg\noffice_3/center/1577401113634101504.jpg\noffice_3/center/1577400916986828032.jpg\noffice_3/center/1577401068685850112.jpg\noffice_3/center/1577401020337513984.jpg\noffice_3/center/1577401022137366528.jpg\noffice_3/center/1577401021237736704.jpg\noffice_3/center/1577401105734487040.jpg\noffice_3/center/1577400929837072384.jpg\noffice_3/center/1577400960540660480.jpg\noffice_3/center/1577401036936666368.jpg\noffice_3/center/1577400846815465984.jpg\noffice_3/center/1577400980840461824.jpg\noffice_3/center/1577400859928912128.jpg\noffice_3/center/1577401127483857408.jpg\noffice_3/center/1577400888734583552.jpg\noffice_3/center/1577401122184212736.jpg\noffice_3/center/1577400867885226496.jpg\noffice_3/center/1577401016488278784.jpg\noffice_3/center/1577401136833005568.jpg\noffice_3/center/1577401049335749376.jpg\noffice_3/center/1577401168382656512.jpg\noffice_3/center/1577400875788561152.jpg\noffice_3/center/1577401057186141952.jpg\noffice_3/center/1577400881186756608.jpg\noffice_3/center/1577401167533131776.jpg\noffice_3/center/1577400964440936960.jpg\noffice_3/center/1577400871688309760.jpg\noffice_3/center/1577400877038087168.jpg\noffice_3/center/1577401139083540992.jpg\noffice_3/center/1577401153682785536.jpg\noffice_3/center/1577401151783249920.jpg\noffice_3/center/1577400911835100416.jpg\noffice_3/center/1577400873789213696.jpg\noffice_3/center/1577400903234364672.jpg\noffice_3/center/1577400897884500992.jpg\noffice_3/center/1577400904584311552.jpg\noffice_3/center/1577400976441221376.jpg\noffice_3/center/1577401108384476928.jpg\noffice_3/center/1577401052985891840.jpg\noffice_3/center/1577400959040296192.jpg\noffice_3/center/1577401178782657280.jpg\noffice_3/center/1577401085485264896.jpg\noffice_3/center/1577400924837483776.jpg\noffice_3/center/1577400919786934272.jpg\noffice_3/center/1577401024137363712.jpg\noffice_3/center/1577400876237948416.jpg\noffice_3/center/1577401092484794112.jpg\noffice_3/center/1577400893535061760.jpg\noffice_3/center/1577401152733137920.jpg\noffice_3/center/1577401149233441536.jpg\noffice_3/center/1577401066136059392.jpg\noffice_3/center/1577400897384721664.jpg\noffice_3/center/1577401078535260416.jpg\noffice_3/center/1577401176332596224.jpg\noffice_3/center/1577400911484696576.jpg\noffice_3/center/1577401079935358976.jpg\noffice_3/center/1577400870287512320.jpg\noffice_3/center/1577400941038110720.jpg\noffice_3/center/1577400973591558912.jpg\noffice_3/center/1577400918136825856.jpg\noffice_3/center/1577401127333739776.jpg\noffice_3/center/1577401083485494272.jpg\noffice_3/center/1577401050935847680.jpg\noffice_3/center/1577401064986030336.jpg\noffice_3/center/1577400881935500032.jpg\noffice_3/center/1577401082684675584.jpg\noffice_3/center/1577400897484659712.jpg\noffice_3/center/1577401021737415936.jpg\noffice_3/center/1577400967741201152.jpg\noffice_3/center/1577401183582160896.jpg\noffice_3/center/1577400953139738880.jpg\noffice_3/center/1577400969591385856.jpg\noffice_3/center/1577400890234984192.jpg\noffice_3/center/1577400934787988480.jpg\noffice_3/center/1577401184081931008.jpg\noffice_3/center/1577401155382482944.jpg\noffice_3/center/1577400904284241152.jpg\noffice_3/center/1577400872189132544.jpg\noffice_3/center/1577401105034516736.jpg\noffice_3/center/1577401170132343296.jpg\noffice_3/center/1577401130433420544.jpg\noffice_3/center/1577400935187659776.jpg\noffice_3/center/1577400887884662016.jpg\noffice_3/center/1577400850170850048.jpg\noffice_3/center/1577401102934500608.jpg\noffice_3/center/1577401093134929664.jpg\noffice_3/center/1577401120084312320.jpg\noffice_3/center/1577400954489420544.jpg\noffice_3/center/1577401102084481536.jpg\noffice_3/center/1577400925187355392.jpg\noffice_3/center/1577400941488195072.jpg\noffice_3/center/1577400876537663488.jpg\noffice_3/center/1577400965440575744.jpg\noffice_3/center/1577400874789247744.jpg\noffice_3/center/1577401129533672960.jpg\noffice_3/center/1577400966940722944.jpg\noffice_3/center/1577401033186736896.jpg\noffice_3/center/1577401131683586560.jpg\noffice_3/center/1577401024887267584.jpg\noffice_3/center/1577400971441476864.jpg\noffice_3/center/1577400851971983360.jpg\noffice_3/center/1577400863131421184.jpg\noffice_3/center/1577401161332892416.jpg\noffice_3/center/1577401096884642048.jpg\noffice_3/center/1577401155432571648.jpg\noffice_3/center/1577401058536482816.jpg\noffice_3/center/1577401048586103808.jpg\noffice_3/center/1577401093434846976.jpg\noffice_3/center/1577400879586893568.jpg\noffice_3/center/1577401050185964800.jpg\noffice_3/center/1577401032686732544.jpg\noffice_3/center/1577400848418272768.jpg\noffice_3/center/1577401052035872256.jpg\noffice_3/center/1577401066286106112.jpg\noffice_3/center/1577401063836145408.jpg\noffice_3/center/1577400951038821888.jpg\noffice_3/center/1577401107584850176.jpg\noffice_3/center/1577401135782701312.jpg\noffice_3/center/1577400846215585536.jpg\noffice_3/center/1577400912085609728.jpg\noffice_3/center/1577401175632081152.jpg\noffice_3/center/1577401145683519488.jpg\noffice_3/center/1577401116134358016.jpg\noffice_3/center/1577400975591796992.jpg\noffice_3/center/1577401145383155968.jpg\noffice_3/center/1577401122584248576.jpg\noffice_3/center/1577400964690987264.jpg\noffice_3/center/1577401163532961536.jpg\noffice_3/center/1577400859878868480.jpg\noffice_3/center/1577401061335892480.jpg\noffice_3/center/1577400956989602304.jpg\noffice_3/center/1577400856025825792.jpg\noffice_3/center/1577401064635910144.jpg\noffice_3/center/1577401109534520064.jpg\noffice_3/center/1577400862480690944.jpg\noffice_3/center/1577401035736974848.jpg\noffice_3/center/1577400858578194432.jpg\noffice_3/center/1577400911234550528.jpg\noffice_3/center/1577400912185672448.jpg\noffice_3/center/1577400958440102400.jpg\noffice_3/center/1577400849168324352.jpg\noffice_3/center/1577401143983166976.jpg\noffice_3/center/1577400976041534720.jpg\noffice_3/center/1577401049635925504.jpg\noffice_3/center/1577401013787741696.jpg\noffice_3/center/1577401099184467456.jpg\noffice_3/center/1577401074885937408.jpg\noffice_3/center/1577401149982520320.jpg\noffice_3/center/1577401055585524736.jpg\noffice_3/center/1577400888934686720.jpg\noffice_3/center/1577401039536783360.jpg\noffice_3/center/1577401075035859456.jpg\noffice_3/center/1577401122034152448.jpg\noffice_3/center/1577401030236803072.jpg\noffice_3/center/1577401079885362688.jpg\noffice_3/center/1577401181832289024.jpg\noffice_3/center/1577400855324356096.jpg\noffice_3/center/1577401024187338240.jpg\noffice_3/center/1577401085985114880.jpg\noffice_3/center/1577400860479435264.jpg\noffice_3/center/1577401101334653952.jpg\noffice_3/center/1577401024437464576.jpg\noffice_3/center/1577400877188469248.jpg\noffice_3/center/1577401011238389248.jpg\noffice_3/center/1577400949039210240.jpg\noffice_3/center/1577401013638042880.jpg\noffice_3/center/1577401074985918720.jpg\noffice_3/center/1577400926737359872.jpg\noffice_3/center/1577401034586820608.jpg\noffice_3/center/1577400906334592512.jpg\noffice_3/center/1577401050635868160.jpg\noffice_3/center/1577400924436937984.jpg\noffice_3/center/1577401080985090048.jpg\noffice_3/center/1577400956689808640.jpg\noffice_3/center/1577401066735580160.jpg\noffice_3/center/1577400901784456192.jpg\noffice_3/center/1577401040136431616.jpg\noffice_3/center/1577401129883623168.jpg\noffice_3/center/1577401156632356096.jpg\noffice_3/center/1577401111934662912.jpg\noffice_3/center/1577400972891975424.jpg\noffice_3/center/1577400905084311296.jpg\noffice_3/center/1577400954039902720.jpg\noffice_3/center/1577400928587561472.jpg\noffice_3/center/1577401171282405632.jpg\noffice_3/center/1577400931387558144.jpg\noffice_3/center/1577401014787947264.jpg\noffice_3/center/1577401070735825152.jpg\noffice_3/center/1577401037136724992.jpg\noffice_3/center/1577401143133397504.jpg\noffice_3/center/1577400885784905984.jpg\noffice_3/center/1577401120684300288.jpg\noffice_3/center/1577401087935036928.jpg\noffice_3/center/1577401013538280704.jpg\noffice_3/center/1577400941338248448.jpg\noffice_3/center/1577400907834285056.jpg\noffice_3/center/1577401061585852416.jpg\noffice_3/center/1577401144983309312.jpg\noffice_3/center/1577401105434699008.jpg\noffice_3/center/1577401040886405120.jpg\noffice_3/center/1577401127933790720.jpg\noffice_3/center/1577400861580351232.jpg\noffice_3/center/1577401157282642944.jpg\noffice_3/center/1577400949489133312.jpg\noffice_3/center/1577401065391646464.jpg\noffice_3/center/1577400958390104320.jpg\noffice_3/center/1577401108784795392.jpg\noffice_3/center/1577400903734444800.jpg\noffice_3/center/1577401075885977600.jpg\noffice_3/center/1577401048086036224.jpg\noffice_3/center/1577401178482402816.jpg\noffice_3/center/1577400880285927424.jpg\noffice_3/center/1577400973941665536.jpg\noffice_3/center/1577401149299368960.jpg\noffice_3/center/1577401110634630656.jpg\noffice_3/center/1577401099685020416.jpg\noffice_3/center/1577401088235173376.jpg\noffice_3/center/1577400850621146368.jpg\noffice_3/center/1577400869837169920.jpg\noffice_3/center/1577401086484948992.jpg\noffice_3/center/1577401067635965952.jpg\noffice_3/center/1577401065236036864.jpg\noffice_3/center/1577400903784453888.jpg\noffice_3/center/1577401068985835520.jpg\noffice_3/center/1577401125933201408.jpg\noffice_3/center/1577401052935913984.jpg\noffice_3/center/1577401109484519680.jpg\noffice_3/center/1577401011038307072.jpg\noffice_3/center/1577400883934930176.jpg\noffice_3/center/1577401122284239360.jpg\noffice_3/center/1577401061835922944.jpg\noffice_3/center/1577401147933072384.jpg\noffice_3/center/1577400886434523648.jpg\noffice_3/center/1577400927687728384.jpg\noffice_3/center/1577401154883241984.jpg\noffice_3/center/1577401064086130688.jpg\noffice_3/center/1577400943188329472.jpg\noffice_3/center/1577400963840635392.jpg\noffice_3/center/1577401076385217536.jpg\noffice_3/center/1577401045486144000.jpg\noffice_3/center/1577400945038632448.jpg\noffice_3/center/1577401126083361024.jpg\noffice_3/center/1577401116034312448.jpg\noffice_3/center/1577401085035114496.jpg\noffice_3/center/1577400977991348736.jpg\noffice_3/center/1577400937787945216.jpg\noffice_3/center/1577400923937547008.jpg\noffice_3/center/1577401172782581760.jpg\noffice_3/center/1577400908284762880.jpg\noffice_3/center/1577401020237515008.jpg\noffice_3/center/1577401163432904960.jpg\noffice_3/center/1577400883234620672.jpg\noffice_3/center/1577400959340359424.jpg\noffice_3/center/1577401098184368128.jpg\noffice_3/center/1577401166882002688.jpg\noffice_3/center/1577401059185585664.jpg\noffice_3/center/1577400978391021824.jpg\noffice_3/center/1577400850571174912.jpg\noffice_3/center/1577401042436325632.jpg\noffice_3/center/1577400923037206016.jpg\noffice_3/center/1577401027537284352.jpg\noffice_3/center/1577400859177957888.jpg\noffice_3/center/1577401036986676224.jpg\noffice_3/center/1577401121234397440.jpg\noffice_3/center/1577400959140344064.jpg\noffice_3/center/1577401048985808384.jpg\noffice_3/center/1577400909634751232.jpg\noffice_3/center/1577401144783562752.jpg\noffice_3/center/1577401039337022464.jpg\noffice_3/center/1577401123034187520.jpg\noffice_3/center/1577400863932166400.jpg\noffice_3/center/1577400969841426176.jpg\noffice_3/center/1577400961190432768.jpg\noffice_3/center/1577401038386534656.jpg\noffice_3/center/1577401017037460480.jpg\noffice_3/center/1577400904484264960.jpg\noffice_3/center/1577401172431989248.jpg\noffice_3/center/1577400950589444864.jpg\noffice_3/center/1577401016887721472.jpg\noffice_3/center/1577401058836316160.jpg\noffice_3/center/1577401148333409024.jpg\noffice_3/center/1577401144033143552.jpg\noffice_3/center/1577401050435909888.jpg\noffice_3/center/1577400915836610560.jpg\noffice_3/center/1577400849920084736.jpg\noffice_3/center/1577401168632512512.jpg\noffice_3/center/1577400898484554752.jpg\noffice_3/center/1577400923337145344.jpg\noffice_3/center/1577401072986090752.jpg\noffice_3/center/1577401018087793152.jpg\noffice_3/center/1577401093284857344.jpg\noffice_3/center/1577401129933627136.jpg\noffice_3/center/1577400890784632832.jpg\noffice_3/center/1577401038986033664.jpg\noffice_3/center/1577400880236122368.jpg\noffice_3/center/1577401089584947968.jpg\noffice_3/center/1577401139933557248.jpg\noffice_3/center/1577401132133544192.jpg\noffice_3/center/1577400979141337088.jpg\noffice_3/center/1577401128083680512.jpg\noffice_3/center/1577400875439115776.jpg\noffice_3/center/1577401181182150656.jpg\noffice_3/center/1577400884484382464.jpg\noffice_3/center/1577401110434707968.jpg\noffice_3/center/1577400865333422336.jpg\noffice_3/center/1577400978440934912.jpg\noffice_3/center/1577401132433554176.jpg\noffice_3/center/1577401156782587904.jpg\noffice_3/center/1577400939137799680.jpg\noffice_3/center/1577401116534447360.jpg\noffice_3/center/1577400873189529088.jpg\noffice_3/center/1577401038486265344.jpg\noffice_3/center/1577401100184641792.jpg\noffice_3/center/1577400962640685056.jpg\noffice_3/center/1577400931037686016.jpg\noffice_3/center/1577401178732555776.jpg\noffice_3/center/1577401089135086592.jpg\noffice_3/center/1577401167632800512.jpg\noffice_3/center/1577401113483866880.jpg\noffice_3/center/1577400923537191680.jpg\noffice_3/center/1577401097734851328.jpg\noffice_3/center/1577400936537638912.jpg\noffice_3/center/1577401028787091968.jpg\noffice_3/center/1577401165632568064.jpg\noffice_3/center/1577401100434783232.jpg\noffice_3/center/1577401141933987840.jpg\noffice_3/center/1577400952089326848.jpg\noffice_3/center/1577400905284448768.jpg\noffice_3/center/1577400978790758400.jpg\noffice_3/center/1577401128183405056.jpg\noffice_3/center/1577401065685726464.jpg\noffice_3/center/1577401155933547264.jpg\noffice_3/center/1577401167283200256.jpg\noffice_3/center/1577401156133219072.jpg\noffice_3/center/1577400854174192640.jpg\noffice_3/center/1577400945438531328.jpg\noffice_3/center/1577401112634723072.jpg\noffice_3/center/1577400968891000064.jpg\noffice_3/center/1577400924636994816.jpg\noffice_3/center/1577400948638913792.jpg\noffice_3/center/1577401104834304768.jpg\noffice_3/center/1577400951339443200.jpg\noffice_3/center/1577400980990557952.jpg\noffice_3/center/1577400907134253568.jpg\noffice_3/center/1577401057336116992.jpg\noffice_3/center/1577401050385911808.jpg\noffice_3/center/1577400947689414144.jpg\noffice_3/center/1577401055235716608.jpg\noffice_3/center/1577401095584819712.jpg\noffice_3/center/1577400858678365440.jpg\noffice_3/center/1577401073435718912.jpg\noffice_3/center/1577401026737479936.jpg\noffice_3/center/1577400919087377152.jpg\noffice_3/center/1577400893785084928.jpg\noffice_3/center/1577401121684069120.jpg\noffice_3/center/1577400932337754112.jpg\noffice_3/center/1577401023337246208.jpg\noffice_3/center/1577400907234277120.jpg\noffice_3/center/1577400886034534144.jpg\noffice_3/center/1577401159033240320.jpg\noffice_3/center/1577401162882501376.jpg\noffice_3/center/1577400889784699648.jpg\noffice_3/center/1577401129133827584.jpg\noffice_3/center/1577401071985788160.jpg\noffice_3/center/1577401174232714496.jpg\noffice_3/center/1577401127033643264.jpg\noffice_3/center/1577401125034106624.jpg\noffice_3/center/1577400944488394752.jpg\noffice_3/center/1577401019287610368.jpg\noffice_3/center/1577400888984717568.jpg\noffice_3/center/1577401103984481536.jpg\noffice_3/center/1577400920687266560.jpg\noffice_3/center/1577400876138128640.jpg\noffice_3/center/1577400879037402880.jpg\noffice_3/center/1577401149383593472.jpg\noffice_3/center/1577400859078216448.jpg\noffice_3/center/1577400862681112832.jpg\noffice_3/center/1577401162982588672.jpg\noffice_3/center/1577400854374310400.jpg\noffice_3/center/1577400943788157952.jpg\noffice_3/center/1577400879137420800.jpg\noffice_3/center/1577400918586594816.jpg\noffice_3/center/1577401070286079488.jpg\noffice_3/center/1577401045786177792.jpg\noffice_3/center/1577401074635649280.jpg\noffice_3/center/1577400872139293952.jpg\noffice_3/center/1577400855074653696.jpg\noffice_3/center/1577401011288388608.jpg\noffice_3/center/1577400923237161216.jpg\noffice_3/center/1577401064286013952.jpg\noffice_3/center/1577401086285030400.jpg\noffice_3/center/1577401170182349312.jpg\noffice_3/center/1577401139683694848.jpg\noffice_3/center/1577401134133487872.jpg\noffice_3/center/1577401135133926656.jpg\noffice_3/center/1577400849870097664.jpg\noffice_3/center/1577401128833956864.jpg\noffice_3/center/1577401081585054976.jpg\noffice_3/center/1577401165082306560.jpg\noffice_3/center/1577400854724583168.jpg\noffice_3/center/1577401112534599680.jpg\noffice_3/center/1577400947789412608.jpg\noffice_3/center/1577401173681940992.jpg\noffice_3/center/1577401145733521920.jpg\noffice_3/center/1577400938587901952.jpg\noffice_3/center/1577401054535719936.jpg\noffice_3/center/1577400975791760384.jpg\noffice_3/center/1577401183882038016.jpg\noffice_3/center/1577401015087705344.jpg\noffice_3/center/1577401075435478528.jpg\noffice_3/center/1577401014538608640.jpg\noffice_3/center/1577400909934714112.jpg\noffice_3/center/1577401131483681280.jpg\noffice_3/center/1577401124483958016.jpg\noffice_3/center/1577401137333570816.jpg\noffice_3/center/1577401164482968064.jpg\noffice_3/center/1577400859979032576.jpg\noffice_3/center/1577401175332750080.jpg\noffice_3/center/1577401022437314816.jpg\noffice_3/center/1577400967240955136.jpg\noffice_3/center/1577400885434795520.jpg\noffice_3/center/1577401173132785664.jpg\noffice_3/center/1577401029487053824.jpg\noffice_3/center/1577401047536205312.jpg\noffice_3/center/1577400941638115840.jpg\noffice_3/center/1577400947589245440.jpg\noffice_3/center/1577400903634450432.jpg\noffice_3/center/1577401017787974912.jpg\noffice_3/center/1577401044286252288.jpg\noffice_3/center/1577401081735034624.jpg\noffice_3/center/1577401113284146944.jpg\noffice_3/center/1577400912785703168.jpg\noffice_3/center/1577401109034798080.jpg\noffice_3/center/1577400920987231488.jpg\noffice_3/center/1577401169832375296.jpg\noffice_3/center/1577400862831395584.jpg\noffice_3/center/1577400865733661696.jpg\noffice_3/center/1577400845614142464.jpg\noffice_3/center/1577400869035953408.jpg\noffice_3/center/1577401097084644096.jpg\noffice_3/center/1577401130183669504.jpg\noffice_3/center/1577401015387875072.jpg\noffice_3/center/1577400914336297984.jpg\noffice_3/center/1577400913235603200.jpg\noffice_3/center/1577400962040747776.jpg\noffice_3/center/1577400973491621376.jpg\noffice_3/center/1577401111334685184.jpg\noffice_3/center/1577401119734317568.jpg\noffice_3/center/1577400869987276544.jpg\noffice_3/center/1577400878336342528.jpg\noffice_3/center/1577400908334756864.jpg\noffice_3/center/1577401046585847040.jpg\noffice_3/center/1577401010788324096.jpg\noffice_3/center/1577401032186577920.jpg\noffice_3/center/1577401127983771648.jpg\noffice_3/center/1577400906033915136.jpg\noffice_3/center/1577400935937750016.jpg\noffice_3/center/1577401107934693632.jpg\noffice_3/center/1577401078985574656.jpg\noffice_3/center/1577401015237748480.jpg\noffice_3/center/1577400872637827328.jpg\noffice_3/center/1577400854124090368.jpg\noffice_3/center/1577401124184064000.jpg\noffice_3/center/1577401038536131072.jpg\noffice_3/center/1577400936037764096.jpg\noffice_3/center/1577400852773070592.jpg\noffice_3/center/1577400874689071104.jpg\noffice_3/center/1577400974441539328.jpg\noffice_3/center/1577400963290337024.jpg\noffice_3/center/1577400891534924800.jpg\noffice_3/center/1577401031986625792.jpg\noffice_3/center/1577401164832387840.jpg\noffice_3/center/1577400948388766976.jpg\noffice_3/center/1577401063385732864.jpg\noffice_3/center/1577401122234234112.jpg\noffice_3/center/1577401157432739328.jpg\noffice_3/center/1577401099884748288.jpg\noffice_3/center/1577400894784926976.jpg\noffice_3/center/1577401146583291392.jpg\noffice_3/center/1577400953940089088.jpg\noffice_3/center/1577400970441320448.jpg\noffice_3/center/1577400977640950016.jpg\noffice_3/center/1577400899034705664.jpg\noffice_3/center/1577401070435958272.jpg\noffice_3/center/1577400971491491328.jpg\noffice_3/center/1577401021487681024.jpg\noffice_3/center/1577401123984140800.jpg\noffice_3/center/1577401112734871808.jpg\noffice_3/center/1577401071785929984.jpg\noffice_3/center/1577400885884790016.jpg\noffice_3/center/1577401052085893120.jpg\noffice_3/center/1577400970241120256.jpg\noffice_3/center/1577400912335601920.jpg\noffice_3/center/1577401137783130112.jpg\noffice_3/center/1577400929687201536.jpg\noffice_3/center/1577401103084406272.jpg\noffice_3/center/1577401049385755392.jpg\noffice_3/center/1577401061136118016.jpg\noffice_3/center/1577401095785000192.jpg\noffice_3/center/1577401115034780928.jpg\noffice_3/center/1577400969641375232.jpg\noffice_3/center/1577401123584163328.jpg\noffice_3/center/1577401095885051904.jpg\noffice_3/center/1577401035886850816.jpg\noffice_3/center/1577400931937537024.jpg\noffice_3/center/1577400953740050688.jpg\noffice_3/center/1577401175582120704.jpg\noffice_3/center/1577401096484785664.jpg\noffice_3/center/1577401043386297088.jpg\noffice_3/center/1577400909534777600.jpg\noffice_3/center/1577401064385932288.jpg\noffice_3/center/1577401120484303872.jpg\noffice_3/center/1577400860679582720.jpg\noffice_3/center/1577401164333068800.jpg\noffice_3/center/1577400933637338112.jpg\noffice_3/center/1577401013288218368.jpg\noffice_3/center/1577401123134101504.jpg\noffice_3/center/1577400857427309056.jpg\noffice_3/center/1577400920537282304.jpg\noffice_3/center/1577400873089582848.jpg\noffice_3/center/1577400968391079680.jpg\noffice_3/center/1577401139233561600.jpg\noffice_3/center/1577401059635938048.jpg\noffice_3/center/1577400906384679680.jpg\noffice_3/center/1577400924937612288.jpg\noffice_3/center/1577401146782963968.jpg\noffice_3/center/1577401181382012928.jpg\noffice_3/center/1577400900334600960.jpg\noffice_3/center/1577400867184900352.jpg\noffice_3/center/1577400885685021184.jpg\noffice_3/center/1577400935737583360.jpg\noffice_3/center/1577401107984570880.jpg\noffice_3/center/1577400863732003328.jpg\noffice_3/center/1577400853823740928.jpg\noffice_3/center/1577401119334141696.jpg\noffice_3/center/1577400876988016384.jpg\noffice_3/center/1577401032336599552.jpg\noffice_3/center/1577400952889921024.jpg\noffice_3/center/1577401044086304768.jpg\noffice_3/center/1577401099384801792.jpg\noffice_3/center/1577401042036348416.jpg\noffice_3/center/1577401039986361856.jpg\noffice_3/center/1577401153382882560.jpg\noffice_3/center/1577400843912922880.jpg\noffice_3/center/1577400899784519424.jpg\noffice_3/center/1577400942888532992.jpg\noffice_3/center/1577401032086565888.jpg\noffice_3/center/1577400917086846720.jpg\noffice_3/center/1577400901734473728.jpg\noffice_3/center/1577400954189708544.jpg\noffice_3/center/1577401157882928640.jpg\noffice_3/center/1577401164632766208.jpg\noffice_3/center/1577400850371058944.jpg\noffice_3/center/1577401015637935616.jpg\noffice_3/center/1577400898984727296.jpg\noffice_3/center/1577400909084417536.jpg\noffice_3/center/1577401130033668096.jpg\noffice_3/center/1577400918987250432.jpg\noffice_3/center/1577401134883296000.jpg\noffice_3/center/1577400916586618624.jpg\noffice_3/center/1577400854674574336.jpg\noffice_3/center/1577400852322513664.jpg\noffice_3/center/1577400851321616640.jpg\noffice_3/center/1577401086985246976.jpg\noffice_3/center/1577401171432465920.jpg\noffice_3/center/1577400862530728704.jpg\noffice_3/center/1577401146233595392.jpg\noffice_3/center/1577400894734920192.jpg\noffice_3/center/1577401144883458048.jpg\noffice_3/center/1577400927588065024.jpg\noffice_3/center/1577401012188292352.jpg\noffice_3/center/1577400930287491328.jpg\noffice_3/center/1577401145183075840.jpg\noffice_3/center/1577401079035557888.jpg\noffice_3/center/1577400967341100800.jpg\noffice_3/center/1577400981940087808.jpg\noffice_3/center/1577401120734321408.jpg\noffice_3/center/1577400970341201408.jpg\noffice_3/center/1577401073985824000.jpg\noffice_3/center/1577400970991261952.jpg\noffice_3/center/1577400967791157504.jpg\noffice_3/center/1577400975741796608.jpg\noffice_3/center/1577401131283751680.jpg\noffice_3/center/1577400894534805504.jpg\noffice_3/center/1577400929987156992.jpg\noffice_3/center/1577400926837367040.jpg\noffice_3/center/1577400906834409472.jpg\noffice_3/center/1577400860529434112.jpg\noffice_3/center/1577401076885405440.jpg\noffice_3/center/1577400893334997248.jpg\noffice_3/center/1577400904334225408.jpg\noffice_3/center/1577401020987397632.jpg\noffice_3/center/1577400952739891712.jpg\noffice_3/center/1577400952439476992.jpg\noffice_3/center/1577400946938987264.jpg\noffice_3/center/1577401022337395456.jpg\noffice_3/center/1577400876337696768.jpg\noffice_3/center/1577400951539673088.jpg\noffice_3/center/1577400901984380928.jpg\noffice_3/center/1577401083685226496.jpg\noffice_3/center/1577400938537936640.jpg\noffice_3/center/1577401152183103232.jpg\noffice_3/center/1577401066385998848.jpg\noffice_3/center/1577401111084462080.jpg\noffice_3/center/1577401101434581248.jpg\noffice_3/center/1577401074335553536.jpg\noffice_3/center/1577400873739183616.jpg\noffice_3/center/1577401036836678144.jpg\noffice_3/center/1577401015987794944.jpg\noffice_3/center/1577401096384800256.jpg\noffice_3/center/1577401054635922688.jpg\noffice_3/center/1577400954739613184.jpg\noffice_3/center/1577401095935027200.jpg\noffice_3/center/1577401114034713344.jpg\noffice_3/center/1577400965040670208.jpg\noffice_3/center/1577400914836316416.jpg\noffice_3/center/1577401150783537920.jpg\noffice_3/center/1577400881585600768.jpg\noffice_3/center/1577400906484806400.jpg\noffice_3/center/1577401090884977920.jpg\noffice_3/center/1577401020137482496.jpg\noffice_3/center/1577400944388292864.jpg\noffice_3/center/1577400950139309056.jpg\noffice_3/center/1577400931687406592.jpg\noffice_3/center/1577400959740242432.jpg\noffice_3/center/1577400867535173888.jpg\noffice_3/center/1577400963640355328.jpg\noffice_3/center/1577400964140893184.jpg\noffice_3/center/1577401065835681024.jpg\noffice_3/center/1577400979990492928.jpg\noffice_3/center/1577401116634364160.jpg\noffice_3/center/1577400851572128256.jpg\noffice_3/center/1577400945538480896.jpg\noffice_3/center/1577401109884937216.jpg\noffice_3/center/1577401128883970816.jpg\noffice_3/center/1577401055036320768.jpg\noffice_3/center/1577401088785010944.jpg\noffice_3/center/1577400963490286592.jpg\noffice_3/center/1577400943538311168.jpg\noffice_3/center/1577400982339868672.jpg\noffice_3/center/1577401129333752064.jpg\noffice_3/center/1577401176482558976.jpg\noffice_3/center/1577400844163332352.jpg\noffice_3/center/1577401153182892288.jpg\noffice_3/center/1577400960390638592.jpg\noffice_3/center/1577400933237778432.jpg\noffice_3/center/1577401182731844608.jpg\noffice_3/center/1577401061985934080.jpg\noffice_3/center/1577401154283090688.jpg\noffice_3/center/1577401159682927616.jpg\noffice_3/center/1577400851271537920.jpg\noffice_3/center/1577400946788941568.jpg\noffice_3/center/1577400927287833856.jpg\noffice_3/center/1577401152083131904.jpg\noffice_3/center/1577401053535985152.jpg\noffice_3/center/1577400937737887488.jpg\noffice_3/center/1577400864332502784.jpg\noffice_3/center/1577401058985988608.jpg\noffice_3/center/1577400964340919040.jpg\noffice_3/center/1577401046336151552.jpg\noffice_3/center/1577401152333103104.jpg\noffice_3/center/1577401086684780032.jpg\noffice_3/center/1577400932137672960.jpg\noffice_3/center/1577401110234796800.jpg\noffice_3/center/1577401060986212096.jpg\noffice_3/center/1577400926987133952.jpg\noffice_3/center/1577401127383777792.jpg\noffice_3/center/1577400851471987200.jpg\noffice_3/center/1577400930987680256.jpg\noffice_3/center/1577401079835383296.jpg\noffice_3/center/1577401065187035648.jpg\noffice_3/center/1577401057036059392.jpg\noffice_3/center/1577400867935237888.jpg\noffice_3/center/1577401019137693184.jpg\noffice_3/center/1577400847817019904.jpg\noffice_3/center/1577401026887629312.jpg\noffice_3/center/1577401045736179712.jpg\noffice_3/center/1577400920237116416.jpg\noffice_3/center/1577401061086183936.jpg\noffice_3/center/1577401132083524864.jpg\noffice_3/center/1577400859377772032.jpg\noffice_3/center/1577401047486251008.jpg\noffice_3/center/1577401017237564160.jpg\noffice_3/center/1577401084585308928.jpg\noffice_3/center/1577400880385739520.jpg\noffice_3/center/1577401158732984576.jpg\noffice_3/center/1577400924037574144.jpg\noffice_3/center/1577401073735802624.jpg\noffice_3/center/1577401097585080064.jpg\noffice_3/center/1577401169932415232.jpg\noffice_3/center/1577401019537701632.jpg\noffice_3/center/1577400855675151360.jpg\noffice_3/center/1577401160333198592.jpg\noffice_3/center/1577400863581832448.jpg\noffice_3/center/1577401012488230400.jpg\noffice_3/center/1577401070535893504.jpg\noffice_3/center/1577401163933043456.jpg\noffice_3/center/1577401113684206592.jpg\noffice_3/center/1577401140033557504.jpg\noffice_3/center/1577401105934203904.jpg\noffice_3/center/1577400964240929536.jpg\noffice_3/center/1577401137283617536.jpg\noffice_3/center/1577400893184898816.jpg\noffice_3/center/1577401154982917376.jpg\noffice_3/center/1577401032986669056.jpg\noffice_3/center/1577401025487512064.jpg\noffice_3/center/1577400970841427200.jpg\noffice_3/center/1577400932387845120.jpg\noffice_3/center/1577401106634583040.jpg\noffice_3/center/1577401116334562048.jpg\noffice_3/center/1577401181232090112.jpg\noffice_3/center/1577400876887851264.jpg\noffice_3/center/1577401172082662144.jpg\noffice_3/center/1577401165932503808.jpg\noffice_3/center/1577400907634195712.jpg\noffice_3/center/1577401076435181824.jpg\noffice_3/center/1577401145333096960.jpg\noffice_3/center/1577400974841554944.jpg\noffice_3/center/1577401051385728512.jpg\noffice_3/center/1577401145833556992.jpg\noffice_3/center/1577400972241346048.jpg\noffice_3/center/1577401095835022592.jpg\noffice_3/center/1577401181682211584.jpg\noffice_3/center/1577401082085708032.jpg\noffice_3/center/1577401066435878400.jpg\noffice_3/center/1577401101884482304.jpg\noffice_3/center/1577401064435892480.jpg\noffice_3/center/1577400929087705344.jpg\noffice_3/center/1577401148632773120.jpg\noffice_3/center/1577400858778476800.jpg\noffice_3/center/1577400885734936320.jpg\noffice_3/center/1577401022287408128.jpg\noffice_3/center/1577401133683252224.jpg\noffice_3/center/1577400898934761216.jpg\noffice_3/center/1577401115234535168.jpg\noffice_3/center/1577401145233057024.jpg\noffice_3/center/1577401051435725056.jpg\noffice_3/center/1577400958940348928.jpg\noffice_3/center/1577400943288329984.jpg\noffice_3/center/1577400897084802304.jpg\noffice_3/center/1577401158432844544.jpg\noffice_3/center/1577401075385532160.jpg\noffice_3/center/1577400846115343104.jpg\noffice_3/center/1577401081885269248.jpg\noffice_3/center/1577400898184493824.jpg\noffice_3/center/1577401183832047360.jpg\noffice_3/center/1577401080335664896.jpg\noffice_3/center/1577400875688666880.jpg\noffice_3/center/1577401100534769152.jpg\noffice_3/center/1577401020687253504.jpg\noffice_3/center/1577401035637021952.jpg\noffice_3/center/1577401154233036544.jpg\noffice_3/center/1577401043036269568.jpg\noffice_3/center/1577400884884357888.jpg\noffice_3/center/1577400889884813824.jpg\noffice_3/center/1577401179132435712.jpg\noffice_3/center/1577401161432884224.jpg\noffice_3/center/1577401063786122752.jpg\noffice_3/center/1577400979191336960.jpg\noffice_3/center/1577400891584966144.jpg\noffice_3/center/1577401105534689280.jpg\noffice_3/center/1577401102284482816.jpg\noffice_3/center/1577401123784102912.jpg\noffice_3/center/1577400966041558016.jpg\noffice_3/center/1577401137383518208.jpg\noffice_3/center/1577400960190651648.jpg\noffice_3/center/1577401129033879296.jpg\noffice_3/center/1577401116084327424.jpg\noffice_3/center/1577400882184977152.jpg\noffice_3/center/1577401119634310656.jpg\noffice_3/center/1577400977741030656.jpg\noffice_3/center/1577401120434270720.jpg\noffice_3/center/1577401064335957760.jpg\noffice_3/center/1577401076085904640.jpg\noffice_3/center/1577400855725278208.jpg\noffice_3/center/1577401155482722816.jpg\noffice_3/center/1577400912985704960.jpg\noffice_3/center/1577400890684699904.jpg\noffice_3/center/1577400981190340096.jpg\noffice_3/center/1577401116934229504.jpg\noffice_3/center/1577400933937529344.jpg\noffice_3/center/1577401128733851904.jpg\noffice_3/center/1577401157632920576.jpg\noffice_3/center/1577401142033949696.jpg\noffice_3/center/1577400866284002048.jpg\noffice_3/center/1577401123334062848.jpg\noffice_3/center/1577401037186724864.jpg\noffice_3/center/1577400844663345408.jpg\noffice_3/center/1577401061635842560.jpg\noffice_3/center/1577400934638003456.jpg\noffice_3/center/1577400850971147008.jpg\noffice_3/center/1577401090284925696.jpg\noffice_3/center/1577400914035835136.jpg\noffice_3/center/1577401010838303744.jpg\noffice_3/center/1577400931537436416.jpg\noffice_3/center/1577401078335194112.jpg\noffice_3/center/1577401151883258624.jpg\noffice_3/center/1577401124134074368.jpg\noffice_3/center/1577401056336184832.jpg\noffice_3/center/1577401104934432000.jpg\noffice_3/center/1577401171682693376.jpg\noffice_3/center/1577401015337827840.jpg\noffice_3/center/1577400882434650624.jpg\noffice_3/center/1577401100234668544.jpg\noffice_3/center/1577401087985079552.jpg\noffice_3/center/1577401163182850560.jpg\noffice_3/center/1577400887584399872.jpg\noffice_3/center/1577400850321005056.jpg\noffice_3/center/1577401089734896896.jpg\noffice_3/center/1577401067336289024.jpg\noffice_3/center/1577400892784740096.jpg\noffice_3/center/1577400857776525056.jpg\noffice_3/center/1577400954839666944.jpg\noffice_3/center/1577400943388296960.jpg\noffice_3/center/1577401135333607424.jpg\noffice_3/center/1577401035936764928.jpg\noffice_3/center/1577401137733155584.jpg\noffice_3/center/1577401118234165248.jpg\noffice_3/center/1577400955339748608.jpg\noffice_3/center/1577400936532416768.jpg\noffice_3/center/1577400967441179136.jpg\noffice_3/center/1577401079185495552.jpg\noffice_3/center/1577401162333269760.jpg\noffice_3/center/1577401080785265408.jpg\noffice_3/center/1577400844813402368.jpg\noffice_3/center/1577400950839145216.jpg\noffice_3/center/1577401065735686912.jpg\noffice_3/center/1577400970941297408.jpg\noffice_3/center/1577401117384463872.jpg\noffice_3/center/1577401027087600384.jpg\noffice_3/center/1577400966391032320.jpg\noffice_3/center/1577401090684661248.jpg\noffice_3/center/1577401035786953984.jpg\noffice_3/center/1577401061485809152.jpg\noffice_3/center/1577400871939286272.jpg\noffice_3/center/1577401014887768576.jpg\noffice_3/center/1577401161232925184.jpg\noffice_3/center/1577401161482933248.jpg\noffice_3/center/1577401026037019904.jpg\noffice_3/center/1577401184481826048.jpg\noffice_3/center/1577400845363720704.jpg\noffice_3/center/1577401109434515712.jpg\noffice_3/center/1577401056086269440.jpg\noffice_3/center/1577401082985024256.jpg\noffice_3/center/1577401107784937216.jpg\noffice_3/center/1577401182432277504.jpg\noffice_3/center/1577400979041232128.jpg\noffice_3/center/1577401087484839168.jpg\noffice_3/center/1577401138383542784.jpg\noffice_3/center/1577401066485783296.jpg\noffice_3/center/1577401153732781824.jpg\noffice_3/center/1577400900534578944.jpg\noffice_3/center/1577401110484699392.jpg\noffice_3/center/1577400914486444544.jpg\noffice_3/center/1577400964490918144.jpg\noffice_3/center/1577401037336599040.jpg\noffice_3/center/1577400924486912000.jpg\noffice_3/center/1577401016338064384.jpg\noffice_3/center/1577401174632522496.jpg\noffice_3/center/1577400914986145280.jpg\noffice_3/center/1577401038685783040.jpg\noffice_3/center/1577401149633403392.jpg\noffice_3/center/1577401150483476224.jpg\noffice_3/center/1577401156532447488.jpg\noffice_3/center/1577401075335599616.jpg\noffice_3/center/1577401049986051584.jpg\noffice_3/center/1577400901584658176.jpg\noffice_3/center/1577401103234375680.jpg\noffice_3/center/1577400957089705216.jpg\noffice_3/center/1577400922687604992.jpg\noffice_3/center/1577401043686310144.jpg\noffice_3/center/1577401013687934208.jpg\noffice_3/center/1577400882634704896.jpg\noffice_3/center/1577401021787376128.jpg\noffice_3/center/1577400954339495424.jpg\noffice_3/center/1577400965841142016.jpg\noffice_3/center/1577401126684083712.jpg\noffice_3/center/1577401157832925696.jpg\noffice_3/center/1577401146733037568.jpg\noffice_3/center/1577400930937628160.jpg\noffice_3/center/1577401093334859008.jpg\noffice_3/center/1577401066086002688.jpg\noffice_3/center/1577401100384765952.jpg\noffice_3/center/1577400868786000896.jpg\noffice_3/center/1577400888135149056.jpg\noffice_3/center/1577400919886940672.jpg\noffice_3/center/1577400876088119296.jpg\noffice_3/center/1577401138733336576.jpg\noffice_3/center/1577400863832111360.jpg\noffice_3/center/1577401161582967552.jpg\noffice_3/center/1577400891234847232.jpg\noffice_3/center/1577400904684289280.jpg\noffice_3/center/1577400919437356032.jpg\noffice_3/center/1577400946889051648.jpg\noffice_3/center/1577400969441349632.jpg\noffice_3/center/1577401029986934528.jpg\noffice_3/center/1577400978740759552.jpg\noffice_3/center/1577400922037247488.jpg\noffice_3/center/1577400931287662592.jpg\noffice_3/center/1577400958740314624.jpg\noffice_3/center/1577401124884045568.jpg\noffice_3/center/1577401112584643584.jpg\noffice_3/center/1577401160732923136.jpg\noffice_3/center/1577400914536454400.jpg\noffice_3/center/1577401019737793024.jpg\noffice_3/center/1577401179882312704.jpg\noffice_3/center/1577401084635285504.jpg\noffice_3/center/1577401102034448128.jpg\noffice_3/center/1577400954089841408.jpg\noffice_3/center/1577401176382581248.jpg\noffice_3/center/1577400925337056512.jpg\noffice_3/center/1577401076735497728.jpg\noffice_3/center/1577401138583371008.jpg\noffice_3/center/1577400858928413696.jpg\noffice_3/center/1577401087335239424.jpg\noffice_3/center/1577400963940714496.jpg\noffice_3/center/1577401155583084032.jpg\noffice_3/center/1577400950189350912.jpg\noffice_3/center/1577401130783817728.jpg\noffice_3/center/1577400917286838016.jpg\noffice_3/center/1577400892534700032.jpg\noffice_3/center/1577401046186244096.jpg\noffice_3/center/1577401037236694784.jpg\noffice_3/center/1577400875738696192.jpg\noffice_3/center/1577401112384425984.jpg\noffice_3/center/1577401147133106944.jpg\noffice_3/center/1577401181032252160.jpg\noffice_3/center/1577401052785911808.jpg\noffice_3/center/1577401055285636608.jpg\noffice_3/center/1577401129183825920.jpg\noffice_3/center/1577401045386126848.jpg\noffice_3/center/1577401019237618688.jpg\noffice_3/center/1577400862280512768.jpg\noffice_3/center/1577400892285043456.jpg\noffice_3/center/1577400890834655488.jpg\noffice_3/center/1577400898434542080.jpg\noffice_3/center/1577401178332417280.jpg\noffice_3/center/1577401117184389120.jpg\noffice_3/center/1577401136283657984.jpg\noffice_3/center/1577400910434772736.jpg\noffice_3/center/1577400935987761408.jpg\noffice_3/center/1577401178532353024.jpg\noffice_3/center/1577400958790320896.jpg\noffice_3/center/1577401118484254208.jpg\noffice_3/center/1577400880685981696.jpg\noffice_3/center/1577401075835932160.jpg\noffice_3/center/1577401141233217536.jpg\noffice_3/center/1577400869937210368.jpg\noffice_3/center/1577400881535806464.jpg\noffice_3/center/1577401130483447808.jpg\noffice_3/center/1577400897634638336.jpg\noffice_3/center/1577400869236076288.jpg\noffice_3/center/1577400945388572672.jpg\noffice_3/center/1577400905933958656.jpg\noffice_3/center/1577401151433014016.jpg\noffice_3/center/1577400871337806848.jpg\noffice_3/center/1577400979291294464.jpg\noffice_3/center/1577400860129153280.jpg\noffice_3/center/1577400961040430848.jpg\noffice_3/center/1577401042886224128.jpg\noffice_3/center/1577400977690982656.jpg\noffice_3/center/1577401021937372672.jpg\noffice_3/center/1577401121834084096.jpg\noffice_3/center/1577401156482556416.jpg\noffice_3/center/1577400913335550976.jpg\noffice_3/center/1577400957189930496.jpg\noffice_3/center/1577401035536943104.jpg\noffice_3/center/1577400918036981504.jpg\noffice_3/center/1577401091135395328.jpg\noffice_3/center/1577401141733405184.jpg\noffice_3/center/1577400963990782464.jpg\noffice_3/center/1577401054936388096.jpg\noffice_3/center/1577400879287546112.jpg\noffice_3/center/1577400907984448000.jpg\noffice_3/center/1577400931887502848.jpg\noffice_3/center/1577401118134333952.jpg\noffice_3/center/1577400910334675712.jpg\noffice_3/center/1577400951389559040.jpg\noffice_3/center/1577401102884552448.jpg\noffice_3/center/1577401168432631040.jpg\noffice_3/center/1577401074485559040.jpg\noffice_3/center/1577401033086702592.jpg\noffice_3/center/1577401133883236608.jpg\noffice_3/center/1577401113533895424.jpg\noffice_3/center/1577401139733713408.jpg\noffice_3/center/1577400976691246592.jpg\noffice_3/center/1577401057735941376.jpg\noffice_3/center/1577401053085835264.jpg\noffice_3/center/1577400853573568768.jpg\noffice_3/center/1577401177832343552.jpg\noffice_3/center/1577400848518388224.jpg\noffice_3/center/1577400890535134464.jpg\noffice_3/center/1577401161933022720.jpg\noffice_3/center/1577401170882334976.jpg\noffice_3/center/1577400915036076288.jpg\noffice_3/center/1577400971291190528.jpg\noffice_3/center/1577401110934388736.jpg\noffice_3/center/1577400940237831168.jpg\noffice_3/center/1577400892934755072.jpg\noffice_3/center/1577401173782040576.jpg\noffice_3/center/1577400854224182784.jpg\noffice_3/center/1577401025887181056.jpg\noffice_3/center/1577401169882424064.jpg\noffice_3/center/1577401018387605248.jpg\noffice_3/center/1577400981639924992.jpg\noffice_3/center/1577401070685852160.jpg\noffice_3/center/1577400914386391296.jpg\noffice_3/center/1577401039186664704.jpg\noffice_3/center/1577401147782972928.jpg\noffice_3/center/1577400881885474048.jpg\noffice_3/center/1577400963090669568.jpg\noffice_3/center/1577401072085713920.jpg\noffice_3/center/1577401135632465920.jpg\noffice_3/center/1577401101934459904.jpg\noffice_3/center/1577400908384742400.jpg\noffice_3/center/1577401044136288512.jpg\noffice_3/center/1577400925737788416.jpg\noffice_3/center/1577400973291660288.jpg\noffice_3/center/1577400887184652544.jpg\noffice_3/center/1577400974791522560.jpg\noffice_3/center/1577401073535740928.jpg\noffice_3/center/1577400930137367808.jpg\noffice_3/center/1577401088535028480.jpg\noffice_3/center/1577401070386014464.jpg\noffice_3/center/1577401031836719616.jpg\noffice_3/center/1577400863882183936.jpg\noffice_3/center/1577401169182621952.jpg\noffice_3/center/1577400958690251520.jpg\noffice_3/center/1577400849819862784.jpg\noffice_3/center/1577400956539877888.jpg\noffice_3/center/1577401158332921088.jpg\noffice_3/center/1577400913985798144.jpg\noffice_3/center/1577401020587309568.jpg\noffice_3/center/1577401080035467008.jpg\noffice_3/center/1577400895485039360.jpg\noffice_3/center/1577400870087341568.jpg\noffice_3/center/1577400956589869568.jpg\noffice_3/center/1577400975291882240.jpg\noffice_3/center/1577400850921094144.jpg\noffice_3/center/1577400906083983360.jpg\noffice_3/center/1577401153232850176.jpg\noffice_3/center/1577400898084458752.jpg\noffice_3/center/1577401148582849536.jpg\noffice_3/center/1577400955789858304.jpg\noffice_3/center/1577401134333402112.jpg\noffice_3/center/1577400944438361088.jpg\noffice_3/center/1577400860929682688.jpg\noffice_3/center/1577400960640576000.jpg\noffice_3/center/1577401092534792448.jpg\noffice_3/center/1577400924536936704.jpg\noffice_3/center/1577400851421842944.jpg\noffice_3/center/1577401156282887936.jpg\noffice_3/center/1577400848217945856.jpg\noffice_3/center/1577401058185924352.jpg\noffice_3/center/1577401060635992320.jpg\noffice_3/center/1577400956390022912.jpg\noffice_3/center/1577401046935782912.jpg\noffice_3/center/1577400954589471232.jpg\noffice_3/center/1577401066585642752.jpg\noffice_3/center/1577400913785717504.jpg\noffice_3/center/1577401128933956096.jpg\noffice_3/center/1577401136083895296.jpg\noffice_3/center/1577401037086712576.jpg\noffice_3/center/1577401134083475200.jpg\noffice_3/center/1577400895934463488.jpg\noffice_3/center/1577400919137387520.jpg\noffice_3/center/1577401165782486272.jpg\noffice_3/center/1577400949639070208.jpg\noffice_3/center/1577401066186094592.jpg\noffice_3/center/1577401050835834880.jpg\noffice_3/center/1577401097234792704.jpg\noffice_3/center/1577401104684163328.jpg\noffice_3/center/1577400897934479104.jpg\noffice_3/center/1577401100034652928.jpg\noffice_3/center/1577401169132578304.jpg\noffice_3/center/1577401183732099584.jpg\noffice_3/center/1577401119084311808.jpg\noffice_3/center/1577401156382718464.jpg\noffice_3/center/1577401105334696448.jpg\noffice_3/center/1577400874989315328.jpg\noffice_3/center/1577401152883123200.jpg\noffice_3/center/1577401057586008832.jpg\noffice_3/center/1577400916536629504.jpg\noffice_3/center/1577401025787330048.jpg\noffice_3/center/1577400903934430208.jpg\noffice_3/center/1577401044586150400.jpg\noffice_3/center/1577401150082513408.jpg\noffice_3/center/1577401133184130560.jpg\noffice_3/center/1577400944288158976.jpg\noffice_3/center/1577400853623555584.jpg\noffice_3/center/1577401074235628288.jpg\noffice_3/center/1577400878687134464.jpg\noffice_3/center/1577401145283072512.jpg\noffice_3/center/1577400936787802880.jpg\noffice_3/center/1577401064886028544.jpg\noffice_3/center/1577401023637248768.jpg\noffice_3/center/1577400934137730816.jpg\noffice_3/center/1577401100834544640.jpg\noffice_3/center/1577400887484439040.jpg\noffice_3/center/1577400894834937344.jpg\noffice_3/center/1577400968191111168.jpg\noffice_3/center/1577401034936827904.jpg\noffice_3/center/1577401035386724352.jpg\noffice_3/center/1577401086534894592.jpg\noffice_3/center/1577400927637903360.jpg\noffice_3/center/1577401139833654784.jpg\noffice_3/center/1577400946038739968.jpg\noffice_3/center/1577401026287131392.jpg\noffice_3/center/1577401068085644032.jpg\noffice_3/center/1577400903884466944.jpg\noffice_3/center/1577400980340349952.jpg\noffice_3/center/1577400960940527616.jpg\noffice_3/center/1577401101984459008.jpg\noffice_3/center/1577401066935940608.jpg\noffice_3/center/1577400873289366784.jpg\noffice_3/center/1577400884084897536.jpg\noffice_3/center/1577401091634636800.jpg\noffice_3/center/1577401072585921792.jpg\noffice_3/center/1577400977141511424.jpg\noffice_3/center/1577401148682760960.jpg\noffice_3/center/1577401029936927744.jpg\noffice_3/center/1577400905384487936.jpg\noffice_3/center/1577401090634600448.jpg\noffice_3/center/1577400929287741184.jpg\noffice_3/center/1577401099635027200.jpg\noffice_3/center/1577401029836960768.jpg\noffice_3/center/1577400963390243072.jpg\noffice_3/center/1577400869486631680.jpg\noffice_3/center/1577400844863412992.jpg\noffice_3/center/1577401174032547840.jpg\noffice_3/center/1577400895134939904.jpg\noffice_3/center/1577400965140456192.jpg\noffice_3/center/1577400922137362944.jpg\noffice_3/center/1577400854324223744.jpg\noffice_3/center/1577401068535848704.jpg\noffice_3/center/1577400874889314048.jpg\noffice_3/center/1577401022637267456.jpg\noffice_3/center/1577400908934201088.jpg\noffice_3/center/1577400905834097152.jpg\noffice_3/center/1577400962790724352.jpg\noffice_3/center/1577401183031755520.jpg\noffice_3/center/1577401163833101568.jpg\noffice_3/center/1577401119934309376.jpg\noffice_3/center/1577401130333521152.jpg\noffice_3/center/1577400869737061120.jpg\noffice_3/center/1577400924237432320.jpg\noffice_3/center/1577401048040913920.jpg\noffice_3/center/1577400903284348672.jpg\noffice_3/center/1577400972091525888.jpg\noffice_3/center/1577401049535874304.jpg\noffice_3/center/1577400870837999616.jpg\noffice_3/center/1577400875538952960.jpg\noffice_3/center/1577400924287334144.jpg\noffice_3/center/1577400940088109824.jpg\noffice_3/center/1577400907584227840.jpg\noffice_3/center/1577400908884172544.jpg\noffice_3/center/1577400918236717824.jpg\noffice_3/center/1577401042836200704.jpg\noffice_3/center/1577400943688198400.jpg\noffice_3/center/1577401032386603776.jpg\noffice_3/center/1577400978191325440.jpg\noffice_3/center/1577400979740709888.jpg\noffice_3/center/1577401133084094464.jpg\noffice_3/center/1577400891785127680.jpg\noffice_3/center/1577400917436712960.jpg\noffice_3/center/1577400919637079296.jpg\noffice_3/center/1577401154333108480.jpg\noffice_3/center/1577401090234921984.jpg\noffice_3/center/1577401086185111040.jpg\noffice_3/center/1577401020537331712.jpg\noffice_3/center/1577400856725230080.jpg\noffice_3/center/1577400854074070528.jpg\noffice_3/center/1577400911785051904.jpg\noffice_3/center/1577400856875256832.jpg\noffice_3/center/1577400932837862656.jpg\noffice_3/center/1577401110384736256.jpg\noffice_3/center/1577400980640361216.jpg\noffice_3/center/1577401152233094656.jpg\noffice_3/center/1577401082884856064.jpg\noffice_3/center/1577401052685980672.jpg\noffice_3/center/1577401063435755264.jpg\noffice_3/center/1577401075685684480.jpg\noffice_3/center/1577401087584756224.jpg\noffice_3/center/1577400859828703232.jpg\noffice_3/center/1577401012888143104.jpg\noffice_3/center/1577401140583561984.jpg\noffice_3/center/1577401092084770816.jpg\noffice_3/center/1577400973191725056.jpg\noffice_3/center/1577400925237238016.jpg\noffice_3/center/1577400886084484352.jpg\noffice_3/center/1577401130833839616.jpg\noffice_3/center/1577400852873105152.jpg\noffice_3/center/1577401151733267712.jpg\noffice_3/center/1577400886484591616.jpg\noffice_3/center/1577401118084450304.jpg\noffice_3/center/1577400848568425472.jpg\noffice_3/center/1577401154383141376.jpg\noffice_3/center/1577401040086432512.jpg\noffice_3/center/1577401079485485056.jpg\noffice_3/center/1577400934337860608.jpg\noffice_3/center/1577400894984878848.jpg\noffice_3/center/1577401114934785280.jpg\noffice_3/center/1577401107434608128.jpg\noffice_3/center/1577401070336062976.jpg\noffice_3/center/1577401148433185024.jpg\noffice_3/center/1577401153083001600.jpg\noffice_3/center/1577401071535861760.jpg\noffice_3/center/1577400867685250560.jpg\noffice_3/center/1577400844713366272.jpg\noffice_3/center/1577401061285936128.jpg\noffice_3/center/1577401076635429376.jpg\noffice_3/center/1577401056985997824.jpg\noffice_3/center/1577401115184579584.jpg\noffice_3/center/1577400941987971328.jpg\noffice_3/center/1577401050985863168.jpg\noffice_3/center/1577400879437365504.jpg\noffice_3/center/1577401093684803584.jpg\noffice_3/center/1577401170482489856.jpg\noffice_3/center/1577401183782084096.jpg\noffice_3/center/1577400891084722944.jpg\noffice_3/center/1577401012088380160.jpg\noffice_3/center/1577401082934930688.jpg\noffice_3/center/1577400844363330560.jpg\noffice_3/center/1577400929187741696.jpg\noffice_3/center/1577400860279295744.jpg\noffice_3/center/1577400912585696000.jpg\noffice_3/center/1577400855124612864.jpg\noffice_3/center/1577401064036204032.jpg\noffice_3/center/1577400959790214912.jpg\noffice_3/center/1577401098485114112.jpg\noffice_3/center/1577401118934371584.jpg\noffice_3/center/1577400933287731712.jpg\noffice_3/center/1577401132833723904.jpg\noffice_3/center/1577400869586870528.jpg\noffice_3/center/1577401126783946240.jpg\noffice_3/center/1577400895535000576.jpg\noffice_3/center/1577400930537619456.jpg\noffice_3/center/1577401082584796160.jpg\noffice_3/center/1577401171232395264.jpg\noffice_3/center/1577400887634423040.jpg\noffice_3/center/1577401098234475264.jpg\noffice_3/center/1577401155733490688.jpg\noffice_3/center/1577400974241576960.jpg\noffice_3/center/1577401174982490112.jpg\noffice_3/center/1577400912285655296.jpg\noffice_3/center/1577401078235257088.jpg\noffice_3/center/1577401114984811776.jpg\noffice_3/center/1577400890084954880.jpg\noffice_3/center/1577400917837161984.jpg\noffice_3/center/1577401120334299136.jpg\noffice_3/center/1577401110884387072.jpg\noffice_3/center/1577400905184377088.jpg\noffice_3/center/1577401118384185088.jpg\noffice_3/center/1577401173882201088.jpg\noffice_3/center/1577400946138740736.jpg\noffice_3/center/1577401097184770560.jpg\noffice_3/center/1577401023737249024.jpg\noffice_3/center/1577401140083557632.jpg\noffice_3/center/1577401118284146432.jpg\noffice_3/center/1577400883634360320.jpg\noffice_3/center/1577401069285712128.jpg\noffice_3/center/1577400919736975104.jpg\noffice_3/center/1577401148383350528.jpg\noffice_3/center/1577401054836328960.jpg\noffice_3/center/1577401073335727616.jpg\noffice_3/center/1577401169532553984.jpg\noffice_3/center/1577400883834739968.jpg\noffice_3/center/1577401130683650816.jpg\noffice_3/center/1577401015437874176.jpg\noffice_3/center/1577401055635611648.jpg\noffice_3/center/1577400889084743168.jpg\noffice_3/center/1577400961390328064.jpg\noffice_3/center/1577401156183104000.jpg\noffice_3/center/1577400931087685632.jpg\noffice_3/center/1577401071035647744.jpg\noffice_3/center/1577400976591247616.jpg\noffice_3/center/1577400964790969600.jpg\noffice_3/center/1577400891835181312.jpg\noffice_3/center/1577400868735991296.jpg\noffice_3/center/1577401106934624256.jpg\noffice_3/center/1577401022787386624.jpg\noffice_3/center/1577400859128038144.jpg\noffice_3/center/1577400907684231168.jpg\noffice_3/center/1577401036436722432.jpg\noffice_3/center/1577400877238528000.jpg\noffice_3/center/1577401044386268160.jpg\noffice_3/center/1577401088835028224.jpg\noffice_3/center/1577400915436313600.jpg\noffice_3/center/1577401171082346752.jpg\noffice_3/center/1577400864832823808.jpg\noffice_3/center/1577401058035920640.jpg\noffice_3/center/1577401110534689792.jpg\noffice_3/center/1577400848818465536.jpg\noffice_3/center/1577401143283306496.jpg\noffice_3/center/1577400891434849536.jpg\noffice_3/center/1577400942488118016.jpg\noffice_3/center/1577400865883785216.jpg\noffice_3/center/1577401129083862272.jpg\noffice_3/center/1577400951489659904.jpg\noffice_3/center/1577401027637241088.jpg\noffice_3/center/1577400894584857600.jpg\noffice_3/center/1577400939888163328.jpg\noffice_3/center/1577401053435933952.jpg\noffice_3/center/1577401151933228544.jpg\noffice_3/center/1577401172232232448.jpg\noffice_3/center/1577401067885612544.jpg\noffice_3/center/1577400903484396800.jpg\noffice_3/center/1577400891985315840.jpg\noffice_3/center/1577401133533454592.jpg\noffice_3/center/1577400872738246656.jpg\noffice_3/center/1577401085085120768.jpg\noffice_3/center/1577401014438771712.jpg\noffice_3/center/1577400958490121216.jpg\noffice_3/center/1577401034336724736.jpg\noffice_3/center/1577401183532158208.jpg\noffice_3/center/1577401120634258688.jpg\noffice_3/center/1577400846765478400.jpg\noffice_3/center/1577401048686095360.jpg\noffice_3/center/1577401106134186752.jpg\noffice_3/center/1577401039486920448.jpg\noffice_3/center/1577401093034894336.jpg\noffice_3/center/1577401145033216512.jpg\noffice_3/center/1577401028737082368.jpg\noffice_3/center/1577401174482594048.jpg\noffice_3/center/1577400943438291968.jpg\noffice_3/center/1577401028537124608.jpg\noffice_3/center/1577400862781373184.jpg\noffice_3/center/1577401133284011776.jpg\noffice_3/center/1577401171732746496.jpg\noffice_3/center/1577401102834563328.jpg\noffice_3/center/1577401073135924224.jpg\noffice_3/center/1577401020487360256.jpg\noffice_3/center/1577401182931761408.jpg\noffice_3/center/1577401162632984832.jpg\noffice_3/center/1577401109734802176.jpg\noffice_3/center/1577401179481799424.jpg\noffice_3/center/1577401173481912576.jpg\noffice_3/center/1577400959840275456.jpg\noffice_3/center/1577400897284832000.jpg\noffice_3/center/1577401079385458176.jpg\noffice_3/center/1577401137633278720.jpg\noffice_3/center/1577400870237420288.jpg\noffice_3/center/1577401170732408832.jpg\noffice_3/center/1577401112084432128.jpg\noffice_3/center/1577401084785170688.jpg\noffice_3/center/1577401065985873664.jpg\noffice_3/center/1577400978540822784.jpg\noffice_3/center/1577401041136364288.jpg\noffice_3/center/1577401023687259136.jpg\noffice_3/center/1577400910934636288.jpg\noffice_3/center/1577400942387814656.jpg\noffice_3/center/1577400904834252032.jpg\noffice_3/center/1577401094235012864.jpg\noffice_3/center/1577400980690366464.jpg\noffice_3/center/1577401174682471168.jpg\noffice_3/center/1577400878286300416.jpg\noffice_3/center/1577401033286754560.jpg\noffice_3/center/1577401028487142144.jpg\noffice_3/center/1577400868035334912.jpg\noffice_3/center/1577401024937250560.jpg\noffice_3/center/1577400965640924928.jpg\noffice_3/center/1577401103784718592.jpg\noffice_3/center/1577400903984418304.jpg\noffice_3/center/1577400934087688960.jpg\noffice_3/center/1577401148183438848.jpg\noffice_3/center/1577401158532823040.jpg\noffice_3/center/1577401147533434624.jpg\noffice_3/center/1577401025037154560.jpg\noffice_3/center/1577400883484224000.jpg\noffice_3/center/1577401045836172544.jpg\noffice_3/center/1577401166732154624.jpg\noffice_3/center/1577400976491218432.jpg\noffice_3/center/1577400888584671744.jpg\noffice_3/center/1577401075135787008.jpg\noffice_3/center/1577401030336801024.jpg\noffice_3/center/1577401087734767104.jpg\noffice_3/center/1577401099134418176.jpg\noffice_3/center/1577401154583317760.jpg\noffice_3/center/1577401045085822464.jpg\noffice_3/center/1577401124234008320.jpg\noffice_3/center/1577400902034356480.jpg\noffice_3/center/1577401148283426048.jpg\noffice_3/center/1577401072135675904.jpg\noffice_3/center/1577401169482591232.jpg\noffice_3/center/1577401143033530880.jpg\noffice_3/center/1577400871537828352.jpg\noffice_3/center/1577400884284636160.jpg\noffice_3/center/1577401102134492160.jpg\noffice_3/center/1577401093985038080.jpg\noffice_3/center/1577400927488149760.jpg\noffice_3/center/1577401077335391232.jpg\noffice_3/center/1577401135732561920.jpg\noffice_3/center/1577401159632957952.jpg\noffice_3/center/1577401116984231936.jpg\noffice_3/center/1577400903434365440.jpg\noffice_3/center/1577401184531827456.jpg\noffice_3/center/1577400979441078784.jpg\noffice_3/center/1577401019987610112.jpg\noffice_3/center/1577400892185230336.jpg\noffice_3/center/1577400874638906880.jpg\noffice_3/center/1577401039736350720.jpg\noffice_3/center/1577400908584425216.jpg\noffice_3/center/1577401018987785472.jpg\noffice_3/center/1577401045336065536.jpg\noffice_3/center/1577400878837308928.jpg\noffice_3/center/1577400870037249024.jpg\noffice_3/center/1577401172382010624.jpg\noffice_3/center/1577400973091781120.jpg\noffice_3/center/1577401135582538240.jpg\noffice_3/center/1577401121434183424.jpg\noffice_3/center/1577401125633920256.jpg\noffice_3/center/1577400947188707328.jpg\noffice_3/center/1577401069485442304.jpg\noffice_3/center/1577400912235619072.jpg\noffice_3/center/1577401083035104000.jpg\noffice_3/center/1577401078285220096.jpg\noffice_3/center/1577400961890672896.jpg\noffice_3/center/1577401158883179264.jpg\noffice_3/center/1577401174732444160.jpg\noffice_3/center/1577401036286692864.jpg\noffice_3/center/1577401079285446400.jpg\noffice_3/center/1577400939187915520.jpg\noffice_3/center/1577401178032357120.jpg\noffice_3/center/1577401174282720768.jpg\noffice_3/center/1577401046735684096.jpg\noffice_3/center/1577401048186083840.jpg\noffice_3/center/1577400966690664192.jpg\noffice_3/center/1577401132483549440.jpg\noffice_3/center/1577400940737820160.jpg\noffice_3/center/1577401090334919680.jpg\noffice_3/center/1577401056485953280.jpg\noffice_3/center/1577400875638806016.jpg\noffice_3/center/1577400926887313920.jpg\noffice_3/center/1577400843963078912.jpg\noffice_3/center/1577400917386762496.jpg\noffice_3/center/1577401136883130368.jpg\noffice_3/center/1577401047785949184.jpg\noffice_3/center/1577401033036686848.jpg\noffice_3/center/1577401078035524608.jpg\noffice_3/center/1577401169782388992.jpg\noffice_3/center/1577400884384478976.jpg\noffice_3/center/1577401040436466432.jpg\noffice_3/center/1577401147483517184.jpg\noffice_3/center/1577400861179987200.jpg\noffice_3/center/1577400890335019264.jpg\noffice_3/center/1577401083835037440.jpg\noffice_3/center/1577401017937843968.jpg\noffice_3/center/1577401101784492032.jpg\noffice_3/center/1577401177632343808.jpg\noffice_3/center/1577401175532171008.jpg\noffice_3/center/1577400940437651968.jpg\noffice_3/center/1577401051535811840.jpg\noffice_3/center/1577401055185855744.jpg\noffice_3/center/1577400955940064256.jpg\noffice_3/center/1577400921686982144.jpg\noffice_3/center/1577400928837707264.jpg\noffice_3/center/1577401146133614336.jpg\noffice_3/center/1577401131833488384.jpg\noffice_3/center/1577401026387206144.jpg\noffice_3/center/1577401111535002112.jpg\noffice_3/center/1577400938937563648.jpg\noffice_3/center/1577401129783667456.jpg\noffice_3/center/1577400852122019840.jpg\noffice_3/center/1577401073935830528.jpg\noffice_3/center/1577400901084665344.jpg\noffice_3/center/1577400900834527232.jpg\noffice_3/center/1577401096684842240.jpg\noffice_3/center/1577401167233056512.jpg\noffice_3/center/1577400972691781632.jpg\noffice_3/center/1577400902234267392.jpg\noffice_3/center/1577400863331448064.jpg\noffice_3/center/1577400920387241728.jpg\noffice_3/center/1577401011888583424.jpg\noffice_3/center/1577400855424349696.jpg\noffice_3/center/1577401025237328384.jpg\noffice_3/center/1577400848167919872.jpg\noffice_3/center/1577401026937654272.jpg\noffice_3/center/1577400977191442432.jpg\noffice_3/center/1577401086935130112.jpg\noffice_3/center/1577401184181856512.jpg\noffice_3/center/1577400932987844608.jpg\noffice_3/center/1577400855825569792.jpg\noffice_3/center/1577400954939726080.jpg\noffice_3/center/1577401103684729856.jpg\noffice_3/center/1577401122784331264.jpg\noffice_3/center/1577400945288668160.jpg\noffice_3/center/1577400872039472384.jpg\noffice_3/center/1577400874488493056.jpg\noffice_3/center/1577401130133680128.jpg\noffice_3/center/1577400899934577408.jpg\noffice_3/center/1577400868486013184.jpg\noffice_3/center/1577401063936244992.jpg\noffice_3/center/1577401022887527680.jpg\noffice_3/center/1577400953790101760.jpg\noffice_3/center/1577401120184299264.jpg\noffice_3/center/1577400857377355264.jpg\noffice_3/center/1577401089534949376.jpg\noffice_3/center/1577401142332879616.jpg\noffice_3/center/1577401138283530752.jpg\noffice_3/center/1577400922987306496.jpg\noffice_3/center/1577401044736071168.jpg\noffice_3/center/1577401080585548288.jpg\noffice_3/center/1577400916486664704.jpg\noffice_3/center/1577401097385036032.jpg\noffice_3/center/1577401110684607744.jpg\noffice_3/center/1577401140933403648.jpg\noffice_3/center/1577401032886734080.jpg\noffice_3/center/1577400859778622976.jpg\noffice_3/center/1577401179782260480.jpg\noffice_3/center/1577400854424292352.jpg\noffice_3/center/1577401124733960704.jpg\noffice_3/center/1577401088685013504.jpg\noffice_3/center/1577401106234212096.jpg\noffice_3/center/1577401081335131904.jpg\noffice_3/center/1577401165832437248.jpg\noffice_3/center/1577400970491366400.jpg\noffice_3/center/1577401086334992128.jpg\noffice_3/center/1577400892235120896.jpg\noffice_3/center/1577401018937827072.jpg\noffice_3/center/1577400863281468928.jpg\noffice_3/center/1577401042236314112.jpg\noffice_3/center/1577400950389483008.jpg\noffice_3/center/1577401076935372288.jpg\noffice_3/center/1577400940187894784.jpg\noffice_3/center/1577401018587671296.jpg\noffice_3/center/1577401156432627456.jpg\noffice_3/center/1577400950239350784.jpg\noffice_3/center/1577400962340626944.jpg\noffice_3/center/1577400961990745344.jpg\noffice_3/center/1577401028837073664.jpg\noffice_3/center/1577401134433153536.jpg\noffice_3/center/1577400852973135616.jpg\noffice_3/center/1577400886934846976.jpg\noffice_3/center/1577400883884871168.jpg\noffice_3/center/1577400941188231936.jpg\noffice_3/center/1577401128683772672.jpg\noffice_3/center/1577400956289994240.jpg\noffice_3/center/1577400955890007296.jpg\noffice_3/center/1577400966590729728.jpg\noffice_3/center/1577401089834878464.jpg\noffice_3/center/1577400957589973504.jpg\noffice_3/center/1577401053385918208.jpg\noffice_3/center/1577400960440687104.jpg\noffice_3/center/1577400972541554688.jpg\noffice_3/center/1577401172182386944.jpg\noffice_3/center/1577401085385253888.jpg\noffice_3/center/1577401181332009984.jpg\noffice_3/center/1577401041436482304.jpg\noffice_3/center/1577400928937710080.jpg\noffice_3/center/1577400851121257728.jpg\noffice_3/center/1577401155182535936.jpg\noffice_3/center/1577400853373452800.jpg\noffice_3/center/1577400876687752448.jpg\noffice_3/center/1577401163582941952.jpg\noffice_3/center/1577401047136165632.jpg\noffice_3/center/1577400937387463168.jpg\noffice_3/center/1577400845263491584.jpg\noffice_3/center/1577400915186148864.jpg\noffice_3/center/1577401105234619136.jpg\noffice_3/center/1577401152783134720.jpg\noffice_3/center/1577400971941685248.jpg\noffice_3/center/1577401183081815552.jpg\noffice_3/center/1577401078785521920.jpg\noffice_3/center/1577400928187097344.jpg\noffice_3/center/1577400846865466880.jpg\noffice_3/center/1577401158082997248.jpg\noffice_3/center/1577401140983388672.jpg\noffice_3/center/1577401113984762368.jpg\noffice_3/center/1577401168332619008.jpg\noffice_3/center/1577401085785351168.jpg\noffice_3/center/1577400902184293376.jpg\noffice_3/center/1577401110084948992.jpg\noffice_3/center/1577400907934393344.jpg\noffice_3/center/1577400976841334272.jpg\noffice_3/center/1577401015487904256.jpg\noffice_3/center/1577401167832128256.jpg\noffice_3/center/1577401180382312448.jpg\noffice_3/center/1577400933687321344.jpg\noffice_3/center/1577400899334481920.jpg\noffice_3/center/1577400977541015808.jpg\noffice_3/center/1577400902484247296.jpg\noffice_3/center/1577400884984403712.jpg\noffice_3/center/1577401120134299136.jpg\noffice_3/center/1577400912435664640.jpg\noffice_3/center/1577401131883515136.jpg\noffice_3/center/1577401113084624128.jpg\noffice_3/center/1577400966241413632.jpg\noffice_3/center/1577400942788598528.jpg\noffice_3/center/1577400879337536000.jpg\noffice_3/center/1577401062085999616.jpg\noffice_3/center/1577400975941550848.jpg\noffice_3/center/1577400874088840704.jpg\noffice_3/center/1577400906684656384.jpg\noffice_3/center/1577400924087592704.jpg\noffice_3/center/1577401124633961472.jpg\noffice_3/center/1577401119434160640.jpg\noffice_3/center/1577400963540298240.jpg\noffice_3/center/1577400956739713536.jpg\noffice_3/center/1577401176982100736.jpg\noffice_3/center/1577400981489846784.jpg\noffice_3/center/1577400955189797376.jpg\noffice_3/center/1577401117434537984.jpg\noffice_3/center/1577401158482837248.jpg\noffice_3/center/1577401090084898816.jpg\noffice_3/center/1577401165332910336.jpg\noffice_3/center/1577400866484207360.jpg\noffice_3/center/1577401075085842432.jpg\noffice_3/center/1577400931637363456.jpg\noffice_3/center/1577401120984423168.jpg\noffice_3/center/1577401071285699840.jpg\noffice_3/center/1577400883684410880.jpg\noffice_3/center/1577401164932327936.jpg\noffice_3/center/1577401127733891584.jpg\noffice_3/center/1577401160083042048.jpg\noffice_3/center/1577401053685948416.jpg\noffice_3/center/1577401135983659264.jpg\noffice_3/center/1577401069635522816.jpg\noffice_3/center/1577400909984663296.jpg\noffice_3/center/1577400935787665920.jpg\noffice_3/center/1577400855775479296.jpg\noffice_3/center/1577401143083471104.jpg\noffice_3/center/1577400873039424256.jpg\noffice_3/center/1577401071135646464.jpg\noffice_3/center/1577401098585153024.jpg\noffice_3/center/1577401071335732480.jpg\noffice_3/center/1577401168082254848.jpg\noffice_3/center/1577401129583678464.jpg\noffice_3/center/1577401156982898176.jpg\noffice_3/center/1577401062286084864.jpg\noffice_3/center/1577400858177178880.jpg\noffice_3/center/1577400859728455424.jpg\noffice_3/center/1577401051685915648.jpg\noffice_3/center/1577400854974669568.jpg\noffice_3/center/1577401136582667264.jpg\noffice_3/center/1577401179631897600.jpg\noffice_3/center/1577401132683507456.jpg\noffice_3/center/1577400895684787712.jpg\noffice_3/center/1577401146683136256.jpg\noffice_3/center/1577401039886292480.jpg\noffice_3/center/1577400927237651456.jpg\noffice_3/center/1577400914786375424.jpg\noffice_3/center/1577400971991597056.jpg\noffice_3/center/1577401175882289152.jpg\noffice_3/center/1577400930237431296.jpg\noffice_3/center/1577400934887961600.jpg\noffice_3/center/1577401079535478016.jpg\noffice_3/center/1577400927388082944.jpg\noffice_3/center/1577401162682867712.jpg\noffice_3/center/1577400862881477632.jpg\noffice_3/center/1577401099234526720.jpg\noffice_3/center/1577401100484794880.jpg\noffice_3/center/1577401082485020160.jpg\noffice_3/center/1577400937587631616.jpg\noffice_3/center/1577400919986988544.jpg\noffice_3/center/1577401068935803392.jpg\noffice_3/center/1577400867234929920.jpg\noffice_3/center/1577400900484596992.jpg\noffice_3/center/1577401121984142336.jpg\noffice_3/center/1577400880635866624.jpg\noffice_3/center/1577401052636076544.jpg\noffice_3/center/1577401027737252352.jpg\noffice_3/center/1577400918186780160.jpg\noffice_3/center/1577400948138985728.jpg\noffice_3/center/1577400893685092352.jpg\noffice_3/center/1577400982040032768.jpg\noffice_3/center/1577401014088193536.jpg\noffice_3/center/1577400904634294528.jpg\noffice_3/center/1577401099034464768.jpg\noffice_3/center/1577400976641272320.jpg\noffice_3/center/1577401049786081792.jpg\noffice_3/center/1577400973741647104.jpg\noffice_3/center/1577400846365740800.jpg\noffice_3/center/1577401145533347584.jpg\noffice_3/center/1577401026437249280.jpg\noffice_3/center/1577401081385118464.jpg\noffice_3/center/1577400904984283136.jpg\noffice_3/center/1577401068235834624.jpg\noffice_3/center/1577400853273353472.jpg\noffice_3/center/1577400849619396864.jpg\noffice_3/center/1577400941538162432.jpg\noffice_3/center/1577400916686667776.jpg\noffice_3/center/1577400850471145216.jpg\noffice_3/center/1577400887134756864.jpg\noffice_3/center/1577401048159749888.jpg\noffice_3/center/1577401179431797248.jpg\noffice_3/center/1577400871437920512.jpg\noffice_3/center/1577401037736538880.jpg\noffice_3/center/1577401148133391872.jpg\noffice_3/center/1577400879936518656.jpg\noffice_3/center/1577401114333774848.jpg\noffice_3/center/1577401084885158912.jpg\noffice_3/center/1577400935887732992.jpg\noffice_3/center/1577400968990979840.jpg\noffice_3/center/1577401155983512320.jpg\noffice_3/center/1577401077785918976.jpg\noffice_3/center/1577401053285925888.jpg\noffice_3/center/1577401059585830656.jpg\noffice_3/center/1577400909684803328.jpg\noffice_3/center/1577401166782039808.jpg\noffice_3/center/1577400887034832384.jpg\noffice_3/center/1577401051035841792.jpg\noffice_3/center/1577400930337526272.jpg\noffice_3/center/1577401113834573056.jpg\noffice_3/center/1577401067136320512.jpg\noffice_3/center/1577401114584231936.jpg\noffice_3/center/1577400922837455872.jpg\noffice_3/center/1577401170532501760.jpg\noffice_3/center/1577401113334009088.jpg\noffice_3/center/1577400949939134208.jpg\noffice_3/center/1577401069735559424.jpg\noffice_3/center/1577401031886675712.jpg\noffice_3/center/1577401159233108992.jpg\noffice_3/center/1577401141984018176.jpg\noffice_3/center/1577401105634609920.jpg\noffice_3/center/1577400867785257728.jpg\noffice_3/center/1577400910834665472.jpg\noffice_3/center/1577401082285811712.jpg\noffice_3/center/1577400874538589184.jpg\noffice_3/center/1577401138433519872.jpg\noffice_3/center/1577401022037365248.jpg\noffice_3/center/1577400979590960128.jpg\noffice_3/center/1577400846265756672.jpg\noffice_3/center/1577401043186283520.jpg\noffice_3/center/1577400952339374336.jpg\noffice_3/center/1577401042986263808.jpg\noffice_3/center/1577400965741067008.jpg\noffice_3/center/1577401063285781248.jpg\noffice_3/center/1577401161082941952.jpg\noffice_3/center/1577400914135969280.jpg\noffice_3/center/1577400951639713536.jpg\noffice_3/center/1577400912385656832.jpg\noffice_3/center/1577400856975517440.jpg\noffice_3/center/1577401077935744256.jpg\noffice_3/center/1577400958240113408.jpg\noffice_3/center/1577401112134352896.jpg\noffice_3/center/1577401139883611904.jpg\noffice_3/center/1577401030386812928.jpg\noffice_3/center/1577401089235125248.jpg\noffice_3/center/1577400862981535232.jpg\noffice_3/center/1577400890934686720.jpg\noffice_3/center/1577401048636110592.jpg\noffice_3/center/1577400902984475136.jpg\noffice_3/center/1577401138833399552.jpg\noffice_3/center/1577400960140655872.jpg\noffice_3/center/1577401038835703808.jpg\noffice_3/center/1577400919237473024.jpg\noffice_3/center/1577400865983893504.jpg\noffice_3/center/1577400902934475776.jpg\noffice_3/center/1577401070035876096.jpg\noffice_3/center/1577401029237098496.jpg\noffice_3/center/1577400877138310656.jpg\noffice_3/center/1577400972191386880.jpg\noffice_3/center/1577400915886670592.jpg\noffice_3/center/1577401034086808832.jpg\noffice_3/center/1577400858628237312.jpg\noffice_3/center/1577401060886260480.jpg\noffice_3/center/1577400922487654656.jpg\noffice_3/center/1577400977241449984.jpg\noffice_3/center/1577400856575621888.jpg\noffice_3/center/1577401046785698048.jpg\noffice_3/center/1577401075485507584.jpg\noffice_3/center/1577400937237672192.jpg\noffice_3/center/1577400875488937216.jpg\noffice_3/center/1577400869436448512.jpg\noffice_3/center/1577401153532842752.jpg\noffice_3/center/1577400882484612352.jpg\noffice_3/center/1577401080085522944.jpg\noffice_3/center/1577400891634945792.jpg\noffice_3/center/1577400916186791680.jpg\noffice_3/center/1577400962940747264.jpg\noffice_3/center/1577401015037683968.jpg\noffice_3/center/1577401050535876352.jpg\noffice_3/center/1577400981740018432.jpg\noffice_3/center/1577400864432551424.jpg\noffice_3/center/1577400978890856960.jpg\noffice_3/center/1577401106334326272.jpg\noffice_3/center/1577400969241302528.jpg\noffice_3/center/1577401089485011200.jpg\noffice_3/center/1577400901884429056.jpg\noffice_3/center/1577401017837954816.jpg\noffice_3/center/1577401082235858176.jpg\noffice_3/center/1577401017737995520.jpg\noffice_3/center/1577400904134321152.jpg\noffice_3/center/1577400851371793408.jpg\noffice_3/center/1577400863782114304.jpg\noffice_3/center/1577401017437846784.jpg\noffice_3/center/1577400927787439872.jpg\noffice_3/center/1577401115134641152.jpg\noffice_3/center/1577401042786190848.jpg\noffice_3/center/1577401098984536832.jpg\noffice_3/center/1577401174382636800.jpg\noffice_3/center/1577401176882024960.jpg\noffice_3/center/1577400941788001792.jpg\noffice_3/center/1577401105834345984.jpg\noffice_3/center/1577400847215891968.jpg\noffice_3/center/1577400863982238720.jpg\noffice_3/center/1577401014937714176.jpg\noffice_3/center/1577401102434432512.jpg\noffice_3/center/1577401063135860480.jpg\noffice_3/center/1577400978141367296.jpg\noffice_3/center/1577401044236279296.jpg\noffice_3/center/1577401070485933056.jpg\noffice_3/center/1577400917636962816.jpg\noffice_3/center/1577400944788491776.jpg\noffice_3/center/1577401088935065856.jpg\noffice_3/center/1577401134033404928.jpg\noffice_3/center/1577400865533530624.jpg\noffice_3/center/1577401049135711232.jpg\noffice_3/center/1577400902784436480.jpg\noffice_3/center/1577401133933299200.jpg\noffice_3/center/1577401112284329216.jpg\noffice_3/center/1577400904184285440.jpg\noffice_3/center/1577401011638677760.jpg\noffice_3/center/1577401059836129024.jpg\noffice_3/center/1577401169232630528.jpg\noffice_3/center/1577400965240363264.jpg\noffice_3/center/1577401092234840832.jpg\noffice_3/center/1577401073285780992.jpg\noffice_3/center/1577401118534288896.jpg\noffice_3/center/1577401085435240448.jpg\noffice_3/center/1577400866934633472.jpg\noffice_3/center/1577401057885999872.jpg\noffice_3/center/1577401102334450944.jpg\noffice_3/center/1577401125434332928.jpg\noffice_3/center/1577401158582848256.jpg\noffice_3/center/1577400939838178304.jpg\noffice_3/center/1577400963740505344.jpg\noffice_3/center/1577400936437634304.jpg\noffice_3/center/1577401048885907456.jpg\noffice_3/center/1577401139483627520.jpg\noffice_3/center/1577401168232455424.jpg\noffice_3/center/1577400954989771776.jpg\noffice_3/center/1577401153932708352.jpg\noffice_3/center/1577400977791137792.jpg\noffice_3/center/1577401055986204160.jpg\noffice_3/center/1577401096434775296.jpg\noffice_3/center/1577400892984804608.jpg\noffice_3/center/1577401176932031744.jpg\noffice_3/center/1577401133783142144.jpg\noffice_3/center/1577401010688368640.jpg\noffice_3/center/1577401014738052864.jpg\noffice_3/center/1577400916336728320.jpg\noffice_3/center/1577401092284871680.jpg\noffice_3/center/1577401022837448192.jpg\noffice_3/center/1577401036586601984.jpg\noffice_3/center/1577400883084849920.jpg\noffice_3/center/1577401142933568256.jpg\noffice_3/center/1577401024837276672.jpg\noffice_3/center/1577400934037638400.jpg\noffice_3/center/1577401163132758016.jpg\noffice_3/center/1577401077835857664.jpg\noffice_3/center/1577401022087369728.jpg\noffice_3/center/1577400974641608704.jpg\noffice_3/center/1577401131033843456.jpg\noffice_3/center/1577400852172179712.jpg\noffice_3/center/1577400902334213888.jpg\noffice_3/center/1577401072435728640.jpg\noffice_3/center/1577400893134902272.jpg\noffice_3/center/1577401141183244544.jpg\noffice_3/center/1577400949989158400.jpg\noffice_3/center/1577400898334520576.jpg\noffice_3/center/1577401177532425216.jpg\noffice_3/center/1577401083535430656.jpg\noffice_3/center/1577400887934745344.jpg\noffice_3/center/1577400976241456128.jpg\noffice_3/center/1577400911985463552.jpg\noffice_3/center/1577400877737975296.jpg\noffice_3/center/1577401067386215680.jpg\noffice_3/center/1577401070186043648.jpg\noffice_3/center/1577401077385484288.jpg\noffice_3/center/1577400974291526400.jpg\noffice_3/center/1577401086385011712.jpg\noffice_3/center/1577400928487461376.jpg\noffice_3/center/1577400904384232704.jpg\noffice_3/center/1577400917036814080.jpg\noffice_3/center/1577400910284654080.jpg\noffice_3/center/1577400901234748672.jpg\noffice_3/center/1577401068285866240.jpg\noffice_3/center/1577400878236441856.jpg\noffice_3/center/1577401141283195904.jpg\noffice_3/center/1577400969191238144.jpg\noffice_3/center/1577400977391299072.jpg\noffice_3/center/1577401103034421760.jpg\noffice_3/center/1577400936237717248.jpg\noffice_3/center/1577401030837016576.jpg\noffice_3/center/1577400864532550912.jpg\noffice_3/center/1577401109384522752.jpg\noffice_3/center/1577400979890552064.jpg\noffice_3/center/1577401039387062272.jpg\noffice_3/center/1577400844263394816.jpg\noffice_3/center/1577401071885914368.jpg\noffice_3/center/1577400914636434432.jpg\noffice_3/center/1577400977091527680.jpg\noffice_3/center/1577401052486135552.jpg\noffice_3/center/1577401081535090944.jpg\noffice_3/center/1577400939538302464.jpg\noffice_3/center/1577400898384531456.jpg\noffice_3/center/1577401122334184704.jpg\noffice_3/center/1577401056785771520.jpg\noffice_3/center/1577401123534144256.jpg\noffice_3/center/1577401041486481664.jpg\noffice_3/center/1577400906184172032.jpg\noffice_3/center/1577400880936587008.jpg\noffice_3/center/1577400961340361984.jpg\noffice_3/center/1577400896884601088.jpg\noffice_3/center/1577400926037470208.jpg\noffice_3/center/1577400864382569728.jpg\noffice_3/center/1577401163232894720.jpg\noffice_3/center/1577401126283923456.jpg\noffice_3/center/1577401016237984768.jpg\noffice_3/center/1577400918286662400.jpg\noffice_3/center/1577401176232667136.jpg\noffice_3/center/1577401036136620288.jpg\noffice_3/center/1577400885134493184.jpg\noffice_3/center/1577400968041140992.jpg\noffice_3/center/1577401101834476800.jpg\noffice_3/center/1577401032586745856.jpg\noffice_3/center/1577400959540208640.jpg\noffice_3/center/1577401146533331968.jpg\noffice_3/center/1577401054736175360.jpg\noffice_3/center/1577400901834431232.jpg\noffice_3/center/1577401146283549696.jpg\noffice_3/center/1577400932688032768.jpg\noffice_3/center/1577401058235989760.jpg\noffice_3/center/1577400853423463936.jpg\noffice_3/center/1577401099334690816.jpg\noffice_3/center/1577400979091303424.jpg\noffice_3/center/1577400938288189440.jpg\noffice_3/center/1577400919687034112.jpg\noffice_3/center/1577400844413312256.jpg\noffice_3/center/1577400861880551424.jpg\noffice_3/center/1577401152833117184.jpg\noffice_3/center/1577400950489517824.jpg\noffice_3/center/1577401140533533184.jpg\noffice_3/center/1577400917937108224.jpg\noffice_3/center/1577400884784398336.jpg\noffice_3/center/1577400966890663168.jpg\noffice_3/center/1577401128533440768.jpg\noffice_3/center/1577401059786128640.jpg\noffice_3/center/1577400877588261376.jpg\noffice_3/center/1577401015887825664.jpg\noffice_3/center/1577400914286231552.jpg\noffice_3/center/1577400895034874880.jpg\noffice_3/center/1577401053586002176.jpg\noffice_3/center/1577400980440328704.jpg\noffice_3/center/1577400953189726208.jpg\noffice_3/center/1577400873339274752.jpg\noffice_3/center/1577400859028278016.jpg\noffice_3/center/1577400932638007808.jpg\noffice_3/center/1577401061785887488.jpg\noffice_3/center/1577400873239396608.jpg\noffice_3/center/1577400928637587968.jpg\noffice_3/center/1577401056835793408.jpg\noffice_3/center/1577401121534185216.jpg\noffice_3/center/1577401111884701184.jpg\noffice_3/center/1577400955389700352.jpg\noffice_3/center/1577400944188089600.jpg\noffice_3/center/1577400867835188480.jpg\noffice_3/center/1577400921937071360.jpg\noffice_3/center/1577401129383721984.jpg\noffice_3/center/1577401122734320896.jpg\noffice_3/center/1577401029686971904.jpg\noffice_3/center/1577401136033802752.jpg\noffice_3/center/1577400972141491712.jpg\noffice_3/center/1577400892035350528.jpg\noffice_3/center/1577400944588429568.jpg\noffice_3/center/1577400845413688320.jpg\noffice_3/center/1577401018687799808.jpg\noffice_3/center/1577401179332035584.jpg\noffice_3/center/1577400924887577856.jpg\noffice_3/center/1577400933037821440.jpg\noffice_3/center/1577400974991695872.jpg\noffice_3/center/1577401176732118016.jpg\noffice_3/center/1577400938037966336.jpg\noffice_3/center/1577400883584272128.jpg\noffice_3/center/1577400892135286784.jpg\noffice_3/center/1577401084985132032.jpg\noffice_3/center/1577401046386068992.jpg\noffice_3/center/1577401159333029120.jpg\noffice_3/center/1577400892884729856.jpg\noffice_3/center/1577401033986830848.jpg\noffice_3/center/1577400860379373824.jpg\noffice_3/center/1577401016837832192.jpg\noffice_3/center/1577401182482206976.jpg\noffice_3/center/1577400921287301632.jpg\noffice_3/center/1577401091834597632.jpg\noffice_3/center/1577401181431995392.jpg\noffice_3/center/1577400978590768640.jpg\noffice_3/center/1577401073385721856.jpg\noffice_3/center/1577400953089749248.jpg\noffice_3/center/1577401058936110848.jpg\noffice_3/center/1577401117685043712.jpg\noffice_3/center/1577400884234740480.jpg\noffice_3/center/1577400938388117248.jpg\noffice_3/center/1577400858878507264.jpg\noffice_3/center/1577400881685528832.jpg\noffice_3/center/1577400849519123200.jpg\noffice_3/center/1577401116884227072.jpg\noffice_3/center/1577400890384978432.jpg\noffice_3/center/1577401101384641280.jpg\noffice_3/center/1577400917887150336.jpg\noffice_3/center/1577401153832766976.jpg\noffice_3/center/1577401096584856832.jpg\noffice_3/center/1577400955589618944.jpg\noffice_3/center/1577401025287384320.jpg\noffice_3/center/1577401062436045824.jpg\noffice_3/center/1577401013138156032.jpg\noffice_3/center/1577400937437420800.jpg\noffice_3/center/1577400865083297792.jpg\noffice_3/center/1577400956789643520.jpg\noffice_3/center/1577401114234044160.jpg\noffice_3/center/1577401111484973568.jpg\noffice_3/center/1577400899684373504.jpg\noffice_3/center/1577401094834814976.jpg\noffice_3/center/1577400908434684160.jpg\noffice_3/center/1577401043286275584.jpg\noffice_3/center/1577401077535783168.jpg\noffice_3/center/1577400866984764928.jpg\noffice_3/center/1577401144933387008.jpg\noffice_3/center/1577401127633907968.jpg\noffice_3/center/1577401126584175360.jpg\noffice_3/center/1577401140483532288.jpg\noffice_3/center/1577401023237413120.jpg\noffice_3/center/1577401112884895232.jpg\noffice_3/center/1577400871088066816.jpg\noffice_3/center/1577401014837845504.jpg\noffice_3/center/1577401045686179328.jpg\noffice_3/center/1577400861029786112.jpg\noffice_3/center/1577400953389445632.jpg\noffice_3/center/1577400909384747264.jpg\noffice_3/center/1577401108084373760.jpg\noffice_3/center/1577401044486243840.jpg\noffice_3/center/1577400923687287808.jpg\noffice_3/center/1577401144083198464.jpg\noffice_3/center/1577400940137990656.jpg\noffice_3/center/1577401162433208064.jpg\noffice_3/center/1577401111734956800.jpg\noffice_3/center/1577401023537224960.jpg\noffice_3/center/1577401059335493888.jpg\noffice_3/center/1577400867485216512.jpg\noffice_3/center/1577401087684732160.jpg\noffice_3/center/1577400959640188928.jpg\noffice_3/center/1577401064535873280.jpg\noffice_3/center/1577400868885985536.jpg\noffice_3/center/1577401169082553344.jpg\noffice_3/center/1577400861830500096.jpg\noffice_3/center/1577401028287135488.jpg\noffice_3/center/1577401153332877312.jpg\noffice_3/center/1577400945688497664.jpg\noffice_3/center/1577401098784916992.jpg\noffice_3/center/1577400857626945024.jpg\noffice_3/center/1577400905334466048.jpg\noffice_3/center/1577401077885806336.jpg\noffice_3/center/1577400885484869120.jpg\noffice_3/center/1577401064485876224.jpg\noffice_3/center/1577401144733576704.jpg\noffice_3/center/1577401091934667520.jpg\noffice_3/center/1577400969291348992.jpg\noffice_3/center/1577401131583636480.jpg\noffice_3/center/1577401041086371584.jpg\noffice_3/center/1577401053235925760.jpg\noffice_3/center/1577401074435572224.jpg\noffice_3/center/1577401161983044096.jpg\noffice_3/center/1577400963340306176.jpg\noffice_3/center/1577400956040118272.jpg\noffice_3/center/1577400920187103488.jpg\noffice_3/center/1577400880036476416.jpg\noffice_3/center/1577400959390278144.jpg\noffice_3/center/1577400932787909120.jpg\noffice_3/center/1577400919387417088.jpg\noffice_3/center/1577401017987790848.jpg\noffice_3/center/1577401126484215552.jpg\noffice_3/center/1577401053835896832.jpg\noffice_3/center/1577401021637512960.jpg\noffice_3/center/1577401134782975488.jpg\noffice_3/center/1577401152633123584.jpg\noffice_3/center/1577400933887481344.jpg\noffice_3/center/1577400970291114240.jpg\noffice_3/center/1577401063686014464.jpg\noffice_3/center/1577401029736976640.jpg\noffice_3/center/1577401161732950272.jpg\noffice_3/center/1577401133983368960.jpg\noffice_3/center/1577400921736925696.jpg\noffice_3/center/1577401172932908288.jpg\noffice_3/center/1577401075935963904.jpg\noffice_3/center/1577401113934736896.jpg\noffice_3/center/1577401057286124032.jpg\noffice_3/center/1577401097635043584.jpg\noffice_3/center/1577400885284695552.jpg\noffice_3/center/1577400953439497472.jpg\noffice_3/center/1577400918486541312.jpg\noffice_3/center/1577400864932992512.jpg\noffice_3/center/1577401096734784000.jpg\noffice_3/center/1577400867285069312.jpg\noffice_3/center/1577401096984542208.jpg\noffice_3/center/1577401019587714816.jpg\noffice_3/center/1577400936337656832.jpg\noffice_3/center/1577401131233768704.jpg\noffice_3/center/1577400926787393536.jpg\noffice_3/center/1577401074285611776.jpg\noffice_3/center/1577400923837320960.jpg\noffice_3/center/1577400950039194624.jpg\noffice_3/center/1577401099784908544.jpg\noffice_3/center/1577400947288725504.jpg\noffice_3/center/1577400958190140928.jpg\noffice_3/center/1577400912635678720.jpg\noffice_3/center/1577400879786529280.jpg\noffice_3/center/1577401095134811392.jpg\noffice_3/center/1577401062636029952.jpg\noffice_3/center/1577401180482298624.jpg\noffice_3/center/1577401132583509504.jpg\noffice_3/center/1577401182282439680.jpg\noffice_3/center/1577401074785834752.jpg\noffice_3/center/1577401084035053312.jpg\noffice_3/center/1577400943938023424.jpg\noffice_3/center/1577401145083177216.jpg\noffice_3/center/1577401073885840896.jpg\noffice_3/center/1577400968241082112.jpg\noffice_3/center/1577401164432991232.jpg\noffice_3/center/1577401065935788032.jpg\noffice_3/center/1577400921037223936.jpg\noffice_3/center/1577401169982408448.jpg\noffice_3/center/1577400930887632896.jpg\noffice_3/center/1577401078185304832.jpg\noffice_3/center/1577400903134417920.jpg\noffice_3/center/1577401113784469248.jpg\noffice_3/center/1577400939338127872.jpg\noffice_3/center/1577400879636861952.jpg\noffice_3/center/1577400845163436288.jpg\noffice_3/center/1577400888534746112.jpg\noffice_3/center/1577401109834921984.jpg\noffice_3/center/1577401155032813056.jpg\noffice_3/center/1577400978940987648.jpg\noffice_3/center/1577401063035876608.jpg\noffice_3/center/1577400901934413824.jpg\noffice_3/center/1577401101284671744.jpg\noffice_3/center/1577401149083197696.jpg\noffice_3/center/1577400874188496128.jpg\noffice_3/center/1577400856275914752.jpg\noffice_3/center/1577401021587578624.jpg\noffice_3/center/1577401147233404928.jpg\noffice_3/center/1577400934487947008.jpg\noffice_3/center/1577401158783052032.jpg\noffice_3/center/1577400925137385984.jpg\noffice_3/center/1577400911134579456.jpg\noffice_3/center/1577400859227806208.jpg\noffice_3/center/1577401094384860672.jpg\noffice_3/center/1577401045986309120.jpg\noffice_3/center/1577400872989318400.jpg\noffice_3/center/1577400976091512320.jpg\noffice_3/center/1577401151583198720.jpg\noffice_3/center/1577400953689989888.jpg\noffice_3/center/1577400918536565760.jpg\noffice_3/center/1577401022587257344.jpg\noffice_3/center/1577400971741817600.jpg\noffice_3/center/1577401096834689536.jpg\noffice_3/center/1577400972441414144.jpg\noffice_3/center/1577401023787246848.jpg\noffice_3/center/1577401152533099264.jpg\noffice_3/center/1577401143433276672.jpg\noffice_3/center/1577400940837920256.jpg\noffice_3/center/1577400922187439616.jpg\noffice_3/center/1577401033136738304.jpg\noffice_3/center/1577401121034409984.jpg\noffice_3/center/1577401138233470720.jpg\noffice_3/center/1577401033886791168.jpg\noffice_3/center/1577401044436263424.jpg\noffice_3/center/1577400977491112192.jpg\noffice_3/center/1577401063085856512.jpg\noffice_3/center/1577401070885709312.jpg\noffice_3/center/1577401046086299904.jpg\noffice_3/center/1577401159532981504.jpg\noffice_3/center/1577400853173298432.jpg\noffice_3/center/1577401093784843520.jpg\noffice_3/center/1577400847767101952.jpg\noffice_3/center/1577401112434458624.jpg\noffice_3/center/1577401011088324352.jpg\noffice_3/center/1577401112034520576.jpg\noffice_3/center/1577401083135351296.jpg\noffice_3/center/1577400971691791872.jpg\noffice_3/center/1577400876837766656.jpg\noffice_3/center/1577401095434680832.jpg\noffice_3/center/1577401131383704064.jpg\noffice_3/center/1577400852072022784.jpg\noffice_3/center/1577401155232440064.jpg\noffice_3/center/1577401153632783872.jpg\noffice_3/center/1577401037936830464.jpg\noffice_3/center/1577400889984888320.jpg\noffice_3/center/1577400887434474496.jpg\noffice_3/center/1577401021287786752.jpg\noffice_3/center/1577400844613328384.jpg\noffice_3/center/1577401055136017152.jpg\noffice_3/center/1577401123634142464.jpg\noffice_3/center/1577400963140635136.jpg\noffice_3/center/1577400912135604736.jpg\noffice_3/center/1577400911935314432.jpg\noffice_3/center/1577400888884667136.jpg\noffice_3/center/1577400906634744064.jpg\noffice_3/center/1577400926286984960.jpg\noffice_3/center/1577401163032656896.jpg\noffice_3/center/1577400944638459136.jpg\noffice_3/center/1577400956839593472.jpg\noffice_3/center/1577400873689084672.jpg\noffice_3/center/1577401058135903232.jpg\noffice_3/center/1577401038286687488.jpg\noffice_3/center/1577401012038447872.jpg\noffice_3/center/1577400893084905472.jpg\noffice_3/center/1577400952239279616.jpg\noffice_3/center/1577401083085242112.jpg\noffice_3/center/1577401107834888960.jpg\noffice_3/center/1577400930587610112.jpg\noffice_3/center/1577400937937916928.jpg\noffice_3/center/1577401171582589440.jpg\noffice_3/center/1577400889234619904.jpg\noffice_3/center/1577400954689573376.jpg\noffice_3/center/1577401155282417920.jpg\noffice_3/center/1577400978091414272.jpg\noffice_3/center/1577400854524349440.jpg\noffice_3/center/1577401067735799552.jpg\noffice_3/center/1577401165282804736.jpg\noffice_3/center/1577400902434213376.jpg\noffice_3/center/1577400915686550528.jpg\noffice_3/center/1577401059035837440.jpg\noffice_3/center/1577400870337503488.jpg\noffice_3/center/1577401062885944832.jpg\noffice_3/center/1577401058736523264.jpg\noffice_3/center/1577401122984262912.jpg\noffice_3/center/1577400923437169152.jpg\noffice_3/center/1577400926187048192.jpg\noffice_3/center/1577401084735222016.jpg\noffice_3/center/1577401180432312576.jpg\noffice_3/center/1577401069085856768.jpg\noffice_3/center/1577401151533137152.jpg\noffice_3/center/1577400912035510016.jpg\noffice_3/center/1577400975191823616.jpg\noffice_3/center/1577401030536873472.jpg\noffice_3/center/1577401025137146112.jpg\noffice_3/center/1577401088885088768.jpg\noffice_3/center/1577400981240245504.jpg\noffice_3/center/1577401135033807104.jpg\noffice_3/center/1577401078835556096.jpg\noffice_3/center/1577401146333484032.jpg\noffice_3/center/1577400915536466176.jpg\noffice_3/center/1577400935637482752.jpg\noffice_3/center/1577401014488713984.jpg\noffice_3/center/1577401140233511424.jpg\noffice_3/center/1577400894034784000.jpg\noffice_3/center/1577400851622083328.jpg\noffice_3/center/1577401044985744128.jpg\noffice_3/center/1577401047286327808.jpg\noffice_3/center/1577401136532732672.jpg\noffice_3/center/1577401134682848000.jpg\noffice_3/center/1577400935387336704.jpg\noffice_3/center/1577400918686690816.jpg\noffice_3/center/1577401134183493120.jpg\noffice_3/center/1577400951138938624.jpg\noffice_3/center/1577400928687598592.jpg\noffice_3/center/1577401158232928256.jpg\noffice_3/center/1577400955689733632.jpg\noffice_3/center/1577401051835877120.jpg\noffice_3/center/1577400856175960832.jpg\noffice_3/center/1577400934187775232.jpg\noffice_3/center/1577401098134274304.jpg\noffice_3/center/1577400922387623936.jpg\noffice_3/center/1577401177932357888.jpg\noffice_3/center/1577400877987091712.jpg\noffice_3/center/1577401181932404992.jpg\noffice_3/center/1577401065885722880.jpg\noffice_3/center/1577400937038020096.jpg\noffice_3/center/1577400892584657152.jpg\noffice_3/center/1577400886884814336.jpg\noffice_3/center/1577401144183303168.jpg\noffice_3/center/1577400980740383232.jpg\noffice_3/center/1577400919287510272.jpg\noffice_3/center/1577401127183635712.jpg\noffice_3/center/1577401059285507328.jpg\noffice_3/center/1577401040686521344.jpg\noffice_3/center/1577401158033010688.jpg\noffice_3/center/1577400851221404928.jpg\noffice_3/center/1577401179381892864.jpg\noffice_3/center/1577401125983236096.jpg\noffice_3/center/1577400897584636160.jpg\noffice_3/center/1577401078585301504.jpg\noffice_3/center/1577400887084811520.jpg\noffice_3/center/1577400899484334848.jpg\noffice_3/center/1577401111685040128.jpg\noffice_3/center/1577400947939320320.jpg\noffice_3/center/1577400907434266368.jpg\noffice_3/center/1577400882284766720.jpg\noffice_3/center/1577401083985044224.jpg\noffice_3/center/1577401059135620096.jpg\noffice_3/center/1577401177682331648.jpg\noffice_3/center/1577400911034609664.jpg\noffice_3/center/1577401174932449024.jpg\noffice_3/center/1577400872688068864.jpg\noffice_3/center/1577400882534622720.jpg\noffice_3/center/1577401170082381824.jpg\noffice_3/center/1577401130383459584.jpg\noffice_3/center/1577401055435469312.jpg\noffice_3/center/1577401090434824448.jpg\noffice_3/center/1577401136333479936.jpg\noffice_3/center/1577400948039135232.jpg\noffice_3/center/1577400978840790528.jpg\noffice_3/center/1577401171132358656.jpg\noffice_3/center/1577401142282973440.jpg\noffice_3/center/1577400938987597056.jpg\noffice_3/center/1577401134283472896.jpg\noffice_3/center/1577401060285820928.jpg\noffice_3/center/1577401035836915456.jpg\noffice_3/center/1577401181782299904.jpg\noffice_3/center/1577401088734993920.jpg\noffice_3/center/1577400861730429184.jpg\noffice_3/center/1577401022487283712.jpg\noffice_3/center/1577401160633013504.jpg\noffice_3/center/1577401106584569856.jpg\noffice_3/center/1577400974891593216.jpg\noffice_3/center/1577400895335052800.jpg\noffice_3/center/1577400857076061952.jpg\noffice_3/center/1577401072485798400.jpg\noffice_3/center/1577400972841966080.jpg\noffice_3/center/1577401061735836416.jpg\noffice_3/center/1577401076485191168.jpg\noffice_3/center/1577400897984473856.jpg\noffice_3/center/1577401178882688256.jpg\noffice_3/center/1577401032486675200.jpg\noffice_3/center/1577401165032283392.jpg\noffice_3/center/1577401081485127680.jpg\noffice_3/center/1577401134483037696.jpg\noffice_3/center/1577400912685669376.jpg\noffice_3/center/1577400870137348608.jpg\noffice_3/center/1577400870938031360.jpg\noffice_3/center/1577400848268169984.jpg\noffice_3/center/1577400955839935488.jpg\noffice_3/center/1577401136183951104.jpg\noffice_3/center/1577401045135875584.jpg\noffice_3/center/1577401151382988544.jpg\noffice_3/center/1577400946688825088.jpg\noffice_3/center/1577401100884550656.jpg\noffice_3/center/1577401054235634176.jpg\noffice_3/center/1577401163282925312.jpg\noffice_3/center/1577400917787198464.jpg\noffice_3/center/1577401120784310016.jpg\noffice_3/center/1577401177582403584.jpg\noffice_3/center/1577401022687309824.jpg\noffice_3/center/1577400882384710656.jpg\noffice_3/center/1577400875239292928.jpg\noffice_3/center/1577401051785905408.jpg\noffice_3/center/1577401150132571136.jpg\noffice_3/center/1577400896134569984.jpg\noffice_3/center/1577400936837895424.jpg\noffice_3/center/1577401172982918912.jpg\noffice_3/center/1577401049736064000.jpg\noffice_3/center/1577400960340639232.jpg\noffice_3/center/1577400939588284672.jpg\noffice_3/center/1577400847015633408.jpg\noffice_3/center/1577401170032402432.jpg\noffice_3/center/1577401164882391808.jpg\noffice_3/center/1577400934237811968.jpg\noffice_3/center/1577401161882992128.jpg\noffice_3/center/1577400919587157760.jpg\noffice_3/center/1577400884184822784.jpg\noffice_3/center/1577400974541612288.jpg\noffice_3/center/1577401071835915776.jpg\noffice_3/center/1577401164582834176.jpg\noffice_3/center/1577401021687450624.jpg\noffice_3/center/1577400850421036800.jpg\noffice_3/center/1577401167433248256.jpg\noffice_3/center/1577401063986259968.jpg\noffice_3/center/1577400927837305088.jpg\noffice_3/center/1577400938338176768.jpg\noffice_3/center/1577401092434776832.jpg\noffice_3/center/1577401031736763136.jpg\noffice_3/center/1577400909334704384.jpg\noffice_3/center/1577401103934530304.jpg\noffice_3/center/1577401115284516352.jpg\noffice_3/center/1577401128133546240.jpg\noffice_3/center/1577400961440338176.jpg\noffice_3/center/1577401117034220288.jpg\noffice_3/center/1577401078085435392.jpg\noffice_3/center/1577400870637783040.jpg\noffice_3/center/1577400903034448384.jpg\noffice_3/center/1577401120234315776.jpg\noffice_3/center/1577401111284577792.jpg\noffice_3/center/1577400974341509120.jpg\noffice_3/center/1577400917987057408.jpg\noffice_3/center/1577401170332332288.jpg\noffice_3/center/1577400886134394624.jpg\noffice_3/center/1577401164732493056.jpg\noffice_3/center/1577400897184839424.jpg\noffice_3/center/1577401128483329536.jpg\noffice_3/center/1577401091435017984.jpg\noffice_3/center/1577401028387145984.jpg\noffice_3/center/1577401077285286656.jpg\noffice_3/center/1577401141383152896.jpg\noffice_3/center/1577400977891240960.jpg\noffice_3/center/1577401140383525376.jpg\noffice_3/center/1577401149932582144.jpg\noffice_3/center/1577401045636161536.jpg\noffice_3/center/1577401176282649344.jpg\noffice_3/center/1577400935287432960.jpg\noffice_3/center/1577400894084711680.jpg\noffice_3/center/1577400907884342784.jpg\noffice_3/center/1577400970141236736.jpg\noffice_3/center/1577400890034899712.jpg\noffice_3/center/1577401035086796032.jpg\noffice_3/center/1577400918636609536.jpg\noffice_3/center/1577400881236648704.jpg\noffice_3/center/1577400977941287936.jpg\noffice_3/center/1577400953840124416.jpg\noffice_3/center/1577400920587289600.jpg\noffice_3/center/1577401158983239424.jpg\noffice_3/center/1577401089185133568.jpg\noffice_3/center/1577400858828447744.jpg\noffice_3/center/1577401145933619968.jpg\noffice_3/center/1577400944738441472.jpg\noffice_3/center/1577401043886372096.jpg\noffice_3/center/1577400956140121600.jpg\noffice_3/center/1577400847416427520.jpg\noffice_3/center/1577401101484556544.jpg\noffice_3/center/1577400958590199296.jpg\noffice_3/center/1577401071685865472.jpg\noffice_3/center/1577401097284850944.jpg\noffice_3/center/1577401097535057408.jpg\noffice_3/center/1577401138933506560.jpg\noffice_3/center/1577400922587637504.jpg\noffice_3/center/1577400926137148416.jpg\noffice_3/center/1577401136782866176.jpg\noffice_3/center/1577401048786016768.jpg\noffice_3/center/1577401129433683712.jpg\noffice_3/center/1577400909284643840.jpg\noffice_3/center/1577400940887981312.jpg\noffice_3/center/1577401060185920256.jpg\noffice_3/center/1577401138883458304.jpg\noffice_3/center/1577400946839015680.jpg\noffice_3/center/1577401083185453312.jpg\noffice_3/center/1577401046535922432.jpg\noffice_3/center/1577401141083305472.jpg\noffice_3/center/1577400938787549184.jpg\noffice_3/center/1577400852823057920.jpg\noffice_3/center/1577401166831962880.jpg\noffice_3/center/1577401080685360128.jpg\noffice_3/center/1577401036736670208.jpg\noffice_3/center/1577400955990069504.jpg\noffice_3/center/1577401027437333248.jpg\noffice_3/center/1577401127083630592.jpg\noffice_3/center/1577401139633692672.jpg\noffice_3/center/1577401028237119232.jpg\noffice_3/center/1577401057635965696.jpg\noffice_3/center/1577401142532980224.jpg\noffice_3/center/1577400866684529152.jpg\noffice_3/center/1577401168982479104.jpg\noffice_3/center/1577400971841814784.jpg\noffice_3/center/1577400861129907712.jpg\noffice_3/center/1577400962540657920.jpg\noffice_3/center/1577401022387365376.jpg\noffice_3/center/1577400866133885184.jpg\noffice_3/center/1577400918336574720.jpg\noffice_3/center/1577400921487099648.jpg\noffice_3/center/1577401089285131520.jpg\noffice_3/center/1577400918386519808.jpg\noffice_3/center/1577400966540802304.jpg\noffice_3/center/1577401020387481856.jpg\noffice_3/center/1577400862580877056.jpg\noffice_3/center/1577401039437039872.jpg\noffice_3/center/1577401110734543360.jpg\noffice_3/center/1577401048436131328.jpg\noffice_3/center/1577401048536091648.jpg\noffice_3/center/1577401144333394944.jpg\noffice_3/center/1577400853923849472.jpg\noffice_3/center/1577400961690418176.jpg\noffice_3/center/1577400899384401408.jpg\noffice_3/center/1577400898034457600.jpg\noffice_3/center/1577401137033390080.jpg\noffice_3/center/1577401111585029120.jpg\noffice_3/center/1577401161282909440.jpg\noffice_3/center/1577401161182940416.jpg\noffice_3/center/1577401108584675584.jpg\noffice_3/center/1577400979940504832.jpg\noffice_3/center/1577400876187960576.jpg\noffice_3/center/1577400883334534400.jpg\noffice_3/center/1577401134833116672.jpg\noffice_3/center/1577401126983667712.jpg\noffice_3/center/1577401062386085120.jpg\noffice_3/center/1577400923987566592.jpg\noffice_3/center/1577401158933210112.jpg\noffice_3/center/1577400948588895232.jpg\noffice_3/center/1577401049085723392.jpg\noffice_3/center/1577400861630361344.jpg\noffice_3/center/1577400933487468544.jpg\noffice_3/center/1577401084435243776.jpg\noffice_3/center/1577400948188916480.jpg\noffice_3/center/1577400844563309568.jpg\noffice_3/center/1577401103634703360.jpg\noffice_3/center/1577401074385579264.jpg\noffice_3/center/1577400906434762240.jpg\noffice_3/center/1577401061036182272.jpg\noffice_3/center/1577401142083803392.jpg\noffice_3/center/1577400870687889920.jpg\noffice_3/center/1577401087634733568.jpg\noffice_3/center/1577400880435662592.jpg\noffice_3/center/1577400866884649728.jpg\noffice_3/center/1577401046436011008.jpg\noffice_3/center/1577401144833514496.jpg\noffice_3/center/1577401103734720768.jpg\noffice_3/center/1577400864582609664.jpg\noffice_3/center/1577400889484629760.jpg\noffice_3/center/1577401067486097920.jpg\noffice_3/center/1577401132233568768.jpg\noffice_3/center/1577401090935066368.jpg\noffice_3/center/1577400868636061184.jpg\noffice_3/center/1577401135183918848.jpg\noffice_3/center/1577401162233183488.jpg\noffice_3/center/1577400911534713088.jpg\noffice_3/center/1577401146633219584.jpg\noffice_3/center/1577401155132636928.jpg\noffice_3/center/1577401099834815488.jpg\noffice_3/center/1577400942688561920.jpg\noffice_3/center/1577400916836705024.jpg\noffice_3/center/1577400868835941376.jpg\noffice_3/center/1577400958290084096.jpg\noffice_3/center/1577401154082835712.jpg\noffice_3/center/1577401120534289408.jpg\noffice_3/center/1577400864782757632.jpg\noffice_3/center/1577400867735208960.jpg\noffice_3/center/1577401130533487872.jpg\noffice_3/center/1577401032036603904.jpg\noffice_3/center/1577400921137278976.jpg\noffice_3/center/1577401011188381952.jpg\noffice_3/center/1577400847516646656.jpg\noffice_3/center/1577401159433013760.jpg\noffice_3/center/1577401095634877952.jpg\noffice_3/center/1577401067586033152.jpg\noffice_3/center/1577400904884256256.jpg\noffice_3/center/1577400906534813184.jpg\noffice_3/center/1577400865033153280.jpg\noffice_3/center/1577401166532548864.jpg\noffice_3/center/1577401021387785472.jpg\noffice_3/center/1577400859578059008.jpg\noffice_3/center/1577401164782416896.jpg\noffice_3/center/1577401063635921664.jpg\noffice_3/center/1577401179732157184.jpg\noffice_3/center/1577400864182409472.jpg\noffice_3/center/1577401162932539392.jpg\noffice_3/center/1577401174832421376.jpg\noffice_3/center/1577400977841170432.jpg\noffice_3/center/1577400871487812608.jpg\noffice_3/center/1577400928137073664.jpg\noffice_3/center/1577400856425819136.jpg\noffice_3/center/1577400857277110016.jpg\noffice_3/center/1577401047886967040.jpg\noffice_3/center/1577401031486909696.jpg\noffice_3/center/1577400844963412992.jpg\noffice_3/center/1577401026537399808.jpg\noffice_3/center/1577401116434539776.jpg\noffice_3/center/1577400955539653120.jpg\noffice_3/center/1577400968541104128.jpg\noffice_3/center/1577400944338217216.jpg\noffice_3/center/1577401015287767808.jpg\noffice_3/center/1577401143683234048.jpg\noffice_3/center/1577401047835951616.jpg\noffice_3/center/1577400958990312960.jpg\noffice_3/center/1577401090384891392.jpg\noffice_3/center/1577400876487713280.jpg\noffice_3/center/1577400926937187328.jpg\noffice_3/center/1577401038436407040.jpg\noffice_3/center/1577401128633673728.jpg\noffice_3/center/1577401166233241600.jpg\noffice_3/center/1577400874839244544.jpg\noffice_3/center/1577400924137597184.jpg\noffice_3/center/1577400858026567936.jpg\noffice_3/center/1577401132733556224.jpg\noffice_3/center/1577401040836474624.jpg\noffice_3/center/1577400948788924928.jpg\noffice_3/center/1577400911084601088.jpg\noffice_3/center/1577401080385721856.jpg\noffice_3/center/1577400849669640960.jpg\noffice_3/center/1577401082734644736.jpg\noffice_3/center/1577401032136557312.jpg\noffice_3/center/1577400904434245888.jpg\noffice_3/center/1577400934287849472.jpg\noffice_3/center/1577400922887422720.jpg\noffice_3/center/1577401036086619904.jpg\noffice_3/center/1577400894334645504.jpg\noffice_3/center/1577400976191471360.jpg\noffice_3/center/1577401144583641344.jpg\noffice_3/center/1577401140883435264.jpg\noffice_3/center/1577401018187655424.jpg\noffice_3/center/1577401040036401152.jpg\noffice_3/center/1577400892085341440.jpg\noffice_3/center/1577400879487157248.jpg\noffice_3/center/1577400906284486656.jpg\noffice_3/center/1577400937887934464.jpg\noffice_3/center/1577401092334849280.jpg\noffice_3/center/1577401146832859648.jpg\noffice_3/center/1577400857327260416.jpg\noffice_3/center/1577400854774641920.jpg\noffice_3/center/1577401145783549184.jpg\noffice_3/center/1577401180582146816.jpg\noffice_3/center/1577401132933892352.jpg\noffice_3/center/1577401080635453696.jpg\noffice_3/center/1577401138333549056.jpg\noffice_3/center/1577401092684756224.jpg\noffice_3/center/1577400966341169408.jpg\noffice_3/center/1577400920787233024.jpg\noffice_3/center/1577401177032176896.jpg\noffice_3/center/1577400946488590336.jpg\noffice_3/center/1577401117884841728.jpg\noffice_3/center/1577400965941302528.jpg\noffice_3/center/1577401014288762880.jpg\noffice_3/center/1577400887334530048.jpg\noffice_3/center/1577401069785620224.jpg\noffice_3/center/1577401105384730112.jpg\noffice_3/center/1577401061186073088.jpg\noffice_3/center/1577401041686450432.jpg\noffice_3/center/1577400871889146624.jpg\noffice_3/center/1577400968291038464.jpg\noffice_3/center/1577401136983299584.jpg\noffice_3/center/1577400919037329408.jpg\noffice_3/center/1577401178832692992.jpg\noffice_3/center/1577400939938206464.jpg\noffice_3/center/1577401012738234112.jpg\noffice_3/center/1577400859427761152.jpg\noffice_3/center/1577400872238858496.jpg\noffice_3/center/1577401053185891328.jpg\noffice_3/center/1577400907084234752.jpg\noffice_3/center/1577401065635744512.jpg\noffice_3/center/1577401039036162048.jpg\noffice_3/center/1577400942187544064.jpg\noffice_3/center/1577400911434600192.jpg\noffice_3/center/1577401094784816128.jpg\noffice_3/center/1577401038885777152.jpg\noffice_3/center/1577401121584149248.jpg\noffice_3/center/1577400961590382080.jpg\noffice_3/center/1577401131183808768.jpg\noffice_3/center/1577401056236299008.jpg\noffice_3/center/1577400898534563328.jpg\noffice_3/center/1577400908134689024.jpg\noffice_3/center/1577400864082353664.jpg\noffice_3/center/1577401076285313792.jpg\noffice_3/center/1577401015787844608.jpg\noffice_3/center/1577401039936327936.jpg\noffice_3/center/1577401059936119552.jpg\noffice_3/center/1577401025637514240.jpg\noffice_3/center/1577400911184567808.jpg\noffice_3/center/1577400910534811648.jpg\noffice_3/center/1577401180232304896.jpg\noffice_3/center/1577401165132336896.jpg\noffice_3/center/1577400939988266240.jpg\noffice_3/center/1577400866033872384.jpg\noffice_3/center/1577401125334365184.jpg\noffice_3/center/1577400960690553600.jpg\noffice_3/center/1577401053935923456.jpg\noffice_3/center/1577400901534686976.jpg\noffice_3/center/1577400872537727744.jpg\noffice_3/center/1577401093234854656.jpg\noffice_3/center/1577401167732395008.jpg\noffice_3/center/1577400945938652160.jpg\noffice_3/center/1577401102184504576.jpg\noffice_3/center/1577401151683272448.jpg\noffice_3/center/1577401139783713280.jpg\noffice_3/center/1577401023437197824.jpg\noffice_3/center/1577401158833107456.jpg\noffice_3/center/1577400861280059904.jpg\noffice_3/center/1577400917687113472.jpg\noffice_3/center/1577401084135071744.jpg\noffice_3/center/1577401157582864640.jpg\noffice_3/center/1577401093634785792.jpg\noffice_3/center/1577401015937817344.jpg\noffice_3/center/1577400910984630272.jpg\noffice_3/center/1577401075785853696.jpg\noffice_3/center/1577401069135781888.jpg\noffice_3/center/1577401083885028352.jpg\noffice_3/center/1577401012638248192.jpg\noffice_3/center/1577401123484128768.jpg\noffice_3/center/1577401122384163584.jpg\noffice_3/center/1577401022937618176.jpg\noffice_3/center/1577400866784641024.jpg\noffice_3/center/1577400899434362624.jpg\noffice_3/center/1577400905484521472.jpg\noffice_3/center/1577400849719644416.jpg\noffice_3/center/1577400867635197696.jpg\noffice_3/center/1577400929237725184.jpg\noffice_3/center/1577401141533150208.jpg\noffice_3/center/1577401089784879616.jpg\noffice_3/center/1577401110284781056.jpg\noffice_3/center/1577401149683307008.jpg\noffice_3/center/1577401123184099328.jpg\noffice_3/center/1577400856675369728.jpg\noffice_3/center/1577400869136004864.jpg\noffice_3/center/1577401154433186560.jpg\noffice_3/center/1577400974491582464.jpg\noffice_3/center/1577401062786031872.jpg\noffice_3/center/1577401148882900992.jpg\noffice_3/center/1577400973441643008.jpg\noffice_3/center/1577400855524583936.jpg\noffice_3/center/1577401154483249408.jpg\noffice_3/center/1577400906984233472.jpg\noffice_3/center/1577401031037054720.jpg\noffice_3/center/1577400978291195136.jpg\noffice_3/center/1577400877688047872.jpg\noffice_3/center/1577401136233821184.jpg\noffice_3/center/1577401108434519552.jpg\noffice_3/center/1577401110984423168.jpg\noffice_3/center/1577401154533265408.jpg\noffice_3/center/1577401098084224512.jpg\noffice_3/center/1577401012388242432.jpg\noffice_3/center/1577400978640772096.jpg\noffice_3/center/1577400973241696256.jpg\noffice_3/center/1577401057785968128.jpg\noffice_3/center/1577401167383299072.jpg\noffice_3/center/1577400899284585472.jpg\noffice_3/center/1577401117234379008.jpg\noffice_3/center/1577400846515626496.jpg\noffice_3/center/1577400896834535936.jpg\noffice_3/center/1577400974091652864.jpg\noffice_3/center/1577400949589090048.jpg\noffice_3/center/1577401091734571008.jpg\noffice_3/center/1577401022987684608.jpg\noffice_3/center/1577401069835694336.jpg\noffice_3/center/1577401114784662784.jpg\noffice_3/center/1577401093584809984.jpg\noffice_3/center/1577401022237410048.jpg\noffice_3/center/1577401049585896704.jpg\noffice_3/center/1577400868586111744.jpg\noffice_3/center/1577401149333538560.jpg\noffice_3/center/1577401032936688128.jpg\noffice_3/center/1577401106784692224.jpg\noffice_3/center/1577401040986375168.jpg\noffice_3/center/1577400914886259200.jpg\noffice_3/center/1577400920637259520.jpg\noffice_3/center/1577401069335653632.jpg\noffice_3/center/1577400886734770688.jpg\noffice_3/center/1577401094085130752.jpg\noffice_3/center/1577401031336965120.jpg\noffice_3/center/1577400897334779904.jpg\noffice_3/center/1577400863681976320.jpg\noffice_3/center/1577400952989837568.jpg\noffice_3/center/1577400857025717504.jpg\noffice_3/center/1577401034986824960.jpg\noffice_3/center/1577401027937183488.jpg\noffice_3/center/1577401045185906688.jpg\noffice_3/center/1577401170782365184.jpg\noffice_3/center/1577400936137762304.jpg\noffice_3/center/1577400930787650816.jpg\noffice_3/center/1577401014188540928.jpg\noffice_3/center/1577400844763386624.jpg\noffice_3/center/1577401117834904064.jpg\noffice_3/center/1577401122684311296.jpg\noffice_3/center/1577401068185777920.jpg\noffice_3/center/1577401163082720768.jpg\noffice_3/center/1577400975541763584.jpg\noffice_3/center/1577401137983249408.jpg\noffice_3/center/1577401101184719360.jpg\noffice_3/center/1577400913485647616.jpg\noffice_3/center/1577400952539576576.jpg\noffice_3/center/1577400873839289600.jpg\noffice_3/center/1577400874939276544.jpg\noffice_3/center/1577401043586286336.jpg\noffice_3/center/1577400982239904000.jpg\noffice_3/center/1577401121134450688.jpg\noffice_3/center/1577401014038024448.jpg\noffice_3/center/1577401063535795456.jpg\noffice_3/center/1577401167333274624.jpg\noffice_3/center/1577401101084666368.jpg\noffice_3/center/1577401157732970496.jpg\noffice_3/center/1577401157682986240.jpg\noffice_3/center/1577400856075932416.jpg\noffice_3/center/1577401107534756864.jpg\noffice_3/center/1577400868335748864.jpg\noffice_3/center/1577400850721184768.jpg\noffice_3/center/1577400950988857856.jpg\noffice_3/center/1577400923487195392.jpg\noffice_3/center/1577401166982215680.jpg\noffice_3/center/1577401144433428992.jpg\noffice_3/center/1577401153432867328.jpg\noffice_3/center/1577401076535248384.jpg\noffice_3/center/1577400919936943104.jpg\noffice_3/center/1577400946238692608.jpg\noffice_3/center/1577401018287572992.jpg\noffice_3/center/1577400935087779072.jpg\noffice_3/center/1577400923737321728.jpg\noffice_3/center/1577401029187079936.jpg\noffice_3/center/1577400941138214144.jpg\noffice_3/center/1577401097984232960.jpg\noffice_3/center/1577400922087304704.jpg\noffice_3/center/1577400865633608960.jpg\noffice_3/center/1577401032836739072.jpg\noffice_3/center/1577401040286420224.jpg\noffice_3/center/1577400894484761344.jpg\noffice_3/center/1577401114684475904.jpg\noffice_3/center/1577400891334872320.jpg\noffice_3/center/1577400905634409472.jpg\noffice_3/center/1577400877887430144.jpg\noffice_3/center/1577400935537398528.jpg\noffice_3/center/1577401063585863936.jpg\noffice_3/center/1577401162533099264.jpg\noffice_3/center/1577401136433068032.jpg\noffice_3/center/1577400860579517440.jpg\noffice_3/center/1577401107734941952.jpg\noffice_3/center/1577401055385515264.jpg\noffice_3/center/1577401115834256128.jpg\noffice_3/center/1577401182631936000.jpg\noffice_3/center/1577400893984874240.jpg\noffice_3/center/1577400939288067072.jpg\noffice_3/center/1577401036036630016.jpg\noffice_3/center/1577400846965588992.jpg\noffice_3/center/1577400864232378624.jpg\noffice_3/center/1577400912935729408.jpg\noffice_3/center/1577401092384818432.jpg\noffice_3/center/1577400905983918848.jpg\noffice_3/center/1577401029387113984.jpg\noffice_3/center/1577401125783468544.jpg\noffice_3/center/1577400972041578240.jpg\noffice_3/center/1577400938487969792.jpg\noffice_3/center/1577401171932741632.jpg\noffice_3/center/1577401087834929152.jpg\noffice_3/center/1577400903534412544.jpg\noffice_3/center/1577401109984968448.jpg\noffice_3/center/1577400886534669312.jpg\noffice_3/center/1577400854874688512.jpg\noffice_3/center/1577400868385872640.jpg\noffice_3/center/1577401057935996928.jpg\noffice_3/center/1577401171482509568.jpg\noffice_3/center/1577401175782148608.jpg\noffice_3/center/1577401135482842368.jpg\noffice_3/center/1577401173731971584.jpg\noffice_3/center/1577400976791303936.jpg\noffice_3/center/1577401179032634112.jpg\noffice_3/center/1577400885534902272.jpg\noffice_3/center/1577400966640702976.jpg\noffice_3/center/1577401115984320000.jpg\noffice_3/center/1577401104433938176.jpg\noffice_3/center/1577401106034152704.jpg\noffice_3/center/1577401039686415616.jpg\noffice_3/center/1577400912485662720.jpg\noffice_3/center/1577401089934899200.jpg\noffice_3/center/1577400898684657664.jpg\noffice_3/center/1577400979640871424.jpg\noffice_3/center/1577401124783991296.jpg\noffice_3/center/1577400934387900416.jpg\noffice_3/center/1577400901434747136.jpg\noffice_3/center/1577401096934560768.jpg\noffice_3/center/1577400971791788288.jpg\noffice_3/center/1577401122484215296.jpg\noffice_3/center/1577401075235702784.jpg\noffice_3/center/1577401085635371776.jpg\noffice_3/center/1577400896734448896.jpg\noffice_3/center/1577400891184828672.jpg\noffice_3/center/1577401149733111808.jpg\noffice_3/center/1577400865683695616.jpg\noffice_3/center/1577400895784620032.jpg\noffice_3/center/1577401095384704512.jpg\noffice_3/center/1577401042636245760.jpg\noffice_3/center/1577401068835856384.jpg\noffice_3/center/1577401095684926208.jpg\noffice_3/center/1577401026587452160.jpg\noffice_3/center/1577400893234924800.jpg\noffice_3/center/1577401105484709888.jpg\noffice_3/center/1577400931237662976.jpg\noffice_3/center/1577400848618428416.jpg\noffice_3/center/1577401160283185152.jpg\noffice_3/center/1577401041036370176.jpg\noffice_3/center/1577401089335128832.jpg\noffice_3/center/1577401160932907264.jpg\noffice_3/center/1577401080535612928.jpg\noffice_3/center/1577401086435007744.jpg\noffice_3/center/1577401180632088064.jpg\noffice_3/center/1577401120584267264.jpg\noffice_3/center/1577401157382704896.jpg\noffice_3/center/1577401051585872384.jpg\noffice_3/center/1577401048336054784.jpg\noffice_3/center/1577401043636285952.jpg\noffice_3/center/1577401165532833024.jpg\noffice_3/center/1577401145583411456.jpg\noffice_3/center/1577400948438778624.jpg\noffice_3/center/1577400954539430656.jpg\noffice_3/center/1577401054485676800.jpg\noffice_3/center/1577401037586386688.jpg\noffice_3/center/1577400871387871744.jpg\noffice_3/center/1577400939438287360.jpg\noffice_3/center/1577400854824649984.jpg\noffice_3/center/1577401087235386112.jpg\noffice_3/center/1577401139183551232.jpg\noffice_3/center/1577400909234609408.jpg\noffice_3/center/1577400929587428352.jpg\noffice_3/center/1577401076685490688.jpg\noffice_3/center/1577401031386939904.jpg\noffice_3/center/1577401116784253440.jpg\noffice_3/center/1577400933437536512.jpg\noffice_3/center/1577400927538145536.jpg\noffice_3/center/1577400868686067456.jpg\noffice_3/center/1577401066035915776.jpg\noffice_3/center/1577401012788213248.jpg\noffice_3/center/1577401116834233856.jpg\noffice_3/center/1577401157032839680.jpg\noffice_3/center/1577400964040841984.jpg\noffice_3/center/1577400869536717312.jpg\noffice_3/center/1577400911584824320.jpg\noffice_3/center/1577400942938460160.jpg\noffice_3/center/1577401108234309376.jpg\noffice_3/center/1577400942437959424.jpg\noffice_3/center/1577401102384444416.jpg\noffice_3/center/1577400896084554752.jpg\noffice_3/center/1577401172682335744.jpg\noffice_3/center/1577401100084640000.jpg\noffice_3/center/1577401059535717888.jpg\noffice_3/center/1577401124533948416.jpg\noffice_3/center/1577401060485884928.jpg\noffice_3/center/1577400950089252608.jpg\noffice_3/center/1577400975991560192.jpg\noffice_3/center/1577401122934294272.jpg\noffice_3/center/1577400891284869376.jpg\noffice_3/center/1577401033536753152.jpg\noffice_3/center/1577401142783464960.jpg\noffice_3/center/1577401084235134464.jpg\noffice_3/center/1577401116484505856.jpg\noffice_3/center/1577400860729558528.jpg\noffice_3/center/1577400876437659904.jpg\noffice_3/center/1577400938887555840.jpg\noffice_3/center/1577401038136848128.jpg\noffice_3/center/1577400877438540800.jpg\noffice_3/center/1577400904784273152.jpg\noffice_3/center/1577400909734833920.jpg\noffice_3/center/1577401046985829888.jpg\noffice_3/center/1577401054786243328.jpg\noffice_3/center/1577400973341684992.jpg\noffice_3/center/1577400926336981248.jpg\noffice_3/center/1577400920036993792.jpg\noffice_3/center/1577400878386442240.jpg\noffice_3/center/1577401063235837184.jpg\noffice_3/center/1577401147633228032.jpg\noffice_3/center/1577401052735943936.jpg\noffice_3/center/1577401138033326848.jpg\noffice_3/center/1577400956639827712.jpg\noffice_3/center/1577401053735921152.jpg\noffice_3/center/1577401127583916288.jpg\noffice_3/center/1577401059685971712.jpg\noffice_3/center/1577400879736700416.jpg\noffice_3/center/1577400883784604416.jpg\noffice_3/center/1577401171782789376.jpg\noffice_3/center/1577401020437426176.jpg\noffice_3/center/1577400903684451072.jpg\noffice_3/center/1577400948488810752.jpg\noffice_3/center/1577401087035338240.jpg\noffice_3/center/1577401126434212352.jpg\noffice_3/center/1577401062586070784.jpg\noffice_3/center/1577401069585505536.jpg\noffice_3/center/1577400902384208128.jpg\noffice_3/center/1577400932087608320.jpg\noffice_3/center/1577400853773736192.jpg\noffice_3/center/1577400966291305984.jpg\noffice_3/center/1577400959990373632.jpg\noffice_3/center/1577401084485281536.jpg\noffice_3/center/1577401069185714944.jpg\noffice_3/center/1577401106384391168.jpg\noffice_3/center/1577401125084145152.jpg\noffice_3/center/1577400884734398464.jpg\noffice_3/center/1577401016787957504.jpg\noffice_3/center/1577400926386985472.jpg\noffice_3/center/1577401141683294976.jpg\noffice_3/center/1577400947639326464.jpg\noffice_3/center/1577400914586464768.jpg\noffice_3/center/1577400967190907904.jpg\noffice_3/center/1577400852522973952.jpg\noffice_3/center/1577401092984879360.jpg\noffice_3/center/1577401018637739264.jpg\noffice_3/center/1577401096184760064.jpg\noffice_3/center/1577400928387437824.jpg\noffice_3/center/1577400956090112256.jpg\noffice_3/center/1577400937487452416.jpg\noffice_3/center/1577400894884933632.jpg\noffice_3/center/1577401065435898880.jpg\noffice_3/center/1577401028637111040.jpg\noffice_3/center/1577400845814652416.jpg\noffice_3/center/1577400870537657856.jpg\noffice_3/center/1577400884634309888.jpg\noffice_3/center/1577401081135142656.jpg\noffice_3/center/1577400862931452672.jpg\noffice_3/center/1577401118634312704.jpg\noffice_3/center/1577400855975810304.jpg\noffice_3/center/1577400896334480128.jpg\noffice_3/center/1577401029287113728.jpg\noffice_3/center/1577401020787185920.jpg\noffice_3/center/1577401110334736384.jpg\noffice_3/center/1577400967691239936.jpg\noffice_3/center/1577400861980504832.jpg\noffice_3/center/1577401080935079424.jpg\noffice_3/center/1577400879886448384.jpg\noffice_3/center/1577401125833337344.jpg\noffice_3/center/1577401074735768576.jpg\noffice_3/center/1577400865833727232.jpg\noffice_3/center/1577400892684665600.jpg\noffice_3/center/1577401102634509568.jpg\noffice_3/center/1577400965490647552.jpg\noffice_3/center/1577400970791510784.jpg\noffice_3/center/1577400904934270464.jpg\noffice_3/center/1577401027237543424.jpg\noffice_3/center/1577401047186240512.jpg\noffice_3/center/1577400930087318528.jpg\noffice_3/center/1577401183981990400.jpg\noffice_3/center/1577401090734713088.jpg\noffice_3/center/1577401115334471168.jpg\noffice_3/center/1577401166482701568.jpg\noffice_3/center/1577401078935582976.jpg\noffice_3/center/1577401176832017920.jpg\noffice_3/center/1577401031786756608.jpg\noffice_3/center/1577401179982350848.jpg\noffice_3/center/1577400969091152640.jpg\noffice_3/center/1577400851921946112.jpg\noffice_3/center/1577401128983931392.jpg\noffice_3/center/1577401129983670272.jpg\noffice_3/center/1577401071635867904.jpg\noffice_3/center/1577401043536318720.jpg\noffice_3/center/1577401041286393600.jpg\noffice_3/center/1577401165982645504.jpg\noffice_3/center/1577400970541468672.jpg\noffice_3/center/1577400904734287104.jpg\noffice_3/center/1577401032636731904.jpg\noffice_3/center/1577401098934599680.jpg\noffice_3/center/1577400953039764480.jpg\noffice_3/center/1577400889034728192.jpg\noffice_3/center/1577401154683339008.jpg\noffice_3/center/1577401126133483776.jpg\noffice_3/center/1577401026787508992.jpg\noffice_3/center/1577400935237552384.jpg\noffice_3/center/1577401103534657024.jpg\noffice_3/center/1577400927337958656.jpg\noffice_3/center/1577400882234934016.jpg\noffice_3/center/1577401179581836544.jpg\noffice_3/center/1577400895584940032.jpg\noffice_3/center/1577401116684299776.jpg\noffice_3/center/1577401025387468800.jpg\noffice_3/center/1577401013388300800.jpg\noffice_3/center/1577400946088764928.jpg\noffice_3/center/1577401028937054208.jpg\noffice_3/center/1577401067985628928.jpg\noffice_3/center/1577400953239623680.jpg\noffice_3/center/1577400899884606720.jpg\noffice_3/center/1577401156083338752.jpg\noffice_3/center/1577400922287570688.jpg\noffice_3/center/1577400910484815104.jpg\noffice_3/center/1577401113383938048.jpg\noffice_3/center/1577401055685694976.jpg\noffice_3/center/1577400868085421824.jpg\noffice_3/center/1577400896234569984.jpg\noffice_3/center/1577401143733219072.jpg\noffice_3/center/1577401169382623232.jpg\noffice_3/center/1577400862630937088.jpg\noffice_3/center/1577401143933203456.jpg\noffice_3/center/1577400952639769856.jpg\noffice_3/center/1577401167132707072.jpg\noffice_3/center/1577401122084177152.jpg\noffice_3/center/1577401157232608768.jpg\noffice_3/center/1577400863531712768.jpg\noffice_3/center/1577400945238686464.jpg\noffice_3/center/1577400917737173504.jpg\noffice_3/center/1577401132283583488.jpg\noffice_3/center/1577400920937209344.jpg\noffice_3/center/1577401178582370048.jpg\noffice_3/center/1577400939388210944.jpg\noffice_3/center/1577401040236410368.jpg\noffice_3/center/1577400889334591744.jpg\noffice_3/center/1577401035687010560.jpg\noffice_3/center/1577401106684641024.jpg\noffice_3/center/1577401173531837952.jpg\noffice_3/center/1577401177382413056.jpg\noffice_3/center/1577400895984482560.jpg\noffice_3/center/1577401033386761728.jpg\noffice_3/center/1577401026237102080.jpg\noffice_3/center/1577400933537409024.jpg\noffice_3/center/1577401175832200448.jpg\noffice_3/center/1577400870788020736.jpg\noffice_3/center/1577400901634601216.jpg\noffice_3/center/1577400971541531392.jpg\noffice_3/center/1577401029437096448.jpg\noffice_3/center/1577401144533609984.jpg\noffice_3/center/1577400956439970816.jpg\noffice_3/center/1577400971091134464.jpg\noffice_3/center/1577401176782072064.jpg\noffice_3/center/1577401033586756864.jpg\noffice_3/center/1577401149533509376.jpg\noffice_3/center/1577400894934907392.jpg\noffice_3/center/1577401060936240640.jpg\noffice_3/center/1577400959240304384.jpg\noffice_3/center/1577400875039285248.jpg\noffice_3/center/1577401083335573504.jpg\noffice_3/center/1577400945788523008.jpg\noffice_3/center/1577401147032894976.jpg\noffice_3/center/1577400948238860288.jpg\noffice_3/center/1577400922337590784.jpg\noffice_3/center/1577400931137644288.jpg\noffice_3/center/1577400933987593728.jpg\noffice_3/center/1577400844463289088.jpg\noffice_3/center/1577401059736039936.jpg\noffice_3/center/1577401152133099008.jpg\noffice_3/center/1577401090134927872.jpg\noffice_3/center/1577400902134298368.jpg\noffice_3/center/1577401054135744512.jpg\noffice_3/center/1577401071435784192.jpg\noffice_3/center/1577401078685405184.jpg\noffice_3/center/1577400950539468800.jpg\noffice_3/center/1577401020737230592.jpg\noffice_3/center/1577401140733525760.jpg\noffice_3/center/1577401079635453184.jpg\noffice_3/center/1577401124583966976.jpg\noffice_3/center/1577400964590933760.jpg\noffice_3/center/1577401072185673728.jpg\noffice_3/center/1577401144133240320.jpg\noffice_3/center/1577400929037683200.jpg\noffice_3/center/1577401106484475392.jpg\noffice_3/center/1577401060235831808.jpg\noffice_3/center/1577401180532225280.jpg\noffice_3/center/1577401134233472000.jpg\noffice_3/center/1577400848468339712.jpg\noffice_3/center/1577400960890521088.jpg\noffice_3/center/1577401160483175424.jpg\noffice_3/center/1577401173832093952.jpg\noffice_3/center/1577401124433954560.jpg\noffice_3/center/1577401147433540864.jpg\noffice_3/center/1577401109234653952.jpg\noffice_3/center/1577400854924617472.jpg\noffice_3/center/1577401083585383936.jpg\noffice_3/center/1577401014138379008.jpg\noffice_3/center/1577400870387558400.jpg\noffice_3/center/1577400880186162432.jpg\noffice_3/center/1577400863631867648.jpg\noffice_3/center/1577401138783382272.jpg\noffice_3/center/1577400947989229056.jpg\noffice_3/center/1577400853473507840.jpg\noffice_3/center/1577401180282293760.jpg\noffice_3/center/1577401175382619648.jpg\noffice_3/ml_training_2019-12-26-14-55-53_4.yaml\n"
]
],
[
[
"## Parse the CSV File",
"_____no_output_____"
]
],
[
[
"# Define path to csv file\ncsv_path = data_set + '/interpolated.csv'\n\n# Load the CSV file into a pandas dataframe\ndf = pd.read_csv(csv_path, sep=\",\")\n\n# Print the dimensions\nprint(\"Dataset Dimensions:\")\nprint(df.shape)\n\n# Print the first 5 lines of the dataframe for review\nprint(\"\\nDataset Summary:\")\ndf.head(5)\n ",
"Dataset Dimensions:\n(6253, 8)\n\nDataset Summary:\n"
]
],
[
[
"# Clean and Pre-process the Dataset",
"_____no_output_____"
],
[
"## Remove Unneccessary Columns",
"_____no_output_____"
]
],
[
[
"# Remove 'index' and 'frame_id' columns \ndf.drop(['index','frame_id'],axis=1,inplace=True)\n\n# Verify new dataframe dimensions\nprint(\"Dataset Dimensions:\")\nprint(df.shape)\n\n# Print the first 5 lines of the new dataframe for review\nprint(\"\\nDataset Summary:\")\ndf.head(5)",
"Dataset Dimensions:\n(6253, 6)\n\nDataset Summary:\n"
]
],
[
[
"## Detect Missing Data",
"_____no_output_____"
]
],
[
[
"# Detect Missing Values\nprint(\"Any Missing Values?: {}\".format(df.isnull().values.any()))\n\n# Total Sum\nprint(\"\\nTotal Number of Missing Values: {}\".format(df.isnull().sum().sum()))\n\n# Sum Per Column\nprint(\"\\nTotal Number of Missing Values per Column:\")\nprint(df.isnull().sum())",
"Any Missing Values?: False\n\nTotal Number of Missing Values: 0\n\nTotal Number of Missing Values per Column:\ntimestamp 0\nwidth 0\nheight 0\nfilename 0\nangle 0\nspeed 0\ndtype: int64\n"
]
],
[
[
"## Remove Zero Throttle Values",
"_____no_output_____"
]
],
[
[
"# Determine if any throttle values are zeroes\nprint(\"Any 0 throttle values?: {}\".format(df['speed'].eq(0).any()))\n\n# Determine number of 0 throttle values:\nprint(\"\\nNumber of 0 throttle values: {}\".format(df['speed'].eq(0).sum()))\n\n# Remove rows with 0 throttle values\nif df['speed'].eq(0).any():\n df = df.query('speed != 0')\n \n # Reset the index\n df.reset_index(inplace=True,drop=True)\n \n# Verify new dataframe dimensions\nprint(\"\\nNew Dataset Dimensions:\")\nprint(df.shape)\ndf.head(5)",
"Any 0 throttle values?: True\n\nNumber of 0 throttle values: 55\n\nNew Dataset Dimensions:\n(6198, 6)\n"
]
],
[
[
"## View Label Statistics",
"_____no_output_____"
]
],
[
[
"# Steering Command Statistics\nprint(\"\\nSteering Command Statistics:\")\nprint(df['angle'].describe())\n\nprint(\"\\nThrottle Command Statistics:\")\n# Throttle Command Statistics\nprint(df['speed'].describe())",
"\nSteering Command Statistics:\ncount 6198.000000\nmean 0.822324\nstd 1.008619\nmin -1.533349\n25% 0.471148\n50% 1.380756\n75% 1.466080\nmax 1.531508\nName: angle, dtype: float64\n\nThrottle Command Statistics:\ncount 6198.000000\nmean 0.129354\nstd 0.015255\nmin 0.002261\n25% 0.118947\n50% 0.131835\n75% 0.139840\nmax 0.150000\nName: speed, dtype: float64\n"
]
],
[
[
"## View Histogram of Steering Commands",
"_____no_output_____"
]
],
[
[
"#@title Select the number of histogram bins\n\nnum_bins = 25 #@param {type:\"slider\", min:5, max:50, step:1}\n\nhist, bins = np.histogram(df['angle'], num_bins)\ncenter = (bins[:-1]+ bins[1:]) * 0.5\nplt.bar(center, hist, width=0.05)\n#plt.plot((np.min(df['angle']), np.max(df['angle'])), (samples_per_bin, samples_per_bin))",
"_____no_output_____"
],
[
"# Normalize the histogram (150-300 for RBG)\n#@title Normalize the Histogram { run: \"auto\" }\nhist = False #@param {type:\"boolean\"}\n\nremove_list = []\nsamples_per_bin = 150\n\nif hist:\n for j in range(num_bins):\n list_ = []\n for i in range(len(df['angle'])):\n if df.loc[i,'angle'] >= bins[j] and df.loc[i,'angle'] <= bins[j+1]:\n list_.append(i)\n random.shuffle(list_)\n list_ = list_[samples_per_bin:]\n remove_list.extend(list_)\n\n print('removed:', len(remove_list))\n df.drop(df.index[remove_list], inplace=True)\n df.reset_index(inplace=True)\n df.drop(['index'],axis=1,inplace=True)\n print('remaining:', len(df))\n \n hist, _ = np.histogram(df['angle'], (num_bins))\n plt.bar(center, hist, width=0.05)\n plt.plot((np.min(df['angle']), np.max(df['angle'])), (samples_per_bin, samples_per_bin))",
"_____no_output_____"
]
],
[
[
"## View a Sample Image",
"_____no_output_____"
]
],
[
[
"# View a Single Image \nindex = random.randint(0,df.shape[0]-1)\n\nimg_name = data_set + '/' + df.loc[index,'filename']\nangle = df.loc[index,'angle']\n\ncenter_image = cv2.imread(img_name)\ncenter_image_mod = cv2.resize(center_image, (320,180))\ncenter_image_mod = cv2.cvtColor(center_image_mod,cv2.COLOR_RGB2BGR)\n\n# Crop the image\nheight_min = 100 \nheight_max = 170\nwidth_min = 120\nwidth_max = 200\nbottom_crop = center_image_mod.shape[0] - height_max\nright_crop = center_image_mod.shape[1] - width_max\n\ncrop_img = center_image_mod[height_min:height_max, width_min:width_max]\n\nplt.subplot(2,1,1)\nplt.imshow(center_image_mod)\nplt.grid(False)\nplt.xlabel('angle: {:.2}'.format(angle))\nplt.show() \n\nplt.subplot(2,1,2)\nplt.imshow(crop_img)\nplt.grid(False)\nplt.xlabel('angle: {:.2}'.format(angle))\nplt.show() ",
"_____no_output_____"
]
],
[
[
"## View Multiple Images",
"_____no_output_____"
]
],
[
[
"# Number of Images to Display\nnum_images = 4\n\n# Display the images\ni = 0\nfor i in range (i,num_images):\n index = random.randint(0,df.shape[0]-1)\n image_path = df.loc[index,'filename']\n angle = df.loc[index,'angle']\n img_name = data_set + '/' + image_path\n image = cv2.imread(img_name)\n image = cv2.resize(image, (320,180))\n image = cv2.cvtColor(image,cv2.COLOR_RGB2BGR)\n plt.subplot(num_images/2,num_images/2,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(image, cmap=plt.cm.binary)\n plt.xlabel('angle: {:.3}'.format(angle))\n i += 1",
"_____no_output_____"
]
],
[
[
"# Split the Dataset",
"_____no_output_____"
],
[
"## Define an ImageDataGenerator to Augment Images\n\n",
"_____no_output_____"
]
],
[
[
"# Create image data augmentation generator and choose augmentation types\ndatagen = ImageDataGenerator(\n #rotation_range=20,\n zoom_range=0.15,\n #width_shift_range=0.1,\n #height_shift_range=0.2,\n #shear_range=10,\n brightness_range=[0.5,1.0],\n \t #horizontal_flip=True,\n #vertical_flip=True,\n #channel_shift_range=100.0,\n fill_mode=\"reflect\")",
"_____no_output_____"
]
],
[
[
"## View Image Augmentation Examples",
"_____no_output_____"
]
],
[
[
"# load the image\nindex = random.randint(0,df.shape[0]-1)\n\nimg_name = data_set + '/' + df.loc[index,'filename']\noriginal_image = cv2.imread(img_name)\noriginal_image = cv2.cvtColor(original_image,cv2.COLOR_RGB2BGR)\noriginal_image = cv2.resize(original_image, (320,180))\nlabel = df.loc[index,'angle']\n\n# convert to numpy array\ndata = img_to_array(original_image)\n\n# expand dimension to one sample\ntest = expand_dims(data, 0)\n\n# prepare iterator\nit = datagen.flow(test, batch_size=1)\n\n# generate batch of images\nbatch = it.next()\n\n# convert to unsigned integers for viewing\nimage_aug = batch[0].astype('uint8')\n\nprint(\"Augmenting a Single Image: \\n\")\n\nplt.subplot(2,1,1)\nplt.imshow(original_image)\nplt.grid(False)\nplt.xlabel('angle: {:.2}'.format(label))\nplt.show() \n\nplt.subplot(2,1,2)\nplt.imshow(image_aug)\nplt.grid(False)\nplt.xlabel('angle: {:.2}'.format(label))\nplt.show() \n\nprint(\"Multiple Augmentations: \\n\")\n# generate samples and plot\nfor i in range(0,num_images):\n\t# define subplot\n\tplt.subplot(num_images/2,num_images/2,i+1)\n\t# generate batch of images\n\tbatch = it.next()\n\t# convert to unsigned integers for viewing\n\timage = batch[0].astype('uint8')\n\t# plot raw pixel data\n\tplt.imshow(image)\n# show the figure\nplt.show()\n",
"Augmenting a Single Image: \n\n"
]
],
[
[
"## Define a Data Generator",
"_____no_output_____"
]
],
[
[
"def generator(samples, batch_size=32, aug=0):\n num_samples = len(samples)\n\n while 1: # Loop forever so the generator never terminates\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset + batch_size]\n\n #print(batch_samples)\n images = []\n angles = []\n for batch_sample in batch_samples:\n if batch_sample[5] != \"filename\":\n name = data_set + '/' + batch_sample[3]\n center_image = cv2.imread(name)\n center_image = cv2.cvtColor(center_image,cv2.COLOR_RGB2BGR)\n center_image = cv2.resize(\n center_image,\n (320, 180)) #resize from 720x1280 to 180x320\n angle = float(batch_sample[4])\n if not aug:\n images.append(center_image)\n angles.append(angle)\n else:\n data = img_to_array(center_image)\n sample = expand_dims(data, 0)\n it = datagen.flow(sample, batch_size=1)\n batch = it.next()\n image_aug = batch[0].astype('uint8')\n if random.random() < .5:\n image_aug = np.fliplr(image_aug)\n angle = -1 * angle\n images.append(image_aug)\n angles.append(angle)\n\n X_train = np.array(images)\n y_train = np.array(angles)\n\n yield sklearn.utils.shuffle(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"## Split the Dataset",
"_____no_output_____"
]
],
[
[
"samples = []\n\nsamples = df.values.tolist()\n\nsklearn.utils.shuffle(samples)\ntrain_samples, validation_samples = train_test_split(samples, test_size=0.2)\n\nprint(\"Number of traing samples: \", len(train_samples))\nprint(\"Number of validation samples: \", len(validation_samples))",
"('Number of traing samples: ', 4958)\n('Number of validation samples: ', 1240)\n"
]
],
[
[
"## Define Training and Validation Data Generators",
"_____no_output_____"
]
],
[
[
"batch_size_value = 32\nimg_aug = 1\n\ntrain_generator = generator(train_samples, batch_size=batch_size_value, aug=img_aug)\nvalidation_generator = generator(\n validation_samples, batch_size=batch_size_value, aug=0)",
"_____no_output_____"
]
],
[
[
"# Compile and Train the Model",
"_____no_output_____"
],
[
"## Build the Model",
"_____no_output_____"
]
],
[
[
"# Initialize the model\nmodel = Sequential()\n\n# trim image to only see section with road\n# (top_crop, bottom_crop), (left_crop, right_crop)\nmodel.add(Cropping2D(cropping=((height_min,bottom_crop), (width_min,right_crop)), input_shape=(180,320,3)))\n\n# Preprocess incoming data, centered around zero with small standard deviation\nmodel.add(Lambda(lambda x: (x / 255.0) - 0.5))\n\n# Nvidia model\nmodel.add(Convolution2D(24, (5, 5), activation=\"relu\", name=\"conv_1\", strides=(2, 2)))\nmodel.add(Convolution2D(36, (5, 5), activation=\"relu\", name=\"conv_2\", strides=(2, 2)))\nmodel.add(Convolution2D(48, (5, 5), activation=\"relu\", name=\"conv_3\", strides=(2, 2)))\nmodel.add(SpatialDropout2D(.5, dim_ordering='default'))\n\nmodel.add(Convolution2D(64, (3, 3), activation=\"relu\", name=\"conv_4\", strides=(1, 1)))\nmodel.add(Convolution2D(64, (3, 3), activation=\"relu\", name=\"conv_5\", strides=(1, 1)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(1164))\nmodel.add(Dropout(.5))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dropout(.5))\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dropout(.5))\nmodel.add(Dense(10, activation='relu'))\nmodel.add(Dropout(.5))\nmodel.add(Dense(1))\n\nmodel.compile(loss='mse', optimizer=Adam(lr=0.001), metrics=['mse','mae','mape','cosine'])\n\n# Print model sumamry\nmodel.summary()",
"/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py:14: UserWarning: Update your `SpatialDropout2D` call to the Keras 2 API: `SpatialDropout2D(0.5, data_format=None)`\n \n"
]
],
[
[
"## Setup Checkpoints",
"_____no_output_____"
]
],
[
[
"# checkpoint\nmodel_path = './model'\n\n!if [ -d $model_path ]; then echo 'Directory Exists'; else mkdir $model_path; fi\n\nfilepath = model_path + \"/weights-improvement-{epoch:02d}-{val_loss:.2f}.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto', period=1)",
"_____no_output_____"
]
],
[
[
"## Setup Early Stopping to Prevent Overfitting",
"_____no_output_____"
]
],
[
[
"# The patience parameter is the amount of epochs to check for improvement\nearly_stop = EarlyStopping(monitor='val_loss', patience=10)",
"_____no_output_____"
]
],
[
[
"## Reduce Learning Rate When a Metric has Stopped Improving",
"_____no_output_____"
]
],
[
[
"reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,\n patience=5, min_lr=0.001)",
"_____no_output_____"
]
],
[
[
"## Setup Tensorboard",
"_____no_output_____"
]
],
[
[
"# Clear any logs from previous runs\n!rm -rf ./Graph/ \n\n# Launch Tensorboard\n!pip install -U tensorboardcolab\n\nfrom tensorboardcolab import *\n\ntbc = TensorBoardColab()\n\n# Configure the Tensorboard Callback\ntbCallBack = TensorBoard(log_dir='./Graph', \n histogram_freq=1,\n write_graph=True,\n write_grads=True,\n write_images=True,\n batch_size=batch_size_value,\n update_freq='epoch')\n",
"Requirement already up-to-date: tensorboardcolab in /usr/local/lib/python2.7/dist-packages (0.0.22)\nWait for 8 seconds...\nTensorBoard link:\nhttp://5deaa30c.ngrok.io\n"
]
],
[
[
"## Load Existing Model",
"_____no_output_____"
]
],
[
[
"load = True #@param {type:\"boolean\"}\n\nif load:\n # Returns a compiled model identical to the previous one\n !curl -O https://selbystorage.s3-us-west-2.amazonaws.com/research/office_3/model_intensity.h5\n !mv model_intensity.h5 model/\n model_path_full = model_path + '/' + 'model_intensity.h5'\n model = load_model(model_path_full)\n print(\"Loaded previous model: {} \\n\".format(model_path_full))\nelse:\n print(\"No previous model loaded \\n\")",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 8297k 100 8297k 0 0 10.4M 0 --:--:-- --:--:-- --:--:-- 10.4M\nLoaded previous model: ./model/model_intensity.h5 \n\n"
]
],
[
[
"\n## Train the Model",
"_____no_output_____"
]
],
[
[
"# Define step sizes\nSTEP_SIZE_TRAIN = len(train_samples) / batch_size_value\nSTEP_SIZE_VALID = len(validation_samples) / batch_size_value\n\n# Define number of epochs\nn_epoch = 50\n\n# Define callbacks\n# callbacks_list = [TensorBoardColabCallback(tbc)]\n# callbacks_list = [TensorBoardColabCallback(tbc), early_stop]\n# callbacks_list = [TensorBoardColabCallback(tbc), early_stop, checkpoint]\ncallbacks_list = [TensorBoardColabCallback(tbc), early_stop, checkpoint, reduce_lr]\n\n# Fit the model\nhistory_object = model.fit_generator(\n generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=validation_generator,\n validation_steps=STEP_SIZE_VALID,\n callbacks=callbacks_list,\n use_multiprocessing=True,\n epochs=n_epoch)\n",
"Epoch 1/50\n154/154 [==============================] - 87s 563ms/step - loss: 1.6989 - mean_squared_error: 1.6989 - mean_absolute_error: 1.2303 - mean_absolute_percentage_error: 2537433.2419 - cosine_proximity: -0.0099 - val_loss: 1.7245 - val_mean_squared_error: 1.7245 - val_mean_absolute_error: 1.2423 - val_mean_absolute_percentage_error: 359371.0461 - val_cosine_proximity: 0.6513\n\nEpoch 00001: val_loss did not improve from 0.25825\nEpoch 2/50\n154/154 [==============================] - 84s 544ms/step - loss: 1.6901 - mean_squared_error: 1.6901 - mean_absolute_error: 1.2264 - mean_absolute_percentage_error: 1111287.3951 - cosine_proximity: 0.0278 - val_loss: 1.7239 - val_mean_squared_error: 1.7239 - val_mean_absolute_error: 1.2447 - val_mean_absolute_percentage_error: 135715.2303 - val_cosine_proximity: 0.6531\n\nEpoch 00002: val_loss did not improve from 0.25825\nEpoch 3/50\n154/154 [==============================] - 84s 547ms/step - loss: 1.6869 - mean_squared_error: 1.6869 - mean_absolute_error: 1.2249 - mean_absolute_percentage_error: 1008224.7047 - cosine_proximity: -0.0091 - val_loss: 1.7412 - val_mean_squared_error: 1.7412 - val_mean_absolute_error: 1.2491 - val_mean_absolute_percentage_error: 829392.7223 - val_cosine_proximity: 0.6490\n\nEpoch 00003: val_loss did not improve from 0.25825\nEpoch 4/50\n154/154 [==============================] - 84s 547ms/step - loss: 1.6889 - mean_squared_error: 1.6889 - mean_absolute_error: 1.2260 - mean_absolute_percentage_error: 1412263.8743 - cosine_proximity: -0.0113 - val_loss: 1.7407 - val_mean_squared_error: 1.7407 - val_mean_absolute_error: 1.2500 - val_mean_absolute_percentage_error: 764262.0272 - val_cosine_proximity: 0.6540\n\nEpoch 00004: val_loss did not improve from 0.25825\nEpoch 5/50\n154/154 [==============================] - 84s 546ms/step - loss: 1.6907 - mean_squared_error: 1.6907 - mean_absolute_error: 1.2266 - mean_absolute_percentage_error: 828353.1170 - cosine_proximity: -0.0121 - val_loss: 1.7345 - val_mean_squared_error: 1.7345 - val_mean_absolute_error: 1.2476 - val_mean_absolute_percentage_error: 642487.7258 - val_cosine_proximity: 0.6440\n\nEpoch 00005: val_loss did not improve from 0.25825\nEpoch 6/50\n154/154 [==============================] - 84s 547ms/step - loss: 1.6900 - mean_squared_error: 1.6900 - mean_absolute_error: 1.2263 - mean_absolute_percentage_error: 477814.4326 - cosine_proximity: -0.0047 - val_loss: 1.7299 - val_mean_squared_error: 1.7299 - val_mean_absolute_error: 1.2463 - val_mean_absolute_percentage_error: 307544.4697 - val_cosine_proximity: 0.6482\n\nEpoch 00006: val_loss did not improve from 0.25825\nEpoch 7/50\n154/154 [==============================] - 84s 545ms/step - loss: 1.6886 - mean_squared_error: 1.6886 - mean_absolute_error: 1.2257 - mean_absolute_percentage_error: 516291.1301 - cosine_proximity: 0.0073 - val_loss: 1.7157 - val_mean_squared_error: 1.7157 - val_mean_absolute_error: 1.2402 - val_mean_absolute_percentage_error: 33908.3636 - val_cosine_proximity: -0.6482\n\nEpoch 00007: val_loss did not improve from 0.25825\nEpoch 8/50\n154/154 [==============================] - 84s 547ms/step - loss: 1.6905 - mean_squared_error: 1.6905 - mean_absolute_error: 1.2262 - mean_absolute_percentage_error: 562722.2738 - cosine_proximity: 0.0023 - val_loss: 1.7237 - val_mean_squared_error: 1.7237 - val_mean_absolute_error: 1.2433 - val_mean_absolute_percentage_error: 251274.9909 - val_cosine_proximity: 0.6474\n\nEpoch 00008: val_loss did not improve from 0.25825\nEpoch 9/50\n 8/154 [>.............................] - ETA: 56s - loss: 1.7026 - mean_squared_error: 1.7026 - mean_absolute_error: 1.2320 - mean_absolute_percentage_error: 139298.7649 - cosine_proximity: 0.0745"
]
],
[
[
"## Save the Model",
"_____no_output_____"
]
],
[
[
"# Save model\nmodel_path_full = model_path + '/'\n\nmodel.save(model_path_full + 'model.h5')\nwith open(model_path_full + 'model.json', 'w') as output_json:\n output_json.write(model.to_json())",
"_____no_output_____"
]
],
[
[
"# Evaluate the Model",
"_____no_output_____"
],
[
"## Plot the Training Results",
"_____no_output_____"
]
],
[
[
"# Plot the training and validation loss for each epoch\nprint('Generating loss chart...')\nplt.plot(history_object.history['loss'])\nplt.plot(history_object.history['val_loss'])\nplt.title('model mean squared error loss')\nplt.ylabel('mean squared error loss')\nplt.xlabel('epoch')\nplt.legend(['training set', 'validation set'], loc='upper right')\nplt.savefig(model_path + '/model.png')\n\n# Done\nprint('Done.')",
"Generating loss chart...\nDone.\n"
]
],
[
[
"## Print Performance Metrics",
"_____no_output_____"
]
],
[
[
"scores = model.evaluate_generator(validation_generator, STEP_SIZE_VALID, use_multiprocessing=True)\n\nmetrics_names = model.metrics_names\n\nfor i in range(len(model.metrics_names)):\n print(\"Metric: {} - {}\".format(metrics_names[i],scores[i]))\n",
"Metric: loss - 0.190782873646\nMetric: mean_squared_error - 0.190782873646\nMetric: mean_absolute_error - 0.330186681136\nMetric: mean_absolute_percentage_error - 28329829.3002\nMetric: cosine_proximity - -0.870888157895\n"
]
],
[
[
"## Compute Prediction Statistics",
"_____no_output_____"
]
],
[
[
"# Define image loading function\ndef load_images(dataframe):\n \n # initialize images array\n images = []\n \n for i in dataframe.index.values:\n name = data_set + '/' + dataframe.loc[i,'filename']\n center_image = cv2.imread(name)\n center_image = cv2.resize(center_image, (320,180))\n images.append(center_image)\n \n return np.array(images)\n \n# Load images \ntest_size = 200\ndf_test = df.sample(frac=1).reset_index(drop=True)\ndf_test = df_test.head(test_size)\n\ntest_images = load_images(df_test)\n\nbatch_size = 32\npreds = model.predict(test_images, batch_size=batch_size, verbose=1)\n\n#print(\"Preds: {} \\n\".format(preds))\n\ntestY = df_test.iloc[:,4].values\n\n#print(\"Labels: {} \\n\".format(testY))\n\ndf_testY = pd.Series(testY)\ndf_preds = pd.Series(preds.flatten)\n\n# Replace 0 angle values\nif df_testY.eq(0).any():\n df_testY.replace(0, 0.0001,inplace=True)\n\n# Calculate the difference\ndiff = preds.flatten() - df_testY\npercentDiff = (diff / testY) * 100\nabsPercentDiff = np.abs(percentDiff)\n\n# compute the mean and standard deviation of the absolute percentage\n# difference\nmean = np.mean(absPercentDiff)\nstd = np.std(absPercentDiff)\nprint(\"[INFO] mean: {:.2f}%, std: {:.2f}%\".format(mean, std))\n\n# Compute the mean and standard deviation of the difference\nprint(diff.describe())\n\n# Plot a histogram of the prediction errors\nnum_bins = 25\nhist, bins = np.histogram(diff, num_bins)\ncenter = (bins[:-1]+ bins[1:]) * 0.5\nplt.bar(center, hist, width=0.05)\nplt.title('Historgram of Predicted Error')\nplt.xlabel('Steering Angle')\nplt.ylabel('Number of predictions')\nplt.xlim(-2.0, 2.0)\nplt.plot(np.min(diff), np.max(diff))",
"200/200 [==============================] - 0s 381us/step\n[INFO] mean: 22781.22%, std: 143750.05%\ncount 200.000000\nmean -0.069993\nstd 0.367974\nmin -0.937922\n25% -0.275053\n50% -0.170840\n75% -0.080705\nmax 1.389061\ndtype: float64\n"
],
[
"# Plot a Scatter Plot of the Error\nplt.scatter(testY, preds)\nplt.xlabel('True Values ')\nplt.ylabel('Predictions ')\nplt.axis('equal')\nplt.axis('square')\nplt.xlim([-1.75,1.75])\nplt.ylim([-1.75,1.75])\nplt.plot([-1.75, 1.75], [-1.75, 1.75], color='k', linestyle='-', linewidth=.1)",
"_____no_output_____"
]
],
[
[
"## Plot a Prediction",
"_____no_output_____"
]
],
[
[
"# Plot the image with the actual and predicted steering angle\nindex = random.randint(0,df_test.shape[0]-1)\nimg_name = data_set + '/' + df_test.loc[index,'filename']\ncenter_image = cv2.imread(img_name)\ncenter_image = cv2.cvtColor(center_image,cv2.COLOR_RGB2BGR)\ncenter_image_mod = cv2.resize(center_image, (320,180)) \nplt.imshow(center_image_mod)\nplt.grid(False)\nplt.xlabel('Actual: {:.2f} Predicted: {:.2f}'.format(df_test.loc[index,'angle'],float(preds[index])))\nplt.show() \n",
"_____no_output_____"
]
],
[
[
"#Visualize the Network\n",
"_____no_output_____"
],
[
"##Show the Model Summary",
"_____no_output_____"
]
],
[
[
"model.summary()",
"_____no_output_____"
]
],
[
[
"##Access Individual Layers",
"_____no_output_____"
]
],
[
[
"# Creating a mapping of layer name ot layer details \n# We will create a dictionary layers_info which maps a layer name to its charcteristics\nlayers_info = {}\nfor i in model.layers:\n layers_info[i.name] = i.get_config()\n\n# Here the layer_weights dictionary will map every layer_name to its corresponding weights\nlayer_weights = {}\nfor i in model.layers:\n layer_weights[i.name] = i.get_weights()\n\npprint.pprint(layers_info['conv_5'])",
"_____no_output_____"
]
],
[
[
"##Visualize the Filters",
"_____no_output_____"
]
],
[
[
"# Visualize the first filter of each convolution layer\nlayers = model.layers\nlayer_ids = [2,3,4,6,7]\n\n#plot the filters\nfig,ax = plt.subplots(nrows=1,ncols=5)\nfor i in range(5):\n ax[i].imshow(layers[layer_ids[i]].get_weights()[0][:,:,:,0][:,:,0],cmap='gray')\n ax[i].set_title('Conv'+str(i+1))\n ax[i].set_xticks([])\n ax[i].set_yticks([])",
"_____no_output_____"
]
],
[
[
"##Visualize the Saliency Map\n",
"_____no_output_____"
]
],
[
[
"!pip install -I scipy==1.2.*\n!pip install git+https://github.com/raghakot/keras-vis.git -U\n\n# import specific functions from keras-vis package\nfrom vis.utils import utils\nfrom vis.visualization import visualize_saliency, visualize_cam, overlay",
"Collecting scipy==1.2.*\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/1d/f6/7c16d60aeb3694e5611976cb4f1eaf1c6b7f1e7c55771d691013405a02ea/scipy-1.2.2-cp27-cp27mu-manylinux1_x86_64.whl (24.8MB)\n\u001b[K |████████████████████████████████| 24.8MB 126kB/s \n\u001b[?25hCollecting numpy>=1.8.2\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/3a/5f/47e578b3ae79e2624e205445ab77a1848acdaa2929a00eeef6b16eaaeb20/numpy-1.16.6-cp27-cp27mu-manylinux1_x86_64.whl (17.0MB)\n\u001b[K |████████████████████████████████| 17.0MB 222kB/s \n\u001b[31mERROR: tensorflow 1.15.0 has requirement tensorflow-estimator==1.15.1, but you'll have tensorflow-estimator 1.15.0 which is incompatible.\u001b[0m\n\u001b[31mERROR: fastai 0.7.0 has requirement torch<0.4, but you'll have torch 1.3.1+cu100 which is incompatible.\u001b[0m\n\u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n\u001b[?25hInstalling collected packages: numpy, scipy\nSuccessfully installed numpy-1.16.6 scipy-1.2.2\n"
],
[
"# View a Single Image \nindex = random.randint(0,df.shape[0]-1)\nimg_name = data_set + '/' + df.loc[index,'filename']\n\nsample_image = cv2.imread(img_name)\nsample_image = cv2.cvtColor(sample_image,cv2.COLOR_RGB2BGR)\nsample_image_mod = cv2.resize(sample_image, (320,180))\nplt.imshow(sample_image_mod)\n \nlayer_idx = utils.find_layer_idx(model, 'conv_5')\n\ngrads = visualize_saliency(model, \n layer_idx, \n filter_indices=None, \n seed_input=sample_image_mod,\n grad_modifier='absolute',\n backprop_modifier='guided')\n\nplt.imshow(grads, alpha = 0.6)",
"_____no_output_____"
]
],
[
[
"# References:\n[Keras, Regression, and CNNs](https://www.pyimagesearch.com/2019/01/28/keras-regression-and-cnns/)\n\n[Regression with Keras](https://www.pyimagesearch.com/2019/01/21/regression-with-keras/)\n\n[How to use Keras fit and fit_generator](https://www.pyimagesearch.com/2018/12/24/how-to-use-keras-fit-and-fit_generator-a-hands-on-tutorial/)\n\n[Image Classification with Convolutional Neural Networks](https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l04c01_image_classification_with_cnns.ipynb#scrollTo=7MqDQO0KCaWS)\n\n[Keras Image Processing Documentation](https://keras.io/preprocessing/image/)\n\n[Attribution.ipynb](https://colab.research.google.com/github/idealo/cnn-exposed/blob/master/notebooks/Attribution.ipynb#scrollTo=jqSOW0pQniCw)\n\n[A Guide to Understanding Convolutional Neural Networks (CNNs) using Visualization](https://www.analyticsvidhya.com/blog/2019/05/understanding-visualizing-neural-networks/)\n\n[Visualizing attention on self driving car](https://github.com/raghakot/keras-vis/blob/master/applications/self_driving/visualize_attention.ipynb)\n\n[Exploring Image Data Augmentation with Keras and Tensorflow](https://towardsdatascience.com/exploring-image-data-augmentation-with-eras-and-tensorflow-a8162d89b844\n)\n\n[Tensorboard Documentation](https://keras.io/callbacks/#tensorboard)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e7ab7bc63374f50bc9c290b30e38cc1ee2a3ad0b | 24,156 | ipynb | Jupyter Notebook | yolov5/YOLOv5_Task1.ipynb | sosodoit/yolov5 | bd8489c9aad983efcbbf80eeb4ff2ab572ae5842 | [
"MIT"
] | null | null | null | yolov5/YOLOv5_Task1.ipynb | sosodoit/yolov5 | bd8489c9aad983efcbbf80eeb4ff2ab572ae5842 | [
"MIT"
] | null | null | null | yolov5/YOLOv5_Task1.ipynb | sosodoit/yolov5 | bd8489c9aad983efcbbf80eeb4ff2ab572ae5842 | [
"MIT"
] | null | null | null | 31.868074 | 224 | 0.451151 | [
[
[
"<a href=\"https://colab.research.google.com/github/sosodoit/yolov5/blob/main/YOLOv5_Task1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"<ul>Task 0 (YOLOv5 note)\n<dl>용어, 개념, 궁금한 문제들 기록 (<a href=\"https://colab.research.google.com/drive/1u8S1vF5g9dSR8oDBJxjqiY9AH0C43jjF?usp=sharing\">link</a>)</dl>\n</ul>\n\n<ol type=\"I\">\n<strong>\n <li>Task 1 (사전작업)</li>\n <dl>YOLOv5 모델작업에 들어가기전, 데이터를 확인하고 정제한 작업 내용을 담고 있습니다(here)</dl>\n <ul type=\"square\">\n <li>Putting data into a folder</li>\n <li>Convert the Annotations into the YOLOv5 Format</li>\n <li>Testing the annotations</li>\n <li>Partition the Dataset</li>\n </ul>\n</strong>\n <li>Task 2 (학습)</li>\n <dl>YOLOv5 환경설정부터 학습한 작업내용을 담고 있습니다(<a href=\"https://colab.research.google.com/drive/1zHrTaAlsT4tDxZhGhUYK1ZIGjtrrvv-y?usp=sharing\">link</a>)</dl>\n <ul type=\"square\">\n <li>Set up the environment</li>\n <li>Data Config File</li>\n <li>Hyper-parameter Config File</li>\n <li>Custom Network Architecture</li>\n <li>Train the Model</li>\n </ul>\n <li>Task 3 (결과)</li>\n <dl>학습 후 테스트와 성능평가의 결과내용을 담고 있습니다(<a href=\"https://colab.research.google.com/drive/1---iUi0KXpVVjn95BNmsDyScnzLmFY6p?usp=sharing\">link</a>)</dl>\n <ul type=\"square\">\n <li>Test</li>\n <li>Computing the mAP on test dataset</li>\n </ul>\n</ol>",
"_____no_output_____"
],
[
"---\n# 수정된 작업(up-to-date)",
"_____no_output_____"
],
[
"**1. Putting data into a folder**\n<ul>나눠진 데이터를 작업할 폴더에 images와 labels폴더 아래로 모음</ul>\n\n**Original Data**\n\n- [원천]도심로_주간일출_맑음_45_전방, [라벨]도심로_주간일출_맑음_45_전방\n- [원천]도심로_주간일출_맑음_60_전방, [라벨]도심로_주간일출_맑음_60_전방\n- [원천]도심로_주간일출_맑음_120_전방, [라벨]도심로_주간일출_맑음_120_전방\n<dl>총 2318개의 이미지와 라벨링된 xml</dl>\n\n**Datafile Directory**\n\n- dataset\n - images\n - train\n - val\n - labels\n - train\n - val",
"_____no_output_____"
],
[
"**2. Convert the Annotations into the YOLOv5 Format**\n\n주의: dataset폴더가 있는 상위폴더 경로에서 진행해야함\n\n``` python\n#ex\n%cd /content/gdrive/MyDrive/객체탐지\n!ls\n# dataset\n```\n",
"_____no_output_____"
]
],
[
[
"############ 경로설정 ############\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n%cd /content/gdrive/MyDrive/객체탐지\n!ls",
"_____no_output_____"
],
[
"############ xml 파일 확인 ############\n#!cat dataset/labels/Bright_20130218_153731_000210_v001_1.xml",
"_____no_output_____"
],
[
"############ XML파일에서 정보 긁어오는 함수 ############\ndef extract_info_from_xml(xml_file):\n root = ET.parse(xml_file).getroot()\n \n info_dict = {}\n info_dict['bboxes'] = []\n\n for elem in root:\n if elem.tag == \"filename\":\n info_dict['filename'] = elem.text\n \n elif elem.tag == \"size\":\n image_size = []\n for subelem in elem:\n image_size.append(int(subelem.text))\n \n info_dict['image_size'] = tuple(image_size)\n \n elif elem.tag == \"object\":\n bbox = {}\n for subelem in elem:\n if subelem.tag == \"name\":\n bbox[\"class\"] = subelem.text\n \n elif subelem.tag == \"bndbox\":\n for subsubelem in subelem:\n bbox[subsubelem.tag] = int(subsubelem.text) \n info_dict['bboxes'].append(bbox)\n \n return info_dict",
"_____no_output_____"
],
[
"############ 긁어온 xml 정보 확인 ############\nprint(extract_info_from_xml('dataset/labels/Bright_20130218_153731_000210_v001_1.xml'))",
"_____no_output_____"
],
[
"############ 클래스명과 클래스ID dictionary 만듬 ############\nclass_name_to_id_mapping = {\"Vehicle_Car\": 0,\n \"Vehicle_Bus\": 1,\n \"Vehicle_Motorcycle\": 2,\n \"Vehicle_Unknown\": 3}",
"_____no_output_____"
],
[
"############ yolov5 형식으로 변환하는 함수 ############\ndef convert_to_yolov5(info_dict):\n global class_id\n print_buffer = []\n \n for b in info_dict[\"bboxes\"]:\n try:\n class_id = class_name_to_id_mapping[b[\"class\"]]\n except KeyError:\n print(\"Invalid Class. Must be one from \", class_name_to_id_mapping.keys())\n \n b_center_x = (b[\"xmin\"] + b[\"xmax\"]) / 2 \n b_center_y = (b[\"ymin\"] + b[\"ymax\"]) / 2\n b_width = (b[\"xmax\"] - b[\"xmin\"])\n b_height = (b[\"ymax\"] - b[\"ymin\"])\n \n image_w, image_h, image_c = info_dict[\"image_size\"] \n b_center_x /= image_w \n b_center_y /= image_h \n b_width /= image_w \n b_height /= image_h \n \n print_buffer.append(\"{} {:.3f} {:.3f} {:.3f} {:.3f}\".format(class_id, b_center_x, b_center_y, b_width, b_height))\n \n save_file_name = os.path.join(\"dataset/labels\", info_dict[\"filename\"].replace(\"jpg\", \"txt\"))\n \n print(\"\\n\".join(print_buffer), file= open(save_file_name, \"w\"))",
"_____no_output_____"
],
[
"############ 함수실행(포맷)을 위해 xml 파일이름 가져오기 ############\nannotations = [os.path.join('dataset/labels', x) for x in os.listdir('dataset/labels') if x[-3:] == \"xml\"]\nannotations.sort()\n\n############ 변환 후 저장(시간 조금 소요) ############\nfor ann in tqdm(annotations):\n info_dict = extract_info_from_xml(ann)\n convert_to_yolov5(info_dict)\nannotations = [os.path.join('dataset/labels', x) for x in os.listdir('dataset/labels') if x[-3:] == \"txt\"]",
"_____no_output_____"
]
],
[
[
"**3. Testing the annotations**\n\nxml이 잘 변환되어서 bb 잘 잡는지 테스트",
"_____no_output_____"
]
],
[
[
"%cd /content/gdrive/MyDrive/객체탐지",
"_____no_output_____"
],
[
"random.seed(0)\n\nclass_id_to_name_mapping = dict(zip(class_name_to_id_mapping.values(), class_name_to_id_mapping.keys()))\n\ndef plot_bounding_box(image, annotation_list):\n annotations = np.array(annotation_list)\n w, h = image.size\n \n plotted_image = ImageDraw.Draw(image)\n\n transformed_annotations = np.copy(annotations)\n transformed_annotations[:,[1,3]] = annotations[:,[1,3]] * w\n transformed_annotations[:,[2,4]] = annotations[:,[2,4]] * h \n \n transformed_annotations[:,1] = transformed_annotations[:,1] - (transformed_annotations[:,3] / 2)\n transformed_annotations[:,2] = transformed_annotations[:,2] - (transformed_annotations[:,4] / 2)\n transformed_annotations[:,3] = transformed_annotations[:,1] + transformed_annotations[:,3]\n transformed_annotations[:,4] = transformed_annotations[:,2] + transformed_annotations[:,4]\n \n for ann in transformed_annotations:\n obj_cls, x0, y0, x1, y1 = ann\n plotted_image.rectangle(((x0,y0), (x1,y1)))\n \n plotted_image.text((x0, y0 - 10), class_id_to_name_mapping[(int(obj_cls))])\n \n plt.imshow(np.array(image))\n plt.show()\n\n# Get any random annotation file \nannotation_file = random.choice(annotations)\nwith open(annotation_file, \"r\") as file:\n annotation_list = file.read().split(\"\\n\")[:-1]\n annotation_list = [x.split(\" \") for x in annotation_list]\n annotation_list = [[float(y) for y in x ] for x in annotation_list]\n\n#Get the corresponding image file\nimage_file = annotation_file.replace(\"labels\", \"images\").replace(\"txt\", \"jpg\")\nassert os.path.exists(image_file)\n\n#Load the image\nimage = Image.open(image_file)\n\n#Plot the Bounding Box\nplot_bounding_box(image, annotation_list)",
"_____no_output_____"
]
],
[
[
"**4. Partition the Dataset**\n\nYOLOv5 학습 진행 하기전, train-valid dataset을 나누는 작업을 진행",
"_____no_output_____"
]
],
[
[
"########## 사진과 라벨링 파일명 읽어오기 ##########\nimages = [os.path.join('dataset/images', x) for x in os.listdir('dataset/images')]\nannotations = [os.path.join('dataset/labels', x) for x in os.listdir('dataset/labels') if x[-3:] == \"txt\"]\n\nimages.sort()\nannotations.sort()",
"_____no_output_____"
],
[
"########## train-valid 8:2 비율로 데이터셋 나누기 ##########\ntrain_images, val_images, train_annotations, val_annotations = train_test_split(images, annotations, test_size = 0.2, random_state = 2000)",
"_____no_output_____"
],
[
"########## 나눠진 데이터를 각각 train, val 폴더에 옮겨줌 ##########\n!mkdir dataset/images/train dataset/images/val dataset/labels/train dataset/labels/val\n\ndef move_files_to_folder(list_of_files, destination_folder):\n for f in list_of_files:\n try:\n shutil.move(f, destination_folder)\n except:\n print(f)\n assert False\n\nmove_files_to_folder(train_images, 'dataset/images/train')\nmove_files_to_folder(val_images, 'dataset/images/val/')\nmove_files_to_folder(train_annotations, 'dataset/labels/train/')\nmove_files_to_folder(val_annotations, 'dataset/labels/val/')",
"_____no_output_____"
]
],
[
[
"---\n# 과거작업",
"_____no_output_____"
],
[
"## [1] Rename",
"_____no_output_____"
]
],
[
[
"# 1) 경로설정\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n%cd /content/gdrive/MyDrive/객체탐지/dataset",
"_____no_output_____"
],
[
"# 2) 필요한 라이브러리 임포트\nimport os\nimport torch\nfrom IPython.display import Image\nimport os \nimport random\nimport shutil\nfrom sklearn.model_selection import train_test_split\nimport xml.etree.ElementTree as ET\nfrom xml.dom import minidom\nfrom tqdm import tqdm\nfrom PIL import Image, ImageDraw\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# 3) 이미지 폴더 접근\n## 주어진 디렉토리에 있는 항목들의 이름을 담고 있는 리스트를 반환합니다.\n## 리스트는 임의의 순서대로 나열됩니다.\nimages = os.listdir('origin/images')\nimages.sort()\n\nlabels = os.listdir('origin/labels')\nlabels.sort()",
"_____no_output_____"
],
[
"# 파일명 확인\nprint(images[1200:1204])\nprint(labels[1200:1204])",
"['3_20201019_165355_000570.jpg', '3_20201019_165355_000600.jpg', '3_20201019_165355_000630.jpg', '3_20201019_171412_000360.jpg']\n['3_20201019_165355_000570_v001_1.xml', '3_20201019_165355_000600_v001_1.xml', '3_20201019_165355_000630_v001_1.xml', '3_20201019_171412_000360_v001_1.xml']\n"
],
[
"file_path = 'origin/images'\nresult_path = 'images'\nfile_names = images\n\nfile2_path = 'origin/labels'\nresult2_path = 'labels'\nfile2_names = labels",
"_____no_output_____"
],
[
"# 4) 차례대로 파일 이름을 변경하고 저장 \".jpg\"\n## os.rename(src, dst) 메서드는 파일 또는 디렉토리(폴더) src의 이름을 dst로 변경합니다.\ni = 1\nfor name in file_names:\n src = os.path.join(file_path, name)\n dst = str(i) + '.jpg'\n dst = os.path.join(result_path, dst)\n os.rename(src, dst)\n i += 1",
"_____no_output_____"
],
[
"# 4) 차례대로 파일 이름을 변경하고 저장 \".xml\"\n## os.rename(src, dst) 메서드는 파일 또는 디렉토리(폴더) src의 이름을 dst로 변경합니다.\ni = 1\nfor name in file2_names:\n src = os.path.join(file2_path, name)\n dst = str(i) + '.xml'\n dst = os.path.join(result2_path, dst)\n os.rename(src, dst)\n i += 1",
"_____no_output_____"
]
],
[
[
"## [2] XmlToTxt\n- https://github.com/Isabek/XmlToTxt\n\n## [3] Devide",
"_____no_output_____"
],
[
"## [4] 사진 거르기\n\nclass 1,2,3,4 하나라도 있으면 살리고 없으면 제거.",
"_____no_output_____"
]
],
[
[
"# 1) 경로설정\n%cd /content/gdrive/MyDrive/객체탐지/dataset",
"_____no_output_____"
],
[
"# 2) 필요한 라이브러리 임포트\nimport os\nfrom glob import glob",
"_____no_output_____"
],
[
"img_list = glob('labels/train/*.txt')\nval_img_list = glob('labels/val/*.txt')\n\nprint(len(img_list))\nprint(len(val_img_list))",
"_____no_output_____"
],
[
"four = [] #체크를 위한 리스트 생성\n\n## 여기서 val_img_list / img_list 두개를 변경하면서 내부의 다른 index를 제거해주어야 한다.\nfor x in img_list:\n four = [] #새로운 라벨링 데이터 .txt를 불렀을 때 초기화를 위함\n f = open(x, 'r')\n lines = f.readlines() \n for line in lines: #읽어들인 모든 데이터를 한 줄씩 불러옴\n\n # 1,2,3,4 없으면 모두 제거하기 위해 check.\n # 1:Vehicle_Car 2:Vehicle_Bus 3:Vehicle_Motorcycle 4:Vehicle_Unknown\n if (int(line.split(' ')[0]) == 1) or (int(line.split(' ')[0]) == 2) or (int(line.split(' ')[0]) == 3) or (int(line.split(' ')[0]) == 4):\n four.append(line)\n\n # 만약 넷 중 하나도 없는 사진이 있다면 제거.\n if len(four) == 0:\n print(\"four 내용 없음\")\n os.remove(x.split('.txt')[0].replace('labels','images')+'.jpg')\n os.remove(x)\n \n f.close()\n \n #두 개가 존재한다면 다시 두 개만 불러오도록 재정의.\n #다시 쓰는이유는 하나의 사진에 1,2,3,4 이외에 다른 값도 있는 사진을 수정하기 위함.\n #w를 이용해 재정의하면 원래 txt파일에 존재하는 모든 수치를 제거하고 처음부터 적는다. 이를 이용함.\n if len(four) >= 1:\n print(\"four 씀: \", len(four))\n w = open(x,'w')\n w.writelines(four)\n w.close()",
"_____no_output_____"
],
[
"four = []\ncount1 = 0\ncount2 = 0\ncount3 = 0\ncount4 = 0\n\nfor x in val_img_list:\n four = []\n f = open(x, 'r')\n lines = f.readlines()\n\n for line in lines:\n if line.split(' ')[0] == '1':\n four.append(line.replace(line.split(' ')[0], '0'))\n count1 += 1\n elif line.split(' ')[0] == '2':\n four.append(line.replace(line.split(' ')[0], '1'))\n count2 += 1\n elif line.split(' ')[0] == '3':\n four.append(line.replace(line.split(' ')[0], '2'))\n count3 += 1\n elif line.split(' ')[0] == '4':\n four.append(line.replace(line.split(' ')[0], '3'))\n count4 += 1\n \n f.close()\n\n w = open(x,'w')\n w.writelines(four)\n w.close()\n\nprint(' 1:Vehicle_Car %d 개 변환 완료 ' % count1 )\nprint(' 2:Vehicle_Bus %d 개 변환 완료 ' % count2 )\nprint(' 3:Vehicle_Motorcycle %d 개 변환 완료 ' % count3 )\nprint(' 4:Vehicle_Unknown %d 개 변환 완료 ' % count4 )\n\n## val_img_list\n# 1:Vehicle_Car 2155 개 변환 완료 \n# 2:Vehicle_Bus 109 개 변환 완료 \n# 3:Vehicle_Motorcycle 195 개 변환 완료 \n# 4:Vehicle_Unknown 579 개 변환 완료 \n\n## img_list (train)\n# 1:Vehicle_Car 8967 개 변환 완료 \n# 2:Vehicle_Bus 399 개 변환 완료 \n# 3:Vehicle_Motorcycle 790 개 변환 완료 \n# 4:Vehicle_Unknown 2395 개 변환 완료 ",
"_____no_output_____"
]
],
[
[
"# **Issue**\n\n파일명이 복잡해서 간단하게 바꾼 후 구분할 클래스 4종이 하나라도 안들어 있는 사진이 있다면 거르는 작업을 통해 학습 성능을 높여 볼려고 생각하고 진행했다. \n\n이 때, 굉장히 이상하게 detection되고 있는 것을 확인하고 문제점을 찾아보니 파일명을 rename하는 과정에서 xml에 있는 filename과 rename된 파일이름이 달라지면서 학습과정에 문제가 발생했다. 또한, 걸러진 사진이 10개도 되지 않아서 정확도에 주는 영향은 미미했다.\n\n이 작업을 훗날 다시 하게된다면 아래 순서로 해야할 것이다.\n1. xml 사진 거르고\n2. xml 변환 한 다음에\n3. xml 파일명 수정시 filename도 함께 수정.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7ab8d15a3cba4435ab7d9f454a5cef92492de5d | 4,832 | ipynb | Jupyter Notebook | DA Lab/1806554_da_lab_records_all.ipynb | ganeshbhandarkar/College-Labs-And-Projects | f99a99cda97a0e3d220ad5b6e31fc02d7d77ee68 | [
"MIT"
] | null | null | null | DA Lab/1806554_da_lab_records_all.ipynb | ganeshbhandarkar/College-Labs-And-Projects | f99a99cda97a0e3d220ad5b6e31fc02d7d77ee68 | [
"MIT"
] | null | null | null | DA Lab/1806554_da_lab_records_all.ipynb | ganeshbhandarkar/College-Labs-And-Projects | f99a99cda97a0e3d220ad5b6e31fc02d7d77ee68 | [
"MIT"
] | 1 | 2020-11-05T04:25:11.000Z | 2020-11-05T04:25:11.000Z | 22.474419 | 90 | 0.431912 | [
[
[
"# 1806554 Ganesh Bhandarkar (DA LAB RECORD)",
"_____no_output_____"
],
[
"## LAB 1",
"_____no_output_____"
]
],
[
[
"print(\"Hello World\")\ndate()\nprint(mean(1:5))\nx <- 1\nx\napple <-c('red','green',\"yellow\")\nprint(apple)\nprint(class(apple))\nlist1 <-list(c(2,5,3),21.3,sin)\nM = matrix(c('a','a','b','c','b','a'),nrow=2,ncol=3,byrow =TRUE) \n\napple_colors <-c('green','green','yellow','red','red','red','green')\nfactor_apple <-factor(apple_colors)\nprint(factor_apple)\nprint(nlevels(factor_apple))\n\nBMI <-data.frame(gender =c(\"Male\",\"Male\",\"Female\"),\n height =c(152,171.5,165),\n weight =c(81,93,78),\n age=c(42,38,26))\nprint(BMI)\n\nvar_x <-\"Hello\"\ncat(\"The class of var_x is \",class(var_x),\"\\n\")\nvar_x <-34.5\ncat(\"Now the class of var_x is \",class(var_x),\"\\n\")\nvar_x <-27L\ncat(\" Next the class of var_x becomes \",class(var_x),\"\\n\")\n\n\nv <-c(2,5.5,6)\nt <-c(8,3,4)\nprint(v+t)\nprint(v-t)\nprint(v*t)\nprint(v/t)\nprint(v%%t) # Give the remainder of the first vector with the second\nprint(v%/%t) # Give the result of division of first vector with second (quotient)\nprint(v^t) # The first vector raised to the exponent of second vector\n\n\nv <-c(2,5.5,6)\nt <-c(8,3,4)\nprint(v>t)\nprint(v<t)\nprint(v==t)\nprint(v<=t)\nprint(v>=t)\nprint(v!=t)\n\nv <-c(2,5.5,6)\nu = c(18,13,14)\nprint(v)\nprint(t)\nprint(u)\n\nc(2,5.5,6) -> v\nprint(v)\nprint(t)\n\nv <-2:8\nprint(v)",
"[1] \"Hello World\"\n"
]
],
[
[
"## LAB 2",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7ab93ed8d87ffa0048f272704cbd1f0998303e0 | 19,595 | ipynb | Jupyter Notebook | examples/batch/argo-workflows-batch/README.ipynb | Syakyr/seldon-core | 938a8ffd19fc321eed4c7347ef56cc0b59f448dd | [
"Apache-2.0"
] | null | null | null | examples/batch/argo-workflows-batch/README.ipynb | Syakyr/seldon-core | 938a8ffd19fc321eed4c7347ef56cc0b59f448dd | [
"Apache-2.0"
] | 183 | 2020-08-05T21:17:14.000Z | 2021-08-02T06:32:24.000Z | examples/batch/argo-workflows-batch/README.ipynb | hmonteiro/seldon-core | 2305d73927b135af1627f6e921cfb51a65fec374 | [
"Apache-2.0"
] | null | null | null | 44.534091 | 1,571 | 0.578362 | [
[
[
"# Batch processing with Argo Worfklows\n\nIn this notebook we will dive into how you can run batch processing with Argo Workflows and Seldon Core.\n\nDependencies:\n\n* Seldon core installed as per the docs with an ingress\n* Minio running in your cluster to use as local (s3) object storage\n* Argo Workfklows installed in cluster (and argo CLI for commands)\n",
"_____no_output_____"
],
[
"### Setup\n\n#### Install Seldon Core\nUse the notebook to [set-up Seldon Core with Ambassador or Istio Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html).\n\nNote: If running with KIND you need to make sure do follow [these steps](https://github.com/argoproj/argo/issues/2376#issuecomment-595593237) as workaround to the `/.../docker.sock` known issue.\n\n#### Set up Minio in your cluster\nUse the notebook to [set-up Minio in your cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/minio_setup.html).\n\n#### Copy the Minio Secret to namespace\n\nWe need to re-use the minio secret for the batch job, so this can be done by just copying the minio secret created in the `minio-system`\n\nThe command below just copies the secred with the name \"minio\" from the minio-system namespace to the default namespace.",
"_____no_output_____"
]
],
[
[
"!kubectl get secret minio -n minio-system -o json | jq '{apiVersion,data,kind,metadata,type} | .metadata |= {\"annotations\", \"name\"}' | kubectl apply -n default -f -",
"secret/minio created\r\n"
]
],
[
[
"#### Install Argo Workflows\nYou can follow the instructions from the official [Argo Workflows Documentation](https://github.com/argoproj/argo#quickstart).\n\nYou also need to make sure that argo has permissions to create seldon deployments - for this you can just create a default-admin rolebinding as follows:",
"_____no_output_____"
]
],
[
[
"!kubectl create rolebinding default-admin --clusterrole=admin --serviceaccount=default:default",
"rolebinding.rbac.authorization.k8s.io/default-admin created\r\n"
]
],
[
[
"### Create some input for our model\n\nWe will create a file that will contain the inputs that will be sent to our model",
"_____no_output_____"
]
],
[
[
"mkdir -p assets/",
"_____no_output_____"
],
[
"with open(\"assets/input-data.txt\", \"w\") as f:\n for i in range(10000):\n f.write('[[1, 2, 3, 4]]\\n')",
"_____no_output_____"
]
],
[
[
"#### Check the contents of the file",
"_____no_output_____"
]
],
[
[
"!wc -l assets/input-data.txt\n!head assets/input-data.txt",
"10000 assets/input-data.txt\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n[[1, 2, 3, 4]]\n"
]
],
[
[
"#### Upload the file to our minio",
"_____no_output_____"
]
],
[
[
"!mc mb minio-seldon/data\n!mc cp assets/input-data.txt minio-seldon/data/",
"\u001b[m\u001b[32;1mBucket created successfully `minio-seldon/data`.\u001b[0m\n...-data.txt: 146.48 KiB / 146.48 KiB ┃▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┃ 2.14 MiB/s 0s\u001b[0m\u001b[0m\u001b[m\u001b[32;1m"
]
],
[
[
"#### Create Argo Workflow\n\nIn order to create our argo workflow we have made it simple so you can leverage the power of the helm charts.\n\nBefore we dive into the contents of the full helm chart, let's first give it a try with some of the settings.\n\nWe will run a batch job that will set up a Seldon Deployment with 10 replicas and 100 batch client workers to send requests.",
"_____no_output_____"
]
],
[
[
"!helm template seldon-batch-workflow helm-charts/seldon-batch-workflow/ \\\n --set workflow.name=seldon-batch-process \\\n --set seldonDeployment.name=sklearn \\\n --set seldonDeployment.replicas=10 \\\n --set seldonDeployment.serverWorkers=1 \\\n --set seldonDeployment.serverThreads=10 \\\n --set batchWorker.workers=100 \\\n --set batchWorker.payloadType=ndarray \\\n --set batchWorker.dataType=data \\\n | argo submit -",
"Name: seldon-batch-process\r\nNamespace: default\r\nServiceAccount: default\r\nStatus: Pending\r\nCreated: Thu Aug 06 08:21:47 +0100 (now)\r\n"
],
[
"!argo list",
"NAME STATUS AGE DURATION PRIORITY\r\nseldon-batch-process Running 2s 2s 0\r\n"
],
[
"!argo get seldon-batch-process",
"Name: seldon-batch-process\r\nNamespace: default\r\nServiceAccount: default\r\nStatus: Succeeded\r\nCreated: Thu Aug 06 08:03:31 +0100 (1 minute ago)\r\nStarted: Thu Aug 06 08:03:31 +0100 (1 minute ago)\r\nFinished: Thu Aug 06 08:04:54 +0100 (26 seconds ago)\r\nDuration: 1 minute 23 seconds\r\n\r\n\u001b[39mSTEP\u001b[0m PODNAME DURATION MESSAGE\r\n \u001b[32m✔\u001b[0m seldon-batch-process (seldon-batch-process) \r\n ├---\u001b[32m✔\u001b[0m create-seldon-resource (create-seldon-resource-template) seldon-batch-process-3626514072 2s \r\n ├---\u001b[32m✔\u001b[0m wait-seldon-resource (wait-seldon-resource-template) seldon-batch-process-2052519094 28s \r\n ├---\u001b[32m✔\u001b[0m download-object-store (download-object-store-template) seldon-batch-process-1257652469 2s \r\n ├---\u001b[32m✔\u001b[0m process-batch-inputs (process-batch-inputs-template) seldon-batch-process-2033515954 39s \r\n └---\u001b[32m✔\u001b[0m upload-object-store (upload-object-store-template) seldon-batch-process-2123074048 3s \r\n"
],
[
"!argo logs -w seldon-batch-process || argo logs seldon-batch-process # The 2nd command is for argo 2.8+",
"\u001b[35mcreate-seldon-resource\u001b[0m:\ttime=\"2020-08-06T07:21:48.400Z\" level=info msg=\"Starting Workflow Executor\" version=v2.9.3\r\n\u001b[35mcreate-seldon-resource\u001b[0m:\ttime=\"2020-08-06T07:21:48.404Z\" level=info msg=\"Creating a docker executor\"\r\n\u001b[35mcreate-seldon-resource\u001b[0m:\ttime=\"2020-08-06T07:21:48.404Z\" level=info msg=\"Executor (version: v2.9.3, build_date: 2020-07-18T19:11:19Z) initialized (pod: default/seldon-batch-process-3626514072) with template:\\n{\\\"name\\\":\\\"create-seldon-resource-template\\\",\\\"arguments\\\":{},\\\"inputs\\\":{},\\\"outputs\\\":{},\\\"metadata\\\":{},\\\"resource\\\":{\\\"action\\\":\\\"create\\\",\\\"manifest\\\":\\\"apiVersion: machinelearning.seldon.io/v1\\\\nkind: SeldonDeployment\\\\nmetadata:\\\\n name: \\\\\\\"sklearn\\\\\\\"\\\\n namespace: default\\\\n ownerReferences:\\\\n - apiVersion: argoproj.io/v1alpha1\\\\n blockOwnerDeletion: true\\\\n kind: Workflow\\\\n name: \\\\\\\"seldon-batch-process\\\\\\\"\\\\n uid: \\\\\\\"401c8bc0-0ff0-4f7b-94ba-347df5c786f9\\\\\\\"\\\\nspec:\\\\n name: \\\\\\\"sklearn\\\\\\\"\\\\n predictors:\\\\n - componentSpecs:\\\\n - spec:\\\\n containers:\\\\n - name: classifier\\\\n env:\\\\n - name: GUNICORN_THREADS\\\\n value: 10\\\\n - name: GUNICORN_WORKERS\\\\n value: 1\\\\n resources:\\\\n requests:\\\\n cpu: 50m\\\\n memory: 100Mi\\\\n limits:\\\\n cpu: 50m\\\\n memory: 1000Mi\\\\n graph:\\\\n children: []\\\\n implementation: SKLEARN_SERVER\\\\n modelUri: gs://seldon-models/sklearn/iris\\\\n name: classifier\\\\n name: default\\\\n replicas: 10\\\\n \\\\n\\\"}}\"\r\n\u001b[35mcreate-seldon-resource\u001b[0m:\ttime=\"2020-08-06T07:21:48.404Z\" level=info msg=\"Loading manifest to /tmp/manifest.yaml\"\r\n\u001b[35mcreate-seldon-resource\u001b[0m:\ttime=\"2020-08-06T07:21:48.405Z\" level=info msg=\"kubectl create -f /tmp/manifest.yaml -o json\"\r\n\u001b[35mcreate-seldon-resource\u001b[0m:\ttime=\"2020-08-06T07:21:48.954Z\" level=info msg=default/SeldonDeployment.machinelearning.seldon.io/sklearn\r\n\u001b[35mcreate-seldon-resource\u001b[0m:\ttime=\"2020-08-06T07:21:48.954Z\" level=info msg=\"No output parameters\"\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 0 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 1 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 2 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 3 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 4 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 5 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 6 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 7 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 8 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tWaiting for deployment \"sklearn-default-0-classifier\" rollout to finish: 9 of 10 updated replicas are available...\r\n\u001b[32mwait-seldon-resource\u001b[0m:\tdeployment \"sklearn-default-0-classifier\" successfully rolled out\r\n\u001b[34mdownload-object-store\u001b[0m:\tAdded `minio-local` successfully.\r\n\u001b[34mdownload-object-store\u001b[0m:\t`minio-local/data/input-data.txt` -> `/assets/input-data.txt`\r\n\u001b[34mdownload-object-store\u001b[0m:\tTotal: 0 B, Transferred: 146.48 KiB, Speed: 31.81 MiB/s\r\n\u001b[39mprocess-batch-inputs\u001b[0m:\tElapsed time: 35.089903831481934\r\n\u001b[31mupload-object-store\u001b[0m:\tAdded `minio-local` successfully.\r\n\u001b[31mupload-object-store\u001b[0m:\t`/assets/output-data.txt` -> `minio-local/data/output-data-401c8bc0-0ff0-4f7b-94ba-347df5c786f9.txt`\r\n\u001b[31mupload-object-store\u001b[0m:\tTotal: 0 B, Transferred: 2.75 MiB, Speed: 105.34 MiB/s\r\n"
]
],
[
[
"### Check output in object store\n\nWe can now visualise the output that we obtained in the object store.\n\nFirst we can check that the file is present:",
"_____no_output_____"
]
],
[
[
"import json\nwf_arr = !argo get seldon-batch-process -o json\nwf = json.loads(\"\".join(wf_arr))\nWF_ID = wf[\"metadata\"][\"uid\"]\nprint(f\"Workflow ID is {WF_ID}\")",
"Workflow ID is 401c8bc0-0ff0-4f7b-94ba-347df5c786f9\n"
],
[
"!mc ls minio-seldon/data/output-data-\"$WF_ID\".txt",
"\u001b[m\u001b[32m[2020-08-06 08:23:07 BST] \u001b[0m\u001b[33m 2.7MiB \u001b[0m\u001b[1moutput-data-401c8bc0-0ff0-4f7b-94ba-347df5c786f9.txt\u001b[0m\r\n\u001b[0m"
]
],
[
[
"Now we can output the contents of the file created using the `mc head` command.",
"_____no_output_____"
]
],
[
[
"!mc cp minio-seldon/data/output-data-\"$WF_ID\".txt assets/output-data.txt\n!head assets/output-data.txt",
"...786f9.txt: 2.75 MiB / 2.75 MiB ┃▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┃ 26.55 MiB/s 0s\u001b[0m\u001b[0m\u001b[m\u001b[32;1m{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 2.0, \"batch_instance_id\": \"95e7df56-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 0.0, \"batch_instance_id\": \"95e77c3c-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 1.0, \"batch_instance_id\": \"95e787ae-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 3.0, \"batch_instance_id\": \"95e80990-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 4.0, \"batch_instance_id\": \"95e83cf8-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 6.0, \"batch_instance_id\": \"95e85990-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 8.0, \"batch_instance_id\": \"95e85e40-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 7.0, \"batch_instance_id\": \"95e85c1a-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 10.0, \"batch_instance_id\": \"95e864c6-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n{\"data\": {\"names\": [\"t:0\", \"t:1\", \"t:2\"], \"ndarray\": [[0.0006985194531162841, 0.003668039039435755, 0.9956334415074478]]}, \"meta\": {\"tags\": {\"tags\": {\"batch_id\": \"95e6e8d0-d7b5-11ea-b00e-ea443eed4c19\", \"batch_index\": 5.0, \"batch_instance_id\": \"95e83f8c-d7b5-11ea-b5f2-ea443eed4c19\"}}}}\n"
],
[
"!argo delete seldon-batch-process",
"Workflow 'seldon-batch-process' deleted\r\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7aba29ae50b706d5ada9f7ca8bc7267af9b5548 | 183,317 | ipynb | Jupyter Notebook | Mixture/Mixture demo1.ipynb | balarsen/pymc_learning | e4a077d492af6604a433433e64b835ce4ed0333a | [
"BSD-3-Clause"
] | null | null | null | Mixture/Mixture demo1.ipynb | balarsen/pymc_learning | e4a077d492af6604a433433e64b835ce4ed0333a | [
"BSD-3-Clause"
] | null | null | null | Mixture/Mixture demo1.ipynb | balarsen/pymc_learning | e4a077d492af6604a433433e64b835ce4ed0333a | [
"BSD-3-Clause"
] | 1 | 2017-05-23T16:38:55.000Z | 2017-05-23T16:38:55.000Z | 537.58651 | 43,900 | 0.725465 | [
[
[
"# Can I undetand what a Normal mixture model is and how to use it?\n",
"_____no_output_____"
]
],
[
[
"Los Alamos National Laboratory\nISR-1 Space Science and Applications\nBrian Larsen, Ph.D.\[email protected]\n505-665-7691",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n#%matplotlib notebook\n%load_ext version_information\n%load_ext autoreload\n",
"_____no_output_____"
],
[
"import datetime\nimport os\nimport sys\nimport warnings\n\nwarnings.simplefilter(\"ignore\")\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport spacepy.datamodel as dm\nimport spacepy.plot as spp\nimport spacepy.toolbox as tb\nimport tqdm\nimport pymc3 as mc3\n\n%version_information matplotlib, numpy, pandas",
"\nBad key \"axes.color_cycle\" on line 17 in\n/Users/balarsen/.local/lib/python3.6/site-packages/spacepy/data/spacepy.mplstyle.\nYou probably need to get an updated matplotlibrc file from\nhttp://github.com/matplotlib/matplotlib/blob/master/matplotlibrc.template\nor from the matplotlib source distribution\n"
],
[
"plt.rcParams['figure.figsize'] = [10, 6]\nplt.rcParams['savefig.dpi'] = plt.rcParams['figure.dpi'] # 72\n%config InlineBackend.figure_format = 'retina'",
"_____no_output_____"
],
[
"# Lets make to Normal distributions and add them together\nlocs = np.asarray([3,10])\nsds = np.asarray([2,2])\nD1 = np.random.normal(locs[0], sds[0], size=10000)\nD2 = np.random.normal(locs[1], sds[1], size=10000)",
"_____no_output_____"
],
[
"bins = np.linspace(-24,24, 100)\nplt.hist(D1, bins=bins, histtype='step', lw=3, label='D1')\nplt.hist(D2, bins=bins, histtype='step', lw=3, label='D2')\n\nplt.hist(np.append(D1,D2), bins=bins, histtype='step', lw=3, label='D1+D2')\nplt.legend()",
"_____no_output_____"
],
[
"D = np.append(D1,D2)\nprint(D.shape)\nplt.hist(D, bins=bins, histtype='step', lw=3, label='D1+D2');\n",
"(20000,)\n"
],
[
"with mc3.Model() as model:\n weights = mc3.Uniform('weights', 0,1 , shape=2)\n loc1_mc = mc3.Uniform('loc1_mc', -10,20)\n loc2_mc = mc3.Uniform('loc2_mc', loc1_mc,20)\n sds_mc = mc3.Uniform('sds_mc', 0, 10) # we know they are the same for round 1\n obs = mc3.NormalMixture('obs', w=weights, mu=[loc1_mc, loc2_mc], sd=sds_mc, observed=D, shape=2)\n start = mc3.find_MAP()\n trace = mc3.sample(20000, start=start, njobs=6)\n \nmc3.traceplot(trace);\nmc3.summary(trace)\n",
"logp = -inf, ||grad|| = 0.95999: 100%|██████████| 14/14 [00:00<00:00, 321.09it/s] \nAuto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nMultiprocess sampling (6 chains in 6 jobs)\nNUTS: [sds_mc_interval__, loc2_mc_interval__, loc1_mc_interval__, weights_interval__]\n 0%| | 0/20500 [00:00<?, ?it/s]\n"
],
[
"ppc = mc3.sample_ppc(trace, model=model, samples=500)\nppc.keys()",
"_____no_output_____"
],
[
"plt.hist(ppc['obs'], bins=bins)",
"_____no_output_____"
]
]
] | [
"markdown",
"raw",
"code"
] | [
[
"markdown"
],
[
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7aba990bd83a82bd7404e144f68a8d7f5f9eb49 | 214,961 | ipynb | Jupyter Notebook | components/notebooks/Clean_Up_Speeches.ipynb | jfsalcedo10/mda-kuwait | da216ce48bc3374b99d420c44498eff1beabf442 | [
"MIT"
] | null | null | null | components/notebooks/Clean_Up_Speeches.ipynb | jfsalcedo10/mda-kuwait | da216ce48bc3374b99d420c44498eff1beabf442 | [
"MIT"
] | null | null | null | components/notebooks/Clean_Up_Speeches.ipynb | jfsalcedo10/mda-kuwait | da216ce48bc3374b99d420c44498eff1beabf442 | [
"MIT"
] | null | null | null | 40.38343 | 596 | 0.417011 | [
[
[
"from pathlib import Path\n\nimport pandas as pd\nimport numpy as np\nimport re\nimport regex\nfrom pprint import pprint\n\nimport csv ",
"_____no_output_____"
]
],
[
[
"# Load data",
"_____no_output_____"
],
[
"Read the csv file (first row contains the column names), specify the data types.",
"_____no_output_____"
]
],
[
[
"csv_dir = Path.cwd().parent / \"data\" \nspeeches_path = csv_dir / \"all_speeches.txt\"\ndtypes={'title':'string', 'pages':'int64', 'date':'string', 'location':'string', \n 'highest_speaker_count':'int64', 'content':'string'}\ndf = pd.read_csv(speeches_path, header=0, dtype=dtypes)\ndf.head()",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
]
],
[
[
"# Dates",
"_____no_output_____"
],
[
"Some dates had the year missing. The year for `Community_College_Plan` has a typo.",
"_____no_output_____"
]
],
[
[
"temp = df.loc[:, ['title','date']]\ntemp['has_year'] = temp.apply(lambda row: row['date'][-4:].isnumeric(), axis=1)\ntemp.loc[temp.has_year==False, :]",
"_____no_output_____"
]
],
[
[
"Edit the dates that need to be corrected.",
"_____no_output_____"
]
],
[
[
"print(df.loc[df.title=='Community_College_Plan','date'])\ndf.loc[df.title=='Community_College_Plan','date'] = '9 January 2015'\nprint(df.loc[df.title=='Community_College_Plan','date'], '\\n')\n\nprint(df.loc[df.title=='Recovery_and_Reinvestment_Act_2016','date'])\ndf.loc[df.title=='Recovery_and_Reinvestment_Act_2016','date'] = '26 February 2016'\nprint(df.loc[df.title=='Recovery_and_Reinvestment_Act_2016','date'], '\\n')\n\nprint(df.loc[df.title=='Post_Iran_Nuclear_Accord_Presser','date'])\ndf.loc[df.title=='Post_Iran_Nuclear_Accord_Presser','date'] = '15 July 2015'\nprint(df.loc[df.title=='Post_Iran_Nuclear_Accord_Presser','date'], '\\n')",
"78 9 January 20105\nName: date, dtype: string\n78 9 January 2015\nName: date, dtype: string \n\n256 26 February \nName: date, dtype: string\n256 26 February 2016\nName: date, dtype: string \n\n265 15 July \nName: date, dtype: string\n265 15 July 2015\nName: date, dtype: string \n\n"
]
],
[
[
"Parse the dates.",
"_____no_output_____"
]
],
[
[
"df['date'] = pd.to_datetime(df['date'], dayfirst=True, format=\"%d %B %Y\")\ndf.head()",
"_____no_output_____"
]
],
[
[
"The `date` column now has type `datetime`.",
"_____no_output_____"
]
],
[
[
"df.dtypes",
"_____no_output_____"
]
],
[
[
"# Locations",
"_____no_output_____"
],
[
"Locations that specify a specific place in the White House can be replaced by `White House, Washington D.C.`.",
"_____no_output_____"
]
],
[
[
"contains_WH = df.location.str.contains(\"White House\", flags=re.I)\ndf.loc[contains_WH, 'location'] = \"White House, Washington D.C.\"",
"_____no_output_____"
]
],
[
[
"Make a `country`column, values for `White House` can already be filled.",
"_____no_output_____"
]
],
[
[
"df.loc[contains_WH, 'country'] = \"USA\"\ndf.loc[~contains_WH, 'country'] = \"\"",
"_____no_output_____"
]
],
[
[
"Set country to `USA` for locations that contain state names or state abbreviations. In case it contains the abbreviation, replace it by the full state name.",
"_____no_output_____"
]
],
[
[
"states_full = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming']\nstates_abbr = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY']\n\nfor state in states_full:\n contains = df.location.str.contains(state, flags=re.I)\n df.loc[contains, 'country'] = \"USA\"\n \nfor i in range(len(states_abbr)):\n contains = df.location.str.contains(r\", \\b\"+states_abbr[i]+r\"\\b\", flags=re.I)\n df.loc[contains, 'country'] = \"USA\"\n df['location'] = df.location.str.replace(\n r\", \\b\"+states_abbr[i]+r\"\\b\", repl=\", \"+states_full[i], flags=re.I, regex=True)",
"_____no_output_____"
],
[
"df.loc[df.country==\"USA\", :]",
"_____no_output_____"
],
[
"df.loc[(df.country!=\"USA\") & (df.location!=\"unknown_location\"), :]",
"_____no_output_____"
]
],
[
[
"Change `Washington, D.C.` (and some variations) to `Washington D.C.`.",
"_____no_output_____"
]
],
[
[
"df['location'] = df.location.str.replace(\"Washington, D.?C.?\", repl=\"Washington D.C.\", flags=re.I, regex=True)",
"_____no_output_____"
]
],
[
[
"If `country=='USA'`: We assume the last substring to be the state, the second to last the city and everything before that a more specific locations.\n\n\nIf `country!='USA'`: We assume the last substring to be the country, the second to last the city and everything before that a more specific locations.",
"_____no_output_____"
]
],
[
[
"df.loc[:, 'count_commas'] = df.loc[:, 'location'].str.count(',')\ndf.loc[:,['location','country','count_commas']].sort_values(by='count_commas')",
"_____no_output_____"
]
],
[
[
"## USA",
"_____no_output_____"
],
[
"### No commas",
"_____no_output_____"
]
],
[
[
"print(df.loc[(df.country==\"USA\") & (df.count_commas == 0), ['title','location']].sort_values(by='location'), '\\n')\n\ndf.loc[df.title=='Ebola_CDC', ['state','city','specific_location']] = ['Georgia', 'Atlanta', 'no_specific_location']\ndf.loc[df.location=='Washington D.C.', ['state','city','specific_location']] = ['no_state', 'Washington D.C.', \n 'no_specific_location']",
" title location\n308 Ebola_CDC Atlanta Georgia\n258 State_of_the_Union_2012 Washington D.C.\n278 Health_Care_Law_Signing Washington D.C.\n284 White_House_Correspondents_Dinner_2015 Washington D.C.\n285 Paris_Terrorist_Attacks Washington D.C.\n288 Brookings_Institute Washington D.C.\n293 Go_Presidential_Election_Outcome_2016 Washington D.C.\n298 Howard_University_Commencement Washington D.C.\n4 Umpqua_Community_College_Shootings Washington D.C.\n314 National_Holocaust_Memorial_Museum Washington D.C.\n321 Iftar_Dinner_on_Religious_Tolerance Washington D.C.\n322 Second_Presidential_Inaugural_Address Washington D.C.\n330 White_House_Correspondent_Dinner_2014 Washington D.C.\n356 Syria_Speech_to_the_Nation Washington D.C.\n370 Final_State_of_the_Union_Address Washington D.C.\n371 Lincoln_Memorial Washington D.C.\n234 Naturalization_National_Archives Washington D.C.\n215 Prayer_Breakfast_2011 Washington D.C.\n203 Senate_Floor_Coretta_King Washington D.C.\n181 National_Chamber_of_Commerce Washington D.C.\n7 Senate_Floor_Immigration_Reform Washington D.C.\n13 Holocaust_Days_of_Remembrance Washington D.C.\n22 Prayer_Breakfast_2014 Washington D.C.\n33 Joint_Session_on_Economy_and_Jobs Washington D.C.\n62 White_House_Correspondents_Dinner_2011 Washington D.C.\n63 Iran_Deal_American_University Washington D.C.\n73 Iraq_War_After_4_Years Washington D.C.\n401 Rosa_Parks Washington D.C.\n81 State_of_the_Union_2011 Washington D.C.\n93 Chicago_Cubs_WH_Visit Washington D.C.\n100 Senate_Speech_on_Ohio_Electoral_Vote Washington D.C.\n112 Congressional_Black_Caucus Washington D.C.\n120 Oval_Office_BP Washington D.C.\n139 VOX_Interview Washington D.C.\n145 State_of_the_Union_2010 Washington D.C.\n148 Hurricane_Sandy_Red_Cross Washington D.C.\n88 State_of_the_Union_2013 Washington D.C.\n417 Birth_Certificate_Release Washington D.C. \n\n"
]
],
[
[
"### One comma + `Washington D.C.`",
"_____no_output_____"
]
],
[
[
"contains_WDC = df.location.str.contains(\"Washington D.C.\", flags=re.I)\nselect = contains_WDC & (df.count_commas == 1)\nprint(df.loc[select, 'location'])\n\nlocations = df.loc[select, 'location'].str.extract(r\"(.+), Washington D.C. *\", flags=re.I)\n\ndf.loc[select, ['state','city']] = ['no_state', 'Washington D.C.']\ndf.loc[select, 'specific_location'] = locations.values",
"1 Washington Hilton, Washington D.C.\n5 Washington Hilton Hotel, Washington D.C.\n8 White House, Washington D.C.\n11 White House, Washington D.C.\n12 White House, Washington D.C.\n ... \n414 White House, Washington D.C.\n415 State Department, Washington D.C.\n416 Eisenhower Building, Washington D.C.\n418 U.S. Capitol Western Front, Washington D.C.\n434 White House, Washington D.C.\nName: location, Length: 106, dtype: string\n"
]
],
[
[
"### One comma + other",
"_____no_output_____"
]
],
[
[
"select = (df.country==\"USA\") & ~contains_WDC & (df.count_commas == 1)\nprint(df.loc[select, 'location'])\n\nstates = df.loc[select, 'location'].str.extract(r\".+?, *(.+)\", flags=re.I)\ncities = df.loc[select, 'location'].str.extract(r\"(.+?), *.+\", flags=re.I)\n\ndf.loc[select, 'state'] = states.values\ndf.loc[select, 'city'] = cities.values\ndf.loc[select, 'specific_location'] = 'no_specific_location'",
"2 Chicago, Illinois\n10 San Jose, California\n20 Fairfax, Virginia\n28 Beaverton, Oregon\n31 Kailua, Hawaii\n ... \n420 Arlington, Virginia\n421 Reno, Nevada\n423 Arlington, Virginia\n424 Langley, Virginia\n429 Charlotte, North Carolina\nName: location, Length: 73, dtype: string\n"
],
[
"df.loc[select, ['location','country','state','city','specific_location']].sort_values(\n by= ['state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"Some cities need corrections. Cities that don't have a space in them are all ok, we only need to look at ones with spaces.",
"_____no_output_____"
]
],
[
[
"contains = df.loc[select, 'city'].str.contains(\" \", flags=re.I)\ndf.loc[select & contains, ['title', 'location','state','city','specific_location']].sort_values(\n by= ['state','city','specific_location'])",
"_____no_output_____"
],
[
"need_corrections = ['Mayors_Conference_2015','White_House_Correspondents_Dinner_First','Beau_Biden_Eulogy',\n 'Gun_Violence_Denver','Second_Presidential_Election_Victory_Speech','Joplin_Tornado_Victims_Memorial',\n 'American_Legion_Conference','Iraq_War_Camp_Lejeune','Martin_Dempsey_Retirement']\n\nstates = ['California', 'no_state', 'Delaware', 'Colorado', 'Illinois', 'Missouri', 'Minnesota', 'North Carolina', \n 'Virginia']\ncities = ['San Francisco', 'Washington D.C.', 'Wilmington', 'Denver', 'Chicago', 'Joplin', 'Minneapolis', 'Jacksonville', \n 'Arlington']\nlocations = ['Hilton San Francisco Union Square Hotel', 'Washington Hilton Hotel', 'St. Anthony of Padua Church', \n 'Denver Police Academy', 'McCormick Place', 'Missouri Southern University', 'Minneapolis Convention Center', \n 'Camp Lejeune', 'Joint Base Myer-Henderson Hall']\n\ndf.loc[df.title.isin(need_corrections), 'state'] = states\ndf.loc[df.title.isin(need_corrections), 'city'] = cities\ndf.loc[df.title.isin(need_corrections), 'specific_location'] = locations\ndf.loc[df.title.isin(need_corrections), ['location','state','city','specific_location']].sort_values(\n by= ['state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"### Two commas",
"_____no_output_____"
]
],
[
[
"select = (df.country==\"USA\") & (df.count_commas == 2)\nprint(df.loc[select, 'location'])\n\nstates = df.loc[select, 'location'].str.extract(r\".+?,.+?, *(.+)\", flags=re.I)\ncities = df.loc[select, 'location'].str.extract(r\".+?, *(.+?),.+\", flags=re.I)\nlocations = df.loc[select, 'location'].str.extract(r\" *(.+?),.+?,.+\", flags=re.I)\n\ndf.loc[select, 'state'] = states.values\ndf.loc[select, 'city'] = cities.values\ndf.loc[select, 'specific_location'] = locations.values",
"0 Sheraton New York Hotel and Towers, New York, ...\n24 Harborside Event Center, Fort Myers, Florida\n26 Kaneohe Bay Marine Base, Kaneohe, Hawaii\n38 Veterans Memorial Auditorium, Des Moines, Iowa\n53 Newport News Shipbuilding, Newport News, Virginia\n56 McCormick Place, Chicago, Illinois\n65 Hofstra University, Hempstead, New York\n71 Del Sol HS, Las Vegas, Nevada\n78 Pellissippi State Community College, Knoxville...\n80 Lyndon Baines Johnson Library, Austin, Texas\n92 Lincoln Center, New York, New York\n99 Pentagon, Arlington, Virginia\n102 Joint Base Myer-Henderson, Fort Myer, Virginia\n106 Philadelphia Convention Center, Philadelphia, ...\n107 Sun Devil Stadium, Tempe, Arizona\n109 Illinois State Capitol, Springfield, Illinois\n111 Hyde Park Career Academy, Chicago, Illinois\n137 Arlington National Cemetery, Arlington, Virginia\n144 Macomb Community College, Warren, Michigan\n147 Hyatt Regency, Chicago, Illinois\n158 University of Baylor, Waco, Texas\n164 East End Family Community Center, Charleston, ...\n190 Lynn University, Boca Raton, Florida\n219 Michie Stadium, West Point, New York\n220 United States Air Force Academy, Colorado Spri...\n225 Carnegie Mellon University, Pittsburgh, Pennsy...\n237 Magness Arena, University of Denver, Colorado\n245 JFK Space Center, Merritt Island, Florida\n246 Phillips Center for the Performing Arts, Orlan...\n259 MacDill Air Force Base, Tampa, Florida\n289 Lotte New York Palace Hotel, New York City, Ne...\n310 UN Headquarters, New York, New York\n312 Andrew Sanchez Community Center, New Orleans, ...\n325 University of Chicago Law School, Chicago, Ill...\n326 Eisenhower Hall, West Point Military Academy, ...\n327 Georgia Institute of Technology, Atlanta, Georgia\n331 Southern Methodist University, Dallas, Texas\n336 Long Center for Performing Arts, Austin, Texas\n346 Northwestern High School, Flint, Michigan\n367 Edmund Pettus Bridge, Selma, Alabama\n368 Cooper Union, New York, New York\n376 McKale Memorial Center, University of Arizona,...\n380 College of Charleston, Charleston, South Carolina\n381 Stanford University, Stanford, California\n382 West Virginia State Capitol, Charleston, West ...\n412 Northern Michigan University, Marquette, Michigan\nName: location, dtype: string\n"
],
[
"df.loc[select, ['title','location','state','city','specific_location']].sort_values(\n by= ['state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"Some cities need corrections.",
"_____no_output_____"
]
],
[
[
"need_corrections = ['Obama-Romney_-_First_Live_Debate', 'NY_NJ_Explosions', 'Afghanistan_War_Troop_Surge', \n 'Tucson_Memorial_Address', 'Armed_Forces_Farewell']\n\nstates = ['Colorado', 'New York', 'New York', 'Arizona', 'Virginia']\ncities = ['Denver', 'New York', 'West Point', 'Tucson', 'Arlington']\nlocations = ['University of Denver Magness Arena', 'Lotte New York Palace Hotel', 'Military Academy Eisenhower Hall', \n 'University of Arizona McKale Memorial Center', 'Fort Myer Joint Base Myer-Henderson']\n\ndf.loc[df.title.isin(need_corrections), 'state'] = states\ndf.loc[df.title.isin(need_corrections), 'city'] = cities\ndf.loc[df.title.isin(need_corrections), 'specific_location'] = locations\ndf.loc[df.title.isin(need_corrections), ['location','state','city','specific_location']].sort_values(\n by= ['state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"### Result for locations in USA",
"_____no_output_____"
]
],
[
[
"df.loc[df.country==\"USA\", ['location','country','state','city','specific_location']].sort_values(\n by=['state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"## Not USA, but known location",
"_____no_output_____"
],
[
"Note: some US locations don't have `country=='USA'` yet",
"_____no_output_____"
],
[
"### Zero commas",
"_____no_output_____"
]
],
[
[
"select = (df.country!=\"USA\") & (df.location!=\"unknown_location\") & (df.count_commas == 0)\ndf.loc[select, ['title','location']]",
"_____no_output_____"
],
[
"titles = df.loc[select, 'title']\ndf.loc[df.title=='Joint_Presser_with_President_Benigno_Aquino', \n ['country','state','city','specific_location']] = ['Philippines', 'no_state', 'Manila', 'no_specific_location']\ndf.loc[df.title=='Benghazi_Remains_Transfer', \n ['country','state','city','specific_location']] = ['USA', 'no_state', 'Washington D.C.', 'White House']\ndf.loc[df.title=='Berlin_Address', \n ['country','state','city','specific_location']] = ['Germany', 'no_state', 'Berlin', 'Victory Column']\ndf.loc[df.title=='Miami_Dade_College_Commencement', \n ['country','state','city','specific_location']] = ['USA', 'Florida', 'Miami', 'James L. Knight International Center']\ndf.loc[df.title=='Strasbourg_Town_Hall', \n ['country','state','city','specific_location']] = ['France', 'no_state', 'Strasbourg', 'Rhenus Sports Arena']\ndf.loc[df.title=='Hradany_Square_Prague', \n ['country','state','city','specific_location']] = ['Czech Republic', 'no_state', 'Prague', 'Hradany Square']\ndf.loc[df.title=='Hurricane_Sandy_ERT', \n ['country','state','city','specific_location']] = ['USA', 'no_state', 'Washington D.C.', 'White House']\n\ndf.loc[df.title.isin(titles), ['location','country','state','city','specific_location']].sort_values(\n by= ['country','state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"### One comma",
"_____no_output_____"
]
],
[
[
"select = (df.country!=\"USA\") & (df.location!=\"unknown_location\") & (df.count_commas == 1)\ntitles = df.loc[select, 'title']\ndf.loc[select, ['title','location']]",
"_____no_output_____"
],
[
"countries = df.loc[df.title.isin(titles), 'location'].str.extract(r\".+?, *(.+)\", flags=re.I)\ncities = df.loc[df.title.isin(titles), 'location'].str.extract(r\" *(.+?),.+\", flags=re.I)\n\ndf.loc[df.title.isin(titles), 'country'] = countries.values\ndf.loc[df.title.isin(titles), 'state'] = 'no_state'\ndf.loc[df.title.isin(titles), 'city'] = cities.values\ndf.loc[df.title.isin(titles), 'specific_location'] = 'no_specific_location'",
"_____no_output_____"
]
],
[
[
"some corrections",
"_____no_output_____"
]
],
[
[
"df.loc[df.title=='2004_DNC_Address', \n ['country','state','city','specific_location']] = ['USA', 'New York', 'Boston', 'no_specific_location']\ndf.loc[df.title=='Afghanistan_US_Troops_Bagram', \n ['country','state','city','specific_location']] = ['Afghanistan', 'no_state', 'Bagram', 'Bagram Air Field']\ndf.loc[df.title=='Peru_Press_Conference', \n ['country','state','city','specific_location']] = ['Peru', 'no_state', 'Lima', 'Lima Convention Center']\ndf.loc[df.title=='Rio_de_Janeiro', \n ['country','state','city','specific_location']] = ['Brazil', 'no_state', 'Rio de Janeiro', 'Teatro Municipal']\ndf.loc[df.title=='Bagram_Air_Base_December_2010', \n ['country','state','city','specific_location']] = ['Afghanistan', 'no_state', 'Bagram', 'Bagram Air Field']\ndf.loc[df.title=='Ebenezer_Baptist', \n ['country','state','city','specific_location']] = ['USA', 'Georgia', 'Atlanta', 'Ebenezer Baptist Church']\ndf.loc[df.title=='British_Parliament', \n ['country','state','city','specific_location']] = ['England', 'no_state', 'London', 'Westminster Hall']\ndf.loc[df.title=='Ted_Kennedy_Eulogy', \n ['country','state','city','specific_location']] = ['USA', 'New York', 'Boston', 'Our Lady of Perpetual Help Basilica']\ndf.loc[df.title=='Post_G7_Conference_Presser_2015', \n ['country','state','city','specific_location']] = ['Germany', 'no_state', 'Krun', 'Elmau Briefing Center']\ndf.loc[df.title=='Mexico_Address', \n ['country','state','city','specific_location']] = ['Mexico', 'no_state', 'Mexico City', 'Anthropological Museum']\ndf.loc[df.title=='Estonia_People', \n ['country','state','city','specific_location']] = ['Estonia', 'no_state', 'Tallinn', 'Nordea Concert Hall']",
"_____no_output_____"
],
[
"df.loc[df.title.isin(titles), ['location','country','state','city','specific_location']].sort_values(\n by= ['country','state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"### Two commas",
"_____no_output_____"
]
],
[
[
"select = (df.country!=\"USA\") & (df.location!=\"unknown_location\") & (df.count_commas == 2)\ntitles = df.loc[select, 'title']\ndf.loc[select, ['title','location']]",
"_____no_output_____"
],
[
"countries = df.loc[df.title.isin(titles), 'location'].str.extract(r\".+?,.+?, *(.+)\", flags=re.I)\ncities = df.loc[df.title.isin(titles), 'location'].str.extract(r\".+?, *(.+?),.+\", flags=re.I)\nlocations = df.loc[df.title.isin(titles), 'location'].str.extract(r\" *(.+?),.+?,.+\", flags=re.I)\n\ndf.loc[df.title.isin(titles), 'country'] = countries.values\ndf.loc[df.title.isin(titles), 'state'] = 'no_state'\ndf.loc[df.title.isin(titles), 'city'] = cities.values\ndf.loc[df.title.isin(titles), 'specific_location'] = locations.values\n\ndf.loc[df.title=='YSEALI_Town_Hall', \n ['country','state','city','specific_location']] = ['Myanmar', 'no_state', 'Yangon', 'Yangon University']",
"_____no_output_____"
],
[
"df.loc[df.title.isin(titles), ['title','location','country','state','city','specific_location']].sort_values(\n by= ['country','state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"### Three commas",
"_____no_output_____"
]
],
[
[
"select = (df.country!=\"USA\") & (df.location!=\"unknown_location\") & (df.count_commas == 3)\ndf.loc[select, ['title','location']]",
"_____no_output_____"
],
[
"df.loc[df.title=='UK_Young_Leaders', \n ['country','state','city','specific_location']] = ['England', 'no_state', 'London', 'Lindley Hall, Royal Horticulture Halls']",
"_____no_output_____"
]
],
[
[
"### Result for locations not in USA",
"_____no_output_____"
]
],
[
[
"df.loc[(df.country!=\"USA\") & (df.location!=\"unknown_location\"), ['location','country','state','city','specific_location']].sort_values(\n by=['country','state','city','specific_location'])",
"_____no_output_____"
]
],
[
[
"## Unknown locations",
"_____no_output_____"
]
],
[
[
"print('There are %i unknown locations.' % len(df.loc[df.location==\"unknown_location\", :]))",
"There are 89 unknown locations.\n"
]
],
[
[
"## drop location column",
"_____no_output_____"
],
[
"# Make new csv",
"_____no_output_____"
],
[
"Only known locations",
"_____no_output_____"
]
],
[
[
"csv_dir = Path.cwd().parent / \"speeches_csv\" \npath_only_known = csv_dir / \"speeches_loc_known_cleaned.txt\"\n\nonly_known = df.loc[df.location!=\"unknown_location\", :]\nonly_known.to_csv(path_only_known, index=False, header=True, mode='w')",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
e7abb30cdfac674cdf04cb5252c887f47844ea76 | 671 | ipynb | Jupyter Notebook | Programming/UCIcourse.ipynb | stOOrz-Mathematical-Modelling-Group/MCM-ICM_2022 | 12c95a31f811e1745465b49a66d1a4975a3ee932 | [
"MIT"
] | null | null | null | Programming/UCIcourse.ipynb | stOOrz-Mathematical-Modelling-Group/MCM-ICM_2022 | 12c95a31f811e1745465b49a66d1a4975a3ee932 | [
"MIT"
] | null | null | null | Programming/UCIcourse.ipynb | stOOrz-Mathematical-Modelling-Group/MCM-ICM_2022 | 12c95a31f811e1745465b49a66d1a4975a3ee932 | [
"MIT"
] | null | null | null | 26.84 | 55 | 0.590164 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7abccac0c42a1ce44107677449dac7668f157af | 657,157 | ipynb | Jupyter Notebook | pset-3/pset3.ipynb | aberke/mit-stats-15.077 | 25a28ffb9f766bcc940e9749dc41523057b4db72 | [
"MIT"
] | null | null | null | pset-3/pset3.ipynb | aberke/mit-stats-15.077 | 25a28ffb9f766bcc940e9749dc41523057b4db72 | [
"MIT"
] | null | null | null | pset-3/pset3.ipynb | aberke/mit-stats-15.077 | 25a28ffb9f766bcc940e9749dc41523057b4db72 | [
"MIT"
] | 1 | 2021-06-14T14:30:24.000Z | 2021-06-14T14:30:24.000Z | 175.945649 | 121,920 | 0.869985 | [
[
[
"# 15.077: Problem Set 3\n\nAlex Berke (aberke)\n\n\nFrom \n\nRice, J.A., Mathematical Statistics and Data Analysis (with CD Data Sets), 3rd ed., Duxbury, 2007 (ISBN 978-0-534-39942-9).\n",
"_____no_output_____"
]
],
[
[
"%config Completer.use_jedi = False # autocomplete\n\nimport math\nimport numpy as np\nimport pandas as pd\nimport scipy.special\nfrom scipy import stats\nfrom sklearn.utils import resample\n\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'",
"_____no_output_____"
]
],
[
[
"## Problems",
"_____no_output_____"
],
[
"### 10.48\nIn 1970, Congress instituted a lottery for the military draft to support the unpopular war in Vietnam. All 366 possible birth dates were placed in plastic capsules in a rotating drum and were selected one by one. Eligible males born on the first day drawn were first in line to be drafted followed by those born on the second day drawn, etc. The results were criticized by some who claimed that government incompetence at running a fair lottery resulted in a tendency of men born later in the year being more likely to be drafted. Indeed, later investigation revealed that the birthdates were placed in the drum by month and were not thoroughly mixed. The columns of the file 1970lottery are month, month number, day of the year, and draft number.",
"_____no_output_____"
]
],
[
[
"lottery = pd.read_csv('1970lottery.txt')\nlottery.columns = [c.replace(\"'\", \"\") for c in lottery.columns]\nlottery['Month'] = lottery['Month'].apply(lambda m: m.replace(\"'\", \"\"))\nlottery.head()",
"_____no_output_____"
]
],
[
[
"#### A. Plot draft number versus day number. Do you see any trend?\n\nNo, a trend is not clear from a simple plot with these two variables.",
"_____no_output_____"
]
],
[
[
"_ = lottery.plot.scatter('Day_of_year', 'Draft_No', title='Day of year vs draft number')",
"_____no_output_____"
]
],
[
[
"#### B. Calculate the Pearson and rank correlation coefficients. What do they suggest?\n\nBoth correlation coefficcients suggest there could be a relationship that is not immediately visible.",
"_____no_output_____"
]
],
[
[
"print('Pearson correlation coefficient: %0.4f' % (\n stats.pearsonr(lottery['Draft_No'], lottery['Day_of_year'])[0]))\nprint('Spearman rank correlation coefficient: %0.4f' % (\n stats.spearmanr(lottery['Draft_No'], lottery['Day_of_year'])[0]))",
"Pearson correlation coefficient: -0.2260\nSpearman rank correlation coefficient: -0.2258\n"
]
],
[
[
"#### C. Is the correlation statistically significant? One way to assess this is via a permutation test. Randomly permute the draft numbers and find the correlation of this random permutation with the day numbers. Do this 100 times and see how many of the resulting correlation coefficients exceed the one observed in the data. If you are not satisfied with 100 times, do it 1,000 times.\n\nThe correlation does appear statistically significant.\n\nThis is because after 1000 iterations of randomly permuting the draft numbers and computing correlation coefficients between those draft numbers and day numbers, we compute the 95% CI for these correlations (see below) and see that the true correlation coefficients fall outside these confidence intervals.\n\nPearson correlation coefficient 95% CI for randomly permuted draft numbers vs day:\n(-0.0044, 0.0019)\n\nSpearman rank correlation coefficient 95% CI for randomly permuted draft numbers vs day:\n(-0.0044, 0.0019)\n\nTrue correlation coefficients:\n\nPearson correlation coefficient: -0.2260\n\nSpearman rank correlation coefficient: -0.2258",
"_____no_output_____"
]
],
[
[
"iterations = 1000\n\npearson_coefficients = []\nrank_coefficients = []\nfor i in range(iterations):\n permuted_draft_no = np.random.permutation(lottery['Draft_No'])\n pearson_coefficients += [stats.pearsonr(permuted_draft_no, lottery['Day_of_year'])[0]]\n rank_coefficients += [stats.spearmanr(permuted_draft_no, lottery['Day_of_year'])[0]]\n\nprint('Pearson correlation coefficient 95% CI for randomly permuted draft numbers vs day:')\nprint('(%0.4f, %0.4f)' % stats.t.interval(0.95, len(pearson_coefficients)-1,\n loc=np.mean(pearson_coefficients), \n scale=stats.sem(pearson_coefficients)))\nprint('Spearman rank correlation coefficient 95% CI for randomly permuted draft numbers vs day:')\nprint('(%0.4f, %0.4f)' % stats.t.interval(0.95, len(rank_coefficients)-1,\n loc=np.mean(rank_coefficients), \n scale=stats.sem(rank_coefficients)))",
"Pearson correlation coefficient 95% CI for randomly permuted draft numbers vs day:\n(-0.0044, 0.0019)\nSpearman rank correlation coefficient 95% CI for randomly permuted draft numbers vs day:\n(-0.0044, 0.0019)\n"
],
[
"fig, ax = plt.subplots(1, 2, figsize=(15, 5), sharey=True)\nfig.suptitle('Correlation coefficicents for randomly permuted draft numbers vs day number (%s iterations)' % iterations)\nax[0].hist(pearson_coefficients)\nax[1].hist(rank_coefficients)\nax[0].set_title('Pearson correlation')\nax[1].set_title('Spearman rank correlation')\nax[0].set_xlabel('Pearson correlation coefficient')\n_ = ax[1].set_xlabel('Spearman rank correlation coefficient')",
"_____no_output_____"
]
],
[
[
"#### D. Make parallel boxplots of the draft numbers by month. Do you see any pattern? \n\nThe mean draft numbers are lowest in the (later) months of November and December.",
"_____no_output_____"
]
],
[
[
"pd.DataFrame(\n {m: lottery[lottery['Month']==m]['Draft_No'] for m in months.values()}\n).boxplot(grid=False)",
"_____no_output_____"
]
],
[
[
"#### E. Examine the sampling variability of the two correlation coefficients (Pearson and rank) using the bootstrap (re-sampling pairs with replacement) with 100 (or 1000) bootstrap samples. How does this compare with the permutation approach?\n\nThe results are drastically different from the results of the permutation approach. \n\nThe random permutation correlation coefficients were (as expected) centered around a mean of 0. \n\nThe bootstrap Pearson and Rank correlation coefficient values are both around -0.22.\nThe 95% CIs for the bootstrap vs permutation method values do not overlap.\n",
"_____no_output_____"
]
],
[
[
"pearson_coefficients = []\nrank_coefficients = []\nfor i in range(iterations):\n resampled = resample(lottery)\n pearson_coefficients += [stats.pearsonr(resampled['Draft_No'], resampled['Day_of_year'])[0]]\n rank_coefficients += [stats.spearmanr(resampled['Draft_No'], resampled['Day_of_year'])[0]]\n\nprint('Pearson correlation coefficient 95%% CI for (%s) bootstrap samples:' % iterations)\nprint('(%0.4f, %0.4f)' % stats.t.interval(0.95, len(pearson_coefficients)-1,\n loc=np.mean(pearson_coefficients), \n scale=stats.sem(pearson_coefficients)))\nprint('Spearman rank correlation coefficient 95%% CI for (%s) bootstrap samples:' % iterations)\nprint('(%0.4f, %0.4f)' % stats.t.interval(0.95, len(rank_coefficients)-1,\n loc=np.mean(rank_coefficients), \n scale=stats.sem(rank_coefficients)))\n\nfig, ax = plt.subplots(1, 2, figsize=(15, 5), sharey=True)\nfig.suptitle('Correlation coefficicents for draft numbers vs day number (%s) bootstrap samples' % iterations)\nax[0].hist(pearson_coefficients)\nax[1].hist(rank_coefficients)\nax[0].set_title('Pearson correlation')\nax[1].set_title('Spearman rank correlation')\nax[0].set_xlabel('Pearson correlation coefficient')\n_ = ax[1].set_xlabel('Spearman rank correlation coefficient')",
"Pearson correlation coefficient 95% CI for (1000) bootstrap samples:\n(-0.2292, -0.2231)\nSpearman rank correlation coefficient 95% CI for (1000) bootstrap samples:\n(-0.2285, -0.2224)\n"
]
],
[
[
"### 11.15 \n#### Suppose that n measurements are to be taken under a treatment condition and another n measurements are to be taken independently under a control condition. It is thought that the standard deviation of a single observation is about 10 under both conditions. How large should n be so that a 95% confidence interval for μX − μY has a width of 2? Use the normal distribution rather than the t distribution, since n will turn out to be rather large. \n",
"_____no_output_____"
],
[
"find: n control = n treatment\n\nσ = 10\n\n|μX − μY| = 2\n\nα = 0.05\n\n\nFrom Rice 11.2.1: \nSince we are using the normal distribution, and σ is assumed, a confidence interval for (μX − μY) can be based on:\n\n$Z = \\frac{(\\bar{X} - \\bar{Y}) - (μX − μY)}{\\sigma \\sqrt{\\frac{1}{n} + \\frac{1}{m}}} = \\frac{(\\bar{X} - \\bar{Y}) - (μX − μY)}{\\sigma \\sqrt{\\frac{2}{n}}} $\n\n\n\nThe confidence interval is then of form:\n\n$ (\\bar{X} - \\bar{Y}) \\pm z_{α/2} \\sigma \\sqrt{\\frac{2}{n}} $\n\nSince the confidence interval is symmetric around $ (\\bar{X} - \\bar{Y})$ and its width is 2 we have:\n\n$ 2 = 2 (z_{α/2}) \\sigma \\sqrt{\\frac{2}{n}} $\n\nrearranging terms we have:\n\n$ n = ((z_{α/2})\\sigma \\sqrt{2} )^2 = (1.96)^2 (10)^2 2 = 768.32$\n\ni.e. n= 768\n",
"_____no_output_____"
],
[
"### 11.16\n#### Referring to Problem 15, how large should n be so that the test of H0: μX = μY against the one-sided alternative HA : μX > μY has a power of .5 if μX − μY = 2 and α = .10?\n",
"_____no_output_____"
],
[
"find: n control = n treatment\n\nσ = 10\n\nα = 0.05\n\nΔ = (μX − μY) = 2\n\nBased on Rice 11.2.2 this is a problem in solving:\n\n$ 1 - \\beta = 0.5 = 1 - Φ[z(\\alpha) - \\frac{Δ}{\\sigma}\\sqrt{\\frac{n}{2}}] $\n\nRearranging we have:\n\n$ 0.5 = Φ[z(\\alpha) - \\frac{Δ}{\\sigma}\\sqrt{\\frac{n}{2}}] $\n\nSince $0.5 = Φ(0)$ this means solving for n where:\n\n$0 = z(\\alpha) - \\frac{Δ}{\\sigma}\\sqrt{\\frac{n}{2}}$\n\n$ \\frac{Δ}{\\sigma}\\sqrt{\\frac{n}{2}} = z(\\alpha)$\n\n$ n = (z(\\alpha)\\frac{\\sigma}{Δ} \\sqrt{2})^2 = (1.28)^2 (\\frac{10}{2})^2 2 = 81.92 $\n\ni.e. n = 82",
"_____no_output_____"
],
[
"### 11.39\n#### An experiment was done to test a method for reducing faults on telephone lines (Welch 1987). Fourteen matched pairs of areas were used. The following table shows the fault rates for the control areas and for the test areas: ",
"_____no_output_____"
]
],
[
[
"l = \"676 88 206 570 230 605 256 617 280 653 433 2913 337 924 466 286 497 1098 512 982 794 2346 428 321 452 615 512 519\".split(\" \")\ndf = pd.DataFrame({\n 'test': l[::2],\n 'control': l[1::2],\n}).astype(int)\ndf",
"_____no_output_____"
]
],
[
[
"#### A. Plot the differences versus the control rate and summarize what you see.",
"_____no_output_____"
]
],
[
[
"differences = df['test'] - df['control']\nplt.scatter(df['control'], differences)\nplt.xlabel('control values')\nplt.ylabel('difference values')\n_ = plt.title(' difference vs control values')",
"_____no_output_____"
]
],
[
[
"The difference values decrease as the control values increase. This relationship appears linear.",
"_____no_output_____"
],
[
"#### B. Calculate the mean difference, its standard deviation, and a confidence interval.",
"_____no_output_____"
],
[
"Let $D_i$ be the difference value.\n\nFrom Rice Section 11.3.1, a 100(1 − α)% confidence interval for $μ_D$ is\n\n$ \\bar{D} \\pm t_{n-1}(α/2)s_{\\bar{D}}$\n\nAnd from class slides “Samples” (slide 44):\n\n$s_{\\bar{D}}^2 = \\frac{1}{n (n - 1)} \\sum{(D_i - \\bar{D})^2} $",
"_____no_output_____"
]
],
[
[
"mean_D = differences.mean()\nprint('The mean difference ~ %s' % round(mean_D, 2))",
"The mean difference ~ -461.29\n"
],
[
"n = len(differences)\nstd = np.sqrt((1/((n-1)*(n)))*(((differences - mean_D)**2).sum()))\nprint('The standard deviation ~ %s' % round(std, 2))",
"The standard deviation ~ 202.53\n"
]
],
[
[
"Since $n = 14$ and $t_{13}(0.025) = 2.160$, a 95% confidence interval for the mean difference is\n\n$ -461.29 \\pm (437.46) = -461.29 \\pm (2.160 \\times 202.53) = \\bar{D} \\pm t_{n-1}(α/2)s_{\\bar{D}}$",
"_____no_output_____"
]
],
[
[
"print('95%% CI (%s , %s)' % (round(mean_D - (2.160 * std), 2), round(mean_D + (2.160 * std), 2)))",
"95% CI (-898.76 , -23.81)\n"
]
],
[
[
"#### C. Calculate the median difference and a confidence interval and compare to the previous result.\n",
"_____no_output_____"
],
[
"Based on Rice section 10.4: We can sort the values, and find the median and find confidence intervals around that median by using a binomial distribution.",
"_____no_output_____"
]
],
[
[
"sorted_differences = sorted(differences)\nprint('sorted difference values:', sorted_differences)\nmedian = np.median(sorted_differences)\nprint('η: median value = %s' % median)\n\nn = len(sorted_differences)\nprint('n = %s' % n)",
"sorted difference values: [-2480, -1552, -601, -587, -470, -375, -373, -364, -361, -163, -7, 107, 180, 588]\nη: median value = -368.5\nn = 14\n"
]
],
[
[
"We look to form a confidence interval of the following form:\n\n(X(k), X(n−k+1))\n\nThe coverage probability of this interval is\n\nP(X(k) ≤ η ≤ X(n−k+1)) = = 1 − P(η < X(k)) − P(η > X(n−k+1))\n\nThe distribution of the number of observations greater than the median is binomial with n trials and probability $\\frac{1}{2}$ of success on each trial. Thus,\n\nP( j observations are greater than η) = $ \\frac{1}{2^n} \\binom{n}{j} $\n\nNow I make a cumulative binomial distrbution table for\n\nn = 14\n\np = 0.5\n\nP[X ≤ k]",
"_____no_output_____"
]
],
[
[
"binomials = []\nfor i in range(int(n/2)):\n binomials += [((1/(2**n)) * sum([scipy.special.binom(n, j) for j in range(i+1)]))]\n\npd.Series(binomials).rename('P[X ≤ k]').to_frame()",
"_____no_output_____"
]
],
[
[
"P(X < k)= P(X > n−k+1)\n\nWe can choose k = 4\n\nP(X < 4) = P(X > 11) = 0.0287\n\nSince \n\n$2 \\times 0.0287 = 0.0574$\n\nThen we have about a 94% confidence interval for (X(4), X(11)) which is:",
"_____no_output_____"
]
],
[
[
"print('(%s, %s)' % (sorted_differences[4], sorted_differences[11]))",
"(-470, 107)\n"
]
],
[
[
"In summary, the median vaue is -368.5 with a 94% CI of (-470, 107).\n\nIn comparison, the mean value is approximately -461.29 with a 95% CI of (-898.76 , -23.81).\n\nThe mean value is lower than the median value and it has a wider confidence interval due to its larger standard deviation. The mean value and its standard deviation is clearly effected by the extreme negative values.",
"_____no_output_____"
],
[
"#### D . Do you think it is more appropriate to use a t test or a nonparametric method to test whether the apparent difference between test and control could be due to chance? Why? Carry out both tests and compare. ",
"_____no_output_____"
],
[
"A nonparametric test, namely the Signed Rank Test would be better. This is for the following reasons:\n- The t test assumes the values follow a normal distribution. However, the following plots show this assumption does not hold for the differences values.\n- The differences data has extreme outliers and the t test is sensitive to outliers while the Signed Rank Test is not.\n",
"_____no_output_____"
]
],
[
[
"fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(15,5))\nstats.probplot(differences.values, plot=ax0)\nax0.set_title('Normal probability plot: difference values')\nax1.hist(differences)\n_ = ax1.set_title('Histogram: difference values')",
"_____no_output_____"
]
],
[
[
"##### Using a t test:\n\nThe null hypothesis is for no difference, i.e.\n\n$H_0: μ_𝐷 = 0 $\n\nThe test statistic is then\n\n$ t = \\frac{\\bar{D} - μ_𝐷}{s_{\\bar{D}}} = \\frac{\\bar{D}}{s_{\\bar{D}}} $ \n\nwhich follows a t distribution with n - 1 degrees of freedom.\n",
"_____no_output_____"
]
],
[
[
"t = (np.abs(mean_D)/std)\nprint('t = %s' % round(t, 3))",
"t = 2.278\n"
]
],
[
[
"From the t distribution table:\n\n$ t_{13}(0.025) = 2.160$ and $t_{13}(0.01) = 2.650 $ so the p-value of a two-sided test is less than .05 but not less than 0.02. ",
"_____no_output_____"
],
[
"##### Using The Signed Rank Test:",
"_____no_output_____"
]
],
[
[
"test_df = differences.rename('difference').to_frame()\ntest_df['|difference|'] = np.abs(test_df['difference'])\ntest_df = test_df.sort_values('|difference|').reset_index().drop('index', axis=1).reset_index().rename(\n columns={'index':'rank'}\n)[['difference', '|difference|', 'rank']]\ntest_df['rank'] = test_df['rank'] + 1\ntest_df['signed rank'] = test_df.apply(lambda row: row['rank'] * -1 if row['difference'] < 0 else row['rank'], axis=1)\ntest_df",
"_____no_output_____"
]
],
[
[
"We now calculate W+ by summing the positive ranks.",
"_____no_output_____"
]
],
[
[
"positive_ranks = [w for w in test_df['signed rank'] if w > 0]\nprint('W+ = %s' % sum(positive_ranks))",
"W+ = 17\n"
]
],
[
[
"From Table 9 of Appendix B, the two-sided test is significant at α = .05, but not at α = .02.",
"_____no_output_____"
],
[
"The findings between the t test and The Unsigned Rank test are consistent.",
"_____no_output_____"
],
[
"### 11.46\n#### The National Weather Bureau’s ACN cloud-seeding project was carried out in the states of Oregon and Washington. Cloud seeding was accomplished by dispersing dry ice from an aircraft; only clouds that were deemed “ripe” for seeding were candidates for seeding. On each occasion, a decision was made at random whether to seed, the probability of seeding being 2/3. This resulted in 22 seeded and 13 control cases. Three types of targets were considered, two of which are dealt with in this problem. Type I targets were large geographical areas downwind from the seeding; type II targets were sections of type I targets located so as to have, theoretically, the greatest sensitivity to cloud seeding. The following table gives the average target rainfalls (in inches) for the seeded and control cases, listed in chronological order. Is there evidence that seeding has an effect on either type of target? ",
"_____no_output_____"
]
],
[
[
"control = pd.DataFrame({\n 'Type I': [\n .0080, .0046, .0549, .1313, .0587, .1723, .3812, .1720, .1182, .1383, .0106, .2126, .1435,\n ],\n 'Type II': [\n .0000, .0000, .0053, .0920, .0220, .1133, .2880, .0000, .1058, .2050, .0100, .2450, .1529,\n ],\n})\n\nseeded = pd.DataFrame({\n 'Type I': [\n .1218, .0403, .1166, .2375, .1256, .1400, .2439, .0072, .0707, .1036, .1632, .0788, .0365, .2409, .0408, .2204, .1847, .3332, .0676, .1097, .0952, .2095,\n ],\n 'Type II': [\n .0200, .0163, .1560, .2885, .1483, .1019, .1867, .0233, .1067, .1011, .2407, .0666, .0133, .2897, .0425, .2191, .0789, .3570, .0760, .0913, .0400, .1467, \n ],\n})\ncontrol",
"_____no_output_____"
],
[
"seeded",
"_____no_output_____"
]
],
[
[
"First we compare the mean values of each sample with boxplots, and check for normality with normal probability plots.",
"_____no_output_____"
]
],
[
[
"fig, (ax0, ax1, ax2, ax3) = plt.subplots(1, 4, figsize=(20,5))\nfig.suptitle('Normal probability plots of values')\nstats.probplot(control['Type I'], plot=ax0)\nstats.probplot(control['Type II'], plot=ax1)\nax0.set_title('Control Type I')\nax1.set_title('Control Type II')\nstats.probplot(seeded['Type I'], plot=ax2)\nstats.probplot(seeded['Type II'], plot=ax3)\nax2.set_title('Seeded Type I')\n_ = ax3.set_title('Seeded Type II')",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\nax.boxplot([\n control['Type I'],\n control['Type II'],\n seeded['Type I'],\n seeded['Type II'],\n], labels=[\n 'Control Type I',\n 'Control Type II',\n 'Seeded Type I',\n 'Seeded Type II',\n])\nplt.show()",
"_____no_output_____"
]
],
[
[
"The boxplots do not show significant differences.\nThe means of the seeded samples overlap with the values of their control counterparts. The seeded samples have longer tails.\n\nThe normal probability plots show that the control data does not follow a normal distribution and the sample sizes are relatively small. For this reason, a t test may not be appropriate. It would seem safer to use a nonparametric method.\n\nWe use the Mann-Whitney test to test the null hypothesis that there is no difference in the control and seeded samples.\n\nWe test Type I vs Type II separately. i.e. we first compare \n`Control Type I vs Seeded Type I`\nand then \n`Control Type II vs Seeded Type II`.\n\nn = the number of control samples\n\nm = the number of seeded samples",
"_____no_output_____"
]
],
[
[
"n = len(control)\nm = len(seeded)\nprint('n = %s' % n)\nprint('m = %s' % m)",
"n = 13\nm = 22\n"
]
],
[
[
"From Rice Section 11.2.3, a test statistic is calculated in the following way. First, we group all m + n observations together and rank them in order of increasing size.\n\nLet $n_1$ be the smaller sample size and let R be the sum of the ranks from that sample. Let $R′ = n_1(m + n + 1) − R$ and $R^* = min(R, R′)$.\n\nIn our case the smaller sample is the control, so we compute R as the summed ranks of the control and $R′ = 13 (22 + 13 + 1) − R$.\n\n\n##### Test for Type I:\n\nSee computations below.\nWe can visually see there are no ties to worry about.\n\n𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = 221\n\nFrom [these Wilcoxon Rank-Sum Tables](https://www.real-statistics.com/statistics-tables/wilcoxon-rank-sum-table-independent-samples/) we see 195 is the critical value for a two-tailed test with α = .2. \n\nWe therefore do not have evidence to reject the null hypothesis.",
"_____no_output_____"
]
],
[
[
"type1 = pd.DataFrame({\n 'value': control['Type I'],\n 'sample': 'control',\n}).append(pd.DataFrame({\n 'value': seeded['Type I'],\n 'sample': 'seeded',\n})).sort_values('value').reset_index().drop('index', axis=1).reset_index().rename(\n columns={'index':'rank'}\n)\ntype1['rank'] += 1\n\nR = type1[type1['sample']=='control']['rank'].sum()\nprint('R = %s' % R)\nR_prime = 13*(22+13+1) - 𝑅\nprint('𝑅′= 𝑛1(𝑚+𝑛+1)−𝑅 = %s' % R_prime)\nR_star = min(R, R_prime)\nprint('𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = %s' % R_star)\n\ntype1",
"R = 221\n𝑅′= 𝑛1(𝑚+𝑛+1)−𝑅 = 247\n𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = 221\n"
]
],
[
[
"##### Test for Type II:\n\nSee computations below.\n\nThere are 3 tied vaues of 0. We can assign them each the values of (1 + 2 + 3) / 3 = 2. However, since they are all in the same sample (control) this does not make a difference.\n\n𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = 199\n\nFrom [these Wilcoxon Rank-Sum Tables](https://www.real-statistics.com/statistics-tables/wilcoxon-rank-sum-table-independent-samples/) we see 195 is the critical value for a two-tailed test with α = .2 and 176 is the critical. \n\nWe therefore have a suggestion to reject the null hypothesis with 80% confidence for the type II target.",
"_____no_output_____"
]
],
[
[
"type2 = pd.DataFrame({\n 'value': control['Type II'],\n 'sample': 'control',\n}).append(pd.DataFrame({\n 'value': seeded['Type II'],\n 'sample': 'seeded',\n})).sort_values('value').reset_index().drop('index', axis=1).reset_index().rename(\n columns={'index':'rank'}\n)\ntype2['rank'] += 1\n\nR = type2[type2['sample']=='control']['rank'].sum()\nprint('R = %s' % R)\nR_prime = 13*(22+13+1) - 𝑅\nprint('𝑅′= 𝑛1(𝑚+𝑛+1)−𝑅 = %s' % R_prime)\nR_star = min(R, R_prime)\nprint('𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = %s' % R_star)\n\ntype2",
"R = 199\n𝑅′= 𝑛1(𝑚+𝑛+1)−𝑅 = 269\n𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = 199\n"
]
],
[
[
"In general, there is weak evidence that seeding has an effect on either type of target.",
"_____no_output_____"
],
[
"### 13.24",
"_____no_output_____"
],
[
"Is it advantageous to wear the color red in a sporting contest? According to Hill and Barton (2005):\n\t\t\t\t\t\nAlthough other colours are also present in animal displays, it is specifically the presence and intensity of red coloration that correlates with male dominance and testosterone levels. In humans, anger is associated with a reddening of the skin due to increased blood flow, whereas fear is as- sociated with increased pallor in similarly threatening situations. Hence, increased redness during aggressive interactions may reflect relative dominance. Because artificial stimuli can exploit innate responses to natural stimuli, we tested whether wearing red might influence the outcome of physical contests in humans.\n\t\t\t\t\t\nIn the 2004 Olympic Games, contestants in four combat sports (boxing, tae kwon do, Greco-Roman wrestling, and freestyle wrestling) were randomly assigned red or blue outfits (or body protectors). If colour has no effect on the outcome of contests, the number of winners wearing red should be statistically indistinguishable from the number of winners wearing blue.\n\t\t\t\t\t\nThey thus tabulated the colors worn by the winners in these contests: \n",
"_____no_output_____"
]
],
[
[
"sports = pd.DataFrame({\n 'Sport': ['Boxing','Freestyle Wrestling', 'Greco Roman Wrestling', 'Tae Kwon Do'],\n 'Red': [148, 27, 25, 45,],\n 'Blue': [120, 24, 23, 35],\n}).set_index('Sport')\nsports",
"_____no_output_____"
],
[
"sports['Total'] = sports['Red'] + sports['Blue']\nsports.loc['Total'] = sports.sum()\nsports",
"_____no_output_____"
]
],
[
[
"Some supplementary information is given in the file red-blue.txt.",
"_____no_output_____"
],
[
"#### a. Let πR denote the probability that the contestant wearing red wins. Test the null hypothesis that πR = ½ versus the alternative hypothesis that πR is the same in each sport, but πR ≠ ½ .\n\n\nThe null and alternative hypothesis setup models a game as a Bernoulli trial where the probabilily of a win (success) is πR for any sport.\n\nSince that is the case we can model the Bernoulli trial over the sum of all the games in all the sports.\n\nThere were n=447 total games, with r=245 wins by red. The probability of this with the null hypothesis that \n\nH0: πR = ½\n\nis:\n\n$Pr(X=r) = \\binom{n}{r}p^r(1 - p)^{n-r}$\n\n$Pr(X=245) = \\binom{447}{245}0.5^{245}(0.5)^{202} = \\binom{447}{245}0.5^{447} = 0.0048 $\n\nWe can therefore reject the null hypothesis with alpha = 0.01\n\nSince n is large, we could also apply the Central limit Theorem and obtain the test statistic and its distribution under the null hypothesis:\n\n$ Z = \\frac{X - E(X)}{\\sqrt{Var(X)}} $ \n\nWhere Z --> N(0,1) as n --> ∞\n\nIn this case, $E(X) = n (π_R) = 447 (0.5) = 223.5$\n\n$ \\sqrt{Var(X)} = \\sqrt{n (p)(1 - p)} $\n\n$ Z = \\frac{245 - 223.5}{\\sqrt{447 (0.5)(0.5)}} = 2.03 $\n\n\n$P(Z > 2) = .025 $\n\nSince Z is symmetric, this coresponds to alpha = 0.05.\n\nAgain, we have evidence to reject the null hypothesis for the alternative hypothesis, with alpha = 0.05.",
"_____no_output_____"
]
],
[
[
"print('(447 choose 245) x (0.5)^447 = %s' % (scipy.special.comb(447, 245) * (0.5 ** 447)))",
"(447 choose 245) x (0.5)^447 = 0.004774706298173504\n"
],
[
"print('Z = %s' % ((245 - 223.5)/(np.sqrt(447*(0.5)*(0.5)))))",
"Z = 2.033830210313729\n"
]
],
[
[
"#### b. Test the null hypothesis πR = ½ against the alternative hypothesis that allows πR to be different in different sports, but not equal to ½.\n\nAgain, games are modeled as bernoulli trials, but this time the bernoulli trials are independent across sports. \n\nSince the minimum n (total games) from each sport is reasonably large, the probability of the outcome can be approximated with a normal distribution.\n\nSince the $X^2$ distribution is defined as a sum of squared independent and identically distributed standard normal distributions, we can use the $X^2$ test statistic. The number of degrees of freedom are the different sports.\n\ni.e.\n\n$X_{k}^2 = \\sum_{i=1}^{k} \\frac{(x_i - p_i n_i)^2}{n_i p_i (1 - p_i)} $\n\n(The denominator is the definition of Var(X) squared)\n\nIn our case, we are testing the null hypothesis where:\n\n$H_0: p_i = 0.5, i=1,2,3,4 $\n\n$k = 4$\n\n$n_i$ is the total number of games in each sport \n\nTables show the $X^2$ critical value with 4 degrees of freedom is 7.78 for alpha=0.1 and 9.49 for alpha = 0.05. \n\nThe test statistic value is 8.57.\n\nThere is evidence to reject the null hypothesis with 90% confidence, but not 95% confidence.",
"_____no_output_____"
]
],
[
[
"t = ( ((sports['Red'] - (0.5 * sports['Total']))**2) / (sports['Total'] * 0.5 * 0.5 )).sum()\nprint('chi-squared = %s' % t)",
"chi-squared = 8.571642380281773\n"
]
],
[
[
"#### C. Are either of these hypothesis tests equivalent to that which would test the null hypothesis πR = ½ versus the alternative hypothesis πR ≠ ½ using as data the total numbers of wins summed over all the sports?\n\nYes, (A) was equivalent to this.",
"_____no_output_____"
],
[
"#### D. Is there any evidence that wearing red is more favorable in some of the sports than others?\n\nFrom Rice 13.3,\n\nWe can use a chi-squared test of homogeneity, modeling the outcomes of each of the 4 sports as (I=4) multinomial disitributions, each with J=2 cells.\nWe want to test the homogeneity of the multinomial distributions.\n\ni.e. we want to test the null hypothesis vs the alternative:\n\n$H_0 = π_{1,1} = π_{2,1} = π_{3,1} = π_{4,1}$ ($π_{i,2}$ is determinedd by $π_{i,1}$)\n\n$H_1$ : Not all probabilities are as specified in $H_0$\n\n$df = (I-1)(J-1) = 3$\n\n$ X^2 = \\sum_{i}^4 \\sum_{j}^2 \\frac{(O_{i,j} - E_{i,j})^2}{E_{i,j}} $\n\nWhere $E_{i,j} = \\frac{n_{.j}n_{i.}}{n_{..}} $\n\nThe output expected frequencies from the following test are close to the observed frequencies.\n\nThe 10% point with 3 df is 6.25.\n\nThe data are consistent with the null hypothesis.",
"_____no_output_____"
]
],
[
[
"sports.drop('Total', axis=0).drop('Total', axis=1)",
"_____no_output_____"
],
[
"chi2, p, dof, ex = stats.chi2_contingency(sports.drop('Total', axis=0).drop('Total', axis=1))\nassert(dof == 3)\nprint('chi-squared test statistic = %s' % chi2)\nprint('p = %s' % p)\nprint('\\nexpected frequencies:')\npd.DataFrame(ex, columns=['Red','Blue'])",
"chi-squared test statistic = 0.3015017799642389\np = 0.9597457890114767\n\nexpected frequencies:\n"
]
],
[
[
"#### E. From an analysis of the points scored by winners and losers, Hill and Barton concluded that color had the greatest effect in close contests. Data on the points of each match are contained in the file red-blue.xls. Analyze this data and see whether you agree with their conclusion. \n\nHere we analyze the sports separately. We compare the distribution of absolute difference in points scored and the number of Red vs Blue winners. A smaller absolute difference in points means a closer contest.\n\nFirst we load the data for each sport, and plot the differences against wins.",
"_____no_output_____"
]
],
[
[
"def get_red_blue_points_differences(points_fpath):\n df =pd.read_csv(points_fpath)[\n ['Winner','Points Scored by Red', 'Points Scored by Blue']\n ].dropna()\n df['|Difference|'] = np.abs(df['Points Scored by Red'] - df['Points Scored by Blue'])\n return df",
"_____no_output_____"
],
[
"def plot_point_differences(df, name):\n fig, ax = plt.subplots(1,1)\n max_points_diff = df['|Difference|'].max()\n ax.hist(\n df[df['Winner']=='Red']['|Difference|'],\n alpha=0.5, color='red', label='Red wins (n=%s)'%len(df[df['Winner']=='Red']),\n bins=int(max_points_diff)\n )\n ax.hist(\n df[df['Winner']=='Blue']['|Difference|'], \n alpha=0.5, color='blue', label='Blue wins (n=%s)'%len(df[df['Winner']=='Blue']),\n bins=int(max_points_diff)\n )\n ax.set_ylabel('Wins')\n ax.set_xlabel('Points difference')\n ax.legend()\n ax.set_title('%s: Point differences vs wins by Red and Blue' % name)\n plt.show()",
"_____no_output_____"
],
[
"tkd = get_red_blue_points_differences('red-blue TKD.txt')\nboxing = get_red_blue_points_differences('red-blue boxing.txt')\ngr_wrestling = get_red_blue_points_differences('red-blue GR.txt')\nfw_wrestling = get_red_blue_points_differences('red-blue FW.txt')\nplot_point_differences(tkd, 'Tae Kwon Doe')\nplot_point_differences(boxing, 'Boxing')\nplot_point_differences(gr_wrestling, 'Greco Roman Wrestling')\nplot_point_differences(fw_wrestling, 'Freestyle Wrestling')",
"_____no_output_____"
]
],
[
[
"It does appear that for each of the sports, *excluding* Freestyle Wrestling, the distribution of Red wins are skewed towards the smaller points differences, as compared to the Blue wins.",
"_____no_output_____"
],
[
"We already saw from previous tests (parts A and B) that Red has a statistically significant higher chance of winning (p > 0.5). However, maybe these extra wins are due to the close games.\n\nHere we test a slightly different kind of hypothesis: Wearing Red vs Blue has an impact on how many points are scored over the opponent.\n\nWell actually we test the opposite as the null hypothesis:\n\nH0: The mean difference in Red vs Blue points is 0.\n\nIf this is the case, then, as the researchers suggested, the Red wins might be due to an advantage in the close contests rather than red having an impact on total point scoring.\n\nAs we can see above, the distribution of differences in points does not follow a normal distribution, so a non parametric test should be used.\n\nWe use the Wilcoxon signed-rank test on the observed differences, testing each sport separately.\n\nFrom Rice Section 11.3:\n\n\nThe Wilcoxon signed-rank test statistic is W = min{W+, W−} , where W+ is the sum of signed ranks that are positive and W− is the sum of ranks whose signs are negative.\n\nSince n > 20 for each sport, we use the normalized test statistic:\n\n$ Z = \\frac{W_+ - E(W_+)}{\\sqrt{Var(W+)}} $\n\n$ E(W_+) = \\frac{n(n+1)}{4} $\n\n$ Var(W_+) = \\frac{n(n + 1)(2n + 1)}{24} $\n\nWhen computing W+ we will consider Red wins as the positives (though it doesn't make a difference), so that the sign of the differences is the sign of (Red points - Blue points).",
"_____no_output_____"
]
],
[
[
"def get_signed_ranks(df):\n \"\"\" \n Assigns signed ranks and computes W+\n Returns W+, df\n \"\"\"\n df = df.sort_values('|Difference|').reset_index(drop=True)\n # get the ranks, handling ties\n differences = df['|Difference|']\n ranks = []\n r = []\n for index, d in differences.items():\n if (index > 0) and (d > differences[index - 1]):\n ranks += [np.mean(r) for i in range(len(r))]\n r = []\n r += [index+1]\n ranks += [np.mean(r) for i in range(len(r))]\n df['Rank'] = ranks\n df['Signed Rank'] = df.apply(lambda r: r['Rank'] * (-1 if r['Winner'] == 'Blue' else 1), axis=1)\n w_plus = df[df['Signed Rank']>0]['Signed Rank'].sum()\n return w_plus, df",
"_____no_output_____"
]
],
[
[
"Tae Kwon Doe",
"_____no_output_____"
]
],
[
[
"w, tkd = get_signed_ranks(tkd)\nn = len(tkd)\nexp_w = (n*(n+1))/4\nvar_w = (n*(n+1)*((2*n)+1))/24\nz = (w - exp_w)/(np.sqrt(var_w))\nprint('n = %s' % n)\nprint('W+ = %s' % w)\nprint('E(W+) = %s' % exp_w)\nprint('Var(W+) = %s' % var_w)\nprint('Z = %s' % z)\ntkd.head()",
"n = 70\nW+ = 1292.0\nE(W+) = 1242.5\nVar(W+) = 29198.75\nZ = 0.2896830397843113\n"
]
],
[
[
"Boxing",
"_____no_output_____"
]
],
[
[
"w, boxing = get_signed_ranks(boxing)\nn = len(boxing)\nexp_w = (n*(n+1))/4\nvar_w = (n*(n+1)*((2*n)+1))/24\nz = (w - exp_w)/(np.sqrt(var_w))\nprint('n = %s' % n)\nprint('W+ = %s' % w)\nprint('E(W+) = %s' % exp_w)\nprint('Var(W+) = %s' % var_w)\nprint('Z = %s' % z)\nboxing.head()",
"n = 233\nW+ = 13854.0\nE(W+) = 13630.5\nVar(W+) = 1060907.25\nZ = 0.2169895498296029\n"
]
],
[
[
"Greco Roman Wrestling",
"_____no_output_____"
]
],
[
[
"w, gr_wrestling = get_signed_ranks(gr_wrestling)\nn = len(gr_wrestling)\nexp_w = (n*(n+1))/4\nvar_w = (n*(n+1)*((2*n)+1))/24\nz = (w - exp_w)/(np.sqrt(var_w))\nprint('n = %s' % n)\nprint('W+ = %s' % w)\nprint('E(W+) = %s' % exp_w)\nprint('Var(W+) = %s' % var_w)\nprint('Z = %s' % z)\ngr_wrestling.head()",
"n = 51\nW+ = 580.5\nE(W+) = 663.0\nVar(W+) = 11381.5\nZ = -0.773311016598475\n"
]
],
[
[
"Freestyle Wrestling",
"_____no_output_____"
]
],
[
[
"w, fw_wrestling = get_signed_ranks(fw_wrestling)\nn = len(fw_wrestling)\nexp_w = (n*(n+1))/4\nvar_w = (n*(n+1)*((2*n)+1))/24\nz = (w - exp_w)/(np.sqrt(var_w))\nprint('n = %s' % n)\nprint('W+ = %s' % w)\nprint('E(W+) = %s' % exp_w)\nprint('Var(W+) = %s' % var_w)\nprint('Z = %s' % z)\nfw_wrestling.head()",
"n = 54\nW+ = 835.5\nE(W+) = 742.5\nVar(W+) = 13488.75\nZ = 0.8007502737021251\n"
]
],
[
[
"There is not strong evidence to reject the null hypothesis for any of these sports.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7abd4ee1db927bd17d7d87ec2d0e140418d2b35 | 5,736 | ipynb | Jupyter Notebook | docs/contents/basic/merge.ipynb | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | docs/contents/basic/merge.ipynb | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | docs/contents/basic/merge.ipynb | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | 26.191781 | 149 | 0.521792 | [
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"import molsysmt as msm",
"Warning: importing 'simtk.openmm' is deprecated. Import 'openmm' instead.\n"
]
],
[
[
"# Merge",
"_____no_output_____"
],
[
"## Merging molecular systems",
"_____no_output_____"
],
[
"A list of molecular systems are merged in to a new molecular system:",
"_____no_output_____"
]
],
[
[
"molsys_A = msm.build.build_peptide(['AceProNme',{'forcefield':'AMBER14', 'implicit_solvent':'OBC1'}])\nmolsys_B = msm.build.build_peptide(['AceValNme',{'forcefield':'AMBER14', 'implicit_solvent':'OBC1'}])\nmolsys_C = msm.build.build_peptide(['AceLysNme',{'forcefield':'AMBER14', 'implicit_solvent':'OBC1'}])",
"_____no_output_____"
],
[
"molsys_B = msm.structure.translate(molsys_B, translation='[-1.0, 0.0, 0.0] nanometers')\nmolsys_C = msm.structure.translate(molsys_C, translation='[1.0, 0.0, 0.0] nanometers')",
"_____no_output_____"
],
[
"molsys_D = msm.merge([molsys_A, molsys_B, molsys_C])",
"_____no_output_____"
],
[
"msm.info(molsys_D)",
"_____no_output_____"
],
[
"msm.view(molsys_D, standardize=True)",
"_____no_output_____"
]
],
[
[
"**Implementar o Checar**: Que pasa si quiero por ejemplo hacer merge de varios sistemas moleculares descritos por varios items? Por ejemplo:\n\nmsm.merge([[a.prmtop, a.inpcrd], [b.prmtop, b.inpcrd], [c.prmtop, c.inpcrd]])\n\no \n\nmsm.merge([[a.msm.topology, a.msm.trajectory], [b.msm.topology, b.msm.trajectory], [c.msm.topology, c.msm.trajectory]])",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown"
] | [
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7abdfe115b68c7239cc1ba5cfdf57098024d61f | 13,262 | ipynb | Jupyter Notebook | agrodem_preprocessing/Future_Scenarios/Converting raster to vector.ipynb | babakkhavari/agrodem | 8de2559afa5a5d1ea9498e52c4f7eeb35dbad0cc | [
"MIT"
] | 3 | 2020-04-24T17:04:17.000Z | 2021-01-17T10:52:08.000Z | agrodem_preprocessing/Future_Scenarios/Converting raster to vector.ipynb | babakkhavari/agrodem | 8de2559afa5a5d1ea9498e52c4f7eeb35dbad0cc | [
"MIT"
] | 39 | 2019-05-14T13:19:24.000Z | 2019-07-23T16:40:56.000Z | agrodem_preprocessing/Future_Scenarios/Converting raster to vector.ipynb | babakkhavari/agrodem | 8de2559afa5a5d1ea9498e52c4f7eeb35dbad0cc | [
"MIT"
] | 10 | 2019-09-19T13:37:18.000Z | 2021-02-09T15:58:17.000Z | 31.803357 | 192 | 0.530463 | [
[
[
"# Converting raster to vector\n\nA cluster of functions that convert raster (.tiff) files generated as part of future scenario pipeline code, to vector (point shapefile) files.\n\n**Original code:** [Konstantinos Pegios](https://github.com/kopegios) <br />\n**Conceptualization & Methodological review :** [Alexandros Korkovelos](https://github.com/akorkovelos) & [Konstantinos Pegios](https://github.com/kopegios)<br />\n**Updates, Modifications:** [Alexandros Korkovelos](https://github.com/akorkovelos) <br />\n**Funding:** The World Bank (contract number: 7190531), [KTH](https://www.kth.se/en/itm/inst/energiteknik/forskning/desa/welcome-to-the-unit-of-energy-systems-analysis-kth-desa-1.197296)",
"_____no_output_____"
]
],
[
[
"# Importing necessary modules\n\nimport geopandas as gpd\nimport rasterio as rio\nimport pandas as pd\nimport fiona\nimport gdal\nimport osr\nimport ogr\nimport rasterio.mask\nimport time\nimport os\nimport ogr, gdal, osr, os\nimport numpy as np\nimport itertools\nimport re\nfrom rasterio.warp import calculate_default_transform, reproject\nfrom rasterio.enums import Resampling\nfrom rasterstats import point_query\nfrom pyproj import Proj",
"_____no_output_____"
]
],
[
[
"### Raster (Re)projection to target CRS\n\nThis step is not necessary if the raster file is already in the target CRS",
"_____no_output_____"
]
],
[
[
"# Define project function\n\ndef reproj(input_raster, output_raster, new_crs, factor):\n dst_crs = new_crs\n\n with rio.open(input_raster) as src:\n transform, width, height = calculate_default_transform(\n src.crs, dst_crs, src.width*factor, src.height*factor, *src.bounds)\n kwargs = src.meta.copy()\n kwargs.update({\n 'crs': dst_crs,\n 'transform': transform,\n 'width': width,\n 'height': height\n })\n\n with rio.open(output_raster, 'w', **kwargs) as dst:\n for i in range(1, src.count + 1):\n reproject(\n source=rio.band(src, i),\n destination=rio.band(dst, i),\n src_transform=src.transform,\n src_crs=src.crs,\n dst_transform=transform,\n dst_crs=dst_crs,\n resampling=Resampling.nearest)",
"_____no_output_____"
],
[
"# Set inout directories\ninpath = r\"N:\\Agrodem\\Future_Scenarios\\maize_cassava_scenarios\\maize_cassava_scenarios\"\noutpath= r\"N:\\Agrodem\\Future_Scenarios\\maize_cassava_scenarios\\maize_cassava_scenarios\\re_projected\"\n\n# Provide the input raster and give a name to the output (reprojected) raster\ninput_raster = inpath + \"\\\\\" + \"cassava_SG.tif\"\noutput_raster = outpath + \"\\\\\" + \"cassava_SG_reproj.tif\"\n\n# Set target CRS\nnew_crs = \"epsg:4326\"\n\n# Provide a factor if you want zoomed in/out results; suggest keeping it to one unless fully understanding the implications\nfactor = 1",
"_____no_output_____"
],
[
"# Run function \nreproj(input_raster, output_raster, new_crs, factor)",
"_____no_output_____"
]
],
[
[
"### Converting raster to shapefile",
"_____no_output_____"
]
],
[
[
"# Define functions\n\ndef pixelOffset2coord(raster, xOffset,yOffset):\n geotransform = raster.GetGeoTransform()\n originX = geotransform[0]\n originY = geotransform[3]\n pixelWidth = geotransform[1]\n pixelHeight = geotransform[5]\n coordX = originX+pixelWidth*xOffset\n coordY = originY+pixelHeight*yOffset\n return coordX, coordY\n\ndef raster2array(rasterfn):\n raster = gdal.Open(rasterfn)\n band = raster.GetRasterBand(1)\n array = band.ReadAsArray()\n return array\n\ndef array2shp(array,outSHPfn,rasterfn):\n\n # max distance between points\n raster = gdal.Open(rasterfn)\n geotransform = raster.GetGeoTransform()\n pixelWidth = geotransform[1]\n\n srs = osr.SpatialReference()\n srs.ImportFromWkt(raster.GetProjection())\n \n # wkbPoint\n shpDriver = ogr.GetDriverByName(\"ESRI Shapefile\")\n if os.path.exists(outSHPfn):\n shpDriver.DeleteDataSource(outSHPfn)\n outDataSource = shpDriver.CreateDataSource(outSHPfn)\n outLayer = outDataSource.CreateLayer(outSHPfn, geom_type=ogr.wkbPoint, srs=srs )\n featureDefn = outLayer.GetLayerDefn()\n outLayer.CreateField(ogr.FieldDefn(\"VALUE\", ogr.OFTInteger))\n\n # array2dict\n point = ogr.Geometry(ogr.wkbPoint)\n row_count = array.shape[0]\n for ridx, row in enumerate(array):\n# print(\"Printing ridx..\")\n# print(ridx)\n if ridx % 100 == 0:\n print (\"{0} of {1} rows processed\".format(ridx, row_count))\n for cidx, value in enumerate(row):\n #print(\"Printing cidx..\")\n #print(cidx)\n #Only positive values\n if value > 0:\n Xcoord, Ycoord = pixelOffset2coord(raster,cidx,ridx)\n point.AddPoint(Xcoord, Ycoord)\n outFeature = ogr.Feature(featureDefn)\n outFeature.SetGeometry(point)\n outFeature.SetField(\"VALUE\", int(ridx))\n outLayer.CreateFeature(outFeature)\n outFeature.Destroy()\n #outDS.Destroy()\n\ndef main(rasterfn,outSHPfn):\n array = raster2array(rasterfn)\n array2shp(array,outSHPfn,rasterfn)",
"_____no_output_____"
],
[
"# Set inout directories\ninpath = r\"N:\\Agrodem\\Future_Scenarios\\maize_cassava_scenarios\\maize_cassava_scenarios\\re_projected\"\noutpath= r\"N:\\Agrodem\\Future_Scenarios\\maize_cassava_scenarios\\maize_cassava_scenarios\\vectorfiles\"\n\n# Provide the input raster and give a name to the output (reprojected) raster\nrasterfn = inpath + \"\\\\\" + \"cassava_SG_reproj.tif\"\noutSHPfn = outpath + \"\\\\\" + \"cassava_SG.shp\"",
"_____no_output_____"
],
[
"# Run the function\nmain(rasterfn,outSHPfn)",
"0 of 3580 rows processed\n100 of 3580 rows processed\n200 of 3580 rows processed\n300 of 3580 rows processed\n400 of 3580 rows processed\n500 of 3580 rows processed\n600 of 3580 rows processed\n700 of 3580 rows processed\n800 of 3580 rows processed\n900 of 3580 rows processed\n1000 of 3580 rows processed\n1100 of 3580 rows processed\n1200 of 3580 rows processed\n1300 of 3580 rows processed\n1400 of 3580 rows processed\n1500 of 3580 rows processed\n1600 of 3580 rows processed\n1700 of 3580 rows processed\n1800 of 3580 rows processed\n1900 of 3580 rows processed\n2000 of 3580 rows processed\n2100 of 3580 rows processed\n2200 of 3580 rows processed\n2300 of 3580 rows processed\n2400 of 3580 rows processed\n2500 of 3580 rows processed\n2600 of 3580 rows processed\n2700 of 3580 rows processed\n2800 of 3580 rows processed\n2900 of 3580 rows processed\n3000 of 3580 rows processed\n3100 of 3580 rows processed\n3200 of 3580 rows processed\n3300 of 3580 rows processed\n3400 of 3580 rows processed\n3500 of 3580 rows processed\n"
]
],
[
[
"### Assigning lat/long columns to the shapefile",
"_____no_output_____"
]
],
[
[
"# Import as geodataframe\npath_shp = r\"N:\\Agrodem\\Future_Scenarios\\maize_cassava_scenarios\\maize_cassava_scenarios\\vectorfiles\"\nname_shp = \"cassava_SG.shp\"\nfuture_crop_gdf = gpd.read_file(path_shp + \"\\\\\" + name_shp)",
"_____no_output_____"
],
[
"# Creating lon/lat columns\nfuture_crop_gdf['lon'] = future_crop_gdf[\"geometry\"].x\nfuture_crop_gdf['lat'] = future_crop_gdf[\"geometry\"].y",
"_____no_output_____"
],
[
"future_crop_gdf.head(3)",
"_____no_output_____"
]
],
[
[
"#### Exporting file back to shp or gpkg",
"_____no_output_____"
]
],
[
[
"# Define output path\npath = r\"N:\\Agrodem\\Future_Scenarios\\maize_cassava_scenarios\\maize_cassava_scenarios\\vectorfiles\"\nname_shp = \"cassava_SG.shp\"\n\n#dshp\nfuture_crop_gdf.to_file(os.path.join(path,name_shp), index=False)\n\n#gpkg\n#future_crop_gdf.to_file(\"maize_BAU.gpkg\", layer='Maize_Inputfile_Future', driver=\"GPKG\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7abe7d22ad726a3605018cf0eaae9637e0152ce | 11,867 | ipynb | Jupyter Notebook | errordist.ipynb | akashlevy/RRAM-DNN-Quantized | 535a1aad7a56e13455c541375b3811fd5eca7026 | [
"MIT"
] | 2 | 2021-09-21T19:33:43.000Z | 2021-09-21T19:33:53.000Z | errordist.ipynb | akashlevy/RRAM-DNN-Quantized | 535a1aad7a56e13455c541375b3811fd5eca7026 | [
"MIT"
] | null | null | null | errordist.ipynb | akashlevy/RRAM-DNN-Quantized | 535a1aad7a56e13455c541375b3811fd5eca7026 | [
"MIT"
] | null | null | null | 91.284615 | 7,350 | 0.744333 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Confusion matrix for one RRAM cell (test)\nCM = [[0.99, 0.01, 0, 0], [0.01, 0.98, 0.01, 0], [0, 0.01, 0.98, 0.01], [0, 0, 0.01, 0.99]]\nCM = [[0.95, 0.05, 0, 0], [0.05, 0.95, 0, 0], [0, 0, 0.95, 0.05], [0, 0, 0.05, 0.95]]\nCM = np.array(CM)\n\n# Kronecker confusion matrix for two RRAM cells (test)\nKCM = np.kron(CM, CM)\norder = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15]\nKCM = KCM[np.ix_(order, order)]\nprint(KCM)\n\n# Weight probability matrix\nWPM = 1/16 * np.ones(16)\nWPM\n\n# Error distribution matrix\nEDM = np.zeros((16, 32))\nfor i in range(16):\n for j in range(16):\n EDM[i][i-j+16] += KCM[i][j]\n\n# Error distribution vector with weight probabilities accounted for\nEDV = np.dot(EDM.T, WPM)\n\n# CDF of error distribution\nCDF = np.cumsum(EDV)\nplt.plot(np.arange(-16, 16), CDF)\n\nvariance = np.dot(EDV, np.arange(-16, 16)**2)\nvariance",
"[[0.9025 0.0475 0.0475 0.0025 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [0.0475 0.9025 0.0025 0.0475 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [0.0475 0.0025 0.9025 0.0475 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [0.0025 0.0475 0.0475 0.9025 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0.9025 0.0475 0.0475 0.0025 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0.0475 0.9025 0.0025 0.0475 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0.0475 0.0025 0.9025 0.0475 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0.0025 0.0475 0.0475 0.9025 0. 0.\n 0. 0. 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.9025 0.0475\n 0.0475 0.0025 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.0475 0.9025\n 0.0025 0.0475 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.0475 0.0025\n 0.9025 0.0475 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0. 0. 0. 0. 0.0025 0.0475\n 0.0475 0.9025 0. 0. 0. 0. ]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0.9025 0.0475 0.0475 0.0025]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0.0475 0.9025 0.0025 0.0475]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0.0475 0.0025 0.9025 0.0475]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0.0025 0.0475 0.0475 0.9025]]\n"
]
]
] | [
"code"
] | [
[
"code"
]
] |
e7abed17e22e2f3fbb2d8adebb61b94b744559aa | 11,475 | ipynb | Jupyter Notebook | docs/tutorials/2_candidate_config.ipynb | networktocode/ntc-rosetta-conf | 06c8028e0bbafdd97d15e14ca13faa2601345d8b | [
"Apache-2.0"
] | 5 | 2019-07-31T03:06:48.000Z | 2020-09-01T21:51:04.000Z | docs/tutorials/2_candidate_config.ipynb | networktocode/ntc-rosetta-conf | 06c8028e0bbafdd97d15e14ca13faa2601345d8b | [
"Apache-2.0"
] | 1 | 2020-12-14T15:02:05.000Z | 2020-12-14T15:02:05.000Z | docs/tutorials/2_candidate_config.ipynb | networktocode/ntc-rosetta-conf | 06c8028e0bbafdd97d15e14ca13faa2601345d8b | [
"Apache-2.0"
] | 1 | 2021-04-05T09:53:53.000Z | 2021-04-05T09:53:53.000Z | 27.12766 | 254 | 0.461176 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7abf4d252ad3ca17f581d2ad6cfafda64f9ea56 | 9,089 | ipynb | Jupyter Notebook | EvaluativeFeedback/TenArmedTestbed.ipynb | xiaorancs/xr-reinforcement-learning | 7f262c5497edf11e3eb7eb6c964a84eec11c5626 | [
"BSD-2-Clause"
] | null | null | null | EvaluativeFeedback/TenArmedTestbed.ipynb | xiaorancs/xr-reinforcement-learning | 7f262c5497edf11e3eb7eb6c964a84eec11c5626 | [
"BSD-2-Clause"
] | null | null | null | EvaluativeFeedback/TenArmedTestbed.ipynb | xiaorancs/xr-reinforcement-learning | 7f262c5497edf11e3eb7eb6c964a84eec11c5626 | [
"BSD-2-Clause"
] | null | null | null | 34.298113 | 114 | 0.469579 | [
[
[
"#######################################################################\n# Copyright (C) #\n# 2016 Shangtong Zhang([email protected]) #\n# 2016 Jan Hakenberg([email protected]) #\n# 2016 Tian Jun([email protected]) #\n# 2016 Kenta Shimada([email protected]) #\n# update ---> #\n# 2018 Ran Xiao([email protected]) #\n# python3.5 #\n#######################################################################\n",
"_____no_output_____"
],
[
"from __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n",
"_____no_output_____"
]
],
[
[
"强化学习第二章的例子的代码,10臂赌博问题,首先建立一个k臂赌博者的类。\n",
"_____no_output_____"
]
],
[
[
"class Bandit:\n '''参数:\n kArm: int, 赌博臂的个数\n epsilon: double, e-贪心算法的概率值\n initial: 每个行为的行为的初始化估计\n stepSize: double,更加估计值的常数步数\n sampleAverages: if ture, 使用简单的均值方法替代stepSize权重更新\n UCB: 不是None时,使用UCB算法,(初始值优化算法)\n gradient: if ture, 使用算法的选择的基础标志(过去的均值作为基准,评价现在的值)\n gradientBaseline: if true, 使用过去的奖励的平均值\n '''\n def __init__(self, kArm=10, epsilon=0., initial=0., stepSize=0.1, \n sampleAverages=False,UCB=None, gradient=False, \n gradientBaseline=False, trueReward=0.):\n self.k = kArm\n self.epsilon = epsilon\n self.stepSize = stepSize\n self.sampleAverages = sampleAverages\n self.indices = np.arange(self.k) # 有kArm个选择\n self.time = 0 # 总的选择次数 ??\n self.UCB = UCB\n self.gradient = gradient\n self.gradientBaseline = gradientBaseline\n self.averageReward = 0\n self.trueReward = trueReward\n \n # 记录每个行为的真实奖励\n self.qTrue = []\n \n # 记录每个行为的估计值\n self.qEst = np.zeros(self.k)\n \n # 记录每个行为被选择的次数\n self.actionCount = []\n \n # 使用N(0,1)高斯分布+trueReward,初始化真是的奖励\n # 使用初始值initial初始化估计值\n for i in range(0,self.k):\n self.qTrue.append(np.random.randn()+trueReward)\n self.qEst[i] = initial\n self.actionCount.append(0)\n \n # 得到正在的最好的选择对饮的k臂\n self.bestAction = np.argmax(self.qTrue)\n \n # 对于这个bandit游戏,选择一个行为,使用explore(评估) or exploit(探索)\n def getAction(self):\n # explore(评估)\n # 使用epsilon-greedy算法,每次以概率epsilon随机选择一个行为,\n # 否则使用贪心规则\n if self.epsilon > 0: \n if np.random.binomial(1,self.epsilon) == 1:# 打乱,随机选择\n np.random.shuffle(self.indices)\n return self.indices[0]\n \n # exploit\n # 使用初始值优化这个算法\n if self.UCB is not None:\n UCBEst = self.qEst + self.UCB * np.sqrt(np.log(self.time+1) / np.asarray(self.actionCount)+1)\n return np.argmax(UCBEst)\n \n # 使用基准线评测,增强比较\n if self.gradient:\n # softmax计算每个行为的偏好程度\n expEst = np.exp(self.qEst)\n self.actionProb = expEst / np.sum(expEst)\n # 根据概率随机选择\n return np.random.choice(self.indices,p=self.actionProb)\n # 选择最大值的下标\n return np.argmax(self.qEst)\n \n # 采取何种行为\n def takeAction(self, action):\n # 基于N(real reward, 1)产生一个奖励\n reward = np.random.randn() + self.qTrue[action]\n # 次数加1\n self.time += 1\n # 迭代计算平均奖励\n self.averageReward = (self.time - 1.0) / self.time * self.averageReward + reward / self.time\n self.actionCount[action] += 1\n \n if self.sampleAverages:\n # 使用简单平均值更新估计值\n self.qEst[action] += 1.0 / self.actionCount[action] * (reward - self.qEst[action])\n elif self.gradient:\n oneHot = np.zeros(self.k)\n oneHot[action] = 1\n if self.gradientBaseline:\n baseline = gradientBaseline\n else:\n baseline = 0\n # 基于选择,全部更新值,选中的action进行加,没有选中的进行减去一个值\n self.qEst = self.qEst + self.stepSize * (reward - baseline) * (oneHot - self.actionProb)\n else:\n # 固定步长更新值\n self.qEst += self.stepSize * (reward - self.qEst[action])\n \n return reward\n ",
"_____no_output_____"
],
[
"figureIndex = 0\n\n# 做出对应的图,figure 2.1\ndef figure2_1():\n global figureIndex\n figureIndex += 1\n sns.violinplot(data=np.random.randn(200,10) + np.random.randn(10))\n plt.xlabel('Action')\n plt.ylabel('Reward distribution')\n\n\ndef banditSimulation(nBandits, time, bandits):\n bestActionCounts = [np.zeros(time, dtype='float') for _ in range(0, len(bandits))]\n averageRewards = [np.zeros(time, dtype='float') for _ in range(0, len(bandits))]\n for banditInd, bandit in enumerate(bandits):\n for i in range(0, nBandits):\n for t in range(0, time):\n action = bandit[i].getAction()\n reward = bandit[i].takeAction(action)\n averageRewards[banditInd][t] += reward\n if action == bandit[i].bestAction:\n bestActionCounts[banditInd][t] += 1\n bestActionCounts[banditInd] /= nBandits\n averageRewards[banditInd] /= nBandits\n return bestActionCounts, averageRewards\n\n\n# for figure 2.2\ndef epsilonGreedy(nBandits, time):\n epsilons = [0, 0.1, 0.01]\n # 赌博的个数\n bandits = []\n for epsInd, eps in enumerate(epsilons):\n bandits.append([Bandit(epsilon=eps, sampleAverages=True) for _ in range(0,nBandits)])\n \n bestActionCounts, avetageReward = banditSimulation(nBandits, time, bandits)\n global figureIndex\n plt.figure(figureIndex)\n figureIndex += 1\n for eps, counts in zip(epsilons, beatActionCounts):\n plt.plot(counts, label='epsilon='+str(eps))\n plt.xlabel('Steps')\n plt.ylabel('% optimal action')\n plt.legend()\n plt.figure(figureIndex)\n figureIndex += 1\n for eps, reward in zip(epsilons, avetageReward):\n plt.plot(reward, label='epsolon='+str(eps))\n plt.xlabel('Steps')\n plt.ylabel('average reward')\n plt.legend()\n \n \n ",
"_____no_output_____"
],
[
"figure2_1()\n\nepsilonGreedy(2000,1000)\n\nplt.show()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7abf7731bf19f98885459f1c65b00428c1d872e | 39,412 | ipynb | Jupyter Notebook | Deep_Learning_with_TensorFlow/1.4.0/Chapter06/.ipynb_checkpoints/fine_tuning-checkpoint.ipynb | Asurada2015/TensorFlow_Google_Practice | 0ea7d52a4056e5e53391a452a9bbd468175af7f5 | [
"MIT"
] | 14 | 2018-03-07T00:44:25.000Z | 2019-08-25T03:06:58.000Z | Deep_Learning_with_TensorFlow/1.4.0/Chapter06/.ipynb_checkpoints/fine_tuning-checkpoint.ipynb | Asurada2015/TensorFlow_Google_Practice | 0ea7d52a4056e5e53391a452a9bbd468175af7f5 | [
"MIT"
] | 1 | 2018-10-15T12:04:05.000Z | 2018-10-15T12:04:05.000Z | Deep_Learning_with_TensorFlow/1.4.0/Chapter06/.ipynb_checkpoints/fine_tuning-checkpoint.ipynb | Asurada2015/TensorFlow_Google_Practice | 0ea7d52a4056e5e53391a452a9bbd468175af7f5 | [
"MIT"
] | 10 | 2018-05-20T10:46:56.000Z | 2020-04-17T11:50:40.000Z | 63.876823 | 1,633 | 0.725591 | [
[
[
"# -*- coding: utf-8 -*-\n\nimport glob\nimport os.path\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.platform import gfile\nimport tensorflow.contrib.slim as slim\n\n# 因为slim.nets包在 tensorflow 1.3 中有一些问题,所以这里为了方便\n# 我们将slim.nets.inception_v3中的代码拷贝到了同一个文件夹下。\nimport inception_v3\n\n# 处理好之后的数据文件。\nINPUT_DATA = 'flower_processed_data.npy'\n# 保存训练好的模型的路径。这里我们可以将使用新数据训练得到的完整模型保存\n# 下来,如果计算资源充足,我们还可以在训练完最后的全联接层之后再训练所有\n# 网络层,这样可以使得新模型更加贴近新数据。\nTRAIN_FILE = 'train_dir/model'\n# 谷歌提供的训练好的模型文件地址。\nCKPT_FILE = 'inception_v3.ckpt'\n\n# 定义训练中使用的参数。\nLEARNING_RATE = 0.01\nSTEPS = 5000\nBATCH = 128\nN_CLASSES = 5\n\n# 不需要从谷歌训练好的模型中加载的参数。这里就是最后的全联接层,因为在\n# 新的问题中我们要重新训练这一层中的参数。这里给出的是参数的前缀。\nCHECKPOINT_EXCLUDE_SCOPES = 'InceptionV3/Logits,InceptionV3/AuxLogits'\n# 需要训练的网络层参数明层,在fine-tuning的过程中就是最后的全联接层。\n# 这里给出的是参数的前缀。\nTRAINABLE_SCOPES='InceptionV3/Logits'\n\n# 获取所有需要从谷歌训练好的模型中加载的参数。\ndef get_tuned_variables():\n exclusions = [scope.strip() for scope in CHECKPOINT_EXCLUDE_SCOPES.split(',')]\n\n variables_to_restore = []\n # 枚举inception-v3模型中所有的参数,然后判断是否需要从加载列表中\n # 移除。\n for var in slim.get_model_variables():\n print var.op.name\n excluded = False\n for exclusion in exclusions:\n if var.op.name.startswith(exclusion):\n excluded = True\n break\n if not excluded:\n variables_to_restore.append(var)\n return variables_to_restore\n\n# 获取所有需要训练的变量列表。\ndef get_trainable_variables(): \n scopes = [scope.strip() for scope in TRAINABLE_SCOPES.split(',')]\n variables_to_train = []\n # 枚举所有需要训练的参数前缀,并通过这些前缀找到所有的参数。\n for scope in scopes:\n variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)\n variables_to_train.extend(variables)\n return variables_to_train\n \ndef main():\n # 加载预处理好的数据。\n processed_data = np.load(INPUT_DATA)\n training_images = processed_data[0]\n n_training_example = len(training_images)\n training_labels = processed_data[1]\n validation_images = processed_data[2]\n validation_labels = processed_data[3]\n testing_images = processed_data[4]\n testing_labels = processed_data[5]\n\n # 定义inception-v3的输入,images为输入图片,labels为每一张图片\n # 对应的标签。\n images = tf.placeholder(\n tf.float32, [None, 299, 299, 3], \n name='input_images')\n labels = tf.placeholder(tf.int64, [None], name='labels')\n \n # 定义inception-v3模型。因为谷歌给出的只有模型参数取值,所以这里\n # 需要在这个代码中定义inception-v3的模型结构。因为模型\n # 中使用到了dropout,所以需要定一个训练时使用的模型,一个测试时\n # 使用的模型。\n with slim.arg_scope(inception_v3.inception_v3_arg_scope()):\n train_logits, _ = inception_v3.inception_v3(\n images, num_classes=N_CLASSES, is_training=True)\n # 定义测试使用的模型时需要将reuse设置为True。\n test_logits, _ = inception_v3.inception_v3(\n images, num_classes=N_CLASSES, is_training=False, reuse=True)\n \n \n trainable_variables = get_trainable_variables()\n print trainable_variables\n \n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(\n logits=train_logits, \n labels=tf.one_hot(labels, N_CLASSES))\n cross_entropy_mean = tf.reduce_mean(cross_entropy)\n train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(\n cross_entropy_mean,\n var_list=trainable_variables)\n \n # 计算正确率。\n with tf.name_scope('evaluation'):\n correct_prediction = tf.equal(tf.argmax(test_logits, 1), labels)\n evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n \n # \n loader = tf.train.Saver(get_tuned_variables())\n saver = tf.train.Saver()\n with tf.variable_scope(\"InceptionV3\", reuse = True):\n check1 = tf.get_variable(\"Conv2d_1a_3x3/weights\")\n check2 = tf.get_variable(\"Logits/Conv2d_1c_1x1/weights\")\n \n with tf.Session() as sess:\n # 初始化没有加载进来的变量。\n init = tf.global_variables_initializer()\n sess.run(init)\n print sess.run(check1)\n print sess.run(check2)\n \n # 加载谷歌已经训练好的模型。\n print('Loading tuned variables from %s' % CKPT_FILE)\n loader.restore(sess, CKPT_FILE)\n \n start = 0\n end = BATCH\n for i in range(STEPS):\n print sess.run(check1)\n print sess.run(check2)\n \n _, loss = sess.run([train_step, cross_entropy_mean], feed_dict={\n images: training_images[start:end], \n labels: training_labels[start:end]})\n\n if i % 100 == 0 or i + 1 == STEPS:\n saver.save(sess, TRAIN_FILE, global_step=i)\n validation_accuracy = sess.run(evaluation_step, feed_dict={\n images: validation_images, labels: validation_labels})\n print('Step %d: Training loss is %.1f%% Validation accuracy = %.1f%%' % (\n i, loss * 100.0, validation_accuracy * 100.0))\n \n start = end\n if start == n_training_example:\n start = 0\n \n end = start + BATCH\n if end > n_training_example: \n end = n_training_example\n \n # 在最后的测试数据上测试正确率。\n test_accuracy = sess.run(evaluation_step, feed_dict={\n images: test_images, labels: test_labels})\n print('Final test accuracy = %.1f%%' % (test_accuracy * 100))\n\nif __name__ == '__main__':\n main()",
"[<tf.Variable 'InceptionV3/Logits/Conv2d_1c_1x1/weights:0' shape=(1, 1, 2048, 5) dtype=float32_ref>, <tf.Variable 'InceptionV3/Logits/Conv2d_1c_1x1/biases:0' shape=(5,) dtype=float32_ref>]\nInceptionV3/Conv2d_1a_3x3/weights\nInceptionV3/Conv2d_1a_3x3/BatchNorm/beta\nInceptionV3/Conv2d_1a_3x3/BatchNorm/moving_mean\nInceptionV3/Conv2d_1a_3x3/BatchNorm/moving_variance\nInceptionV3/Conv2d_2a_3x3/weights\nInceptionV3/Conv2d_2a_3x3/BatchNorm/beta\nInceptionV3/Conv2d_2a_3x3/BatchNorm/moving_mean\nInceptionV3/Conv2d_2a_3x3/BatchNorm/moving_variance\nInceptionV3/Conv2d_2b_3x3/weights\nInceptionV3/Conv2d_2b_3x3/BatchNorm/beta\nInceptionV3/Conv2d_2b_3x3/BatchNorm/moving_mean\nInceptionV3/Conv2d_2b_3x3/BatchNorm/moving_variance\nInceptionV3/Conv2d_3b_1x1/weights\nInceptionV3/Conv2d_3b_1x1/BatchNorm/beta\nInceptionV3/Conv2d_3b_1x1/BatchNorm/moving_mean\nInceptionV3/Conv2d_3b_1x1/BatchNorm/moving_variance\nInceptionV3/Conv2d_4a_3x3/weights\nInceptionV3/Conv2d_4a_3x3/BatchNorm/beta\nInceptionV3/Conv2d_4a_3x3/BatchNorm/moving_mean\nInceptionV3/Conv2d_4a_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_5b/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_5b/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_5b/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5b/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5b/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_5b/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_5b/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5b/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5b/Branch_1/Conv2d_0b_5x5/weights\nInceptionV3/Mixed_5b/Branch_1/Conv2d_0b_5x5/BatchNorm/beta\nInceptionV3/Mixed_5b/Branch_1/Conv2d_0b_5x5/BatchNorm/moving_mean\nInceptionV3/Mixed_5b/Branch_1/Conv2d_0b_5x5/BatchNorm/moving_variance\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0b_3x3/weights\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0b_3x3/BatchNorm/beta\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0c_3x3/weights\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0c_3x3/BatchNorm/beta\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0c_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_5b/Branch_2/Conv2d_0c_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_5b/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_5b/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_5b/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5b/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5c/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_5c/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_5c/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5c/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5c/Branch_1/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_5c/Branch_1/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_5c/Branch_1/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5c/Branch_1/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5c/Branch_1/Conv_1_0c_5x5/weights\nInceptionV3/Mixed_5c/Branch_1/Conv_1_0c_5x5/BatchNorm/beta\nInceptionV3/Mixed_5c/Branch_1/Conv_1_0c_5x5/BatchNorm/moving_mean\nInceptionV3/Mixed_5c/Branch_1/Conv_1_0c_5x5/BatchNorm/moving_variance\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0b_3x3/weights\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0b_3x3/BatchNorm/beta\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0c_3x3/weights\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0c_3x3/BatchNorm/beta\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0c_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_5c/Branch_2/Conv2d_0c_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_5c/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_5c/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_5c/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5c/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5d/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_5d/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_5d/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5d/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5d/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_5d/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_5d/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5d/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5d/Branch_1/Conv2d_0b_5x5/weights\nInceptionV3/Mixed_5d/Branch_1/Conv2d_0b_5x5/BatchNorm/beta\nInceptionV3/Mixed_5d/Branch_1/Conv2d_0b_5x5/BatchNorm/moving_mean\nInceptionV3/Mixed_5d/Branch_1/Conv2d_0b_5x5/BatchNorm/moving_variance\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0b_3x3/weights\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0b_3x3/BatchNorm/beta\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0c_3x3/weights\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0c_3x3/BatchNorm/beta\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0c_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_5d/Branch_2/Conv2d_0c_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_5d/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_5d/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_5d/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_5d/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6a/Branch_0/Conv2d_1a_1x1/weights\nInceptionV3/Mixed_6a/Branch_0/Conv2d_1a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6a/Branch_0/Conv2d_1a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6a/Branch_0/Conv2d_1a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6a/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6a/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6a/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6a/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6a/Branch_1/Conv2d_0b_3x3/weights\nInceptionV3/Mixed_6a/Branch_1/Conv2d_0b_3x3/BatchNorm/beta\nInceptionV3/Mixed_6a/Branch_1/Conv2d_0b_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_6a/Branch_1/Conv2d_0b_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_6a/Branch_1/Conv2d_1a_1x1/weights\nInceptionV3/Mixed_6a/Branch_1/Conv2d_1a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6a/Branch_1/Conv2d_1a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6a/Branch_1/Conv2d_1a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6b/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0b_1x7/weights\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0b_1x7/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0c_7x1/weights\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0c_7x1/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0b_7x1/weights\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0b_7x1/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0b_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0b_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0c_1x7/weights\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0c_1x7/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0c_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0c_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0d_7x1/weights\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0d_7x1/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0d_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0d_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0e_1x7/weights\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0e_1x7/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0e_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_2/Conv2d_0e_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6b/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_6b/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_6b/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6b/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6c/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0b_1x7/weights\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0b_1x7/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0c_7x1/weights\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0c_7x1/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0b_7x1/weights\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0b_7x1/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0b_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0b_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0c_1x7/weights\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0c_1x7/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0c_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0c_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0d_7x1/weights\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0d_7x1/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0d_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0d_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0e_1x7/weights\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0e_1x7/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0e_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_2/Conv2d_0e_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6c/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_6c/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_6c/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6c/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6d/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0b_1x7/weights\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0b_1x7/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0c_7x1/weights\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0c_7x1/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0b_7x1/weights\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0b_7x1/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0b_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0b_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0c_1x7/weights\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0c_1x7/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0c_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0c_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0d_7x1/weights\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0d_7x1/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0d_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0d_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0e_1x7/weights\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0e_1x7/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0e_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_2/Conv2d_0e_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6d/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_6d/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_6d/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6d/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6e/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0b_1x7/weights\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0b_1x7/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0c_7x1/weights\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0c_7x1/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0b_7x1/weights\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0b_7x1/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0b_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0b_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0c_1x7/weights\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0c_1x7/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0c_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0c_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0d_7x1/weights\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0d_7x1/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0d_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0d_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0e_1x7/weights\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0e_1x7/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0e_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_2/Conv2d_0e_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_6e/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_6e/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_6e/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_6e/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7a/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_7a/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_7a/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7a/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7a/Branch_0/Conv2d_1a_3x3/weights\nInceptionV3/Mixed_7a/Branch_0/Conv2d_1a_3x3/BatchNorm/beta\nInceptionV3/Mixed_7a/Branch_0/Conv2d_1a_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_7a/Branch_0/Conv2d_1a_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0b_1x7/weights\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0b_1x7/BatchNorm/beta\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_mean\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0b_1x7/BatchNorm/moving_variance\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0c_7x1/weights\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0c_7x1/BatchNorm/beta\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7a/Branch_1/Conv2d_0c_7x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7a/Branch_1/Conv2d_1a_3x3/weights\nInceptionV3/Mixed_7a/Branch_1/Conv2d_1a_3x3/BatchNorm/beta\nInceptionV3/Mixed_7a/Branch_1/Conv2d_1a_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_7a/Branch_1/Conv2d_1a_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_7b/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0b_1x3/weights\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0b_1x3/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0b_1x3/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0b_1x3/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0b_3x1/weights\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0b_3x1/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0b_3x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_1/Conv2d_0b_3x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0b_3x3/weights\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0b_3x3/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0c_1x3/weights\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0c_1x3/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0c_1x3/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0c_1x3/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0d_3x1/weights\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0d_3x1/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0d_3x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_2/Conv2d_0d_3x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7b/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_7b/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_7b/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7b/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_0/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_7c/Branch_0/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_0/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0b_1x3/weights\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0b_1x3/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0b_1x3/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0b_1x3/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0c_3x1/weights\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0c_3x1/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0c_3x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_1/Conv2d_0c_3x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0a_1x1/weights\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0a_1x1/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0a_1x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0b_3x3/weights\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0b_3x3/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0b_3x3/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0c_1x3/weights\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0c_1x3/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0c_1x3/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0c_1x3/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0d_3x1/weights\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0d_3x1/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0d_3x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_2/Conv2d_0d_3x1/BatchNorm/moving_variance\nInceptionV3/Mixed_7c/Branch_3/Conv2d_0b_1x1/weights\nInceptionV3/Mixed_7c/Branch_3/Conv2d_0b_1x1/BatchNorm/beta\nInceptionV3/Mixed_7c/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_mean\nInceptionV3/Mixed_7c/Branch_3/Conv2d_0b_1x1/BatchNorm/moving_variance\nInceptionV3/AuxLogits/Conv2d_1b_1x1/weights\nInceptionV3/AuxLogits/Conv2d_1b_1x1/BatchNorm/beta\nInceptionV3/AuxLogits/Conv2d_1b_1x1/BatchNorm/moving_mean\nInceptionV3/AuxLogits/Conv2d_1b_1x1/BatchNorm/moving_variance\nInceptionV3/AuxLogits/Conv2d_2a_5x5/weights\n"
]
]
] | [
"code"
] | [
[
"code"
]
] |
e7ac012743ae17fe745c32f4548ffdae18595f60 | 768,238 | ipynb | Jupyter Notebook | source_code/MidTerm_Project_srini.V3_trials.ipynb | Denny-Meyer/IronHack_mid_term_real_state_regression | f013843aba7c3ead17c52837eb78d520ef7e50ae | [
"MIT"
] | null | null | null | source_code/MidTerm_Project_srini.V3_trials.ipynb | Denny-Meyer/IronHack_mid_term_real_state_regression | f013843aba7c3ead17c52837eb78d520ef7e50ae | [
"MIT"
] | null | null | null | source_code/MidTerm_Project_srini.V3_trials.ipynb | Denny-Meyer/IronHack_mid_term_real_state_regression | f013843aba7c3ead17c52837eb78d520ef7e50ae | [
"MIT"
] | null | null | null | 182.090069 | 164,048 | 0.855981 | [
[
[
"### Real Estate Modelling Project -Srini",
"_____no_output_____"
],
[
"### Objective",
"_____no_output_____"
],
[
"-Build a model to predict house prices based on features provided in the dataset. <br />\n-One of those parameters include understanding which factors are responsible for higher property value - $650K and above.<br />\n-The data set consists of information on some 22,000 properties. <br />\n-The dataset consisted of historic data of houses sold between May 2014 to May 2015.<br />\n-Tools to be used are Pandas (Jupyter notebook) and Tableau.<br />",
"_____no_output_____"
],
[
"### Importing libraries",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import QuantileTransformer\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import PowerTransformer\nfrom sklearn.metrics import r2_score\nimport statsmodels.api as sm\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.metrics import mean_absolute_error as mae\nfrom scipy.stats import boxcox\npd.options.display.max_rows = 50\npd.options.display.max_columns = 999\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom haversine import haversine",
"_____no_output_____"
]
],
[
[
"### Fetching the data",
"_____no_output_____"
]
],
[
[
"df=pd.read_excel(\"Data_MidTerm_Project_Real_State_Regression.xls\" ) # reading the excel file",
"_____no_output_____"
]
],
[
[
"#### Checking the data type of the features for any corrections",
"_____no_output_____"
]
],
[
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 21597 entries, 0 to 21596\nData columns (total 21 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 id 21597 non-null int64 \n 1 date 21597 non-null datetime64[ns]\n 2 bedrooms 21597 non-null int64 \n 3 bathrooms 21597 non-null float64 \n 4 sqft_living 21597 non-null int64 \n 5 sqft_lot 21597 non-null int64 \n 6 floors 21597 non-null float64 \n 7 waterfront 21597 non-null int64 \n 8 view 21597 non-null int64 \n 9 condition 21597 non-null int64 \n 10 grade 21597 non-null int64 \n 11 sqft_above 21597 non-null int64 \n 12 sqft_basement 21597 non-null int64 \n 13 yr_built 21597 non-null int64 \n 14 yr_renovated 21597 non-null int64 \n 15 zipcode 21597 non-null int64 \n 16 lat 21597 non-null float64 \n 17 long 21597 non-null float64 \n 18 sqft_living15 21597 non-null int64 \n 19 sqft_lot15 21597 non-null int64 \n 20 price 21597 non-null int64 \ndtypes: datetime64[ns](1), float64(4), int64(16)\nmemory usage: 3.5 MB\n"
]
],
[
[
"#### Checking the column headers for case consistency and spacing for any corrections",
"_____no_output_____"
]
],
[
[
"col_list = df.columns\ncol_list",
"_____no_output_____"
],
[
"#filtered view of the repetitive house ids\nrepetitive_sales = df.groupby('id').filter(lambda x: len(x) > 1) \nrepetitive_sales",
"_____no_output_____"
]
],
[
[
"#### Exploring the data",
"_____no_output_____"
]
],
[
[
"df['zipcode']= df['zipcode'].astype(str)",
"_____no_output_____"
],
[
"df.zipcode[df.zipcode.isin([\"98102\",\n\"98103\",\n\"98105\",\n\"98106\",\n\"98107\",\n\"98108\",\n\"98109\",\n\"98112\",\n\"98115\",\n\"98116\",\n\"98117\",\n\"98118\",\n\"98119\",\n\"98122\",\n\"98125\",\n\"98126\",\n\"98133\",\n\"98136\",\n\"98144\",\n\"98177\",\n\"98178\",\n\"98199\"])] = \"seattle_zipcode\"",
"_____no_output_____"
],
[
"df.zipcode[df.zipcode.isin([\"98002\",\n\"98003\",\n\"98023\",\n\"98092\"])]= 'Auburn_zipcode'",
"_____no_output_____"
],
[
"df.zipcode[df.zipcode.isin([\"98004\",\n\"98005\",\n\"98006\",\n\"98007\",\n\"98008\"])]= 'Bellevue_zipcode'",
"_____no_output_____"
],
[
"df.zipcode[df.zipcode.isin([\"98146\",\n\"98148\",\n\"98166\",\n\"98168\"])]= 'Burien_zipcode'",
"_____no_output_____"
],
[
"df.zipcode[df.zipcode.isin([\"98001\",\n\"98010\",\n\"98011\",\n\"98014\",\n\"98019\",\n\"98022\",\n\"98024\",\n\"98027\",\n\"98028\",\n\"98029\",\n\"98030\",\n\"98031\",\n\"98032\",\n\"98033\",\n\"98034\",\n\"98038\",\n\"98039\",\n\"98040\",\n\"98042\",\n\"98045\",\n\"98052\",\n\"98053\",\n\"98055\",\n\"98056\",\n\"98058\",\n\"98059\",\n\"98065\",\n\"98070\",\n\"98072\",\n\"98074\",\n\"98075\",\n\"98077\",\n\"98155\",\n\"98188\",\n\"98198\"])]= 'other_zipcode'",
"_____no_output_____"
],
[
"# List of variables to be dropped from the model\ndrop_list = [\"price\",\n \"id\",\n \"sqft_above\",\n \"sqft_basement\",\n \"sqft_lot15\",\n \"sqft_living15\",\n 'lat', \n 'long',\n 'dist_from_seattle',\n 'dist_from_bellevue',\n 'Auburn_zipcode',\n 'floors',\n 'other_zipcode'] # 'lat_long' is not a numeric element hence not passed on",
"_____no_output_____"
],
[
"outlier_list = []\nfor item in df.columns:\n if item not in drop_list:\n if item not in ['price','date']: # target variable\n outlier_list.append(item)\n\noutlier_list",
"_____no_output_____"
],
[
"# placeholder for dealing with outliers\n#Q1 = df.sqft_basement.quantile(0.25)\n#Q3 = df.sqft_basement.quantile(0.75)\n#IQR = Q3 - Q1 #IQR is interquartile range.\n\n#filter = (df[\"price\"] >= 100000) # Removed the houses with less than price of 100k, that accounted for 45 records \n#df=df.loc[filter]\n#filter = (df['bedrooms'] !=33) # Removed the houses with less than condition value 1, that accounted for 29 records \n#df=df.loc[filter]",
"_____no_output_____"
]
],
[
[
"Mapping a new variable called distance from the epicenter to see how far the properties are located to the main areas of Seatlle and Bellevue.",
"_____no_output_____"
]
],
[
[
"df['lat_long'] = tuple(zip(df.lat,df.long)) # creating one column with a tuple using latitude and longitude coordinates\ndf",
"_____no_output_____"
],
[
"df['zipcode']= df['zipcode'].astype(str)",
"_____no_output_____"
],
[
"seattle = [47.6092,-122.3363]\nbellevue = [47.61555,-122.20392]",
"_____no_output_____"
],
[
"seattle_dist = []\nfor i in df['lat_long']:\n seattle_dist.append(haversine((seattle),(i), unit = 'mi'))\ndf['dist_from_seattle'] = pd.Series(seattle_dist)",
"_____no_output_____"
],
[
"bellevue_dist = []\nfor i in df['lat_long']:\n bellevue_dist.append(haversine((bellevue),(i), unit = 'mi'))\ndf['dist_from_bellevue'] = pd.Series(bellevue_dist)",
"_____no_output_____"
],
[
"df['dist_from_citycenter'] = df[['dist_from_seattle', 'dist_from_bellevue']].min(axis=1)",
"_____no_output_____"
],
[
"corr = round(df.corr(),2)\nmask = np.zeros_like(corr)\nmask[np.triu_indices_from(mask)] = True\nwith sns.axes_style(\"white\"):\n f, ax = plt.subplots(figsize=(14, 11))\n ax = sns.heatmap(corr, mask=mask,cmap='coolwarm', vmin=-1,vmax=1,annot=True, square=True)",
"_____no_output_____"
],
[
"df_zip_dummies = pd.get_dummies(df['zipcode'])\ndf_zips= pd.concat([df, df_zip_dummies],axis=1)",
"_____no_output_____"
],
[
"df_zips.head()",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"#### Applying Box-cox Powertransform",
"_____no_output_____"
]
],
[
[
"def plots (df, var, t):\n plt.figure(figsize= (13,5))\n plt.subplot(121)\n sns.kdeplot(df[var])\n plt.title('before' + str(t).split('(')[0])\n \n plt.subplot(122)\n p1 = t.fit_transform(df[[var]]).flatten()\n sns.kdeplot(p1)\n plt.title('after' + str(t).split('(')[0])",
"_____no_output_____"
],
[
"box_col = []\nfor item in df.columns:\n if item not in drop_list:\n if item not in ['date', 'lat_long','waterfront','view','zipcode','yr_renovated']: # target variable\n box_col.append(item)\n\nbox_col",
"_____no_output_____"
],
[
"for col in box_col:\n plots(df, col, PowerTransformer (method='box-cox'))",
"_____no_output_____"
],
[
"plots(df, 'price', PowerTransformer (method='box-cox'))",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
],
[
"nulls_df = pd.DataFrame(round(df.isna().sum()/len(df),4)*100)\nnulls_df = nulls_df.reset_index()\nnulls_df.columns = ['header_name', 'percent_nulls']\nnulls_df",
"_____no_output_____"
]
],
[
[
"#### Preparing the data",
"_____no_output_____"
]
],
[
[
"# x = df.drop(\"price\", axis=1)\nx = df_zips._get_numeric_data()\ny = x['price']",
"_____no_output_____"
],
[
"x",
"_____no_output_____"
],
[
"for col in drop_list:\n x.drop([col],axis=1,inplace=True)",
"_____no_output_____"
]
],
[
[
"#### Modelling the data",
"_____no_output_____"
]
],
[
[
"y",
"_____no_output_____"
],
[
"x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2, random_state =1)",
"_____no_output_____"
],
[
"std_scaler=StandardScaler().fit(x_train) \n\nx_train_scaled=std_scaler.transform(x_train)\n\nx_test_scaled=std_scaler.transform(x_test)",
"_____no_output_____"
],
[
"x_train_scaled[0]",
"_____no_output_____"
]
],
[
[
"### Modeling using Statsmodels",
"_____no_output_____"
],
[
"#### without scaling",
"_____no_output_____"
]
],
[
[
"x_train_const= sm.add_constant(x_train) # adding a constant\n\nmodel = sm.OLS(y_train, x_train_const).fit()\npredictions_train = model.predict(x_train_const) \n\nx_test_const = sm.add_constant(x_test) # adding a constant\npredictions_test = model.predict(x_test_const) \nprint_model = model.summary()\nprint(print_model)",
" OLS Regression Results \n==============================================================================\nDep. Variable: price R-squared: 0.725\nModel: OLS Adj. R-squared: 0.724\nMethod: Least Squares F-statistic: 3244.\nDate: Tue, 16 Nov 2021 Prob (F-statistic): 0.00\nTime: 19:44:26 Log-Likelihood: -2.3487e+05\nNo. Observations: 17277 AIC: 4.698e+05\nDf Residuals: 17262 BIC: 4.699e+05\nDf Model: 14 \nCovariance Type: nonrobust \n========================================================================================\n coef std err t P>|t| [0.025 0.975]\n----------------------------------------------------------------------------------------\nconst 2.875e+06 1.53e+05 18.733 0.000 2.57e+06 3.18e+06\nbedrooms -3.533e+04 2034.728 -17.366 0.000 -3.93e+04 -3.13e+04\nbathrooms 2.614e+04 3409.075 7.669 0.000 1.95e+04 3.28e+04\nsqft_living 191.9273 3.347 57.348 0.000 185.367 198.487\nsqft_lot 0.2241 0.037 6.034 0.000 0.151 0.297\nwaterfront 6.341e+05 1.86e+04 34.006 0.000 5.98e+05 6.71e+05\nview 4.455e+04 2229.911 19.979 0.000 4.02e+04 4.89e+04\ncondition 2.292e+04 2518.999 9.098 0.000 1.8e+04 2.79e+04\ngrade 8.743e+04 2193.290 39.863 0.000 8.31e+04 9.17e+04\nyr_built -1668.9448 78.656 -21.218 0.000 -1823.118 -1514.771\nyr_renovated 26.0857 3.932 6.634 0.000 18.378 33.793\ndist_from_citycenter -1.617e+04 324.581 -49.832 0.000 -1.68e+04 -1.55e+04\nBellevue_zipcode 9.396e+04 6928.163 13.562 0.000 8.04e+04 1.08e+05\nBurien_zipcode -9.052e+04 7926.803 -11.419 0.000 -1.06e+05 -7.5e+04\nseattle_zipcode 1.323e+04 4472.788 2.957 0.003 4457.918 2.2e+04\n==============================================================================\nOmnibus: 16099.402 Durbin-Watson: 1.997\nProb(Omnibus): 0.000 Jarque-Bera (JB): 2300363.949\nSkew: 4.041 Prob(JB): 0.00\nKurtosis: 58.948 Cond. No. 4.60e+06\n==============================================================================\n\nNotes:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The condition number is large, 4.6e+06. This might indicate that there are\nstrong multicollinearity or other numerical problems.\n"
]
],
[
[
"#### checking the significant variables",
"_____no_output_____"
]
],
[
[
"model.params[list(np.where(model.pvalues < 0.05)[0])].iloc[1:].index.tolist()",
"_____no_output_____"
],
[
"significant_features=x[model.params[list(np.where(model.pvalues < 0.05)[0])].iloc[1:].index.tolist()]",
"_____no_output_____"
],
[
"model = LinearRegression()\nmodel.fit(x_train, y_train)\ncoefficients = list(model.coef_)\ncoefficients",
"_____no_output_____"
]
],
[
[
"#### with scaling",
"_____no_output_____"
]
],
[
[
"x_train.columns",
"_____no_output_____"
],
[
"x_train_const_scaled = sm.add_constant(x_train_scaled) # adding a constant\n\nmodel = sm.OLS(y_train, x_train_const_scaled).fit()\npredictions_train = model.predict(x_train_const_scaled) \n\nx_test_const_scaled = sm.add_constant(x_test_scaled) # adding a constant\npredictions_test = model.predict(x_test_const_scaled) \nprint_model = model.summary()\nprint(print_model)",
" OLS Regression Results \n==============================================================================\nDep. Variable: price R-squared: 0.725\nModel: OLS Adj. R-squared: 0.724\nMethod: Least Squares F-statistic: 3244.\nDate: Tue, 16 Nov 2021 Prob (F-statistic): 0.00\nTime: 19:44:26 Log-Likelihood: -2.3487e+05\nNo. Observations: 17277 AIC: 4.698e+05\nDf Residuals: 17262 BIC: 4.699e+05\nDf Model: 14 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nconst 5.414e+05 1475.929 366.787 0.000 5.38e+05 5.44e+05\nx1 -3.292e+04 1895.393 -17.366 0.000 -3.66e+04 -2.92e+04\nx2 2.015e+04 2627.833 7.669 0.000 1.5e+04 2.53e+04\nx3 1.758e+05 3065.731 57.348 0.000 1.7e+05 1.82e+05\nx4 9318.8176 1544.413 6.034 0.000 6291.612 1.23e+04\nx5 5.501e+04 1617.643 34.006 0.000 5.18e+04 5.82e+04\nx6 3.423e+04 1713.086 19.979 0.000 3.09e+04 3.76e+04\nx7 1.493e+04 1640.633 9.098 0.000 1.17e+04 1.81e+04\nx8 1.029e+05 2581.308 39.863 0.000 9.78e+04 1.08e+05\nx9 -4.911e+04 2314.516 -21.218 0.000 -5.36e+04 -4.46e+04\nx10 1.048e+04 1580.113 6.634 0.000 7384.994 1.36e+04\nx11 -1.005e+05 2015.803 -49.832 0.000 -1.04e+05 -9.65e+04\nx12 2.291e+04 1689.438 13.562 0.000 1.96e+04 2.62e+04\nx13 -1.787e+04 1565.039 -11.419 0.000 -2.09e+04 -1.48e+04\nx14 6249.0668 2113.473 2.957 0.003 2106.446 1.04e+04\n==============================================================================\nOmnibus: 16099.402 Durbin-Watson: 1.997\nProb(Omnibus): 0.000 Jarque-Bera (JB): 2300363.949\nSkew: 4.041 Prob(JB): 0.00\nKurtosis: 58.948 Cond. No. 4.86\n==============================================================================\n\nNotes:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n"
]
],
[
[
"#### Linear regression",
"_____no_output_____"
]
],
[
[
"model=LinearRegression() # model\nmodel.fit(x_train_scaled, y_train) # model train\n\ny\ny_pred=model.predict(x_test_scaled) # model prediction\n\n\ny_pred_train=model.predict(x_train_scaled)",
"_____no_output_____"
],
[
"# Make an scatter plot y_pred vs y\n# What kind of plot you will get if all the all the predictions are ok?\n# A stright line\n\nfig, ax = plt.subplots(2,3,figsize=(14,12))\nax[0,0].plot(y_pred, y_test, 'o')\nax[0,0].set_xlabel(\"y_test\")\nax[0,0].set_ylabel(\"y_pred\")\nax[0,0].set_title(\"Test Set -Predicted vs real\")\n\n# Get a histogram of the residuals ie: y - y_pred. Homoscdasticity\n# It resembles a normal distribution?\nax[0,1].hist(y_test - y_pred)\nax[0,1].set_xlabel(\"Test y-y_pred\")\nax[0,1].set_title(\"Test Set Residual histogram\")\n\nax[0,2].plot(y_pred,y_test - y_pred,\"o\")\nax[0,2].set_xlabel(\"predited\")\nax[0,2].set_ylabel(\"residuals\")\nax[0,2].set_title(\"Residuals by Predicted -- Test set\")\nax[0,2].plot(y_pred,np.zeros(len(y_pred)),linestyle='dashed')\n\n\nax[1,0].plot(y_pred_train, y_train, 'o')\nax[1,0].set_xlabel(\"y_train\")\nax[1,0].set_ylabel(\"y_pred_train\")\nax[1,0].set_title(\"Train set Predicted vs real\")\n\n# Get a histogram of the residuals ie: y - y_pred. Homoscdasticity\n# It resembles a normal distribution?\nax[1,1].hist(y_train - y_pred_train)\nax[1,1].set_xlabel(\"Train y-y_pred\")\nax[1,1].set_title(\"Train Residual histogram\")\n\nax[1,2].plot(y_pred_train,y_train - y_pred_train,\"o\")\nax[1,2].set_xlabel(\"predited\")\nax[1,2].set_ylabel(\"residuals\")\nax[1,2].set_title(\"Residuals by Predicted -- Train set\")\nax[1,2].plot(y_pred_train,np.zeros(len(y_pred_train)),linestyle='dashed')",
"_____no_output_____"
],
[
"y_pred =model.predict(x_test_scaled).astype(int)\ny_change = round((y_pred/y_test)-1, 2)\nresult = pd.DataFrame({\"y_test\":y_test, \"y_pred\":y_pred, \"∆ %\": y_change})\nresult",
"_____no_output_____"
],
[
"fig, axs = plt.subplots(1,2,figsize=(12,6))\n\nsns.regplot(x=\"y_test\", y=\"y_pred\", data=result, scatter_kws={\"color\": \"blue\"}, line_kws={\"color\": \"black\"}, ax=axs[0])\nsns.histplot(y_test-y_pred, kde=True, ax=axs[1])\n\naxs[0].set_title(\"Test Set - Observed VS Predicted\")\naxs[1].set_title(\"Test Set - Histogram of the Residuals\")\naxs[1].set_xlabel(\"y_test - y_pred\")\n",
"_____no_output_____"
]
],
[
[
"### Model validation",
"_____no_output_____"
]
],
[
[
"train_mse=mse(y_train,y_pred_train)\ntest_mse=mse(y_test,y_pred)\n\nprint ('train MSE: {} -- test MSE: {}'.format(train_mse, test_mse))",
"train MSE: 37602966924.11132 -- test MSE: 34361724727.49398\n"
]
],
[
[
"RMSE",
"_____no_output_____"
]
],
[
[
"print ('train RMSE: {} -- test RMSE: {}'.format(train_mse**.5, test_mse**.5))",
"train RMSE: 193914.84451715223 -- test RMSE: 185369.1579726627\n"
]
],
[
[
"MAE",
"_____no_output_____"
]
],
[
[
"train_mae=mae(y_train,y_pred_train)\ntest_mae=mae(y_test,y_pred)\n\nprint ('train MAE: {} -- test MAE: {}'.format(train_mse, test_mse))",
"train MAE: 37602966924.11132 -- test MAE: 34361724727.49398\n"
]
],
[
[
"R2",
"_____no_output_____"
]
],
[
[
"#R2= model.score(X_test_scaled, y_test)\nR2_train=r2_score(y_train,y_pred_train)\nR2_test=r2_score(y_test,y_pred)\n\nprint (R2_train)\nprint(R2_test)",
"0.7245706790336555\n0.7328942631975932\n"
],
[
"print ('train R2: {} -- test R2: {}'.format(model.score(x_train_scaled, y_train),\n model.score(x_test_scaled, y_test)))",
"train R2: 0.7245706790336555 -- test R2: 0.7328942112790509\n"
]
],
[
[
"adjusted rsquare",
"_____no_output_____"
]
],
[
[
"Adj_R2_train= 1 - (1-R2_train)*(len(y_train)-1)/(len(y_train)-x_train.shape[1]-1)\nAdj_R2_train",
"_____no_output_____"
],
[
"Adj_R2_test= 1 - (1-R2_test)*(len(y_test)-1)/(len(y_test)-x_test.shape[1]-1)\nAdj_R2_test",
"_____no_output_____"
],
[
"features_importances = pd.DataFrame(data={\n 'Attribute': x_train.columns,\n 'Importance': abs(model.coef_)\n})\nfeatures_importances = features_importances.sort_values(by='Importance', ascending=False)",
"_____no_output_____"
],
[
"features_importances",
"_____no_output_____"
],
[
"metrics = {\"MSE\":mse(y_test, y_pred), \"RMSE\":mse(y_test, y_pred, squared=False), \"MAE\":mae(y_test, y_pred), \"R2\":r2_score(y_test, y_pred)}",
"_____no_output_____"
],
[
"metrics",
"_____no_output_____"
],
[
"plt.bar(x=features_importances['Attribute'], height=features_importances['Importance'], color='Orange')\nplt.title('Feature importances obtained from coefficients', size=20)\nplt.xticks(rotation='vertical')\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Fine-tuning the models",
"_____no_output_____"
],
[
"#### Presenting the results",
"_____no_output_____"
],
[
"1.Summary of the dataset in 1 min, the key aspects of the dataset and observation. <br />\n2. \n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
e7ac01aea15cb993d39f7ec3235663384f2b5825 | 3,436 | ipynb | Jupyter Notebook | docs/notebooks/api/iteration.ipynb | yusukeaoki1223/pyblp | 71cea45251f3772ef8f3dc62c7e47b9820308396 | [
"MIT"
] | 1 | 2019-02-10T14:25:08.000Z | 2019-02-10T14:25:08.000Z | docs/notebooks/api/iteration.ipynb | yusukeaoki1223/pyblp | 71cea45251f3772ef8f3dc62c7e47b9820308396 | [
"MIT"
] | null | null | null | docs/notebooks/api/iteration.ipynb | yusukeaoki1223/pyblp | 71cea45251f3772ef8f3dc62c7e47b9820308396 | [
"MIT"
] | null | null | null | 24.197183 | 286 | 0.542491 | [
[
[
"# Iteration Example",
"_____no_output_____"
]
],
[
[
"import pyblp\nimport numpy as np\n\npyblp.__version__",
"_____no_output_____"
]
],
[
[
"In this example, we'll build a SQUAREM configuration with a $\\ell^2$-norm and use scheme S1 from :ref:`references:Varadhan and Roland (2008)`.",
"_____no_output_____"
]
],
[
[
"iteration = pyblp.Iteration('squarem', {'norm': np.linalg.norm, 'scheme': 1})\niteration",
"_____no_output_____"
]
],
[
[
"Next, instead of using a built-in routine, we'll create a custom method that implements a version of simple iteration, which, for the sake of having a nontrivial example, arbitrarily identifies a major iteration with three objective evaluations.",
"_____no_output_____"
]
],
[
[
"def custom_method(initial, contraction, callback, max_evaluations, tol, norm):\n x = initial\n evaluations = 0\n while evaluations < max_evaluations:\n x0, (x, weights, _) = x, contraction(x)\n evaluations += 1\n if evaluations % 3 == 0:\n callback()\n if weights is None:\n difference = norm(x - x0)\n else:\n difference = norm(weights * (x - x0))\n if difference < tol:\n break\n return x, evaluations < max_evaluations",
"_____no_output_____"
]
],
[
[
"We can then use this custom method to build a custom iteration configuration.",
"_____no_output_____"
]
],
[
[
"iteration = pyblp.Iteration(custom_method)\niteration",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ac0a3ecbcb7757cbe597888a83acec1207a7e7 | 501,581 | ipynb | Jupyter Notebook | python/redditscore.ipynb | AlexHartford/redditscore | 0c986809a3a7d933387397597859a8b3271545d4 | [
"MIT"
] | 2 | 2020-05-17T03:50:00.000Z | 2020-10-13T19:54:10.000Z | python/redditscore.ipynb | AlexHartford/redditscore | 0c986809a3a7d933387397597859a8b3271545d4 | [
"MIT"
] | null | null | null | python/redditscore.ipynb | AlexHartford/redditscore | 0c986809a3a7d933387397597859a8b3271545d4 | [
"MIT"
] | null | null | null | 57.004319 | 10,628 | 0.589145 | [
[
[
"# <a href=\"http://www.redditscore.com\"></a> \n***A machine learning approach to predicting how badly you'll get roasted for your sub-par reddit comments.***\n\nAlex Hartford & Trevor Hacker\n\n### **Dataset**\n\nReddit comments from September, 2018 (<a href=\"http://files.pushshift.io/reddit/\">source</a>). This is well over 100gb of data. We will likely only use a subset of the data but will ultimately try to use the entire dataset.\n\n### **Objectives**\n\nCreate a linear regression model to predict the reddit score of a comment a user is considering posting. \n\nStretch goal - narrow comment scoring down by subreddit, as comment popularity will differ between reddit communities.\n\nAllow users to use this model with a publicly available <a href=\"http://www.redditscore.com\">Website</a>.\n\nOpen source the project to allow further contributions if anyone is interested.\n\n## Formal Hypothesis and Data Analysis\n\nBy analyzing comments made on the Reddit platform by prior users, we believe that people who seek to gather as much reputation as possible on Reddit would find value in being able to predict whether their comments will be well received by the community. In the process, finding some of the most common highly/negatively received comments would be very interesting information as it can provide insight into the current trends of the web.\n\nThis dataset is just one of many - there are datasets for all the information ever posted on Reddit, publicly available for use. Community members of Reddit have assembled the data by running scripts on the Reddit API and did most of the cleaning for us. Interestingly, people released these datasets in hope that people would create something out of them - quite awhile ago. From what I can tell, Redditscore is one of the first applications that uses this data, rather than just providing a few nice graphs. There is actually a problem potentially being solved here, as there are people who live for Reddit karma.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.linear_model import SGDRegressor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\nprint('Libraries loaded!')",
"Libraries loaded!\n"
]
],
[
[
"## Import and Clean Data",
"_____no_output_____"
]
],
[
[
"print('Loading memes...')\n\n# df = pd.read_csv('https://s3.us-east-2.amazonaws.com/redditscore/2500rows.csv')\ndf = pd.read_csv('https://s3.us-east-2.amazonaws.com/redditscore/2mrows.csv', error_bad_lines=False, engine='python', encoding='utf-8')\n\nprint('Memes are fully operational!')",
"Loading memes...\n"
],
[
"print(df.dtypes)\nprint()\nprint(df.shape)\ndf.head(10)",
"subreddit object\nbody object\nscore float64\ndtype: object\n\n(1961645, 3)\n"
]
],
[
[
"The score will always be an integer since it is based on upvotes and downvotes. Before converting however, we need to check if there are any null values.",
"_____no_output_____"
]
],
[
[
"df.isna().sum()",
"_____no_output_____"
],
[
"df[df.isnull().any(axis=1)].head(20)",
"_____no_output_____"
]
],
[
[
"There is only a small amount of null values and they appear to be of little use, so removing them seems to be the best bet. Once the null values are removed we can convert score to an integer.",
"_____no_output_____"
]
],
[
[
"df = df.dropna()\ndf['score'] = df['score'].astype('int')",
"_____no_output_____"
],
[
"print(df.shape)\ndf.head(10)",
"(1941086, 3)\n"
]
],
[
[
"## Initial Data Analysis\n\nBefore getting into handling the comment body a better understanding of the score collumn needs to be gained.",
"_____no_output_____"
]
],
[
[
"df['score'].describe()",
"_____no_output_____"
],
[
"sns.distplot(df[\"score\"], kde=False)",
"_____no_output_____"
]
],
[
[
"As seen standard deviation and the distribution plot, there is a large distribution of data which makes the dataset skewed.",
"_____no_output_____"
],
[
"In order to solve this log sclaling can be applied which might be useful later on.",
"_____no_output_____"
]
],
[
[
"mask = df[\"score\"] > 0\nsns.distplot(np.log1p(df[\"score\"][mask]), kde=False)",
"_____no_output_____"
]
],
[
[
"The positive scores appear to be skewed with a significant majority of values being equal to 1. ",
"_____no_output_____"
]
],
[
[
"mask = df[\"score\"] < 0\nsns.distplot(-np.log1p(-df[\"score\"][mask]), kde=False)",
"_____no_output_____"
]
],
[
[
"The negative scores also seem a little skewed.",
"_____no_output_____"
],
[
"#### Adding another score column\n\nIn order to understand the data better and also create a logistic regression model a seperate column was created with the values of positive, negative or one score. Positive score being anything greater than 1, negative being anything less than 1 and one being 1. The reason for this classification is how comments on reddit work, since whenever a comment is made it automatically gets an upvote and therfore if the score is zero it got a downvote.",
"_____no_output_____"
]
],
[
[
"df['pn_score'] = \"\"\n\nfor i in df['score'].index:\n if df['score'].at[i] > 1:\n df['pn_score'].at[i] = 'positive'\n elif float(df['score'].at[i]) <= 0:\n df['pn_score'].at[i] = 'negative'\n else:\n df['pn_score'].at[i] = 'one' \n\ndf.head(10)",
"_____no_output_____"
],
[
"pn_counts = df['pn_score'].value_counts()\nprint(pn_counts)\npn_counts.plot.bar()\nplt.ylabel(\"Number of Samples\", fontsize=16)",
"positive 1053684\none 739088\nnegative 148314\nName: pn_score, dtype: int64\n"
]
],
[
[
"Again there is an issue with distribution here. The majority of dataset has positive score values, where negative scores are much less frequent.",
"_____no_output_____"
],
[
"## Logistic Regression Model\nThere will be a combination of logistic regression and linear regression models used.\n\nThe logistic model will be created based on the categorical score values, so it will predict whether the comment will have a postive or negative score or a score of 1. \n\nIn order for the comments to be meaningful predictors of score they first need to be turned into a vector of numerical features. The vectorizer used implements Text Frequency-Inverse Document Frequency (TfIdf) weighting. Additionally stop_words were removed from the vector.",
"_____no_output_____"
]
],
[
[
"log_vect = TfidfVectorizer(max_df = 0.95, min_df = 5, binary=True, stop_words='english')\ntext_features = log_vect.fit_transform(df.body)\nprint(text_features.shape)",
"(1941086, 101474)\n"
],
[
"list(log_vect.vocabulary_)[:10]",
"_____no_output_____"
],
[
"encoder = LabelEncoder()\nnumerical_labels = encoder.fit_transform(df['pn_score'])\n\ntraining_X, testing_X, training_y, testing_y = train_test_split(text_features,\n numerical_labels,\n stratify=numerical_labels)\nprint(training_y)\n\nlogistic_regression = SGDClassifier(loss=\"log\", penalty=\"l2\", max_iter=250)\nlogistic_regression.fit(training_X, training_y)\npred_labels = logistic_regression.predict(testing_X)\n\naccuracy = accuracy_score(testing_y, pred_labels)\ncm = confusion_matrix(testing_y, pred_labels)\n\nprint(\"Accuracy:\", accuracy)\nprint(\"Classes:\", str(encoder.classes_))\nprint(\"Confusion Matrix:\")\nprint(cm)",
"[2 2 2 ... 0 0 1]\nAccuracy: 0.5961028042005309\nClasses: ['negative' 'one' 'positive']\nConfusion Matrix:\n[[ 0 5712 31367]\n [ 0 37538 147234]\n [ 0 11687 251734]]\n"
]
],
[
[
"Since the data is so skewed a simple random over-sampling was used in order to increase the number of negative scores. The reason for using over-sampling as opposed to under-sampling is because we didn't want to loose any comments that could contribute as predictors. This does run the risk of overfitting the data however.",
"_____no_output_____"
]
],
[
[
"count_pos, count_one, count_neg = df['pn_score'].value_counts()\n\ndf_pos_score = df[df['pn_score'] == 'positive']\ndf_neg_score = df[df['pn_score'] == 'negative']\ndf_one_score = df[df['pn_score'] == 'one']\n\ndf_neg_score_over = df_neg_score.sample(count_one, replace=True)\ndf_score_over = pd.concat([df_pos_score, df_neg_score_over, df_one_score], axis=0)\n\nprint('Random over-sampling:')\n\npn_counts = df_score_over['pn_score'].value_counts()\nprint(pn_counts)\npn_counts.plot.bar()\nplt.ylabel(\"Number of Samples\", fontsize=16)",
"Random over-sampling:\npositive 1053684\none 739088\nnegative 739088\nName: pn_score, dtype: int64\n"
]
],
[
[
"Similarily to first model the comments need to be vectorized.",
"_____no_output_____"
]
],
[
[
"log_vect_over = TfidfVectorizer(max_df = 0.95, min_df = 5, binary=True, stop_words='english')\ntext_features = log_vect_over.fit_transform(df_score_over.body)\nprint(text_features.shape)",
"(2531860, 128094)\n"
],
[
"list(log_vect_over.vocabulary_)[:10]",
"_____no_output_____"
]
],
[
[
"Now that the comments are turned into vectorized features they can be used in the logistic regression model. In order to achieve better results the random over-sampled data is used.",
"_____no_output_____"
]
],
[
[
"encoder = LabelEncoder()\nnumerical_labels = encoder.fit_transform(df_score_over['pn_score'])\n\ntraining_X, testing_X, training_y, testing_y = train_test_split(text_features,\n numerical_labels,\n stratify=numerical_labels)\nprint(training_y)\n\nlogistic_regression_over = SGDClassifier(loss=\"log\", penalty=\"l2\", max_iter=1500)\nlogistic_regression_over.fit(training_X, training_y)\npred_labels = logistic_regression_over.predict(testing_X)\n\naccuracy = accuracy_score(testing_y, pred_labels)\ncm = confusion_matrix(testing_y, pred_labels)\n\nprint(\"Accuracy:\", accuracy)\nprint(\"Classes:\", str(encoder.classes_))\nprint(\"Confusion Matrix:\")\nprint(cm)",
"[2 1 1 ... 0 2 0]\nAccuracy: 0.4774545196021897\nClasses: ['negative' 'one' 'positive']\nConfusion Matrix:\n[[ 33626 10591 140555]\n [ 16730 25612 142430]\n [ 13682 6765 242974]]\n"
]
],
[
[
"According to the confusion matrix the model struggles with determining a comment that has a score of 1 and usually mistakes it for a positive comment. It seems to perform the best with negative comments which could indicate overfitting of the data.",
"_____no_output_____"
],
[
"## Linear Regression Models\n\nThere will be two linear regression models, one for detecting the value of the positive score comments and another for detective the value of the negative score comments. The specific one will be used depending on the outcome of the logistic regression model.\n\n### Positive Scores\n\nThe first linear regression model will predict that of the postive score. In order to do that only the rows with a positive score are necessary.",
"_____no_output_____"
]
],
[
[
"pos_score_df = df[df.pn_score == 'positive']\n\npos_score_df.head()",
"_____no_output_____"
]
],
[
[
"Similarily to the logistic regression the comments need to be transformed into a vector of numerical values.",
"_____no_output_____"
]
],
[
[
"pos_vect = TfidfVectorizer(max_df = 0.95, min_df = 5, binary=True, stop_words='english')\ntext_features = pos_vect.fit_transform(pos_score_df.body)\nprint(text_features.shape)",
"(1053684, 74485)\n"
],
[
"list(pos_vect.vocabulary_)[:10]",
"_____no_output_____"
]
],
[
[
"Now that the comments are vectorized, the model can be created. In order to eliminate the issue with large distribution noticed during the alaysis, the scores are log scaled.",
"_____no_output_____"
]
],
[
[
"X_train, X_test, y_train, y_test = train_test_split(text_features, np.log1p(pos_score_df['score']))\n\npos_linear_regression = SGDRegressor(max_iter=1500)\npos_linear_regression.fit(X_train, y_train)\ntest = pos_linear_regression.predict(X_test)\nmse = mean_squared_error(y_test, test)\nrmse = np.sqrt(mse)\nprint()\nprint(\"Positive Score Model MSE:\", mse)\nprint(\"Positive Score Model RMSE:\", rmse)",
"\nPositive Score Model MSE: 0.8749582956086429\nPositive Score Model RMSE: 0.935392054493004\n"
]
],
[
[
"Based on the rmse the model seems to preform pretty well.",
"_____no_output_____"
],
[
"### Negative Scores\n\nThe second linear regression model will predict the negative scores. Similarily to the first model only the rows with negative scores are necessary and the comment need to be vectorized using those.",
"_____no_output_____"
]
],
[
[
"neg_score_df = df[df.pn_score == 'negative']\n\nneg_score_df.head()",
"_____no_output_____"
],
[
"neg_vect = TfidfVectorizer(max_df = 0.95, min_df = 5, binary=True, stop_words='english')\ntext_features = neg_vect.fit_transform(neg_score_df.body)\nprint(text_features.shape)",
"(148314, 22404)\n"
],
[
"list(neg_vect.vocabulary_)[:10]",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(text_features, -np.log1p(-neg_score_df[\"score\"]))\n\nneg_linear_regression = SGDRegressor(max_iter=1500)\nneg_linear_regression.fit(X_train, y_train)\ntest = neg_linear_regression.predict(X_test)\nmse = mean_squared_error(y_test, test)\nrmse = np.sqrt(mse)\nprint()\nprint(\"Negative Score Model MSE:\", mse)\nprint(\"Negative Score Model RMSE:\", rmse)",
"\nNegative Score Model MSE: 1.0130192799066775\nNegative Score Model RMSE: 1.0064885890593482\n"
]
],
[
[
"The results are similar to the first model.",
"_____no_output_____"
],
[
"## Combining Models\n\nFirst the logistic regression model will be used to preditc whether or not the score is negative or positive, then depending on the outcome the appropriate linear regression model will be used to predict the score value",
"_____no_output_____"
]
],
[
[
"a = ([\"You sir a simple idiot. Or a Russian bot. Either way not worth an actual sentence on why I didn't vote for that loon.\"])\n\nlogistic_result = logistic_regression_over.predict(log_vect_over.transform(a))\nprint('Logistic Result: ')\nprint(logistic_result)\nprint()\n\nif(logistic_result) == 2:\n linear_result = pos_linear_regression.predict(pos_vect.transform(a))\n print('Linear Result: ')\n print(linear_result)\nelif(logistic_result) == 0:\n linear_result = neg_linear_regression.predict(neg_vect.transform(a))\n print('Linear Result: ')\n print(linear_result)",
"Logistic Result: \n[0]\n\nLinear Result: \n[-1.09910057]\n"
]
],
[
[
"Lastly, we want to pickle our models and vectorizers for deployment.",
"_____no_output_____"
]
],
[
[
"import pickle\npickle.dump(logistic_regression_over, open('logreg.pkl', 'wb'))\npickle.dump(pos_linear_regression, open('poslinreg.pkl', 'wb'))\npickle.dump(neg_linear_regression, open('neglinreg.pkl', 'wb'))\npickle.dump(log_vect_over, open('log_vect.pkl', 'wb'))\npickle.dump(pos_vect, open('pos_vect.pkl', 'wb'))\npickle.dump(neg_vect, open('neg_vect.pkl', 'wb'))",
"_____no_output_____"
]
],
[
[
"## **Conclusion**\n\nWe did a fair job of proving our hypothesis. We found that due to the large volume of comments that go relatively unseen,\na model isn't going to be able to predict any huge scores. However, it does a really nice job of pointing you in the right\ndirection as it can properly determine if the comment will be received positively or negatively, and does give a range,\nusually between -10 and 10. This is enough to let a commenter know what to expect from their comment.\n\nOur analysis could be improved by including the subreddit as a category. Reddit is a large community, with many subcommunities.\nThese subcommunities often have a completely different audience from one another, so it's important to distinguish what may be\nreceived positively by one community may be received very negatively by another. I'm sure there are also other factors that could\nbe added in that would help improve the model as the dataset is quite extensive, and we decided just to focus on what we considered\nthe strongest predictor.\n\nA lesson learned was to really know the data you are working with. We were struggling to get varying values for a long time,\nhaving most scores range around 1. Suddenly, it hit us... Reddit comments have a score of 1 by default as the poster automatically\nupvotes their own comment. Therefore, using zero to categorize comments that saw no attention was leaving all the 1 values in,\nwhich led to them dominating the prediction of positive scores. By instead counting 0 as a negative, as someone would have to\ndownvote a comment for it to have a 0, and 1 as the neutral value, our model became exponentially more predictive. It was the\nvery definition of a lightbulb moment, and if we had saw this earlier it could have given us more time to spend in other areas.\n\nHaving the freedom to work on a dataset of our choice is a really great way to end a course as it gives you an application of what\nyou spent the term learning. So often that is missed, you complete a course and you don't apply the material and therefore it's lost.\nThis was a great opportunity to apply our new skills to a domain we found very interesting.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7ac22d8a0e06e22c43dffeeba9996d37312c121 | 12,184 | ipynb | Jupyter Notebook | IRENE UMOH Assignment (Week 1 and 2).ipynb | ireneumoh24/ISM416 | c39d84a99d0d836751d449b09fceac7fa1f0689c | [
"MIT"
] | null | null | null | IRENE UMOH Assignment (Week 1 and 2).ipynb | ireneumoh24/ISM416 | c39d84a99d0d836751d449b09fceac7fa1f0689c | [
"MIT"
] | null | null | null | IRENE UMOH Assignment (Week 1 and 2).ipynb | ireneumoh24/ISM416 | c39d84a99d0d836751d449b09fceac7fa1f0689c | [
"MIT"
] | null | null | null | 19.588424 | 517 | 0.467991 | [
[
[
"# `Note:` All assignment should be done inside the notebook (Double tap on each of this text to edit).",
"_____no_output_____"
],
[
"### `Question 1`: IRENE UMOH 17100310866",
"_____no_output_____"
],
[
"### `Question 2`: What do you understand by natural language processing \nNLP is a subfield of artificial Intelligence (AI). In simple terms, Natural Language Processing is the ability of a computer program to learn, understand, and interpret the natural language of humans in any give context which can be either be written or spoken. Computers go through large amounts of text data and undergoes data preprocessing. Afterwards, an algorithm is developed to process the preprocessed data. This algorithm is developed either through rules-based system or machine learning-based system.",
"_____no_output_____"
],
[
" ### `Question 3`: List some of the applications of natural language processing\n a. automatic translation \n\n b. analysis and categorization of medical records to predict illnesses and diseases\n\n c. for checking plagiarism and proofreading\n\n d. stock forecasting and insights into financial trading\n\n e. Customer service and feedback analysis\n",
"_____no_output_____"
],
[
"### `Question 4`: What are some of the challenges of NLP?\na. Precision: Human speech is very ambiguous and not precise. This could be an issue for the computer program to analyse and give a precise output\n \nb. Tone of voice and inflection in semantic analysis. For example, computers cannot detect sarcasm\n \nc. Language continually evolves and this could lead to some computer programs becoming obsolete\n\nd. Errors in text and speech could be a hinderance during text analysis. This is because it would be difficult fir the machine to understand and interpret\n\ne.Contextual words, phrases, homonyms and synonyms",
"_____no_output_____"
],
[
"### `Question 5`: Using some of the string operations learnt from this weeks topic (like: `set(), istitle(), split(), replace(), etc.`)\n### Declear 4 different strings (sentences) and apply the functions/methods.",
"_____no_output_____"
]
],
[
[
"a = ' In the end, he realized he could see sound and hear words. '\nb = 'I ate a sock because people on the Internet told me to'\nc = 'She had a car and she also had a car'\nd = 'The skeleton had skeletons of his own in the closet'\ne = 'peered'",
"_____no_output_____"
],
[
"a1=a.split(' ')\nb1=b.split(' ')\nc1=c.split(' ')\nd1=d.split(' ')\ne1=e.split('e')\n\nlen(a1)",
"_____no_output_____"
],
[
"a1",
"_____no_output_____"
],
[
"[w for w in b1 if len(w) > 3]",
"_____no_output_____"
],
[
"[w for w in b1 if w.istitle()]",
"_____no_output_____"
],
[
"[w for w in d1 if w.endswith('n')]",
"_____no_output_____"
],
[
"[w for w in d1 if w.startswith('s')]",
"_____no_output_____"
],
[
"[w for w in a1 if w.splitlines()]",
"_____no_output_____"
],
[
"len(set(c1))",
"_____no_output_____"
],
[
"set(c1)",
"_____no_output_____"
],
[
"len(set([w.lower() for w in c1]))",
"_____no_output_____"
],
[
"set([w.lower() for w in c1])",
"_____no_output_____"
],
[
"set([w.upper() for w in c1])",
"_____no_output_____"
],
[
"e1",
"_____no_output_____"
],
[
"'e'.join(e1)",
"_____no_output_____"
],
[
"a2 = a.strip()\na2.split(' ')",
"_____no_output_____"
],
[
"a2",
"_____no_output_____"
],
[
"a2.find('a')",
"_____no_output_____"
],
[
"a2.rfind('a')",
"_____no_output_____"
],
[
"a3 = a2.replace('e','q')\na3",
"_____no_output_____"
],
[
"c2=c.strip()\nc2.split()",
"_____no_output_____"
],
[
"c2",
"_____no_output_____"
],
[
"c2.find('a')",
"_____no_output_____"
],
[
"c2.rfind('a')",
"_____no_output_____"
],
[
"c3 = c2.replace('car','child')\nc3",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ac248d0c6d99caf63096ad39b6bca970e796c5 | 291,708 | ipynb | Jupyter Notebook | 09_Post_Experiments.ipynb | alexanderkrauck/AI-Warriors | d401af2e46c421e54cd8a986ac482bd959855b54 | [
"Apache-2.0"
] | 1 | 2021-11-11T15:25:23.000Z | 2021-11-11T15:25:23.000Z | 09_Post_Experiments.ipynb | alexanderkrauck/AI-Warriors | d401af2e46c421e54cd8a986ac482bd959855b54 | [
"Apache-2.0"
] | null | null | null | 09_Post_Experiments.ipynb | alexanderkrauck/AI-Warriors | d401af2e46c421e54cd8a986ac482bd959855b54 | [
"Apache-2.0"
] | 2 | 2021-09-18T20:55:12.000Z | 2021-11-11T15:25:24.000Z | 489.442953 | 201,152 | 0.643856 | [
[
[
"import utils.download as downl",
"_____no_output_____"
],
[
"import utils.dataloader as dl",
"_____no_output_____"
],
[
"loader = dl.RecSys2021TSVDataLoader(\n \"data/test_data\", \n \"indices/user_index_w_type.parquet\", \n mode=\"test\",\n batch_size = 1500000,\n remove_user_counts=True,\n remove_day_counts=True)",
"_____no_output_____"
],
[
"res = next(iter(loader))",
"_____no_output_____"
],
[
"res[0]",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"pd.read_csv(\"data/train_files/part-00000.csv\")",
"_____no_output_____"
],
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport numpy as np\n\n# use latex for font rendering\n#rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})\n#rc('text', usetex=True)",
"_____no_output_____"
],
[
"user_index = pd.read_parquet(\"indices/user_index.parquet\")\nuser_index",
"_____no_output_____"
],
[
"user_index[\"n_present\"] = user_index[\"n_present_a\"]#user_index[\"n_present_a\"] + user_index[\"n_present_b\"]\nuser_index = user_index[user_index[\"n_present\"]>0]\ndef quantile_mapping(x):\n if x < 93:\n return 1\n if x < 217:\n return 2\n if x < 442:\n return 3\n if x < 1064:\n return 4\n return 5\n\nuser_index[\"quantile\"] = user_index[\"follower_count\"].apply(quantile_mapping)",
"<ipython-input-21-e312e61a2554>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n user_index[\"n_present\"] = user_index[\"n_present_a\"]#user_index[\"n_present_a\"] + user_index[\"n_present_b\"]\n"
],
[
"quantiles = user_index.groupby([\"user_id\", \"quantile\"]).size().unstack(fill_value=0)\nquantiles.columns = [\"quantile\"+str(col) for col in quantiles.columns]\nuser_index = pd.merge(user_index, quantiles, how='inner', left_index=True, right_index=True)",
"_____no_output_____"
],
[
"len(user_index[user_index[\"quantile\"] == 1])",
"_____no_output_____"
],
[
"grp = user_index.groupby(\"n_present\")",
"_____no_output_____"
],
[
"cnt = grp.agg({\"follower_count\":[\"count\"], \"quantile1\":[\"mean\"], \"quantile2\":[\"mean\"], \"quantile3\":[\"mean\"],\"quantile4\":[\"mean\"],\"quantile5\":[\"mean\"]})",
"_____no_output_____"
],
[
"cnt",
"_____no_output_____"
],
[
"cnts = cnt.reset_index()\n#cnts.columns = [\"n_present\", \"times\"]\ncnts = cnts.to_numpy()\ncnts\n#plt.xscale(\"linear\")\n#plt.show()",
"_____no_output_____"
],
[
"cnts[:,2:] = (cnts[:,2:].T * cnts[:, 1]).T",
"_____no_output_____"
],
[
"cnts",
"_____no_output_____"
],
[
"import matplotlib as mpl\n\nhfont = {'fontname': 'serif'}\nmpl.rc('font',family='serif')\n\n\nplt.figure(figsize=(20,10))\nplt.hist(np.repeat(np.expand_dims(cnts[:,0],-1), 5, axis=-1), bins=130, stacked = True, weights = cnts[:,2:], label=[\"User Bin 1\", \"User Bin 2\", \"User Bin 3\", \"User Bin 4\", \"User Bin 5\"])\nplt.yscale(\"log\")\nplt.xticks(fontsize= 20, **hfont)\nplt.yticks(fontsize= 20, **hfont)\nplt.ylabel(\"Number of Users (log)\", fontsize=25, **hfont)#fontdict={'family': 'serif', 'serif': ['Computer Modern']})\nplt.xlabel('Number of Appearances', fontsize=25, **hfont)\nplt.margins(x=0)\nplt.legend(fontsize=15)\nplt.savefig('interaction_dist.png')\nplt.show()",
"_____no_output_____"
],
[
"np.repeat(np.expand_dims(cnts[:,0],-1), 5, axis=-1).shape",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ac2bcc3f0c187e8e7631867dfdb8f0c28ac392 | 93,454 | ipynb | Jupyter Notebook | mywork/Session 6 - GRU Language Model.ipynb | mingsqtt/textanalytics_ml | 87b0bd3d0e716e44a2cf627a6d7a1345aa886959 | [
"MIT"
] | null | null | null | mywork/Session 6 - GRU Language Model.ipynb | mingsqtt/textanalytics_ml | 87b0bd3d0e716e44a2cf627a6d7a1345aa886959 | [
"MIT"
] | null | null | null | mywork/Session 6 - GRU Language Model.ipynb | mingsqtt/textanalytics_ml | 87b0bd3d0e716e44a2cf627a6d7a1345aa886959 | [
"MIT"
] | null | null | null | 55.627381 | 13,576 | 0.631712 | [
[
[
"# IPython candies...\nfrom IPython.display import Image\nfrom IPython.core.display import HTML\n\nfrom IPython.display import clear_output",
"_____no_output_____"
],
[
"from collections import namedtuple\n\nimport numpy as np\nfrom tqdm import tqdm\n\nimport pandas as pd\n\nfrom gensim.corpora import Dictionary\n\nimport torch\nfrom torch import nn, optim, tensor, autograd\nfrom torch.nn import functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(\"Using device: {}\".format(device))",
"Using device: cuda\n"
],
[
"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_style(\"darkgrid\")\nsns.set(rc={'figure.figsize':(12, 8)})\n\n\ntorch.manual_seed(42)",
"_____no_output_____"
],
[
"try: # Use the default NLTK tokenizer.\n from nltk import word_tokenize, sent_tokenize \n # Testing whether it works. \n # Sometimes it doesn't work on some machines because of setup issues.\n print(\"nltk is working: {}\".format(word_tokenize(sent_tokenize(\"This is a foobar sentence. Yes it is.\")[0])))\nexcept: # Use a naive sentence tokenizer and toktok.\n import re\n from nltk.tokenize import ToktokTokenizer\n # See https://stackoverflow.com/a/25736515/610569\n sent_tokenize = lambda x: re.split(r'(?<=[^A-Z].[.?]) +(?=[A-Z])', x)\n # Use the toktok tokenizer that requires no dependencies.\n toktok = ToktokTokenizer()\n word_tokenize = word_tokenize = toktok.tokenize",
"nltk is working: ['This', 'is', 'a', 'foobar', 'sentence', '.']\n"
],
[
"import os\nimport requests\nimport io #codecs\n\n\n# Text version of https://kilgarriff.co.uk/Publications/2005-K-lineer.pdf\nif os.path.isfile('language-never-random.txt'):\n with io.open('language-never-random.txt', encoding='utf8') as fin:\n text = fin.read()\nelse:\n url = \"https://gist.githubusercontent.com/alvations/53b01e4076573fea47c6057120bb017a/raw/b01ff96a5f76848450e648f35da6497ca9454e4a/language-never-random.txt\"\n text = requests.get(url).content.decode('utf8')\n with io.open('language-never-random.txt', 'w', encoding='utf8') as fout:\n fout.write(text)\n \nprint(text)",
" Language is never, ever, ever, random\n\n ADAM KILGARRIFF\n\n\n\n\nAbstract\nLanguage users never choose words randomly, and language is essentially\nnon-random. Statistical hypothesis testing uses a null hypothesis, which\nposits randomness. Hence, when we look at linguistic phenomena in cor-\npora, the null hypothesis will never be true. Moreover, where there is enough\ndata, we shall (almost) always be able to establish that it is not true. In\ncorpus studies, we frequently do have enough data, so the fact that a rela-\ntion between two phenomena is demonstrably non-random, does not sup-\nport the inference that it is not arbitrary. We present experimental evidence\nof how arbitrary associations between word frequencies and corpora are\nsystematically non-random. We review literature in which hypothesis test-\ning has been used, and show how it has often led to unhelpful or mislead-\ning results.\nKeywords: 쎲쎲쎲\n\n1. Introduction\nAny two phenomena might or might not be related. The range of pos-\nsibilities is that the association is Random, Arbitrary, Motivated or Pre-\ndictable (R, A, M, P). The bulk of linguistic questions concern the dis-\ntinction between A and M. A linguistic account of a phenomenon gen-\nerally gives us reason to view the relation between, for example, a verb’s\nsyntax and its semantics, as motivated rather than arbitrary. However,\nit is not in general possible to model the A-M distinction mathematically.\nThe distinction that can be modeled mathematically is between R and\nnot-R, that is, between random, or uncorrelated, pairs and pairs where\nthere is some correlation, be it arbitrary, motivated or predictable.1 The\nmechanism here is hypothesis-testing. A null hypothesis, H0 is con-\nstructed to model the situation in which there is no correlation between\n\nCorpus Linguistics and Linguistic Theory 1⫺2 (2005), 263⫺275 1613-7027/05/0001⫺0263\n 쑕 Walter de Gruyter\n\f264 A. Kilgarriff\n\nthe two phenomena. As the mathematics of the random is well under-\nstood, we can compute the likelihood of the null hypothesis given the\ndata. If the likelihood is low, we reject H0.\n The problem for empirical linguistics is that language is not random,\nso the null hypothesis is never true. Language is not random because we\nspeak or write with purposes. We do not, indeed, without computational\nhelp are not capable of, producing words or sounds or sentences or\ndocuments randomly. We do not always have enough data to reject the\nnull hypothesis, but that is a distinct issue: wherever there is enough\ndata, it is rejected. Using language corpora, we are frequently in the\nfortunate position of having very large quantities of data at our disposal.\nThen, even where pairs of corpora are set up to be linguistically identical,\nthe null hypothesis is resoundingly defeated. In section 4, we present an\nexperiment demonstrating this counterintuitive effect.\n There are a number of papers in the empirical linguistics literature\nwhere researchers seemed to be testing whether an association was lin-\nguistically salient, or used the confidence with which H0 could be re-\njected as a measure of salience, whereas in fact they were merely testing\nwhether they had enough data to reject H0 with confidence. Some such\ncases are reviewed in section 5. Hypothesis testing has been widely used\nin the acquisition of subcategorization frames from corpora and this\nliterature is considered in some detail. Alternatives to inappropriate hy-\npothesis-testing are presented.\n Before proceeding, may I clarify that this paper is in no way critical\nof using probability models, all of which are based on assumptions of\nrandomness, in empirical linguistics in general. Probability models have\nbeen responsible for a large share of progress in the field in the last\ndecade and a half. The randomness assumptions are always untrue, but\nthat does not preclude them from frequently being useful. Making false\nassumptions is often an ingenious way to proceed; the problem arises\nwhere the literal falsity of the assumption is overlooked, and inappropri-\nate inferences are drawn.\n\n2. The arbitrary and the random\nIn common parlance, random and arbitrary are synonyms, with diction-\naries giving near-identical definitions: LDOCE (1995) defines random as\n happening or chosen without any definite plan, or pattern\nand arbitrary as\n 1 decided or arranged without any reason or plan, often unfairly … 2\n happening or decided by chance rather than a plan\n\f Language is never, ever, ever, random 265\n\n Superficially, randomness, as defined here, is what the technical sense\nof random captures and makes explicit. The technical sense is defined in\nterms of statistical independence. First, we formalize the framework:\n\n For a population of events, the first phenomenon holds where x is\n true of the event, the second holds where y is true of the event.\n\n Now, the relation between the phenomena is random iff the prob-\nability of x, for that subset of events where y does hold, is identical to\nits probability for the subset where y does not hold, that is\n\n P (x|y) ⫽ P (x|ÿ y)\n\n The relation is symmetric: P (x|y) ⫽ P (x|ÿ y) entails P (y|x) ⫽\nP (y|ÿ x). Hereafter I use ‘random’ for the technical meaning and ‘arbi-\ntrary’ for the non-technical one.\n Arbitrary events are very rarely random, and random events are very\nrarely arbitrary. It takes considerable ingenuity and sophisticated mathe-\nmatics to produce a pseudo-random sequence algorithmically, and true\nrandomness is not possible at all. Events happening “without any defi-\nnite plan, aim or pattern” are, by definition, arbitrary, but are vanish-\ningly unlikely to be random. Outside the sub-atomic realm, natural\nevents are very rarely random.\n Consider, for example, cat food purchases and shoe-polish purchases\nwithin the space of all UK supermarket-shopping events: does the fact\nthat cat food was bought predict (positively or negatively) whether shoe\npolish was bought in the same shopping trip? There is no obvious reason\nwhy it should, and we can happily declare the relation arbitrary. But\nperhaps either cat food or shoe-polish are more (or less) often bought in\nhot (or cold) weather, or on Saturday nights, or Sunday mornings, or\nMonday lunchtimes, or by richer (or poorer) people, or by men (or\nwomen), or by people in (or out of) towns… There is an unlimited\nnumber of hypotheses connecting the two (positively or negatively); if\njust one of these has any validity, however weak, then the null hypothesis\nis false.\n At this point, you may question why the null hypothesis is ever a\nuseful construct.\n For a wide range of tasks, although H0 is false, there is only enough\nevidence to establish the fact if there is a strong relation between the two\nphenomena. Thus, given evidence from 1,000 shopping trips, it is un-\nlikely we shall be able to reject H0 concerning cat food and shoe-polish,\nwhereas we shall be able to reject it concerning strawberry-buying and\ncream-buying. Given further evidence, perhaps from 1,000,000 shopping\n\f266 A. Kilgarriff\n\ntrips, we shall also be able to reject the null hypothesis regarding nappy2-\nbuying and beer-sixpack-buying. (The correlation, the most newsworthy\nproduct of large-scale data mining by supermarkets, was widely reported\nin the British media.) But still not for catf ood and shoe-polish. But,\ngiven 1,000,000,000 events, we shall in all likelihood also be able to reject\nit for cat food and shoe-polish.\n Whether or not we can reject the null hypothesis (with eg. 95 % confi-\ndence) is a function of sample size and level of correlation. Where sample\nsize is held constant (and is not enormous), whether or not we can reject\nH0 can be seen as a way of providing statistical support for distinguish-\ning the arbitrary and the motivated. This is a role that hypothesis testing\nplays across the social sciences. However where the sample size varies\nby an order of magnitude, or where it is enormous, it is wrong to identify\nthe accept-H0/reject-H0 distinction with the arbitrary/motivated one.\n The uneasy relationship between hypothesis-testing, and quantity of\ndata, is familiar to statisticians though frequently overlooked or mis-\nunderstood by users of statistics (Carver 1993, Stubbs 1995, Brandstätter\n1999). One statistics textbook warns thus:\n None of the null hypotheses we have considered with respect to good-\n ness of fit can be exactly true, so if we increase the sample size (and\n hence the value of χ2) we would ultimately reach the point when all\n null hypotheses would be rejected. All that the χ2 test can tell us, then,\n is that the sample size is too small to reject the null hypothesis! (Owen\n and Jones, 1977, p 359).\nThe issue is particularly salient for empirical linguistics because, firstly,\nwe have access to extremely large sample sizes, and secondly, the distri-\nbution of many language phenomena is Zipfian. The has 6,000,000 oc-\ncurrences in the BNC whereas cat food (spelled as one word or two) has\n66. For a vast number of third phenomena X, the null hypothesis that\nthe and X are uncorrelated will be rejected, whereas the null hypothesis\nthat cat food and X are uncorrelated will not. It would be wrong to draw\ninferences about what was arbitrary, what motivated.\n\n3. Objections to Maximum Likelihood Estimates (MLEs)\nChurch and Hanks (1990) inaugurated the research area of lexical statis-\ntics with their presentation of Mutual Information (I), a measure of how\nclosely associated two phenomena are. It can be applied to finding words\nwhich occur together to a noteworthy degree, or to finding words which\nare particularly associated with one corpus as against another, or for\nvarious other purposes.3 They define the mutual information between\ntwo words x and y as\n\f Language is never, ever, ever, random 267\n\n I (x; y) ⫽ log 2 冉 p (xandy)\n p (x) · p(y)\n 冊\nand then estimate probabilities directly from frequencies, that is using\nthe ‘Maximum Likelihood Estimate’ (MLE) of f (x)/N for p (x), f (y)/N\nfor p (y), f (x-and-y)/N for p (x-and-y), thereby giving\n\n\n I (x; y) ⫽ log 2 冉 N · f (x ⫺ and ⫺ y)\n f (x) · f (y)\n 冊\n Dunning (1993) presents a critique of the use of Mutual Information\nin empirical linguistics. His objection has been confused with the critique\nof hypothesis-testing I make here so I mention his work in order to\nclarify that the two objections, while both valid, are different in nature\nand independent.\n Dunning demonstrates how MLEs fare poorly when estimating the\nprobabilities of rare events. The problem is essentially this: if a word (or\nbigram, or trigram, or character-sequence etc.) occurs just once or twice\nin a corpus of N words (bigrams, etc.), then the simplest way to estimate\nthe probability is the NILE, which gives 1/N or 2/N. However this does\nnot factor in the arbitrariness of the word occurring at all in the corpus:\nin a corpus ten times the size, there would be roughly ten times the\nnumber of singletons and doubletons in the corpus, most of which would\nnot have occurred at all in the original corpus. Thus some of the prob-\nability mass contributing to the 1/N or 2/N MLEs should have been put\naside for the words (bigrams etc.) which did not occur at all in this\nparticular corpus. Viewed another way, the 1/N and 2/N should be dis-\ncounted to allow for the fact that one or two occurrences are very low\nbases of evidence on which to assert probabilities.\n There are various ways in which the discounting can be done, for\nexample the Good-Turing method (Good 1953), usefully applied to em-\npirical linguistics in Gale and Sampson (1995), Bod (1995). Dunning\npresents and advocates the use of the log-likelihood statistic, which, like\nthe χ2 statistic, is χ2-distributed,4 but more accurately estimates probabil-\nities where counts are low. The log-likelihood statistic still only estimates\nprobabilities: since Dunning’s work, Pedersen (1996) has shown how\nFisher’s Exact Method can be applied to the problem, to identify the\nexact probability of a word (bigram etc.) rather than estimating it at all.\n Thus Dunning’s objection to Mutual Information is that it fails to\naccurately represent probabilities when counts are low (where ‘low’ is\ngenerally taken as less than five). If the probabilities can be accurately\nrepresented, Dunning’s anxieties will be set at ease.\n\f268 A. Kilgarriff\n\n The critique in this paper does not concern whether probabilities are\naccurately calculated. Rather, the objection is that the probability model,\nwith its assumptions of randomness, is inappropriate, particularly where\ncounts are high (eg, thousands or more).\n Where the task is to determine whether there is an interesting associa-\ntion between two rare events, Dunning’s concern must be heeded. Where\nit is to determine whether there is an interesting association between\nhigh-frequency events, the concerns of this paper must be.\n\n\n4. Experiment\nGiven enough data, H0 is almost always rejected however arbitrary the\ndata, as the author discovered when grappling with the following data.\n Two corpora were set up to be indisputably of the same language type,\nwith only arbitrary differences between them: each was a random subset\nof the written part of the British National Corpus (BNC). The sampling\nwas as follows: all texts shorter than 20,000 words were excluded. This\nleft 820 texts. Half the texts were then randomly assigned to each of\ntwo corpora.\n The null hypotheses were (1) that the two subcorpora, viewed as col-\nlections of words rather than documents, were random samples drawn\nfrom the same population; and consequently, (2) that the deviation in\nfrequency of occurrence for each individual word between the two sub-\ncorpora was explicable as random fluctuation. The HO were tested using\nthe χ2-test: is χ2\n\n Σ(|O ⫺ E | ⫺ 0.5) 2 /E\n\ngreater than the critical value? The sum is over the four cells of the\ncontingency table\n\n Corpus 1 Corpus 2\n\nword w a b\nnot word w c d\n\n\n If we randomly assign words (as opposed to documents) to the one\ncorpus or the other, then we have a straightforward random distribution,\nwith the value of the χ2-statistic equal to or greater than the 99.5 %\nconfidence threshold of 7.88 for just 0.5 % of words. The average value\nof the error term,\n\f Language is never, ever, ever, random 269\n\n (|O ⫺ E| ⫺ 0.5) 2 /E\n\nis then 0.5.5 The hypothesis can, therefore, be couched as: are the error\nterms systematically greater than 0.5? If they are, we should be wary of\nattributing high error terms to significant differences between text types,\nsince we also obtain many high error terms where there are no significant\ndifferences between text types.\n Frequency lists for word-POS pairs for each subcorpus were gener-\nated. For each word occurring in either subcorpus, the error term which\nwould have contributed to a χ2 calculation was determined. As Table 4\nshows, average values for the error term are far greater than 0.5, and\ntend to increase as word frequency increases.\n As the averages indicate, the error term is very often greater than 0.5\n* 7.88 ⫽ 3.94, the relevant critical value of the chi-square statistic. For\nvery many words, including most common words, the null hypothesis is\nresoundingly defeated (as is the null hypthesis regarding the two subc-\norpora as wholes).\n There is no a priori reason to expect words to behave as if they had\nbeen selected at random, and indeed they do not. It is in the nature of\n\n\n\n\nTable 1. Comparing two same-genre corpora using χ2\nClass First item in class Mean error term\n(Words in freq. order) for items in class\n word POS\n\nFirst 10 items the DET 18.76\nNext 10 items for PRP 17.45\nNext 20 items not XX 14.39\nNext 40 items have VHB 10.71\nNext 80 items also AVO 7.03\nNext 160 items know VVI 6.40\nNext 320 items six CRD 5.30\nNext 640 items finally AV0 6.71\nNext 1280 items plants NN2 6.05\nNext 2560 items pocket NN1 5.82\nNext 5120 items represent VVB 4.53\nNext 10240 items peking NP0 3.07\nNext 20480 items fondly AV0 1.87\nNext 40960 items chandelier NN1 1.15\nTable note. Mean error term is far greater than 0.5, and increases with frequency.\nPOS tags are drawn from the CLAWS-5 tagset as used in the BNC (see http:/info.ox.\nac.uk/bnc)\n\f270 A. Kilgarriff\n\nlanguage that any two collections of texts, covering a wide range of\nregisters (and comprising, say, less than a thousand samples of over a\nthousand words each) will show such differences. While it might seem\nplausible that oddities would in some way balance out to give a popula-\ntion that was indistinguishable from one where the individual words (as\nopposed to the texts) had been randomly selected, this turns out not to\nbe the case.\n The key word in the last paragraph is ‘indistinguishable’. In hypothesis\ntesting, the objective is generally to see if the population can be distin-\nguished from one that has been randomly generated ⫺ or, in our case,\nto see if the two populations are distinguishable from two populations\nwhich have been randomly generated on the basis of the frequencies in\nthe joint corpus. Since words in a text are not random, we know that\nour corpora are not randomly generated, and the hypothesis test con-\nfirms the fact.\n\n\n5. Re-analysis of previous work\n\n5.1. Brown and LOB\n\nHofland and Johansson (1982) wanted to find words which were signifi-\ncantly different in their frequencies between British and American Eng-\nlish, as represented in the Brown corpus for American English and LOB\ncorpus for British. For each word, they tested the null hypothesis that\nthe difference in frequency between the two corpora could be explained\nas random variation, with the samples being random samples from the\nsame source, and in their frequency lists, they mark words where the\nnull hypothesis was defeated (at a 95, 99 or 99.9 % confidence level).\nLooking at these lists suggests that virtually all common words are\nmarkedly different in their levels of use between the US and the UK:\nthey are all marked as such. By contrast, most of the rarer marked words\nare words we know to be American or British, or to refer to items that\nare more common or more salient in the US or the UK.\n As the argument of the previous section explains, most of the marked\nhigh-frequency words are marked simply as a consequence of the essen-\ntially non-random nature of language. It would not be surprising for a\nhigh-frequency word marked as British English in these lists to be\nmarked as American English in a repeat of the experiment using new\ndata.\n Similar strategies are used by, and a similar critique is applicable to,\nLeech and Fallon (1992) (again, for comparing LOB and Brown), Ray-\n\f Language is never, ever, ever, random 271\n\nson, Leech, and Hodges (1997) for comparing the conversation of dif-\nferent social groups, and Rayson and Garside (2000) for contrasting the\nlanguage of a specialist genre with ‘general language’, as represented by\nthe British National Corpus.\n\n\n5.2 Subcategorization frame (SCF) learning\nHypothesis-testing has been used in a number of papers concerning the\nautomatic acquisition of subcategorization frames (SCFs) for verbs from\ncorpora. The problem is this. Dictionaries, even where they do present\nexplicit and accurate SCFs for verbs, are not complete: they do not pre-\nsent all the frames for each verb. This gives rise to many parsing errors.\nResearchers including Brent (1993), Briscoe and Carroll (1997) and Kor-\nhonen (2000) have developed methods for SCF acquisition. However,\ntheir methods are inevitably noisy, suffering, for example, from just those\nparser errors that the whole process is designed to address, and they do\nnot wish to accept any SCF for which there is any evidence as a true\nSCF for the verb. They wish to filter out those SCFs where the evidence\nis not strong enough. Brent and Briscoe and Carroll used hypothesis\ntesting to this end. However, problems are noted:\n\n Further evaluation of the results ...reveals that the filtering phase is\n the weak link in the system … The performance of the filter for classes\n with less than 10 exemplars is around chance, and a simple heuristic\n of accepting all classes with more then 10 exemplars would have pro-\n duced broadly similar results for these verbs (Briscoe and Carroll\n 1997: 360⫺36).\n\nKorhonen, Correll, and McCarthy (2000) explore the issue in detail.\nUsing Briscoe and Carroll’s SCF acquisition system, they explore the\nimpact of four different strategies for filtering out noise:\n\nBaseline No filter\nBHT binomial hypothesis test: reject the SCF if Ho is not defeated6\nLLR hypothesis test using log-likelihood ratio: reject the SCF if\n Ho is not defeated\nMLE threshold based on the relative frequency (which is also the\n maximum likelihood estimate (MLE) of the probability) of\n the verb occurring in the SCF given the verb, with the thresh-\n old determined empirically\n\f272 A. Kilgarriff\n\n They observe\n\n MLE thresholding produced better results than the two statistical tests\n used. Precision improved considerably, showing that the classes occur-\n ring in the data with the highest frequency are often correct … MLE\n is not adept at finding low frequency SCFs … (Korhonen, Correll,\n and McCarthy 2000: 202)\n\nThis concurs with the theoretical argument above. Hypothesis tests are\ninappropriate for the task, because the relations between verb and SCF\nwill never be random and the hypothesis test will merely reject the null\nhypothesis wherever there is enough data, in a manner not closely corre-\nlated with whether the SCF-verb link is motivated. Where there is\nenough data, then the relationship between verb and SCF is easy to see\nso even a simple threshold method will identify the verb’s SCFs. Where\ndata is very sparse, no method works well.\n Korhonen (2000) extends this line of work, exploring thresholding\nmethods where a more accurate estimate of the probability is obtained\nby using data from semantically similar but higher frequency verbs. She\nachieves modest improvements over the baseline which uses Korhonen,\nCorrell and McCarthy’s MLE, particularly when combining the fre-\nquencies of the target verb and its semantic neighbour using a linear\nmethod based on the quantity of evidence available for each.\n The problem is not one of distinguishing random and non-random\nrelationships, but of sparseness of data. Where the data is not sparse,\nthe difference between arbitrary and motivated connections is evident in\ngreatly differing relative frequencies. This makes the moral of the story\nplain. Data is abundant. A modest-frequency verb like devastate occurs\n(Google tells us) in well over a million web pages. With just 1 % of them,\ndevastate becomes one of the verbs for which we have plenty of data,\nand crude thresholding methods will distinguish associated SCFs from\nnoise. It is possible that parsing errors are systematic and thus that the\nsame errors occur very often in very large corpora although our experi-\nence from looking at large corpora in the Word Sketch Engine (Kilgarriff\net al 2004) suggests not. Harvesting the web (or other huge corpora) is\nthe way to build an accurate SCF lexicon.7\n\n6. Conclusion\nLanguage is non-random and hence, when we look at linguistic phenom-\nena in corpora, the null hypothesis will never be true. Moreover, where\nthere is enough data, we shall (almost) always be able to establish that\nit is not true. In corpus studies, we frequently do have enough data, so\n\f Language is never, ever, ever, random 273\n\nthe fact that a relation between two phenomena is demonstrably non-\nrandom, does not support the inference that it is not arbitrary. Hypoth-\nesis testing is rarely useful for distinguishing associated from non-associ-\nated pairs of phenomena in large corpora. Where used, it has often led\nto unhelpful or misleading results.\n Hypothesis testing has been used to reach conclusions, where the diffi-\nculty in reaching a conclusion is caused by sparsity of data. But language\ndata, in this age of information glut, is available in vast quantities. A\nbetter strategy will generally be to use more data Then the difference\nbetween the motivated and the arbitrary will be evident without the use\nof compromised hypothesis testing. As Lord Rutherford put it: “If your\nexperiment needs statistics, you ought to have done a better experi-\nment.”\nReceived July 2004 Lexical Computing Ltd.\nRevisions received May 2005\nFinal acceptance May 2005\n\nNotes\n * This work was supported by the UK EPSRC, under grants GR/K18931 (SEAL)\n and GR/M54971 (WASPS).\n 1. In this paper we do not consider the distinction between the predictable and the\n ‘merely’ motivated.\n 2. Diapers, in American English\n 3. There is some confusion over names. In information theory, Mutual Information\n is usually defined over a whole population of words, rather than being specified\n for a particular word-pair, as here, and the definition incorporates information\n from all cells of the contingency table. Church and Hanks only use a subset of that\n information. Church-and-Hanks Mutual Information has been called Pointwise\n Mutual Information. see Manning and Schütze (1999: 66 ff.) for a fuller discus-\n sion. Here we use Church and Hanks’s definition and name.\n 4. This sentence will be confusing to non-mathematicians. The χ2 statistic is a statis-\n tic, that is, it can be calculated from a data sample using actual numbers. The χ2\n distribution is a theoretical construct. If a sufficiently large number of chi-square\n statistics are calculated, all from true random samples of the same population,\n then this population of χ2 statistics will, provably, fit a χ2 distribution. This is\n also true for other statistics: that is, if a sufficiently large number of log-likelihood\n statistics are calculated, all from true random samples of the same population,\n then this population of log-likelihood statistics will, provably, fit a χ2 distribution.\n Some texts call the statistic χ2 rather than χ2 to distinguish it more clearly from\n the distribution, but this practice is in the minority and is not adopted here.\n 5. See appendix\n 6. The model used was a sophisticated one incorporating evidence about type fre-\n quencies of verbs from the ANLT lexicon: see Briscoe and Carroll (1997) or Kor-\n honen, Correll, and McCarthy (2000) for details.\n 7. See Kilgarriff and Grefenstette (2003) and papers therein. The web is a vast re-\n source for many languages. See also Banko and Brill (2001) for the benefits of\n large data over sophisticated mathematics.\n\f274 A. Kilgarriff\n\nAppendix\nThe average value of the error term is 0.5. We explain this as follows.\n If we do in fact have a random distribution, then by the definition of\nthe χ2 distribution, the sum of the cells in the contingency table is 1:\n\n a⫹b⫹c⫹d⫽1\n\nEach of these error terms is calculated as\n\n (O ⫺ E ⫺ 0.5) 2/E\n\nIn our situation, there are very large datasets and the phenomenon of\ninterest only accounts for a very small proportion of cases. The fre-\nquency of not word w is very high. Thus the expected values, E, for not\nword w to be used when calculating c and d for the contingency table are\nvery high. As we divide by very large E, c and d are vanishingly small, so\n\n a⫹b⫹c⫹d⫽1\n\nreduces to\n\n a⫹b⫽1\n\nSince we have set the situation up symmetrically, a and b are the same\nsize, so each will be, on average, 0.5.\n\nReferences\nBanko, Michele and Eric Brill\n 2001 Scaling to very very large corpora for natural language disambiguation.\n Proceedings of the 39th Annual Meeting of the Association for Computa-\n tional Linguistics and the 10th Conference of the European Chapter of the\n Association for Computational Linguistics.\nBod, Rens\n 1995 Enriching linguistics with statistics: performance models of natural lan-\n guage. Ph.D. dissertation, University of Amsterdam.\nBrandstätter, E.\n 1999 Confidence intervals as an alternative to significance testing. Methods of\n Psychological Research Outline 4(2), 33⫺46.\nBrent, Michael R.\n 1993 From grammar to lexicon: unsupervised learning of lexical syntax. Com-\n putational Linguistics 19(2), 243⫺262.\nBriscoe, Ted and John Carroll\n 1997 Automatic extraction of subcategorization from corpora. Proceedings of\n the Fifth Conference on Applied Natural Language Processing, 356⫺363.\n\f Language is never, ever, ever, random 275\nCarver, R. P.\n 1993 The case against statistical significance testing, revisited. Journal of Ex-\n perimental Education 61, 287⫺292.\nChurch, Kenneth and Patrick Hanks\n 1990 Word association norms, mutual information and lexicography. Compu-\n tational Linguistics 16(1), 22⫺29.\nDunning, Ted\n 1993 Accurate methods for the statistics of surprise and coincidence. Compu-\n tational Linguistics 19(1), 61⫺74.\nGale, William and Geoffrey Sampson\n 1995 Good-Turing frequency estimation without tears. Journal of Quantitative\n Linguistics 2(3),\nGood, I. J.\n 1953 The population frequencies of species and the estimation of population\n parameters. Biometrika 40, 237⫺264.\nGrefenstette, Gregory and Julien Nioche\n 2000 Estimation of English and non-English language use on the www. In\n Proceedings of RIAO (Recherche d’Informations Assiste´ e par Ordinateur),\n 237⫺246.\nHofland, Knud and Stig Johanson (Eds.)\n 1982 Word Frequencies in British and American English. Bergen: The Norwe-\n gian Computing Centre for the Humanities.\nKorhonen, Anna\n 2000 Using semantically motivated estimates to help subcategorization\n acquisition. Proceedings of the Joint Conference on Empirical Methods in\n NLP and Very Large Corpora, 216⫺223.\nKorhonen, Anna, Genevieve Gorrell, and Diana McCarthy\n 2000 Statistical filtering and subcategorization frame acquisition. Proceedings\n of the Joint Conference on Empirical Methods in NLP and Very Large\n Corpora, 199⫺206.\nLDOCE\n 1995 Longman Dictionary of Contemporary English, 3rd Edition. Ed. Della\n Summers. Harlow: Longman.\nLeech, Geoffrey and Roger Fallon\n 1992 Computer corpora — what do they tell us about culture? ICAME Journal\n 16, 29⫺50.\nManning, Christopher and Hinrich Schütze\n 1999 Foundations of Statistical Natural Language Processing. Cambridge, MA:\n MIT Press.\nOwen, Frank and Ronald Jones\n 1977 Statistics. Polytech Publishers.\nPedersen, Ted\n 1996 Fishing for exactness. Proceedings of the Conference of the South-Central\n SAS Users Group, 188⫺200.\nRayson, Paul and Roger Garside\n 2000 Comparing corpora using frequency profiling. Proceedings of the Work-\n shop on Comparing Corpora, 38th ACL, 1⫺6.\nRayson, Paul, Geoffrey Leech, and Mary Hodges\n 1997 Social differentiation in the use of English vocabulary: some analysis of\n the conversational component of the British National Corpus. Interna-\n tional Journal of Corpus Linguistics 2(1), 133⫺152.\nStubbs, Michael\n 1995 Collocations and semantic profiles: On the cause of the trouble with\n quantitative studies. Functions of Language 2(1), 23⫺55.\n\f\n"
],
[
"# Tokenize the text.\ntokenized_text = [list(map(str.lower, word_tokenize(sent))) \n for sent in sent_tokenize(text)]\nprint(\"len(tokenized_text): {}\".format(len(tokenized_text)))\nprint(\"The longest sentence has {} tokens.\".format(max([len(sent) for sent in tokenized_text])))\nfor i, sent in enumerate(tokenized_text):\n print(\"len(sentence[{}]): {}\".format(i, len(sent)))",
"len(tokenized_text): 235\nThe longest sentence has 184 tokens.\nlen(sentence[0]): 25\nlen(sentence[1]): 12\nlen(sentence[2]): 20\nlen(sentence[3]): 24\nlen(sentence[4]): 37\nlen(sentence[5]): 17\nlen(sentence[6]): 26\nlen(sentence[7]): 5\nlen(sentence[8]): 11\nlen(sentence[9]): 28\nlen(sentence[10]): 48\nlen(sentence[11]): 15\nlen(sentence[12]): 44\nlen(sentence[13]): 42\nlen(sentence[14]): 24\nlen(sentence[15]): 10\nlen(sentence[16]): 20\nlen(sentence[17]): 12\nlen(sentence[18]): 24\nlen(sentence[19]): 30\nlen(sentence[20]): 22\nlen(sentence[21]): 22\nlen(sentence[22]): 13\nlen(sentence[23]): 60\nlen(sentence[24]): 9\nlen(sentence[25]): 23\nlen(sentence[26]): 8\nlen(sentence[27]): 35\nlen(sentence[28]): 22\nlen(sentence[29]): 18\nlen(sentence[30]): 31\nlen(sentence[31]): 2\nlen(sentence[32]): 95\nlen(sentence[33]): 11\nlen(sentence[34]): 36\nlen(sentence[35]): 79\nlen(sentence[36]): 20\nlen(sentence[37]): 15\nlen(sentence[38]): 24\nlen(sentence[39]): 29\nlen(sentence[40]): 12\nlen(sentence[41]): 45\nlen(sentence[42]): 18\nlen(sentence[43]): 98\nlen(sentence[44]): 17\nlen(sentence[45]): 32\nlen(sentence[46]): 39\nlen(sentence[47]): 29\nlen(sentence[48]): 24\nlen(sentence[49]): 9\nlen(sentence[50]): 23\nlen(sentence[51]): 13\nlen(sentence[52]): 16\nlen(sentence[53]): 39\nlen(sentence[54]): 13\nlen(sentence[55]): 31\nlen(sentence[56]): 36\nlen(sentence[57]): 55\nlen(sentence[58]): 25\nlen(sentence[59]): 11\nlen(sentence[60]): 34\nlen(sentence[61]): 22\nlen(sentence[62]): 36\nlen(sentence[63]): 15\nlen(sentence[64]): 2\nlen(sentence[65]): 42\nlen(sentence[66]): 184\nlen(sentence[67]): 38\nlen(sentence[68]): 14\nlen(sentence[69]): 21\nlen(sentence[70]): 16\nlen(sentence[71]): 20\nlen(sentence[72]): 56\nlen(sentence[73]): 27\nlen(sentence[74]): 11\nlen(sentence[75]): 34\nlen(sentence[76]): 41\nlen(sentence[77]): 31\nlen(sentence[78]): 46\nlen(sentence[79]): 7\nlen(sentence[80]): 34\nlen(sentence[81]): 18\nlen(sentence[82]): 17\nlen(sentence[83]): 32\nlen(sentence[84]): 26\nlen(sentence[85]): 23\nlen(sentence[86]): 2\nlen(sentence[87]): 26\nlen(sentence[88]): 39\nlen(sentence[89]): 15\nlen(sentence[90]): 5\nlen(sentence[91]): 13\nlen(sentence[92]): 59\nlen(sentence[93]): 27\nlen(sentence[94]): 76\nlen(sentence[95]): 49\nlen(sentence[96]): 38\nlen(sentence[97]): 12\nlen(sentence[98]): 22\nlen(sentence[99]): 26\nlen(sentence[100]): 28\nlen(sentence[101]): 31\nlen(sentence[102]): 26\nlen(sentence[103]): 9\nlen(sentence[104]): 19\nlen(sentence[105]): 95\nlen(sentence[106]): 14\nlen(sentence[107]): 19\nlen(sentence[108]): 42\nlen(sentence[109]): 48\nlen(sentence[110]): 12\nlen(sentence[111]): 58\nlen(sentence[112]): 28\nlen(sentence[113]): 2\nlen(sentence[114]): 6\nlen(sentence[115]): 43\nlen(sentence[116]): 64\nlen(sentence[117]): 32\nlen(sentence[118]): 38\nlen(sentence[119]): 30\nlen(sentence[120]): 32\nlen(sentence[121]): 89\nlen(sentence[122]): 31\nlen(sentence[123]): 5\nlen(sentence[124]): 30\nlen(sentence[125]): 8\nlen(sentence[126]): 26\nlen(sentence[127]): 50\nlen(sentence[128]): 15\nlen(sentence[129]): 12\nlen(sentence[130]): 73\nlen(sentence[131]): 15\nlen(sentence[132]): 110\nlen(sentence[133]): 50\nlen(sentence[134]): 50\nlen(sentence[135]): 31\nlen(sentence[136]): 11\nlen(sentence[137]): 34\nlen(sentence[138]): 46\nlen(sentence[139]): 18\nlen(sentence[140]): 22\nlen(sentence[141]): 9\nlen(sentence[142]): 4\nlen(sentence[143]): 19\nlen(sentence[144]): 32\nlen(sentence[145]): 44\nlen(sentence[146]): 20\nlen(sentence[147]): 25\nlen(sentence[148]): 24\nlen(sentence[149]): 46\nlen(sentence[150]): 19\nlen(sentence[151]): 13\nlen(sentence[152]): 24\nlen(sentence[153]): 17\nlen(sentence[154]): 30\nlen(sentence[155]): 30\nlen(sentence[156]): 31\nlen(sentence[157]): 2\nlen(sentence[158]): 19\nlen(sentence[159]): 2\nlen(sentence[160]): 7\nlen(sentence[161]): 7\nlen(sentence[162]): 41\nlen(sentence[163]): 11\nlen(sentence[164]): 10\nlen(sentence[165]): 11\nlen(sentence[166]): 6\nlen(sentence[167]): 12\nlen(sentence[168]): 2\nlen(sentence[169]): 8\nlen(sentence[170]): 23\nlen(sentence[171]): 8\nlen(sentence[172]): 36\nlen(sentence[173]): 47\nlen(sentence[174]): 31\nlen(sentence[175]): 2\nlen(sentence[176]): 4\nlen(sentence[177]): 41\nlen(sentence[178]): 2\nlen(sentence[179]): 11\nlen(sentence[180]): 11\nlen(sentence[181]): 18\nlen(sentence[182]): 14\nlen(sentence[183]): 6\nlen(sentence[184]): 72\nlen(sentence[185]): 11\nlen(sentence[186]): 27\nlen(sentence[187]): 47\nlen(sentence[188]): 19\nlen(sentence[189]): 28\nlen(sentence[190]): 16\nlen(sentence[191]): 7\nlen(sentence[192]): 13\nlen(sentence[193]): 12\nlen(sentence[194]): 16\nlen(sentence[195]): 10\nlen(sentence[196]): 14\nlen(sentence[197]): 13\nlen(sentence[198]): 24\nlen(sentence[199]): 9\nlen(sentence[200]): 16\nlen(sentence[201]): 10\nlen(sentence[202]): 14\nlen(sentence[203]): 10\nlen(sentence[204]): 13\nlen(sentence[205]): 14\nlen(sentence[206]): 13\nlen(sentence[207]): 5\nlen(sentence[208]): 18\nlen(sentence[209]): 17\nlen(sentence[210]): 10\nlen(sentence[211]): 9\nlen(sentence[212]): 11\nlen(sentence[213]): 13\nlen(sentence[214]): 17\nlen(sentence[215]): 18\nlen(sentence[216]): 17\nlen(sentence[217]): 11\nlen(sentence[218]): 2\nlen(sentence[219]): 3\nlen(sentence[220]): 4\nlen(sentence[221]): 18\nlen(sentence[222]): 6\nlen(sentence[223]): 14\nlen(sentence[224]): 7\nlen(sentence[225]): 9\nlen(sentence[226]): 3\nlen(sentence[227]): 8\nlen(sentence[228]): 13\nlen(sentence[229]): 13\nlen(sentence[230]): 14\nlen(sentence[231]): 32\nlen(sentence[232]): 13\nlen(sentence[233]): 19\nlen(sentence[234]): 10\n"
],
[
"voc = Dictionary(tokenized_text)\n\nprint(\"len(voc) unique terms: {}\".format(len(voc)))\nprint(\"indices of tokens {} in token dictionary are: {}\".format([\"we\", \"the\", \"is\", \"<unk>\", \"<s>\", \"</s>\"], voc.doc2idx([\"we\", \"the\", \"is\", \"<unk>\", \"<s>\", \"</s>\"])))\nori_tokens = [voc[0], voc[1], voc[2], voc[3]]\nprint(\"original tokens at index [0,1,2,3] are: {}\".format(ori_tokens))\n\nspecial_tokens = {'<pad>': 0, '<unk>':1, '<s>':2, '</s>':3}\nvoc.patch_with_special_tokens(special_tokens) # this will change the indices of the original terms from [0,1,2,3] to the tail of the token vector\n\nprint(\"after patch_with_special_tokens(), the new indices of those tokens are now: {}\".format(voc.doc2idx(ori_tokens)))\n# dir(voc)",
"len(voc) unique terms: 1388\nindices of tokens ['we', 'the', 'is', '<unk>', '<s>', '</s>'] in token dictionary are: [37, 35, 8, -1, -1, -1]\noriginal tokens at index [0,1,2,3] are: [',', '.', 'abstract', 'adam']\nafter patch_with_special_tokens(), the new indices of those tokens are now: [1388, 1389, 1390, 1391]\n"
],
[
"class KilgariffDataset(nn.Module):\n def __init__(self, tokenized_texts):\n self.texts = tokenized_texts\n \n # Initialize the vocab \n special_tokens = {'<pad>': 0, '<unk>':1, '<s>':2, '</s>':3}\n self.vocab = Dictionary(tokenized_texts)\n self.vocab.patch_with_special_tokens(special_tokens)\n \n # Keep track of the vocab size.\n self.vocab_size = len(self.vocab)\n \n # Keep track of how many data points.\n self._len = len(self.texts)\n \n # Find the longest sentence in the data.\n self.max_len = max(len(sent) for sent in tokenized_texts) \n \n def __getitem__(self, sent_index):\n sent = self.texts[sent_index]\n vectorized_sent = self.vectorize(sent)\n sent_len = len(vectorized_sent)\n # To pad the sentence:\n # Pad left = 0; Pad right = max_len - len of sent.\n pad_len = self.max_len - len(vectorized_sent)\n pad_dim = (0, pad_len)\n padded_vectorized_sent = F.pad(vectorized_sent, pad_dim, 'constant')\n return {'x':padded_vectorized_sent[:-1], \n 'y':padded_vectorized_sent[1:], \n 'x_len':sent_len,\n \"pad_len\":pad_len,\n \"padded_vectorized_sent\": padded_vectorized_sent}\n \n def __len__(self):\n return self._len\n \n def vectorize(self, sent_tokens, start_sent_idx=2, end_sent_idx=3):\n \"\"\"\n :param tokens: Tokens that should be vectorized. \n :type tokens: list(str)\n \"\"\"\n # See https://radimrehurek.com/gensim/corpora/dictionary.html#gensim.corpora.dictionary.Dictionary.doc2idx \n # Lets just cast list of indices into torch tensors directly =)\n \n vectorized_sent = [start_sent_idx] + self.vocab.doc2idx(sent_tokens) + [end_sent_idx]\n return torch.tensor(vectorized_sent)\n \n def unvectorize(self, indices):\n \"\"\"\n :param indices: Converts the indices back to tokens.\n :type tokens: list(int)\n \"\"\"\n return [self.vocab[i] for i in indices]",
"_____no_output_____"
],
[
"kilgariff_data = KilgariffDataset(tokenized_text)\nprint(\"len(kilgariff_data.vocab): {}\".format(len(kilgariff_data.vocab)))\nkilgariff_data0 = kilgariff_data[0]\nprint(\"kilgariff_data[0] has sentence len: {}, pad len: {}, total len: {}, trainable data series len: {}\".format(kilgariff_data0[\"x_len\"], kilgariff_data0[\"pad_len\"], len(kilgariff_data[0][\"padded_vectorized_sent\"]), len(kilgariff_data0[\"x\"])))\nprint()\nprint(\"kilgariff_data[0]: {}\".format(kilgariff_data[0][\"padded_vectorized_sent\"]))",
"len(kilgariff_data.vocab): 1392\nkilgariff_data[0] has sentence len: 27, pad len: 157, total len: 184, trainable data series len: 183\n\nkilgariff_data[0]: tensor([ 2, 10, 8, 11, 1388, 7, 1388, 7, 1388, 13, 1391, 9,\n 1390, 10, 15, 11, 5, 16, 14, 1388, 4, 10, 8, 6,\n 12, 1389, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0])\n"
],
[
"batch_size = 10\ndataloader = DataLoader(dataset=kilgariff_data, batch_size=batch_size, shuffle=True) # please disable shuffle if the data is time series\n\nfor item_dict in dataloader:\n # Sort indices of data in batch by lengths.\n sorted_indices = np.array(item_dict['x_len']).argsort()[::-1].tolist()\n data_batch = {name: _tensor[sorted_indices]\n for name, _tensor in item_dict.items()}\n for key in data_batch:\n print(\"{}: <{}>\\n{}\".format(key, data_batch[key].shape, data_batch[key]))\n print()\n break\n \n# x's shape: (batch_size, sequence_len=max_sent_len-1)\n# y's shape: (batch_size, sequence_len=max_sent_len-1)\n# x_len's shape: (batch_size)\n# pad_len's shape: (batch_size)\n# padded_vectorized_sent's shape: (batch_size, max_sent_len)",
"x: <torch.Size([10, 183])>\ntensor([[ 2, 184, 248, ..., 0, 0, 0],\n [ 2, 344, 327, ..., 0, 0, 0],\n [ 2, 269, 52, ..., 0, 0, 0],\n ...,\n [ 2, 994, 1388, ..., 0, 0, 0],\n [ 2, 747, 799, ..., 0, 0, 0],\n [ 2, 1206, 1389, ..., 0, 0, 0]])\n\ny: <torch.Size([10, 183])>\ntensor([[ 184, 248, 73, ..., 0, 0, 0],\n [ 344, 327, 392, ..., 0, 0, 0],\n [ 269, 52, 35, ..., 0, 0, 0],\n ...,\n [ 994, 1388, 1272, ..., 0, 0, 0],\n [ 747, 799, 123, ..., 0, 0, 0],\n [1206, 1389, 3, ..., 0, 0, 0]])\n\nx_len: <torch.Size([10])>\ntensor([40, 31, 27, 19, 18, 17, 16, 16, 14, 4])\n\npad_len: <torch.Size([10])>\ntensor([144, 153, 157, 165, 166, 167, 168, 168, 170, 180])\n\npadded_vectorized_sent: <torch.Size([10, 184])>\ntensor([[ 2, 184, 248, ..., 0, 0, 0],\n [ 2, 344, 327, ..., 0, 0, 0],\n [ 2, 269, 52, ..., 0, 0, 0],\n ...,\n [ 2, 994, 1388, ..., 0, 0, 0],\n [ 2, 747, 799, ..., 0, 0, 0],\n [ 2, 1206, 1389, ..., 0, 0, 0]])\n\n"
]
],
[
[
"contiguous() is to arrange the tensor in a standard layout",
"_____no_output_____"
]
],
[
[
"a = torch.randn(3, 4, 5)\nb = a.permute(1, 2, 0)\nb_cont = b.contiguous()\na_cont = a.contiguous()\n# a has \"standard layout\" (also known as C layout in numpy) descending strides, and no memory gaps (stride(i-1) == size(i)*stride(i))\nprint (a.shape, a.stride(), a.data_ptr())\n# b has same storage as a (data_ptr), but has the strides and sizes swapped around\nprint (b.shape, b.stride(), b.data_ptr())\n# b_cont is in new storage, where it has been arranged in standard layout (which is \"contiguous\")\nprint (b_cont.shape, b_cont.stride(), b_cont.data_ptr())\n# a_cont is exactly as a, as a was contiguous all along\nprint (a_cont.shape, a_cont.stride(), a_cont.data_ptr())",
"torch.Size([3, 4, 5]) (20, 5, 1) 2130351979776\ntorch.Size([4, 5, 3]) (5, 1, 20) 2130351979776\ntorch.Size([4, 5, 3]) (15, 3, 1) 2130351986176\ntorch.Size([3, 4, 5]) (20, 5, 1) 2130351979776\n"
],
[
"class Generator(nn.Module):\n def __init__(self, vocab_size, embedding_size, hidden_size, num_layers, bidirectionary_gru=False):\n super(Generator, self).__init__()\n\n # Initialize the embedding layer with the \n # - size of input (i.e. no. of words in input vocab)\n # - no. of hidden nodes in the embedding layer\n self.embedding = nn.Embedding(vocab_size, embedding_size, padding_idx=0)\n \n self.bidirectionary = bidirectionary_gru\n \n # Initialize the GRU with the \n # - size of the input (i.e. embedding layer)\n # - size of the hidden layer \n self.gru = nn.GRU(\n input_size=embedding_size, \n hidden_size=hidden_size, \n num_layers=num_layers,\n bias=True, # default True\n batch_first=True, # if True, then the input and output tensors are provided as (batch, seq, feature), otherwise, (seq, batch, feature) will be used.\n dropout=0, # default 0\n bidirectional=bidirectionary_gru)\n \n # Initialize the \"classifier\" layer to map the RNN outputs\n # to the vocabulary. Remember we need to -1 because the \n # vectorized sentence we left out one token for both x and y:\n # - size of hidden_size of the GRU output.\n # - size of vocabulary\n self.classifier = nn.Linear(hidden_size * (2 if self.bidirectionary else 1), vocab_size)\n \n def forward(self, inputs, activate_by_softmax=False, initial_hidden_states=None):\n # vocab_size: V\n # embed_size: E\n # hidden_size: H\n # num_layers: L\n # num_directions: Dir\n # sequence_len: Seq = max_sent_len-1\n # batch_size: n\n \n # single shape: (, Seq) ~~> (Seq, V) ==> via x weights:(V, E) ==> (Seq, E)\n # batched shape: (n, Seq) ~~> (n, Seq, V) ==> via x weights:(V, E) ==> (n, Seq, E)\n embedded = self.embedding(inputs)\n \n # single\n # input => final GRU output shape, for each token in each sentence: (Seq, E) ==> (Seq, H*Dir)\n # initial => final hidden states shape, for each sentence as a whole: (L*Dir, H) ==> (L*Dir, H)\n #\n # batched\n # input => final GRU output shape, for each token in each sentence: (n, Seq, E) ==> (n, Seq, H*Dir)\n # initial => final hidden states shape, for each sentence as a whole: (L*Dir, n, H) ==> (L*Dir, n, H)\n gru_output, final_hidden_states = self.gru(embedded, initial_hidden_states)\n \n # Matrix manipulation magic.\n batch_size, sequence_len, directional_hidden_size = gru_output.shape\n \n # Technically, linear layer takes a 2-D matrix as input, so more manipulation...\n # single shape: (Seq, H*Dir) ==> (Seq, H*Dir)\n # batched shape: (n, Seq, H*Dir) ==> (n*Seq, H*Dir)\n classification_inputs = gru_output.contiguous().view(batch_size * sequence_len, directional_hidden_size)\n \n # Apply dropout.\n # if the data size is relatively small, the dropout rate can be higher. normally 0.1~0.8\n classification_inputs = F.dropout(classification_inputs, 0.5)\n \n # Put it through the classifier\n # single shape: (Seq, H*Dir) ==> via x weights:(H*Dir, V) ==> (Seq, V)\n # batched shape: (n*Seq, H*Dir) ==> via x weights:(H*Dir, V) ==> (n*Seq, V)\n output = self.classifier(classification_inputs)\n \n # reshape it to [batch_size x sequence_len x vocab_size]\n # single shape: (Seq, V) ==> via reshape ==> (Seq, V)\n # batched shape: (n*Seq, V) ==> via reshape ==> (n, Seq, V)\n output = output.view(batch_size, sequence_len, -1)\n \n # classification output shape: (n, Seq, V)\n # final hidden states shape, for each sentence as a whole: (L*Dir, n, H)\n return (F.softmax(output,dim=2), final_hidden_states) if activate_by_softmax else (output, final_hidden_states)\n \n",
"_____no_output_____"
],
[
"# Set the hidden_size of the GRU \nembed_size = 12\nhidden_size = 10\nnum_layers = 7\nbidirectional = True\n\n_encoder = Generator(len(kilgariff_data.vocab), embed_size, hidden_size, num_layers, bidirectionary_gru=bidirectional)",
"_____no_output_____"
],
[
"# Take a batch.\nbatch_size = 15\ndataloader = DataLoader(dataset=kilgariff_data, batch_size=batch_size, shuffle=True)\n\nbatch0 = next(iter(dataloader))\ninputs0, lengths0 = batch0['x'], batch0['x_len']\ntargets0 = batch0['y']",
"_____no_output_____"
],
[
"initial_hidden_states = torch.zeros(num_layers*(2 if bidirectional else 1), batch_size, hidden_size)\n\nprint('Input shape:\\t', inputs0.shape)\nprint(\"Vocab shape:\\t\", len(kilgariff_data.vocab))\nprint('Target shape:\\t', targets0.shape)\noutput0, hidden0 = _encoder(inputs0, initial_hidden_states=initial_hidden_states)\nprint('Hidden shape:\\t', hidden0.shape)\nprint('Output shape:\\t', output0.shape)",
"Input shape:\t torch.Size([15, 183])\nVocab shape:\t 1392\nTarget shape:\t torch.Size([15, 183])\nHidden shape:\t torch.Size([14, 15, 10])\nOutput shape:\t torch.Size([15, 183, 1392])\n"
],
[
"_, predicted_indices = torch.max(output0, dim=1)\nprint(predicted_indices.shape)\n",
"torch.Size([15, 1392])\n"
],
[
"device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n_hyper_para_names = ['embed_size', 'hidden_size', 'num_layers',\n 'loss_func', 'learning_rate', 'optimizer', 'batch_size']\nHyperparams = namedtuple('Hyperparams', _hyper_para_names)\n\n\nhyperparams = Hyperparams(embed_size=250, \n hidden_size=250, \n num_layers=1,\n loss_func=nn.CrossEntropyLoss,\n learning_rate=0.03, \n optimizer=optim.Adam, \n batch_size=245)\n\nhyperparams",
"_____no_output_____"
],
[
"# Training routine.\ndef train(num_epochs, dataloader, model, criterion, optimizer):\n losses = []\n plt.ion()\n for _e in range(num_epochs):\n for batch in tqdm(dataloader):\n # Zero gradient.\n optimizer.zero_grad()\n x = batch['x'].to(device)\n x_len = batch['x_len'].to(device)\n y = batch['y'].to(device)\n # Feed forward. \n output, hidden = model(x, activate_by_softmax=False)\n # Compute loss:\n # Shape of the `output` is [batch_size x sequence_len x vocab_size]\n # Shape of `y` is [batch_size x sequence_len]\n # CrossEntropyLoss expects `output` to be [batch_size x vocab_size x sequence_len]\n _, prediction = torch.max(output, dim=2)\n loss = criterion(output.permute(0, 2, 1), y)\n loss.backward()\n optimizer.step()\n losses.append(loss.float().data)\n\n clear_output(wait=True)\n plt.plot(losses)\n plt.pause(0.05)\n print(hidden.shape)\n\n\ndef initialize_data_model_optim_loss(hyperparams):\n # Initialize the dataset and dataloader.\n kilgariff_data = KilgariffDataset(tokenized_text)\n dataloader = DataLoader(dataset=kilgariff_data, \n batch_size=hyperparams.batch_size, \n shuffle=True)\n\n # Loss function.\n criterion = hyperparams.loss_func(ignore_index=kilgariff_data.vocab.token2id['<pad>'], \n reduction='mean')\n\n # Model.\n model = Generator(len(kilgariff_data.vocab), hyperparams.embed_size, \n hyperparams.hidden_size, hyperparams.num_layers).to(device)\n\n # Optimizer.\n optimizer = hyperparams.optimizer(model.parameters(), lr=hyperparams.learning_rate)\n \n return dataloader, model, optimizer, criterion",
"_____no_output_____"
],
[
"def generate_example(model, temperature=1.0, max_len=100, hidden_state=None):\n start_token, start_idx = '<s>', 2\n # Start state.\n inputs = torch.tensor(kilgariff_data.vocab.token2id[start_token]).unsqueeze(0).unsqueeze(0).to(device)\n\n sentence = [start_token]\n i = 0\n while i < max_len and sentence[-1] not in ['</s>', '<pad>']:\n i += 1\n \n embedded = model.embedding(inputs)\n output, hidden_state = model.gru(embedded, hidden_state)\n\n batch_size, sequence_len, hidden_size = output.shape\n output = output.contiguous().view(batch_size * sequence_len, hidden_size) \n output = model.classifier(output).view(batch_size, sequence_len, -1).squeeze(0)\n #_, prediction = torch.max(F.softmax(output, dim=2), dim=2)\n \n word_weights = output.div(temperature).exp().cpu()\n if len(word_weights.shape) > 1:\n word_weights = word_weights[-1] # Pick the last word. \n word_idx = torch.multinomial(word_weights, 1).view(-1)\n \n sentence.append(kilgariff_data.vocab[int(word_idx)])\n \n inputs = tensor([kilgariff_data.vocab.token2id[word] for word in sentence]).unsqueeze(0).to(device)\n print(' '.join(sentence))",
"_____no_output_____"
],
[
"hyperparams = Hyperparams(embed_size=200, hidden_size=250, num_layers=3,\n loss_func=nn.CrossEntropyLoss,\n learning_rate=0.03, optimizer=optim.Adam, batch_size=300)\n\ndataloader, model, optimizer, criterion = initialize_data_model_optim_loss(hyperparams)\n\ntrain(3, dataloader, model, criterion, optimizer)",
"_____no_output_____"
],
[
"for _ in range(10):\n generate_example(model)",
"<s> the problem is this . </s>\n<s> for a vast number of third phenomena x , the null hypothesis that the same population ; and consequently , ( 2 ) that the deviation in frequency of the target verb and its semantic neighbour using a linear method based on the quantity of evidence available for each . </s>\n<s> the χ2 distribution is a theoretical construct . </s>\n<s> similar strategies are used by , and a similar critique is applicable to , leech and fallon ( 1992 ) ( again , for comparing lob and brown ) , ray- language is never , ever , ever , random 271 son , leech , and hodges ( 1997 ) for comparing the conversation of dif- ferent social groups , and rayson and garside ( 2000 ) for contrasting the language is never , ever , ever , random 271 son , leech , and hodges ( 1997 ) for comparing the conversation of dif- ferent social groups , and\n<s> keywords : 쎲쎲쎲 1 . </s>\n<s> 3 . </s>\n<s> thus some of the prob- ability mass contributing to the 1/n or 2/n mles should have been put aside for the words ( bigrams etc . ) </s>\n<s> as the mathematics of the random is well under- stood , we can compute the likelihood of the null hypothesis given the data . </s>\n<s> however , their methods are inevitably noisy , suffering , for example , from just those parser errors that the whole process is designed to address , and they do not wish to accept any scf for which there is any evidence as the mathematics of the random is well under- stood , we can compute the likelihood of the null hypothesis given the data . </s>\n<s> language is never , ever , ever , random 269 ( |o ⫺ e| ⫺ 0.5 ) 2 /e is then 0.5.5 the hypothesis can , therefore , be couched as : are the error terms systematically greater than 0.5 ? </s>\n"
],
[
"import json\ntorch.save(model.state_dict(), 'gru-model.pth')\n\nhyperparams_str = Hyperparams(embed_size=250, hidden_size=250, num_layers=1,\n loss_func='nn.CrossEntropyLoss',\n learning_rate=0.03, optimizer='optim.Adam', batch_size=250)\n\nwith open('gru-model.json', 'w') as fout:\n json.dump(dict(hyperparams_str._asdict()), fout)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ac31fbd9ff5196ef9dbf0355b3b2a1100b700b | 5,035 | ipynb | Jupyter Notebook | Tarea26.ipynb | Ed-10/Daa_2021_1 | 6e0bd414851b24cc1ec371aaebee1ed32d94ed48 | [
"MIT"
] | null | null | null | Tarea26.ipynb | Ed-10/Daa_2021_1 | 6e0bd414851b24cc1ec371aaebee1ed32d94ed48 | [
"MIT"
] | null | null | null | Tarea26.ipynb | Ed-10/Daa_2021_1 | 6e0bd414851b24cc1ec371aaebee1ed32d94ed48 | [
"MIT"
] | null | null | null | 34.486301 | 222 | 0.471897 | [
[
[
"<a href=\"https://colab.research.google.com/github/Ed-10/Daa_2021_1/blob/master/Tarea26.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"class NodoArbol:\n def __init__(self, dato, hijo_izq = None, hijo_der = None):\n self.dato = dato\n self.left = hijo_izq\n self.right = hijo_der",
"_____no_output_____"
],
[
"class BinarySearchTree:\n def __init__(self):\n self.__root = None\n \n def insert(self, value):\n if self.__root == None:\n self.__root = NodoArbol(value, None, None)\n else:\n #Preguntar si value es menor que root, de ser el caso\n #Insertar a la izq. PERO puede ser el caso que el sub arbol\n #Izq ya tenga muchos elementos\n self.__insert_nodo__(self.__root, value)\n\n def __insert_nodo__(self, nodo, value):\n if nodo.dato == value:\n pass\n elif value < nodo.dato: #true va a la izq\n if nodo.left == None: #Si hay espacio en la izq, ahi va\n nodo.left = NodoArbol(value, None, None) #Insertamos el nodo\n else:\n self.__insert_nodo__(nodo.left, value) #Buscar en sub arbol izq\n else:\n if nodo.right == None:\n nodo.right = NodoArbol (value, None, None)\n else:\n self.__insert_nodo__ (nodo.right, vlue) #biscar en sub arbol de\n\n def buscar (self, value):\n if self.__root == None:\n return None\n else:\n #Haremos busqueda recursiva\n return self.__busca_nodo(self.__root, value)\n\n def __busca_nodo(self, nodo, value):\n if nodo == None:\n return None\n elif nodo.dato == value:\n return nodo.dato\n elif value < nodo.dato:\n return self.__busca_nodo(nodo.left, value)\n else:\n return self.__busca_nodo(nodo.right, value)\n \n def transversal (self, format = \"inorden\"):\n if format == \"inorden\":\n self.__recorrido_in(self.__root)\n elif format == \"preorden\":\n self.__recorrido_pre(self.__root)\n elif format == \"posorden\":\n self.__recorrido_pos(self.__root)\n else:\n print(\"Formato de recorrido no valido\")\n \n def __recorrido_pre(self, nodo):\n if nodo != None:\n print(nodo.dato, end = \",\")\n self.__recorrido_pre(nodo.left)\n self.__recorrido_pre(nodo.right)\n\n def __recorrido_in(self, nodo):\n if nodo != None: \n self.__recorrido_pre(nodo.left)\n print(nodo.dato, end = \",\")\n self.__recorrido_pre(nodo.right)\n\n def __recorrido_pos(self, nodo):\n if nodo != None: \n self.__recorrido_pre(nodo.left)\n self.__recorrido_pre(nodo.right)\n print(nodo.dato, end = \",\")",
"_____no_output_____"
],
[
"bst = BinarySearchTree()\nbst.insert(50)\nbst.insert(30)\nbst.insert(20)\nres = bst.buscar(30) #true o false\nprint(\"Dato: \" + str(res))\nprint(bst.buscar(40))\nprint(\"Recorrido pre:\")\nbst.transversal(format = \"preorden\")\nprint(\"\\n Recorrido in:\")\nbst.transversal(format = \"inorden\")\nprint(\"\\n Recorrido pos:\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7ac37c5f97e782a4e11102e88279ffbe383e9de | 48,175 | ipynb | Jupyter Notebook | Tutorial-RK_Butcher_Table_Dictionary.ipynb | stevenrbrandt/nrpytutorial | 219af363f810cc46ea8955a9d28cf075f2252582 | [
"BSD-2-Clause"
] | 66 | 2018-06-26T22:18:09.000Z | 2022-02-09T21:12:33.000Z | Tutorial-RK_Butcher_Table_Dictionary.ipynb | stevenrbrandt/nrpytutorial | 219af363f810cc46ea8955a9d28cf075f2252582 | [
"BSD-2-Clause"
] | 14 | 2020-02-13T16:09:29.000Z | 2021-11-12T14:59:59.000Z | Tutorial-RK_Butcher_Table_Dictionary.ipynb | stevenrbrandt/nrpytutorial | 219af363f810cc46ea8955a9d28cf075f2252582 | [
"BSD-2-Clause"
] | 30 | 2019-01-09T09:57:51.000Z | 2022-03-08T18:45:08.000Z | 45.234742 | 436 | 0.55944 | [
[
[
"<script async src=\"https://www.googletagmanager.com/gtag/js?id=UA-59152712-8\"></script>\n<script>\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n\n gtag('config', 'UA-59152712-8');\n</script>\n\n# Explicit Runge Kutta methods and their Butcher tables\n## Authors: Brandon Clark & Zach Etienne\n\n## This tutorial notebook stores known explicit Runge Kutta-like methods as Butcher tables in a Python dictionary format. \n\n**Notebook Status:** <font color='green'><b> Validated </b></font>\n\n**Validation Notes:** This tutorial notebook has been confirmed to be **self-consistent with its corresponding NRPy+ module**, as documented [below](#code_validation). In addition, each of these Butcher tables has been verified to yield an RK method to the expected local truncation error in a challenging battery of ODE tests, in the [RK Butcher Table Validation tutorial notebook](Tutorial-RK_Butcher_Table_Validation.ipynb).\n\n### NRPy+ Source Code for this module: [MoLtimestepping/RK_Butcher_Table_Dictionary.py](../edit/MoLtimestepping/RK_Butcher_Table_Dictionary.py)\n\n## Introduction:\n\nThe family of explicit [Runge Kutta](https://en.wikipedia.org/w/index.php?title=Runge%E2%80%93Kutta_methods&oldid=898536315)-like methods are commonly used when numerically solving ordinary differential equation (ODE) initial value problems of the form\n\n$$ y'(t) = f(y,t),\\ \\ \\ y(t_0)=y_0.$$\n\nThese methods can be extended to solve time-dependent partial differential equations (PDEs) via the [Method of Lines](https://en.wikipedia.org/w/index.php?title=Method_of_lines&oldid=855390257). In the Method of Lines, the above ODE can be generalized to $N$ coupled ODEs, all written as first-order-in-time PDEs of the form\n\n$$ \\partial_{t}\\mathbf{u}(t,x,y,u_1,u_2,u_3,...)=\\mathbf{f}(t,x,y,...,u_1,u_{1,x},...),$$\n\nwhere $\\mathbf{u}$ and $\\mathbf{f}$ are vectors. The spatial partial derivatives of components of $\\mathbf{u}$, e.g., $u_{1,x}$, may be computed using approximate numerical differentiation, like finite differences.\n\nAs any explicit Runge-Kutta method has its own unique local truncation error, can in principle be used to solve time-dependent PDEs using the Method of Lines, and may be stable under different Courant-Friedrichs-Lewy (CFL) conditions, it is useful to have multiple methods at one's disposal. **This module provides a number of such methods.**\n\nMore details about the Method of Lines is discussed further in the [Tutorial-RK_Butcher_Table_Generating_C_Code](Tutorial-RK_Butcher_Table_Generating_C_Code.ipynb) module where we generate the C code to implement the Method of Lines, and additional description can be found in the [Numerically Solving the Scalar Wave Equation: A Complete C Code](Tutorial-Start_to_Finish-ScalarWave.ipynb) NRPy+ tutorial notebook.",
"_____no_output_____"
],
[
"<a id='toc'></a>\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis notebook is organized as follows\n\n1. [Step 1](#initializenrpy): Initialize needed Python modules\n1. [Step 2](#introbutcher): The Family of Explicit Runge-Kutta-Like Schemes (Butcher Tables)\n 1. [Step 2a](#codebutcher): Generating a Dictionary of Butcher Tables for Explicit Runge Kutta Techniques \n 1. [Step 2.a.i](#euler): Euler's Method\n 1. [Step 2.a.ii](#rktwoheun): RK2 Heun's Method\n 1. [Step 2.a.iii](#rk2mp): RK2 Midpoint Method\n 1. [Step 2.a.iv](#rk2ralston): RK2 Ralston's Method\n 1. [Step 2.a.v](#rk3): Kutta's Third-order Method\n 1. [Step 2.a.vi.](#rk3heun): RK3 Heun's Method\n 1. [Step 2.a.vii](#rk3ralston): RK3 Ralston's Method\n 1. [Step 2.a.viii](#ssprk3): Strong Stability Preserving Runge-Kutta (SSPRK3) Method\n 1. [Step 2.a.ix](#rkfour): Classic RK4 Method\n 1. [Step 2.a.x](#dp5): RK5 Dormand-Prince Method\n 1. [Step 2.a.xi](#dp5alt): RK5 Dormand-Prince Method Alternative\n 1. [Step 2.a.xii](#ck5): RK5 Cash-Karp Method\n 1. [Step 2.a.xiii](#dp6): RK6 Dormand-Prince Method\n 1. [Step 2.a.xiv](#l6): RK6 Luther Method\n 1. [Step 2.a.xv](#dp8): RK8 Dormand-Prince Method\n1. [Step 3](#code_validation): Code Validation against `MoLtimestepping.RK_Butcher_Table_Dictionary` NRPy+ module\n1. [Step 4](#latex_pdf_output): Output this notebook to $\\LaTeX$-formatted PDF file",
"_____no_output_____"
],
[
"<a id='initializenrpy'></a>\n\n# Step 1: Initialize needed Python modules [Back to [top](#toc)\\]\n$$\\label{initializenrpy}$$\n\nLet's start by importing all the needed modules from Python:",
"_____no_output_____"
]
],
[
[
"# Step 1: Initialize needed Python modules\nimport sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends",
"_____no_output_____"
]
],
[
[
"<a id='introbutcher'></a>\n\n# Step 2: The Family of Explicit Runge-Kutta-Like Schemes (Butcher Tables) [Back to [top](#toc)\\]\n$$\\label{introbutcher}$$\n\nIn general, a predictor-corrector method performs an estimate timestep from $n$ to $n+1$, using e.g., a Runge Kutta method, to get a prediction of the solution at timestep $n+1$. This is the \"predictor\" step. Then it uses this prediction to perform another, \"corrector\" step, designed to increase the accuracy of the solution.\n\nLet us focus on the ordinary differential equation (ODE)\n\n$$ y'(t) = f(y,t), $$\n\nwhich acts as an analogue for a generic PDE $\\partial_{t}u(t,x,y,...)=f(t,x,y,...,u,u_x,...)$.\n\nThe general family of Runge Kutta \"explicit\" timestepping methods are implemented using the following scheme:\n\n$$y_{n+1} = y_n + \\sum_{i=1}^s b_ik_i $$\n\nwhere \n\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n) \\\\\nk_2 &= \\Delta tf(y_n + [a_{21}k_1], t_n + c_2\\Delta t) \\\\\nk_3 &= \\Delta tf(y_n +[a_{31}k_1 + a_{32}k_2], t_n + c_3\\Delta t) \\\\\n& \\ \\ \\vdots \\\\\nk_s &= \\Delta tf(y_n +[a_{s1}k_1 + a_{s2}k_2 + \\cdots + a_{s, s-1}k_{s-1}], t_n + c_s\\Delta t)\n\\end{align}\n\nNote $s$ is the number of right-hand side evaluations necessary for any given method, i.e., for RK2 $s=2$ and for RK4 $s=4$, and for RK6 $s=7$. These schemes are often written in the form of a so-called \"Butcher tableau\". or \"Butcher table\":\n\n$$\\begin{array}{c|ccccc}\n 0 & \\\\\n c_2 & a_{21} & \\\\\n c_3 & a_{31} & a_{32} & \\\\\n \\vdots & \\vdots & & \\ddots \\\\\n c_s & a_{s_1} & a_{s2} & \\cdots & a_{s,s-1} \\\\ \\hline \n & b_1 & b_2 & \\cdots & b_{s-1} & b_s\n\\end{array} $$\n\nAs an example, the \"classic\" fourth-order Runge Kutta (RK4) method obtains the solution $y(t)$ to the single-variable ODE $y'(t) = f(y(t),t)$ at time $t_{n+1}$ from $t_n$ via:\n\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + \\frac{1}{2}k_1, t_n + \\frac{\\Delta t}{2}), \\\\\nk_3 &= \\Delta tf(y_n + \\frac{1}{2}k_2, t_n + \\frac{\\Delta t}{2}), \\\\\nk_4 &= \\Delta tf(y_n + k_3, t_n + \\Delta t), \\\\\ny_{n+1} &= y_n + \\frac{1}{6}(k_1 + 2k_2 + 2k_3 + k_4) + \\mathcal{O}\\big((\\Delta t)^5\\big).\n\\end{align}\n\nIts corresponding Butcher table is constructed as follows:\n\n$$\\begin{array}{c|cccc}\n 0 & \\\\\n 1/2 & 1/2 & \\\\ \n 1/2 & 0 & 1/2 & \\\\\n 1 & 0 & 0 & 1 & \\\\ \\hline\n & 1/6 & 1/3 & 1/3 & 1/6\n\\end{array} $$\n\n\nThis is one example of many explicit [Runge Kutta methods](https://en.wikipedia.org/w/index.php?title=List_of_Runge%E2%80%93Kutta_methods&oldid=896594269). Throughout the following sections we will highlight different Runge Kutta schemes and their Butcher tables from the first-order Euler's method up to and including an eighth-order method.",
"_____no_output_____"
],
[
"<a id='codebutcher'></a>\n\n## Step 2.a: Generating a Dictionary of Butcher Tables for Explicit Runge Kutta Techniques [Back to [top](#toc)\\]\n$$\\label{codebutcher}$$\n\nWe can store all of the Butcher tables in Python's **Dictionary** format using the curly brackets {} and 'key':value pairs. The 'key' will be the *name* of the Runge Kutta method and the value will be the Butcher table itself stored as a list of lists. The convergence order for each Runge Kutta method is also stored. We will construct the dictionary `Butcher_dict` one Butcher table at a time in the following sections.",
"_____no_output_____"
]
],
[
[
"# Step 2a: Generating a Dictionary of Butcher Tables for Explicit Runge Kutta Techniques\n\n# Initialize the dictionary Butcher_dict\nButcher_dict = {}",
"_____no_output_____"
]
],
[
[
"<a id='euler'></a>\n\n### Step 2.a.i: Euler's Method [Back to [top](#toc)\\]\n$$\\label{euler}$$\n\n[Forward Euler's method](https://en.wikipedia.org/w/index.php?title=Euler_method&oldid=896152463) is a first order Runge Kutta method. Euler's method obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n$$y_{n+1} = y_{n} + \\Delta tf(y_{n}, t_{n})$$\nwith the trivial corresponding Butcher table \n$$\\begin{array}{c|c}\n0 & \\\\ \\hline\n & 1 \n\\end{array}$$\n",
"_____no_output_____"
]
],
[
[
"# Step 2.a.i: Euler's Method\n\nButcher_dict['Euler'] = (\n[[sp.sympify(0)],\n[\"\", sp.sympify(1)]]\n, 1)",
"_____no_output_____"
]
],
[
[
"<a id='rktwoheun'></a>\n\n### Step 2.a.ii: RK2 Heun's Method [Back to [top](#toc)\\]\n$$\\label{rktwoheun}$$\n\n[Heun's method](https://en.wikipedia.org/w/index.php?title=Heun%27s_method&oldid=866896936) is a second-order RK method that obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + k_1, t_n + \\Delta t), \\\\\ny_{n+1} &= y_n + \\frac{1}{2}(k_1 + k_2) + \\mathcal{O}\\big((\\Delta t)^3\\big).\n\\end{align}\nwith corresponding Butcher table\n$$\\begin{array}{c|cc}\n 0 & \\\\\n 1 & 1 & \\\\ \\hline\n & 1/2 & 1/2\n\\end{array} $$\n",
"_____no_output_____"
]
],
[
[
"# Step 2.a.ii: RK2 Heun's Method\n\nButcher_dict['RK2 Heun'] = (\n[[sp.sympify(0)],\n[sp.sympify(1), sp.sympify(1)],\n[\"\", sp.Rational(1,2), sp.Rational(1,2)]]\n, 2)",
"_____no_output_____"
]
],
[
[
"<a id='rk2mp'></a>\n\n### Step 2.a.iii: RK2 Midpoint Method [Back to [top](#toc)\\]\n$$\\label{rk2mp}$$\n\n[Midpoint method](https://en.wikipedia.org/w/index.php?title=Midpoint_method&oldid=886630580) is a second-order RK method that obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + \\frac{2}{3}k_1, t_n + \\frac{2}{3}\\Delta t), \\\\\ny_{n+1} &= y_n + \\frac{1}{2}k_2 + \\mathcal{O}\\big((\\Delta t)^3\\big).\n\\end{align}\nwith corresponding Butcher table\n$$\\begin{array}{c|cc}\n 0 & \\\\\n 1/2 & 1/2 & \\\\ \\hline\n & 0 & 1\n\\end{array} $$\n",
"_____no_output_____"
]
],
[
[
"# Step 2.a.iii: RK2 Midpoint (MP) Method\n\nButcher_dict['RK2 MP'] = (\n[[sp.sympify(0)],\n[sp.Rational(1,2), sp.Rational(1,2)],\n[\"\", sp.sympify(0), sp.sympify(1)]]\n, 2)",
"_____no_output_____"
]
],
[
[
"<a id='rk2ralston'></a>\n\n### Step 2.a.iv: RK2 Ralston's Method [Back to [top](#toc)\\]\n$$\\label{rk2ralston}$$\n\nRalston's method (see [Ralston (1962)](https://www.ams.org/journals/mcom/1962-16-080/S0025-5718-1962-0150954-0/S0025-5718-1962-0150954-0.pdf), is a second-order RK method that obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + \\frac{1}{2}k_1, t_n + \\frac{1}{2}\\Delta t), \\\\\ny_{n+1} &= y_n + \\frac{1}{4}k_1 + \\frac{3}{4}k_2 + \\mathcal{O}\\big((\\Delta t)^3\\big).\n\\end{align}\nwith corresponding Butcher table\n$$\\begin{array}{c|cc}\n 0 & \\\\\n 2/3 & 2/3 & \\\\ \\hline\n & 1/4 & 3/4\n\\end{array} $$",
"_____no_output_____"
]
],
[
[
"# Step 2.a.iv: RK2 Ralston's Method\n\nButcher_dict['RK2 Ralston'] = (\n[[sp.sympify(0)],\n[sp.Rational(2,3), sp.Rational(2,3)],\n[\"\", sp.Rational(1,4), sp.Rational(3,4)]]\n, 2)\n",
"_____no_output_____"
]
],
[
[
"<a id='rk3'></a>\n\n### Step 2.a.v: Kutta's Third-order Method [Back to [top](#toc)\\]\n$$\\label{rk3}$$\n\n[Kutta's third-order method](https://en.wikipedia.org/w/index.php?title=List_of_Runge%E2%80%93Kutta_methods&oldid=896594269) obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + \\frac{1}{2}k_1, t_n + \\frac{1}{2}\\Delta t), \\\\\nk_3 &= \\Delta tf(y_n - k_1 + 2k_2, t_n + \\Delta t) \\\\\ny_{n+1} &= y_n + \\frac{1}{6}k_1 + \\frac{2}{3}k_2 + \\frac{1}{6}k_3 + \\mathcal{O}\\big((\\Delta t)^4\\big).\n\\end{align}\nwith corresponding Butcher table\n\\begin{array}{c|ccc}\n 0 & \\\\\n 1/2 & 1/2 & \\\\\n 1 & -1 & 2 & \\\\ \\hline\n & 1/6 & 2/3 & 1/6\n\\end{array}",
"_____no_output_____"
]
],
[
[
"# Step 2.a.v: Kutta's Third-order Method\n\nButcher_dict['RK3'] = (\n[[sp.sympify(0)],\n[sp.Rational(1,2), sp.Rational(1,2)],\n[sp.sympify(1), sp.sympify(-1), sp.sympify(2)],\n[\"\", sp.Rational(1,6), sp.Rational(2,3), sp.Rational(1,6)]]\n, 3)",
"_____no_output_____"
]
],
[
[
"<a id='rk3heun'></a>\n\n### Step 2.a.vi: RK3 Heun's Method [Back to [top](#toc)\\]\n$$\\label{rk3heun}$$\n\n[Heun's third-order method](https://en.wikipedia.org/w/index.php?title=List_of_Runge%E2%80%93Kutta_methods&oldid=896594269) obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + \\frac{1}{3}k_1, t_n + \\frac{1}{3}\\Delta t), \\\\\nk_3 &= \\Delta tf(y_n + \\frac{2}{3}k_2, t_n + \\frac{2}{3}\\Delta t) \\\\\ny_{n+1} &= y_n + \\frac{1}{4}k_1 + \\frac{3}{4}k_3 + \\mathcal{O}\\big((\\Delta t)^4\\big).\n\\end{align}\n\nwith corresponding Butcher table\n\n\\begin{array}{c|ccc}\n 0 & \\\\\n 1/3 & 1/3 & \\\\\n 2/3 & 0 & 2/3 & \\\\ \\hline\n & 1/4 & 0 & 3/4\n\\end{array}\n",
"_____no_output_____"
]
],
[
[
"# Step 2.a.vi: RK3 Heun's Method\n\nButcher_dict['RK3 Heun'] = (\n[[sp.sympify(0)],\n[sp.Rational(1,3), sp.Rational(1,3)],\n[sp.Rational(2,3), sp.sympify(0), sp.Rational(2,3)],\n[\"\", sp.Rational(1,4), sp.sympify(0), sp.Rational(3,4)]]\n, 3)",
"_____no_output_____"
]
],
[
[
"<a id='rk3ralston'></a>\n\n### Step 2.a.vii: RK3 Ralton's Method [Back to [top](#toc)\\]\n$$\\label{rk3ralston}$$\n\nRalston's third-order method (see [Ralston (1962)](https://www.ams.org/journals/mcom/1962-16-080/S0025-5718-1962-0150954-0/S0025-5718-1962-0150954-0.pdf), obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + \\frac{1}{2}k_1, t_n + \\frac{1}{2}\\Delta t), \\\\\nk_3 &= \\Delta tf(y_n + \\frac{3}{4}k_2, t_n + \\frac{3}{4}\\Delta t) \\\\\ny_{n+1} &= y_n + \\frac{2}{9}k_1 + \\frac{1}{3}k_2 + \\frac{4}{9}k_3 + \\mathcal{O}\\big((\\Delta t)^4\\big).\n\\end{align}\n\nwith corresponding Butcher table\n\n\\begin{array}{c|ccc}\n 0 & \\\\\n 1/2 & 1/2 & \\\\\n 3/4 & 0 & 3/4 & \\\\ \\hline\n & 2/9 & 1/3 & 4/9\n\\end{array}",
"_____no_output_____"
]
],
[
[
"# Step 2.a.vii: RK3 Ralton's Method\n\nButcher_dict['RK3 Ralston'] = (\n[[0],\n[sp.Rational(1,2), sp.Rational(1,2)],\n[sp.Rational(3,4), sp.sympify(0), sp.Rational(3,4)],\n[\"\", sp.Rational(2,9), sp.Rational(1,3), sp.Rational(4,9)]]\n, 3)",
"_____no_output_____"
]
],
[
[
"<a id='ssprk3'></a>\n\n### Step 2.a.viii: Strong Stability Preserving Runge-Kutta (SSPRK3) Method [Back to [top](#toc)\\]\n$\\label{ssprk3}$\n\nThe [Strong Stability Preserving Runge-Kutta (SSPRK3)](https://en.wikipedia.org/wiki/List_of_Runge%E2%80%93Kutta_methods#Kutta's_third-order_method) method obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + k_1, t_n + \\Delta t), \\\\\nk_3 &= \\Delta tf(y_n + \\frac{1}{4}k_1 + \\frac{1}{4}k_2, t_n + \\frac{1}{2}\\Delta t) \\\\\ny_{n+1} &= y_n + \\frac{1}{6}k_1 + \\frac{1}{6}k_2 + \\frac{2}{3}k_3 + \\mathcal{O}\\big((\\Delta t)^4\\big).\n\\end{align}\n\nwith corresponding Butcher table\n\n\\begin{array}{c|ccc}\n 0 & \\\\\n 1 & 1 & \\\\\n 1/2 & 1/4 & 1/4 & \\\\ \\hline\n & 1/6 & 1/6 & 2/3\n\\end{array}\n",
"_____no_output_____"
]
],
[
[
"# Step 2.a.viii: Strong Stability Preserving Runge-Kutta (SSPRK3) Method\n\nButcher_dict['SSPRK3'] = (\n[[0],\n[sp.sympify(1), sp.sympify(1)],\n[sp.Rational(1,2), sp.Rational(1,4), sp.Rational(1,4)],\n[\"\", sp.Rational(1,6), sp.Rational(1,6), sp.Rational(2,3)]]\n, 3)",
"_____no_output_____"
]
],
[
[
"<a id='rkfour'></a>\n\n### Step 2.a.ix: Classic RK4 Method [Back to [top](#toc)\\]\n$$\\label{rkfour}$$\n\nThe [classic RK4 method](https://en.wikipedia.org/w/index.php?title=Runge%E2%80%93Kutta_methods&oldid=894771467) obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\n\n\\begin{align}\nk_1 &= \\Delta tf(y_n, t_n), \\\\\nk_2 &= \\Delta tf(y_n + \\frac{1}{2}k_1, t_n + \\frac{\\Delta t}{2}), \\\\\nk_3 &= \\Delta tf(y_n + \\frac{1}{2}k_2, t_n + \\frac{\\Delta t}{2}), \\\\\nk_4 &= \\Delta tf(y_n + k_3, t_n + \\Delta t), \\\\\ny_{n+1} &= y_n + \\frac{1}{6}(k_1 + 2k_2 + 2k_3 + k_4) + \\mathcal{O}\\big((\\Delta t)^5\\big).\n\\end{align}\n\nwith corresponding Butcher table\n\n$$\\begin{array}{c|cccc}\n 0 & \\\\\n 1/2 & 1/2 & \\\\ \n 1/2 & 0 & 1/2 & \\\\\n 1 & 0 & 0 & 1 & \\\\ \\hline\n & 1/6 & 1/3 & 1/3 & 1/6\n\\end{array} $$",
"_____no_output_____"
]
],
[
[
"# Step 2.a.vix: Classic RK4 Method\n\nButcher_dict['RK4'] = (\n[[sp.sympify(0)],\n[sp.Rational(1,2), sp.Rational(1,2)],\n[sp.Rational(1,2), sp.sympify(0), sp.Rational(1,2)],\n[sp.sympify(1), sp.sympify(0), sp.sympify(0), sp.sympify(1)],\n[\"\", sp.Rational(1,6), sp.Rational(1,3), sp.Rational(1,3), sp.Rational(1,6)]]\n, 4)",
"_____no_output_____"
]
],
[
[
"<a id='dp5'></a>\n\n### Step 2.a.x: RK5 Dormand-Prince Method [Back to [top](#toc)\\]\n$$\\label{dp5}$$\n\nThe fifth-order Dormand-Prince (DP) method from the RK5(4) family (see [Dormand, J. R.; Prince, P. J. (1980)](https://www.sciencedirect.com/science/article/pii/0771050X80900133?via%3Dihub)) Butcher table is:\n\n$$\\begin{array}{c|ccccccc}\n 0 & \\\\\n \\frac{1}{5} & \\frac{1}{5} & \\\\ \n \\frac{3}{10} & \\frac{3}{40} & \\frac{9}{40} & \\\\\n \\frac{4}{5} & \\frac{44}{45} & \\frac{-56}{15} & \\frac{32}{9} & \\\\ \n \\frac{8}{9} & \\frac{19372}{6561} & \\frac{−25360}{2187} & \\frac{64448}{6561} & \\frac{−212}{729} & \\\\\n 1 & \\frac{9017}{3168} & \\frac{−355}{33} & \\frac{46732}{5247} & \\frac{49}{176} & \\frac{−5103}{18656} & \\\\\n 1 & \\frac{35}{384} & 0 & \\frac{500}{1113} & \\frac{125}{192} & \\frac{−2187}{6784} & \\frac{11}{84} & \\\\ \\hline\n & \\frac{35}{384} & 0 & \\frac{500}{1113} & \\frac{125}{192} & \\frac{−2187}{6784} & \\frac{11}{84} & 0\n\\end{array} $$",
"_____no_output_____"
]
],
[
[
"# Step 2.a.x: RK5 Dormand-Prince Method\n\nButcher_dict['DP5'] = (\n[[0],\n[sp.Rational(1,5), sp.Rational(1,5)],\n[sp.Rational(3,10),sp.Rational(3,40), sp.Rational(9,40)],\n[sp.Rational(4,5), sp.Rational(44,45), sp.Rational(-56,15), sp.Rational(32,9)],\n[sp.Rational(8,9), sp.Rational(19372,6561), sp.Rational(-25360,2187), sp.Rational(64448,6561), sp.Rational(-212,729)],\n[sp.sympify(1), sp.Rational(9017,3168), sp.Rational(-355,33), sp.Rational(46732,5247), sp.Rational(49,176), sp.Rational(-5103,18656)],\n[sp.sympify(1), sp.Rational(35,384), sp.sympify(0), sp.Rational(500,1113), sp.Rational(125,192), sp.Rational(-2187,6784), sp.Rational(11,84)],\n[\"\", sp.Rational(35,384), sp.sympify(0), sp.Rational(500,1113), sp.Rational(125,192), sp.Rational(-2187,6784), sp.Rational(11,84), sp.sympify(0)]]\n, 5)",
"_____no_output_____"
]
],
[
[
"<a id='dp5alt'></a>\n\n### Step 2.a.xi: RK5 Dormand-Prince Method Alternative [Back to [top](#toc)\\]\n$$\\label{dp5alt}$$\n\nThe fifth-order Dormand-Prince (DP) method from the RK6(5) family (see [Dormand, J. R.; Prince, P. J. (1981)](https://www.sciencedirect.com/science/article/pii/0771050X81900103)) Butcher table is:\n\n$$\\begin{array}{c|ccccccc}\n 0 & \\\\\n \\frac{1}{10} & \\frac{1}{10} & \\\\\n \\frac{2}{9} & \\frac{-2}{81} & \\frac{20}{81} & \\\\\n \\frac{3}{7} & \\frac{615}{1372} & \\frac{-270}{343} & \\frac{1053}{1372} & \\\\\n \\frac{3}{5} & \\frac{3243}{5500} & \\frac{-54}{55} & \\frac{50949}{71500} & \\frac{4998}{17875} & \\\\\n \\frac{4}{5} & \\frac{-26492}{37125} & \\frac{72}{55} & \\frac{2808}{23375} & \\frac{-24206}{37125} & \\frac{338}{459} & \\\\\n 1 & \\frac{5561}{2376} & \\frac{-35}{11} & \\frac{-24117}{31603} & \\frac{899983}{200772} & \\frac{-5225}{1836} & \\frac{3925}{4056} & \\\\ \\hline\n & \\frac{821}{10800} & 0 & \\frac{19683}{71825} & \\frac{175273}{912600} & \\frac{395}{3672} & \\frac{785}{2704} & \\frac{3}{50}\n\\end{array}$$",
"_____no_output_____"
]
],
[
[
"# Step 2.a.xi: RK5 Dormand-Prince Method Alternative\n\nButcher_dict['DP5alt'] = (\n[[0],\n[sp.Rational(1,10), sp.Rational(1,10)],\n[sp.Rational(2,9), sp.Rational(-2, 81), sp.Rational(20, 81)],\n[sp.Rational(3,7), sp.Rational(615, 1372), sp.Rational(-270, 343), sp.Rational(1053, 1372)],\n[sp.Rational(3,5), sp.Rational(3243, 5500), sp.Rational(-54, 55), sp.Rational(50949, 71500), sp.Rational(4998, 17875)],\n[sp.Rational(4, 5), sp.Rational(-26492, 37125), sp.Rational(72, 55), sp.Rational(2808, 23375), sp.Rational(-24206, 37125), sp.Rational(338, 459)],\n[sp.sympify(1), sp.Rational(5561, 2376), sp.Rational(-35, 11), sp.Rational(-24117, 31603), sp.Rational(899983, 200772), sp.Rational(-5225, 1836), sp.Rational(3925, 4056)],\n[\"\", sp.Rational(821, 10800), sp.sympify(0), sp.Rational(19683, 71825), sp.Rational(175273, 912600), sp.Rational(395, 3672), sp.Rational(785, 2704), sp.Rational(3, 50)]]\n, 5)",
"_____no_output_____"
]
],
[
[
"<a id='ck5'></a>\n\n### Step 2.a.xii: RK5 Cash-Karp Method [Back to [top](#toc)\\]\n$$\\label{ck5}$$\n\nThe fifth-order Cash-Karp Method (see [J. R. Cash, A. H. Karp. (1980)](https://dl.acm.org/citation.cfm?doid=79505.79507)) Butcher table is:\n\n$$\\begin{array}{c|cccccc}\n 0 & \\\\ \n\t\\frac{1}{5} & \\frac{1}{5} & \\\\ \n\t\\frac{3}{10} & \\frac{3}{40} & \\frac{9}{40} & \\\\ \n\t\\frac{3}{5} & \\frac{3}{10} & \\frac{−9}{10} & \\frac{6}{5} & \\\\ \n\t1 & \\frac{−11}{54} & \\frac{5}{2} & \\frac{−70}{27} & \\frac{35}{27} & \\\\ \n\t\\frac{7}{8} & \\frac{1631}{55296} & \\frac{175}{512} & \\frac{575}{13824} & \\frac{44275}{110592} & \\frac{253}{4096} & \\\\ \\hline\n\t & \\frac{37}{378} & 0 & \\frac{250}{621} & \\frac{125}{594} & 0 & \\frac{512}{1771} \n\\end{array}$$\n\n\n",
"_____no_output_____"
]
],
[
[
"# Step 2.a.xii: RK5 Cash-Karp Method\n\nButcher_dict['CK5'] = (\n[[0],\n[sp.Rational(1,5), sp.Rational(1,5)],\n[sp.Rational(3,10),sp.Rational(3,40), sp.Rational(9,40)],\n[sp.Rational(3,5), sp.Rational(3,10), sp.Rational(-9,10), sp.Rational(6,5)],\n[sp.sympify(1), sp.Rational(-11,54), sp.Rational(5,2), sp.Rational(-70,27), sp.Rational(35,27)],\n[sp.Rational(7,8), sp.Rational(1631,55296), sp.Rational(175,512), sp.Rational(575,13824), sp.Rational(44275,110592), sp.Rational(253,4096)],\n[\"\",sp.Rational(37,378), sp.sympify(0), sp.Rational(250,621), sp.Rational(125,594), sp.sympify(0), sp.Rational(512,1771)]]\n, 5)",
"_____no_output_____"
]
],
[
[
"<a id='dp6'></a>\n\n### Step 2.a.xiii: RK6 Dormand-Prince Method [Back to [top](#toc)\\]\n$$\\label{dp6}$$\n\nThe sixth-order Dormand-Prince method (see [Dormand, J. R.; Prince, P. J. (1981)](https://www.sciencedirect.com/science/article/pii/0771050X81900103)) Butcher Table is\n\n\n$$\\begin{array}{c|cccccccc}\n 0 & \\\\\n \\frac{1}{10} & \\frac{1}{10} & \\\\\n \\frac{2}{9} & \\frac{-2}{81} & \\frac{20}{81} & \\\\\n \\frac{3}{7} & \\frac{615}{1372} & \\frac{-270}{343} & \\frac{1053}{1372} & \\\\\n \\frac{3}{5} & \\frac{3243}{5500} & \\frac{-54}{55} & \\frac{50949}{71500} & \\frac{4998}{17875} & \\\\\n \\frac{4}{5} & \\frac{-26492}{37125} & \\frac{72}{55} & \\frac{2808}{23375} & \\frac{-24206}{37125} & \\frac{338}{459} & \\\\\n 1 & \\frac{5561}{2376} & \\frac{-35}{11} & \\frac{-24117}{31603} & \\frac{899983}{200772} & \\frac{-5225}{1836} & \\frac{3925}{4056} & \\\\\n 1 & \\frac{465467}{266112} & \\frac{-2945}{1232} & \\frac{-5610201}{14158144} & \\frac{10513573}{3212352} & \\frac{-424325}{205632} & \\frac{376225}{454272} & 0 & \\\\ \\hline\n & \\frac{61}{864} & 0 & \\frac{98415}{321776} & \\frac{16807}{146016} & \\frac{1375}{7344} & \\frac{1375}{5408} & \\frac{-37}{1120} & \\frac{1}{10}\n\\end{array}$$\n\n",
"_____no_output_____"
]
],
[
[
"# Step 2.a.xiii: RK6 Dormand-Prince Method\n\nButcher_dict['DP6'] = (\n[[0],\n[sp.Rational(1,10), sp.Rational(1,10)],\n[sp.Rational(2,9), sp.Rational(-2, 81), sp.Rational(20, 81)],\n[sp.Rational(3,7), sp.Rational(615, 1372), sp.Rational(-270, 343), sp.Rational(1053, 1372)],\n[sp.Rational(3,5), sp.Rational(3243, 5500), sp.Rational(-54, 55), sp.Rational(50949, 71500), sp.Rational(4998, 17875)],\n[sp.Rational(4, 5), sp.Rational(-26492, 37125), sp.Rational(72, 55), sp.Rational(2808, 23375), sp.Rational(-24206, 37125), sp.Rational(338, 459)],\n[sp.sympify(1), sp.Rational(5561, 2376), sp.Rational(-35, 11), sp.Rational(-24117, 31603), sp.Rational(899983, 200772), sp.Rational(-5225, 1836), sp.Rational(3925, 4056)],\n[sp.sympify(1), sp.Rational(465467, 266112), sp.Rational(-2945, 1232), sp.Rational(-5610201, 14158144), sp.Rational(10513573, 3212352), sp.Rational(-424325, 205632), sp.Rational(376225, 454272), sp.sympify(0)],\n[\"\", sp.Rational(61, 864), sp.sympify(0), sp.Rational(98415, 321776), sp.Rational(16807, 146016), sp.Rational(1375, 7344), sp.Rational(1375, 5408), sp.Rational(-37, 1120), sp.Rational(1,10)]]\n, 6)",
"_____no_output_____"
]
],
[
[
"<a id='l6'></a>\n\n### Step 2.a.xiv: RK6 Luther's Method [Back to [top](#toc)\\]\n$$\\label{l6}$$\n\nLuther's sixth-order method (see [H. A. Luther (1968)](http://www.ams.org/journals/mcom/1968-22-102/S0025-5718-68-99876-1/S0025-5718-68-99876-1.pdf)) Butcher table is:\n$$\\begin{array}{c|ccccccc}\n 0 & \\\\\n 1 & 1 & \\\\\n \\frac{1}{2} & \\frac{3}{8} & \\frac{1}{8} & \\\\\n \\frac{2}{3} & \\frac{8}{27} & \\frac{2}{27} & \\frac{8}{27} & \\\\\n \\frac{(7-q)}{14} & \\frac{(-21 + 9q)}{392} & \\frac{(-56 + 8q)}{392} & \\frac{(336 - 48q)}{392} & \\frac{(-63 + 3q)}{392} & \\\\\n \\frac{(7+q)}{14} & \\frac{(-1155 - 255q)}{1960} & \\frac{(-280 - 40q)}{1960} & \\frac{320q}{1960} & \\frac{(63 + 363q)}{1960} & \\frac{(2352 + 392q)}{1960} & \\\\\n 1 & \\frac{(330 + 105q)}{180} & \\frac{2}{3} & \\frac{(-200 + 280q)}{180} & \\frac{(126 - 189q)}{180} & \\frac{(-686 - 126q)}{180} & \\frac{(490 - 70q)}{180} & \\\\ \\hline\n & \\frac{1}{20} & 0 & \\frac{16}{45} & 0 & \\frac{49}{180} & \\frac{49}{180} & \\frac{1}{20}\n\\end{array}$$\n\nwhere $q = \\sqrt{21}$.",
"_____no_output_____"
]
],
[
[
"# Step 2.a.xiv: RK6 Luther's Method\n\nq = sp.sqrt(21)\nButcher_dict['L6'] = (\n[[0],\n[sp.sympify(1), sp.sympify(1)],\n[sp.Rational(1,2), sp.Rational(3,8), sp.Rational(1,8)],\n[sp.Rational(2,3), sp.Rational(8,27), sp.Rational(2,27), sp.Rational(8,27)],\n[(7 - q)/14, (-21 + 9*q)/392, (-56 + 8*q)/392, (336 -48*q)/392, (-63 + 3*q)/392],\n[(7 + q)/14, (-1155 - 255*q)/1960, (-280 - 40*q)/1960, (-320*q)/1960, (63 + 363*q)/1960, (2352 + 392*q)/1960],\n[sp.sympify(1), ( 330 + 105*q)/180, sp.Rational(2,3), (-200 + 280*q)/180, (126 - 189*q)/180, (-686 - 126*q)/180, (490 - 70*q)/180],\n[\"\", sp.Rational(1, 20), sp.sympify(0), sp.Rational(16, 45), sp.sympify(0), sp.Rational(49, 180), sp.Rational(49, 180), sp.Rational(1, 20)]]\n, 6)",
"_____no_output_____"
]
],
[
[
"<a id='dp8'></a>\n\n### Step 2.a.xv: RK8 Dormand-Prince Method [Back to [top](#toc)\\]\n$$\\label{dp8}$$\n\nThe eighth-order Dormand-Prince Method (see [Dormand, J. R.; Prince, P. J. (1981)](https://www.sciencedirect.com/science/article/pii/0771050X81900103)) Butcher table is:\n\n$$\\begin{array}{c|ccccccccc}\n 0 & \\\\\n \\frac{1}{18} & \\frac{1}{18} & \\\\\n \\frac{1}{12} & \\frac{1}{48} & \\frac{1}{16} & \\\\\n \\frac{1}{8} & \\frac{1}{32} & 0 & \\frac{3}{32} & \\\\\n \\frac{5}{16} & \\frac{5}{16} & 0 & \\frac{-75}{64} & \\frac{75}{64} & \\\\\n \\frac{3}{8} & \\frac{3}{80} & 0 & 0 & \\frac{3}{16} & \\frac{3}{20} & \\\\\n \\frac{59}{400} & \\frac{29443841}{614563906} & 0 & 0 & \\frac{77736538}{692538347} & \\frac{-28693883}{1125000000} & \\frac{23124283}{1800000000} & \\\\\n \\frac{93}{200} & \\frac{16016141}{946692911} & 0 & 0 & \\frac{61564180}{158732637} & \\frac{22789713}{633445777} & \\frac{545815736}{2771057229} & \\frac{-180193667}{1043307555} & \\\\\n \\frac{5490023248}{9719169821} & \\frac{39632708}{573591083} & 0 & 0 & \\frac{-433636366}{683701615} & \\frac{-421739975}{2616292301} & \\frac{100302831}{723423059} & \\frac{790204164}{839813087} & \\frac{800635310}{3783071287} & \\\\\n \\frac{13}{20} & \\frac{246121993}{1340847787} & 0 & 0 & \\frac{-37695042795}{15268766246} & \\frac{-309121744}{1061227803} & \\frac{-12992083}{490766935} & \\frac{6005943493}{2108947869} & \\frac{393006217}{1396673457} & \\frac{123872331}{1001029789} & \\\\\n \\frac{1201146811}{1299019798} & \\frac{-1028468189}{846180014} & 0 & 0 & \\frac{8478235783}{508512852} & \\frac{1311729495}{1432422823} & \\frac{-10304129995}{1701304382} & \\frac{-48777925059}{3047939560} & \\frac{15336726248}{1032824649} & \\frac{-45442868181}{3398467696} & \\frac{3065993473}{597172653} & \\\\\n 1 & \\frac{185892177}{718116043} & 0 & 0 & \\frac{-3185094517}{667107341} & \\frac{-477755414}{1098053517} & \\frac{-703635378}{230739211} & \\frac{5731566787}{1027545527} & \\frac{5232866602}{850066563} & \\frac{-4093664535}{808688257} & \\frac{3962137247}{1805957418} & \\frac{65686358}{487910083} & \\\\\n 1 & \\frac{403863854}{491063109} & 0 & 0 & \\frac{-5068492393}{434740067} & \\frac{-411421997}{543043805} & \\frac{652783627}{914296604} & \\frac{11173962825}{925320556} & \\frac{-13158990841}{6184727034} & \\frac{3936647629}{1978049680} & \\frac{-160528059}{685178525} & \\frac{248638103}{1413531060} & 0 & \\\\\n & \\frac{14005451}{335480064} & 0 & 0 & 0 & 0 & \\frac{-59238493}{1068277825} & \\frac{181606767}{758867731} & \\frac{561292985}{797845732} & \\frac{-1041891430}{1371343529} & \\frac{760417239}{1151165299} & \\frac{118820643}{751138087} & \\frac{-528747749}{2220607170} & \\frac{1}{4}\n\\end{array}$$\n\n",
"_____no_output_____"
]
],
[
[
"# Step 2.a.xv: RK8 Dormand-Prince Method\n\nButcher_dict['DP8']=(\n[[0],\n[sp.Rational(1, 18), sp.Rational(1, 18)],\n[sp.Rational(1, 12), sp.Rational(1, 48), sp.Rational(1, 16)],\n[sp.Rational(1, 8), sp.Rational(1, 32), sp.sympify(0), sp.Rational(3, 32)],\n[sp.Rational(5, 16), sp.Rational(5, 16), sp.sympify(0), sp.Rational(-75, 64), sp.Rational(75, 64)],\n[sp.Rational(3, 8), sp.Rational(3, 80), sp.sympify(0), sp.sympify(0), sp.Rational(3, 16), sp.Rational(3, 20)],\n[sp.Rational(59, 400), sp.Rational(29443841, 614563906), sp.sympify(0), sp.sympify(0), sp.Rational(77736538, 692538347), sp.Rational(-28693883, 1125000000), sp.Rational(23124283, 1800000000)],\n[sp.Rational(93, 200), sp.Rational(16016141, 946692911), sp.sympify(0), sp.sympify(0), sp.Rational(61564180, 158732637), sp.Rational(22789713, 633445777), sp.Rational(545815736, 2771057229), sp.Rational(-180193667, 1043307555)],\n[sp.Rational(5490023248, 9719169821), sp.Rational(39632708, 573591083), sp.sympify(0), sp.sympify(0), sp.Rational(-433636366, 683701615), sp.Rational(-421739975, 2616292301), sp.Rational(100302831, 723423059), sp.Rational(790204164, 839813087), sp.Rational(800635310, 3783071287)],\n[sp.Rational(13, 20), sp.Rational(246121993, 1340847787), sp.sympify(0), sp.sympify(0), sp.Rational(-37695042795, 15268766246), sp.Rational(-309121744, 1061227803), sp.Rational(-12992083, 490766935), sp.Rational(6005943493, 2108947869), sp.Rational(393006217, 1396673457), sp.Rational(123872331, 1001029789)],\n[sp.Rational(1201146811, 1299019798), sp.Rational(-1028468189, 846180014), sp.sympify(0), sp.sympify(0), sp.Rational(8478235783, 508512852), sp.Rational(1311729495, 1432422823), sp.Rational(-10304129995, 1701304382), sp.Rational(-48777925059, 3047939560), sp.Rational(15336726248, 1032824649), sp.Rational(-45442868181, 3398467696), sp.Rational(3065993473, 597172653)],\n[sp.sympify(1), sp.Rational(185892177, 718116043), sp.sympify(0), sp.sympify(0), sp.Rational(-3185094517, 667107341), sp.Rational(-477755414, 1098053517), sp.Rational(-703635378, 230739211), sp.Rational(5731566787, 1027545527), sp.Rational(5232866602, 850066563), sp.Rational(-4093664535, 808688257), sp.Rational(3962137247, 1805957418), sp.Rational(65686358, 487910083)],\n[sp.sympify(1), sp.Rational(403863854, 491063109), sp.sympify(0), sp.sympify(0), sp.Rational(-5068492393, 434740067), sp.Rational(-411421997, 543043805), sp.Rational(652783627, 914296604), sp.Rational(11173962825, 925320556), sp.Rational(-13158990841, 6184727034), sp.Rational(3936647629, 1978049680), sp.Rational(-160528059, 685178525), sp.Rational(248638103, 1413531060), sp.sympify(0)],\n[\"\", sp.Rational(14005451, 335480064), sp.sympify(0), sp.sympify(0), sp.sympify(0), sp.sympify(0), sp.Rational(-59238493, 1068277825), sp.Rational(181606767, 758867731), sp.Rational(561292985, 797845732), sp.Rational(-1041891430, 1371343529), sp.Rational(760417239, 1151165299), sp.Rational(118820643, 751138087), sp.Rational(-528747749, 2220607170), sp.Rational(1, 4)]]\n, 8)",
"_____no_output_____"
]
],
[
[
"<a id='code_validation'></a>\n\n# Step 3: Code validation against `MoLtimestepping.RK_Butcher_Table_Dictionary` NRPy+ module [Back to [top](#toc)\\]\n$$\\label{code_validation}$$\n\nAs a code validation check, we verify agreement in the dictionary of Butcher tables between\n1. this tutorial and \n2. the NRPy+ [MoLtimestepping.RK_Butcher_Table_Dictionary](../edit/MoLtimestepping/RK_Butcher_Table_Dictionary.py) module.\n\nWe analyze all key/value entries in the dictionary for consistency.",
"_____no_output_____"
]
],
[
[
"# Step 3: Code validation against MoLtimestepping.RK_Butcher_Table_Dictionary NRPy+ module\nimport sys # Standard Python module for multiplatform OS-level functions\nfrom MoLtimestepping.RK_Butcher_Table_Dictionary import Butcher_dict as B_dict\nvalid = True\nfor key, value in Butcher_dict.items():\n if Butcher_dict[key] != B_dict[key]:\n valid = False\n print(key)\nif valid == True and len(Butcher_dict.items()) == len(B_dict.items()):\n print(\"The dictionaries match!\")\nelse:\n print(\"ERROR: Dictionaries don't match!\")\n sys.exit(1)",
"The dictionaries match!\n"
]
],
[
[
"<a id='latex_pdf_output'></a>\n\n# Step 4: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\nThe following code cell converts this Jupyter notebook into a proper, clickable $\\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename\n[Tutorial-RK_Butcher_Table_Dictionary.pdf](Tutorial-RK_Butcher_Table_Dictionary.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.)",
"_____no_output_____"
]
],
[
[
"import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface\ncmd.output_Jupyter_notebook_to_LaTeXed_PDF(\"Tutorial-RK_Butcher_Table_Dictionary\")",
"Created Tutorial-RK_Butcher_Table_Dictionary.tex, and compiled LaTeX file\n to PDF file Tutorial-RK_Butcher_Table_Dictionary.pdf\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ac3c6a400c8faa8999ea5b18cf7ee3a61fedaa | 64,200 | ipynb | Jupyter Notebook | Stat.ipynb | Abhinav-Rijal/Statistics | f29dc1f37911aed43114b606baf0c168ae3de912 | [
"MIT"
] | 2 | 2020-08-30T01:11:16.000Z | 2020-09-02T03:00:33.000Z | Stat.ipynb | Abhinav-Rijal/Statistics | f29dc1f37911aed43114b606baf0c168ae3de912 | [
"MIT"
] | null | null | null | Stat.ipynb | Abhinav-Rijal/Statistics | f29dc1f37911aed43114b606baf0c168ae3de912 | [
"MIT"
] | null | null | null | 87.109905 | 23,436 | 0.790452 | [
[
[
"#Generating random data\nimport random\nimport collections as cl\nimport math\nimport matplotlib.pyplot as plt\n%matplotlib inline\nx = [random.randint(0,200) for k in range(200)]\nprint(x)\nc= cl.Counter(x)\n#print(c)",
"[23, 128, 75, 139, 188, 156, 8, 69, 141, 200, 180, 145, 85, 75, 100, 59, 91, 168, 88, 26, 49, 166, 86, 93, 68, 36, 75, 84, 30, 35, 39, 40, 159, 26, 79, 15, 86, 196, 65, 157, 17, 72, 61, 54, 78, 182, 65, 117, 181, 98, 160, 94, 103, 87, 83, 57, 72, 32, 9, 110, 122, 32, 65, 191, 70, 186, 120, 120, 42, 145, 44, 70, 65, 13, 137, 51, 192, 166, 20, 149, 129, 33, 108, 19, 41, 95, 46, 148, 13, 158, 197, 4, 26, 183, 76, 133, 65, 54, 136, 141, 172, 103, 80, 149, 105, 153, 57, 26, 2, 14, 57, 38, 65, 120, 89, 193, 23, 132, 26, 27, 131, 104, 92, 30, 200, 130, 49, 104, 145, 127, 44, 110, 99, 42, 39, 112, 49, 158, 59, 77, 62, 69, 114, 26, 68, 161, 181, 39, 112, 118, 107, 200, 31, 166, 120, 40, 149, 94, 35, 198, 38, 49, 6, 57, 48, 140, 99, 179, 62, 123, 103, 64, 68, 182, 70, 21, 134, 126, 114, 58, 57, 85, 77, 190, 136, 71, 88, 192, 82, 181, 67, 157, 0, 72, 196, 20, 75, 159, 191, 27]\n"
],
[
"#Mean of the data\n\nN=200\nSum=0\nSum_GM=0\nfor i in range(200):\n Sum=Sum+x[i]\n if x[i]!=0:\n Sum_GM=Sum_GM + math.log10(x[i])\n#print(Sum)\nMean=round(Sum/N,3)\nGM=round(10**(Sum_GM/N),3)\nHM=round((GM**2)/Mean,3)\nprint(\"The Arithmetic mean, Geometric mean and Harmonic mean of the data are:\",Mean, GM, HM)",
"The Arithmetic mean, Geometric mean and Harmonic mean of the data are: 93.755 72.894 56.675\n"
],
[
"#Moments,Skewness, Kurtosis\nSum=0\nfor i in range(0,N):\n Sum=Sum+(x[i]-Mean)**1\nmu1=round(Sum/N,3)\nSum=0\nfor i in range(0,N):\n Sum=Sum+(x[i]-Mean)**2\nmu2=round(Sum/N,3)\nSum=0\nfor i in range(0,N):\n Sum=Sum+(x[i]-Mean)**3\nmu3=round(Sum/N,3)\nSum=0\nfor i in range(0,N):\n Sum=Sum+(x[i]-Mean)**4\nmu4=round(Sum/N,3)\ngamma1=mu3/(mu2)**(3/2)\ngamma2=(mu4/(mu2)**2)-3\nprint(\"The first, second, third and fourth central moments are:\", mu1, mu2, mu3, mu4)\nSum=0\nfor i in range(0,N):\n Sum=Sum+(x[i]-0)**1\nmu1=round(Sum/N,3)\nSum=0\nfor i in range(0,N):\n Sum=Sum+(x[i]-0)**2\nmu2=round(Sum/N,3)\nSum=0\nfor i in range(0,N):\n Sum=Sum+(x[i]-0)**3\nmu3=round(Sum/N,3)\nSum=0\nfor i in range(0,N):\n Sum=Sum+(x[i]-0)**4\nmu4=round(Sum/N,3)\nprint(\"The first, second, third and fourth raw moments wrt 0 are:\", mu1, mu2, mu3, mu4)\nif gamma1==0:\n print('The distribution is symmetric')\nelif gamma1>0:\n print('The distribution is positively skewed')\nelse:\n print('The distribution is negatively skewed')\nif gamma2==0:\n print('The distribution is mesokurtic')\nelif gamma2>0:\n print('The distribution is leptokurtic')\nelse:\n print('The distribution is platykurtic')",
"The first, second, third and fourth central moments are: 0.0 2990.035 52391.135 18101250.123\nThe first, second, third and fourth raw moments wrt 0 are: 93.755 11780.035 1717489.775 272707519.195\nThe distribution is positively skewed\nThe distribution is platykurtic\n"
],
[
"#SELECTION SORT, for Ascending order, by finding smallest numbers \nfor i in range(0,N):\n Min=x[i]\n Index=i\n #print(i) \n for j in range(i+1,N):\n #print(j)\n if x[j]<Min:\n Min=x[j]\n Index=j\n x[Index]=x[i]\n x[i]=Min\nprint(x)",
"[0, 1, 6, 7, 7, 9, 9, 10, 11, 12, 13, 13, 14, 16, 17, 17, 19, 19, 20, 25, 25, 27, 28, 28, 30, 31, 32, 33, 33, 35, 35, 36, 36, 37, 38, 38, 41, 41, 42, 42, 44, 46, 46, 46, 48, 48, 50, 50, 50, 51, 52, 52, 54, 55, 55, 57, 58, 58, 61, 62, 64, 66, 70, 71, 71, 75, 76, 77, 78, 81, 82, 83, 83, 84, 85, 85, 85, 85, 87, 87, 87, 87, 89, 89, 90, 90, 92, 92, 93, 94, 96, 96, 97, 100, 102, 103, 103, 104, 105, 106, 107, 109, 110, 112, 113, 115, 115, 115, 116, 117, 120, 121, 123, 123, 124, 125, 127, 127, 128, 129, 129, 130, 130, 130, 130, 131, 132, 132, 133, 134, 135, 135, 135, 136, 137, 138, 140, 143, 144, 145, 145, 145, 146, 147, 148, 148, 150, 150, 151, 152, 153, 153, 153, 154, 154, 156, 156, 160, 160, 160, 160, 163, 164, 165, 165, 168, 170, 170, 171, 171, 172, 173, 173, 174, 175, 175, 176, 178, 178, 178, 179, 179, 180, 180, 181, 182, 182, 184, 188, 188, 189, 190, 190, 191, 192, 192, 193, 197, 198, 200]\n"
],
[
"#Median, Quartiles, Deciles, Percentiles\n#import math\nMd_pos= math.floor((N+1)/2)\nd=x[Md_pos-1]-x[Md_pos]\nMd=x[Md_pos-1]+(((N+1)/2)-Md_pos)*d\nQ1_pos=math.floor((N+1)/4)\nQ3_pos=math.floor(3*(N+1)/4)\nd1=x[Q1_pos-1]-x[Q1_pos]\nd2=x[Q3_pos-1]-x[Q3_pos]\nQ1=x[Q1_pos-1]+(((N+1)/4)-Q1_pos)*d1\nQ3=x[Q3_pos-1]+((3*(N+1)/4)-Q3_pos)*d2\nQ1=round(Q1,3)\nMd=round(Md,3)\nQ3=round(Q3,3)\nprint(\"The first quartile, Median or second quartile and the third quartile are respectively:\", Q1, Md, Q3)\nD=[]\nfor i in range(1,10):\n D_pos= math.floor(i*(N+1)/10)\n d=x[D_pos-1]-x[D_pos]\n D.append(round(x[D_pos-1]+((i*(N+1)/10)-D_pos)*d,3))\nprint(\"The 9 Deciles are:\", D)\nP=[]\nfor i in range(1,100):\n P_pos= math.floor(i*(N+1)/100)\n d=x[P_pos-1]-x[P_pos]\n P.append(round(x[P_pos-1]+((i*(N+1)/100)-P_pos)*d,3))\nprint(\"The 99 Percentiles are:\", P)\n \n",
"The first quartile, Median or second quartile and the third quartile are respectively: 50.75 105.5 151.25\nThe 9 Deciles are: [25.0, 41.6, 61.4, 87.0, 105.5, 129.0, 145.0, 160.0, 177.1]\nThe 99 Percentiles are: [0.95, 7.0, 9.0, 9.96, 11.95, 12.94, 15.93, 16.84, 18.91, 25.0, 26.89, 27.76, 30.87, 33.0, 35.0, 36.0, 36.83, 37.46, 40.81, 41.6, 46.0, 45.56, 47.54, 50.0, 50.75, 51.48, 55.0, 56.72, 57.13, 61.4, 64.76, 71.0, 74.67, 76.66, 80.65, 83.0, 83.63, 85.0, 84.22, 87.0, 86.18, 88.58, 89.14, 91.56, 93.1, 95.54, 99.06, 103.0, 103.51, 105.5, 108.49, 111.48, 115.0, 114.46, 115.35, 119.88, 122.43, 123.84, 126.41, 129.0, 130.0, 130.0, 130.37, 131.36, 133.35, 135.0, 135.33, 136.64, 142.31, 145.0, 144.29, 146.28, 146.54, 149.26, 151.25, 153.0, 154.0, 156.0, 160.0, 160.0, 162.19, 165.0, 166.34, 169.16, 170.15, 173.0, 173.13, 174.12, 178.0, 177.1, 178.09, 179.08, 182.0, 180.24, 187.05, 190.0, 190.03, 191.02, 196.01]\n"
],
[
"#frequency table, Mode\n\ncount=[]\nfreq=[]\ny=[]\ny.append('X')\nfreq.append('f')\nrepeat=0\nfor i in range(0,N-1):\n count.append(1)\n \n if x[i]==x[i+1]:\n count[i-repeat]=count[i-repeat] +1\n repeat=repeat+1\n else:\n y.append(x[i])\n \n#print(repeat) \n#print(x)\n#more_than_cf=[]\n#more_than_cf.append('More than cf')\ny.append(x[N-1])\nfor i in range(0,N-repeat):\n freq.append(count[i])\n #more_than_cf.append(count[i])\n #for j in range(i+1,N-repeat):\n #more_than_cf[i+1]=more_than_cf[i+1]+count[j]\n \n \n#print(freq)\n#print(len(freq))\nprint(\"Number of discrete data items\",N-repeat)\n#print(y)\n#print(len(y))\n#list_of_lists = [y, freq]\n\n#for a in zip(*list_of_lists):\n #print(*a)\n \nIndices=[]\nmax_count=0\ny.pop(0)\nfreq.pop(0)\nmaxf=freq[0]\nfor i in range(0,len(freq)):\n if freq[i]>maxf:\n maxf=freq[i]\n max_index=i\n\nfor i in range(0,len(freq)): \n if freq[i]==maxf:\n max_count=max_count+1\n Indices.append(i)\nif max_count==1:\n print(\"The mode is:\", y[max_index])\n Mo=y[max_index]\n print(\"and its frequency is:\" ,freq[max_index])\n\n\nif max_count>1:\n print(\"Mode is ill-defined; maximum freq. is\", freq[max_index], \", which repeats\", max_count, \"times. And the modes are:\")\n for i in range(0, len(Indices)):\n print(y[Indices[i]]) \n Mo=round(3*Md-2*Mean,3)\n print(\"Mode, for ill-defined case, using Emperical relationship between Mode, Median and Mean is:\", Mo) \n ",
"Number of discrete data items 131\nMode is ill-defined; maximum freq. is 4 , which repeats 4 times. And the modes are:\n85\n87\n130\n160\nMode, for ill-defined case, using Emperical relationship between Mode, Median and Mean is: 108.94\n"
],
[
"#Dispersion\nRange=max(y)-min(y)\nRange_coeff= round(Range/(max(y)+min(y)),3)\nIQR=Q3-Q1\nQD=round(IQR/2,3)\nQD_coeff=round(IQR/(Q3+Q1),3)\nDev_Mean=[]\nMod_Dev_Mean=[]\nMod_Dev_Md=[]\nMod_Dev_Mo=[]\nSD=0\nMD_M=0\nMD_Md=0\nMD_Mo=0\nSum_Dev=0\n\nfor i in range(0, len(y)):\n Dev_Mean.append(round(y[i]-Mean,3))\n Mod_Dev_Mean.append(round(abs(y[i]-Mean),3))\n Mod_Dev_Md.append(round(abs(y[i]-Md),3))\n Mod_Dev_Mo.append(round(abs(y[i]-Mo),3))\n SD=SD+freq[i]*Mod_Dev_Mean[i]**2\n MD_M=MD_M+freq[i]*Mod_Dev_Mean[i]\n MD_Md=MD_Md+freq[i]*Mod_Dev_Md[i]\n MD_Mo=MD_Mo+freq[i]*Mod_Dev_Mo[i]\n Sum_Dev=Sum_Dev+round(freq[i]*Dev_Mean[i],3)\nVar=round(SD/N,3)\nSD=round(math.sqrt(SD/N),3)\nCOV=round(SD*100/Mean,3)\nMD_M=round(MD_M/N,3)\nCoeff_MD_M=round(MD_M/Mean,3)\nMD_Md=round(MD_Md/N,3)\nCoeff_MD_Md=round(MD_Md/Md,3)\nMD_Mo=round(MD_Mo/N,3)\nCoeff_MD_Mo=round(MD_Mo/Mo,3)\n#print(Dev)\ny.insert(0,'X')\nfreq.insert(0,'f')\nMod_Dev_Mean.insert(0,'|X-Mean|')\nDev_Mean.insert(0,'X-Mean')\n\nlist_of_lists = [y, freq, Dev_Mean, Mod_Dev_Mean ]\n\nfor a in zip(*list_of_lists):\n print(*a)\ny.pop(0)\nfreq.pop(0)\n\nprint(\"The data ranges from \", min(y),\" to \", max(y), \"with Range=\", Range, \"and Range coeff=\", Range_coeff)\nprint(\"Inter-Quartile Range, Quartile Deviation or Semi-IQR and the coefficient of QD or relative QD are respectively: \", IQR, QD, QD_coeff)\nprint(\"Total Deviation= \", Sum_Dev)\nprint(\"Variance= \", Var)\nprint(\"Standard Deviation= \", SD)\nprint(\"Coefficient Of Variation= \", COV)\nprint(\"Mean Deviation wrt Mean, Median, Mode are respectively: \", MD_M, MD_Md, MD_Mo)\nprint(\"Coefficient of(or relative) Mean Deviation wrt Mean, Median, Mode are respectively: \", Coeff_MD_M, Coeff_MD_Md, Coeff_MD_Mo)\n",
"X f X-Mean |X-Mean|\n0 1 -103.78 103.78\n1 1 -102.78 102.78\n6 1 -97.78 97.78\n7 2 -96.78 96.78\n9 2 -94.78 94.78\n10 1 -93.78 93.78\n11 1 -92.78 92.78\n12 1 -91.78 91.78\n13 2 -90.78 90.78\n14 1 -89.78 89.78\n16 1 -87.78 87.78\n17 2 -86.78 86.78\n19 2 -84.78 84.78\n20 1 -83.78 83.78\n25 2 -78.78 78.78\n27 1 -76.78 76.78\n28 2 -75.78 75.78\n30 1 -73.78 73.78\n31 1 -72.78 72.78\n32 1 -71.78 71.78\n33 2 -70.78 70.78\n35 2 -68.78 68.78\n36 2 -67.78 67.78\n37 1 -66.78 66.78\n38 2 -65.78 65.78\n41 2 -62.78 62.78\n42 2 -61.78 61.78\n44 1 -59.78 59.78\n46 3 -57.78 57.78\n48 2 -55.78 55.78\n50 3 -53.78 53.78\n51 1 -52.78 52.78\n52 2 -51.78 51.78\n54 1 -49.78 49.78\n55 2 -48.78 48.78\n57 1 -46.78 46.78\n58 2 -45.78 45.78\n61 1 -42.78 42.78\n62 1 -41.78 41.78\n64 1 -39.78 39.78\n66 1 -37.78 37.78\n70 1 -33.78 33.78\n71 2 -32.78 32.78\n75 1 -28.78 28.78\n76 1 -27.78 27.78\n77 1 -26.78 26.78\n78 1 -25.78 25.78\n81 1 -22.78 22.78\n82 1 -21.78 21.78\n83 2 -20.78 20.78\n84 1 -19.78 19.78\n85 4 -18.78 18.78\n87 4 -16.78 16.78\n89 2 -14.78 14.78\n90 2 -13.78 13.78\n92 2 -11.78 11.78\n93 1 -10.78 10.78\n94 1 -9.78 9.78\n96 2 -7.78 7.78\n97 1 -6.78 6.78\n100 1 -3.78 3.78\n102 1 -1.78 1.78\n103 2 -0.78 0.78\n104 1 0.22 0.22\n105 1 1.22 1.22\n106 1 2.22 2.22\n107 1 3.22 3.22\n109 1 5.22 5.22\n110 1 6.22 6.22\n112 1 8.22 8.22\n113 1 9.22 9.22\n115 3 11.22 11.22\n116 1 12.22 12.22\n117 1 13.22 13.22\n120 1 16.22 16.22\n121 1 17.22 17.22\n123 2 19.22 19.22\n124 1 20.22 20.22\n125 1 21.22 21.22\n127 2 23.22 23.22\n128 1 24.22 24.22\n129 2 25.22 25.22\n130 4 26.22 26.22\n131 1 27.22 27.22\n132 2 28.22 28.22\n133 1 29.22 29.22\n134 1 30.22 30.22\n135 3 31.22 31.22\n136 1 32.22 32.22\n137 1 33.22 33.22\n138 1 34.22 34.22\n140 1 36.22 36.22\n143 1 39.22 39.22\n144 1 40.22 40.22\n145 3 41.22 41.22\n146 1 42.22 42.22\n147 1 43.22 43.22\n148 2 44.22 44.22\n150 2 46.22 46.22\n151 1 47.22 47.22\n152 1 48.22 48.22\n153 3 49.22 49.22\n154 2 50.22 50.22\n156 2 52.22 52.22\n160 4 56.22 56.22\n163 1 59.22 59.22\n164 1 60.22 60.22\n165 2 61.22 61.22\n168 1 64.22 64.22\n170 2 66.22 66.22\n171 2 67.22 67.22\n172 1 68.22 68.22\n173 2 69.22 69.22\n174 1 70.22 70.22\n175 2 71.22 71.22\n176 1 72.22 72.22\n178 3 74.22 74.22\n179 2 75.22 75.22\n180 2 76.22 76.22\n181 1 77.22 77.22\n182 2 78.22 78.22\n184 1 80.22 80.22\n188 2 84.22 84.22\n189 1 85.22 85.22\n190 2 86.22 86.22\n191 1 87.22 87.22\n192 2 88.22 88.22\n193 1 89.22 89.22\n197 1 93.22 93.22\n198 1 94.22 94.22\n200 1 96.22 96.22\nThe data ranges from 0 to 200 with Range= 200 and Range coeff= 1.0\nInter-Quartile Range, Quartile Deviation or Semi-IQR and the coefficient of QD or relative QD are respectively: 100.5 50.25 0.498\nTotal Deviation= 2.5295321393059567e-12\nVariance= 3197.192\nStandard Deviation= 56.544\nCoefficient Of Variation= 54.484\nMean Deviation wrt Mean, Median, Mode are respectively: 49.157 49.125 49.139\nCoefficient of(or relative) Mean Deviation wrt Mean, Median, Mode are respectively: 0.474 0.466 0.451\n"
],
[
"def sum_freq(mini,maxi):\n #Exclusive class interval\n sumf=0\n for i in range(0,len(y)):\n if y[i]>=mini and y[i]<maxi: #upperbound is excluded\n sumf=sumf+freq[i]\n elif y[i]==maxi:\n break\n return(sumf)",
"_____no_output_____"
],
[
"def cf_more_than(mini):\n mt_cf=0\n for i in range(0, len(y)):\n if y[i]>=mini:\n mt_cf=mt_cf+freq[i]\n return(mt_cf)",
"_____no_output_____"
],
[
"def cf_less_than(maxi):\n lt_cf=0\n for i in range(0, len(y)):\n if y[i]<maxi:\n lt_cf=lt_cf+freq[i]\n return(lt_cf)",
"_____no_output_____"
],
[
"#Converting to continuous/class intervals\nK=1+3.322*math.log10(N)\nW=round(Range/K)\nK=round(K)\nprint(\"Using Struge's law to transform the discrete data into continuous, the number of intervals and width of an interval are respectively: \", K, W)\ncont=[]\ncont_freq=[]\nmore_than_cf=[]\nless_than_cf=[]\nrel_freq=[]\npoints=[]\nmid_pts=[]\nmini=min(y)\npoints.append(mini)\nfor i in range(0,K):\n \n cont.append(str(mini)+'-'+str(mini+W))\n cont_freq.append(sum_freq(mini,mini+W))\n rel_freq.append(round(cont_freq[i]/N,3))\n more_than_cf.append(cf_more_than(mini))\n less_than_cf.append(cf_less_than(mini+W))\n mini=mini+W\n mid_pts.append(mini-W/2)\n points.append(mini)\ncont.insert(0,'class')\ncont_freq.insert(0,'f')\nmore_than_cf.insert(0, 'cf(mt)')\nless_than_cf.insert(0, 'cf(lt)')\nrel_freq.insert(0,'rel.f')\nprint(points)\nprint(mid_pts)\n\nlist_of_lists = [cont, cont_freq, rel_freq, more_than_cf, less_than_cf ]\n\nfor a in zip(*list_of_lists):\n print(*a)\n",
"Using Struge's law to transform the discrete data into continuous, the number of intervals and width of an interval are respectively: 9 23\n[0, 23, 46, 69, 92, 115, 138, 161, 184, 207]\n[11.5, 34.5, 57.5, 80.5, 103.5, 126.5, 149.5, 172.5, 195.5]\nclass f rel.f cf(mt) cf(lt)\n0-23 19 0.095 200 19\n23-46 22 0.11 181 41\n46-69 21 0.105 159 62\n69-92 24 0.12 138 86\n92-115 19 0.095 114 105\n115-138 30 0.15 95 135\n138-161 26 0.13 65 161\n161-184 26 0.13 39 187\n184-207 13 0.065 13 200\n"
],
[
"\ncont_freq.pop(0)\ncont.pop(0)\nrel_freq.pop(0)\nmore_than_cf.pop(0)\nless_than_cf.pop(0)\nmore_than_cf.append(0)\nless_than_cf.insert(0,0)\n\n#print(len(more_than_cf))\n#print(len(points))",
"_____no_output_____"
],
[
"#Ogive curve\nplt.plot(points, more_than_cf, label='more than')\nplt.plot(points, less_than_cf, label='less than')\nplt.xlabel('X')\nplt.ylabel('cf')\nplt.title('Less than and More than Ogives')\nplt.legend()",
"_____no_output_____"
],
[
"#Frequency curve\nplt.title('Frequency curve')\nplt.plot(mid_pts,cont_freq)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ac3e748a14dec861ad25dde52fbb0f289249d6 | 80,491 | ipynb | Jupyter Notebook | notebooks/AudioManipulation.ipynb | DePacifier/AMH-STT | 875848048943477aad4a3ee8a19101fe3ca80bd5 | [
"MIT"
] | null | null | null | notebooks/AudioManipulation.ipynb | DePacifier/AMH-STT | 875848048943477aad4a3ee8a19101fe3ca80bd5 | [
"MIT"
] | null | null | null | notebooks/AudioManipulation.ipynb | DePacifier/AMH-STT | 875848048943477aad4a3ee8a19101fe3ca80bd5 | [
"MIT"
] | null | null | null | 67.356485 | 18,324 | 0.686064 | [
[
[
"import os\nimport sys\nimport librosa\nimport seaborn as sn\nsys.path.append(os.path.abspath(os.path.join('../')))\nfrom scripts.audio_loader import AudioLoader\nfrom scripts.audio_manuplator import AudioManipulator\nimport scripts.visualize as vis\nfrom scripts.results_pickler import ResultPickler\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n",
"_____no_output_____"
]
],
[
[
"## Load Audio files",
"_____no_output_____"
]
],
[
[
"al_train = AudioLoader(directory='../data/train')\n# al_test = AudioLoader(directory=\"../data/test\",tts_file=r'/trsTest.txt')\n",
"AudioExplorer:INFO->Successfully Created AudioExplorer Class\nAudioExplorer:INFO->Successfully Loaded Audio and TTS files\nAudioPreprocessor:INFO->Successfully Inherited AudioExplorer Class\nAudioPreprocessor:INFO->Successfully Inherited AudioExplorer Class\n"
],
[
"df_train_audio_data = al_train.get_audio_info_with_data()\n# df_test_audio_data = al_test.get_audio_info_with_data()\n# rp = ResultPickler()\n# rp.load_data(\"../models/LoadedAudioInfo.pkl\")\n# data_dict = rp.get_data()\n# # data_dict.keys()\n# df_train_audio_data = data_dict['TrainAudioInfoWithoutTTS']\ndf_train_audio_data\n",
"_____no_output_____"
],
[
"\n# instantiate audio manuplator class\nam_train = AudioManipulator(df_train_audio_data)\n",
"AudioPreprocessor:ERROR->successfully Initialized AudioPreprocessor class!\nNoneType: None\nAudioPreprocessor:ERROR->successfully Initialized AudioPreprocessor class!\nNoneType: None\n"
],
[
"# Plot Time Series data of \nvis.plot_series(df_train_audio_data.loc[0,\"TimeSeriesData\"])\n",
"_____no_output_____"
]
],
[
[
"## Preprocessing the audio Data\n- ### change the duration to the same size\n- ### convert channels to stereo by duplicating the other channel\n- ### standardize the sampling rate to the same one\n- ### Data Augmentation\n- ### Extract Features\n\n",
"_____no_output_____"
],
[
"### Convert Channels to Stereo by duplicating the other channel\n",
"_____no_output_____"
]
],
[
[
"am_train.convert_stereo_audio()\nam_train.get_audio_info()",
"_____no_output_____"
],
[
"# am_train.get_audio_info().head().loc[0,\"TimeSeriesData\"].shape\nnum_rows, y_len = am_train.get_audio_info().loc[0,\"TimeSeriesData\"].shape\nnum_rows,y_len",
"_____no_output_____"
]
],
[
[
"### Change the duration to the same size\nFrom Our Data Exploration, we found that most frequent audio files has a duration between 2 to 6. And to reduce the bias, we will pad all the audio to make it equal in length with the maximum.",
"_____no_output_____"
]
],
[
[
"am_train.resize_audio()\n",
"_____no_output_____"
],
[
"am_train.get_audio_info()",
"_____no_output_____"
],
[
"am_train.get_audio_info().loc[0,\"TimeSeriesData\"].shape",
"_____no_output_____"
]
],
[
[
"### Standardize Sampling Rate",
"_____no_output_____"
]
],
[
[
"# count sampling rate frequencies\npd.DataFrame({\"count\": df_train_audio_data.groupby(\"SamplingRate\")[\"SamplingRate\"].count()})\n",
"_____no_output_____"
],
[
"am_train.resample_audio()",
"_____no_output_____"
],
[
"am_train.get_audio_info()",
"_____no_output_____"
]
],
[
[
"### Our SamplingRate is the same all around our data but we have resampled it to 44100. Now we have our processed data, we will save the preprocessed files to a folder in a .wav format. \n\n ",
"_____no_output_____"
]
],
[
[
"am_train.write_wave_files(\"../data/train/wav/\")",
"_____no_output_____"
]
],
[
[
"## Augmentation",
"_____no_output_____"
],
[
"## Feature Extraction\n### We can now extract features but first we convert back to mono since the librosa library expects a monochannel audio.",
"_____no_output_____"
]
],
[
[
"\n# features = am_train.extract_features()",
"/home/dibora/AMH-STT/STT/lib/python3.7/site-packages/librosa/core/spectrum.py:224: UserWarning: n_fft=2048 is too small for input signal of length=132\n n_fft, y.shape[-1]\n"
],
[
"# features.head()",
"_____no_output_____"
],
[
"# vis.plot_spectrogram(features.loc[0,'Melspectogram'])",
"_____no_output_____"
],
[
"# vis.plot_spectrogram(features.loc[0,'Melspectogram_db'])",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e7ac53fb6e6da6e0cacfb5ba947717c31b4d5099 | 21,664 | ipynb | Jupyter Notebook | 05_Merge/Fictitous Names/Exercises_with_solutions.ipynb | ktats/pandas_exercises | 0a8b3751fb839cc2c1e5f2827439a54b1823e7c2 | [
"BSD-3-Clause"
] | null | null | null | 05_Merge/Fictitous Names/Exercises_with_solutions.ipynb | ktats/pandas_exercises | 0a8b3751fb839cc2c1e5f2827439a54b1823e7c2 | [
"BSD-3-Clause"
] | null | null | null | 05_Merge/Fictitous Names/Exercises_with_solutions.ipynb | ktats/pandas_exercises | 0a8b3751fb839cc2c1e5f2827439a54b1823e7c2 | [
"BSD-3-Clause"
] | null | null | null | 27.046192 | 120 | 0.320716 | [
[
[
"# Fictitious Names",
"_____no_output_____"
],
[
"### Introduction:\n\nThis time you will create a data again \n\nSpecial thanks to [Chris Albon](http://chrisalbon.com/) for sharing the dataset and materials.\nAll the credits to this exercise belongs to him. \n\nIn order to understand about it go to [here](https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/).\n\n### Step 1. Import the necessary libraries",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"### Step 2. Create the 3 DataFrames based on the followin raw data",
"_____no_output_____"
]
],
[
[
"raw_data_1 = {\n 'subject_id': ['1', '2', '3', '4', '5'],\n 'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], \n 'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']}\n\nraw_data_2 = {\n 'subject_id': ['4', '5', '6', '7', '8'],\n 'first_name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'], \n 'last_name': ['Bonder', 'Black', 'Balwner', 'Brice', 'Btisan']}\n\nraw_data_3 = {\n 'subject_id': ['1', '2', '3', '4', '5', '7', '8', '9', '10', '11'],\n 'test_id': [51, 15, 15, 61, 16, 14, 15, 1, 61, 16]}",
"_____no_output_____"
]
],
[
[
"### Step 3. Assign each to a variable called data1, data2, data3",
"_____no_output_____"
]
],
[
[
" \n\ndata3",
"_____no_output_____"
]
],
[
[
"### Step 4. Join the two dataframes along rows and assign all_data",
"_____no_output_____"
]
],
[
[
"all_data = pd.concat([data1, data2])\nall_data",
"_____no_output_____"
]
],
[
[
"### Step 5. Join the two dataframes along columns and assing to all_data_col",
"_____no_output_____"
]
],
[
[
"all_data_col = pd.concat([data1, data2], axis = 1)\nall_data_col",
"_____no_output_____"
]
],
[
[
"### Step 6. Print data3",
"_____no_output_____"
]
],
[
[
"data3",
"_____no_output_____"
]
],
[
[
"### Step 7. Merge all_data and data3 along the subject_id value",
"_____no_output_____"
]
],
[
[
"pd.merge(all_data, data3, on='subject_id')",
"_____no_output_____"
]
],
[
[
"### Step 8. Merge only the data that has the same 'subject_id' on both data1 and data2",
"_____no_output_____"
]
],
[
[
"pd.merge(data1, data2, on='subject_id', how='inner')",
"_____no_output_____"
]
],
[
[
"### Step 9. Merge all values in data1 and data2, with matching records from both sides where available.",
"_____no_output_____"
]
],
[
[
"pd.merge(data1, data2, on='subject_id', how='outer')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ac5646cacbdbd3e190fee63f069489a86eed49 | 383,711 | ipynb | Jupyter Notebook | examples/PairsTrading.ipynb | zhnagchulan/vectorbt | 6b199f6cc8c32fc5eeaa10f88bf8aa81774969c9 | [
"Apache-2.0"
] | 1 | 2021-08-29T00:25:41.000Z | 2021-08-29T00:25:41.000Z | examples/PairsTrading.ipynb | zhnagchulan/vectorbt | 6b199f6cc8c32fc5eeaa10f88bf8aa81774969c9 | [
"Apache-2.0"
] | null | null | null | examples/PairsTrading.ipynb | zhnagchulan/vectorbt | 6b199f6cc8c32fc5eeaa10f88bf8aa81774969c9 | [
"Apache-2.0"
] | null | null | null | 229.629563 | 245,548 | 0.838715 | [
[
[
"In this example, we will compare development of a pairs trading strategy using backtrader and vectorbt.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport datetime\nimport collections\nimport math\nimport pytz",
"_____no_output_____"
],
[
"import scipy.stats as st\n\nSYMBOL1 = 'PEP'\nSYMBOL2 = 'KO'\nFROMDATE = datetime.datetime(2017, 1, 1, tzinfo=pytz.utc)\nTODATE = datetime.datetime(2019, 1, 1, tzinfo=pytz.utc)\nPERIOD = 100\nCASH = 100000\nCOMMPERC = 0.005 # 0.5%\nORDER_PCT1 = 0.1\nORDER_PCT2 = 0.1\nUPPER = st.norm.ppf(1 - 0.05 / 2)\nLOWER = -st.norm.ppf(1 - 0.05 / 2)\nMODE = 'OLS' # OLS, log_return",
"_____no_output_____"
]
],
[
[
"## Data",
"_____no_output_____"
]
],
[
[
"import vectorbt as vbt\n\nstart_date = FROMDATE.replace(tzinfo=pytz.utc)\nend_date = TODATE.replace(tzinfo=pytz.utc)\ndata = vbt.YFData.download([SYMBOL1, SYMBOL2], start=start_date, end=end_date)\ndata = data.loc[(data.wrapper.index >= start_date) & (data.wrapper.index < end_date)]",
"_____no_output_____"
],
[
"print(data.data[SYMBOL1].iloc[[0, -1]])\nprint(data.data[SYMBOL2].iloc[[0, -1]])",
" Open High Low Close \\\nDate \n2017-01-03 00:00:00+00:00 91.831129 91.962386 91.192316 91.577354 \n2018-12-31 00:00:00+00:00 102.775161 103.249160 101.604091 102.682220 \n\n Volume Dividends Stock Splits \nDate \n2017-01-03 00:00:00+00:00 3741200 0.0 0 \n2018-12-31 00:00:00+00:00 5019100 0.0 0 \n Open High Low Close \\\nDate \n2017-01-03 00:00:00+00:00 35.801111 36.068542 35.611321 36.059914 \n2018-12-31 00:00:00+00:00 43.810820 43.856946 43.321878 43.681664 \n\n Volume Dividends Stock Splits \nDate \n2017-01-03 00:00:00+00:00 14711000 0.0 0 \n2018-12-31 00:00:00+00:00 10576300 0.0 0 \n"
]
],
[
[
"## backtrader",
"_____no_output_____"
],
[
"Adapted version of https://github.com/mementum/backtrader/blob/master/contrib/samples/pair-trading/pair-trading.py",
"_____no_output_____"
]
],
[
[
"import backtrader as bt\nimport backtrader.feeds as btfeeds\nimport backtrader.indicators as btind\n\nclass CommInfoFloat(bt.CommInfoBase):\n \"\"\"Commission schema that keeps size as float.\"\"\"\n params = (\n ('stocklike', True),\n ('commtype', bt.CommInfoBase.COMM_PERC),\n ('percabs', True),\n )\n \n def getsize(self, price, cash):\n if not self._stocklike:\n return self.p.leverage * (cash / self.get_margin(price))\n\n return self.p.leverage * (cash / price)\n \nclass OLSSlopeIntercept(btind.PeriodN):\n \"\"\"Calculates a linear regression using OLS.\"\"\"\n _mindatas = 2 # ensure at least 2 data feeds are passed\n\n packages = (\n ('pandas', 'pd'),\n ('statsmodels.api', 'sm'),\n )\n lines = ('slope', 'intercept',)\n params = (\n ('period', 10),\n )\n\n def next(self):\n p0 = pd.Series(self.data0.get(size=self.p.period))\n p1 = pd.Series(self.data1.get(size=self.p.period))\n p1 = sm.add_constant(p1)\n intercept, slope = sm.OLS(p0, p1).fit().params\n\n self.lines.slope[0] = slope\n self.lines.intercept[0] = intercept\n \n \nclass Log(btind.Indicator):\n \"\"\"Calculates log.\"\"\"\n lines = ('log',)\n \n def next(self):\n self.l.log[0] = math.log(self.data[0])\n\n\nclass OLSSpread(btind.PeriodN):\n \"\"\"Calculates the z-score of the OLS spread.\"\"\"\n _mindatas = 2 # ensure at least 2 data feeds are passed\n lines = ('spread', 'spread_mean', 'spread_std', 'zscore',)\n params = (('period', 10),)\n\n def __init__(self):\n data0_log = Log(self.data0)\n data1_log = Log(self.data1)\n slint = OLSSlopeIntercept(data0_log, data1_log, period=self.p.period)\n\n spread = data0_log - (slint.slope * data1_log + slint.intercept)\n self.l.spread = spread\n\n self.l.spread_mean = bt.ind.SMA(spread, period=self.p.period)\n self.l.spread_std = bt.ind.StdDev(spread, period=self.p.period)\n self.l.zscore = (spread - self.l.spread_mean) / self.l.spread_std\n \nclass LogReturns(btind.PeriodN):\n \"\"\"Calculates the log returns.\"\"\"\n lines = ('logret',)\n params = (('period', 1),)\n \n def __init__(self):\n self.addminperiod(self.p.period + 1)\n \n def next(self):\n self.l.logret[0] = math.log(self.data[0] / self.data[-self.p.period])\n \nclass LogReturnSpread(btind.PeriodN):\n \"\"\"Calculates the spread of the log returns.\"\"\"\n _mindatas = 2 # ensure at least 2 data feeds are passed\n lines = ('logret0', 'logret1', 'spread', 'spread_mean', 'spread_std', 'zscore',)\n params = (('period', 10),)\n\n def __init__(self):\n self.l.logret0 = LogReturns(self.data0, period=1)\n self.l.logret1 = LogReturns(self.data1, period=1)\n self.l.spread = self.l.logret0 - self.l.logret1\n self.l.spread_mean = bt.ind.SMA(self.l.spread, period=self.p.period)\n self.l.spread_std = bt.ind.StdDev(self.l.spread, period=self.p.period)\n self.l.zscore = (self.l.spread - self.l.spread_mean) / self.l.spread_std\n\nclass PairTradingStrategy(bt.Strategy):\n \"\"\"Basic pair trading strategy.\"\"\"\n params = dict(\n period=PERIOD,\n order_pct1=ORDER_PCT1,\n order_pct2=ORDER_PCT2,\n printout=True,\n upper=UPPER,\n lower=LOWER,\n mode=MODE\n )\n\n def log(self, txt, dt=None):\n if self.p.printout:\n dt = dt or self.data.datetime[0]\n dt = bt.num2date(dt)\n print('%s, %s' % (dt.isoformat(), txt))\n\n def notify_order(self, order):\n if order.status in [bt.Order.Submitted, bt.Order.Accepted]:\n return # Await further notifications\n\n if order.status == order.Completed:\n if order.isbuy():\n buytxt = 'BUY COMPLETE {}, size = {:.2f}, price = {:.2f}'.format(\n order.data._name, order.executed.size, order.executed.price)\n self.log(buytxt, order.executed.dt)\n else:\n selltxt = 'SELL COMPLETE {}, size = {:.2f}, price = {:.2f}'.format(\n order.data._name, order.executed.size, order.executed.price)\n self.log(selltxt, order.executed.dt)\n\n elif order.status in [order.Expired, order.Canceled, order.Margin]:\n self.log('%s ,' % order.Status[order.status])\n pass # Simply log\n\n # Allow new orders\n self.orderid = None\n\n def __init__(self):\n # To control operation entries\n self.orderid = None\n self.order_pct1 = self.p.order_pct1\n self.order_pct2 = self.p.order_pct2\n self.upper = self.p.upper\n self.lower = self.p.lower\n self.status = 0\n \n # Signals performed with PD.OLS :\n if self.p.mode == 'log_return':\n self.transform = LogReturnSpread(self.data0, self.data1, period=self.p.period)\n elif self.p.mode == 'OLS':\n self.transform = OLSSpread(self.data0, self.data1, period=self.p.period)\n else:\n raise ValueError(\"Unknown mode\")\n self.spread = self.transform.spread\n self.zscore = self.transform.zscore\n \n # For tracking\n self.spread_sr = pd.Series(dtype=float, name='spread')\n self.zscore_sr = pd.Series(dtype=float, name='zscore')\n self.short_signal_sr = pd.Series(dtype=bool, name='short_signals')\n self.long_signal_sr = pd.Series(dtype=bool, name='long_signals')\n\n def next(self):\n if self.orderid:\n return # if an order is active, no new orders are allowed\n \n self.spread_sr[self.data0.datetime.datetime()] = self.spread[0]\n self.zscore_sr[self.data0.datetime.datetime()] = self.zscore[0]\n self.short_signal_sr[self.data0.datetime.datetime()] = False\n self.long_signal_sr[self.data0.datetime.datetime()] = False\n\n if self.zscore[0] > self.upper and self.status != 1:\n # Check conditions for shorting the spread & place the order\n self.short_signal_sr[self.data0.datetime.datetime()] = True\n\n # Placing the order\n self.log('SELL CREATE {}, price = {:.2f}, target pct = {:.2%}'.format(\n self.data0._name, self.data0.close[0], -self.order_pct1))\n self.order_target_percent(data=self.data0, target=-self.order_pct1)\n self.log('BUY CREATE {}, price = {:.2f}, target pct = {:.2%}'.format(\n self.data1._name, self.data1.close[0], self.order_pct2))\n self.order_target_percent(data=self.data1, target=self.order_pct2)\n\n self.status = 1\n\n elif self.zscore[0] < self.lower and self.status != 2:\n # Check conditions for longing the spread & place the order\n self.long_signal_sr[self.data0.datetime.datetime()] = True\n\n # Place the order\n self.log('SELL CREATE {}, price = {:.2f}, target pct = {:.2%}'.format(\n self.data1._name, self.data1.close[0], -self.order_pct2))\n self.order_target_percent(data=self.data1, target=-self.order_pct2)\n self.log('BUY CREATE {}, price = {:.2f}, target pct = {:.2%}'.format(\n self.data0._name, self.data0.close[0], self.order_pct1))\n self.order_target_percent(data=self.data0, target=self.order_pct1)\n \n self.status = 2\n\n def stop(self):\n if self.p.printout:\n print('==================================================')\n print('Starting Value - %.2f' % self.broker.startingcash)\n print('Ending Value - %.2f' % self.broker.getvalue())\n print('==================================================')",
"_____no_output_____"
],
[
"class DataAnalyzer(bt.analyzers.Analyzer):\n \"\"\"Analyzer to extract OHLCV.\"\"\"\n def create_analysis(self):\n self.rets0 = {}\n self.rets1 = {}\n\n def next(self):\n self.rets0[self.strategy.datetime.datetime()] = [\n self.data0.open[0],\n self.data0.high[0],\n self.data0.low[0],\n self.data0.close[0],\n self.data0.volume[0]\n ]\n self.rets1[self.strategy.datetime.datetime()] = [\n self.data1.open[0],\n self.data1.high[0],\n self.data1.low[0],\n self.data1.close[0],\n self.data1.volume[0]\n ]\n\n def get_analysis(self):\n return self.rets0, self.rets1\n\nclass CashValueAnalyzer(bt.analyzers.Analyzer):\n \"\"\"Analyzer to extract cash and value.\"\"\"\n def create_analysis(self):\n self.rets = {}\n\n def notify_cashvalue(self, cash, value):\n self.rets[self.strategy.datetime.datetime()] = (cash, value)\n\n def get_analysis(self):\n return self.rets\n \nclass OrderAnalyzer(bt.analyzers.Analyzer):\n \"\"\"Analyzer to extract order price, size, value, and paid commission.\"\"\"\n def create_analysis(self):\n self.rets0 = {}\n self.rets1 = {}\n\n def notify_order(self, order):\n if order.status == order.Completed:\n if order.data._name == SYMBOL1:\n rets = self.rets0\n else:\n rets = self.rets1\n rets[self.strategy.datetime.datetime()] = (\n order.executed.price,\n order.executed.size,\n -order.executed.size * order.executed.price,\n order.executed.comm\n )\n\n def get_analysis(self):\n return self.rets0, self.rets1",
"_____no_output_____"
],
[
"def prepare_cerebro(data0, data1, use_analyzers=True, **params):\n # Create a cerebro\n cerebro = bt.Cerebro()\n\n # Add the 1st data to cerebro\n cerebro.adddata(data0)\n\n # Add the 2nd data to cerebro\n cerebro.adddata(data1)\n\n # Add the strategy\n cerebro.addstrategy(PairTradingStrategy, **params)\n\n # Add the commission - only stocks like a for each operation\n cerebro.broker.setcash(CASH)\n\n # Add the commission - only stocks like a for each operation\n comminfo = CommInfoFloat(commission=COMMPERC)\n cerebro.broker.addcommissioninfo(comminfo)\n\n if use_analyzers:\n # Add analyzers \n cerebro.addanalyzer(DataAnalyzer)\n cerebro.addanalyzer(CashValueAnalyzer)\n cerebro.addanalyzer(OrderAnalyzer)\n \n return cerebro",
"_____no_output_____"
],
[
"class PandasData(btfeeds.PandasData):\n params = (\n # Possible values for datetime (must always be present)\n # None : datetime is the \"index\" in the Pandas Dataframe\n # -1 : autodetect position or case-wise equal name\n # >= 0 : numeric index to the colum in the pandas dataframe\n # string : column name (as index) in the pandas dataframe\n ('datetime', None),\n\n ('open', 'Open'),\n ('high', 'High'),\n ('low', 'Low'),\n ('close', 'Close'),\n ('volume', 'Volume'),\n ('openinterest', None),\n )",
"_____no_output_____"
],
[
"# Create the 1st data\ndata0 = PandasData(dataname=data.data[SYMBOL1], name=SYMBOL1)\n\n# Create the 2nd data\ndata1 = PandasData(dataname=data.data[SYMBOL2], name=SYMBOL2)\n\n# Prepare a cerebro\ncerebro = prepare_cerebro(data0, data1)\n\n# And run it\nbt_strategy = cerebro.run()[0]",
"2017-11-14T00:00:00, SELL CREATE PEP, price = 103.41, target pct = -10.00%\n2017-11-14T00:00:00, BUY CREATE KO, price = 41.95, target pct = 10.00%\n2017-11-15T00:00:00, SELL COMPLETE PEP, size = -96.70, price = 103.32\n2017-11-15T00:00:00, BUY COMPLETE KO, size = 238.39, price = 41.85\n2018-04-11T00:00:00, SELL CREATE KO, price = 39.57, target pct = -10.00%\n2018-04-11T00:00:00, BUY CREATE PEP, price = 98.49, target pct = 10.00%\n2018-04-12T00:00:00, SELL COMPLETE KO, size = -490.65, price = 39.65\n2018-04-12T00:00:00, BUY COMPLETE PEP, size = 198.06, price = 98.74\n2018-08-31T00:00:00, SELL CREATE PEP, price = 102.44, target pct = -10.00%\n2018-08-31T00:00:00, BUY CREATE KO, price = 40.45, target pct = 10.00%\n2018-09-04T00:00:00, SELL COMPLETE PEP, size = -198.78, price = 102.26\n2018-09-04T00:00:00, BUY COMPLETE KO, size = 498.98, price = 40.48\n2018-10-02T00:00:00, SELL CREATE KO, price = 42.57, target pct = -10.00%\n2018-10-02T00:00:00, BUY CREATE PEP, price = 100.25, target pct = 10.00%\n2018-10-03T00:00:00, SELL COMPLETE KO, size = -482.28, price = 42.52\n2018-10-03T00:00:00, BUY COMPLETE PEP, size = 197.45, price = 100.70\n2018-11-30T00:00:00, SELL CREATE PEP, price = 112.44, target pct = -10.00%\n2018-11-30T00:00:00, BUY CREATE KO, price = 46.50, target pct = 10.00%\n2018-12-03T00:00:00, SELL COMPLETE PEP, size = -189.20, price = 111.09\n2018-12-03T00:00:00, BUY COMPLETE KO, size = 451.21, price = 46.01\n==================================================\nStarting Value - 100000.00\nEnding Value - 100284.08\n==================================================\n"
],
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = (13, 8)\ncerebro.plot(iplot=False)",
"_____no_output_____"
],
[
"# Extract OHLCV\nbt_s1_rets, bt_s2_rets = bt_strategy.analyzers.dataanalyzer.get_analysis()\ndata_cols = ['open', 'high', 'low', 'close', 'volume']\nbt_s1_ohlcv = pd.DataFrame.from_dict(bt_s1_rets, orient='index', columns=data_cols)\nbt_s2_ohlcv = pd.DataFrame.from_dict(bt_s2_rets, orient='index', columns=data_cols)\n\nprint(bt_s1_ohlcv.shape)\nprint(bt_s2_ohlcv.shape)\n\nprint(bt_s1_ohlcv.iloc[[0, -1]])\nprint(bt_s2_ohlcv.iloc[[0, -1]])",
"(502, 5)\n(502, 5)\n open high low close volume\n2017-01-03 91.831129 91.962386 91.192316 91.577354 3741200.0\n2018-12-31 102.775161 103.249160 101.604091 102.682220 5019100.0\n open high low close volume\n2017-01-03 35.801111 36.068542 35.611321 36.059914 14711000.0\n2018-12-31 43.810820 43.856946 43.321878 43.681664 10576300.0\n"
],
[
"try:\n np.testing.assert_allclose(bt_s1_ohlcv.values, data.data[SYMBOL1].iloc[:, :5].values)\n np.testing.assert_allclose(bt_s2_ohlcv.values, data.data[SYMBOL2].iloc[:, :5].values)\nexcept AssertionError as e:\n print(e)",
"_____no_output_____"
],
[
"# Extract cash and value series\nbt_cashvalue_rets = bt_strategy.analyzers.cashvalueanalyzer.get_analysis()\nbt_cashvalue_df = pd.DataFrame.from_dict(bt_cashvalue_rets, orient='index', columns=['cash', 'value'])\nbt_cash = bt_cashvalue_df['cash']\nbt_value = bt_cashvalue_df['value']\n\nprint(bt_cash.iloc[[0, -1]])\nprint(bt_value.iloc[[0, -1]])",
"2017-01-03 100000.000000\n2018-12-31 100020.682139\nName: cash, dtype: float64\n2017-01-03 100000.000000\n2018-12-31 100284.081822\nName: value, dtype: float64\n"
],
[
"# Extract order info\nbt_s1_order_rets, bt_s2_order_rets = bt_strategy.analyzers.orderanalyzer.get_analysis()\norder_cols = ['order_price', 'order_size', 'order_value', 'order_comm']\nbt_s1_orders = pd.DataFrame.from_dict(bt_s1_order_rets, orient='index', columns=order_cols)\nbt_s2_orders = pd.DataFrame.from_dict(bt_s2_order_rets, orient='index', columns=order_cols)\n\nprint(bt_s1_orders.iloc[[0, -1]])\nprint(bt_s2_orders.iloc[[0, -1]])",
" order_price order_size order_value order_comm\n2017-11-15 103.316229 -96.698241 9990.497637 49.952488\n2018-12-03 111.094282 -189.202087 21019.269920 105.096350\n order_price order_size order_value order_comm\n2017-11-15 41.851497 238.385955 -9976.809115 49.884046\n2018-12-03 46.006429 451.211817 -20758.644494 103.793222\n"
],
[
"# Extract spread and z-score\nbt_spread = bt_strategy.spread_sr\nbt_zscore = bt_strategy.zscore_sr\n\nprint(bt_spread.iloc[[0, -1]])\nprint(bt_zscore.iloc[[0, -1]])",
"2017-10-16 -0.009388\n2018-12-31 -0.021157\nName: spread, dtype: float64\n2017-10-16 0.242706\n2018-12-31 -0.307914\nName: zscore, dtype: float64\n"
],
[
"# Extract signals\nbt_short_signals = bt_strategy.short_signal_sr\nbt_long_signals = bt_strategy.long_signal_sr\n\nprint(bt_short_signals[bt_short_signals])\nprint(bt_long_signals[bt_long_signals])",
"2017-11-14 True\n2018-08-31 True\n2018-11-30 True\nName: short_signals, dtype: bool\n2018-04-11 True\n2018-10-02 True\nName: long_signals, dtype: bool\n"
],
[
"# How fast is bt?\ncerebro = prepare_cerebro(data0, data1, use_analyzers=False, printout=False)\n\n%timeit cerebro.run(preload=False)",
"1.07 s ± 16.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
],
[
[
"## vectorbt",
"_____no_output_____"
],
[
"### Using Portfolio.from_orders",
"_____no_output_____"
]
],
[
[
"from numba import njit\n\n@njit\ndef rolling_logret_zscore_nb(a, b, period):\n \"\"\"Calculate the log return spread.\"\"\"\n spread = np.full_like(a, np.nan, dtype=np.float_)\n spread[1:] = np.log(a[1:] / a[:-1]) - np.log(b[1:] / b[:-1])\n zscore = np.full_like(a, np.nan, dtype=np.float_)\n for i in range(a.shape[0]):\n from_i = max(0, i + 1 - period)\n to_i = i + 1\n if i < period - 1:\n continue\n spread_mean = np.mean(spread[from_i:to_i])\n spread_std = np.std(spread[from_i:to_i])\n zscore[i] = (spread[i] - spread_mean) / spread_std\n return spread, zscore\n\n@njit\ndef ols_spread_nb(a, b):\n \"\"\"Calculate the OLS spread.\"\"\"\n a = np.log(a)\n b = np.log(b)\n _b = np.vstack((b, np.ones(len(b)))).T\n slope, intercept = np.dot(np.linalg.inv(np.dot(_b.T, _b)), np.dot(_b.T, a))\n spread = a - (slope * b + intercept)\n return spread[-1]\n \n@njit\ndef rolling_ols_zscore_nb(a, b, period):\n \"\"\"Calculate the z-score of the rolling OLS spread.\"\"\"\n spread = np.full_like(a, np.nan, dtype=np.float_)\n zscore = np.full_like(a, np.nan, dtype=np.float_)\n for i in range(a.shape[0]):\n from_i = max(0, i + 1 - period)\n to_i = i + 1\n if i < period - 1:\n continue\n spread[i] = ols_spread_nb(a[from_i:to_i], b[from_i:to_i])\n spread_mean = np.mean(spread[from_i:to_i])\n spread_std = np.std(spread[from_i:to_i])\n zscore[i] = (spread[i] - spread_mean) / spread_std\n return spread, zscore",
"_____no_output_____"
],
[
"# Calculate OLS z-score using Numba for a nice speedup\nif MODE == 'OLS':\n vbt_spread, vbt_zscore = rolling_ols_zscore_nb(\n bt_s1_ohlcv['close'].values, \n bt_s2_ohlcv['close'].values, \n PERIOD\n )\nelif MODE == 'log_return':\n vbt_spread, vbt_zscore = rolling_logret_zscore_nb(\n bt_s1_ohlcv['close'].values, \n bt_s2_ohlcv['close'].values, \n PERIOD\n )\nelse:\n raise ValueError(\"Unknown mode\")\nvbt_spread = pd.Series(vbt_spread, index=bt_s1_ohlcv.index, name='spread')\nvbt_zscore = pd.Series(vbt_zscore, index=bt_s1_ohlcv.index, name='zscore')",
"_____no_output_____"
],
[
"# Assert equality of bt and vbt z-score arrays\npd.testing.assert_series_equal(bt_spread, vbt_spread[bt_spread.index])\npd.testing.assert_series_equal(bt_zscore, vbt_zscore[bt_zscore.index])",
"_____no_output_____"
],
[
"# Generate short and long spread signals\nvbt_short_signals = (vbt_zscore > UPPER).rename('short_signals')\nvbt_long_signals = (vbt_zscore < LOWER).rename('long_signals')",
"_____no_output_____"
],
[
"vbt_short_signals, vbt_long_signals = pd.Series.vbt.signals.clean(\n vbt_short_signals, vbt_long_signals, entry_first=False, broadcast_kwargs=dict(columns_from='keep'))\n\ndef plot_spread_and_zscore(spread, zscore):\n fig = vbt.make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.05)\n spread.vbt.plot(add_trace_kwargs=dict(row=1, col=1), fig=fig)\n zscore.vbt.plot(add_trace_kwargs=dict(row=2, col=1), fig=fig)\n vbt_short_signals.vbt.signals.plot_as_exit_markers(zscore, add_trace_kwargs=dict(row=2, col=1), fig=fig)\n vbt_long_signals.vbt.signals.plot_as_entry_markers(zscore, add_trace_kwargs=dict(row=2, col=1), fig=fig)\n fig.update_layout(height=500)\n fig.add_shape(\n type=\"rect\",\n xref='paper',\n yref='y2',\n x0=0,\n y0=UPPER,\n x1=1,\n y1=LOWER,\n fillcolor=\"gray\",\n opacity=0.2,\n layer=\"below\",\n line_width=0,\n )\n return fig\n \nplot_spread_and_zscore(vbt_spread, vbt_zscore).show_svg()",
"_____no_output_____"
],
[
"# Assert equality of bt and vbt signal arrays\npd.testing.assert_series_equal(\n bt_short_signals[bt_short_signals], \n vbt_short_signals[vbt_short_signals]\n)\npd.testing.assert_series_equal(\n bt_long_signals[bt_long_signals], \n vbt_long_signals[vbt_long_signals]\n)",
"_____no_output_____"
],
[
"# Build percentage order size\nsymbol_cols = pd.Index([SYMBOL1, SYMBOL2], name='symbol')\nvbt_order_size = pd.DataFrame(index=bt_s1_ohlcv.index, columns=symbol_cols)\nvbt_order_size[SYMBOL1] = np.nan\nvbt_order_size[SYMBOL2] = np.nan\nvbt_order_size.loc[vbt_short_signals, SYMBOL1] = -ORDER_PCT1\nvbt_order_size.loc[vbt_long_signals, SYMBOL1] = ORDER_PCT1\nvbt_order_size.loc[vbt_short_signals, SYMBOL2] = ORDER_PCT2\nvbt_order_size.loc[vbt_long_signals, SYMBOL2] = -ORDER_PCT2\n\n# Execute at the next bar\nvbt_order_size = vbt_order_size.vbt.fshift(1)\n\nprint(vbt_order_size[~vbt_order_size.isnull().any(axis=1)])",
"symbol PEP KO\n2017-11-15 -0.1 0.1\n2018-04-12 0.1 -0.1\n2018-09-04 -0.1 0.1\n2018-10-03 0.1 -0.1\n2018-12-03 -0.1 0.1\n"
],
[
"# Simulate the portfolio\nvbt_close_price = pd.concat((bt_s1_ohlcv['close'], bt_s2_ohlcv['close']), axis=1, keys=symbol_cols)\nvbt_open_price = pd.concat((bt_s1_ohlcv['open'], bt_s2_ohlcv['open']), axis=1, keys=symbol_cols)\n\ndef simulate_from_orders():\n \"\"\"Simulate using `Portfolio.from_orders`.\"\"\"\n return vbt.Portfolio.from_orders(\n vbt_close_price, # current close as reference price\n size=vbt_order_size, \n price=vbt_open_price, # current open as execution price\n size_type='targetpercent', \n val_price=vbt_close_price.vbt.fshift(1), # previous close as group valuation price\n init_cash=CASH,\n fees=COMMPERC,\n cash_sharing=True, # share capital between assets in the same group\n group_by=True, # all columns belong to the same group\n call_seq='auto', # sell before buying\n freq='d' # index frequency for annualization\n )\n\nvbt_pf = simulate_from_orders()",
"_____no_output_____"
],
[
"print(vbt_pf.orders.records_readable)",
" Order Id Date Column Size Price Fees Side\n0 0 2017-11-15 PEP 96.698241 103.316229 49.952488 Sell\n1 1 2017-11-15 KO 238.385955 41.851497 49.884046 Buy\n2 2 2018-04-12 KO 490.647327 39.652521 97.277017 Sell\n3 3 2018-04-12 PEP 198.056953 98.739352 97.780076 Buy\n4 4 2018-09-04 PEP 198.781680 102.263047 101.640101 Sell\n5 5 2018-09-04 KO 498.975917 40.477607 100.986755 Buy\n6 6 2018-10-03 KO 482.284086 42.524342 102.544068 Sell\n7 7 2018-10-03 PEP 197.454665 100.702245 99.420640 Buy\n8 8 2018-12-03 PEP 189.202087 111.094282 105.096350 Sell\n9 9 2018-12-03 KO 451.211817 46.006429 103.793222 Buy\n"
],
[
"# Proof that both bt and vbt produce the same result\npd.testing.assert_series_equal(bt_cash, vbt_pf.cash().rename('cash'))\npd.testing.assert_series_equal(bt_value, vbt_pf.value().rename('value'))",
"_____no_output_____"
],
[
"print(vbt_pf.stats())",
"Start 2017-01-03 00:00:00\nEnd 2018-12-31 00:00:00\nPeriod 502 days 00:00:00\nStart Value 100000.0\nEnd Value 100284.081822\nTotal Return [%] 0.284082\nBenchmark Return [%] 16.631282\nMax Gross Exposure [%] 0.915879\nTotal Fees Paid 908.374763\nMax Drawdown [%] 1.030291\nMax Drawdown Duration 169 days 00:00:00\nTotal Trades 10\nTotal Closed Trades 8\nTotal Open Trades 2\nOpen Trade P&L 149.652774\nWin Rate [%] 62.5\nBest Trade [%] 9.267971\nWorst Trade [%] -9.229397\nAvg Winning Trade [%] 3.967201\nAvg Losing Trade [%] -6.182852\nAvg Winning Trade Duration 56 days 19:12:00\nAvg Losing Trade Duration 80 days 16:00:00\nProfit Factor 1.072464\nExpectancy 16.803631\nSharpe Ratio 0.185035\nCalmar Ratio 0.200403\nOmega Ratio 1.036058\nSortino Ratio 0.266979\nName: group, dtype: object\n"
],
[
"# Plot portfolio\nfrom functools import partial\n\ndef plot_orders(portfolio, column=None, add_trace_kwargs=None, fig=None):\n portfolio.orders.plot(column=column, add_trace_kwargs=add_trace_kwargs, fig=fig)\n\nvbt_pf.plot(subplots=[\n ('symbol1_orders', dict(\n title=f\"Orders ({SYMBOL1})\",\n yaxis_title=\"Price\",\n check_is_not_grouped=False,\n plot_func=partial(plot_orders, column=SYMBOL1),\n pass_column=False\n )),\n ('symbol2_orders', dict(\n title=f\"Orders ({SYMBOL2})\",\n yaxis_title=\"Price\",\n check_is_not_grouped=False,\n plot_func=partial(plot_orders, column=SYMBOL2),\n pass_column=False\n ))\n]).show_svg()",
"_____no_output_____"
],
[
"# How fast is vbt?\n%timeit simulate_from_orders()",
"3.04 ms ± 5.31 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
],
[
[
"While Portfolio.from_orders is a very convenient and optimized function for simulating portfolios, it requires some prior steps to produce the size array. In the example above, we needed to manually run the calculation of the spread z-score, generate the signals from the z-score, build the size array from the signals, and make sure that all arrays are perfectly aligned. All these steps must be repeated and adapted accordingly once there is more than one hyperparameter combination to test.\n\nNevertheless, dividing the pipeline into clearly separated backtesting steps helps us to analyze each step thoroughly and actually does wonders for strategy development and debugging.",
"_____no_output_____"
],
[
"### Using Portfolio.from_order_func",
"_____no_output_____"
],
[
"Portfolio.from_order_func follows a different (self-contained) approach where as much steps as possible should be defined in the simulation function itself. It sequentially processes timestamps one by one and executes orders based on the logic the user defined rather than parses this logic from some arrays. While this makes order execution less transparent as you cannot analyze each piece of data on the fly anymore (sadly, no pandas and plotting within Numba), it has one big advantage over other vectorized methods: event-driven order processing. This gives best flexibility (you can write any logic), security (less probability of exposing yourself to a look-ahead bias among other biases), and performance (you're traversing the data only once). This method is the most similar one compared to backtrader.",
"_____no_output_____"
]
],
[
[
"from vectorbt.portfolio import nb as portfolio_nb\nfrom vectorbt.base.reshape_fns import flex_select_auto_nb\nfrom vectorbt.portfolio.enums import SizeType, Direction\nfrom collections import namedtuple\n\nMemory = namedtuple(\"Memory\", ('spread', 'zscore', 'status'))\nParams = namedtuple(\"Params\", ('period', 'upper', 'lower', 'order_pct1', 'order_pct2'))\n\n@njit\ndef pre_group_func_nb(c, _period, _upper, _lower, _order_pct1, _order_pct2):\n \"\"\"Prepare the current group (= pair of columns).\"\"\"\n assert c.group_len == 2\n \n # In contrast to bt, we don't have a class instance that we could use to store arrays,\n # so let's create a namedtuple acting as a container for our arrays\n # ( you could also pass each array as a standalone object, but a single object is more convenient)\n spread = np.full(c.target_shape[0], np.nan, dtype=np.float_)\n zscore = np.full(c.target_shape[0], np.nan, dtype=np.float_)\n \n # Note that namedtuples aren't mutable, you can't simply assign a value,\n # thus make status variable an array of one element for an easy assignment\n status = np.full(1, 0, dtype=np.int_)\n memory = Memory(spread, zscore, status)\n \n # Treat each param as an array with value per group, and select the combination of params for this group\n period = flex_select_auto_nb(0, c.group, np.asarray(_period), True)\n upper = flex_select_auto_nb(0, c.group, np.asarray(_upper), True)\n lower = flex_select_auto_nb(0, c.group, np.asarray(_lower), True)\n order_pct1 = flex_select_auto_nb(0, c.group, np.asarray(_order_pct1), True)\n order_pct2 = flex_select_auto_nb(0, c.group, np.asarray(_order_pct2), True)\n \n # Put all params into a container (again, this is optional)\n params = Params(period, upper, lower, order_pct1, order_pct2)\n \n # Create an array that will store our two target percentages used by order_func_nb\n # we do it here instead of in pre_segment_func_nb to initialize the array once, instead of in each row\n size = np.empty(c.group_len, dtype=np.float_)\n \n # The returned tuple is passed as arguments to the function below\n return (memory, params, size)\n \n\n@njit\ndef pre_segment_func_nb(c, memory, params, size, mode):\n \"\"\"Prepare the current segment (= row within group).\"\"\"\n \n # We want to perform calculations once we reach full window size\n if c.i < params.period - 1:\n size[0] = np.nan # size of nan means no order\n size[1] = np.nan\n return (size,)\n \n # z-core is calculated using a window (=period) of spread values\n # This window can be specified as a slice\n window_slice = slice(max(0, c.i + 1 - params.period), c.i + 1)\n \n # Here comes the same as in rolling_ols_zscore_nb\n if mode == 'OLS':\n a = c.close[window_slice, c.from_col]\n b = c.close[window_slice, c.from_col + 1]\n memory.spread[c.i] = ols_spread_nb(a, b)\n elif mode == 'log_return':\n logret_a = np.log(c.close[c.i, c.from_col] / c.close[c.i - 1, c.from_col])\n logret_b = np.log(c.close[c.i, c.from_col + 1] / c.close[c.i - 1, c.from_col + 1])\n memory.spread[c.i] = logret_a - logret_b\n else:\n raise ValueError(\"Unknown mode\")\n spread_mean = np.mean(memory.spread[window_slice])\n spread_std = np.std(memory.spread[window_slice])\n memory.zscore[c.i] = (memory.spread[c.i] - spread_mean) / spread_std\n \n # Check if any bound is crossed\n # Since zscore is calculated using close, use zscore of the previous step\n # This way we are executing signals defined at the previous bar\n # Same logic as in PairTradingStrategy\n if memory.zscore[c.i - 1] > params.upper and memory.status[0] != 1:\n size[0] = -params.order_pct1\n size[1] = params.order_pct2\n \n # Here we specify the order of execution\n # call_seq_now defines order for the current group (2 elements)\n c.call_seq_now[0] = 0\n c.call_seq_now[1] = 1\n memory.status[0] = 1\n elif memory.zscore[c.i - 1] < params.lower and memory.status[0] != 2:\n size[0] = params.order_pct1\n size[1] = -params.order_pct2\n c.call_seq_now[0] = 1 # execute the second order first to release funds early\n c.call_seq_now[1] = 0\n memory.status[0] = 2\n else:\n size[0] = np.nan\n size[1] = np.nan\n \n # Group value is converted to shares using previous close, just like in bt\n # Note that last_val_price contains valuation price of all columns, not just the current pair\n c.last_val_price[c.from_col] = c.close[c.i - 1, c.from_col]\n c.last_val_price[c.from_col + 1] = c.close[c.i - 1, c.from_col + 1]\n \n return (size,)\n\n@njit\ndef order_func_nb(c, size, price, commperc):\n \"\"\"Place an order (= element within group and row).\"\"\"\n \n # Get column index within group (if group starts at column 58 and current column is 59, \n # the column within group is 1, which can be used to get size)\n group_col = c.col - c.from_col\n return portfolio_nb.order_nb(\n size=size[group_col], \n price=price[c.i, c.col],\n size_type=SizeType.TargetPercent,\n fees=commperc\n )",
"_____no_output_____"
],
[
"def simulate_from_order_func():\n \"\"\"Simulate using `Portfolio.from_order_func`.\"\"\"\n return vbt.Portfolio.from_order_func(\n vbt_close_price,\n order_func_nb, \n vbt_open_price.values, COMMPERC, # *args for order_func_nb\n pre_group_func_nb=pre_group_func_nb, \n pre_group_args=(PERIOD, UPPER, LOWER, ORDER_PCT1, ORDER_PCT2),\n pre_segment_func_nb=pre_segment_func_nb, \n pre_segment_args=(MODE,),\n fill_pos_record=False, # a bit faster\n init_cash=CASH,\n cash_sharing=True, \n group_by=True,\n freq='d'\n )\n\nvbt_pf2 = simulate_from_order_func()",
"_____no_output_____"
],
[
"print(vbt_pf2.orders.records_readable)",
" Order Id Date Column Size Price Fees Side\n0 0 2017-11-15 PEP 96.698241 103.316229 49.952488 Sell\n1 1 2017-11-15 KO 238.385955 41.851497 49.884046 Buy\n2 2 2018-04-12 KO 490.647327 39.652521 97.277017 Sell\n3 3 2018-04-12 PEP 198.056953 98.739352 97.780076 Buy\n4 4 2018-09-04 PEP 198.781680 102.263047 101.640101 Sell\n5 5 2018-09-04 KO 498.975917 40.477607 100.986755 Buy\n6 6 2018-10-03 KO 482.284086 42.524342 102.544068 Sell\n7 7 2018-10-03 PEP 197.454665 100.702245 99.420640 Buy\n8 8 2018-12-03 PEP 189.202087 111.094282 105.096350 Sell\n9 9 2018-12-03 KO 451.211817 46.006429 103.793222 Buy\n"
],
[
"# Proof that both bt and vbt produce the same result\npd.testing.assert_series_equal(bt_cash, vbt_pf2.cash().rename('cash'))\npd.testing.assert_series_equal(bt_value, vbt_pf2.value().rename('value'))",
"_____no_output_____"
],
[
"# How fast is vbt?\n%timeit simulate_from_order_func()",
"4.44 ms ± 20.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
],
[
[
"### Numba paradise (or hell?) - fastest",
"_____no_output_____"
]
],
[
[
"def simulate_nb_from_order_func():\n \"\"\"Simulate using `simulate_nb`.\"\"\"\n # iterate over 502 rows and 2 columns, each element is a potential order\n target_shape = vbt_close_price.shape\n \n # number of columns in the group - exactly two\n group_lens = np.array([2])\n \n # build default call sequence (orders are executed from the left to the right column)\n call_seq = portfolio_nb.build_call_seq(target_shape, group_lens)\n \n # initial cash per group\n init_cash = np.array([CASH], dtype=np.float_)\n \n order_records, log_records = portfolio_nb.simulate_nb(\n target_shape=target_shape, \n close=vbt_close_price.values, # used for target percentage, but we override the valuation price\n group_lens=group_lens,\n init_cash=init_cash,\n cash_sharing=True,\n call_seq=call_seq, \n segment_mask=np.full(target_shape, True), # used for disabling some segments\n pre_group_func_nb=pre_group_func_nb, \n pre_group_args=(PERIOD, UPPER, LOWER, ORDER_PCT1, ORDER_PCT2),\n pre_segment_func_nb=pre_segment_func_nb, \n pre_segment_args=(MODE,),\n order_func_nb=order_func_nb, \n order_args=(vbt_open_price.values, COMMPERC),\n fill_pos_record=False\n )\n \n return target_shape, group_lens, call_seq, init_cash, order_records, log_records\n\ntarget_shape, group_lens, call_seq, init_cash, order_records, log_records = simulate_nb_from_order_func()",
"_____no_output_____"
],
[
"# Print order records in a readable format\nprint(vbt.Orders(vbt_close_price.vbt.wrapper, order_records, vbt_close_price).records_readable)",
" Order Id Date Column Size Price Fees Side\n0 0 2017-11-15 PEP 96.698241 103.316229 49.952488 Sell\n1 1 2017-11-15 KO 238.385955 41.851497 49.884046 Buy\n2 2 2018-04-12 KO 490.647327 39.652521 97.277017 Sell\n3 3 2018-04-12 PEP 198.056953 98.739352 97.780076 Buy\n4 4 2018-09-04 PEP 198.781680 102.263047 101.640101 Sell\n5 5 2018-09-04 KO 498.975917 40.477607 100.986755 Buy\n6 6 2018-10-03 KO 482.284086 42.524342 102.544068 Sell\n7 7 2018-10-03 PEP 197.454665 100.702245 99.420640 Buy\n8 8 2018-12-03 PEP 189.202087 111.094282 105.096350 Sell\n9 9 2018-12-03 KO 451.211817 46.006429 103.793222 Buy\n"
],
[
"# Proof that both bt and vbt produce the same cash\nfrom vectorbt.records import nb as records_nb\n\ncol_map = records_nb.col_map_nb(order_records['col'], target_shape[1])\ncash_flow = portfolio_nb.cash_flow_nb(target_shape, order_records, col_map, False)\ncash_flow_grouped = portfolio_nb.cash_flow_grouped_nb(cash_flow, group_lens)\ncash_grouped = portfolio_nb.cash_grouped_nb(target_shape, cash_flow_grouped, group_lens, init_cash)\n\npd.testing.assert_series_equal(bt_cash, bt_cash.vbt.wrapper.wrap(cash_grouped))",
"_____no_output_____"
],
[
"# Proof that both bt and vbt produce the same value\nasset_flow = portfolio_nb.asset_flow_nb(target_shape, order_records, col_map, Direction.All)\nassets = portfolio_nb.assets_nb(asset_flow)\nasset_value = portfolio_nb.asset_value_nb(vbt_close_price.values, assets)\nasset_value_grouped = portfolio_nb.asset_value_grouped_nb(asset_value, group_lens)\nvalue = portfolio_nb.value_nb(cash_grouped, asset_value_grouped)\n\npd.testing.assert_series_equal(bt_value, bt_value.vbt.wrapper.wrap(value))",
"_____no_output_____"
],
[
"# To produce more complex metrics such as stats, it's advisable to use Portfolio,\n# which can be easily constructed from the arguments and outputs of simulate_nb\nvbt_pf3 = vbt.Portfolio(\n wrapper=vbt_close_price.vbt(freq='d', group_by=True).wrapper, \n close=vbt_close_price, \n order_records=order_records, \n log_records=log_records, \n init_cash=init_cash,\n cash_sharing=True, \n call_seq=call_seq\n)\n\nprint(vbt_pf3.stats())",
"Start 2017-01-03 00:00:00\nEnd 2018-12-31 00:00:00\nPeriod 502 days 00:00:00\nStart Value 100000.0\nEnd Value 100284.081822\nTotal Return [%] 0.284082\nBenchmark Return [%] 16.631282\nMax Gross Exposure [%] 0.915879\nTotal Fees Paid 908.374763\nMax Drawdown [%] 1.030291\nMax Drawdown Duration 169 days 00:00:00\nTotal Trades 10\nTotal Closed Trades 8\nTotal Open Trades 2\nOpen Trade P&L 149.652774\nWin Rate [%] 62.5\nBest Trade [%] 9.267971\nWorst Trade [%] -9.229397\nAvg Winning Trade [%] 3.967201\nAvg Losing Trade [%] -6.182852\nAvg Winning Trade Duration 56 days 19:12:00\nAvg Losing Trade Duration 80 days 16:00:00\nProfit Factor 1.072464\nExpectancy 16.803631\nSharpe Ratio 0.185035\nCalmar Ratio 0.200403\nOmega Ratio 1.036058\nSortino Ratio 0.266979\nName: group, dtype: object\n"
],
[
"# How fast is vbt?\n%timeit simulate_nb_from_order_func()",
"2.24 ms ± 3.67 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
]
],
[
[
"As you can see, writing Numba isn't straightforward and requires at least intermediate knowledge of NumPy. That's why Portfolio.from_orders and other class methods based on arrays are usually a good starting point.",
"_____no_output_____"
],
[
"### Multiple parameters",
"_____no_output_____"
],
[
"Now, why waste all energy to port a strategy to vectorbt? Right, for hyperparameter optimization.\n\n*The example below is just for demo purposes, usually brute-forcing many combinations on a single data sample easily leads to overfitting.*",
"_____no_output_____"
]
],
[
[
"periods = np.arange(10, 105, 5)\nuppers = np.arange(1.5, 2.2, 0.1)\nlowers = -1 * np.arange(1.5, 2.2, 0.1)",
"_____no_output_____"
],
[
"def simulate_mult_from_order_func(periods, uppers, lowers):\n \"\"\"Simulate multiple parameter combinations using `Portfolio.from_order_func`.\"\"\"\n # Build param grid\n param_product = vbt.utils.params.create_param_product([periods, uppers, lowers])\n param_tuples = list(zip(*param_product))\n param_columns = pd.MultiIndex.from_tuples(param_tuples, names=['period', 'upper', 'lower'])\n \n # We need two price columns per param combination\n vbt_close_price_mult = vbt_close_price.vbt.tile(len(param_columns), keys=param_columns)\n vbt_open_price_mult = vbt_open_price.vbt.tile(len(param_columns), keys=param_columns)\n \n return vbt.Portfolio.from_order_func(\n vbt_close_price_mult,\n order_func_nb, \n vbt_open_price_mult.values, COMMPERC, # *args for order_func_nb\n pre_group_func_nb=pre_group_func_nb, \n pre_group_args=(\n np.array(param_product[0]), \n np.array(param_product[1]), \n np.array(param_product[2]), \n ORDER_PCT1, \n ORDER_PCT2\n ),\n pre_segment_func_nb=pre_segment_func_nb, \n pre_segment_args=(MODE,),\n fill_pos_record=False,\n init_cash=CASH,\n cash_sharing=True, \n group_by=param_columns.names,\n freq='d'\n )\n\nvbt_pf_mult = simulate_mult_from_order_func(periods, uppers, lowers)",
"_____no_output_____"
],
[
"print(vbt_pf_mult.total_return().sort_values())\n\nvbt_pf_mult.total_return().vbt.histplot().show_svg()",
"period upper lower\n10 1.6 -1.5 -0.068466\n 1.5 -1.5 -0.067897\n 1.8 -1.5 -0.066885\n 1.5 -1.6 -0.065260\n 1.7 -1.5 -0.065036\n ... \n100 2.0 -2.2 0.003538\n 1.9 -2.2 0.003538\n 2.1 -2.2 0.003538\n 1.8 -2.2 0.003538\n 2.2 -2.2 0.003538\nName: total_return, Length: 1216, dtype: float64\n"
],
[
"# How fast is vbt?\n%timeit simulate_mult_from_order_func(periods, uppers, lowers)",
"2.16 s ± 16.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
],
[
[
"Even though the strategy is profitable on paper, the majority of hyperparameter combinations yield a loss, so finding a proper \"slice\" of hyperparameters is just a question of luck when relying on a single backtest. Thanks to vectorbt, we can do thousands of tests in seconds to validate our strategy - the same would last hours using conventional libraries.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7ac5bd1cfe48440de00d45aa7a5ae6835b10658 | 16,735 | ipynb | Jupyter Notebook | Section4b/04JoiningDatasets.ipynb | MBadriNarayanan/YoloV3ForCustomDataset | 5df8adda1d5db95fc471c04f6fb8b5967e522701 | [
"MIT"
] | 2 | 2021-07-05T00:21:35.000Z | 2022-02-05T15:03:39.000Z | Section4b/04JoiningDatasets.ipynb | MBadriNarayanan/YoloV3ForCustomDataset | 5df8adda1d5db95fc471c04f6fb8b5967e522701 | [
"MIT"
] | null | null | null | Section4b/04JoiningDatasets.ipynb | MBadriNarayanan/YoloV3ForCustomDataset | 5df8adda1d5db95fc471c04f6fb8b5967e522701 | [
"MIT"
] | null | null | null | 38.034091 | 104 | 0.507141 | [
[
[
"import os",
"_____no_output_____"
],
[
"\"\"\"\nStart of:\nSetting up full path to directory with joined images\n\"\"\"\n\n# Full or absolute path to the folder with labelled and downloaded images\n# Find it with second Py file getting-full-path.py\n# Pay attention! If you're using Windows, yours path might looks like:\n# r'C:\\Users\\my_name\\Downloads\\Labelled-Custom'\n# or:\n# 'C:\\\\Users\\\\my_name\\\\Downloads\\\\Labelled-Custom'\nfull_path_to_joined_images = \\\n 'C:/Users/badri/Desktop/YoloV3CustomDataset/Section4b/LabelledCustom'\n\n\"\"\"\nEnd of:\nSetting up full path to directory with joined images\n\"\"\"\n\n\n\"\"\"\nStart of:\nGetting list of full paths to joined images\n\"\"\"\n\n# Check point\n# Getting the current directory\n# print(os.getcwd())\n\n# Changing the current directory\n# to one with images\nos.chdir(full_path_to_joined_images)\n\n# Check point\n# Getting the current directory\n# print(os.getcwd())\n\n# Defining list to write paths in\np = []\n\n# Using os.walk for going through all directories\n# and files in them from the current directory\n# Fullstop in os.walk('.') means the current directory\nfor current_dir, dirs, files in os.walk('.'):\n # Going through all files\n for f in files:\n # Checking if filename ends with '.jpeg' or '.jpg'\n if f.endswith('.jpeg') or f.endswith('.jpg'):\n # Preparing path to save into train.txt file\n # Pay attention!\n # If you're using Windows, it might need to change\n # this: + '/' +\n # to this: + '\\' +\n # or to this: + '\\\\' +\n path_to_save_into_txt_files = \\\n full_path_to_joined_images + '/' + f\n\n # Appending the line into the list\n # We use here '\\n' to move to the next line\n # when writing lines into txt files\n p.append(path_to_save_into_txt_files + '\\n')\n\n\n# Slicing first 15% of elements from the list\n# to write into the test.txt file\np_test = p[:int(len(p) * 0.15)]\n\n# Deleting from initial list first 15% of elements\np = p[int(len(p) * 0.15):]\n\n\"\"\"\nEnd of:\nGetting list of full paths to joined images\n\"\"\"\n\n\n\"\"\"\nStart of:\nCreating train.txt and test.txt files\n\"\"\"\n\n# Creating file train.txt and writing 85% of lines in it\nwith open('train.txt', 'w') as train_txt:\n # Going through all elements of the list\n for e in p:\n # Writing current path at the end of the file\n train_txt.write(e)\n\n# Creating file test.txt and writing 15% of lines in it\nwith open('test.txt', 'w') as test_txt:\n # Going through all elements of the list\n for e in p_test:\n # Writing current path at the end of the file\n test_txt.write(e)",
"_____no_output_____"
],
[
"\"\"\"\nStart of:\nSetting up full paths to directories\n\"\"\"\n\n# Full or absolute path to the folder with labelled images\n# Find it with Py file getting-full-path.py\n# Pay attention! If you're using Windows, yours path might looks like:\n# r'C:\\Users\\my_name\\Downloads\\video-to-annotate'\n# or:\n# 'C:\\\\Users\\\\my_name\\\\Downloads\\\\video-to-annotate'\n\nfull_path_to_labelled_images = 'C:/Users/badri/Desktop/YoloV3CustomDataset/Section3'\n\n# Full or absolute path to the folder with downloaded images\n# Find it with Py file getting-full-path.py\n# Pay attention! If you're using Windows, yours path might looks like:\n# r'C:\\Users\\my_name\\OIDv4_ToolKit\\OID\\Dataset\\train\\Car_Bicycle_wheel_Bus'\n# or:\n# 'C:\\\\Users\\\\my_name\\\\OIDv4_ToolKit\\\\OID\\\\Dataset\\\\train\\\\Car_Bicycle_wheel_Bus'\n\n\nfull_path_to_downloaded_images = \\\n 'C:/Users/badri/Desktop/YoloV3CustomDataset/Section4/Dataset/train/Car_Bicycle_wheel_Bus'\n\n# Full or absolute path to the folder with joined images\n# Find it with Py file getting-full-path.py\n# Pay attention! If you're using Windows, yours path might looks like:\n# r'C:\\Users\\my_name\\Downloads\\Labelled-Custom'\n# or:\n# 'C:\\\\Users\\\\my_name\\\\Downloads\\\\Labelled-Custom'\n\n\nfull_path_to_joined_images = \\\n 'C:/Users/badri/Desktop/YoloV3CustomDataset/Section4b/LabelledCustom'\n \n\n\"\"\"\nEnd of:\nSetting up full paths to directories\n\"\"\"\n\n\n\"\"\"\nStart of:\nCreating joined file classes.names\n\"\"\"\n\n# Defining lists for classes from labelled and downloaded data\nclasses_labelled = []\nclasses_downloaded = []\n\n# Defining set for classes from labelled and downloaded data\n# Repeated elements will not be added\nclasses_joined = set()\n\n# Reading existing files classes.names for labelled and downloaded data\n# Adding all classes into one set\n# Appending classes into appropriate lists\n# Pay attention! If you're using Windows, it might need to change\n# this: + '/' +\n# to this: + '\\' +\n# or to this: + '\\\\' +\nwith open(full_path_to_labelled_images + '/' + 'classes.names', 'r') \\\n as names_1, \\\n open(full_path_to_downloaded_images + '/' + 'classes.names', 'r') \\\n as names_2:\n\n # Going through all lines from first file and adding them into set\n # Making all names with lowercase letters\n for line in names_1:\n classes_joined.add(line.lower().strip())\n\n # Appending classes into list\n classes_labelled.append(line.lower().strip())\n\n # Going through all lines from first file and adding them into set\n # Making all names with lowercase letters\n for line in names_2:\n classes_joined.add(line.lower().strip())\n\n # Appending classes into list\n classes_downloaded.append(line.lower().strip())\n\n\n# Converting set into the list with only unique names of classes\nclasses_joined = list(classes_joined)\n\n\n# Creating file classes.names for joined datasets\n# Pay attention! If you're using Windows, it might need to change\n# this: + '/' +\n# to this: + '\\' +\n# or to this: + '\\\\' +\nwith open(full_path_to_joined_images + '/' + 'classes.names', 'w') \\\n as names:\n\n # Writing lists' elements into joined classes.names file\n # By adding '\\n' we move to the next line\n for e in classes_joined:\n names.write(e + '\\n')\n\n\"\"\"\nEnd of:\nCreating joined file classes.names\n\"\"\"\n\n\n\"\"\"\nStart of:\nCreating file joined_data.data\n\"\"\"\n\n# Creating file joined_data.data\n# Pay attention! If you're using Windows, it might need to change\n# this: + '/' +\n# to this: + '\\' +\n# or to this: + '\\\\' +\nwith open(full_path_to_joined_images + '/' + 'joined_data.data', 'w') \\\n as data:\n # Writing needed 5 lines\n # Number of classes\n # By using '\\n' we move to the next line\n data.write('classes = ' + str(len(classes_joined)) + '\\n')\n\n # Location of the train.txt file\n data.write('train = '\n + full_path_to_joined_images + '/' + 'train.txt' + '\\n')\n\n # Location of the test.txt file\n data.write('valid = '\n + full_path_to_joined_images + '/' + 'test.txt' + '\\n')\n\n # Location of the classes.names file\n data.write('names = '\n + full_path_to_joined_images + '/' + 'classes.names' + '\\n')\n\n # Location where to save weights\n data.write('backup = backup')\n\n\"\"\"\nEnd of:\nCreating file joined_data.data\n\"\"\"\n\n\n\"\"\"\nStart of:\nUpdating classes' numbers in annotations from labelled data\n\"\"\"\n\n# Check point\n# Getting the current directory\n# print(os.getcwd())\n\n# Changing the current directory\n# to one with images\nos.chdir(full_path_to_labelled_images)\n\n# Check point\n# Getting the current directory\n# print(os.getcwd())\n\n# Using os.walk for going through all directories\n# and files in them from the current directory\n# Fullstop in os.walk('.') means the current directory\nfor current_dir, dirs, files in os.walk('.'):\n # Going through all files\n for f in files:\n # Checking if filename ends with '.jpeg' or '.jpg'\n if f.endswith('.jpeg') or f.endswith('.jpg'):\n # Slicing from image's name extension\n name_of_txt = f[:-5] if f.endswith('jpeg') else f[:-4]\n\n # Preparing path to annotation txt file from labelled\n # data that has the same name as image file has\n # Pay attention!\n # If you're using Windows, it might need to change\n # this: + '/' +\n # to this: + '\\' +\n # or to this: + '\\\\' +\n path_to_txt_file_labelled = \\\n full_path_to_labelled_images + '/' + \\\n name_of_txt + '.txt'\n\n # Preparing path to annotation txt file for joined\n # data that has the same name as image file has\n # Pay attention!\n # If you're using Windows, it might need to change\n # this: + '/' +\n # to this: + '\\' +\n # or to this: + '\\\\' +\n path_to_txt_file_joined = \\\n full_path_to_joined_images + '/' + \\\n name_of_txt + '.txt'\n\n # Opening annotation txt file from labelled data\n # Updating classes' number in annotation\n # Writing annotation txt file into joined data\n with open(path_to_txt_file_labelled, 'r') as labelled, \\\n open(path_to_txt_file_joined, 'w') as joined:\n # Going through all lines from file\n for line in labelled:\n # Getting current class's number\n c_number = int(line[:1])\n\n # Getting current class's name from labelled data\n c_name = classes_labelled[c_number]\n\n # Getting new class's number\n c_number_updated = classes_joined.index(c_name)\n\n # Updating current annotation line\n line_updated = str(c_number_updated) + line[1:]\n\n # Writing updated annotation line into joined data\n joined.write(line_updated)\n\n\"\"\"\nEnd of:\nUpdating classes' numbers in annotations from labelled data\n\"\"\"\n\n\n\"\"\"\nStart of:\nUpdating classes' numbers in annotations from downloaded data\n\"\"\"\n\n# Check point\n# Getting the current directory\n# print(os.getcwd())\n\n# Changing the current directory\n# to one with images\nos.chdir(full_path_to_downloaded_images)\n\n# Check point\n# Getting the current directory\n# print(os.getcwd())\n\n# Using os.walk for going through all directories\n# and files in them from the current directory\n# Fullstop in os.walk('.') means the current directory\nfor current_dir, dirs, files in os.walk('.'):\n # Going through all files\n for f in files:\n # Checking if filename ends with '.jpeg' or '.jpg'\n if f.endswith('.jpeg') or f.endswith('.jpg'):\n # Slicing from image's name extension\n name_of_txt = f[:-5] if f.endswith('jpeg') else f[:-4]\n\n # Preparing path to annotation txt file from downloaded\n # data that has the same name as image file has\n # Pay attention!\n # If you're using Windows, it might need to change\n # this: + '/' +\n # to this: + '\\' +\n # or to this: + '\\\\' +\n path_to_txt_file_downloaded = \\\n full_path_to_downloaded_images + '/' + \\\n name_of_txt + '.txt'\n\n # Preparing path to annotation txt file for joined\n # data that has the same name as image file has\n # Pay attention!\n # If you're using Windows, it might need to change\n # this: + '/' +\n # to this: + '\\' +\n # or to this: + '\\\\' +\n path_to_txt_file_joined = \\\n full_path_to_joined_images + '/' + \\\n name_of_txt + '.txt'\n\n # Opening annotation txt file from labelled data\n # Updating classes' number in annotation\n # Writing annotation txt file into joined data\n with open(path_to_txt_file_downloaded, 'r') as downloaded, \\\n open(path_to_txt_file_joined, 'w') as joined:\n # Going through all lines from file\n for line in downloaded:\n # Getting current class's number\n c_number = int(line[:1])\n\n # Getting current class's name from downloaded data\n c_name = classes_downloaded[c_number]\n\n # Getting new class's number\n c_number_updated = classes_joined.index(c_name)\n\n # Updating current annotation line\n line_updated = str(c_number_updated) + line[1:]\n\n # Writing updated annotation line into joined data\n joined.write(line_updated)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
e7ac691fdffc9c5e905f2aebfbdc579c20669895 | 40,943 | ipynb | Jupyter Notebook | Company Sector Determination(Text Classification)/mohit_BERT_Embeddings_other_feautures_With_Classifier.ipynb | mohit-bags/BERT-Notebooks | 71971a57d2e1eda701a93fa3bfcca75c2ec95ca8 | [
"MIT"
] | null | null | null | Company Sector Determination(Text Classification)/mohit_BERT_Embeddings_other_feautures_With_Classifier.ipynb | mohit-bags/BERT-Notebooks | 71971a57d2e1eda701a93fa3bfcca75c2ec95ca8 | [
"MIT"
] | null | null | null | Company Sector Determination(Text Classification)/mohit_BERT_Embeddings_other_feautures_With_Classifier.ipynb | mohit-bags/BERT-Notebooks | 71971a57d2e1eda701a93fa3bfcca75c2ec95ca8 | [
"MIT"
] | null | null | null | 40.983984 | 274 | 0.414259 | [
[
[
"import pandas as pd\nimport numpy as np\nimport nltk\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import f1_score\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom nltk.stem.porter import PorterStemmer\n\nimport re\nimport codecs\nimport seaborn as sns\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import f1_score\n\nimport torch\nfrom tqdm.notebook import tqdm\n\nfrom transformers import BertTokenizer\nfrom torch.utils.data import TensorDataset\n\nfrom sklearn.svm import LinearSVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\nfrom sklearn import metrics\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix\nn_jobs=-1",
"_____no_output_____"
],
[
"def clean_text(df, text_field, new_text_field_name):\n df[new_text_field_name] = df[text_field].str.lower()\n df[new_text_field_name] = df[new_text_field_name].apply(lambda elem: re.sub(r\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)|^rt|http.+?\", \"\", elem)) \n df[new_text_field_name] = df[new_text_field_name].apply(lambda elem: re.sub(r\"\\d+\", \"\", elem))\n return df",
"_____no_output_____"
],
[
"# X_train, X_val, y_train, y_val = train_test_split(df.company_description, \n# df.category_id, \n# test_size=0.15, \n# random_state=42, \n# stratify=df.category_id)",
"_____no_output_____"
],
[
"X_train=pd.read_csv('../data/X_train.csv')\nX_test=pd.read_csv('../data/X_test.csv')\ny_train=pd.read_csv('../data/y_train.csv')\ny_test=pd.read_csv('../data/y_test.csv')",
"_____no_output_____"
],
[
"X_train_clean = clean_text(X_train, 'company_description', 'text_clean')\nX_train['company_description'] = X_train_clean['text_clean']\ndel X_train_clean\n\nX_test_clean = clean_text(X_test, 'company_description', 'text_clean')\nX_test['company_description'] = X_test_clean['text_clean']\ndel X_test_clean",
"_____no_output_____"
],
[
"X_train=X_train.drop(['company_address_encoded','company_name','_id','text_clean'],axis=1)\nX_test=X_test.drop(['company_address_encoded','company_name','_id','text_clean'],axis=1)",
"_____no_output_____"
],
[
"X_train = X_train.drop(['company_sector_encoded','company_description'],axis=1)\nX_test = X_test.drop(['company_sector_encoded','company_description'],axis=1)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\n\nX_train = MinMaxScaler().fit_transform(X_train)\nX_test = MinMaxScaler().fit_transform(X_test)",
"_____no_output_____"
],
[
"# # roc curve and auc\n# from sklearn.datasets import make_classification\n# from sklearn.linear_model import LogisticRegression\n# from sklearn.model_selection import train_test_split\n# from sklearn.metrics import roc_curve\n# from sklearn.metrics import roc_auc_score\n# from matplotlib import pyplot\n# # generate 2 class dataset\n# X, y = make_classification(n_samples=1000, n_classes=2, random_state=1)\n# # split into train/test sets\n# trainX, testX, trainy, testy = train_test_split(X, y, test_size=0.5, random_state=2)\n# # generate a no skill prediction (majority class)\n# ns_probs = [0 for _ in range(len(testy))]\n# # fit a model\n# model = LogisticRegression(solver='lbfgs')\n# model.fit(trainX, trainy)\n# # predict probabilities\n# lr_probs = model.predict_proba(testX)\n# # keep probabilities for the positive outcome only\n# lr_probs = lr_probs[:, 1]\n# # calculate scores\n# ns_auc = roc_auc_score(testy, ns_probs)\n# lr_auc = roc_auc_score(testy, lr_probs)\n# # summarize scores\n# print('No Skill: ROC AUC=%.3f' % (ns_auc))\n# print('Logistic: ROC AUC=%.3f' % (lr_auc))\n# # calculate roc curves\n# ns_fpr, ns_tpr, _ = roc_curve(testy, ns_probs)\n# lr_fpr, lr_tpr, _ = roc_curve(testy, lr_probs)\n# # plot the roc curve for the model\n# pyplot.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')\n# pyplot.plot(lr_fpr, lr_tpr, marker='.', label='Logistic')\n# # axis labels\n# pyplot.xlabel('False Positive Rate')\n# pyplot.ylabel('True Positive Rate')\n# # show the legend\n# pyplot.legend()\n# # show the plot\n# pyplot.show()",
"_____no_output_____"
],
[
"# from sentence_transformers import SentenceTransformer\n# bert = SentenceTransformer('stsb-roberta-large') #RoBERTa, an optimized version of BERT by Facebook.",
"_____no_output_____"
],
[
"# # vectorize the data\n# X_train_vec = pd.DataFrame(np.vstack(X_train.company_description.apply(bert.encode)))\n# X_test_vec = pd.DataFrame(np.vstack(X_test.company_description.apply(bert.encode)))",
"_____no_output_____"
],
[
"# X_train_vec.to_csv('../data/bert_encoded_train.csv',index=False)\n# X_test_vec.to_csv('../data/bert_encoded_test.csv',index=False)\n# y_train.to_csv('../data/for_bert_emb_Y_train.csv',index=False)\n# y_test.to_csv('../data/for_bert_emb_Y_test.csv',index=False)",
"_____no_output_____"
],
[
"#reading bert encoded company description\nX_train_vec=pd.read_csv('../data/bert_encoded_train.csv')\nX_test_vec=pd.read_csv('../data/bert_encoded_test.csv')\ny_train=pd.read_csv('../data/for_bert_emb_Y_train.csv')\ny_test=pd.read_csv('../data/for_bert_emb_Y_test.csv')",
"_____no_output_____"
],
[
"X_train_vec = np.concatenate((X_train_vec, X_train),axis = 1)\nX_test_vec = np.concatenate((X_test_vec, X_test),axis = 1)",
"_____no_output_____"
],
[
"# scalar = MinMaxScaler()\n# # fitting\n# scalar.fit(X_train)\n# scaled_data = scalar.transform(X_train)\n\n# # Importing PCA\n# from sklearn.decomposition import PCA\n\n# pca = PCA(n_components = 10)\n# pca.fit(scaled_data)\n# x_pca_train = pca.transform(scaled_data)\n\n# x_pca_train.shape\n\n# scalar.fit(X_test)\n# scaled_data_x_test = scalar.transform(X_test)\n\n# pca = PCA(n_components = 10)\n# pca.fit(scaled_data_x_test)\n# x_pca_test = pca.transform(scaled_data_x_test)\n\n# x_pca_test.shape",
"_____no_output_____"
],
[
"# scalar.fit(X_train_vec)\n# scaled_data_bert_train = scalar.transform(X_train_vec)\n\n# pca = PCA(n_components = 100)\n# pca.fit(scaled_data_bert_train)\n# x_pca_bert_train = pca.transform(scaled_data_bert_train)\n\n# x_pca_bert_train.shape\n\n\n# scalar.fit(X_test_vec)\n# scaled_data_bert_test = scalar.transform(X_test_vec)\n\n# pca = PCA(n_components = 100)\n# pca.fit(scaled_data_bert_test)\n# x_pca_bert_test = pca.transform(scaled_data_bert_test)\n\n# x_pca_bert_test.shape",
"_____no_output_____"
],
[
"y_train=y_train.values.ravel()\ny_test=y_test.values.ravel()",
"_____no_output_____"
],
[
"'''RANDOM FOREST '''\nmodel = RandomForestClassifier(n_estimators=500, n_jobs=-1,verbose=1)\nmodel.fit(X_train_vec, y_train)",
"[Parallel(n_jobs=-1)]: Using backend ThreadingBackend with 6 concurrent workers.\n[Parallel(n_jobs=-1)]: Done 38 tasks | elapsed: 31.6s\n[Parallel(n_jobs=-1)]: Done 188 tasks | elapsed: 2.4min\n[Parallel(n_jobs=-1)]: Done 438 tasks | elapsed: 5.5min\n[Parallel(n_jobs=-1)]: Done 500 out of 500 | elapsed: 6.3min finished\n"
],
[
"model.score(X_test_vec, y_test)",
"[Parallel(n_jobs=6)]: Using backend ThreadingBackend with 6 concurrent workers.\n[Parallel(n_jobs=6)]: Done 38 tasks | elapsed: 0.2s\n[Parallel(n_jobs=6)]: Done 188 tasks | elapsed: 0.8s\n[Parallel(n_jobs=6)]: Done 438 tasks | elapsed: 1.9s\n[Parallel(n_jobs=6)]: Done 500 out of 500 | elapsed: 2.2s finished\n"
],
[
"y_pred=model.predict(X_test_vec)",
"[Parallel(n_jobs=6)]: Using backend ThreadingBackend with 6 concurrent workers.\n[Parallel(n_jobs=6)]: Done 38 tasks | elapsed: 0.2s\n[Parallel(n_jobs=6)]: Done 188 tasks | elapsed: 0.8s\n[Parallel(n_jobs=6)]: Done 438 tasks | elapsed: 1.9s\n[Parallel(n_jobs=6)]: Done 500 out of 500 | elapsed: 2.1s finished\n"
],
[
"# X_train_vec = np.concatenate((x_pca_bert_train, x_pca_train),axis = 1)\n# X_test_vec = np.concatenate((x_pca_bert_test, x_pca_test),axis = 1)",
"_____no_output_____"
],
[
"# #BERT doesn't have feature names, \n# #use your classifier\n# '''RANDOM FOREST '''\n# model = RandomForestClassifier(n_estimators=200, n_jobs=8,verbose=1)\n# model.fit(X_train_vec, y_train)\n\n# # model.score(X_test_vec, y_test)",
"_____no_output_____"
],
[
"print(metrics.classification_report(y_test, y_pred))",
" precision recall f1-score support\n\n 0 0.21 0.78 0.33 1523\n 1 0.86 0.41 0.55 135\n 2 0.42 0.65 0.51 720\n 3 0.57 0.11 0.19 107\n 4 0.00 0.00 0.00 85\n 5 0.32 0.56 0.41 131\n 6 0.42 0.11 0.17 157\n 7 0.00 0.00 0.00 87\n 8 0.00 0.00 0.00 26\n 9 0.25 0.28 0.27 1036\n 10 0.43 0.62 0.51 224\n 11 0.40 0.71 0.51 486\n 12 1.00 0.04 0.08 48\n 13 0.00 0.00 0.00 5\n 14 0.21 0.32 0.25 789\n 15 0.00 0.00 0.00 56\n 16 0.43 0.06 0.10 53\n 17 0.00 0.00 0.00 117\n 18 0.00 0.00 0.00 37\n 19 0.61 0.45 0.52 232\n 20 0.00 0.00 0.00 76\n 21 0.67 0.01 0.02 196\n 22 0.00 0.00 0.00 145\n 23 0.00 0.00 0.00 24\n 24 0.00 0.00 0.00 13\n 25 0.59 0.10 0.17 98\n 26 0.67 0.09 0.15 117\n 27 0.00 0.00 0.00 31\n 28 0.00 0.00 0.00 28\n 29 1.00 0.03 0.06 185\n 30 1.00 0.11 0.20 36\n 31 0.65 0.25 0.36 146\n 32 0.00 0.00 0.00 38\n 33 0.67 0.06 0.11 68\n 34 1.00 0.02 0.04 48\n 35 0.50 0.01 0.03 75\n 36 0.00 0.00 0.00 9\n 37 0.91 0.11 0.20 89\n 38 0.65 0.12 0.20 92\n 39 0.47 0.51 0.49 126\n 40 0.75 0.22 0.34 82\n 41 0.87 0.55 0.67 62\n 42 0.00 0.00 0.00 66\n 43 0.49 0.71 0.58 169\n 44 0.64 0.46 0.54 141\n 45 0.48 0.25 0.33 127\n 46 0.67 0.05 0.10 75\n 47 0.75 0.09 0.16 69\n 48 0.49 0.52 0.50 124\n 49 0.00 0.00 0.00 5\n 50 0.00 0.00 0.00 9\n 51 0.00 0.00 0.00 22\n 52 0.00 0.00 0.00 39\n 53 0.00 0.00 0.00 53\n 54 0.00 0.00 0.00 77\n 55 0.00 0.00 0.00 58\n 56 0.00 0.00 0.00 75\n 57 1.00 0.01 0.02 86\n 58 1.00 0.01 0.02 115\n 59 0.35 0.16 0.22 177\n 60 0.00 0.00 0.00 15\n 61 0.31 0.05 0.08 102\n 62 0.59 0.27 0.37 188\n 63 0.00 0.00 0.00 46\n 64 0.00 0.00 0.00 68\n 65 0.00 0.00 0.00 38\n 66 0.00 0.00 0.00 37\n 67 0.59 0.50 0.54 191\n 68 0.00 0.00 0.00 19\n 69 0.00 0.00 0.00 57\n 70 0.00 0.00 0.00 9\n 71 0.00 0.00 0.00 33\n 72 1.00 0.04 0.08 24\n 73 0.70 0.23 0.35 81\n 74 0.43 0.48 0.45 194\n 75 0.00 0.00 0.00 45\n 76 1.00 0.02 0.03 65\n 77 0.56 0.34 0.42 107\n 78 1.00 0.03 0.06 32\n 79 0.00 0.00 0.00 23\n 80 0.00 0.00 0.00 28\n 81 0.44 0.24 0.31 146\n 82 0.00 0.00 0.00 46\n 83 0.00 0.00 0.00 30\n 84 0.00 0.00 0.00 36\n 85 0.00 0.00 0.00 20\n 86 0.00 0.00 0.00 27\n 87 0.00 0.00 0.00 9\n 88 0.65 0.26 0.37 99\n 89 0.00 0.00 0.00 15\n 90 0.00 0.00 0.00 18\n 91 0.00 0.00 0.00 28\n 92 0.00 0.00 0.00 81\n 93 0.15 0.02 0.03 123\n 94 0.00 0.00 0.00 81\n 95 0.00 0.00 0.00 46\n 96 0.00 0.00 0.00 51\n 97 0.00 0.00 0.00 22\n 98 0.00 0.00 0.00 58\n 99 0.67 0.07 0.13 82\n 100 0.00 0.00 0.00 11\n 101 0.00 0.00 0.00 21\n 102 0.00 0.00 0.00 33\n 103 0.00 0.00 0.00 91\n 104 1.00 0.04 0.07 26\n 105 0.00 0.00 0.00 40\n 106 0.00 0.00 0.00 37\n 107 0.00 0.00 0.00 14\n 108 0.00 0.00 0.00 5\n 109 0.00 0.00 0.00 6\n 110 1.00 0.02 0.04 53\n 111 0.00 0.00 0.00 15\n 112 0.00 0.00 0.00 23\n 113 0.00 0.00 0.00 11\n 114 0.00 0.00 0.00 6\n 115 0.00 0.00 0.00 10\n 116 0.00 0.00 0.00 36\n 117 0.00 0.00 0.00 25\n 118 0.00 0.00 0.00 12\n 119 0.00 0.00 0.00 4\n 120 0.00 0.00 0.00 31\n 121 0.00 0.00 0.00 2\n 122 0.00 0.00 0.00 15\n 123 0.00 0.00 0.00 15\n 124 0.00 0.00 0.00 4\n 125 0.00 0.00 0.00 13\n 126 0.00 0.00 0.00 11\n 127 0.00 0.00 0.00 19\n 128 0.00 0.00 0.00 16\n 129 0.00 0.00 0.00 41\n 130 0.00 0.00 0.00 25\n 131 0.00 0.00 0.00 14\n 132 0.00 0.00 0.00 26\n 133 0.00 0.00 0.00 7\n 134 0.00 0.00 0.00 9\n 135 0.00 0.00 0.00 6\n 136 0.00 0.00 0.00 10\n 137 0.00 0.00 0.00 2\n 139 0.00 0.00 0.00 1\n 140 0.00 0.00 0.00 4\n 141 0.00 0.00 0.00 11\n 142 0.00 0.00 0.00 1\n 143 0.00 0.00 0.00 3\n 144 0.00 0.00 0.00 3\n 145 0.00 0.00 0.00 1\n 146 0.00 0.00 0.00 1\n\n accuracy 0.31 12515\n macro avg 0.22 0.08 0.09 12515\nweighted avg 0.35 0.31 0.25 12515\n\n"
],
[
"LR_model = LogisticRegression(n_jobs=-1,verbose=True)\nLR_model.fit(X_train_vec, y_train)\ny_pred = LR_model.predict(X_test_vec)\nacc_score = LR_model.score(X_test_vec, y_test)\nprint(acc_score)",
"[Parallel(n_jobs=-1)]: Using backend LokyBackend with 6 concurrent workers.\n[Parallel(n_jobs=-1)]: Done 1 out of 1 | elapsed: 2.5min finished\n"
],
[
"print(metrics.classification_report(y_test, y_pred))",
" precision recall f1-score support\n\n 0 0.45 0.49 0.47 1523\n 1 0.80 0.76 0.78 135\n 2 0.55 0.67 0.61 720\n 3 0.38 0.49 0.43 107\n 4 0.24 0.16 0.20 85\n 5 0.42 0.48 0.45 131\n 6 0.41 0.43 0.42 157\n 7 0.29 0.22 0.25 87\n 8 0.23 0.12 0.15 26\n 9 0.41 0.41 0.41 1036\n 10 0.48 0.61 0.54 224\n 11 0.57 0.64 0.60 486\n 12 0.58 0.54 0.56 48\n 13 0.17 0.20 0.18 5\n 14 0.34 0.32 0.33 789\n 15 0.18 0.12 0.15 56\n 16 0.45 0.49 0.47 53\n 17 0.49 0.28 0.36 117\n 18 0.42 0.38 0.40 37\n 19 0.65 0.69 0.67 232\n 20 0.36 0.39 0.38 76\n 21 0.36 0.36 0.36 196\n 22 0.30 0.28 0.29 145\n 23 0.35 0.29 0.32 24\n 24 0.00 0.00 0.00 13\n 25 0.58 0.43 0.49 98\n 26 0.54 0.65 0.59 117\n 27 0.12 0.10 0.11 31\n 28 0.40 0.14 0.21 28\n 29 0.56 0.61 0.59 185\n 30 0.49 0.72 0.58 36\n 31 0.58 0.57 0.57 146\n 32 0.38 0.39 0.39 38\n 33 0.31 0.26 0.29 68\n 34 0.34 0.44 0.38 48\n 35 0.40 0.44 0.42 75\n 36 0.50 0.56 0.53 9\n 37 0.71 0.54 0.61 89\n 38 0.43 0.48 0.45 92\n 39 0.56 0.64 0.60 126\n 40 0.44 0.51 0.47 82\n 41 0.70 0.76 0.73 62\n 42 0.43 0.41 0.42 66\n 43 0.61 0.68 0.64 169\n 44 0.66 0.75 0.70 141\n 45 0.38 0.42 0.40 127\n 46 0.56 0.48 0.52 75\n 47 0.36 0.43 0.39 69\n 48 0.61 0.52 0.56 124\n 49 0.00 0.00 0.00 5\n 50 0.00 0.00 0.00 9\n 51 0.43 0.41 0.42 22\n 52 0.47 0.44 0.45 39\n 53 0.47 0.53 0.50 53\n 54 0.71 0.68 0.69 77\n 55 0.16 0.05 0.08 58\n 56 0.41 0.33 0.37 75\n 57 0.21 0.17 0.19 86\n 58 0.28 0.24 0.26 115\n 59 0.33 0.31 0.31 177\n 60 0.50 0.20 0.29 15\n 61 0.35 0.34 0.34 102\n 62 0.53 0.47 0.50 188\n 63 0.45 0.30 0.36 46\n 64 0.42 0.44 0.43 68\n 65 0.33 0.42 0.37 38\n 66 0.31 0.32 0.32 37\n 67 0.59 0.69 0.64 191\n 68 0.43 0.32 0.36 19\n 69 0.62 0.40 0.49 57\n 70 0.22 0.22 0.22 9\n 71 0.30 0.27 0.29 33\n 72 0.55 0.50 0.52 24\n 73 0.66 0.63 0.65 81\n 74 0.53 0.60 0.56 194\n 75 0.21 0.13 0.16 45\n 76 0.48 0.62 0.54 65\n 77 0.55 0.65 0.60 107\n 78 0.44 0.34 0.39 32\n 79 0.50 0.22 0.30 23\n 80 0.60 0.43 0.50 28\n 81 0.40 0.50 0.44 146\n 82 0.68 0.46 0.55 46\n 83 0.41 0.53 0.46 30\n 84 0.30 0.22 0.25 36\n 85 0.71 0.75 0.73 20\n 86 0.50 0.52 0.51 27\n 87 0.00 0.00 0.00 9\n 88 0.55 0.52 0.53 99\n 89 0.11 0.07 0.08 15\n 90 0.36 0.22 0.28 18\n 91 0.35 0.25 0.29 28\n 92 0.39 0.42 0.40 81\n 93 0.29 0.27 0.28 123\n 94 0.34 0.32 0.33 81\n 95 0.46 0.48 0.47 46\n 96 0.47 0.45 0.46 51\n 97 0.33 0.23 0.27 22\n 98 0.33 0.22 0.27 58\n 99 0.56 0.61 0.58 82\n 100 0.86 0.55 0.67 11\n 101 0.37 0.52 0.43 21\n 102 0.35 0.24 0.29 33\n 103 0.31 0.18 0.23 91\n 104 0.35 0.50 0.41 26\n 105 0.47 0.40 0.43 40\n 106 0.68 0.51 0.58 37\n 107 0.00 0.00 0.00 14\n 108 0.40 0.40 0.40 5\n 109 0.40 0.33 0.36 6\n 110 0.51 0.42 0.46 53\n 111 0.29 0.13 0.18 15\n 112 0.46 0.52 0.49 23\n 113 0.20 0.09 0.13 11\n 114 0.00 0.00 0.00 6\n 115 0.33 0.10 0.15 10\n 116 0.19 0.08 0.12 36\n 117 0.46 0.24 0.32 25\n 118 0.25 0.17 0.20 12\n 119 0.40 0.50 0.44 4\n 120 0.00 0.00 0.00 31\n 121 0.00 0.00 0.00 2\n 122 0.00 0.00 0.00 15\n 123 0.57 0.53 0.55 15\n 124 0.00 0.00 0.00 4\n 125 0.33 0.31 0.32 13\n 126 0.17 0.09 0.12 11\n 127 0.67 0.63 0.65 19\n 128 0.20 0.19 0.19 16\n 129 0.35 0.39 0.37 41\n 130 0.27 0.32 0.29 25\n 131 0.32 0.43 0.36 14\n 132 0.35 0.31 0.33 26\n 133 0.20 0.14 0.17 7\n 134 0.33 0.33 0.33 9\n 135 0.00 0.00 0.00 6\n 136 0.50 0.10 0.17 10\n 137 0.00 0.00 0.00 2\n 139 0.00 0.00 0.00 1\n 140 0.33 0.25 0.29 4\n 141 0.83 0.45 0.59 11\n 142 0.00 0.00 0.00 1\n 143 0.00 0.00 0.00 3\n 144 0.00 0.00 0.00 3\n 145 0.00 0.00 0.00 1\n 146 0.00 0.00 0.00 1\n\n accuracy 0.46 12515\n macro avg 0.38 0.35 0.35 12515\nweighted avg 0.45 0.46 0.45 12515\n\n"
],
[
"from sklearn.svm import SVC\n\nclf = SVC(kernel='linear', C = 1.0)\nclf.fit(X_train_vec,y_train)\ny_pred = clf.predict(X_test_vec)\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))",
"Accuracy: 0.43531761885737114\n"
],
[
"'''SVM'''\nfrom sklearn.multiclass import OneVsRestClassifier\nclf = OneVsRestClassifier(SVC(kernel='linear', probability=True,verbose=True), n_jobs=-1)\n# model = LinearSVC(verbose=1,n_jobs=-1)\nclf.fit(X_train_vec, y_train)",
"_____no_output_____"
],
[
"clf.score(X_test_vec, y_test)",
"_____no_output_____"
],
[
"y_pred = clf.predict(X_test_vec)\nprint(metrics.classification_report(y_test, y_pred)",
"_____no_output_____"
],
[
"conf_mat = confusion_matrix(y_test, y_pred)\nfig, ax = plt.subplots(figsize=(10,10))\nsns.heatmap(conf_mat, annot=True, fmt='d',\n xticklabels=df.company_industry.values, yticklabels=df.company_industry.values)\nplt.ylabel('Actual')\nplt.xlabel('Predicted')\nplt.show()",
"_____no_output_____"
],
[
"y_train=y_train.values.ravel()\ny_test=y_test.values.ravel()",
"_____no_output_____"
],
[
"import time\nimport numpy as np\nfrom sklearn.ensemble import BaggingClassifier, RandomForestClassifier\nfrom sklearn import datasets\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import SVC\n\nX=X_train\ny=y_train\n\nstart = time.time()\nclf = OneVsRestClassifier(SVC(kernel='linear', probability=True, class_weight='auto'.n_jobs=-1,verbose=1))\nclf.fit(X, y)\nend = time.time()\nprint \"Single SVC\", end - start, clf.score(X,y)\nproba = clf.predict_proba(X)\n\nn_estimators = 10\nstart = time.time()\nclf = OneVsRestClassifier(BaggingClassifier(SVC(kernel='linear', probability=True, class_weight='auto',n_jobs=-1,verbose=1), max_samples=1.0 / n_estimators, n_estimators=n_estimators))\nclf.fit(X, y)\nend = time.time()\nprint \"Bagging SVC\", end - start, clf.score(X,y)\nproba = clf.predict_proba(X)\n\nstart = time.time()\nclf = RandomForestClassifier(min_samples_leaf=20,n_jobs=-1,verbose=True)\nclf.fit(X, y)\nend = time.time()\nprint \"Random Forest\", end - start, clf.score(X,y)\nproba = clf.predict_proba(X)",
"_____no_output_____"
],
[
"from sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import plot_precision_recall_curve\nimport matplotlib.pyplot as plt\n\ndisp = plot_precision_recall_curve(classifier, X_test, y_test)\ndisp.ax_.set_title('2-class Precision-Recall curve: '\n 'AP={0:0.2f}'.format(average_precision))",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ac773a5e49dfe68a4c953ef40a2acab190956b | 55,223 | ipynb | Jupyter Notebook | stock_fit.ipynb | LiziCyber/tabnet | 9ccc5e50210f1aff6b49559655c4e0d93fdf00e2 | [
"MIT"
] | null | null | null | stock_fit.ipynb | LiziCyber/tabnet | 9ccc5e50210f1aff6b49559655c4e0d93fdf00e2 | [
"MIT"
] | null | null | null | stock_fit.ipynb | LiziCyber/tabnet | 9ccc5e50210f1aff6b49559655c4e0d93fdf00e2 | [
"MIT"
] | null | null | null | 85.883359 | 12,271 | 0.841696 | [
[
[
"from pytorch_tabnet.tab_modelx import TabNetRegressor\n\nimport torch\nfrom torch.utils.data import Dataset\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import roc_auc_score\n\nimport pandas as pd\nimport numpy as np\n\n\nimport os\nimport wget\nfrom pathlib import Path\n\nfrom matplotlib import pyplot as plt\n\nnp.random.seed(0)\n%matplotlib inline",
"_____no_output_____"
],
[
"LENGTH = 1024",
"_____no_output_____"
],
[
"all_data = pd.read_csv(\"../data/000001.csv\")[\"vwap\"]",
"_____no_output_____"
],
[
"class DatasetRetriever(Dataset):\n\n def __init__(self, raw_data,\n X_len=LENGTH,\n y_len=1,\n if_X=True,\n if_y=True):\n super().__init__()\n self.raw_data = raw_data.reset_index(drop=True)\n self.X_len = X_len\n self.y_len = y_len\n self.if_X = if_X\n self.if_y = if_y\n\n def __getitem__(self, index: int):\n end = index + self.X_len\n if self.if_X and self.if_y:\n return self.raw_data[index : end].to_numpy(), self.raw_data[end].reshape(-1)\n elif self.if_X:\n return self.raw_data[index : end].to_numpy()\n elif self.if_y:\n return self.raw_data[end].reshape(-1)\n else:\n raise Exception\n def __len__(self) -> int:\n return self.raw_data.shape[0] - self.X_len\n @property\n def shape(self):\n if self.if_X and self.if_y:\n return len(self), len(self[0][0])\n elif self.if_X:\n return len(self), len(self[0])\n else:\n return len(self), len(self[0])",
"_____no_output_____"
],
[
"train = DatasetRetriever(all_data[:10000])\nX_train = DatasetRetriever(all_data[:10000], if_y=False)\ny_train = DatasetRetriever(all_data[:10000], if_X=False)\n\nvalid = DatasetRetriever(all_data[10000:12000])\nX_valid = DatasetRetriever(all_data[10000:12000], if_y=False)\ny_valid = DatasetRetriever(all_data[10000:12000], if_X=False)",
"_____no_output_____"
],
[
"from pytorch_tabnet.pretrainingx import TabNetPretrainer",
"_____no_output_____"
],
[
"# TabNetPretrainer\nunsupervised_model = TabNetPretrainer(\n optimizer_fn=torch.optim.Adam,\n optimizer_params=dict(lr=2e-2),\n mask_type=\"sparsemax\",\n net_name=\"tabnetm\"\n)",
"Device used : cuda\n"
],
[
"max_epochs = 1 if not os.getenv(\"CI\", False) else 2",
"_____no_output_____"
],
[
"unsupervised_model.fit(\n train_dataset=X_train,\n eval_datasets=[X_valid],\n max_epochs=max_epochs , patience=5,\n batch_size=128, virtual_batch_size=128,\n num_workers=0,\n drop_last=False,\n pretraining_ratio=0.8,\n)\n",
"100%|██████████| 71/71 [00:12<00:00, 5.78it/s]\n100%|██████████| 8/8 [00:00<00:00, 20.87it/s]\n"
],
[
"unsupervised_model.save_model('./test_pretrain')",
"Successfully saved model at ./test_pretrain.zip\n"
],
[
"loaded_pretrain = TabNetPretrainer()\nloaded_pretrain.load_model('./test_pretrain.zip')",
"Device used : cuda\nDevice used : cuda\n"
],
[
"reg = TabNetRegressor(optimizer_fn=torch.optim.Adam,\n optimizer_params=dict(lr=2e-2),\n scheduler_params={\"step_size\":10, # how to use learning rate scheduler\n \"gamma\":0.9},\n scheduler_fn=torch.optim.lr_scheduler.StepLR,\n mask_type='sparsemax' # This will be overwritten if using pretrain model\n )",
"Device used : cuda\n"
],
[
"reg.fit(\n train_dataset=train,\n eval_datasets=[valid],\n eval_name=['valid'],\n eval_metric=['mae'],\n max_epochs=2 , patience=20,\n batch_size=128, virtual_batch_size=128,\n num_workers=0,\n weights=0,\n drop_last=False,\n from_unsupervised=loaded_pretrain\n)",
"Loading weights from unsupervised pretraining\nepoch 0 | loss: 4.56359 | valid_mae: 1.40906 | 0:00:07s\nepoch 1 | loss: 0.17127 | valid_mae: 0.23881 | 0:00:15s\nStop training because you reached max_epochs = 2 with best_epoch = 1 and best_valid_mae = 0.23881\nBest weights from best epoch are automatically used!\n"
],
[
"# plot losses\nplt.plot(reg.history['loss'])",
"_____no_output_____"
],
[
"# plot mae\nplt.plot(reg.history['valid_mae'])",
"_____no_output_____"
],
[
"# plot learning rates\nplt.plot(reg.history['lr'])",
"_____no_output_____"
]
],
[
[
"## Predictions",
"_____no_output_____"
]
],
[
[
"'''preds = reg.predict_proba(X_test)\n\npreds_valid = clf.predict_proba(X_valid)\n\nprint(f\"BEST VALID SCORE FOR {dataset_name} : {clf.best_cost}\")\nprint(f\"FINAL TEST SCORE FOR {dataset_name} : {test_auc}\")'''",
"_____no_output_____"
]
],
[
[
"# Save and load Model",
"_____no_output_____"
]
],
[
[
"# save tabnet model\nsaving_path_name = \"./tabnet_model_test_1\"\nsaved_filepath = reg.save_model(saving_path_name)",
"Successfully saved model at ./tabnet_model_test_1.zip\n"
],
[
"# define new model with basic parameters and load state dict weights\nloaded_reg = TabNetRegressor()\nloaded_reg.load_model(saved_filepath)",
"_____no_output_____"
]
],
[
[
"# Global explainability : feat importance summing to 1",
"_____no_output_____"
]
],
[
[
"reg.feature_importances_",
"_____no_output_____"
]
],
[
[
"# Local explainability and masks",
"_____no_output_____"
]
],
[
[
"explain_matrix, masks = reg.explain(X_valid)",
"_____no_output_____"
],
[
"fig, axs = plt.subplots(1, 3, figsize=(20,20))\n\nfor i in range(3):\n axs[i].imshow(masks[i][:50])\n axs[i].set_title(f\"mask {i}\")\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7ac90b60b99b055f61d8d4af9a16db077f58298 | 416,798 | ipynb | Jupyter Notebook | notebooks/1-Using-ImageJ/Ops/transform/dropSingletonDimensionsView.ipynb | LorenzoScanu/MaterialeTirocinio | c78764438d774295d00fc8a4273e4c4f25c8ad46 | [
"CC0-1.0"
] | null | null | null | notebooks/1-Using-ImageJ/Ops/transform/dropSingletonDimensionsView.ipynb | LorenzoScanu/MaterialeTirocinio | c78764438d774295d00fc8a4273e4c4f25c8ad46 | [
"CC0-1.0"
] | null | null | null | notebooks/1-Using-ImageJ/Ops/transform/dropSingletonDimensionsView.ipynb | LorenzoScanu/MaterialeTirocinio | c78764438d774295d00fc8a4273e4c4f25c8ad46 | [
"CC0-1.0"
] | null | null | null | 1,422.518771 | 221,793 | 0.96298 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7ac928033982c5f2b341020b7884a1a2921538c | 385,987 | ipynb | Jupyter Notebook | Other_Python/Latent_Dirichlet_Allocation/.ipynb_checkpoints/Choi_NMF_Automated-checkpoint.ipynb | Romit-Maulik/Tutorials-Demos-Practice | a58ddc819f24a16f7059e63d7f201fc2cd23e03a | [
"MIT"
] | 8 | 2020-09-02T14:46:07.000Z | 2021-11-29T15:27:05.000Z | Other_Python/Latent_Dirichlet_Allocation/.ipynb_checkpoints/Choi_NMF_Automated-checkpoint.ipynb | Romit-Maulik/Tutorials-Demos-Practice | a58ddc819f24a16f7059e63d7f201fc2cd23e03a | [
"MIT"
] | 18 | 2020-11-13T18:49:33.000Z | 2022-03-12T00:54:43.000Z | Other_Python/Latent_Dirichlet_Allocation/.ipynb_checkpoints/Choi_NMF_Automated-checkpoint.ipynb | Romit-Maulik/Tutorials-Demos-Practice | a58ddc819f24a16f7059e63d7f201fc2cd23e03a | [
"MIT"
] | 5 | 2019-09-25T23:57:00.000Z | 2021-04-18T08:15:34.000Z | 932.335749 | 62,880 | 0.933855 | [
[
[
"import warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
],
[
"import os\nimport numpy as np\nfrom glob import glob\nfrom time import time\nimport matplotlib.pyplot as plt\nfrom striprtf.striprtf import rtf_to_text\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.decomposition import NMF, LatentDirichletAllocation\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\nn_features = 30\nn_components = 3 # Number of topics\nn_top_words = 10 # Number of top words",
"_____no_output_____"
],
[
"stop_words = [\"0o\", \"0s\", \"3a\", \"3b\", \"mr.\", \"dr.\", \"000\", \"19\", \"year\", \"people\", \"years\", \"time\", \"times\", \"3d\", \"6b\", \"6o\", \"today\", \"a\", \"a1\", \"a2\", \"a3\", \"a4\", \"ab\", \"able\", \"about\", \"above\", \"abst\", \"ac\", \"accordance\", \"according\", \"accordingly\", \"across\", \"act\", \"actually\", \"ad\", \"added\", \"adj\", \"ae\", \"af\", \"affected\", \"affecting\", \"affects\", \"after\", \"afterwards\", \"ag\", \"again\", \"against\", \"ah\", \"ain\", \"ain't\", \"aj\", \"al\", \"all\", \"allow\", \"allows\", \"almost\", \"alone\", \"along\", \"already\", \"also\", \"although\", \"always\", \"am\", \"among\", \"amongst\", \"amoungst\", \"amount\", \"an\", \"and\", \"announce\", \"another\", \"any\", \"anybody\", \"anyhow\", \"anymore\", \"anyone\", \"anything\", \"anyway\", \"anyways\", \"anywhere\", \"ao\", \"ap\", \"apart\", \"apparently\", \"appear\", \"appreciate\", \"appropriate\", \"approximately\", \"ar\", \"are\", \"aren\", \"arent\", \"aren't\", \"arise\", \"around\", \"as\", \"a's\", \"aside\", \"ask\", \"asking\", \"associated\", \"at\", \"au\", \"auth\", \"av\", \"available\", \"aw\", \"away\", \"awfully\", \"ax\", \"ay\", \"az\", \"b\", \"b1\", \"b2\", \"b3\", \"ba\", \"back\", \"bc\", \"bd\", \"be\", \"became\", \"because\", \"become\", \"becomes\", \"becoming\", \"been\", \"before\", \"beforehand\", \"begin\", \"beginning\", \"beginnings\", \"begins\", \"behind\", \"being\", \"believe\", \"below\", \"beside\", \"besides\", \"best\", \"better\", \"between\", \"beyond\", \"bi\", \"bill\", \"biol\", \"bj\", \"bk\", \"bl\", \"bn\", \"both\", \"bottom\", \"bp\", \"br\", \"brief\", \"briefly\", \"bs\", \"bt\", \"bu\", \"but\", \"bx\", \"by\", \"c\", \"c1\", \"c2\", \"c3\", \"ca\", \"call\", \"came\", \"can\", \"cannot\", \"cant\", \"can't\", \"cause\", \"causes\", \"cc\", \"cd\", \"ce\", \"certain\", \"certainly\", \"cf\", \"cg\", \"ch\", \"changes\", \"ci\", \"cit\", \"cj\", \"cl\", \"clearly\", \"cm\", \"c'mon\", \"cn\", \"co\", \"com\", \"come\", \"comes\", \"con\", \"concerning\", \"consequently\", \"consider\", \"considering\", \"contain\", \"containing\", \"contains\", \"corresponding\", \"could\", \"couldn\", \"couldnt\", \"couldn't\", \"course\", \"cp\", \"cq\", \"cr\", \"cry\", \"cs\", \"c's\", \"ct\", \"cu\", \"currently\", \"cv\", \"cx\", \"cy\", \"cz\", \"d\", \"d2\", \"da\", \"date\", \"dc\", \"dd\", \"de\", \"definitely\", \"describe\", \"described\", \"despite\", \"detail\", \"df\", \"di\", \"did\", \"didn\", \"didn't\", \"different\", \"dj\", \"dk\", \"dl\", \"do\", \"does\", \"doesn\", \"doesn't\", \"doing\", \"don\", \"done\", \"don't\", \"down\", \"downwards\", \"dp\", \"dr\", \"ds\", \"dt\", \"du\", \"due\", \"during\", \"dx\", \"dy\", \"e\", \"e2\", \"e3\", \"ea\", \"each\", \"ec\", \"ed\", \"edu\", \"ee\", \"ef\", \"effect\", \"eg\", \"ei\", \"eight\", \"eighty\", \"either\", \"ej\", \"el\", \"eleven\", \"else\", \"elsewhere\", \"em\", \"empty\", \"en\", \"end\", \"ending\", \"enough\", \"entirely\", \"eo\", \"ep\", \"eq\", \"er\", \"es\", \"especially\", \"est\", \"et\", \"et-al\", \"etc\", \"eu\", \"ev\", \"even\", \"ever\", \"every\", \"everybody\", \"everyone\", \"everything\", \"everywhere\", \"ex\", \"exactly\", \"example\", \"except\", \"ey\", \"f\", \"f2\", \"fa\", \"far\", \"fc\", \"few\", \"ff\", \"fi\", \"fifteen\", \"fifth\", \"fify\", \"fill\", \"find\", \"fire\", \"first\", \"five\", \"fix\", \"fj\", \"fl\", \"fn\", \"fo\", \"followed\", \"following\", \"follows\", \"for\", \"former\", \"formerly\", \"forth\", \"forty\", \"found\", \"four\", \"fr\", \"from\", \"front\", \"fs\", \"ft\", \"fu\", \"full\", \"further\", \"furthermore\", \"fy\", \"g\", \"ga\", \"gave\", \"ge\", \"get\", \"gets\", \"getting\", \"gi\", \"give\", \"given\", \"gives\", \"giving\", \"gj\", \"gl\", \"go\", \"goes\", \"going\", \"gone\", \"got\", \"gotten\", \"gr\", \"greetings\", \"gs\", \"gy\", \"h\", \"h2\", \"h3\", \"had\", \"hadn\", \"hadn't\", \"happens\", \"hardly\", \"has\", \"hasn\", \"hasnt\", \"hasn't\", \"have\", \"haven\", \"haven't\", \"having\", \"he\", \"hed\", \"he'd\", \"he'll\", \"hello\", \"help\", \"hence\", \"her\", \"here\", \"hereafter\", \"hereby\", \"herein\", \"heres\", \"here's\", \"hereupon\", \"hers\", \"herself\", \"hes\", \"he's\", \"hh\", \"hi\", \"hid\", \"him\", \"himself\", \"his\", \"hither\", \"hj\", \"ho\", \"home\", \"hopefully\", \"how\", \"howbeit\", \"however\", \"how's\", \"hr\", \"hs\", \"http\", \"hu\", \"hundred\", \"hy\", \"i\", \"i2\", \"i3\", \"i4\", \"i6\", \"i7\", \"i8\", \"ia\", \"ib\", \"ibid\", \"ic\", \"id\", \"i'd\", \"ie\", \"if\", \"ig\", \"ignored\", \"ih\", \"ii\", \"ij\", \"il\", \"i'll\", \"im\", \"i'm\", \"immediate\", \"immediately\", \"importance\", \"important\", \"in\", \"inasmuch\", \"inc\", \"indeed\", \"index\", \"indicate\", \"indicated\", \"indicates\", \"information\", \"inner\", \"insofar\", \"instead\", \"interest\", \"into\", \"invention\", \"inward\", \"io\", \"ip\", \"iq\", \"ir\", \"is\", \"isn\", \"isn't\", \"it\", \"itd\", \"it'd\", \"it'll\", \"its\", \"it's\", \"itself\", \"iv\", \"i've\", \"ix\", \"iy\", \"iz\", \"j\", \"jj\", \"jr\", \"js\", \"jt\", \"ju\", \"just\", \"k\", \"ke\", \"keep\", \"keeps\", \"kept\", \"kg\", \"kj\", \"km\", \"know\", \"known\", \"knows\", \"ko\", \"l\", \"l2\", \"la\", \"largely\", \"last\", \"lately\", \"later\", \"latter\", \"latterly\", \"lb\", \"lc\", \"le\", \"least\", \"les\", \"less\", \"lest\", \"let\", \"lets\", \"let's\", \"lf\", \"like\", \"liked\", \"likely\", \"line\", \"little\", \"lj\", \"ll\", \"ll\", \"ln\", \"lo\", \"look\", \"looking\", \"looks\", \"los\", \"lr\", \"ls\", \"lt\", \"ltd\", \"m\", \"m2\", \"ma\", \"made\", \"mainly\", \"make\", \"makes\", \"many\", \"may\", \"maybe\", \"me\", \"mean\", \"means\", \"meantime\", \"meanwhile\", \"merely\", \"mg\", \"might\", \"mightn\", \"mightn't\", \"mill\", \"million\", \"mine\", \"miss\", \"ml\", \"mn\", \"mo\", \"more\", \"moreover\", \"most\", \"mostly\", \"move\", \"mr\", \"mrs\", \"ms\", \"mt\", \"mu\", \"much\", \"mug\", \"must\", \"mustn\", \"mustn't\", \"my\", \"myself\", \"n\", \"n2\", \"na\", \"name\", \"namely\", \"nay\", \"nc\", \"nd\", \"ne\", \"near\", \"nearly\", \"necessarily\", \"necessary\", \"need\", \"needn\", \"needn't\", \"needs\", \"neither\", \"never\", \"nevertheless\", \"new\", \"next\", \"ng\", \"ni\", \"nine\", \"ninety\", \"nj\", \"nl\", \"nn\", \"no\", \"nobody\", \"non\", \"none\", \"nonetheless\", \"noone\", \"nor\", \"normally\", \"nos\", \"not\", \"noted\", \"nothing\", \"novel\", \"now\", \"nowhere\", \"nr\", \"ns\", \"nt\", \"ny\", \"o\", \"oa\", \"ob\", \"obtain\", \"obtained\", \"obviously\", \"oc\", \"od\", \"of\", \"off\", \"often\", \"og\", \"oh\", \"oi\", \"oj\", \"ok\", \"okay\", \"ol\", \"old\", \"om\", \"omitted\", \"on\", \"once\", \"one\", \"ones\", \"only\", \"onto\", \"oo\", \"op\", \"oq\", \"or\", \"ord\", \"os\", \"ot\", \"other\", \"others\", \"otherwise\", \"ou\", \"ought\", \"our\", \"ours\", \"ourselves\", \"out\", \"outside\", \"over\", \"overall\", \"ow\", \"owing\", \"own\", \"ox\", \"oz\", \"p\", \"p1\", \"p2\", \"p3\", \"page\", \"pagecount\", \"pages\", \"par\", \"part\", \"particular\", \"particularly\", \"pas\", \"past\", \"pc\", \"pd\", \"pe\", \"per\", \"perhaps\", \"pf\", \"ph\", \"pi\", \"pj\", \"pk\", \"pl\", \"placed\", \"please\", \"plus\", \"pm\", \"pn\", \"po\", \"poorly\", \"possible\", \"possibly\", \"potentially\", \"pp\", \"pq\", \"pr\", \"predominantly\", \"present\", \"presumably\", \"previously\", \"primarily\", \"probably\", \"promptly\", \"proud\", \"provides\", \"ps\", \"pt\", \"pu\", \"put\", \"py\", \"q\", \"qj\", \"qu\", \"que\", \"quickly\", \"quite\", \"qv\", \"r\", \"r2\", \"ra\", \"ran\", \"rather\", \"rc\", \"rd\", \"re\", \"readily\", \"really\", \"reasonably\", \"recent\", \"recently\", \"ref\", \"refs\", \"regarding\", \"regardless\", \"regards\", \"related\", \"relatively\", \"research\", \"research-articl\", \"respectively\", \"resulted\", \"resulting\", \"results\", \"rf\", \"rh\", \"ri\", \"right\", \"rj\", \"rl\", \"rm\", \"rn\", \"ro\", \"rq\", \"rr\", \"rs\", \"rt\", \"ru\", \"run\", \"rv\", \"ry\", \"s\", \"s2\", \"sa\", \"said\", \"same\", \"saw\", \"say\", \"saying\", \"says\", \"sc\", \"sd\", \"se\", \"sec\", \"second\", \"secondly\", \"section\", \"see\", \"seeing\", \"seem\", \"seemed\", \"seeming\", \"seems\", \"seen\", \"self\", \"selves\", \"sensible\", \"sent\", \"serious\", \"seriously\", \"seven\", \"several\", \"sf\", \"shall\", \"shan\", \"shan't\", \"she\", \"shed\", \"she'd\", \"she'll\", \"shes\", \"she's\", \"should\", \"shouldn\", \"shouldn't\", \"should've\", \"show\", \"showed\", \"shown\", \"showns\", \"shows\", \"si\", \"side\", \"significant\", \"significantly\", \"similar\", \"similarly\", \"since\", \"sincere\", \"six\", \"sixty\", \"sj\", \"sl\", \"slightly\", \"sm\", \"sn\", \"so\", \"some\", \"somebody\", \"somehow\", \"someone\", \"somethan\", \"something\", \"sometime\", \"sometimes\", \"somewhat\", \"somewhere\", \"soon\", \"sorry\", \"sp\", \"specifically\", \"specified\", \"specify\", \"specifying\", \"sq\", \"sr\", \"ss\", \"st\", \"still\", \"stop\", \"strongly\", \"sub\", \"substantially\", \"successfully\", \"such\", \"sufficiently\", \"suggest\", \"sup\", \"sure\", \"sy\", \"system\", \"sz\", \"t\", \"t1\", \"t2\", \"t3\", \"take\", \"taken\", \"taking\", \"tb\", \"tc\", \"td\", \"te\", \"tell\", \"ten\", \"tends\", \"tf\", \"th\", \"than\", \"thank\", \"thanks\", \"thanx\", \"that\", \"that'll\", \"thats\", \"that's\", \"that've\", \"the\", \"their\", \"theirs\", \"them\", \"themselves\", \"then\", \"thence\", \"there\", \"thereafter\", \"thereby\", \"thered\", \"therefore\", \"therein\", \"there'll\", \"thereof\", \"therere\", \"theres\", \"there's\", \"thereto\", \"thereupon\", \"there've\", \"these\", \"they\", \"theyd\", \"they'd\", \"they'll\", \"theyre\", \"they're\", \"they've\", \"thickv\", \"thin\", \"think\", \"third\", \"this\", \"thorough\", \"thoroughly\", \"those\", \"thou\", \"though\", \"thoughh\", \"thousand\", \"three\", \"throug\", \"through\", \"throughout\", \"thru\", \"thus\", \"ti\", \"til\", \"tip\", \"tj\", \"tl\", \"tm\", \"tn\", \"to\", \"together\", \"too\", \"took\", \"top\", \"toward\", \"towards\", \"tp\", \"tq\", \"tr\", \"tried\", \"tries\", \"truly\", \"try\", \"trying\", \"ts\", \"t's\", \"tt\", \"tv\", \"twelve\", \"twenty\", \"twice\", \"two\", \"tx\", \"u\", \"u201d\", \"ue\", \"ui\", \"uj\", \"uk\", \"um\", \"un\", \"under\", \"unfortunately\", \"unless\", \"unlike\", \"unlikely\", \"until\", \"unto\", \"uo\", \"up\", \"upon\", \"ups\", \"ur\", \"us\", \"use\", \"used\", \"useful\", \"usefully\", \"usefulness\", \"uses\", \"using\", \"usually\", \"ut\", \"v\", \"va\", \"value\", \"various\", \"vd\", \"ve\", \"ve\", \"very\", \"via\", \"viz\", \"vj\", \"vo\", \"vol\", \"vols\", \"volumtype\", \"vq\", \"vs\", \"vt\", \"vu\", \"w\", \"wa\", \"want\", \"wants\", \"was\", \"wasn\", \"wasnt\", \"wasn't\", \"way\", \"we\", \"wed\", \"we'd\", \"welcome\", \"well\", \"we'll\", \"well-b\", \"went\", \"were\", \"we're\", \"weren\", \"werent\", \"weren't\", \"we've\", \"what\", \"whatever\", \"what'll\", \"whats\", \"what's\", \"when\", \"whence\", \"whenever\", \"when's\", \"where\", \"whereafter\", \"whereas\", \"whereby\", \"wherein\", \"wheres\", \"where's\", \"whereupon\", \"wherever\", \"whether\", \"which\", \"while\", \"whim\", \"whither\", \"who\", \"whod\", \"whoever\", \"whole\", \"who'll\", \"whom\", \"whomever\", \"whos\", \"who's\", \"whose\", \"why\", \"why's\", \"wi\", \"widely\", \"will\", \"willing\", \"wish\", \"with\", \"within\", \"without\", \"wo\", \"won\", \"wonder\", \"wont\", \"won't\", \"words\", \"world\", \"would\", \"wouldn\", \"wouldnt\", \"wouldn't\", \"www\", \"x\", \"x1\", \"x2\", \"x3\", \"xf\", \"xi\", \"xj\", \"xk\", \"xl\", \"xn\", \"xo\", \"xs\", \"xt\", \"xv\", \"xx\", \"y\", \"y2\", \"yes\", \"yet\", \"yj\", \"yl\", \"you\", \"youd\", \"you'd\", \"you'll\", \"your\", \"youre\", \"you're\", \"yours\", \"yourself\", \"yourselves\", \"you've\", \"yr\", \"ys\", \"yt\", \"z\", \"zero\", \"zi\", \"zz\"]\nstop_words =[i.replace('\"',\"\").strip() for i in stop_words]",
"_____no_output_____"
],
[
"def plot_top_words(model, feature_names, n_top_words, title):\n fig, axes = plt.subplots(1, n_components, figsize=(30, 15), sharex=True)\n axes = axes.flatten()\n for topic_idx, topic in enumerate(model.components_):\n top_features_ind = topic.argsort()[:-n_top_words - 1:-1]\n top_features = [feature_names[i] for i in top_features_ind]\n weights = topic[top_features_ind]/np.sum(topic)\n\n ax = axes[topic_idx]\n ax.barh(top_features, weights, height=0.7)\n ax.set_title(f'Topic {topic_idx +1}',\n fontdict={'fontsize': 30})\n ax.invert_yaxis()\n ax.tick_params(axis='both', which='major', labelsize=20)\n for i in 'top right left'.split():\n ax.spines[i].set_visible(False)\n fig.suptitle(title, fontsize=40)\n\n plt.subplots_adjust(top=0.90, bottom=0.05, wspace=0.90, hspace=0.3)\n plt.savefig(title+'.png')\n plt.show()",
"_____no_output_____"
],
[
"# Load choi data from rtf\ncurrent_dir = os.getcwd()\ndirnames = glob(current_dir+\"*/*/\")\n\nfor dirname in dirnames:\n filenames = os.listdir(dirname)\n\n data_samples = []\n\n for file in filenames:\n f = open(dirname+file,'r')\n lines = f.readlines()\n\n for line in range(len(lines)):\n lines[line] = rtf_to_text(lines[line]).strip().lower()\n\n # Raw article\n raw_article = ' '.join(lines)\n data_samples.append(raw_article)\n\n n_samples = len(data_samples)\n \n # Get info\n date = dirname.split('/')[-2]\n \n print(\"Extracting tf-idf features for NMF of \"+date)\n tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2,\n max_features=n_features,\n stop_words=stop_words)\n t0 = time()\n tfidf = tfidf_vectorizer.fit_transform(data_samples)\n print(\"done in %0.3fs.\" % (time() - t0))\n\n tfidf_feature_names = tfidf_vectorizer.get_feature_names()\n print(\"Most popular words of \" + date)\n print(tfidf_feature_names)\n \n # Fit the NMF model\n print('\\n' * 2, \"Fitting the NMF model (generalized Kullback-Leibler \"\n \"divergence) with tf-idf features, n_samples=%d and n_features=%d...\"\n % (n_samples, n_features))\n t0 = time()\n nmf = NMF(n_components=n_components, random_state=1,\n beta_loss='kullback-leibler', solver='mu', max_iter=1000, alpha=.1,\n l1_ratio=.5).fit(tfidf)\n print(\"done in %0.3fs.\" % (time() - t0))\n\n tfidf_feature_names = tfidf_vectorizer.get_feature_names()\n plot_top_words(nmf, tfidf_feature_names, n_top_words, date)",
"Extracting tf-idf features for NMF of Jan27\ndone in 0.117s.\nMost popular words of Jan27\n['cases', 'chinese', 'city', 'countries', 'country', 'days', 'disease', 'global', 'government', 'health', 'hong', 'hospital', 'kong', 'medical', 'news', 'officials', 'percent', 'president', 'public', 'sars', 'spread', 'state', 'states', 'travel', 'trump', 'united', 'virus', 'week', 'wuhan', 'york']\n\n\n Fitting the NMF model (generalized Kullback-Leibler divergence) with tf-idf features, n_samples=100 and n_features=30...\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7acb1093bacc8f384c41c10c664e5a629a9d95d | 14,722 | ipynb | Jupyter Notebook | notebooks/chap01.ipynb | erhardt/ModSimPy | e426d5eccf8848473b04c1f2375d9858e7ff0db9 | [
"MIT"
] | null | null | null | notebooks/chap01.ipynb | erhardt/ModSimPy | e426d5eccf8848473b04c1f2375d9858e7ff0db9 | [
"MIT"
] | null | null | null | notebooks/chap01.ipynb | erhardt/ModSimPy | e426d5eccf8848473b04c1f2375d9858e7ff0db9 | [
"MIT"
] | null | null | null | 30.229979 | 357 | 0.599851 | [
[
[
"# Modeling and Simulation in Python\n\nChapter 1\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)",
"_____no_output_____"
],
[
"## Jupyter\n\nWelcome to Modeling and Simulation, welcome to Python, and welcome to Jupyter.\n\nThis is a Jupyter notebook, which is a development environment where you can write and run Python code. Each notebook is divided into cells. Each cell contains either text (like this cell) or Python code.\n\n### Selecting and running cells\n\nTo select a cell, click in the left margin next to the cell. You should see a blue frame surrounding the selected cell.\n\nTo edit a code cell, click inside the cell. You should see a green frame around the selected cell, and you should see a cursor inside the cell.\n\nTo edit a text cell, double-click inside the cell. Again, you should see a green frame around the selected cell, and you should see a cursor inside the cell.\n\nTo run a cell, hold down SHIFT and press ENTER. \n\n* If you run a text cell, Jupyter typesets the text and displays the result.\n\n* If you run a code cell, it runs the Python code in the cell and displays the result, if any.\n\nTo try it out, edit this cell, change some of the text, and then press SHIFT-ENTER to run it.",
"_____no_output_____"
],
[
"### Adding and removing cells\n\nYou can add and remove cells from a notebook using the buttons in the toolbar and the items in the menu, both of which you should see at the top of this notebook.\n\nTry the following exercises:\n\n1. From the Insert menu select \"Insert cell below\" to add a cell below this one. By default, you get a code cell, as you can see in the pulldown menu that says \"Code\".\n\n2. In the new cell, add a print statement like `print('Hello')`, and run it.\n\n3. Add another cell, select the new cell, and then click on the pulldown menu that says \"Code\" and select \"Markdown\". This makes the new cell a text cell.\n\n4. In the new cell, type some text, and then run it.\n\n5. Use the arrow buttons in the toolbar to move cells up and down.\n\n6. Use the cut, copy, and paste buttons to delete, add, and move cells.\n\n7. As you make changes, Jupyter saves your notebook automatically, but if you want to make sure, you can press the save button, which looks like a floppy disk from the 1990s.\n\n8. Finally, when you are done with a notebook, select \"Close and Halt\" from the File menu.",
"_____no_output_____"
],
[
"### Using the notebooks\n\nThe notebooks for each chapter contain the code from the chapter along with addition examples, explanatory text, and exercises. I recommend you \n\n1. Read the chapter first to understand the concepts and vocabulary, \n2. Run the notebook to review what you learned and see it in action, and then\n3. Attempt the exercises.\n\nIf you try to work through the notebooks without reading the book, you're gonna have a bad time. The notebooks contain some explanatory text, but it is probably not enough to make sense if you have not read the book. If you are working through a notebook and you get stuck, you might want to re-read (or read!) the corresponding section of the book.",
"_____no_output_____"
],
[
"### Importing modsim\n\nThe following cell imports `modsim`, which is a collection of functions we will use throughout the book. Whenever you start the notebook, you will have to run the following cell. It does three things:\n\n1. It uses a Jupyter \"magic command\" to specify whether figures should appear in the notebook, or pop up in a new window.\n\n2. It configures Jupyter to display some values that would otherwise be invisible. \n\n3. It imports everything defined in `modsim`.\n\nSelect the following cell and press SHIFT-ENTER to run it.",
"_____no_output_____"
]
],
[
[
"# Configure Jupyter so figures appear in the notebook\n%matplotlib inline\n\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import functions from the modsim library\nfrom modsim import *\n\nprint('If this cell runs successfully, it produces no output other than this message.')",
"_____no_output_____"
]
],
[
[
"The first time you run this on a new installation of Python, it might produce a warning message in pink. That's probably ok, but if you get a message that says `modsim.py depends on Python 3.7 features`, that means you have an older version of Python, and some features in `modsim.py` won't work correctly.\n\nIf you need a newer version of Python, I recommend installing Anaconda. You'll find more information in the preface of the book.",
"_____no_output_____"
],
[
"## The penny myth\n\nThe following cells contain code from the beginning of Chapter 1.\n\n`modsim` defines `UNITS`, which contains variables representing pretty much every unit you've ever heard of. It uses [Pint](https://pint.readthedocs.io/en/latest/), which is a Python library that provides tools for computing with units.\n\nThe following lines create new variables named `meter` and `second`.",
"_____no_output_____"
]
],
[
[
"meter = UNITS.meter",
"_____no_output_____"
],
[
"second = UNITS.second",
"_____no_output_____"
]
],
[
[
"To find out what other units are defined, type `UNITS.` (including the period) in the next cell and then press TAB. You should see a pop-up menu with a list of units.",
"_____no_output_____"
],
[
"Create a variable named `a` and give it the value of acceleration due to gravity.",
"_____no_output_____"
]
],
[
[
"a = 9.8 * meter / second**2",
"_____no_output_____"
]
],
[
[
"Create `t` and give it the value 4 seconds.",
"_____no_output_____"
]
],
[
[
"t = 4 * second",
"_____no_output_____"
]
],
[
[
"Compute the distance a penny would fall after `t` seconds with constant acceleration `a`. Notice that the units of the result are correct.",
"_____no_output_____"
]
],
[
[
"a * t**2 / 2",
"_____no_output_____"
]
],
[
[
"**Exercise**: Compute the velocity of the penny after `t` seconds. Check that the units of the result are correct.",
"_____no_output_____"
]
],
[
[
"# Solution goes here",
"_____no_output_____"
]
],
[
[
"**Exercise**: Why would it be nonsensical to add `a` and `t`? What happens if you try?",
"_____no_output_____"
]
],
[
[
"# Solution goes here",
"_____no_output_____"
]
],
[
[
"The error messages you get from Python are big and scary, but if you read them carefully, they contain a lot of useful information.\n\n1. Start from the bottom and read up.\n2. The last line usually tells you what type of error happened, and sometimes additional information.\n3. The previous lines are a \"traceback\" of what was happening when the error occurred. The first section of the traceback shows the code you wrote. The following sections are often from Python libraries.\n\nIn this example, you should get a `DimensionalityError`, which is defined by Pint to indicate that you have violated a rules of dimensional analysis: you cannot add quantities with different dimensions.\n\nBefore you go on, you might want to delete the erroneous code so the notebook can run without errors.",
"_____no_output_____"
],
[
"## Falling pennies\n\nNow let's solve the falling penny problem.\n\nSet `h` to the height of the Empire State Building:",
"_____no_output_____"
]
],
[
[
"h = 381 * meter",
"_____no_output_____"
]
],
[
[
"Compute the time it would take a penny to fall, assuming constant acceleration.\n\n$ a t^2 / 2 = h $\n\n$ t = \\sqrt{2 h / a}$",
"_____no_output_____"
]
],
[
[
"t = sqrt(2 * h / a)",
"_____no_output_____"
]
],
[
[
"Given `t`, we can compute the velocity of the penny when it lands.\n\n$v = a t$",
"_____no_output_____"
]
],
[
[
"v = a * t",
"_____no_output_____"
]
],
[
[
"We can convert from one set of units to another like this:",
"_____no_output_____"
]
],
[
[
"mile = UNITS.mile\nhour= UNITS.hour",
"_____no_output_____"
],
[
"v.to(mile/hour)",
"_____no_output_____"
]
],
[
[
"**Exercise:** Suppose you bring a 10 foot pole to the top of the Empire State Building and use it to drop the penny from `h` plus 10 feet.\n\nDefine a variable named `foot` that contains the unit `foot` provided by `UNITS`. Define a variable named `pole_height` and give it the value 10 feet.\n\nWhat happens if you add `h`, which is in units of meters, to `pole_height`, which is in units of feet? What happens if you write the addition the other way around?",
"_____no_output_____"
]
],
[
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
]
],
[
[
"**Exercise:** In reality, air resistance limits the velocity of the penny. At about 18 m/s, the force of air resistance equals the force of gravity and the penny stops accelerating.\n\nAs a simplification, let's assume that the acceleration of the penny is `a` until the penny reaches 18 m/s, and then 0 afterwards. What is the total time for the penny to fall 381 m?\n\nYou can break this question into three parts:\n\n1. How long until the penny reaches 18 m/s with constant acceleration `a`.\n2. How far would the penny fall during that time?\n3. How long to fall the remaining distance with constant velocity 18 m/s?\n\nSuggestion: Assign each intermediate result to a variable with a meaningful name. And assign units to all quantities!",
"_____no_output_____"
]
],
[
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
],
[
"# Solution goes here",
"_____no_output_____"
]
],
[
[
"### Restart and run all\n\nWhen you change the contents of a cell, you have to run it again for those changes to have an effect. If you forget to do that, the results can be confusing, because the code you are looking at is not the code you ran.\n\nIf you ever lose track of which cells have run, and in what order, you should go to the Kernel menu and select \"Restart & Run All\". Restarting the kernel means that all of your variables get deleted, and running all the cells means all of your code will run again, in the right order.\n\n**Exercise:** Select \"Restart & Run All\" now and confirm that it does what you want.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7acb21c862233b5edb1850a1a69e4833bcfb3dc | 3,452 | ipynb | Jupyter Notebook | nlib/src/readyt.ipynb | riyadhuddin/intro2py | dec9477b0a7f2ddbe2faac9c3bb903b7692bf8e1 | [
"MIT"
] | null | null | null | nlib/src/readyt.ipynb | riyadhuddin/intro2py | dec9477b0a7f2ddbe2faac9c3bb903b7692bf8e1 | [
"MIT"
] | 4 | 2021-11-22T01:15:03.000Z | 2021-12-09T00:18:26.000Z | nlib/src/readyt.ipynb | riyadhuddin/intro2py | dec9477b0a7f2ddbe2faac9c3bb903b7692bf8e1 | [
"MIT"
] | null | null | null | 30.280702 | 96 | 0.580823 | [
[
[
"#write a function to play youtubevideo in your browser\ndef play_youtube_video(video_id):\n import webbrowser\n webbrowser.open('https://www.youtube.com/watch?v='+video_id)\n#write a function to play youtubevideo in your browser",
"_____no_output_____"
],
[
"play_youtube_video('gSSu-wXo3q8')",
"_____no_output_____"
],
[
"#write a function to play youtubevideo within ipython notebook \ndef play_youtube_video_ipynb(video_id):\n from IPython.display import YouTubeVideo\n YouTubeVideo(video_id)",
"_____no_output_____"
],
[
"play_youtube_video_ipynb('gSSu-wXo3q8')",
"_____no_output_____"
],
[
"#write a function to analyze youtubevideo \ndef analyze_youtube_video(video_id):\n import requests\n from bs4 import BeautifulSoup\n url = 'https://www.youtube.com/watch?v='+video_id\n response = requests.get(url)\n soup = BeautifulSoup(response.text, 'html.parser')\n title = soup.find('h1', id='eow-title')\n print(title.text)\n views = soup.find('div', id='watch7-views-info')\n print(views.text)\n likes = soup.find('button', id='like-button-legacy')\n print(likes.text)\n dislikes = soup.find('button', id='dislike-button-legacy')\n print(dislikes.text)\n comments = soup.find('span', id='comment-count')\n print(comments.text)\n description = soup.find('div', id='eow-description')\n print(description.text)\n channel = soup.find('a', id='channel-name')\n print(channel.text)\n channel_url = soup.find('a', id='channel-link')\n print(channel_url.text)\n channel_url = soup.find('a', id='channel-link')['href']\n print(channel_url)\n channel_subscribers = soup.find('span', id='subscribe-button')\n print(channel_subscribers.text)\n channel_subscribers = soup.find('span', id='subscribe-button')['title']\n print(channel_subscribers)\n channel_subscribers = soup.find('span', id='subscribe-button')['data-tooltip-text']\n print(channel_subscribers)\n channel_subscribers = soup.find('span', id='subscribe-button')['aria-label']\n print(channel_subscribers)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
e7acbfffc233e7d601b76de990f1e602fe71faa3 | 11,360 | ipynb | Jupyter Notebook | Notebooks/HNSCC_Imports.ipynb | theandygross/CancerData | b6d77ae70c1b47d6e9e534ccfa8f086248ead05c | [
"MIT"
] | null | null | null | Notebooks/HNSCC_Imports.ipynb | theandygross/CancerData | b6d77ae70c1b47d6e9e534ccfa8f086248ead05c | [
"MIT"
] | null | null | null | Notebooks/HNSCC_Imports.ipynb | theandygross/CancerData | b6d77ae70c1b47d6e9e534ccfa8f086248ead05c | [
"MIT"
] | null | null | null | 22.015504 | 139 | 0.529842 | [
[
[
"# Global Imports",
"_____no_output_____"
]
],
[
[
"%pylab inline",
"Populating the interactive namespace from numpy and matplotlib\n"
]
],
[
[
"### External Package Imports",
"_____no_output_____"
]
],
[
[
"import os as os\nimport pickle as pickle\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"### Module Imports",
"_____no_output_____"
]
],
[
[
"from Stats.Scipy import *\nfrom Stats.Survival import *\nfrom Helpers.Pandas import *\n\nfrom Figures.FigureHelpers import *\nfrom Figures.Pandas import *\nfrom Figures.Boxplots import *\nfrom Figures.Survival import draw_survival_curve, survival_and_stats\nfrom Figures.Survival import draw_survival_curves\nfrom Figures.Survival import survival_stat_plot",
"_____no_output_____"
],
[
"import Data.Firehose as FH",
"_____no_output_____"
]
],
[
[
"### Tweaking Display Parameters",
"_____no_output_____"
]
],
[
[
"pd.set_option('precision', 3)\npd.set_option('display.width', 300)\nplt.rcParams['font.size'] = 12",
"_____no_output_____"
],
[
"'''Color schemes for paper taken from http://colorbrewer2.org/'''\ncolors = plt.rcParams['axes.color_cycle']\ncolors_st = ['#CA0020', '#F4A582', '#92C5DE', '#0571B0']\ncolors_th = ['#E66101', '#FDB863', '#B2ABD2', '#5E3C99']",
"_____no_output_____"
]
],
[
[
"### Function to Pull a Firehose Run Container",
"_____no_output_____"
]
],
[
[
"def get_run(firehose_dir, version='Latest'):\n '''\n Helper to get a run from the file-system. \n '''\n path = '{}/ucsd_analyses'.format(firehose_dir)\n if version is 'Latest':\n version = sorted(os.listdir(path))[-1]\n run = pickle.load(open('{}/{}/RunObject.p'.format(path, version), 'rb'))\n return run",
"_____no_output_____"
]
],
[
[
"### Read In Data",
"_____no_output_____"
],
[
"Here we read in the pre-processed data that we downloaded and initialized in the [download_data notebook](download_data.ipynb).",
"_____no_output_____"
]
],
[
[
"print 'populating namespace with data'",
"populating namespace with data\n"
],
[
"OUT_PATH = '/cellar/users/agross/TCGA_Code/CancerData/Data'\nRUN_DATE = '2014_07_15'\nVERSION = 'all'\nCANCER = 'HNSC'\nFIGDIR = '../Figures/'\nif not os.path.isdir(FIGDIR):\n os.makedirs(FIGDIR)",
"_____no_output_____"
],
[
"run_path = '{}/Firehose__{}/'.format(OUT_PATH, RUN_DATE)\nrun = get_run(run_path, 'Run_' + VERSION)\nrun.data_path = run_path \nrun.result_path = run_path + 'ucsd_analyses'\nrun.report_path = run_path + 'ucsd_analyses/Run_all'\n\ncancer = run.load_cancer(CANCER)\ncancer.path = '{}/{}'.format(run.report_path , cancer.name)\nclinical = cancer.load_clinical()\n\nmut = cancer.load_data('Mutation')\nmut.uncompress()\ncn = cancer.load_data('CN_broad')\ncn.uncompress()",
"_____no_output_____"
],
[
"rna = FH.read_rnaSeq(run.data_path, cancer.name, tissue_code='All')\nmirna = FH.read_miRNASeq(run.data_path, cancer.name, tissue_code='All')",
"_____no_output_____"
],
[
"keepers_o = pd.read_csv('/cellar/users/agross/TCGA_Code/TCGA_Working/Data/Firehose__2014_04_16/' + 'old_keepers.csv', index_col=0,\n squeeze=True)\nkeepers_o = array(keepers_o)",
"_____no_output_____"
]
],
[
[
"#### Update Clinical Data",
"_____no_output_____"
]
],
[
[
"from Processing.ProcessClinicalDataPortal import update_clinical_object\n\np = '/cellar/users/agross/TCGA_Code/TCGA/Data'\npath = p + '/Followup_R9/HNSC/'\nclinical = update_clinical_object(clinical, path)\nclinical.clinical.shape",
"_____no_output_____"
],
[
"#hpv = clinical.hpv\nsurv = clinical.survival.survival_5y\nage = clinical.clinical.age.astype(float)\nold = pd.Series(1.*(age>=75), name='old')",
"_____no_output_____"
],
[
"p = '/cellar/users/agross/TCGA_Code/TCGA/Data'\nf = p + '/MAFs/PR_TCGA_HNSC_PAIR_Capture_All_Pairs_QCPASS_v4.aggregated.capture.tcga.uuid.automated.somatic.maf.txt'\nmut_new = pd.read_table(f, skiprows=4, low_memory=False)\nkeep = (mut_new.Variant_Classification.isin(['Silent', 'Intron', \"3'UTR\", \"5'UTR\"])==False)\nmut_new = mut_new[keep]\nmut_new['barcode'] = mut_new.Tumor_Sample_Barcode.map(lambda s: s[:12])\nmut_new = mut_new.groupby(['barcode','Hugo_Symbol']).size().unstack().fillna(0).T\nmut_new = mut.df.combine_first(mut_new).fillna(0)",
"_____no_output_____"
],
[
"gistic = FH.get_gistic_gene_matrix(run.data_path, cancer.name)\ndel_3p = gistic.ix['3p14.2'].median(0)\ndel_3p.name = '3p_deletion'",
"_____no_output_____"
]
],
[
[
"#### HPV Data",
"_____no_output_____"
]
],
[
[
"p = '/cellar/users/agross/TCGA_Code/TCGA/'\nhpv_all = pd.read_csv(p + '/Extra_Data/hpv_summary_3_20_13_distribute.csv', index_col=0)\nhpv = hpv_all.Molecular_HPV.map({0:'HPV-', 1:'HPV+'})\nhpv.name = 'HPV'\nhpv_seq = hpv",
"_____no_output_____"
],
[
"status = clinical.clinical[['hpvstatusbyishtesting','hpvstatusbyp16testing']]\nstatus = status.replace('[Not Evaluated]', nan)\nhpv_clin = (status.dropna() == 'Positive').sum(1)\nhpv_clin = hpv_clin.map({2: 'HPV+', 0:'HPV-', 1:nan}).dropna()",
"_____no_output_____"
],
[
"hpv_clin.value_counts()",
"_____no_output_____"
],
[
"hpv_clin.ix[hpv_clin.index.diff(hpv_seq.index)].value_counts()",
"_____no_output_____"
],
[
"hpv_new = pd.read_table(p + '/Data/Followup_R6/HNSC/auxiliary_hnsc.txt',\n skiprows=[1], index_col=0, na_values=['[Not Available]'])\nhpv_new = hpv_new['hpv_status']",
"_____no_output_____"
],
[
"hpv = (hpv_seq.dropna() == 'HPV+').combine_first(hpv_new == 'Positive')\nhpv.name = 'HPV'",
"_____no_output_____"
],
[
"hpv.value_counts()",
"_____no_output_____"
],
[
"n = ti(hpv==False)",
"_____no_output_____"
],
[
"fisher_exact_test(del_3p<0, mut_new.ix['TP53'].ix[n.diff(keepers_o)]>0)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7acc464837f1839f1771b987495c39cac979029 | 1,470 | ipynb | Jupyter Notebook | quera/13609/46444/solution.ipynb | TheMn/Quera-College-ML-Course | 162e37c138ed44233b3699c1192276f5a7d7c62b | [
"MIT"
] | 1 | 2021-01-09T16:07:37.000Z | 2021-01-09T16:07:37.000Z | quera/13609/46444/solution.ipynb | TheMn/Quera-College-ML-Course | 162e37c138ed44233b3699c1192276f5a7d7c62b | [
"MIT"
] | null | null | null | quera/13609/46444/solution.ipynb | TheMn/Quera-College-ML-Course | 162e37c138ed44233b3699c1192276f5a7d7c62b | [
"MIT"
] | 1 | 2021-01-09T15:29:32.000Z | 2021-01-09T15:29:32.000Z | 16.516854 | 72 | 0.453061 | [
[
[
"این دفترچه تنها جهت تمرین در کنار مطالعهی درسنامه اضافه شده است.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"i = np.identity(3)\nb = i == 0\nprint(i[b].shape)",
"(6,)\n"
],
[
"x = np.full((3, 3), 8)",
"_____no_output_____"
],
[
"print(np.dot(i, x))",
"[[8. 8. 8.]\n [8. 8. 8.]\n [8. 8. 8.]]\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e7accb4214a712979b988064dbe79f3955abdcaf | 132,231 | ipynb | Jupyter Notebook | Build own facial detection/own_facial_recogniton_notebook.ipynb | shraiyya/datascience-mashup | 960933cbc018a6b867282163836af0308e5f453d | [
"MIT"
] | 43 | 2020-12-18T17:18:22.000Z | 2022-03-10T08:09:45.000Z | Build own facial detection/own_facial_recogniton_notebook.ipynb | oshi36/datascience-mashup | 82676e88e8c8778db02678aed3bd2f999c7a1761 | [
"MIT"
] | 232 | 2020-12-24T20:33:30.000Z | 2021-05-28T16:03:13.000Z | Build own facial detection/own_facial_recogniton_notebook.ipynb | oshi36/datascience-mashup | 82676e88e8c8778db02678aed3bd2f999c7a1761 | [
"MIT"
] | 94 | 2020-12-21T18:17:36.000Z | 2021-12-14T17:37:56.000Z | 747.067797 | 127,364 | 0.948794 | [
[
[
"import face_recognition as fr\nimport os\nimport cv2\nimport face_recognition\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom time import sleep",
"_____no_output_____"
],
[
"\ndef get_encoded_faces():\n \"\"\"\n looks through the faces folder and encodes all\n the faces\n\n :return: dict of (name, image encoded)\n \"\"\"\n encoded = {}\n\n for dirpath, dnames, fnames in os.walk(\"./faces\"):\n for f in fnames:\n if f.endswith(\".jpg\") or f.endswith(\".png\"):\n face = fr.load_image_file(\"faces/\" + f)\n encoding = fr.face_encodings(face)[0]\n encoded[f.split(\".\")[0]] = encoding\n\n return encoded",
"_____no_output_____"
],
[
"\ndef unknown_image_encoded(img):\n \"\"\"\n encode a face given the file name\n \"\"\"\n face = fr.load_image_file(\"faces/\" + img)\n encoding = fr.face_encodings(face)[0]\n\n return encoding",
"_____no_output_____"
],
[
"def classify_face(im):\n \"\"\"\n will find all of the faces in a given image and label\n them if it knows what they are\n\n :param im: str of file path\n :return: list of face names\n \"\"\"\n faces = get_encoded_faces()\n faces_encoded = list(faces.values())\n known_face_names = list(faces.keys())\n\n img = cv2.imread(im, 1)\n #img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)\n #img = img[:,:,::-1]\n \n face_locations = face_recognition.face_locations(img)\n unknown_face_encodings = face_recognition.face_encodings(img, face_locations)\n\n face_names = []\n for face_encoding in unknown_face_encodings:\n # See if the face is a match for the known face(s)\n matches = face_recognition.compare_faces(faces_encoded, face_encoding)\n name = \"Unknown\"\n\n # use the known face with the smallest distance to the new face\n face_distances = face_recognition.face_distance(faces_encoded, face_encoding)\n best_match_index = np.argmin(face_distances)\n if matches[best_match_index]:\n name = known_face_names[best_match_index]\n\n face_names.append(name)\n\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n # Draw a box around the face\n cv2.rectangle(img, (left-20, top-20), (right+20, bottom+20), (255, 0, 0), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(img, (left-20, bottom -15), (right+20, bottom+20), (255, 0, 0), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(img, name, (left -20, bottom + 15), font, 1.0, (255, 255, 255), 2)\n screen = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n\n plt.imshow(screen)\n return face_names\n\n\n ",
"_____no_output_____"
],
[
"print(classify_face(\"test1.PNG\"))\n",
"['Bharath C S']\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
e7acd7e7e7e3f6c33bc1c8003af3c84b6e9e7f55 | 440,557 | ipynb | Jupyter Notebook | 03 - Displaying Histograms and Crossplots.ipynb | will6309/Petrophysics-Python-Series | 1951fd23b726a8a0e46c767bfb694ed88d06a301 | [
"MIT"
] | null | null | null | 03 - Displaying Histograms and Crossplots.ipynb | will6309/Petrophysics-Python-Series | 1951fd23b726a8a0e46c767bfb694ed88d06a301 | [
"MIT"
] | null | null | null | 03 - Displaying Histograms and Crossplots.ipynb | will6309/Petrophysics-Python-Series | 1951fd23b726a8a0e46c767bfb694ed88d06a301 | [
"MIT"
] | null | null | null | 622.25565 | 243,032 | 0.947196 | [
[
[
"## 3 - Displaying Histograms and Crossplots",
"_____no_output_____"
],
[
"Created by: Andy McDonald",
"_____no_output_____"
],
[
"The following tutorial illustrates how to display well data from a LAS file on histograms and crossplots.",
"_____no_output_____"
],
[
"### Loading Well Data from CSV",
"_____no_output_____"
],
[
"The following cells load data in from a CSV file and replace the null values (-999.25) with Not a Number (NaN) values. More detail can be found in 1. Loading and Displaying Well Data From CSV.",
"_____no_output_____"
]
],
[
[
"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"root = '/users/kai/desktop/data_science/data/dongara'",
"_____no_output_____"
],
[
"well_name = 'dongara_20'",
"_____no_output_____"
],
[
"file_format = '.csv'",
"_____no_output_____"
],
[
"well = pd.read_csv(os.path.join(root,well_name+file_format), header=0)",
"_____no_output_____"
],
[
"well.replace(-999.25, np.nan, inplace=True)",
"_____no_output_____"
],
[
"cols = well.columns[well.dtypes.eq('object')]",
"_____no_output_____"
],
[
"well[cols] = well[cols].apply(pd.to_numeric, errors='coerce')",
"_____no_output_____"
],
[
"well.head(10)",
"_____no_output_____"
]
],
[
[
"### Displaying data on a histogram",
"_____no_output_____"
],
[
"Displaying a simple histogram can be done by calling the .hist function on the well dataframe and specifying the column.",
"_____no_output_____"
]
],
[
[
"well.hist(column=\"GR\")",
"_____no_output_____"
]
],
[
[
"The number of bins can be controled by the bins parameter:",
"_____no_output_____"
]
],
[
[
"well.hist(column=\"GR\", bins = 30)",
"_____no_output_____"
]
],
[
[
"We can also change the opacity of the bars by using the alpha parameter:",
"_____no_output_____"
]
],
[
[
"well.hist(column=\"GR\", bins = 30, alpha = 0.5)",
"_____no_output_____"
]
],
[
[
"#### Plotting multiple histograms on one plot",
"_____no_output_____"
],
[
"It can be more efficient to loop over the columns (curves) within the dataframe and create a plot with multiple histograms, rather than duplicating the previous line multiple times. <br><br>\n\nFirst we need to create a list of our curve names.",
"_____no_output_____"
]
],
[
[
"cols_to_plot = list(well)",
"_____no_output_____"
]
],
[
[
"We can remove the depth curve from our list and focus on our curves. The same line can be applied to other curves that need removing.",
"_____no_output_____"
]
],
[
[
"cols_to_plot.remove(\"DEPT\")",
"_____no_output_____"
],
[
"#Setup the number of rows and columns for our plot\nrows = 5\ncols = 2\n\nfig=plt.figure(figsize=(10,10))\n\nfor i, feature in enumerate(cols_to_plot):\n ax=fig.add_subplot(rows,cols,i+1)\n well[feature].hist(bins=20,ax=ax,facecolor='green', alpha=0.6)\n ax.set_title(feature+\" Distribution\")\n ax.set_axisbelow(True)\n ax.grid(color='whitesmoke')\n\nplt.tight_layout() \nplt.show()",
"_____no_output_____"
]
],
[
[
"### Displaying data on a crossplot (Scatterplot)",
"_____no_output_____"
],
[
"As seen in the first notebook, we can display a crossplot by simply doing the following. using the c argument we can add a third curve to colour the data.",
"_____no_output_____"
]
],
[
[
"well.plot(kind=\"scatter\", x=\"NPHI\", y=\"RHOB\", c=\"GR\", \n colormap=\"YlOrRd_r\", ylim=(3,2))\n",
"_____no_output_____"
]
],
[
[
"We can take the above crossplot and create a 3D version. First we need to make sure the Jupyter notbook is setup for displaying interactive 3D plots using the following command.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"from mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure(figsize=(5,5))\nax = fig.add_subplot(111, projection=\"3d\")\n\nax.scatter(well[\"NPHI\"], well[\"RHOB\"], well[\"GR\"], alpha= 0.3, c=\"r\")",
"_____no_output_____"
]
],
[
[
"If we want to have multiple crossplots on view, we can do this by:",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(10,10))\n\nax1 = plt.subplot2grid((2,2), (0,0), rowspan=1, colspan=1)\nax2 = plt.subplot2grid((2,2), (0,1), rowspan=1, colspan=1)\nax3 = plt.subplot2grid((2,2), (1,0), rowspan=1, colspan=1)\nax4 = plt.subplot2grid((2,2), (1,1), rowspan=1, colspan=1)\n\nax1.scatter(x= \"NPHI\", y= \"RHOB\", data= well, marker=\"s\", alpha= 0.2)\nax1.set_ylim(3, 1.8)\nax1.set_ylabel(\"RHOB (g/cc)\")\nax1.set_xlabel(\"NPHI (dec)\")\n\n\nax2.scatter(x= \"GR\", y= \"RHOB\", data= well, marker=\"p\", alpha= 0.2)\nax1.set_ylim(3, 1.8)\nax2.set_ylabel(\"RHOB (g/cc)\")\nax2.set_xlabel(\"GR (API)\")\n\nax3.scatter(x= \"DT\", y= \"RHOB\", data= well, marker=\"*\", alpha= 0.2)\nax3.set_ylim(3, 1.8)\nax3.set_ylabel(\"RHOB (g/cc)\")\nax3.set_xlabel(\"DT (us/ft)\")\n\nax4.scatter(x= \"GR\", y= \"DT\", data= well, marker=\"D\", alpha= 0.2)\nax4.set_ylabel(\"DT (us/ft)\")\nax4.set_xlabel(\"GR (API)\")\n\n\nplt.tight_layout()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ace5ccabbb42c6cb8c7a94476969ca1af2f67a | 119,193 | ipynb | Jupyter Notebook | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations | 763279bfd096a98d9b984d8e5127a35fa6940e32 | [
"MIT"
] | 1 | 2020-07-10T18:57:28.000Z | 2020-07-10T18:57:28.000Z | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations | 763279bfd096a98d9b984d8e5127a35fa6940e32 | [
"MIT"
] | null | null | null | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations | 763279bfd096a98d9b984d8e5127a35fa6940e32 | [
"MIT"
] | null | null | null | 194.442088 | 40,984 | 0.876796 | [
[
[
"### Ranking multiple systems\n\nIn this notebook, we consider the situation where we have scores from multiple different automated scoring systems, each with different levels of performance. We evaluate these systems against the same as well as different pairs of raters and show that:\n\n1. When using the same pair of raters to evaluate all of the systems, all metrics including PRMSE are able to rank the systems accurately.\n2. However, when a different pair of raters is chosen for each system, the conventional agreement metrics are not able to rank the systems accurately whereas PRMSE still does.",
"_____no_output_____"
]
],
[
[
"import itertools\nimport json\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n\nfrom matplotlib import pyplot as plt\nfrom pathlib import Path\nfrom rsmtool.utils.prmse import prmse_true\nfrom simulation.dataset import Dataset\nfrom simulation.utils import (compute_agreement_one_system_one_rater_pair,\n compute_agreement_multiple_systems_one_rater_pair,\n compute_ranks_from_metrics)",
"_____no_output_____"
]
],
[
[
"### Step 1: Setup\n\nTo set up the experiment, we first load the dataset we have already created and saved in the `making_a_dataset.ipynb` notebook and use that for this experiment.\n\nFor convenience and replicability, we have pre-defined many of the parameters that are used in our notebooks and saved them in the file `settings.json`. We load this file below.",
"_____no_output_____"
]
],
[
[
"# load the dataset file\ndataset = Dataset.from_file('../data/default.dataset')\n\n# let's remind ourselves what the dataset looks like\nprint(dataset)",
"Dataset (10000 responses, scores in [1, 6], 4 rater categories, 50 raters/category, 5 system categories, 5 systems/category)\n"
],
[
"# load the experimental settings file\nexperiment_settings = json.load(open('settings.json', 'r'))",
"_____no_output_____"
],
[
"# now get the data frames for our loaded dataset\ndf_scores, df_rater_metadata, df_system_metadata = dataset.to_frames()",
"_____no_output_____"
]
],
[
[
"### Step 2: Evaluate all systems against same pair of raters\n\nFirst, we evaluate the scores assigned by all our simulated systems in the dataset against the same pair of simulated human raters from the dataset. To simulate the more usual scenario, we sample two raters from the \"average\" rater category.",
"_____no_output_____"
]
],
[
[
"# define our pre-selected rater category\nchosen_rater_category = \"average\"\n\n# get the list of rater IDs in this category\nrater_ids = df_rater_metadata[df_rater_metadata['rater_category'] == chosen_rater_category]['rater_id']\n\n# choose 2 rater IDs randomly from these\nchosen_rater_pair = rater_id1, rater_id2 = rater_ids.sample(n=2, random_state=1234567890).values.tolist()\n\n# Print this pair out\nprint(f'we chose the rater pair: {chosen_rater_pair}')",
"we chose the rater pair: ['h_107', 'h_101']\n"
]
],
[
[
"Now, we compute the agreement metrics as well as the PRMSE values for all of the simulated systems in our dataset against our pre-selected rater pair.",
"_____no_output_____"
]
],
[
[
"# initialize some lists that will hold our metric and PRMSE values for each category\nmetric_dfs = []\nprmse_series = []\n\n# iterate over each system category\nfor system_category in dataset.system_categories:\n \n # get the system IDs that belong to this system category\n system_ids_for_category = df_system_metadata[df_system_metadata['system_category'] == system_category]['system_id']\n \n # compute the agreement metrics for all of the systems in this category against our chosen rater pair\n df_metrics_for_category = compute_agreement_multiple_systems_one_rater_pair(df_scores,\n system_ids_for_category,\n chosen_rater_pair[0],\n chosen_rater_pair[1],\n include_mean=True)\n\n # note that `compute_agreement_multiple_systems_one_rater_pair()` returns the metric values\n # against both the average of the two raters' scores as well as the first rater's scores;\n # for this analysis, we choose to use only the metric values against the average\n df_metrics_for_category = df_metrics_for_category[df_metrics_for_category['reference'] == 'h1-h2 mean']\n df_metrics_for_category.drop('reference', axis=1, inplace=True)\n\n \n # save the system category in the data frame too since we need it for plotting\n df_metrics_for_category['system_category'] = system_category\n\n # save this metrics dataframe in the list\n metric_dfs.append(df_metrics_for_category)\n\n\n # compute the PRMSE values for all of the systems in this category against our chosen ratr pair\n prmse_series_for_category = system_ids_for_category.apply(lambda system_id: prmse_true(df_scores[system_id],\n df_scores[[rater_id1, rater_id2]]))\n # save these PRMES values in the list\n prmse_series.append(prmse_series_for_category)\n \n\n# combine all of the per-category agreement metric values into a single data frame\ndf_metrics_same_rater_pair_with_categories = pd.concat(metric_dfs).reset_index(drop=True)\n\n# and combine all of the per-category PRMSE values and add it as another column in the same data frame\ndf_metrics_same_rater_pair_with_categories['PRMSE'] = pd.concat(prmse_series)",
"_____no_output_____"
]
],
[
[
"Now, we need to use each metric to compute the ranks of each of the systems based on the values.",
"_____no_output_____"
]
],
[
[
"# compute the ranks given the metric values\ndf_ranks_same_rater_pair = compute_ranks_from_metrics(df_metrics_same_rater_pair_with_categories)\n\n# now compute a longer verssion of this rank data frame that is more amenable to plotting\ndf_ranks_same_rater_pair_long = df_ranks_same_rater_pair.melt(id_vars=['system_category', 'system_id'],\n var_name='metric',\n value_name='rank')",
"_____no_output_____"
],
[
"# plot the ranks\nsns.catplot(x='system_category', y='rank', data=df_ranks_same_rater_pair_long,\n col='metric', kind='box')\nplt.show()",
"_____no_output_____"
]
],
[
[
"As expected, this plot shows that all of the agreement metrics as well as PRMSE ranks the systems correctly since all of them are being computed against the same rater pair. Note that systems known to have better performance rank \"higher\". ",
"_____no_output_____"
],
[
"### Step 3: Evaluate each systems against a different pair of raters\n\nNow, we change things up and evaluate the scores assigned by each of our simulated systems in the dataset against a _different_ pair of simulated human raters from the dataset. We always sample both human raters from the same category but different _pairs_ of raters are sampled from different categories so that each system is evaluated against rater pairs with a different level of average inter-rater agreement. ",
"_____no_output_____"
]
],
[
[
"# first let's get rater pairs within each category\nrater_pairs_per_category = df_rater_metadata.groupby('rater_category')['rater_id'].apply(lambda values: itertools.combinations(values, 2))\n\n# next let's combine all possible rater pairs across the categories\ncombined_rater_pairs = [f\"{rater_id1}+{rater_id2}\" for rater_id1, rater_id2 in itertools.chain.from_iterable(rater_pairs_per_category.values)]\n\n# finally sample a rater pair for each of the systems\nprng = np.random.RandomState(1234567890)\nnum_systems = dataset.num_systems_per_category * len(dataset.system_categories)\nrater_pairs_for_systems = prng.choice(combined_rater_pairs, size=num_systems, replace=False)\nrater_pairs_for_systems = [rater_pair.split('+') for rater_pair in rater_pairs_for_systems]",
"_____no_output_____"
]
],
[
[
"Before we proceed, let's see how the different system categories are distributed across different rater pairs. ",
"_____no_output_____"
]
],
[
[
"# create a dataframe from our rater pairs with h1 and h2 as the two columns\ndf_rater_pairs_with_categories = pd.DataFrame(data=rater_pairs_for_systems, columns=['h1', 'h2'])\n\n# add in the system metadata \ndf_rater_pairs_with_categories['system_id'] = df_system_metadata['system_id']\ndf_rater_pairs_with_categories['system_category'] = df_system_metadata['system_category']\n\n# merge in the rater metadata\n# we can use h1 since the pairs are always drawn from the same category of raters\ndf_rater_pairs_with_categories = pd.merge(df_rater_pairs_with_categories,\n df_rater_metadata,\n left_on='h1',\n right_on='rater_id' )\n\nsystem_category_by_rater_category_table = pd.crosstab(df_rater_pairs_with_categories['system_category'],\n df_rater_pairs_with_categories['rater_category']).loc[dataset.system_categories,\n dataset.rater_categories]\nsystem_category_by_rater_category_table",
"_____no_output_____"
]
],
[
[
"As the table shows, we see that systems in different categories were evaluated against rater pairs with different level of agreement. For example, 3 out of 5 systems in \"low\" category were evaluated against raters with \"high\" agreement. At the same time for systems in \"medium\" category, 3 out of 5 systems were evaluated against raters with \"low\" agreement. ",
"_____no_output_____"
],
[
"Next, we compute the values of the conventional agreement metrics and PRMSE for each system against its corresponding rater pair.",
"_____no_output_____"
]
],
[
[
"# initialize an empty list to hold the metric values for each system ID\nmetric_values_list = []\n\n# iterate over each system ID\nfor system_id, rater_id1, rater_id2 in zip(df_rater_pairs_with_categories['system_id'],\n df_rater_pairs_with_categories['h1'],\n df_rater_pairs_with_categories['h2']):\n \n # compute the agreement metrics for all of the systems in this category against our chosen rater pair\n metric_values, _ = compute_agreement_one_system_one_rater_pair(df_scores,\n system_id,\n rater_id1,\n rater_id2,\n include_mean=True)\n\n # now compute the PRMSE value of the system against the two raters\n metric_values['PRMSE'] = prmse_true(df_scores[system_id], df_scores[[rater_id1, rater_id2]])\n \n # save the system ID since we will need it later\n metric_values['system_id'] = system_id\n \n # save this list of metrics in the list\n metric_values_list.append(metric_values)\n\n# now create a data frame with all of the metric values for all system IDs\ndf_metrics_different_rater_pairs = pd.DataFrame(metric_values_list)\n\n# merge in the system category from the metadata since we need that for plotting\ndf_metrics_different_rater_pairs_with_categories = df_metrics_different_rater_pairs.merge(df_system_metadata,\n left_on='system_id',\n right_on='system_id')\n\n# keep only the columns we need\ndf_metrics_different_rater_pairs_with_categories = df_metrics_different_rater_pairs_with_categories[['system_id',\n 'system_category',\n 'r',\n 'QWK',\n 'R2',\n 'degradation',\n 'PRMSE']]",
"_____no_output_____"
]
],
[
[
"Now that we have computed the metrics, we can plot each simulated system's measured performance via each of the metrics against its known performance, as indicated by its system category.",
"_____no_output_____"
]
],
[
[
"# now create a longer version of this data frame that's more amenable to plotting\ndf_metrics_different_rater_pairs_with_categories_long = df_metrics_different_rater_pairs_with_categories.melt(id_vars=['system_id', 'system_category'],\n var_name='metric')\n# plot the metric values by system category\nax = sns.catplot(col='metric',\n y='value',\n x='system_category',\n data=df_metrics_different_rater_pairs_with_categories_long,\n kind='box',\n order=dataset.system_categories)\nplt.show()",
"_____no_output_____"
]
],
[
[
"From this plot, we can see that only PRMSE values accurately separate the systems from each other whereas the other metrics are not able to do. Next, let's plot how the different systems are ranked by each of the metrics and also compare these ranks to the ranks from the same-rater scenario.",
"_____no_output_____"
]
],
[
[
"# get the ranks for the metrics\ndf_ranks_different_rater_pairs = compute_ranks_from_metrics(df_metrics_different_rater_pairs_with_categories)\n\n# and now get a longer version of this data frame that's more amenable to plotting\ndf_ranks_different_rater_pairs_long = df_ranks_different_rater_pairs.melt(id_vars=['system_category', 'system_id'],\n var_name='metric',\n value_name='rank')\n\n# we also merge in the ranks from the same-rater scenario and distinguish the two sets of ranks with suffixes\ndf_all_ranks_long = df_ranks_different_rater_pairs_long.merge(df_ranks_same_rater_pair_long,\n left_on=['system_id', 'system_category', 'metric'],\n right_on=['system_id', 'system_category', 'metric'],\n suffixes=('_diff', '_same'))",
"_____no_output_____"
],
[
"# now make a plot that shows the comparison of the two sets of ranks\nwith sns.plotting_context('notebook', font_scale=1.1):\n g = sns.FacetGrid(df_all_ranks_long, col='metric', height=4, aspect=0.6)\n g.map(sns.boxplot, 'system_category', 'rank_diff', order=dataset.system_categories, color='grey')\n g.map(sns.stripplot, 'system_category', 'rank_same', order=dataset.system_categories, color='red', jitter=False)\n (g.set_xticklabels(dataset.system_categories, rotation=90)\n .set(xlabel='system category')\n .set(ylabel='rank'))\n plt.show()",
"_____no_output_____"
]
],
[
[
"As this plot shows, only the PRMSE metric is still able to rank the systems accurately whereas all the other metrics are not. We can also make another plot that shows a more direct comparison between $R^2$ and PRMSE.",
"_____no_output_____"
]
],
[
[
"# plot PRMSE and R2 ranks only\ndf_r2_prmse_ranks_long = df_all_ranks_long[df_all_ranks_long['metric'].isin(['R2', 'PRMSE'])]\nax = sns.boxplot(x='system_category',\n y='rank_diff',\n hue='metric',\n hue_order=['R2', 'PRMSE'],\n data=df_r2_prmse_ranks_long,)\nax.set_xlabel('system category')\nax.set_ylabel('rank')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Again, this plot shows that PRMSE is much better behaved when it comes to comparing/ranking systems than $R^2$.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7ad213dc03bd79fd90200a2f1758a1d7d739234 | 10,346 | ipynb | Jupyter Notebook | courses/machine_learning/deepdive/05_artandscience/b_hyperparam.ipynb | cjqian/training-data-analyst | d658f5098f7c5940f00eb2f52e391fcc8bb45a77 | [
"Apache-2.0"
] | null | null | null | courses/machine_learning/deepdive/05_artandscience/b_hyperparam.ipynb | cjqian/training-data-analyst | d658f5098f7c5940f00eb2f52e391fcc8bb45a77 | [
"Apache-2.0"
] | null | null | null | courses/machine_learning/deepdive/05_artandscience/b_hyperparam.ipynb | cjqian/training-data-analyst | d658f5098f7c5940f00eb2f52e391fcc8bb45a77 | [
"Apache-2.0"
] | 2 | 2019-12-11T15:08:11.000Z | 2020-12-02T06:15:41.000Z | 29.56 | 553 | 0.532186 | [
[
[
"# Hyperparameter tuning with Cloud ML Engine",
"_____no_output_____"
],
[
"**Learning Objectives:**\n * Improve the accuracy of a model by hyperparameter tuning",
"_____no_output_____"
]
],
[
[
"import os\nPROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID\nBUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME\nREGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1\nos.environ['TFVERSION'] = '1.8' # Tensorflow version",
"_____no_output_____"
],
[
"# for bash\nos.environ['PROJECT'] = PROJECT\nos.environ['BUCKET'] = BUCKET\nos.environ['REGION'] = REGION",
"_____no_output_____"
],
[
"%%bash\ngcloud config set project $PROJECT\ngcloud config set compute/region $REGION",
"_____no_output_____"
]
],
[
[
"## Create command-line program\n\nIn order to submit to Cloud ML Engine, we need to create a distributed training program. Let's convert our housing example to fit that paradigm, using the Estimators API.",
"_____no_output_____"
]
],
[
[
"%%bash\nrm -rf trainer\nmkdir trainer\ntouch trainer/__init__.py",
"_____no_output_____"
],
[
"%%writefile trainer/house.py\nimport os\nimport math\nimport json\nimport shutil\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\ndef train(output_dir, batch_size, learning_rate):\n tf.logging.set_verbosity(tf.logging.INFO)\n \n # Read dataset and split into train and eval\n df = pd.read_csv(\"https://storage.googleapis.com/ml_universities/california_housing_train.csv\", sep=\",\")\n df['num_rooms'] = df['total_rooms'] / df['households']\n msk = np.random.rand(len(df)) < 0.8\n traindf = df[msk]\n evaldf = df[~msk]\n\n # Train and eval input functions\n SCALE = 100000\n \n train_input_fn = tf.estimator.inputs.pandas_input_fn(x = traindf[[\"num_rooms\"]],\n y = traindf[\"median_house_value\"] / SCALE, # note the scaling\n num_epochs = 1,\n batch_size = batch_size, # note the batch size\n shuffle = True)\n \n eval_input_fn = tf.estimator.inputs.pandas_input_fn(x = evaldf[[\"num_rooms\"]],\n y = evaldf[\"median_house_value\"] / SCALE, # note the scaling\n num_epochs = 1,\n batch_size = len(evaldf),\n shuffle=False)\n \n # Define feature columns\n features = [tf.feature_column.numeric_column('num_rooms')]\n \n def train_and_evaluate(output_dir):\n # Compute appropriate number of steps\n num_steps = (len(traindf) / batch_size) / learning_rate # if learning_rate=0.01, hundred epochs\n\n # Create custom optimizer\n myopt = tf.train.FtrlOptimizer(learning_rate = learning_rate) # note the learning rate\n\n # Create rest of the estimator as usual\n estimator = tf.estimator.LinearRegressor(model_dir = output_dir, \n feature_columns = features, \n optimizer = myopt)\n\n train_spec = tf.estimator.TrainSpec(input_fn = train_input_fn,\n max_steps = num_steps)\n eval_spec = tf.estimator.EvalSpec(input_fn = eval_input_fn,\n steps = None)\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n\n # Run the training\n shutil.rmtree(output_dir, ignore_errors=True) # start fresh each time\n train_and_evaluate(output_dir)\n \nif __name__ == '__main__' and \"get_ipython\" not in dir():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--learning_rate',\n type = float, \n default = 0.01\n )\n parser.add_argument(\n '--batch_size',\n type = int, \n default = 30\n ),\n parser.add_argument(\n '--job-dir',\n help = 'GCS location to write checkpoints and export models.',\n required = True\n )\n args = parser.parse_args()\n print(\"Writing checkpoints to {}\".format(args.job_dir))\n train(args.job_dir, args.batch_size, args.learning_rate)",
"_____no_output_____"
],
[
"%%bash\nrm -rf house_trained\ngcloud ml-engine local train \\\n --module-name=trainer.house \\\n --job-dir=house_trained \\\n --package-path=$(pwd)/trainer \\\n -- \\\n --batch_size=30 \\\n --learning_rate=0.02",
"_____no_output_____"
]
],
[
[
"# Create hyperparam.yaml",
"_____no_output_____"
]
],
[
[
"%%writefile hyperparam.yaml\ntrainingInput:\n hyperparameters:\n goal: MINIMIZE\n maxTrials: 5\n maxParallelTrials: 1\n hyperparameterMetricTag: average_loss\n params:\n - parameterName: batch_size\n type: INTEGER\n minValue: 8\n maxValue: 64\n scaleType: UNIT_LINEAR_SCALE\n - parameterName: learning_rate\n type: DOUBLE\n minValue: 0.01\n maxValue: 0.1\n scaleType: UNIT_LOG_SCALE",
"_____no_output_____"
],
[
"%%bash\nOUTDIR=gs://${BUCKET}/house_trained # CHANGE bucket name appropriately\ngsutil rm -rf $OUTDIR\ngcloud ml-engine jobs submit training house_$(date -u +%y%m%d_%H%M%S) \\\n --config=hyperparam.yaml \\\n --module-name=trainer.house \\\n --package-path=$(pwd)/trainer \\\n --job-dir=$OUTDIR \\\n --runtime-version=$TFVERSION \\",
"_____no_output_____"
],
[
"!gcloud ml-engine jobs describe house_180403_231031 # CHANGE jobId appropriately",
"_____no_output_____"
]
],
[
[
"## Challenge exercise\nAdd a few engineered features to the housing model, and use hyperparameter tuning to choose which set of features the model uses.\n\n<p>\nCopyright 2018 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7ad27ff68241c604933df082bba1e8ed71935ff | 111,187 | ipynb | Jupyter Notebook | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app | 885b8d1902d2ebfaf8eca25bbf302324401da7ca | [
"Unlicense"
] | null | null | null | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app | 885b8d1902d2ebfaf8eca25bbf302324401da7ca | [
"Unlicense"
] | null | null | null | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app | 885b8d1902d2ebfaf8eca25bbf302324401da7ca | [
"Unlicense"
] | null | null | null | 60.003778 | 22,160 | 0.704039 | [
[
[
"# Big Brother - Healthcare edition",
"_____no_output_____"
],
[
"### Building a classifier using the [fastai](https://www.fast.ai/) library ",
"_____no_output_____"
]
],
[
[
"from fastai.tabular import *",
"_____no_output_____"
],
[
"#hide\npath = Path('./covid19_ml_education')",
"_____no_output_____"
],
[
"df = pd.read_csv(path/'covid_ml.csv')",
"_____no_output_____"
],
[
"df.head(3)",
"_____no_output_____"
]
],
[
[
"## Independent variable\n\nThis is the value we want to predict",
"_____no_output_____"
]
],
[
[
"y_col = 'urgency_of_admission'",
"_____no_output_____"
]
],
[
[
"## Dependent variable\n\nThe values on which we can make a prediciton",
"_____no_output_____"
]
],
[
[
"cat_names = ['sex', 'cough', 'fever', 'chills', 'sore_throat', 'headache', 'fatigue']",
"_____no_output_____"
],
[
"cat_names = ['sex', 'cough', 'fever', 'headache', 'fatigue']",
"_____no_output_____"
],
[
"cont_names = ['age']",
"_____no_output_____"
],
[
"#hide\nprocs = [FillMissing, Categorify, Normalize]",
"_____no_output_____"
],
[
"#hide\ntest = TabularList.from_df(df.iloc[660:861].copy(), path = path, cat_names= cat_names, cont_names = cont_names)",
"_____no_output_____"
],
[
"data = (TabularList.from_df(df, path=path, cat_names=cat_names, cont_names=cont_names, procs = procs)\n .split_by_rand_pct(0.2)\n .label_from_df(cols=y_col)\n# .add_test(test)\n .databunch() )",
"_____no_output_____"
],
[
"data.show_batch(rows=5)",
"_____no_output_____"
]
],
[
[
"## Model\n\nHere we build our machine learning model that will learn from the dataset to classify between patients",
"_____no_output_____"
],
[
"### Using Focal Loss",
"_____no_output_____"
]
],
[
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nclass FocalLoss(nn.Module):\n def __init__(self, gamma=0, alpha=None, size_average=True):\n super(FocalLoss, self).__init__()\n self.gamma = gamma\n self.alpha = alpha\n if isinstance(alpha,(float,int)): self.alpha = torch.Tensor([alpha,1-alpha])\n if isinstance(alpha,list): self.alpha = torch.Tensor(alpha)\n self.size_average = size_average\n\n def forward(self, input, target):\n if input.dim()>2:\n input = input.view(input.size(0),input.size(1),-1) # N,C,H,W => N,C,H*W\n input = input.transpose(1,2) # N,C,H*W => N,H*W,C\n input = input.contiguous().view(-1,input.size(2)) # N,H*W,C => N*H*W,C\n target = target.view(-1,1)\n\n logpt = F.log_softmax(input)\n logpt = logpt.gather(1,target)\n logpt = logpt.view(-1)\n pt = Variable(logpt.data.exp())\n\n if self.alpha is not None:\n if self.alpha.type()!=input.data.type():\n self.alpha = self.alpha.type_as(input.data)\n at = self.alpha.gather(0,target.data.view(-1))\n logpt = logpt * Variable(at)\n\n loss = -1 * (1-pt)**self.gamma * logpt\n if self.size_average: return loss.mean()\n else: return loss.sum()\n",
"_____no_output_____"
],
[
"learn = tabular_learner(data, layers = [150,50], \\\n metrics = [accuracy,FBeta(\"macro\")])",
"_____no_output_____"
],
[
"learn.load('150-50-focal')",
"_____no_output_____"
],
[
"learn.loss_func = FocalLoss()",
"_____no_output_____"
],
[
"#hide\nlearn.fit_one_cycle(5, 1e-4, wd= 0.2)",
"_____no_output_____"
],
[
"learn.save('150-50-focal')",
"_____no_output_____"
],
[
"learn.export('150-50-focal.pth')",
"_____no_output_____"
],
[
"#hide\ntestdf = df.iloc[660:861].copy()",
"_____no_output_____"
],
[
"testdf.urgency.value_counts()",
"_____no_output_____"
],
[
"testdf.head()",
"_____no_output_____"
],
[
"testdf = testdf.iloc[:,1:]",
"_____no_output_____"
],
[
"#hide\ntestdf.insert(0, 'predictions','')",
"_____no_output_____"
],
[
"#hide\nfor i in range(len(testdf)):\n row = testdf.iloc[i][1:]\n testdf.predictions.iloc[i] = str(learn.predict(row)[0])",
"/usr/local/lib/python3.7/site-packages/pandas/core/indexing.py:205: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self._setitem_with_indexer(indexer, value)\n"
]
],
[
[
"### Making predictions\n\nWe've taken out a test set to see how well our model works, by making predictions on them.\n\nInterestingly, all those predicted with 'High' urgency have a common trait of absence of **chills** and **sore throat**",
"_____no_output_____"
]
],
[
[
"testdf.urgency.value_counts()",
"_____no_output_____"
],
[
"testdf.predictions.value_counts()",
"_____no_output_____"
],
[
"from sklearn.metrics import classification_report",
"_____no_output_____"
],
[
"print(classification_report(testdf.predictions, testdf.urgency, labels = [\"High\", \"Low\"]))",
" precision recall f1-score support\n\n High 0.60 0.35 0.44 78\n Low 0.59 0.80 0.68 90\n\n accuracy 0.59 168\n macro avg 0.59 0.57 0.56 168\nweighted avg 0.59 0.59 0.57 168\n\n"
],
[
"print(classification_report(testdf.predictions, testdf.urgency, labels = [\"High\", \"Low\"]))",
" precision recall f1-score support\n\n High 0.40 0.35 0.37 52\n Low 0.72 0.77 0.74 116\n\n accuracy 0.64 168\n macro avg 0.56 0.56 0.56 168\nweighted avg 0.62 0.64 0.63 168\n\n"
],
[
"testdf = pd.read_csv('processed_over_test.csv')",
"_____no_output_____"
],
[
"testdf = testdf.iloc[:,1:]",
"_____no_output_____"
],
[
"testdf.head()",
"_____no_output_____"
],
[
"yesnomapper = {1:'Yes', 0: 'No'}",
"_____no_output_____"
],
[
"for col in testdf.columns[2:-1]:\n testdf[col]= testdf[col].map(yesnomapper",
"_____no_output_____"
],
[
"testdf['sex'] = testdf['sex'].map({1: 'male', 0:'female'})",
"_____no_output_____"
],
[
"testdf['urgency'] = testdf['urgency'].map({0:'Low', 1:'High'})",
"_____no_output_____"
],
[
"from sklearn.metrics import confusion_matrix",
"_____no_output_____"
],
[
"cm_test = confusion_matrix(testdf.urgency, testdf.predictions)",
"_____no_output_____"
],
[
"cm_test",
"_____no_output_____"
],
[
"cm_test = np.array([[72, 51], [18,27]])",
"_____no_output_____"
],
[
"cm_test",
"_____no_output_____"
],
[
"cm_test2 = np.array([[94, 29],[30,15]])",
"_____no_output_____"
],
[
"df_cm",
"_____no_output_____"
],
[
"import seaborn as sn\nimport pandas as pd\n\nfig, ax = plt.subplots()\nfig.set_size_inches(7,5)\ndf_cm = pd.DataFrame(cm_test2, index = ['Actual Low','Actual High'],\n columns = ['Predicted Low','Predicted High'])\nsns.set(font_scale=1.2)\nsn.heatmap(df_cm, annot=True, ax = ax)\nax.set_ylim([0,2]);\nax.set_title('Deep Model Confusion Matrix')\nfig.savefig('DeepModel_CM.png')",
"_____no_output_____"
]
],
[
[
"## Profile after focal loss",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\nimport pandas as pd\n\nfig, ax = plt.subplots()\nfig.set_size_inches(7,5)\ndf_cm = pd.DataFrame(cm_test, index = ['Actual Low','Actual High'],\n columns = ['Predicted Low','Predicted High'])\nsns.set(font_scale=1.2)\nsns.heatmap(df_cm, annot=True, ax = ax)\nax.set_ylim([0,2]);\nax.set_title('Deep Model Confusion Matrix (with Focal Loss)');\nfig.savefig('DeepModel_CM_Focal Loss.png')",
"_____no_output_____"
],
[
"import seaborn as sns\nimport pandas as pd\n\nfig, ax = plt.subplots()\nfig.set_size_inches(7,5)\ndf_cm = pd.DataFrame(cm_test, index = ['Actual Low','Actual High'],\n columns = ['Predicted Low','Predicted High'])\nsns.set(font_scale=1.2)\nsns.heatmap(df_cm, annot=True, ax = ax)\nax.set_ylim([0,2]);\nax.set_title('Deep Model Confusion Matrix (with Focal Loss)');",
"_____no_output_____"
],
[
"testdf.head()",
"_____no_output_____"
],
[
"row = testdf.iloc[0]",
"_____no_output_____"
],
[
"round(float(learn.predict(row[1:-1])[2][0]),5)",
"_____no_output_____"
]
],
[
[
"## Experimental Section\n\nTrying to figure out top ",
"_____no_output_____"
]
],
[
[
"for i in range(len(testdf)):\n row = testdf.iloc[i][1:]\n testdf.probability.iloc[i] = round(float(learn.predict(row[1:-1])[2][0]),5)",
"/usr/local/lib/python3.7/site-packages/pandas/core/indexing.py:205: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self._setitem_with_indexer(indexer, value)\n"
],
[
"testdf.head()",
"_____no_output_____"
],
[
"testdf.sort_values(by=['probability'],ascending = False, inplace = True)",
"_____no_output_____"
],
[
"#\ncumulative lift gain\n\nbaseline model - test 20%",
"_____no_output_____"
],
[
"Cost based affection \n\nGive kits only top 20%\n\nProfiling them:\nHow you can get the probs?\nDecile?\n\nsubsetting your group - divide 100 people into ten equal groups\ndescending order of probability\n\nprofile them: see features (prediction important features)\n \ntop 20 vs rest 80\n\nDescriptive statistics (count, mean, median, average)\n\nHow are they different? (see a big distinction top 20 top 80)\n\nfigure out what is happening\n\n\n\nquestions:\n \nlift curve\n\n ",
"_____no_output_____"
],
[
"#\n\n1. GET PROBABILITIES\n2. MAKE DECILES\n3. MAKE CURVE\n4. PROFILING (feature selection - HOW ARE THEY BEHAVING??)\n\nOptional:\n \nWork with different thresholds",
"_____no_output_____"
],
[
"Confusion matrix to risk matrix (cost what minimizes - risk utility matrix)",
"_____no_output_____"
],
[
"import scikitplot as skplt",
"_____no_output_____"
],
[
"skplt.metrics.plot_cumulative_gain(y_true = testdf.urgency, testdf.probability)\n# plt.savefig('lift_curve.png')\nplt.show()",
"_____no_output_____"
],
[
"df['decile1'] = pd.qcut(df['pred_prob'].rank(method='first'), 10, labels=np.arange(10, 0, -1))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ad3c58625ff9c0acff5f39a4bd93e6cc400268 | 36,139 | ipynb | Jupyter Notebook | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples | a33f481707014025b41857966144b4a59d6c553b | [
"MIT-0"
] | 298 | 2018-04-16T17:34:01.000Z | 2022-03-27T06:53:21.000Z | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples | a33f481707014025b41857966144b4a59d6c553b | [
"MIT-0"
] | 24 | 2018-06-07T12:48:56.000Z | 2022-03-29T14:28:06.000Z | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples | a33f481707014025b41857966144b4a59d6c553b | [
"MIT-0"
] | 132 | 2018-05-31T02:58:04.000Z | 2022-03-29T21:02:05.000Z | 73.602851 | 1,419 | 0.675392 | [
[
[
"# Edgar Holdings \n\nThe examples in this notebook demonstrate using the GremlinPython library to connect to and work with a Neptune instance. Using a Jupyter notebook in this way provides a nice way to interact with your Neptune graph database in a familiar and instantly productive environment.",
"_____no_output_____"
],
[
"## Connect to the Neptune Database which has the load Edgar Data \n\nWhen the SageMaker notebook instance was created the appropriate Python libraries for working with a Tinkerpop enabled graph were installed. We now need to `import` some classes from those libraries before connecting to our Neptune instance, loading some sample data, and running queries. \n\nBelow are the packages that need to be installed. This should be executed once to configure the environment. ",
"_____no_output_____"
]
],
[
[
"!pip install --upgrade pip\n!pip install futures \n!pip install gremlinpython\n!pip install SPARQLWrapper\n!pip install tornado\n!pip install tornado-httpclient-session\n!pip install tornado-utils\n!pip install matplotlib\n!pip install numpy \n!pip install pandas \n!pip install networkx ",
"Requirement already up-to-date: pip in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (19.0.3)\nRequirement already satisfied: futures in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (3.1.1)\nRequirement already satisfied: gremlinpython in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (3.4.0)\nRequirement already satisfied: six>=1.10.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from gremlinpython) (1.11.0)\nRequirement already satisfied: tornado<5.0,>=4.4.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from gremlinpython) (4.5.3)\nRequirement already satisfied: aenum>=1.4.5 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from gremlinpython) (2.1.2)\nRequirement already satisfied: SPARQLWrapper in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (1.8.2)\nRequirement already satisfied: rdflib>=4.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from SPARQLWrapper) (4.2.2)\nRequirement already satisfied: isodate in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from rdflib>=4.0->SPARQLWrapper) (0.6.0)\nRequirement already satisfied: pyparsing in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from rdflib>=4.0->SPARQLWrapper) (2.2.0)\nRequirement already satisfied: six in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from isodate->rdflib>=4.0->SPARQLWrapper) (1.11.0)\nRequirement already satisfied: tornado in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (4.5.3)\nRequirement already satisfied: tornado-httpclient-session in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (0.2.5)\nRequirement already satisfied: tornado in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from tornado-httpclient-session) (4.5.3)\nRequirement already satisfied: tornado-utils in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (1.6)\nRequirement already satisfied: matplotlib in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (2.2.2)\nRequirement already satisfied: cycler>=0.10 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (0.10.0)\nRequirement already satisfied: numpy>=1.7.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (1.14.5)\nRequirement already satisfied: kiwisolver>=1.0.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (1.0.1)\nRequirement already satisfied: python-dateutil>=2.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (2.7.3)\nRequirement already satisfied: pytz in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (2018.4)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (2.2.0)\nRequirement already satisfied: six>=1.10 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (1.11.0)\nRequirement already satisfied: setuptools in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from kiwisolver>=1.0.1->matplotlib) (39.1.0)\nRequirement already satisfied: numpy in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (1.14.5)\nRequirement already satisfied: pandas in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (0.22.0)\nRequirement already satisfied: pytz>=2011k in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pandas) (2018.4)\nRequirement already satisfied: numpy>=1.9.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pandas) (1.14.5)\nRequirement already satisfied: python-dateutil>=2 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pandas) (2.7.3)\nRequirement already satisfied: six>=1.5 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from python-dateutil>=2->pandas) (1.11.0)\nRequirement already satisfied: networkx in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (2.1)\nRequirement already satisfied: decorator>=4.1.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from networkx) (4.3.0)\n"
]
],
[
[
"## Establish access to our Neptune instance\n\nBefore we can work with our graph we need to establish a connection to it. This is done using the `DriverRemoteConnection` capability as defined by Apache TinkerPop and supported by GremlinPython. The `neptune.py` helper module facilitates creating this connection.\n\nOnce this cell has been run we will be able to use the variable `g` to refer to our graph in Gremlin queries in subsequent cells. By default Neptune uses port 8182 and that is what we connect to below. When you configure your own Neptune instance you can you choose a different endpoint and port number by specifiying the `neptune_endpoint` and `neptune_port` parameters to the `graphTraversal()` method.",
"_____no_output_____"
]
],
[
[
"from gremlin_python import statics\nfrom gremlin_python.structure.graph import Graph\nfrom gremlin_python.process.graph_traversal import __\nfrom gremlin_python.process.strategies import *\nfrom gremlin_python.driver.driver_remote_connection import DriverRemoteConnection\n\nendpoint=\"wss://dbfindata.carpeooi4ov5.us-east-1.neptune.amazonaws.com:8182/gremlin\"\ngraph=Graph()\ng=graph.traversal().withRemote(DriverRemoteConnection(endpoint,'g'))",
"_____no_output_____"
]
],
[
[
"## Let's find out a bit about the graph\n\nLet's start off with a simple query just to make sure our connection to Neptune is working. The queries below look at all of the vertices and edges in the graph and create two maps that show the demographic of the graph. As we are using the air routes data set, not surprisingly, the values returned are related to airports and routes.",
"_____no_output_____"
]
],
[
[
"vertices = g.V().groupCount().by(T.label).toList()\nedges = g.E().groupCount().by(T.label).toList()\nprint(vertices)\nprint(edges)",
"_____no_output_____"
]
],
[
[
"## Find routes longer than 8,400 miles\n\nThe query below finds routes in the graph that are longer than 8,400 miles. This is done by examining the `dist` property of the `routes` edges in the graph. Having found some edges that meet our criteria we sort them in descending order by distance. The `where` step filters out the reverse direction routes for the ones that we have already found beacuse we do not, in this case, want two results for each route. As an experiment, try removing the `where` line and observe the additional results that are returned. Lastly we generate some `path` results using the airport codes and route distances. Notice how we have laid the Gremlin query out over multiple lines to make it easier to read. To avoid errors, when you lay out a query in this way using Python, each line must end with a backslash character \"\\\".\n\nThe results from running the query will be placed into the variable `paths`. Notice how we ended the Gremlin query with a call to `toList`. This tells Gremlin that we want our results back in a list. We can then use a Python `for` loop to print those results. Each entry in the list will itself be a list containing the starting airport code, the length of the route and the destination airport code.",
"_____no_output_____"
]
],
[
[
"paths = g.V().hasLabel('airport').as_('a') \\\n .outE('route').has('dist',gt(8400)) \\\n .order().by('dist',Order.decr) \\\n .inV() \\\n .where(P.lt('a')).by('code') \\\n .path().by('code').by('dist').by('code').toList()\n\nfor p in paths:\n print(p)",
"_____no_output_____"
]
],
[
[
"## Draw a Bar Chart that represents the routes we just found.\n\nOne of the nice things about using Python to work with our graph is that we can take advantage of the larger Python ecosystem of libraries such as `matplotlib`, `numpy` and `pandas` to further analyze our data and represent it pictorially. So, now that we have found some long airline routes we can build a bar chart that represents them graphically.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt; plt.rcdefaults()\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n \nroutes = list()\ndist = list()\n\n# Construct the x-axis labels by combining the airport pairs we found\n# into strings with with a \"-\" between them. We also build a list containing\n# the distance values that will be used to construct and label the bars.\nfor i in range(len(paths)):\n routes.append(paths[i][0] + '-' + paths[i][2])\n dist.append(paths[i][1])\n\n# Setup everything we need to draw the chart\ny_pos = np.arange(len(routes))\ny_labels = (0,1000,2000,3000,4000,5000,6000,7000,8000,9000)\nfreq_series = pd.Series(dist) \nplt.figure(figsize=(11,6))\nfs = freq_series.plot(kind='bar')\nfs.set_xticks(y_pos, routes)\nfs.set_ylabel('Miles')\nfs.set_title('Longest routes')\nfs.set_yticklabels(y_labels)\nfs.set_xticklabels(routes)\nfs.yaxis.set_ticks(np.arange(0, 10000, 1000))\nfs.yaxis.set_ticklabels(y_labels)\n\n# Annotate each bar with the distance value\nfor i in range(len(paths)):\n fs.annotate(dist[i],xy=(i,dist[i]+60),xycoords='data',ha='center')\n\n# We are finally ready to draw the bar chart\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Explore the distribution of airports by continent\n\nThe next example queries the graph to find out how many airports are in each continent. The query starts by finding all vertices that are continents. Next, those vertices are grouped, which creates a map (or dict) whose keys are the continent descriptions and whose values represent the counts of the outgoing edges with a 'contains' label. Finally the resulting map is sorted using the keys in ascending order. That result is then returned to our Python code as the variable `m`. Finally we can print the map nicely using regular Python concepts.",
"_____no_output_____"
]
],
[
[
"# Return a map where the keys are the continent names and the values are the\n# number of airports in that continent.\nm = g.V().hasLabel('continent') \\\n .group().by('desc').by(__.out('contains').count()) \\\n .order(Scope.local).by(Column.keys) \\\n .next()\n\nfor c,n in m.items():\n print('%4d %s' %(n,c))",
"_____no_output_____"
]
],
[
[
"## Draw a pie chart representing the distribution by continent\n\nRather than return the results as text like we did above, it might be nicer to display them as percentages on a pie chart. That is what the code in the next cell does. Rather than return the descriptions of the continents (their names) this time our Gremlin query simply retrieves the two digit character code representing each continent.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt; plt.rcdefaults()\nimport numpy as np\n\n# Return a map where the keys are the continent codes and the values are the\n# number of airports in that continent.\nm = g.V().hasLabel('continent').group().by('code').by(__.out().count()).next()\n\nfig,pie1 = plt.subplots()\n\npie1.pie(m.values() \\\n ,labels=m.keys() \\\n ,autopct='%1.1f%%'\\\n ,shadow=True \\\n ,startangle=90 \\\n ,explode=(0,0,0.1,0,0,0,0))\n\npie1.axis('equal') \n\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Find some routes from London to San Jose and draw them\n\nOne of the nice things about connected graph data is that it lends itself nicely to visualization that people can get value from looking at. The Python `networkx` library makes it fairly easy to draw a graph. The next example takes advantage of this capability to draw a directed graph (DiGraph) of a few airline routes.\n\nThe query below starts by finding the vertex that represents London Heathrow (LHR). It then finds 15 routes from LHR that end up in San Jose California (SJC) with one stop on the way. Those routes are returned as a list of paths. Each path will contain the three character IATA codes representing the airports found.\n\nThe main purpose of this example is to show that we can easily extract part of a larger graph and render it graphically in a way that is easy for an end user to comprehend.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt; plt.rcdefaults()\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport networkx as nx\n\n# Find up to 15 routes from LHR to SJC that make one stop.\npaths = g.V().has('airport','code','LHR') \\\n .out().out().has('code','SJC').limit(15) \\\n .path().by('code').toList()\n\n# Create a new empty DiGraph\nG=nx.DiGraph()\n\n# Add the routes we found to DiGraph we just created\nfor p in paths:\n G.add_edge(p[0],p[1])\n G.add_edge(p[1],p[2])\n\n# Give the starting and ending airports a different color\ncolors = []\n\nfor label in G:\n if label in['LHR','SJC']:\n colors.append('yellow')\n else:\n colors.append('#11cc77')\n\n# Now draw the graph \nplt.figure(figsize=(5,5))\nnx.draw(G, node_color=colors, node_size=1200, with_labels=True)\nplt.show()",
"_____no_output_____"
]
],
[
[
"# PART 2 - Examples that use iPython Gremlin\n\nThis part of the notebook contains examples that use the iPython Gremlin Jupyter extension to work with a Neptune instance using Gremlin.",
"_____no_output_____"
],
[
"## Configuring iPython Gremlin to work with Neptune\n\nBefore we can start to use iPython Gremlin we need to load the Jupyter Kernel extension and configure access to our Neptune endpoint.",
"_____no_output_____"
]
],
[
[
"# Create a string containing the full Web Socket path to the endpoint\n# Replace <neptune-instance-name> with the name of your Neptune instance.\n# which will be of the form myinstance.us-east-1.neptune.amazonaws.com\n\n#neptune_endpoint = '<neptune-instance-name>'\nneptune_endpoint = os.environ['NEPTUNE_CLUSTER_ENDPOINT']\nneptune_port = os.environ['NEPTUNE_CLUSTER_PORT']\nneptune_gremlin_endpoint = 'ws://' + neptune_endpoint + ':' + neptune_port + '/gremlin'\n\n# Load the iPython Gremlin extension and setup access to Neptune.\n%load_ext gremlin\n%gremlin.connection.set_current $neptune_gremlin_endpoint",
"_____no_output_____"
]
],
[
[
"## Run this cell if you need to reload the Gremlin extension.\nOccaisionally it becomes necessary to reload the iPython Gremlin extension to make things work. Running this cell will do that for you.",
"_____no_output_____"
]
],
[
[
"# Re-load the iPython Gremlin Jupyter Kernel extension.\n%reload_ext gremlin",
"_____no_output_____"
]
],
[
[
"## A simple query to make sure we can connect to the graph. \n\nFind all the airports in England that are in London. Notice that when using iPython Gremlin you do not need to use a terminal step such as `next` or `toList` at the end of the query in order to get it to return results. As mentioned earlier in this post, the `%reset -f` is to work around a known issue with iPython Gremlin.",
"_____no_output_____"
]
],
[
[
"%reset -f\n%gremlin g.V().has('airport','region','GB-ENG') \\\n .has('city','London').values('desc')",
"_____no_output_____"
]
],
[
[
"### You can store the results of a query in a variable just as when using Gremlin Python.\nThe query below is the same as the previous one except that the results of running the query are stored in the variable 'places'. We can then work with that variable in our code.",
"_____no_output_____"
]
],
[
[
"%reset -f\nplaces = %gremlin g.V().has('airport','region','GB-ENG') \\\n .has('city','London').values('desc')\nfor p in places:\n print(p)",
"_____no_output_____"
]
],
[
[
"### Treating entire cells as Gremlin\nAny cell that begins with `%%gremlin` tells iPython Gremlin to treat the entire cell as Gremlin. You cannot mix Python code into these cells.",
"_____no_output_____"
]
],
[
[
"%%gremlin\ng.V().has('city','London').has('region','GB-ENG').count()\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ad3ce29eb4657f12bfcb9282c4b9564a5952c2 | 34,111 | ipynb | Jupyter Notebook | experimental-data/create_pd.ipynb | vvoelz/HDX-forward-model | 975c143a37ddc3769a63dd31e6a425390f88fc38 | [
"MIT"
] | null | null | null | experimental-data/create_pd.ipynb | vvoelz/HDX-forward-model | 975c143a37ddc3769a63dd31e6a425390f88fc38 | [
"MIT"
] | null | null | null | experimental-data/create_pd.ipynb | vvoelz/HDX-forward-model | 975c143a37ddc3769a63dd31e6a425390f88fc38 | [
"MIT"
] | null | null | null | 31.380865 | 360 | 0.373076 | [
[
[
"## Creating a pandas data frame for experimental PF values\n\nWan et al. (JCTC 2020) trained a forward model on experimentally measured HDX protection factors:\n\n* 72 PF values for backbone amides of ubiquitin taken from Craig et al.\n* 30 (of 53) for amibackbone amides of BPTI taken from Persson et al.\n\nIn this notebook we have converted the published values to $\\ln$ PF (natural log).\n\n### References\n\nWan, Hongbin, Yunhui Ge, Asghar Razavi, and Vincent A. Voelz. “Reconciling Simulated Ensembles of Apomyoglobin with Experimental Hydrogen/Deuterium Exchange Data Using Bayesian Inference and Multiensemble Markov State Models.” Journal of Chemical Theory and Computation 16, no. 2 (February 11, 2020): 1333–48. https://doi.org/10.1021/acs.jctc.9b01240.\n\nCraig, P. O.; Lätzer, J.; Weinkam, P.; Hoffman, R. M. B.; Ferreiro, D. U.; Komives, E. A.; Wolynes, P. G. Journal of the American Chemical Society 2011, 133, 17463–17472.\n\nPersson, F.; Halle, B. Proceedings of the National Academy of Sciences 2015, 112, 10383– 10388.\n",
"_____no_output_____"
]
],
[
[
"import os, sys\nimport numpy as np\nimport pandas as pd\n\n### Ubiquitin\n\nubiquitin_text =\"\"\"#residue\\tresnum\\tln PF \\\\\nGLN\t& 2\t& 6.210072 \\\\\nILE\t& 3\t& 13.7372227 \\\\\nPHE\t& 4\t& 13.4839383 \\\\\nVAL\t& 5\t& 13.1523661 \\\\\nLYS\t& 6\t& 10.6909026 \\\\\nTHR\t& 7\t& 10.4629467 \\\\\nLEU\t& 8\t& 0.67005226 \\\\\nTHR\t& 9\t& 0 \\\\\nGLY\t& 10\t& 3.93511792 \\\\\nLYS\t& 11\t& 5.21075007 \\\\\nTHR\t& 12\t& 3.2443424 \\\\\nILE\t& 13\t& 11.0570136 \\\\\nTHR\t& 14\t& 2.53514619 \\\\\nLEU\t& 15\t& 11.5336487 \\\\\nGLU\t& 16\t& 5.14167251 \\\\\nVAL\t& 17\t& 12.2405424 \\\\\nGLU\t& 18\t& 7.97845735 \\\\\nSER\t& 20\t& 3.82459384 \\\\\nASP\t& 21\t& 12.9796722 \\\\\nTHR\t& 22\t& 7.73438333 \\\\\nILE\t& 23\t& 11.2135894 \\\\\nGLU\t& 24\t& 5.00581999 \\\\\nASN\t& 25\t& 10.5550501 \\\\\nVAL\t& 26\t& 14.6214153 \\\\\nLYS\t& 27\t& 14.8539764 \\\\\nALA\t& 28\t& 11.4806893 \\\\\nLYS\t& 29\t& 13.4517021 \\\\\nILE\t& 30\t& 14.2483966 \\\\\nGLN\t& 31\t& 7.7689221 \\\\\nASP\t& 32\t& 5.6229128 \\\\\nLYS\t& 33\t& 4.56602624 \\\\\nGLU\t& 34\t& 6.21467717 \\\\\nGLY\t& 35\t& 6.26763662 \\\\\nILE\t& 36\t& 6.981438 \\\\\nASP\t& 39\t& 1.64174317 \\\\\nGLN\t& 40\t& 6.45875119 \\\\\nGLN\t& 41\t& 8.26167531 \\\\\nARG\t& 42\t& 9.13435506 \\\\\nLEU\t& 43\t& 6.56927527 \\\\\nILE\t& 44\t& 12.6573103 \\\\\nPHE\t& 45\t& 6.49328996 \\\\\nALA\t& 46\t& 0 \\\\\nGLY\t& 47\t& 4.1699816 \\\\\nLYS\t& 48\t& 7.86102551 \\\\\nGLN\t& 49\t& 3.80617316 \\\\\nLEU\t& 50\t& 8.45969763 \\\\\nGLU\t& 51\t& 5.41798272 \\\\\nASP\t& 52\t& 2.73316851 \\\\\nGLY\t& 53\t& 3.31802512 \\\\\nARG\t& 54\t& 9.9932193 \\\\\nTHR\t& 55\t& 11.3494419 \\\\\nLEU\t& 56\t& 13.0211187 \\\\\nSER\t& 57\t& 6.68440452 \\\\\nASP\t& 58\t& 6.84098031 \\\\\nTYR\t& 59\t& 10.9580025 \\\\\nASN\t& 60\t& 5.11404149 \\\\\nILE\t& 61\t& 8.54949845 \\\\\nGLN\t& 62\t& 8.27088565 \\\\\nLYS\t& 63\t& 3.09927954 \\\\\nGLU\t& 64\t& 6.37125295 \\\\\nSER\t& 65\t& 7.52484808 \\\\\nTHR\t& 66\t& 6.1939539 \\\\\nLEU\t& 67\t& 7.75740918 \\\\\nHIS\t& 68\t& 8.49884158 \\\\\nLEU\t& 69\t& 7.95773408 \\\\\nVAL\t& 70\t& 9.09981629 \\\\\nLEU\t& 71\t& 3.0278994 \\\\\nARG\t& 72\t& 2.5788953 \\\\\nLEU\t& 73\t& 0 \\\\\nARG\t& 74\t& 0 \\\\\nGLY\t& 75\t& 0 \\\\\nGLY\t& 76\t& 0 \\\\\"\"\"\n\nubiquitin_text = ubiquitin_text.replace('\t& ','\\t').replace(' \\\\','')\n\n# print(ubiquitin_text)\nfout = open('ubiquitin_lnPF.txt', 'w')\nfout.write(ubiquitin_text)\nfout.close()\n\nubi = pd.read_csv('ubiquitin_lnPF.txt', header=0, sep='\\t')\nubi",
"_____no_output_____"
],
[
"### BPTI\n\nbpti_text =\"\"\"#residue\\tresnum\\tln PF \\\\\nCYS\t& 5\t& 8.52877518 \\\\\nLEU\t& 6\t& 7.43504727 \\\\\nGLU\t& 7\t& 8.229439 \\\\\nTYR\t& 10\t& 5.756463 \\\\\nGLY\t& 12\t& 3.840712 \\\\\nALA\t& 16\t& 6.963017 \\\\\nARG\t& 17\t& 1.752267 \\\\\nIIE\t& 18\t& 12.37639 \\\\\nIIE\t& 19\t& 2.256533 \\\\\nALA\t& 25\t& 3.04632 \\\\\nGLY\t& 28\t& 7.676819 \\\\\nLEU\t& 29\t& 10.85899 \\\\\nCYS\t& 30\t& 3.677228 \\\\\nTHR\t& 32\t& 5.701201 \\\\\nVAL\t& 34\t& 3.734793 \\\\\nTYR\t& 35\t& 11.23431 \\\\\nGLY\t& 36\t& 9.574149 \\\\\nGLY\t& 37\t& 11.43924 \\\\\nCYS\t& 38\t& 4.503856 \\\\\nLYS\t& 41\t& 6.988346 \\\\\nARG\t& 42\t& 2.141404 \\\\\nASN\t& 43\t& 5.125554 \\\\\nASN\t& 44\t& 14.02274 \\\\\nSER\t& 47\t& 4.503856 \\\\\nALA\t& 48\t& 2.403899 \\\\\nMET\t& 52\t& 11.02938 \\\\\nARG\t& 53\t& 9.825131 \\\\\nTHR\t& 54\t& 7.962339 \\\\\nCYS\t& 55\t& 12.1139 \\\\\nGLY\t& 56\t& 8.008391 \\\\\"\"\"\n\nbpti_text = bpti_text.replace('\t& ','\\t').replace(' \\\\','')\n\n# print(bpti_text)\nfout = open('bpti_lnPF.txt', 'w')\nfout.write(bpti_text)\nfout.close()\n\nbpti = pd.read_csv('bpti_lnPF.txt', header=0, sep='\\t')\nbpti",
"_____no_output_____"
],
[
"### Finally, we make a data frame that concatenates the ubiquitin and BPTI values\nubi_bpti = pd.concat([ubi, bpti], ignore_index=True)\nubi_bpti\n\n# Also, let's write a text file version too\nubi_lines = ubiquitin_text.split('\\n')\nbpti_lines = bpti_text.split('\\n')\nubi_bpti_lines = ubi_lines + bpti_lines[1:]\n\nfout = open('ubi_bpti_lnPF.txt', 'w')\nfout.writelines(\"%s\\n\" % l for l in ubi_bpti_lines)\nfout.close()\n",
"_____no_output_____"
],
[
"# write all the data frames to JSON\nubi.to_json('ubiquitin_lnPF.json')\nbpti.to_json('bpti_lnPF.json')\nubi_bpti.to_json('ubi_bpti_lnPF.json')",
"_____no_output_____"
],
[
"# write a numpy array of JUST the lnPF values \nall_lnPF_values = np.array(ubi_bpti['ln PF'])\nall_lnPF_values\nnp.save('ubi_bpti_lnPF.npy',all_lnPF_values)\n\n### VERIFY that this data matches Hongbin's earlier data file\nall_lnPF_values_HONGBIN = np.load('ubi_bpti_all_exp_data_in_ln.npy')\n\nprint('all_lnPF_values.shape', all_lnPF_values.shape)\nprint('all_lnPF_values_HONGBIN.shape', all_lnPF_values_HONGBIN.shape)\n\nfor i in range(all_lnPF_values_HONGBIN.shape[0]):\n print(all_lnPF_values[i], all_lnPF_values_HONGBIN[i])",
"all_lnPF_values.shape (102,)\nall_lnPF_values_HONGBIN.shape (102,)\n6.210072 6.210071995804942\n13.737222699999998 13.737222664802477\n13.4839383 13.483938304573131\n13.1523661 13.152366051181989\n10.6909026 10.690902586771355\n10.4629467 10.462946662564942\n0.67005226 0.6700522620612673\n0.0 0.0\n3.93511792 3.9351179239268244\n5.21075007 5.210750065445525\n3.2443424 3.2443423960286104\n11.0570136 11.057013616557407\n2.53514619 2.5351461873864443\n11.533648699999999 11.533648730807176\n5.14167251 5.141672512655704\n12.2405424 12.240542354356347\n7.97845735 7.978457347224368\n3.82459384 3.82459383946311\n12.9796722 12.979672169207435\n7.73438333 7.7343833273669995\n11.2135894 11.213589402881002\n5.00581999 5.005819992169055\n10.555050099999999 10.555050066284705\n14.621415300000002 14.62141534051219\n14.853976399999999 14.853976434904588\n11.480689300000002 11.480689273668311\n13.4517021 13.451702113271214\n14.248396599999998 14.248396555447155\n7.768922099999999 7.76892210376191\n5.6229128 5.62291279709146\n4.56602624 4.566026239407193\n6.21467717 6.214677165990929\n6.26763662 6.267636623129793\n6.981438000000001 6.9814380019579465\n1.64174317 1.6417431713047546\n6.45875119 6.458751185848299\n8.26167531 8.261675313662636\n9.13435506 9.13435506390738\n6.56927527 6.569275270312013\n12.6573103 12.65731025618827\n6.49328996 6.4932899622432085\n0.0 0.0\n4.1699816 4.169981603412217\n7.86102551 7.861025507481672\n3.80617316 3.8061731587191576\n8.45969763 8.459697631660124\n5.41798272 5.41798272381499\n2.73316851 2.7331685053839325\n3.31802512 3.31802511900442\n9.993219300000002 9.993219303594158\n11.3494419 11.349441923367651\n13.021118699999999 13.02111870088133\n6.68440452 6.684404524961715\n6.84098031 6.84098031128531\n10.9580025 10.958002457558663\n5.11404149 5.114041491539775\n8.54949845 8.549498450286892\n8.27088565 8.270885654034613\n3.09927954 3.0992795351699858\n6.37125295 6.371252952314524\n7.52484808 7.524848083904541\n6.1939539 6.193953900153983\n7.75740918 7.757409178296941\n8.49884158 8.498841578241022\n7.95773408 7.9577340813874216\n9.09981629 9.099816287512468\n3.0278994 3.02789939728717\n2.5788952999999997 2.5788953041533316\n0.0 0.0\n0.0 0.0\n0.0 0.0\n0.0 0.0\n8.52877518 8.528775184449946\n7.43504727 7.435047265277774\n8.229439 8.229439122360718\n5.756463 5.756462732485114\n3.8407120000000003 3.840711935114068\n6.963017 6.963017321213994\n1.7522669999999998 1.7522672557684686\n12.376389999999999 12.376394874842996\n2.256533 2.2565333911341647\n3.04632 3.046320078031122\n7.676819 7.676818700042149\n10.858989999999999 10.85899129855992\n3.677228 3.677228393511491\n5.701201 5.701200690253257\n3.734793 3.7347930208363422\n11.23431 11.234312668717948\n9.574149 9.574148816669243\n11.43924 11.439242741994418\n4.503856 4.503856441896353\n6.988346000000001 6.988345757236929\n2.141404 2.1414041364844625\n5.125554 5.125554417004746\n14.022739999999999 14.022743216333739\n4.503856 4.503856441896353\n2.403899 2.4038988370857837\n11.02938 11.02938259544148\n9.825130999999999 9.825130591805594\n7.962339 7.96233925157341\n12.1139 12.113900174241675\n8.008391 8.008390953433292\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e7ad477b1da47ef20bfc32c0e89bf99fe01c95cc | 307,280 | ipynb | Jupyter Notebook | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito | 3cea137538b641bb1788fde65176ffcf82ab0990 | [
"MIT"
] | null | null | null | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito | 3cea137538b641bb1788fde65176ffcf82ab0990 | [
"MIT"
] | 3 | 2020-11-30T06:23:14.000Z | 2022-03-07T19:02:27.000Z | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | cha-tzi/devito | 45b14b7625a21631bd026a0c77911bc46dad9ead | [
"MIT"
] | null | null | null | 253.950413 | 158,572 | 0.905344 | [
[
[
"# Implementation of a Devito skew self adjoint variable density visco- acoustic isotropic modeling operator <br>-- Correctness Testing --\n\n## This operator is contributed by Chevron Energy Technology Company (2020)\n\nThis operator is based on simplfications of the systems presented in:\n<br>**Self-adjoint, energy-conserving second-order pseudoacoustic systems for VTI and TTI media for reverse time migration and full-waveform inversion** (2016)\n<br>Kenneth Bube, John Washbourne, Raymond Ergas, and Tamas Nemeth\n<br>SEG Technical Program Expanded Abstracts\n<br>https://library.seg.org/doi/10.1190/segam2016-13878451.1",
"_____no_output_____"
],
[
"## Introduction \n\nThe goal of this tutorial set is to generate and prove correctness of modeling and inversion capability in Devito for variable density visco- acoustics using an energy conserving form of the wave equation. We describe how the linearization of the energy conserving *skew self adjoint* system with respect to modeling parameters allows using the same modeling system for all nonlinear and linearized forward and adjoint finite difference evolutions. There are three notebooks in this series:\n\n##### 1. Implementation of a Devito skew self adjoint variable density visco- acoustic isotropic modeling operator -- Nonlinear Ops\n- Implement the nonlinear modeling operations. \n- [ssa_01_iso_implementation1.ipynb](ssa_01_iso_implementation1.ipynb)\n\n##### 2. Implementation of a Devito skew self adjoint variable density visco- acoustic isotropic modeling operator -- Linearized Ops\n- Implement the linearized (Jacobian) ```forward``` and ```adjoint``` modeling operations.\n- [ssa_02_iso_implementation2.ipynb](ssa_02_iso_implementation2.ipynb)\n\n##### 3. Implementation of a Devito skew self adjoint variable density visco- acoustic isotropic modeling operator -- Correctness Testing\n- Tests the correctness of the implemented operators.\n- [ssa_03_iso_correctness.ipynb](ssa_03_iso_correctness.ipynb)\n\nThere are similar series of notebooks implementing and testing operators for VTI and TTI anisotropy ([README.md](README.md)).\n\nBelow we describe a suite of unit tests that prove correctness for our *skew self adjoint* operators.",
"_____no_output_____"
],
[
"## Outline \n1. Define symbols\n2. Definition of correctness tests \n3. Analytic response in the far field \n4. Modeling operator linearity test, with respect to source \n5. Modeling operator adjoint test, with respect to source \n6. Nonlinear operator linearization test, with respect to model \n7. Jacobian operator linearity test, with respect to model \n8. Jacobian operator adjoint test, with respect to model \n9. Skew symmetry test for shifted derivatives \n10. References \n",
"_____no_output_____"
],
[
"## Table of symbols\n\nWe show the symbols here relevant to the implementation of the linearized operators.\n\n| Symbol | Description | Dimensionality | \n|:---|:---|:---|\n| $\\overleftarrow{\\partial_t}$ | shifted first derivative wrt $t$ | shifted 1/2 sample backward in time |\n| $\\partial_{tt}$ | centered second derivative wrt $t$ | centered in time |\n| $\\overrightarrow{\\partial_x},\\ \\overrightarrow{\\partial_y},\\ \\overrightarrow{\\partial_z}$ | + shifted first derivative wrt $x,y,z$ | shifted 1/2 sample forward in space |\n| $\\overleftarrow{\\partial_x},\\ \\overleftarrow{\\partial_y},\\ \\overleftarrow{\\partial_z}$ | - shifted first derivative wrt $x,y,z$ | shifted 1/2 sample backward in space |\n| $m(x,y,z)$ | Total P wave velocity ($m_0+\\delta m$) | function of space |\n| $m_0(x,y,z)$ | Reference P wave velocity | function of space |\n| $\\delta m(x,y,z)$ | Perturbation to P wave velocity | function of space |\n| $u(t,x,y,z)$ | Total pressure wavefield ($u_0+\\delta u$)| function of time and space |\n| $u_0(t,x,y,z)$ | Reference pressure wavefield | function of time and space |\n| $\\delta u(t,x,y,z)$ | Perturbation to pressure wavefield | function of time and space |\n| $s(t,x,y,z)$ | Source wavefield | function of time, localized in space to source location |\n| $r(t,x,y,z)$ | Receiver wavefield | function of time, localized in space to receiver locations |\n| $\\delta r(t,x,y,z)$ | Receiver wavefield perturbation | function of time, localized in space to receiver locations |\n| $F[m]\\ q$ | Forward linear modeling operator | Nonlinear in $m$, linear in $q, s$: $\\quad$ maps $q \\rightarrow s$ |\n| $\\bigl( F[m] \\bigr)^\\top\\ s$ | Adjoint linear modeling operator | Nonlinear in $m$, linear in $q, s$: $\\quad$ maps $s \\rightarrow q$ |\n| $F[m; q]$ | Forward nonlinear modeling operator | Nonlinear in $m$, linear in $q$: $\\quad$ maps $m \\rightarrow r$ |\n| $\\nabla F[m; q]\\ \\delta m$ | Forward Jacobian modeling operator | Linearized at $[m; q]$: $\\quad$ maps $\\delta m \\rightarrow \\delta r$ |\n| $\\bigl( \\nabla F[m; q] \\bigr)^\\top\\ \\delta r$ | Adjoint Jacobian modeling operator | Linearized at $[m; q]$: $\\quad$ maps $\\delta r \\rightarrow \\delta m$ |\n| $\\Delta_t, \\Delta_x, \\Delta_y, \\Delta_z$ | sampling rates for $t, x, y , z$ | $t, x, y , z$ | ",
"_____no_output_____"
],
[
"## A word about notation \n\nWe use the arrow symbols over derivatives $\\overrightarrow{\\partial_x}$ as a shorthand notation to indicate that the derivative is taken at a shifted location. For example:\n\n- $\\overrightarrow{\\partial_x}\\ u(t,x,y,z)$ indicates that the $x$ derivative of $u(t,x,y,z)$ is taken at $u(t,x+\\frac{\\Delta x}{2},y,z)$.\n\n- $\\overleftarrow{\\partial_z}\\ u(t,x,y,z)$ indicates that the $z$ derivative of $u(t,x,y,z)$ is taken at $u(t,x,y,z-\\frac{\\Delta z}{2})$.\n\n- $\\overleftarrow{\\partial_t}\\ u(t,x,y,z)$ indicates that the $t$ derivative of $u(t,x,y,z)$ is taken at $u(t-\\frac{\\Delta_t}{2},x,y,z)$.\n\nWe usually drop the $(t,x,y,z)$ notation from wavefield variables unless required for clarity of exposition, so that $u(t,x,y,z)$ becomes $u$.",
"_____no_output_____"
],
[
"## Definition of correctness tests\n\nWe believe that if an operator passes the following suite of unit tests, it can be considered to be *righteous*.\n\n## 1. Analytic response in the far field\nTest that data generated in a wholespace matches analogous analytic data away from the near field. We re-use the material shown in the [examples/seismic/acoustic/accuracy.ipynb](https://github.com/devitocodes/devito/blob/master/examples/seismic/acoustic/accuracy.ipynb) notebook. \n<br>\n\n## 2. Modeling operator linearity test, with respect to source\nFor random vectors $s$ and $r$, prove:\n\n$$\n\\begin{aligned}\nF[m]\\ (\\alpha\\ s) &\\approx \\alpha\\ F[m]\\ s \\\\[5pt]\nF[m]^\\top (\\alpha\\ r) &\\approx \\alpha\\ F[m]^\\top r \\\\[5pt]\n\\end{aligned}\n$$\n## 3. Modeling operator adjoint test, with respect to source\nFor random vectors $s$ and $r$, prove:\n\n$$\nr \\cdot F[m]\\ s \\approx s \\cdot F[m]^\\top r\n$$\n\n## 4. Nonlinear operator linearization test, with respect to model\nFor initial velocity model $m$ and random perturbation $\\delta m$ prove that the $L_2$ norm error in the linearization $E(h)$ is second order (decreases quadratically) with the magnitude of the perturbation.\n\n$$\nE(h) = \\biggl\\|\\ f(m+h\\ \\delta m) - f(m) - h\\ \\nabla F[m; q]\\ \\delta m\\ \\biggr\\|\n$$\n\nOne way to do this is to run a suite of $h$ values decreasing by a factor of $\\gamma$, and prove the error decreases by a factor of $\\gamma^2$: \n\n$$\n\\frac{E\\left(h\\right)}{E\\left(h/\\gamma\\right)} \\approx \\gamma^2\n$$\n\nElsewhere in Devito tutorials, this relation is proven by fitting a line to a sequence of $E(h)$ for various $h$ and showing second order error decrease. We employ this strategy here.\n\n## 5. Jacobian operator linearity test, with respect to model\nFor initial velocity model $m$ and random vectors $\\delta m$ and $\\delta r$, prove:\n\n$$\n\\begin{aligned}\n\\nabla F[m; q]\\ (\\alpha\\ \\delta m) &\\approx \\alpha\\ \\nabla F[m; q]\\ \\delta m \\\\[5pt]\n(\\nabla F[m; q])^\\top (\\alpha\\ \\delta r) &\\approx \\alpha\\ (\\nabla F[m; q])^\\top \\delta r\n\\end{aligned}\n$$\n\n## 6. Jacobian operator adjoint test, with respect to model perturbation and receiver wavefield perturbation \nFor initial velocity model $m$ and random vectors $\\delta m$ and $\\delta r$, prove:\n\n$$\n\\delta r \\cdot \\nabla F[m; q]\\ \\delta m \\approx \\delta m \\cdot (\\nabla F[m; q])^\\top \\delta r\n$$\n\n## 7. Skew symmetry for shifted derivatives\nIn addition to these tests, recall that in the first notebook ([ssa_01_iso_implementation1.ipynb](ssa_01_iso_implementation1.ipynb)) we implemented a unit test that demonstrates skew symmetry of the Devito generated shifted derivatives. We include that test in our suite of unit tests for completeness. \n\nEnsure for random $x_1, x_2$ that Devito shifted derivative operators $\\overrightarrow{\\partial_x}$ and $\\overrightarrow{\\partial_x}$ are skew symmetric by verifying the following dot product test.\n\n$$\nx_2 \\cdot \\left( \\overrightarrow{\\partial_x}\\ x_1 \\right) \\approx -\\ \nx_1 \\cdot \\left( \\overleftarrow{\\partial_x}\\ x_2 \\right) \n$$\n",
"_____no_output_____"
],
[
"## Implementation of correctness tests\n\nBelow we implement the correctness tests described above. These tests are copied from standalone tests that run in the Devito project *continuous integration* (CI) pipeline via the script ```test_iso_wavesolver.py```. We will implement the test methods in one cell and then call from the next cell to verify correctness, but note that a wider variety of parameterization is tested in the CI pipeline.\n\nFor these tests we use the convenience functions implemented in ```operators.py``` and ```wavesolver.py``` rather than implement the operators in the notebook as we have in the first two notebooks in this series. Please review the source to compare with our notebook implementations:\n- [operators.py](operators.py)\n- [wavesolver.py](wavesolver.py)\n- [test_wavesolver_iso.py](test_wavesolver_iso.py)\n\n**Important note:** you must run these notebook cells in order, because some cells have dependencies on state initialized in previous cells.",
"_____no_output_____"
],
[
"## Imports \n\nWe have grouped all imports used in this notebook here for consistency.",
"_____no_output_____"
]
],
[
[
"from scipy.special import hankel2\nimport numpy as np\nfrom examples.seismic import RickerSource, Receiver, TimeAxis, Model, AcquisitionGeometry\nfrom devito import (Grid, Function, TimeFunction, SpaceDimension, Constant, \n Eq, Operator, solve, configuration)\nfrom devito.finite_differences import Derivative\nfrom devito.builtins import gaussian_smooth\nfrom examples.seismic.skew_self_adjoint import (acoustic_ssa_setup, setup_w_over_q,\n SsaIsoAcousticWaveSolver)\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom timeit import default_timer as timer\n\n# These lines force images to be displayed in the notebook, and scale up fonts \n%matplotlib inline\nmpl.rc('font', size=14)\n\n# Make white background for plots, not transparent\nplt.rcParams['figure.facecolor'] = 'white'\n\n# Set the default language to openmp\nconfiguration['language'] = 'openmp'\n\n# Set logging to debug, captures statistics on the performance of operators\n# configuration['log-level'] = 'DEBUG'\nconfiguration['log-level'] = 'INFO'",
"_____no_output_____"
]
],
[
[
"## 1. Analytic response in the far field\nTest that data generated in a wholespace matches analogous analytic data away from the near field. We copy/modify the material shown in the [examples/seismic/acoustic/accuracy.ipynb](https://github.com/devitocodes/devito/blob/master/examples/seismic/acoustic/accuracy.ipynb) notebook.\n\n#### Analytic solution for the 2D acoustic wave equation\n\n$$\n\\begin{aligned}\nu_s(r, t) &= \\frac{1}{2\\pi} \\int_{-\\infty}^{\\infty} \\bigl\\{ -i\\ \\pi\\ H_0^{(2)}\\left(k r \\right)\\ \nq(\\omega)\\ e^{i\\omega t}\\ d\\omega\\bigr\\}\\\\[10pt]\nr &= \\sqrt{(x_{src} - x_{rec})^2+(z_{src} - z_{rec})^2}\n\\end{aligned}\n$$\n\nwhere $H_0^{(2)}$ is the Hankel function of the second kind, $F(\\omega)$ is the Fourier spectrum of the source time function at angular frequencies $\\omega$ and $k = (\\omega\\ /\\ v)$ is the wavenumber. We look at the analytical and numerical solution at a single grid point.\n\nNote that we use a custom discretization for the analytic test that is much finer both temporally and spatially.",
"_____no_output_____"
]
],
[
[
"# Define the analytic response\ndef analytic_response(fpeak, time_axis, src_coords, rec_coords, v):\n nt = time_axis.num\n dt = time_axis.step\n v0 = v.data[0,0]\n sx, sz = src_coords[0, :]\n rx, rz = rec_coords[0, :]\n ntpad = 20 * (nt - 1) + 1\n tmaxpad = dt * (ntpad - 1)\n time_axis_pad = TimeAxis(start=tmin, stop=tmaxpad, step=dt)\n timepad = np.linspace(tmin, tmaxpad, ntpad)\n print(time_axis)\n print(time_axis_pad)\n srcpad = RickerSource(name='srcpad', grid=v.grid, f0=fpeak, npoint=1, \n time_range=time_axis_pad, t0w=t0w)\n nf = int(ntpad / 2 + 1)\n fnyq = 1.0 / (2 * dt)\n df = 1.0 / tmaxpad\n faxis = df * np.arange(nf)\n\n # Take the Fourier transform of the source time-function\n R = np.fft.fft(srcpad.wavelet[:])\n R = R[0:nf]\n nf = len(R)\n\n # Compute the Hankel function and multiply by the source spectrum\n U_a = np.zeros((nf), dtype=complex)\n for a in range(1, nf - 1):\n w = 2 * np.pi * faxis[a] \n r = np.sqrt((rx - sx)**2 + (rz - sz)**2)\n U_a[a] = -1j * np.pi * hankel2(0.0, w * r / v0) * R[a]\n\n # Do inverse fft on 0:dt:T and you have analytical solution\n U_t = 1.0/(2.0 * np.pi) * np.real(np.fft.ifft(U_a[:], ntpad))\n\n # Note that the analytic solution is scaled by dx^2 to convert to pressure\n return (np.real(U_t) * (dx**2))",
"_____no_output_____"
],
[
"#NBVAL_INGNORE_OUTPUT\n\n# Setup time / frequency\nnt = 1001\ndt = 0.1\ntmin = 0.0\ntmax = dt * (nt - 1)\nfpeak = 0.090\nt0w = 1.0 / fpeak\nomega = 2.0 * np.pi * fpeak\ntime_axis = TimeAxis(start=tmin, stop=tmax, step=dt)\ntime = np.linspace(tmin, tmax, nt)\n\n# Model\nspace_order = 8\nnpad = 50\ndx, dz = 0.5, 0.5\nnx, nz = 801, 801\nshape = (nx, nz)\nspacing = (dx, dz)\norigin = (0., 0.)\n\ndtype = np.float64\nqmin = 0.1\nqmax = 100000\nv0 = 1.5*np.ones(shape)\nb0 = 1.0*np.ones(shape)\n\n# Model\ninit_damp = lambda func, nbl: setup_w_over_q(func, omega, qmin, qmax, npad, sigma=0)\nmodel = Model(origin=origin, shape=shape, vp=v0, b=b0, spacing=spacing, nbl=npad,\n space_order=space_order, bcs=init_damp, dtype=dtype, dt=dt)\n\n# Source and reciver coordinates \nsrc_coords = np.empty((1, 2), dtype=dtype)\nrec_coords = np.empty((1, 2), dtype=dtype)\nsrc_coords[:, :] = np.array(model.domain_size) * .5\nrec_coords[:, :] = np.array(model.domain_size) * .5 + 60\n\ngeometry = AcquisitionGeometry(model, rec_coords, src_coords,\n t0=0.0, tn=tmax, src_type='Ricker',\n f0=fpeak)\n# Solver setup\nsolver = SsaIsoAcousticWaveSolver(model, geometry, space_order=space_order)\n\n# Numerical solution\nrecNum, uNum, _ = solver.forward(dt=dt)\n\n# Analytic solution\nuAnaPad = analytic_response(fpeak, time_axis, src_coords, rec_coords, model.vp)\nuAna = uAnaPad[0:nt]\n\n# Compute RMS and difference\ndiff = (recNum.data - uAna)\nnrms = np.max(np.abs(recNum.data))\narms = np.max(np.abs(uAna))\ndrms = np.max(np.abs(diff))\n\nprint(\"\\nMaximum absolute numerical,analytic,diff; %+12.6e %+12.6e %+12.6e\" % (nrms, arms, drms))\n\n# This isnt a very strict tolerance ...\ntol = 0.1\nassert np.allclose(diff, 0.0, atol=tol)\n\nnmin, nmax = np.min(recNum.data), np.max(recNum.data)\namin, amax = np.min(uAna), np.max(uAna)\n\nprint(\"\")\nprint(\"Numerical min/max; %+12.6e %+12.6e\" % (nmin, nmax))\nprint(\"Analytic min/max; %+12.6e %+12.6e\" % (amin, amax))",
"Operator `WOverQ_Operator` run in 0.02 s\nOperator `padfunc` run in 0.35 s\nOperator `padfunc` run in 0.01 s\nOperator `IsoFwdOperator` run in 17.10 s\n"
],
[
"#NBVAL_INGNORE_OUTPUT\n\n# Plot\nx1 = origin[0] - model.nbl * model.spacing[0]\nx2 = model.domain_size[0] + model.nbl * model.spacing[0]\nz1 = origin[1] - model.nbl * model.spacing[1]\nz2 = model.domain_size[1] + model.nbl * model.spacing[1]\n\nxABC1 = origin[0] \nxABC2 = model.domain_size[0]\nzABC1 = origin[1]\nzABC2 = model.domain_size[1]\n\nplt_extent = [x1, x2, z2, z1]\nabc_pairsX = [xABC1, xABC1, xABC2, xABC2, xABC1] \nabc_pairsZ = [zABC1, zABC2, zABC2, zABC1, zABC1] \n\nplt.figure(figsize=(12.5,12.5))\n\n# Plot wavefield\nplt.subplot(2,2,1)\namax = 1.1 * np.max(np.abs(recNum.data[:]))\nplt.imshow(uNum.data[1,:,:], vmin=-amax, vmax=+amax, cmap=\"seismic\",\n aspect=\"auto\", extent=plt_extent)\nplt.plot(src_coords[0, 0], src_coords[0, 1], 'r*', markersize=15, label='Source') \nplt.plot(rec_coords[0, 0], rec_coords[0, 1], 'k^', markersize=11, label='Receiver') \nplt.plot(abc_pairsX, abc_pairsZ, 'black', linewidth=4, linestyle=':', \n label=\"ABC\")\nplt.legend(loc=\"upper left\", bbox_to_anchor=(0.0, 0.9, 0.35, .1), framealpha=1.0)\nplt.xlabel('x position (m)')\nplt.ylabel('z position (m)')\nplt.title('Wavefield of numerical solution')\nplt.tight_layout()\n\n# Plot trace\nplt.subplot(2,2,3)\nplt.plot(time, recNum.data[:, 0], '-b', label='Numeric')\nplt.plot(time, uAna[:], '--r', label='Analytic')\nplt.xlabel('Time (ms)')\nplt.ylabel('Amplitude')\nplt.title('Trace comparison of solutions')\nplt.legend(loc=\"upper right\")\nplt.xlim([50,90])\nplt.ylim([-0.7 * amax, +amax])\n\nplt.subplot(2,2,4)\nplt.plot(time, 10 * (recNum.data[:, 0] - uAna[:]), '-k', label='Difference x10')\nplt.xlabel('Time (ms)')\nplt.ylabel('Amplitude')\nplt.title('Difference of solutions (x10)')\nplt.legend(loc=\"upper right\")\nplt.xlim([50,90])\nplt.ylim([-0.7 * amax, +amax])\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Reset default shapes for subsequent tests",
"_____no_output_____"
]
],
[
[
"npad = 10\nfpeak = 0.010\nqmin = 0.1\nqmax = 500.0\ntmax = 1000.0\nshape = (101, 81)",
"_____no_output_____"
]
],
[
[
"## 2. Modeling operator linearity test, with respect to source\nFor random vectors $s$ and $r$, prove:\n\n$$\n\\begin{aligned}\nF[m]\\ (\\alpha\\ s) &\\approx \\alpha\\ F[m]\\ s \\\\[5pt]\nF[m]^\\top (\\alpha\\ r) &\\approx \\alpha\\ F[m]^\\top r \\\\[5pt]\n\\end{aligned}\n$$\n\nWe first test the forward operator, and in the cell below that the adjoint operator.",
"_____no_output_____"
]
],
[
[
"#NBVAL_INGNORE_OUTPUT\n\nsolver = acoustic_ssa_setup(shape=shape, dtype=dtype, space_order=8, tn=tmax)\nsrc = solver.geometry.src\na = -1 + 2 * np.random.rand()\nrec1, _, _ = solver.forward(src)\nsrc.data[:] *= a\nrec2, _, _ = solver.forward(src)\nrec1.data[:] *= a\n\n# Check receiver wavefeild linearity\n# Normalize by rms of rec2, to enable using abolute tolerance below\nrms2 = np.sqrt(np.mean(rec2.data**2))\ndiff = (rec1.data - rec2.data) / rms2\nprint(\"\\nlinearity forward F %s (so=%d) rms 1,2,diff; \"\n \"%+16.10e %+16.10e %+16.10e\" %\n (shape, 8, np.sqrt(np.mean(rec1.data**2)), np.sqrt(np.mean(rec2.data**2)),\n np.sqrt(np.mean(diff**2))))\ntol = 1.e-12\nassert np.allclose(diff, 0.0, atol=tol)",
"Operator `WOverQ_Operator` run in 0.01 s\nOperator `padfunc` run in 0.01 s\nOperator `padfunc` run in 0.09 s\nOperator `IsoFwdOperator` run in 1.04 s\nOperator `IsoFwdOperator` run in 0.02 s\n"
],
[
"#NBVAL_INGNORE_OUTPUT\n\nsrc0 = solver.geometry.src\nrec, _, _ = solver.forward(src0)\na = -1 + 2 * np.random.rand()\nsrc1, _, _ = solver.adjoint(rec)\nrec.data[:] = a * rec.data[:]\nsrc2, _, _ = solver.adjoint(rec)\nsrc1.data[:] *= a\n\n# Check adjoint source wavefeild linearity\n# Normalize by rms of rec2, to enable using abolute tolerance below\nrms2 = np.sqrt(np.mean(src2.data**2))\ndiff = (src1.data - src2.data) / rms2\nprint(\"\\nlinearity adjoint F %s (so=%d) rms 1,2,diff; \"\n \"%+16.10e %+16.10e %+16.10e\" %\n (shape, 8, np.sqrt(np.mean(src1.data**2)), np.sqrt(np.mean(src2.data**2)),\n np.sqrt(np.mean(diff**2))))\ntol = 1.e-12\nassert np.allclose(diff, 0.0, atol=tol)",
"Operator `IsoFwdOperator` run in 0.03 s\nOperator `IsoAdjOperator` run in 0.02 s\nOperator `IsoAdjOperator` run in 0.03 s\n"
]
],
[
[
"## 3. Modeling operator adjoint test, with respect to source\nFor random vectors $s$ and $r$, prove:\n\n$$\nr \\cdot F[m]\\ s \\approx s \\cdot F[m]^\\top r\n$$",
"_____no_output_____"
]
],
[
[
"#NBVAL_INGNORE_OUTPUT\n\nsrc1 = solver.geometry.src\nrec1 = solver.geometry.rec\n\nrec2, _, _ = solver.forward(src1)\n# flip sign of receiver data for adjoint to make it interesting\nrec1.data[:] = rec2.data[:]\nsrc2, _, _ = solver.adjoint(rec1)\nsum_s = np.dot(src1.data.reshape(-1), src2.data.reshape(-1))\nsum_r = np.dot(rec1.data.reshape(-1), rec2.data.reshape(-1))\ndiff = (sum_s - sum_r) / (sum_s + sum_r)\nprint(\"\\nadjoint F %s (so=%d) sum_s, sum_r, diff; %+16.10e %+16.10e %+16.10e\" %\n (shape, 8, sum_s, sum_r, diff))\nassert np.isclose(diff, 0., atol=1.e-12)",
"Operator `IsoFwdOperator` run in 0.56 s\nOperator `IsoAdjOperator` run in 1.42 s\n"
]
],
[
[
"## 4. Nonlinear operator linearization test, with respect to model\n\nFor initial velocity model $m$ and random perturbation $\\delta m$ prove that the $L_2$ norm error in the linearization $E(h)$ is second order (decreases quadratically) with the magnitude of the perturbation.\n\n$$\nE(h) = \\biggl\\|\\ f(m+h\\ \\delta m) - f(m) - h\\ \\nabla F[m; q]\\ \\delta m\\ \\biggr\\|\n$$\n\nOne way to do this is to run a suite of $h$ values decreasing by a factor of $\\gamma$, and prove the error decreases by a factor of $\\gamma^2$: \n\n$$\n\\frac{E\\left(h\\right)}{E\\left(h/\\gamma\\right)} \\approx \\gamma^2\n$$\n\nElsewhere in Devito tutorials, this relation is proven by fitting a line to a sequence of $E(h)$ for various $h$ and showing second order error decrease. We employ this strategy here.",
"_____no_output_____"
]
],
[
[
"#NBVAL_INGNORE_OUTPUT\n\nsrc = solver.geometry.src\n\n# Create Functions for models and perturbation\nm0 = Function(name='m0', grid=solver.model.grid, space_order=8)\nmm = Function(name='mm', grid=solver.model.grid, space_order=8)\ndm = Function(name='dm', grid=solver.model.grid, space_order=8)\n\n# Background model\nm0.data[:] = 1.5\n\n# Model perturbation, box of (repeatable) random values centered on middle of model\ndm.data[:] = 0\nsize = 5\nns = 2 * size + 1\nnx2, nz2 = shape[0]//2, shape[1]//2\nnp.random.seed(0)\ndm.data[nx2-size:nx2+size, nz2-size:nz2+size] = -1 + 2 * np.random.rand(ns, ns)\n\n# Compute F(m + dm)\nrec0, u0, summary0 = solver.forward(src, vp=m0)\n\n# Compute J(dm)\nrec1, u1, du, summary1 = solver.jacobian(dm, src=src, vp=m0)\n\n# Linearization test via polyfit (see devito/tests/test_gradient.py)\n# Solve F(m + h dm) for sequence of decreasing h\ndh = np.sqrt(2.0)\nh = 0.1\nnstep = 7\nscale = np.empty(nstep)\nnorm1 = np.empty(nstep)\nnorm2 = np.empty(nstep)\nfor kstep in range(nstep):\n h = h / dh\n mm.data[:] = m0.data + h * dm.data\n rec2, _, _ = solver.forward(src, vp=mm)\n scale[kstep] = h\n norm1[kstep] = 0.5 * np.linalg.norm(rec2.data - rec0.data)**2\n norm2[kstep] = 0.5 * np.linalg.norm(rec2.data - rec0.data - h * rec1.data)**2\n\n# Fit 1st order polynomials to the error sequences\n# Assert the 1st order error has slope dh^2\n# Assert the 2nd order error has slope dh^4\np1 = np.polyfit(np.log10(scale), np.log10(norm1), 1)\np2 = np.polyfit(np.log10(scale), np.log10(norm2), 1)\nprint(\"\\nlinearization F %s (so=%d) 1st (%.1f) = %.4f, 2nd (%.1f) = %.4f\" %\n (shape, 8, dh**2, p1[0], dh**4, p2[0]))\nassert np.isclose(p1[0], dh**2, rtol=0.1)\nassert np.isclose(p2[0], dh**4, rtol=0.1)",
"Operator `IsoFwdOperator` run in 0.79 s\nOperator `IsoJacobianFwdOperator` run in 1.83 s\nOperator `IsoFwdOperator` run in 0.08 s\nOperator `IsoFwdOperator` run in 3.28 s\nOperator `IsoFwdOperator` run in 2.49 s\nOperator `IsoFwdOperator` run in 2.23 s\nOperator `IsoFwdOperator` run in 0.68 s\nOperator `IsoFwdOperator` run in 0.54 s\nOperator `IsoFwdOperator` run in 0.11 s\n"
],
[
"#NBVAL_INGNORE_OUTPUT\n\n# Plot linearization tests\nplt.figure(figsize=(12,10))\n\nexpected1 = np.empty(nstep)\nexpected2 = np.empty(nstep)\n\nexpected1[0] = norm1[0]\nexpected2[0] = norm2[0]\n\nfor kstep in range(1, nstep):\n expected1[kstep] = expected1[kstep - 1] / (dh**2)\n expected2[kstep] = expected2[kstep - 1] / (dh**4)\n\nmsize = 10\n\nplt.subplot(2,1,1)\nplt.plot(np.log10(scale), np.log10(expected1), '--k', label='1st order expected', linewidth=1.5)\nplt.plot(np.log10(scale), np.log10(norm1), '-r', label='1st order actual', linewidth=1.5)\nplt.plot(np.log10(scale), np.log10(expected1), 'ko', markersize=10, linewidth=3)\nplt.plot(np.log10(scale), np.log10(norm1), 'r*', markersize=10, linewidth=1.5)\nplt.xlabel('$log_{10}\\ h$')\nplt.ylabel('$log_{10}\\ \\|| F(m+h dm) - F(m) \\||$')\nplt.title('Linearization test (1st order error)')\nplt.legend(loc=\"lower right\")\n\nplt.subplot(2,1,2)\nplt.plot(np.log10(scale), np.log10(expected2), '--k', label='2nd order expected', linewidth=3)\nplt.plot(np.log10(scale), np.log10(norm2), '-r', label='2nd order actual', linewidth=1.5)\nplt.plot(np.log10(scale), np.log10(expected2), 'ko', markersize=10, linewidth=3)\nplt.plot(np.log10(scale), np.log10(norm2), 'r*', markersize=10, linewidth=1.5)\nplt.xlabel('$log_{10}\\ h$')\nplt.ylabel('$log_{10}\\ \\|| F(m+h dm) - F(m) - h J(dm)\\||$')\nplt.title('Linearization test (2nd order error)')\nplt.legend(loc=\"lower right\")\n\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 5. Jacobian operator linearity test, with respect to model\nFor initial velocity model $m$ and random vectors $\\delta m$ and $\\delta r$, prove:\n\n$$\n\\begin{aligned}\n\\nabla F[m; q]\\ (\\alpha\\ \\delta m) &\\approx \\alpha\\ \\nabla F[m; q]\\ \\delta m \\\\[5pt]\n(\\nabla F[m; q])^\\top (\\alpha\\ \\delta r) &\\approx \\alpha\\ (\\nabla F[m; q])^\\top \\delta r\n\\end{aligned}\n$$\n\nWe first test the forward operator, and in the cell below that the adjoint operator.",
"_____no_output_____"
]
],
[
[
"#NBVAL_INGNORE_OUTPUT\n\nsrc0 = solver.geometry.src\n\nm0 = Function(name='m0', grid=solver.model.grid, space_order=8)\nm1 = Function(name='m1', grid=solver.model.grid, space_order=8)\nm0.data[:] = 1.5\n\n# Model perturbation, box of random values centered on middle of model\nm1.data[:] = 0\nsize = 5\nns = 2 * size + 1\nnx2, nz2 = shape[0]//2, shape[1]//2\nm1.data[nx2-size:nx2+size, nz2-size:nz2+size] = \\\n -1 + 2 * np.random.rand(ns, ns)\n\na = np.random.rand()\nrec1, _, _, _ = solver.jacobian(m1, src0, vp=m0)\nrec1.data[:] = a * rec1.data[:]\nm1.data[:] = a * m1.data[:]\nrec2, _, _, _ = solver.jacobian(m1, src0, vp=m0)\n\n# Normalize by rms of rec2, to enable using abolute tolerance below\nrms2 = np.sqrt(np.mean(rec2.data**2))\ndiff = (rec1.data - rec2.data) / rms2\nprint(\"\\nlinearity forward J %s (so=%d) rms 1,2,diff; \"\n \"%+16.10e %+16.10e %+16.10e\" %\n (shape, 8, np.sqrt(np.mean(rec1.data**2)), np.sqrt(np.mean(rec2.data**2)),\n np.sqrt(np.mean(diff**2))))\ntol = 1.e-12\nassert np.allclose(diff, 0.0, atol=tol)\n",
"Operator `IsoJacobianFwdOperator` run in 0.55 s\nOperator `IsoJacobianFwdOperator` run in 0.98 s\n"
],
[
"#NBVAL_INGNORE_OUTPUT\n\nsrc0 = solver.geometry.src\n\nm0 = Function(name='m0', grid=solver.model.grid, space_order=8)\nm1 = Function(name='m1', grid=solver.model.grid, space_order=8)\nm0.data[:] = 1.5\n\n# Model perturbation, box of random values centered on middle of model\nm1.data[:] = 0\nsize = 5\nns = 2 * size + 1\nnx2, nz2 = shape[0]//2, shape[1]//2\nm1.data[nx2-size:nx2+size, nz2-size:nz2+size] = \\\n -1 + 2 * np.random.rand(ns, ns)\n\na = np.random.rand()\nrec0, u0, _ = solver.forward(src0, vp=m0, save=True)\ndm1, _, _, _ = solver.jacobian_adjoint(rec0, u0, vp=m0)\ndm1.data[:] = a * dm1.data[:]\nrec0.data[:] = a * rec0.data[:]\ndm2, _, _, _ = solver.jacobian_adjoint(rec0, u0, vp=m0)\n\n# Normalize by rms of rec2, to enable using abolute tolerance below\nrms2 = np.sqrt(np.mean(dm2.data**2))\ndiff = (dm1.data - dm2.data) / rms2\nprint(\"\\nlinearity adjoint J %s (so=%d) rms 1,2,diff; \"\n \"%+16.10e %+16.10e %+16.10e\" %\n (shape, 8, np.sqrt(np.mean(dm1.data**2)), np.sqrt(np.mean(dm2.data**2)),\n np.sqrt(np.mean(diff**2))))",
"Operator `IsoFwdOperator` run in 0.55 s\nOperator `IsoJacobianAdjOperator` run in 0.13 s\nOperator `IsoJacobianAdjOperator` run in 2.34 s\n"
]
],
[
[
"## 6. Jacobian operator adjoint test, with respect to model perturbation and receiver wavefield perturbation \nFor initial velocity model $m$ and random vectors $\\delta m$ and $\\delta r$, prove:\n\n$$\n\\delta r \\cdot \\nabla F[m; q]\\ \\delta m \\approx \\delta m \\cdot (\\nabla F[m; q])^\\top \\delta r\n$$\n\n<br>\n",
"_____no_output_____"
]
],
[
[
"#NBVAL_INGNORE_OUTPUT\n\nsrc0 = solver.geometry.src\n\nm0 = Function(name='m0', grid=solver.model.grid, space_order=8)\ndm1 = Function(name='dm1', grid=solver.model.grid, space_order=8)\nm0.data[:] = 1.5\n\n# Model perturbation, box of random values centered on middle of model\ndm1.data[:] = 0\nsize = 5\nns = 2 * size + 1\nnx2, nz2 = shape[0]//2, shape[1]//2\ndm1.data[nx2-size:nx2+size, nz2-size:nz2+size] = \\\n -1 + 2 * np.random.rand(ns, ns)\n\n# Data perturbation\nrec1 = solver.geometry.rec\nnt, nr = rec1.data.shape\nrec1.data[:] = np.random.rand(nt, nr)\n\n# Nonlinear modeling\nrec0, u0, _ = solver.forward(src0, vp=m0, save=True)\n\n# Linearized modeling\nrec2, _, _, _ = solver.jacobian(dm1, src0, vp=m0)\ndm2, _, _, _ = solver.jacobian_adjoint(rec1, u0, vp=m0)\n\nsum_m = np.dot(dm1.data.reshape(-1), dm2.data.reshape(-1))\nsum_d = np.dot(rec1.data.reshape(-1), rec2.data.reshape(-1))\ndiff = (sum_m - sum_d) / (sum_m + sum_d)\nprint(\"\\nadjoint J %s (so=%d) sum_m, sum_d, diff; %16.10e %+16.10e %+16.10e\" %\n (shape, 8, sum_m, sum_d, diff))\nassert np.isclose(diff, 0., atol=1.e-11)",
"Operator `IsoFwdOperator` run in 0.09 s\nOperator `IsoJacobianFwdOperator` run in 4.05 s\n"
]
],
[
[
"## 7. Skew symmetry for shifted derivatives\n\nEnsure for random $x_1, x_2$ that Devito shifted derivative operators $\\overrightarrow{\\partial_x}$ and $\\overrightarrow{\\partial_x}$ are skew symmetric by verifying the following dot product test.\n\n$$\nx_2 \\cdot \\left( \\overrightarrow{\\partial_x}\\ x_1 \\right) \\approx -\\ \nx_1 \\cdot \\left( \\overleftarrow{\\partial_x}\\ x_2 \\right) \n$$\n\nWe use Devito to implement the following two equations for random $f_1, g_1$:\n\n$$\n\\begin{aligned}\nf_2 = \\overrightarrow{\\partial_x}\\ f_1 \\\\[5pt]\ng_2 = \\overleftarrow{\\partial_x}\\ g_1\n\\end{aligned}\n$$\n\nWe verify passing this adjoint test by implementing the following equations for random $f_1, g_1$, and ensuring that the relative error terms vanishes.\n\n$$\n\\begin{aligned}\nf_2 = \\overrightarrow{\\partial_x}\\ f_1 \\\\[5pt]\ng_2 = \\overleftarrow{\\partial_x}\\ g_1 \\\\[7pt]\n\\frac{\\displaystyle f_1 \\cdot g_2 + g_1 \\cdot f_2}\n {\\displaystyle f_1 \\cdot g_2 - g_1 \\cdot f_2}\\ <\\ \\epsilon\n\\end{aligned}\n$$",
"_____no_output_____"
]
],
[
[
"#NBVAL_INGNORE_OUTPUT\n\n# Make 1D grid to test derivatives \nn = 101\nd = 1.0\nshape = (n, )\nspacing = (1 / (n-1), ) \norigin = (0., )\nextent = (d * (n-1), )\ndtype = np.float64\n\n# Initialize Devito grid and Functions for input(f1,g1) and output(f2,g2)\n# Note that space_order=8 allows us to use an 8th order finite difference \n# operator by properly setting up grid accesses with halo cells \ngrid1d = Grid(shape=shape, extent=extent, origin=origin, dtype=dtype)\nx = grid1d.dimensions[0]\nf1 = Function(name='f1', grid=grid1d, space_order=8)\nf2 = Function(name='f2', grid=grid1d, space_order=8)\ng1 = Function(name='g1', grid=grid1d, space_order=8)\ng2 = Function(name='g2', grid=grid1d, space_order=8)\n\n# Fill f1 and g1 with random values in [-1,+1]\nf1.data[:] = -1 + 2 * np.random.rand(n,)\ng1.data[:] = -1 + 2 * np.random.rand(n,)\n\n# Equation defining: [f2 = forward 1/2 cell shift derivative applied to f1]\nequation_f2 = Eq(f2, f1.dx(x0=x+0.5*x.spacing))\n\n# Equation defining: [g2 = backward 1/2 cell shift derivative applied to g1]\nequation_g2 = Eq(g2, g1.dx(x0=x-0.5*x.spacing))\n\n# Define an Operator to implement these equations and execute\nop = Operator([equation_f2, equation_g2])\nop()\n\n# Compute the dot products and the relative error\nf1g2 = np.dot(f1.data, g2.data)\ng1f2 = np.dot(g1.data, f2.data)\ndiff = (f1g2+g1f2)/(f1g2-g1f2)\n\ntol = 100 * np.finfo(dtype).eps\nprint(\"f1g2, g1f2, diff, tol; %+.6e %+.6e %+.6e %+.6e\" % (f1g2, g1f2, diff, tol))\n\n# At last the unit test\n# Assert these dot products are float epsilon close in relative error\nassert diff < 100 * np.finfo(np.float32).eps",
"Operator `Kernel` run in 0.01 s\n"
]
],
[
[
"## Discussion\n\nThis concludes the correctness testing of the skew symmetric isotropic visco- acoustic operator. Note that you can run the unit tests directly with the following command, where ```-s``` outputs information about the tolerance and tested values in the tests.\n\n```pytest -s test_wavesolver_iso.py``` \n\nIf you would like to continue this tutorial series with the VTI and TTI operators, please see the README for links. \n\n- [README.md](README.md)",
"_____no_output_____"
],
[
"## References\n\n- **A nonreflecting boundary condition for discrete acoustic and elastic wave equations** (1985)\n<br>Charles Cerjan, Dan Kosloff, Ronnie Kosloff, and Moshe Resheq\n<br> Geophysics, Vol. 50, No. 4\n<br>https://library.seg.org/doi/pdfplus/10.1190/segam2016-13878451.1\n\n- **Generation of Finite Difference Formulas on Arbitrarily Spaced Grids** (1988)\n<br>Bengt Fornberg\n<br>Mathematics of Computation, Vol. 51, No. 184\n<br>http://dx.doi.org/10.1090/S0025-5718-1988-0935077-0\n<br>https://web.njit.edu/~jiang/math712/fornberg.pdf\n\n- **Self-adjoint, energy-conserving second-order pseudoacoustic systems for VTI and TTI media for reverse time migration and full-waveform inversion** (2016)\n<br>Kenneth Bube, John Washbourne, Raymond Ergas, and Tamas Nemeth\n<br>SEG Technical Program Expanded Abstracts\n<br>https://library.seg.org/doi/10.1190/segam2016-13878451.1\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e7ad4858cdc7bd0290a8d59717e473fca10a729c | 2,844 | ipynb | Jupyter Notebook | Coursera/Introduction to the Internet of Things and Embedded Systems/Week-1/Quiz/Module-1-Quiz.ipynb | manipiradi/Online-Courses-Learning | 2a4ce7590d1f6d1dfa5cfde632660b562fcff596 | [
"MIT"
] | 331 | 2019-10-22T09:06:28.000Z | 2022-03-27T13:36:03.000Z | Coursera/Introduction to the Internet of Things and Embedded Systems/Week-1/Quiz/Module-1-Quiz.ipynb | manipiradi/Online-Courses-Learning | 2a4ce7590d1f6d1dfa5cfde632660b562fcff596 | [
"MIT"
] | 8 | 2020-04-10T07:59:06.000Z | 2022-02-06T11:36:47.000Z | Coursera/Introduction to the Internet of Things and Embedded Systems/Week-1/Quiz/Module-1-Quiz.ipynb | manipiradi/Online-Courses-Learning | 2a4ce7590d1f6d1dfa5cfde632660b562fcff596 | [
"MIT"
] | 572 | 2019-07-28T23:43:35.000Z | 2022-03-27T22:40:08.000Z | 20.608696 | 128 | 0.537623 | [
[
[
"#### 1. My watch displays the current weather downloaded from the Internet. My watch is an IoT device.",
"_____no_output_____"
],
[
"##### Ans: True",
"_____no_output_____"
],
[
"#### 2. Which of the following could be an IoT device?",
"_____no_output_____"
],
[
"##### Ans: a lamp, a couch, a pen",
"_____no_output_____"
],
[
"#### 3. An IoT device can most easily be differentiated from a standard computer based on",
"_____no_output_____"
],
[
"##### Ans: interface with the user and the world",
"_____no_output_____"
],
[
"#### 4. The following trend is NOT related to the growth in IoT technology:",
"_____no_output_____"
],
[
"##### Ans: Increase in computer monitor size over time.",
"_____no_output_____"
],
[
"#### 5. IoT devices are likely to be more vulnerable to cyberattacks than standard computers.",
"_____no_output_____"
],
[
"##### Ans: True",
"_____no_output_____"
],
[
"#### 6. Which of these security approaches is feasible for most IoT devices?",
"_____no_output_____"
],
[
"##### Ans: Regular installation of product firmware updates.",
"_____no_output_____"
],
[
"#### 7. IoT devices gather private information about users. Which statement is most true about the security of that data?",
"_____no_output_____"
],
[
"##### Ans: Users must rely on data-collecting agencies to securely store and transmit their data.",
"_____no_output_____"
],
[
"#### 8. Although people are aware of the dangers of cyberattacks, they often do not understand the risks to IoT devices.",
"_____no_output_____"
],
[
"##### Ans: True",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7ad49097d99841a3daa3ecdcc07d8483a0f9a53 | 38,079 | ipynb | Jupyter Notebook | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms | cb5187e491902cbe4c7631f864d4a6db19f7dfa4 | [
"MIT"
] | null | null | null | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms | cb5187e491902cbe4c7631f864d4a6db19f7dfa4 | [
"MIT"
] | null | null | null | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms | cb5187e491902cbe4c7631f864d4a6db19f7dfa4 | [
"MIT"
] | null | null | null | 85.570787 | 13,794 | 0.811103 | [
[
[
"<a href=\"https://colab.research.google.com/github/AstitvaSharma/ML_Algorithms/blob/main/Regression/Support_vector_regression.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Support Vector Regression (SVR)",
"_____no_output_____"
],
[
"## Importing the libraries",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"## Importing the dataset",
"_____no_output_____"
]
],
[
[
"dataset = pd.read_csv('Position_Salaries.csv')\nx = dataset.iloc[:, 1:-1].values\ny = dataset.iloc[:, -1].values",
"_____no_output_____"
],
[
"print(x)",
"[[ 1]\n [ 2]\n [ 3]\n [ 4]\n [ 5]\n [ 6]\n [ 7]\n [ 8]\n [ 9]\n [10]]\n"
],
[
"print(y)",
"[ 45000 50000 60000 80000 110000 150000 200000 300000 500000\n 1000000]\n"
],
[
"y = y.reshape(len(y), 1)\n",
"_____no_output_____"
],
[
"print(y)",
"[[ 45000]\n [ 50000]\n [ 60000]\n [ 80000]\n [ 110000]\n [ 150000]\n [ 200000]\n [ 300000]\n [ 500000]\n [1000000]]\n"
]
],
[
[
"## Feature Scaling",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler\nsc_x = StandardScaler()\nsc_y = StandardScaler()\nx = sc_x.fit_transform(x)\ny = sc_y.fit_transform(y)",
"_____no_output_____"
],
[
"print(x)",
"[[-1.5666989 ]\n [-1.21854359]\n [-0.87038828]\n [-0.52223297]\n [-0.17407766]\n [ 0.17407766]\n [ 0.52223297]\n [ 0.87038828]\n [ 1.21854359]\n [ 1.5666989 ]]\n"
],
[
"print(y)",
"[[-0.72004253]\n [-0.70243757]\n [-0.66722767]\n [-0.59680786]\n [-0.49117815]\n [-0.35033854]\n [-0.17428902]\n [ 0.17781001]\n [ 0.88200808]\n [ 2.64250325]]\n"
]
],
[
[
"## Training the SVR model on the whole dataset",
"_____no_output_____"
]
],
[
[
"from sklearn.svm import SVR\nregressor = SVR(kernel = 'rbf')\nregressor.fit(x, y)",
"/usr/local/lib/python3.7/dist-packages/sklearn/utils/validation.py:993: 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().\n y = column_or_1d(y, warn=True)\n"
]
],
[
[
"## Predicting a new result",
"_____no_output_____"
]
],
[
[
"sc_y.inverse_transform([regressor.predict(sc_x.transform([[6.5]]))]) #requires 2D array, therefore added square brackets before regressor.predict",
"_____no_output_____"
]
],
[
[
"## Visualising the SVR results",
"_____no_output_____"
]
],
[
[
"m=regressor.predict(x)\nplt.scatter(sc_x.inverse_transform(x), sc_y.inverse_transform(y), color = 'red')\nplt.plot(sc_x.inverse_transform(x), sc_y.inverse_transform(m.reshape(len(m),1)), color='blue') # requires 2d array therefore used reshape()\nplt.title('truth or bluff (Support Vector Regression)')\nplt.xlabel('Level')\nplt.ylabel('Salary')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Visualising the SVR results (for higher resolution and smoother curve)",
"_____no_output_____"
]
],
[
[
"X_unscaled = sc_x.inverse_transform(x)\ny_unscaled = sc_y.inverse_transform(y)\nX_grid = np.arange(min(x), max(x), 0.1)\nX_grid = X_grid.reshape((len(X_grid), 1))\nX_grid_unscaled = sc_x.inverse_transform(X_grid)\n \ny_pred_grid = regressor.predict(X_grid)\ny_pred_grid = sc_y.inverse_transform([y_pred_grid])\ny_pred_grid = y_pred_grid.reshape((len(X_grid), 1))\n \nplt.scatter(X_unscaled, y_unscaled, color = 'red')\nplt.plot(X_grid_unscaled, y_pred_grid, color = 'blue')\nplt.title('Level vs Salary (Support Vector Regression')\nplt.xlabel('Level')\nplt.ylabel('Salary')\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ad49e9980f74549da76d1b91665b0a161dc703 | 36,279 | ipynb | Jupyter Notebook | Untitled.ipynb | arora-anmol/pandas-practice | eba21c1697237fceaadc4e831f09617cdf9d73ca | [
"MIT"
] | null | null | null | Untitled.ipynb | arora-anmol/pandas-practice | eba21c1697237fceaadc4e831f09617cdf9d73ca | [
"MIT"
] | null | null | null | Untitled.ipynb | arora-anmol/pandas-practice | eba21c1697237fceaadc4e831f09617cdf9d73ca | [
"MIT"
] | null | null | null | 21.20339 | 328 | 0.387883 | [
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"# The fundamental data structures are Series and DataFrame",
"_____no_output_____"
]
],
[
[
"s = pd.Series(np.random.randn(4), index =['a','f','t','y'])",
"_____no_output_____"
],
[
"s",
"_____no_output_____"
],
[
"s['a']",
"_____no_output_____"
]
],
[
[
"## The data argument can be dict, ndarray, or even a scalar etc",
"_____no_output_____"
]
],
[
[
"data = {'a': 3, 'b':4, 'c': 5, 'f':'something_else'}",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"s_dict = pd.Series(data, index=data.keys())",
"_____no_output_____"
],
[
"s_dict",
"_____no_output_____"
]
],
[
[
"## When the dict doesn't have a matching key, it's not added.\n## And when the index key is missing a value attached, NaN is given",
"_____no_output_____"
]
],
[
[
"s_dict_with_nan = pd.Series(data, index = ['a','b', 'j'])",
"_____no_output_____"
],
[
"s_dict_with_nan",
"_____no_output_____"
]
],
[
[
"## Works differently with scalars",
"_____no_output_____"
]
],
[
[
"s_scalar = pd.Series(3, index=range(5))",
"_____no_output_____"
]
],
[
[
"Works the same way even if you pass a list with one element, like [3] but fails if you pass [3,4] because expects 5 and not 2",
"_____no_output_____"
]
],
[
[
"s_scalar",
"_____no_output_____"
]
],
[
[
"## Series works just like an ndarray, if you have worked with numpy before. I do not have a lot of experience with numpy so can't comment on the full capabilites but according to what I know, you can apply vectorized operations to get a better code performance, slice in the same way we do with numpy ndarrays. ",
"_____no_output_____"
]
],
[
[
"s",
"_____no_output_____"
]
],
[
[
"## MENTIONING PYTHON DATA TYPE IN VARIABLE NAME IS NOT GOOD PRACTICE, SO TRY NOT TO ",
"_____no_output_____"
]
],
[
[
"s[s>s.median()]",
"_____no_output_____"
],
[
"s[[3, 0, 1]]",
"_____no_output_____"
],
[
"np.exp(s)",
"_____no_output_____"
],
[
"s.values",
"_____no_output_____"
],
[
"s.keys",
"_____no_output_____"
],
[
"s.keys()",
"_____no_output_____"
],
[
"s.index\n",
"_____no_output_____"
],
[
"try :\n some_random_var = s['g'] # Raises key error\nexcept KeyError :\n print('Caught key Error')\n ",
"Caught key Error\n"
],
[
"s.f # Can also access elements this way",
"_____no_output_____"
],
[
"s.a",
"_____no_output_____"
],
[
"s",
"_____no_output_____"
]
],
[
[
"### Vectorized operations - Start of the end of matlab RIP",
"_____no_output_____"
]
],
[
[
"s+s ",
"_____no_output_____"
],
[
"s*2",
"_____no_output_____"
],
[
"s*3",
"_____no_output_____"
],
[
"s/2",
"_____no_output_____"
]
],
[
[
"# Moving to Pandas DataFrame",
"_____no_output_____"
],
[
"### According to definition from https://pandas.pydata.org/pandas-docs/stable/dsintro.html#dsintro",
"_____no_output_____"
],
[
"<font size=4>__DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object. Like Series, DataFrame accepts many different kinds of input: __</font>\n\n- Dict of 1D ndarrays, lists, dicts, or Series\n- 2-D numpy.ndarray\n- Structured or record ndarray\n- A Series\n- Another DataFrame \n\n<font size=4>__Along with the data, you can optionally pass index (row labels) and columns (column labels) arguments.__ </font>",
"_____no_output_____"
]
],
[
[
"data = {'one': pd.Series([1,2,3,4], index=['a','b','c','d']),\n 'two': pd.Series([3,4,5,56,6], index=['a','b','f','e','y'])}",
"_____no_output_____"
],
[
"df = pd.DataFrame(data)",
"_____no_output_____"
],
[
"df\n",
"_____no_output_____"
]
],
[
[
"As you can see that it merged the two index together and filled the rest of the values with NaN ",
"_____no_output_____"
]
],
[
[
"df_1 = pd.DataFrame(data, index=['a','b','c','f'])",
"_____no_output_____"
],
[
"df_1",
"_____no_output_____"
],
[
"df_2 = pd.DataFrame(data, columns=['two'])",
"_____no_output_____"
],
[
"df_2",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"df.index",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"data_for_dict = { 'one': [1,2,4,5],\n 'two': [2.,5.4,4.,5]}",
"_____no_output_____"
],
[
"df_from_dict = pd.DataFrame(data_for_dict)",
"_____no_output_____"
],
[
"df_from_dict['one']",
"_____no_output_____"
],
[
"data = np.ones((2,8))\ndata",
"_____no_output_____"
],
[
"data.keys()",
"_____no_output_____"
],
[
"s = pd.Series([3,4,5,5])",
"_____no_output_____"
],
[
"s",
"_____no_output_____"
],
[
"s.values",
"_____no_output_____"
],
[
"s.keys()",
"_____no_output_____"
]
],
[
[
"__A difference to note here is that Series does have a values and keys attribute whereas an ndarray doesn't. Good to know__",
"_____no_output_____"
]
],
[
[
"rows = [[1,2,3,43],[3,5,6,6],[66,6,6]]",
"_____no_output_____"
],
[
"df_rows = pd.DataFrame(rows)",
"_____no_output_____"
],
[
"df_rows",
"_____no_output_____"
],
[
"df_rows_with_index = pd.DataFrame(rows, index=['first', 'second','third'])",
"_____no_output_____"
],
[
"df_rows_with_index # Number of indices should always match the rows count else will raise a shape error",
"_____no_output_____"
],
[
"\ntry:\n df_test = pd.DataFrame({'one':[2,23,4,5,56],\n 'two': [1,3,4,4]})\nexcept ValueError as e:\n print('Value error raised')\n print(e)",
"Value error raised\narrays must all be same length\n"
],
[
"df_test_2 = pd.DataFrame([[1,2,3,4],[2,3,3]])",
"_____no_output_____"
],
[
"df_test_2",
"_____no_output_____"
],
[
"df_test_3 = pd.DataFrame([[1,2,3,4],[2,3,3]], columns=['one','two','three',\n 'four'])",
"_____no_output_____"
],
[
"df_test_3",
"_____no_output_____"
]
],
[
[
"As we can see from the above couple of test df, when we pass a dictionary as data to DataFrame, the arrays needs to be of the same length. But if we pass a row of rows, they are adjusted accordingly\n<br>\nStrange, but need to know the reasoning.\n",
"_____no_output_____"
]
],
[
[
"df_test_4",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ad4cdd2e2eb76bdf03bdef45c7a6706f5d10f5 | 30,447 | ipynb | Jupyter Notebook | spatial_GIS_RS/python_notebooks/4. Working_with_Postgis.ipynb | OpitiCalvin/Scripts_n_Tutorials | 69b42c907c834ad77ed08d36682546c67b90a2b7 | [
"MIT"
] | null | null | null | spatial_GIS_RS/python_notebooks/4. Working_with_Postgis.ipynb | OpitiCalvin/Scripts_n_Tutorials | 69b42c907c834ad77ed08d36682546c67b90a2b7 | [
"MIT"
] | null | null | null | spatial_GIS_RS/python_notebooks/4. Working_with_Postgis.ipynb | OpitiCalvin/Scripts_n_Tutorials | 69b42c907c834ad77ed08d36682546c67b90a2b7 | [
"MIT"
] | null | null | null | 49.507317 | 664 | 0.65192 | [
[
[
"# Working with POSTGIS",
"_____no_output_____"
],
[
"In this chapter we will cover the following topics:\n\n<ul>\n <li>Executing a PostGIS ST_Buffer analysis query and exporting it to GeoJSON</li>\n <li>Finding out whether a point is inside a polygon</li>\n <li>Splitting LineStrings at intersections using ST_Node</li>\n <li>Checking the validity of LineStrings</li>\n <li>Executing a spatial join and assigning point attributes to a polygon</li>\n <li>Conducting a complex spatial analysis query using ST_Distance()</li>\n </ul>",
"_____no_output_____"
],
[
"## Introduction\n\nA spatial database is nothing but a standard database that can store geometry and execute spatial queries in their simplest forms. We will explore how to run spatial analysis queries, handle connections, and more, all from our Python code. Your ability to answer spatial questions such as \"I want to locate all the hotels that are within 2 km of a golf course and less than 5 km from a park\" is where PostGIS comes into play. This chaining of requests into a model is where the powers of spatial analysis shine.\n\nWe will work with the most popular and powerful open source spatial database called <strong>PostgreSQL</strong>, along with the <strong>PostGIS</strong> extension, including over 150 functions. Basically, we'll get a full-blown GIS with complex spatial analysis functions for both vectors and rasters, spatial data types, and diverse methods to move spatial data around.\n\nIf you are looking for more information on PostGIS and a good read, please check out PostGIS Cookbook by Paolo Corti (available at https://www.packtpub.com/big-data-and-business-intelligence/postgis-cookbook). This book explores the wider use of PostGIS and includes a full chapter on PostGIS Programming using Python.\n",
"_____no_output_____"
],
[
"## Executing a PostGIS ST_BUFFER Analysis Query and exporting it to GeoJSON\n\nLet's start by executing our first spatial analysis query from Python against our already running PostgreSQL and PostGIS database. The goal is to generate a 100 m buffer around all schools and export the new buffer polygon to GeoJSON, including the name of a school. The end result will be shown on this map, available (https://github.com/mdiener21/python-geospatial-analysis-cookbook/blob/master/ch04/geodata/out_buff_100m.geojson) on GitHub.\n\n<img src=\"./50790OS_04_01.jpg\" height=400 width=400>\n\nTo get started, we'll use our data in the PostGIS database. We will begin by accessing our schools table that we uploaded to PostGIS in the Batch importing a folder of Shapefiles into PostGIS using ogr2ogr recipe of Chapter 3, Moving Spatial Data from One Format to Another.\n\nConnecting to a PostgreSQL and PostGIS database is accomplished with Psycopg, which is a Python DB API (http://initd.org/psycopg/) implementation. We've already installed this in Chapter 1, Setting Up Your Geospatial Python Environment along with PostgreSQL, Django, and PostGIS.",
"_____no_output_____"
]
],
[
[
"#!/usr/bin/env python\n\nimport psycopg2\nimport json\nfrom geojson import loads, Feature, FeatureCollection\n\n# Database connection information\ndb_host = \"localhost\"\ndb_user = \"calvin\"\ndb_passwd = \"planets\"\ndb_database = \"py_test\"\ndb_port = \"5432\"\n\n# connect to database\nconn = psycopg2.connect(host=db_host, user=db_user,\n port=db_port, password=db_passwd, database=db_database)\n\n# create a cursor\ncur = conn.cursor()\n\n# the PostGIS buffer query\nbuffer_query = \"\"\"SELECT ST_AsGeoJSON(ST_Transform(\n ST_Buffer(wkb_geometry, 100,'quad_segs=8'),4326)) \n AS geom, name\n FROM geodata.schools\"\"\"\n\n# execute the query\ncur.execute(buffer_query)\n\n# return all the rows, we expect more than one\ndbRows = cur.fetchall()\n\n# an empty list to hold each feature of our feature collection\nnew_geom_collection = []\n\n# loop through each row in result query set and add to my feature collection\n# assign name field to the GeoJSON properties\nfor each_poly in dbRows:\n geom = each_poly[0]\n name = each_poly[1]\n geoj_geom = loads(geom)\n myfeat = Feature(geometry=geoj_geom, properties={'name': name})\n new_geom_collection.append(myfeat)\n\n# use the geojson module to create the final Feature Collection of features created from for loop above\nmy_geojson = FeatureCollection(new_geom_collection)\n\n# define the output folder and GeoJSon file name\noutput_geojson_buf = \"../geodata/out_buff_100m.geojson\"\n\n\n# save geojson to a file in our geodata folder\ndef write_geojson():\n fo = open(output_geojson_buf, \"w\")\n fo.write(json.dumps(my_geojson))\n fo.close()\n\n# run the write function to actually create the GeoJSON file\nwrite_geojson()\n\n# close cursor\ncur.close()\n\n# close connection\nconn.close()",
"_____no_output_____"
]
],
[
[
"## How it works\n\nThe database connection is using the pyscopg2 module, so we import the libraries at the start alongside geojson and the standard json modules to handle our GeoJSON export.\n\nOur connection is created and then followed immediately with our SQL Buffer query string. The query uses three PostGIS functions. Working your way from the inside out, you will see the ST_Buffer function taking in the geometry of the school points followed by the 100 m buffer distance and the number of circle segments that we would like to generate. ST_Transform then takes the newly created buffer geometry and transforms it into the WGS84 coordinate system (EPSG: 4326) so that we can display it on GitHub, which only displays WGS84 and the projected GeoJSON. Lastly, we'll use the ST_asGeoJSON function to export our geometry as the GeoJSON geometry.\n\n<pre>\n<strong>Note:</strong>\n\nPostGIS does not export the complete GeoJSON syntax, only the geometry in the form of the GeoJSON geometry. This is the reason that we need to complete our GeoJSON using the Python geojson module.\n</pre>\n\nAll of this means that we not only perform analysis on the query, but we also specify the output format and coordinate system all in one go.\n\nNext, we will execute the query and fetch all the returned objects using cur.fetchall() so that we can later loop through each returned buffer polygon. Our new_geom_collection list will store each of the new geometries and the feature names. Next, in the for loop function, we'll use the geojson module function, loads(geom), to input our geometry into a GeoJSON geometry object. This is followed by the Feature()function that actually creates our GeoJSON feature. This is then used as the input for the FeatureCollection function where the final, completed GeoJSON is created.\n\nLastly, we'll need to write this new GeoJSON file to disk and save it. Hence, we'll use the new file object where we use the standard Python json.dumps module to export our FeatureCollection.\n\nWe'll do a little clean up to close the cursor object and connection. Bingo! We are now done and can visualize our final results.",
"_____no_output_____"
],
[
"## Finding out whether a point is inside a polygon\n\nA point inside a polygon analysis query is a very common spatial operation. This query can identify objects located within an area such as a polygon. The area of interest in this example is a 100 m buffer polygon around bike paths and we would like to locate all schools that are inside this polygon.\n\n### Getting ready\n\nIn the previous section, we used the schools table to create a buffer. This time around, we will use this table as our input points table. The bikeways table that we imported in Chapter 3, Moving Spatial Data from One Format to Another, will be used as our input lines to generate a new 100 m buffer polygon. Be sure, however, that you have the two datasets in your local PostgreSQL database.\n\n### How to do it\nNow, let's dive into some more code to find schools located within 100 m of the bikeways in order to find points inside a polygon:\n",
"_____no_output_____"
]
],
[
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport psycopg2\nfrom geojson import loads, Feature, FeatureCollection\n\n\n# Database Connection Info\ndb_host = \"localhost\"\ndb_user = \"pluto\"\ndb_passwd = \"stars\"\ndb_database = \"py_geoan_cb\"\ndb_port = \"5432\"\n\n# connect to DB\nconn = psycopg2.connect(host=db_host, user=db_user, port=db_port, password=db_passwd, database=db_database)\n\n# create a cursor\ncur = conn.cursor()\n\n# uncomment if needed\n# cur.execute(\"Drop table if exists geodata.bikepath_100m_buff;\")\n\n# query to create a new polygon 100m around the bikepath\nnew_bike_buff_100m = \"\"\" CREATE TABLE geodata.bikepath_100m_buff \n AS SELECT name, \n ST_Buffer(wkb_geometry, 100) AS geom\n FROM geodata.bikeways; \"\"\"\n\n# run the query\ncur.execute(new_bike_buff_100m)\n\n# commit query to database\nconn.commit()\n\n# query to select schools inside the polygon and output geojson\nis_inside_query = \"\"\" SELECT s.name AS name, \n ST_AsGeoJSON(ST_Transform(s.wkb_geometry,4326)) AS geom\n FROM geodata.schools AS s,\n geodata.bikepath_100m_buff AS bp\n WHERE ST_WITHIN(s.wkb_geometry, bp.geom); \"\"\"\n\n# execute the query\ncur.execute(is_inside_query)\n\n# return all the rows, we expect more than one\ndb_rows = cur.fetchall()\n\n# an empty list to hold each feature of our feature collection\nnew_geom_collection = []\n\ndef export2geojson(query_result):\n \"\"\"\n loop through each row in result query set and add to my feature collection\n assign name field to the GeoJSON properties\n :param query_result: pg query set of geometries\n :return: new geojson file\n \"\"\"\n\n for row in db_rows:\n name = row[0]\n geom = row[1]\n geoj_geom = loads(geom)\n myfeat = Feature(geometry=geoj_geom, \n properties={'name': name})\n new_geom_collection.append(myfeat)\n\n # use the geojson module to create the final Feature\n # Collection of features created from for loop above\n my_geojson = FeatureCollection(new_geom_collection)\n # define the output folder and GeoJSon file name\n output_geojson_buf = \"../geodata/out_schools_in_100m.geojson\"\n\n # save geojson to a file in our geodata folder\n def write_geojson():\n fo = open(output_geojson_buf, \"w\")\n fo.write(json.dumps(my_geojson))\n fo.close()\n\n # run the write function to actually create the GeoJSON file\n write_geojson()\n\n\nexport2geojson(db_rows)",
"_____no_output_____"
]
],
[
[
"You can now view your newly created GeoJSON file on a great little site created by Mapbox at http://www.geojson.io. Simply drag and drop your GeoJSON file from Windows Explorer in Windows or Nautilus in Ubuntu onto the http://www.geojson.io web page and, Bob's your uncle, you should see 50 or so schools that are located within 100 m of a bikeway in Vancouver.\n\n<img src=\"./50790OS_04_02.jpg\" height=400 width=400>\n\n### How it works\nWe will reuse code to make our database connection, so this should be familiar to you at this point. The new_bike_buff_100m query string contains our query to generate a new 100 m buffer polygon around all the bikeways. We need to execute this query and commit it to the database so that we can access this new set of polygons as input to our actual query that will find schools (points) located inside this new buffer polygon.\n\nThe is_inside_query string actually does the hard work for us by selecting selecting the values from the field name and the geometry from the geom field. The geometry is wrapped up in two other PostGIS functions to allow us to export our data as GeoJSON in the WGS 84 coordinate system. This will be the input geometry needed to generate our final new GeoJSON file.\n\nThe WHERE clause uses the ST_Within function to see whether a point is inside the polygon and returns True if the point is within the buffer polygon.\n\nNow, we've created a new function that simply wraps up our export to the GeoJSON code that was used in the previous, Executing a PostGIS ST_Buffer analysis query and exporting it to GeoJSON, recipe. This new export2geojson function simply takes one input of our PostGIS query and outputs a GeoJSON file. To set the name and location of the new output file, simply replace the path and name within the function.\n\nFinally, all we need to do is call the new function to export the GeoJSON file using the db_rows variable that contains our list of schools as points located within the 100 m buffer polygon.\n\n### There's more...\n\nThis example to find all schools located within 100 m of the bike paths could be completed using another PostGIS function called ST_Dwithin.\n\nThe SQL to select all the schools located within 100 m of the bikepaths would look like this:\n\n<code>SELECT * FROM geodata.bikeways as b, geodata.schools as s where ST_DWithin(b.wkb_geometry, s.wkb_geometry, 100)\n</code>",
"_____no_output_____"
],
[
"## Splitting LineStrings at Intersections using ST_Node\n\nWorking with road data is usually a tricky business because the validity of the data and data structure plays a very important role. If you want to do anything useful with your road data, such as building a routing network, you will need to prepare the data first. The first task is usually to segmentize your lines, which means splitting all lines at intersections where LineStrings cross each other, creating a base network road dataset.\n\n<pre>\n<strong>Note</strong>\n\nBe aware that this recipe will split all lines on all intersections regardless of whether, for example, there is a road-bridge overpass where no intersection should be created.\n</pre>\n\n### Getting Ready\n\nBefore we get into the details of how to do this, we will use a small section of the OpenStreetMap (OSM) road data for our example. The OSM data is available in your /ch04/geodata/folder called vancouver-osm-data.osm. This data was simply downloaded from the www.openstreetmap.org home page using the Export button located at the top of the page:\n\n<img src=\"./50790OS_04_03.jpg\" height=400 width=500>\n\nThe OSM data contains not only roads but all the other points and polygons located within the extent that I have chosen. The region of interest is again the Burrard Street bridge in Vancouver.\n\nWe are going to need to extract all the roads and import them into our PostGIS table. This time, let's try using the ogr2ogr command line directly from the console to upload the OSM streets to our PostGIS database:\n\n<code>ogr2ogr -lco SCHEMA=geodata -nlt LINESTRING -f \"PostgreSQL\" PG:\"host=localhost port=5432 user=pluto dbname=py_geoan_cb password=stars\" ../geodata/vancouver-osm-data.osm lines -t_srs EPSG:3857\n</code>\n\nThis assumes that your OSM data is in the /ch04/geodata folder and the command is run while you are located in the /ch04/code folder.\n\nNow this really long thing means that we connect to our PostGIS database as our output and input the vancouver-osm-data.osm file. Create a new table called lines and transform the input OSM projection to EPSG:3857. All data exported from OSM is in EPSG:4326. You can, of course, leave it in this system and simply remove the -t_srs EPSG:3857 part of the command line option.\n\nWe are now ready to rock and roll with the splitting at intersections. If you like, go ahead and open the data in QGIS (Quantum GIS). In QGIS, you will see that the road data is not split at all road intersections as shown in this screenshot:\n\n<img src=\"./50790OS_04_04.jpg\" height=400 width=500>\n\nHere, you can see that McNicoll Avenue is a single LineString crossing over Cypress Street. After we've completed the recipe, we will see that McNicoll Avenue will be split at this intersection.",
"_____no_output_____"
]
],
[
[
"#!/usr/bin/env python\n\nimport psycopg2\nimport json\nfrom geojson import loads, Feature, FeatureCollection\n\n# Database Connection Info\ndb_host = \"localhost\"\ndb_user = \"pluto\"\ndb_passwd = \"stars\"\ndb_database = \"py_geoan_cb\"\ndb_port = \"5432\"\n\n# connect to DB\nconn = psycopg2.connect(host=db_host, user=db_user, \n port=db_port, password=db_passwd, database=db_database)\n\n# create a cursor\ncur = conn.cursor()\n\n# drop table if exists\n# cur.execute(\"DROP TABLE IF EXISTS geodata.split_roads;\")\n\n# split lines at intersections query\nsplit_lines_query = \"\"\"\n CREATE TABLE geodata.split_roads\n (ST_Node(ST_Collect(wkb_geometry)))).geom AS geom\n FROM geodata.lines;\"\"\"\n\ncur.execute(split_lines_query)\nconn.commit()\n\ncur.execute(\"ALTER TABLE geodata.split_roads ADD COLUMN id serial;\")\ncur.execute(\"ALTER TABLE geodata.split_roads ADD CONSTRAINT split_roads_pkey PRIMARY KEY (id);\")\n\n# close cursor\ncur.close()\n\n# close connection\nconn.close()",
"_____no_output_____"
]
],
[
[
"<img src=\"./50790OS_04_05.jpg\" height=400 width=500>\n\nWell, this was quite simple and we can now see that McNicoll Avenue is split at the intersection with Cypress Street.",
"_____no_output_____"
],
[
"### HOw it works\n\nLooking at the code, we can see that the database connection remains the same and the only new thing is the query itself that creates the intersection. Here three separate PostGIS functions are used to obtain our results:\n\n<ul>\n <li>The first function, when working our way inside-out in the query, starts with ST_Collect(wkb_geometry). This simply takes our original geometry column as input. The simple combining of the geometries is all that is going on here.</li>\n <li>Next up is the actual splitting of the lines using the ST_Node(geometry), inputting the new geometry collection and nodding, which splits our LineStrings at intersections.</li>\n <li>Finally, we'll use ST_Dump() as a set returning function. This means that it basically explodes all the LineString geometry collections into individual LineStrings. The end of the query with .geom specifies that we only want to export the geometry and not the returned array numbers of the split geometry.</li> </ul>\n\nNow, we'll execute and commit the query to the database. The commit is an important part because, otherwise, the query will be run but it will not actually create the new table that we are looking to generate. Last but not least, we can close down our cursor and connection. That is that; we now have split LineStrings.\n\n<pre>\n<strong>Note:</strong>\n\nBe aware that the new split LineStrings do NOT contain the street names and other attributes. To export the names, we would need to do a join on our data. Such a query to include the attributes on the newly created LineStrings could look like this:\n\n<code>\nCREATE TABLE geodata.split_roads_attributes AS SELECT\n r.geom,\n li.name,\n li.highway\nFROM\n geodata.lines li,\n geodata.split_roads r\nWHERE\n ST_CoveredBy(r.geom, li.wkb_geometry)\n</code>\n</pre>\n",
"_____no_output_____"
],
[
"## Checking the Validity of LineStrings\n\nWorking with road data has many areas to watch out for and one of these is invalid geometry. Our source data is OSM and is, therefore, collected by a community of users that are not trained by GIS professionals, resulting in errors. To execute spatial queries, the data must be valid or we will have results with errors or no results at all.\n\nPostGIS includes the ST_isValid() function that returns True/False on the basis of whether a geometry is valid or not. There is also the ST_isValidReason() function that will output a text description of the geometry error. Finally, the ST_isValidDetail() function will return if the geometry is valid along with the reason and location of the geometry error. These three functions all accomplish similar tasks and selecting one depends on what you want to accomplish.\n\n### How to do it...\n\n1. Now, to determine if geodata.lines are valid, we will run another query that will list all invalid geometries if there are any:",
"_____no_output_____"
]
],
[
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport psycopg2\n\n# Database Connection Info\ndb_host = \"localhost\"\ndb_user = \"pluto\"\ndb_passwd = \"stars\"\ndb_database = \"py_geoan_cb\"\ndb_port = \"5432\"\n\n# connect to DB\nconn = psycopg2.connect(host=db_host, user=db_user, \n port=db_port, password=db_passwd, database=db_database)\n\n# create a cursor\ncur = conn.cursor()\n\n# the PostGIS buffer query\nvalid_query = \"\"\"SELECT\n ogc_fid, \n ST_IsValidDetail(wkb_geometry)\n FROM \n geodata.lines\n WHERE NOT\n ST_IsValid(wkb_geometry);\n \"\"\"\n\n# execute the query\ncur.execute(valid_query)\n\n# return all the rows, we expect more than one\nvalidity_results = cur.fetchall()\n\nprint validity_results\n\n# close cursor\ncur.close()\n\n# close connection\nconn.close();",
"_____no_output_____"
]
],
[
[
"This query should return an empty Python list, which means that we have no invalid geometries. If there are objects in your list, then you'll know that you have some manual work to do to correct those geometries. Your best bet is to fire up QGIS and get started with digitizing tools to clean things up.",
"_____no_output_____"
],
[
"## Executing a spatial join and assigning point attributes to a polygon\n\nWe'll now get back to some more golf action where we would like to execute a spatial attribute join. We're given a situation where we have a set of polygons, in this case, these are in the form of golf greens without any hole number. Our hole number is stored in a point dataset that is located spatially within the green of each hole. We would like to assign each green its appropriate hole number based on its location within the polygon.\n\nThe OSM data from the Pebble Beach Golf Course located in Monterey California is our source data. This golf course is one the great golf courses on the PGA tour and is well mapped in OSM.\n\n### Getting ready\n\nImporting our data into PostGIS will be the first step to execute our spatial query. This time around, we will use the shp2pgsql tool to import our data to change things a little since there are so many ways to get data into PostGIS. The shp2pgsql tool is definitely the most well-tested and common way to import Shapefiles into PostGIS. Let's get going and perform this import once again, executing this tool directly from the command line.\n\nFor Windows users, this should work, but check that the paths are correct or that shp2pgsql.exe is in your system path variable. By doing this, you save having to type the full path to execute.\n\ne.g.\n\n<code>shp2pgsql -s 4326 ..\\geodata\\shp\\pebble-beach-ply-greens.shp geodata.pebble_beach_greens | psql -h localhost -d py_geoan_cb -p 5432 -U pluto\n</code>\n\nOn a Linux machine your command is basically the same without the long path, assuming that your system links were all set up when you installed PostGIS in Chapter 1, Setting Up Your Geospatial Python Environment.\n\nNext up, we need to import our points with the attributes, so let's get to it as follows:\n\n<code>shp2pgsql -s 4326 ..\\geodata\\shp\\pebble-beach-pts-hole-num-green.shp geodata.pebble_bea-ch_hole_num | psql -h localhost -d py_geoan_cb -p 5432 -U postgres\n</code>\n\nThat's that! We now have our points and polygons available in the PostGIS Schema geodata setting, which sets the stage for our spatial join.\n\n### How to do it\n\nThe core work is done once again inside our PostGIS query string, assigning the attributes to the polygons, so follow along:",
"_____no_output_____"
]
],
[
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport psycopg2\n\n# Database Connection Info\ndb_host = \"localhost\"\ndb_user = \"pluto\"\ndb_passwd = \"stars\"\ndb_database = \"py_geoan_cb\"\ndb_port = \"5432\"\n\n# connect to DB\nconn = psycopg2.connect(host=db_host, user=db_user, port=db_port, password=db_passwd, database=db_database)\n\n# create a cursor\ncur = conn.cursor()\n\n# assign polygon attributes from points\nspatial_join = \"\"\" UPDATE geodata.pebble_beach_greens AS g \n SET \n name = h.name\n FROM \n geodata.pebble_beach_hole_num AS h\n WHERE \n ST_Contains(g.geom, h.geom);\n \"\"\"\ncur.execute(spatial_join)\nconn.commit()\n\n# close cursor\ncur.close()\n\n# close connection\nconn.close()",
"_____no_output_____"
]
],
[
[
"### How it works\n\nThe query is straightforward enough; we'll use the UPDATE standard SQL command to update the values in the name field of our table, geodata.pebble_beach_greens, with the hole numbers located in the pebble_beach_hole_num table.\n\nWe follow up by setting the name value from our geodata.pebble_beach_hole_num table, where the field name also exists and holds our needed attribute values.\n\nOur WHERE clause uses the PostGIS query, ST_Contains, to return True if the point lies inside our greens, and if so, it will update our values.\n\nThis was easy and demonstrates the great power of spatial relationships.",
"_____no_output_____"
],
[
"## Conducting a complex spatial analysis query using ST_Distance()\n\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e7ad549bf67ea9b147e176707762e1efdce154a2 | 27,831 | ipynb | Jupyter Notebook | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data | b18426dc2db7cc0612bd5545f72717de61c3c622 | [
"MIT"
] | null | null | null | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data | b18426dc2db7cc0612bd5545f72717de61c3c622 | [
"MIT"
] | null | null | null | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data | b18426dc2db7cc0612bd5545f72717de61c3c622 | [
"MIT"
] | null | null | null | 29.893663 | 1,356 | 0.534943 | [
[
[
"<center>\n <img src=\"https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n</center>\n",
"_____no_output_____"
],
[
"# **Getting Started With Spark using Python**\n",
"_____no_output_____"
],
[
"Estimated time needed: **15** minutes\n",
"_____no_output_____"
],
[
"\n",
"_____no_output_____"
],
[
"### The Python API\n",
"_____no_output_____"
],
[
"Spark is written in Scala, which compiles to Java bytecode, but you can write python code to communicate to the java virtual machine through a library called py4j. Python has the richest API, but it can be somewhat limiting if you need to use a method that is not available, or if you need to write a specialized piece of code. The latency associated with communicating back and forth to the JVM can sometimes cause the code to run slower.\nAn exception to this is the SparkSQL library, which has an execution planning engine that precompiles the queries. Even with this optimization, there are cases where the code may run slower than the native scala version.\nThe general recommendation for PySpark code is to use the \"out of the box\" methods available as much as possible and avoid overly frequent (iterative) calls to Spark methods. If you need to write high-performance or specialized code, try doing it in scala.\nBut hey, we know Python rules, and the plotting libraries are way better. So, it's up to you!\n",
"_____no_output_____"
],
[
"## Objectives\n",
"_____no_output_____"
],
[
"In this lab, we will go over the basics of Apache Spark and PySpark. We will start with creating the SparkContext and SparkSession. We then create an RDD and apply some basic transformations and actions. Finally we demonstrate the basics dataframes and SparkSQL.\n\nAfter this lab you will be able to:\n\n* Create the SparkContext and SparkSession\n* Create an RDD and apply some basic transformations and actions to RDDs\n* Demonstrate the use of the basics Dataframes and SparkSQL\n",
"_____no_output_____"
],
[
"***\n",
"_____no_output_____"
],
[
"## Setup\n",
"_____no_output_____"
],
[
"For this lab, we are going to be using Python and Spark (PySpark). These libraries should be installed in your lab environment or in SN Labs.\n",
"_____no_output_____"
]
],
[
[
"# Installing required packages\n!pip install pyspark\n!pip install findspark",
"_____no_output_____"
],
[
"import findspark\nfindspark.init()",
"_____no_output_____"
],
[
"# PySpark is the Spark API for Python. In this lab, we use PySpark to initialize the spark context. \nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SparkSession",
"_____no_output_____"
]
],
[
[
"## Exercise 1 - Spark Context and Spark Session\n",
"_____no_output_____"
],
[
"In this exercise, you will create the Spark Context and initialize the Spark session needed for SparkSQL and DataFrames.\nSparkContext is the entry point for Spark applications and contains functions to create RDDs such as `parallelize()`. SparkSession is needed for SparkSQL and DataFrame operations.\n",
"_____no_output_____"
],
[
"#### Task 1: Creating the spark session and context\n",
"_____no_output_____"
]
],
[
[
"# Creating a spark context class\nsc = SparkContext()\n\n# Creating a spark session\nspark = SparkSession \\\n .builder \\\n .appName(\"Python Spark DataFrames basic example\") \\\n .config(\"spark.some.config.option\", \"some-value\") \\\n .getOrCreate()",
"_____no_output_____"
]
],
[
[
"#### Task 2: Initialize Spark session\n\nTo work with dataframes we just need to verify that the spark session instance has been created.\n",
"_____no_output_____"
]
],
[
[
"spark",
"_____no_output_____"
]
],
[
[
"## Exercise 2: RDDs\n\nIn this exercise we work with Resilient Distributed Datasets (RDDs). RDDs are Spark's primitive data abstraction and we use concepts from functional programming to create and manipulate RDDs.\n",
"_____no_output_____"
],
[
"#### Task 1: Create an RDD.\n\nFor demonstration purposes, we create an RDD here by calling `sc.parallelize()`\\\nWe create an RDD which has integers from 1 to 30.\n",
"_____no_output_____"
]
],
[
[
"data = range(1,30)\n# print first element of iterator\nprint(data[0])\nlen(data)\nxrangeRDD = sc.parallelize(data, 4)\n\n# this will let us know that we created an RDD\nxrangeRDD",
"1\n"
]
],
[
[
"#### Task 2: Transformations\n",
"_____no_output_____"
],
[
"A transformation is an operation on an RDD that results in a new RDD. The transformed RDD is generated rapidly because the new RDD is lazily evaluated, which means that the calculation is not carried out when the new RDD is generated. The RDD will contain a series of transformations, or computation instructions, that will only be carried out when an action is called. In this transformation, we reduce each element in the RDD by 1. Note the use of the lambda function. We also then filter the RDD to only contain elements <10.\n",
"_____no_output_____"
]
],
[
[
"subRDD = xrangeRDD.map(lambda x: x-1)\nfilteredRDD = subRDD.filter(lambda x : x<10)\n",
"_____no_output_____"
]
],
[
[
"#### Task 3: Actions\n",
"_____no_output_____"
],
[
"A transformation returns a result to the driver. We now apply the `collect()` action to get the output from the transformation.\n",
"_____no_output_____"
]
],
[
[
"print(filteredRDD.collect())\nfilteredRDD.count()",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
]
],
[
[
"#### Task 4: Caching Data\n",
"_____no_output_____"
],
[
"This simple example shows how to create an RDD and cache it. Notice the **10x speed improvement**! If you wish to see the actual computation time, browse to the Spark UI...it's at host:4040. You'll see that the second calculation took much less time!\n",
"_____no_output_____"
]
],
[
[
"import time \n\ntest = sc.parallelize(range(1,50000),4)\ntest.cache()\n\nt1 = time.time()\n# first count will trigger evaluation of count *and* cache\ncount1 = test.count()\ndt1 = time.time() - t1\nprint(\"dt1: \", dt1)\n\n\nt2 = time.time()\n# second count operates on cached data only\ncount2 = test.count()\ndt2 = time.time() - t2\nprint(\"dt2: \", dt2)\n\n#test.count()",
"dt1: 1.997375726699829\ndt2: 0.41718220710754395\n"
]
],
[
[
"## Exercise 3: DataFrames and SparkSQL\n",
"_____no_output_____"
],
[
"In order to work with the extremely powerful SQL engine in Apache Spark, you will need a Spark Session. We have created that in the first Exercise, let us verify that spark session is still active.\n",
"_____no_output_____"
]
],
[
[
"spark",
"_____no_output_____"
]
],
[
[
"#### Task 1: Create Your First DataFrame!\n",
"_____no_output_____"
],
[
"You can create a structured data set (much like a database table) in Spark. Once you have done that, you can then use powerful SQL tools to query and join your dataframes.\n",
"_____no_output_____"
]
],
[
[
"# Download the data first into a local `people.json` file\n!curl https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-BD0225EN-SkillsNetwork/labs/data/people.json >> people.json",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 73 100 73 0 0 162 0 --:--:-- --:--:-- --:--:-- 162\n"
],
[
"# Read the dataset into a spark dataframe using the `read.json()` function\ndf = spark.read.json(\"people.json\").cache()",
"_____no_output_____"
],
[
"# Print the dataframe as well as the data schema\ndf.show()\ndf.printSchema()",
"+----+-------+\n| age| name|\n+----+-------+\n|null|Michael|\n| 30| Andy|\n| 19| Justin|\n+----+-------+\n\nroot\n |-- age: long (nullable = true)\n |-- name: string (nullable = true)\n\n"
],
[
"# Register the DataFrame as a SQL temporary view\ndf.createTempView(\"people\")",
"_____no_output_____"
]
],
[
[
"#### Task 2: Explore the data using DataFrame functions and SparkSQL\n\nIn this section, we explore the datasets using functions both from dataframes as well as corresponding SQL queries using sparksql. Note the different ways to achieve the same task!\n",
"_____no_output_____"
]
],
[
[
"# Select and show basic data columns\n\ndf.select(\"name\").show()\ndf.select(df[\"name\"]).show()\nspark.sql(\"SELECT name FROM people\").show()",
"+-------+\n| name|\n+-------+\n|Michael|\n| Andy|\n| Justin|\n+-------+\n\n+-------+\n| name|\n+-------+\n|Michael|\n| Andy|\n| Justin|\n+-------+\n\n+-------+\n| name|\n+-------+\n|Michael|\n| Andy|\n| Justin|\n+-------+\n\n"
],
[
"# Perform basic filtering\n\ndf.filter(df[\"age\"] > 21).show()\nspark.sql(\"SELECT age, name FROM people WHERE age > 21\").show()",
"+---+----+\n|age|name|\n+---+----+\n| 30|Andy|\n+---+----+\n\n+---+----+\n|age|name|\n+---+----+\n| 30|Andy|\n+---+----+\n\n"
],
[
"# Perfom basic aggregation of data\n\ndf.groupBy(\"age\").count().show()\nspark.sql(\"SELECT age, COUNT(age) as count FROM people GROUP BY age\").show()",
"+----+-----+\n| age|count|\n+----+-----+\n| 19| 1|\n|null| 1|\n| 30| 1|\n+----+-----+\n\n+----+-----+\n| age|count|\n+----+-----+\n| 19| 1|\n|null| 0|\n| 30| 1|\n+----+-----+\n\n"
]
],
[
[
"***\n",
"_____no_output_____"
],
[
"### Question 1 - RDDs\n",
"_____no_output_____"
],
[
"Create an RDD with integers from 1-50. Apply a transformation to multiply every number by 2, resulting in an RDD that contains the first 50 even numbers.\n",
"_____no_output_____"
]
],
[
[
"# starter code\n# numbers = range(1, 50)\n# numbers_RDD = ...\n# even_numbers_RDD = numbers_RDD.map(lambda x: ..)",
"_____no_output_____"
],
[
"# Code block for learners to answer\nnumbers = range(1, 50)\nnumbers_RDD = sc.parallelize(data, 4)\neven_numbers_RDD = numbers_RDD.map(lambda x: x * 2)\neven_numbers_RDD.collect()",
"_____no_output_____"
]
],
[
[
"### Question 2 - DataFrames and SparkSQL\n",
"_____no_output_____"
],
[
"Similar to the `people.json` file, now read the `people2.json` file into the notebook, load it into a dataframe and apply SQL operations to determine the average age in our people2 file.\n",
"_____no_output_____"
]
],
[
[
"# starter code\n# !curl https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-BD0225EN-SkillsNetwork/labs/data/people2.json >> people2.json\n# df = spark.read...\n# df.createTempView..\n# spark.sql(\"SELECT ...\")",
"_____no_output_____"
],
[
"# Code block for learners to answer\n!curl https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-BD0225EN-SkillsNetwork/labs/data/people2.json >> people2.json\ndf = spark.read.json('people2.json')\ndf.createTempView(\"people2\")\nspark.sql(\"SELECT AVG(age) from people2\")",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 326 100 326 0 0 478 0 --:--:-- --:--:-- --:--:-- 478\n"
]
],
[
[
"Double-click **here** for a hint.\n\n<!-- The hint is below:\n\n1. The SQL query \"Select AVG(column_name) from..\" can be used to find the average value of a column. \n2. Another possible way is to use the dataframe operations select() and mean()\n-->\n",
"_____no_output_____"
],
[
"Double-click **here** for the solution.\n\n<!-- The answer is below:\ndf = spark.read('people2.json')\ndf.createTempView(\"people2\")\nspark.sql(\"SELECT AVG(age) from people2\")\n-->\n",
"_____no_output_____"
],
[
"### Question 3 - SparkSession\n",
"_____no_output_____"
],
[
"Close the SparkSession we created for this notebook\n",
"_____no_output_____"
]
],
[
[
"# Code block for learners to answer\nspark.stop()",
"_____no_output_____"
]
],
[
[
"Double-click **here** for the solution.\n\n<!-- The answer is below:\n\nspark.stop() will stop the spark session\n\n-->\n",
"_____no_output_____"
],
[
"## Authors\n",
"_____no_output_____"
],
[
"[Karthik Muthuraman](https://www.linkedin.com/in/karthik-muthuraman/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMBD0225ENSkillsNetwork25716109-2021-01-01)\n",
"_____no_output_____"
],
[
"### Other Contributors\n",
"_____no_output_____"
],
[
"[Jerome Nilmeier](https://github.com/nilmeier)\n",
"_____no_output_____"
],
[
"## Change Log\n",
"_____no_output_____"
],
[
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ---------- | ------------------ |\n| 2021-07-02 | 0.2 | Karthik | Beta launch |\n| 2021-06-30 | 0.1 | Karthik | First Draft |\n",
"_____no_output_____"
],
[
"Copyright © 2021 IBM Corporation. All rights reserved.\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7ad5518f602072e220d7e67aa10741b46cf56f7 | 3,417 | ipynb | Jupyter Notebook | pytorch.lstm.ipynb | anandsaha/rnn-projects | 40ed8eb1e4d48a774c782e763d6021045b4d63ab | [
"MIT"
] | null | null | null | pytorch.lstm.ipynb | anandsaha/rnn-projects | 40ed8eb1e4d48a774c782e763d6021045b4d63ab | [
"MIT"
] | null | null | null | pytorch.lstm.ipynb | anandsaha/rnn-projects | 40ed8eb1e4d48a774c782e763d6021045b4d63ab | [
"MIT"
] | null | null | null | 20.709091 | 68 | 0.46971 | [
[
[
"\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ntorch.manual_seed(1)",
"_____no_output_____"
],
[
"lstm = nn.LSTM(3, 3) # Input dim is 3, output dim is 3\ninputs = [autograd.Variable(torch.randn((1, 3)))\n for _ in range(5)] # make a sequence of length 5",
"_____no_output_____"
],
[
"h0 = autograd.Variable(torch.randn(1, 1, 3))\nc0 = autograd.Variable(torch.randn(1, 1, 3))",
"_____no_output_____"
],
[
"for i in inputs:\n out, hidden = lstm(i.view(1, 1, -1), (h0, c0))",
"_____no_output_____"
],
[
"inputs = torch.cat(inputs).view(len(inputs), 1, -1)\nh0 = autograd.Variable(torch.randn(1, 1, 3))\nc0 = autograd.Variable(torch.randn(1, 1, 3))",
"_____no_output_____"
],
[
"out, hidden = lstm(inputs, hidden)",
"_____no_output_____"
],
[
"out",
"_____no_output_____"
],
[
"hidden",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ad585fd73cf079d56785d5089ec98e28828bff | 107,250 | ipynb | Jupyter Notebook | PyradiomicsExample/Jupyter/Untitled.ipynb | FarnooshKh/JoyOfLearning | 33de11c01388bcaae3bfcc074c2bdb94db447ad0 | [
"MIT"
] | null | null | null | PyradiomicsExample/Jupyter/Untitled.ipynb | FarnooshKh/JoyOfLearning | 33de11c01388bcaae3bfcc074c2bdb94db447ad0 | [
"MIT"
] | null | null | null | PyradiomicsExample/Jupyter/Untitled.ipynb | FarnooshKh/JoyOfLearning | 33de11c01388bcaae3bfcc074c2bdb94db447ad0 | [
"MIT"
] | null | null | null | 67.410434 | 1,643 | 0.732019 | [
[
[
"from __future__ import print_function\nimport six\nimport os # needed navigate the system to get the input data\n\nimport radiomics\nfrom radiomics import featureextractor",
"_____no_output_____"
],
[
"extractor = featureextractor.RadiomicsFeaturesExtractor()\nextractor.enableAllImageTypes()\nextractor.enableAllFeatures()\nprint('Extraction parameters:\\n\\t', extractor.settings)\nprint('Enabled filters:\\n\\t', extractor._enabledImagetypes)\nprint('Enabled features:\\n\\t', extractor._enabledFeatures)",
"Extraction parameters:\n\t {'minimumROIDimensions': 1, 'minimumROISize': None, 'normalize': False, 'normalizeScale': 1, 'removeOutliers': None, 'resampledPixelSpacing': None, 'interpolator': 'sitkBSpline', 'preCrop': False, 'padDistance': 5, 'distances': [1], 'force2D': False, 'force2Ddimension': 0, 'resegmentRange': None, 'label': 1, 'additionalInfo': True}\nEnabled filters:\n\t {'Original': {}, 'Exponential': {}, 'Gradient': {}, 'LBP2D': {}, 'LBP3D': {}, 'LoG': {}, 'Logarithm': {}, 'Square': {}, 'SquareRoot': {}, 'Wavelet': {}}\nEnabled features:\n\t {'firstorder': [], 'glcm': [], 'gldm': [], 'glrlm': [], 'glszm': [], 'ngtdm': [], 'shape': []}\n"
],
[
"result2 = extractor.execute('/Users/farnoosh/Documents/Projects/Data/nifti/BA4075/1_no_series_description.nii', '/Users/farnoosh/Documents/Projects/Data/nifti/BA4075-MASS/1_no_series_description.nii', label=7)\n",
"GLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\n/Users/farnoosh/Projects/PyradiomicsExample/myenv/lib/python3.6/site-packages/radiomics/ngtdm.py:161: RuntimeWarning: invalid value encountered in double_scalars\n contrast = (numpy.sum(p_i[:, None] * p_i[None, :] * (i[:, None] - i[None, :]) ** 2) / (Ngp * (Ngp - 1))) * \\\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nCould not load required package \"skimage\", cannot implement filter LBP 2D\nCould not load required package \"scipy\" or \"trimesh\", cannot implement filter LBP 3D\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\nGLCM is symmetrical, therefore Sum Average = 2 * Joint Average, only 1 needs to be calculated\n"
],
[
"import os\nimport nibabel as nib\nimport numpy as np\n",
"_____no_output_____"
],
[
"print('Result type:', type(result2)) # result is returned in a Python ordered dictionary)\nprint('')\nprint('Calculated features')\ni = 0\nfor key, value in six.iteritems(result2):\n print('\\t', key, ':', value)\n i = i+1\nprint(i)",
"Result type: <class 'collections.OrderedDict'>\n\nCalculated features\n\t general_info_BoundingBox : (189, 223, 50, 128, 176, 10)\n\t general_info_EnabledImageTypes : {'Original': {}, 'Exponential': {}, 'Gradient': {}, 'LBP2D': {}, 'LBP3D': {}, 'LoG': {}, 'Logarithm': {}, 'Square': {}, 'SquareRoot': {}, 'Wavelet': {}}\n\t general_info_GeneralSettings : {'minimumROIDimensions': 1, 'minimumROISize': None, 'normalize': False, 'normalizeScale': 1, 'removeOutliers': None, 'resampledPixelSpacing': None, 'interpolator': 'sitkBSpline', 'preCrop': False, 'padDistance': 5, 'distances': [1], 'force2D': False, 'force2Ddimension': 0, 'resegmentRange': None, 'label': 7, 'additionalInfo': True, 'voxelBased': False}\n\t general_info_ImageHash : 0726d6db9632f6c1f391d2050c05e7c5aac536b4\n\t general_info_ImageSpacing : (0.390625, 0.390625, 3.0)\n\t general_info_MaskHash : e9fbdd9152e2418302dffe62b64e620772d8df82\n\t general_info_NumpyVersion : 1.15.1\n\t general_info_PyWaveletVersion : 0.5.2\n\t general_info_SimpleITKVersion : 1.1.0\n\t general_info_Version : 2.0.0\n\t general_info_VolumeNum : 1\n\t general_info_VoxelNum : 75905\n\t original_shape_Elongation : 0.5817182262232733\n\t original_shape_Flatness : 0.3853168755892375\n\t original_shape_LeastAxis : 25.272472641390582\n\t original_shape_MajorAxis : 65.5888029890806\n\t original_shape_Maximum2DDiameterColumn : 47.75058286620698\n\t original_shape_Maximum2DDiameterRow : 68.359375\n\t original_shape_Maximum2DDiameterSlice : 68.9472489990083\n\t original_shape_Maximum3DDiameter : 72.11538605769229\n\t original_shape_MinorAxis : 38.1542021349157\n\t original_shape_Sphericity : 0.43165048073315915\n\t original_shape_SurfaceArea : 11929.61335061375\n\t original_shape_SurfaceVolumeRatio : 0.3433322971898306\n\t original_shape_Volume : 34746.551513671875\n\t original_firstorder_10Percentile : 18.0\n\t original_firstorder_90Percentile : 88.0\n\t original_firstorder_Energy : 741317835.0\n\t original_firstorder_Entropy : 2.4989960663603004\n\t original_firstorder_InterquartileRange : 34.0\n\t original_firstorder_Kurtosis : 69.5602009948608\n\t original_firstorder_Maximum : 335.0\n\t original_firstorder_MeanAbsoluteDeviation : 34.714544097647085\n\t original_firstorder_Mean : 43.31144193399644\n\t original_firstorder_Median : 54.0\n\t original_firstorder_Minimum : -1024.0\n\t original_firstorder_Range : 1359.0\n\t original_firstorder_RobustMeanAbsoluteDeviation : 14.62006063256598\n\t original_firstorder_RootMeanSquared : 98.8250475689612\n\t original_firstorder_Skewness : -7.314010237982463\n\t original_firstorder_TotalEnergy : 339348374.1760254\n\t original_firstorder_Uniformity : 0.2489447177975968\n\t original_firstorder_Variance : 7890.509024605498\n\t original_glcm_Autocorrelation : 1880.0985853993045\n\t original_glcm_ClusterProminence : 119372.03827346506\n\t original_glcm_ClusterShade : -1933.833080228693\n\t original_glcm_ClusterTendency : 41.88066905844842\n\t original_glcm_Contrast : 7.604835313347592\n\t original_glcm_Correlation : 0.6877514686437946\n\t original_glcm_DifferenceAverage : 1.074595253478026\n\t original_glcm_DifferenceEntropy : 1.7968530072572397\n\t original_glcm_DifferenceVariance : 6.210504657998162\n\t original_glcm_Id : 0.7092748893663402\n\t original_glcm_Idm : 0.6889993518361985\n\t original_glcm_Idmn : 0.9977303535706538\n\t original_glcm_Idn : 0.9824332771230024\n\t original_glcm_Imc1 : -0.23426931995748881\n\t original_glcm_Imc2 : 0.7183660035306162\n\t original_glcm_InverseVariance : 0.36477098744711905\n\t original_glcm_JointAverage : 43.26117748299785\n\t original_glcm_JointEnergy : 0.10514456770404353\n\t original_glcm_JointEntropy : 4.402983553340997\n\t original_glcm_MaximumProbability : 0.21155552772324276\n\t original_glcm_SumAverage : 86.52235496599572\n\t original_glcm_SumEntropy : 3.2696536613166427\n\t original_glcm_SumSquares : 12.371376092949\n\t original_gldm_DependenceEntropy : 6.670570965660703\n\t original_gldm_DependenceNonUniformity : 4137.152822607206\n\t original_gldm_DependenceNonUniformityNormalized : 0.05450435178983211\n\t original_gldm_DependenceVariance : 35.855880806010134\n\t original_gldm_GrayLevelNonUniformity : 18896.148804426586\n\t original_gldm_GrayLevelVariance : 12.693920851881144\n\t original_gldm_HighGrayLevelEmphasis : 1883.2515776299322\n\t original_gldm_LargeDependenceEmphasis : 172.42807456689283\n\t original_gldm_LargeDependenceHighGrayLevelEmphasis : 330642.2388643699\n\t original_gldm_LargeDependenceLowGrayLevelEmphasis : 0.1248346230787021\n\t original_gldm_LowGrayLevelEmphasis : 0.0013790845482853302\n\t original_gldm_SmallDependenceEmphasis : 0.03864821522510601\n\t original_gldm_SmallDependenceHighGrayLevelEmphasis : 57.80270264353245\n\t original_gldm_SmallDependenceLowGrayLevelEmphasis : 8.589116921642772e-05\n\t original_glrlm_GrayLevelNonUniformity : 9724.19178022484\n\t original_glrlm_GrayLevelNonUniformityNormalized : 0.20756890611668619\n\t original_glrlm_GrayLevelVariance : 22.23468649081866\n\t original_glrlm_HighGrayLevelRunEmphasis : 1849.5592850699247\n\t original_glrlm_LongRunEmphasis : 12.275756707588133\n\t original_glrlm_LongRunHighGrayLevelEmphasis : 23386.94389953092\n\t original_glrlm_LongRunLowGrayLevelEmphasis : 0.011639769650792681\n\t original_glrlm_LowGrayLevelRunEmphasis : 0.0017070072166300927\n\t original_glrlm_RunEntropy : 4.504975340694965\n\t original_glrlm_RunLengthNonUniformity : 24189.786393698738\n\t original_glrlm_RunLengthNonUniformityNormalized : 0.47169649768841637\n\t original_glrlm_RunPercentage : 0.5889842059659594\n\t original_glrlm_RunVariance : 6.295479860374657\n\t original_glrlm_ShortRunEmphasis : 0.6870137575452927\n\t original_glrlm_ShortRunHighGrayLevelEmphasis : 1251.2972736567021\n\t original_glrlm_ShortRunLowGrayLevelEmphasis : 0.001341454214950614\n\t original_glszm_GrayLevelNonUniformity : 94.79732468585327\n\t original_glszm_GrayLevelNonUniformityNormalized : 0.03842615512195106\n\t original_glszm_GrayLevelVariance : 101.44349384309037\n\t original_glszm_HighGrayLevelZoneEmphasis : 1343.5845156059993\n\t original_glszm_LargeAreaEmphasis : 492418.13092825294\n\t original_glszm_LargeAreaHighGrayLevelEmphasis : 939853080.6927443\n\t original_glszm_LargeAreaLowGrayLevelEmphasis : 259.1881712096275\n\t original_glszm_LowGrayLevelZoneEmphasis : 0.002563472050761716\n\t original_glszm_SizeZoneNonUniformity : 832.4398054316985\n\t original_glszm_SizeZoneNonUniformityNormalized : 0.3374299981482361\n\t original_glszm_SmallAreaEmphasis : 0.6030879434451928\n\t original_glszm_SmallAreaHighGrayLevelEmphasis : 739.2235997562293\n\t original_glszm_SmallAreaLowGrayLevelEmphasis : 0.001326362194495243\n\t original_glszm_ZoneEntropy : 7.308394674716004\n\t original_glszm_ZonePercentage : 0.032501152756735395\n\t original_glszm_ZoneVariance : 491471.45252361574\n\t original_ngtdm_Busyness : 2.0932767119039895\n\t original_ngtdm_Coarseness : 0.00010870989716313497\n\t original_ngtdm_Complexity : 1319.1347790011296\n\t original_ngtdm_Contrast : 0.006458751780098291\n\t original_ngtdm_Strength : 0.9537223208460109\n\t exponential_firstorder_10Percentile : 1.0481898110013677\n\t exponential_firstorder_90Percentile : 1.2587183549589183\n\t exponential_firstorder_Energy : 100234.22688774449\n\t exponential_firstorder_Entropy : -0.0\n\t exponential_firstorder_InterquartileRange : 0.10268332959454662\n\t exponential_firstorder_Kurtosis : 22.113164218975555\n\t exponential_firstorder_Maximum : 2.4010979614742265\n\t exponential_firstorder_MeanAbsoluteDeviation : 0.08331538816812399\n\t exponential_firstorder_Mean : 1.1393458983342126\n\t exponential_firstorder_Median : 1.1516481158256888\n\t exponential_firstorder_Minimum : 0.06873768115053885\n\t exponential_firstorder_Range : 2.332360280323688\n\t exponential_firstorder_RobustMeanAbsoluteDeviation : 0.044102557182290704\n\t exponential_firstorder_RootMeanSquared : 1.1491397038617324\n\t exponential_firstorder_Skewness : -3.347180732376832\n\t exponential_firstorder_TotalEnergy : 45883.58774768577\n\t exponential_firstorder_Uniformity : 1.0\n\t exponential_firstorder_Variance : 0.022412982940436175\n\t exponential_glcm_Autocorrelation : 1.0\n\t exponential_glcm_ClusterProminence : 0.0\n\t exponential_glcm_ClusterShade : 0.0\n\t exponential_glcm_ClusterTendency : 0.0\n\t exponential_glcm_Contrast : 0.0\n\t exponential_glcm_Correlation : 1.0\n\t exponential_glcm_DifferenceAverage : 0.0\n\t exponential_glcm_DifferenceEntropy : -3.2034265038149176e-16\n\t exponential_glcm_DifferenceVariance : 0.0\n\t exponential_glcm_Id : 1.0\n\t exponential_glcm_Idm : 1.0\n\t exponential_glcm_Idmn : 1.0\n\t exponential_glcm_Idn : 1.0\n\t exponential_glcm_Imc1 : 0.0\n\t exponential_glcm_Imc2 : 0.0\n\t exponential_glcm_InverseVariance : 0.0\n\t exponential_glcm_JointAverage : 1.0\n\t exponential_glcm_JointEnergy : 1.0\n\t exponential_glcm_JointEntropy : -3.2034265038149176e-16\n\t exponential_glcm_MaximumProbability : 1.0\n\t exponential_glcm_SumAverage : 2.0\n\t exponential_glcm_SumEntropy : -3.2034265038149176e-16\n\t exponential_glcm_SumSquares : 0.0\n\t exponential_gldm_DependenceEntropy : 2.4811038795970024\n\t exponential_gldm_DependenceNonUniformity : 22632.31105987748\n\t exponential_gldm_DependenceNonUniformityNormalized : 0.2981662744203607\n\t exponential_gldm_DependenceVariance : 35.79413557403315\n\t exponential_gldm_GrayLevelNonUniformity : 75905.0\n\t exponential_gldm_GrayLevelVariance : 0.0\n\t exponential_gldm_HighGrayLevelEmphasis : 1.0\n\t exponential_gldm_LargeDependenceEmphasis : 487.4259271457743\n\t exponential_gldm_LargeDependenceHighGrayLevelEmphasis : 487.4259271457743\n\t exponential_gldm_LargeDependenceLowGrayLevelEmphasis : 487.4259271457743\n\t exponential_gldm_LowGrayLevelEmphasis : 1.0\n\t exponential_gldm_SmallDependenceEmphasis : 0.003407121743987557\n\t exponential_gldm_SmallDependenceHighGrayLevelEmphasis : 0.003407121743987557\n\t exponential_gldm_SmallDependenceLowGrayLevelEmphasis : 0.003407121743987557\n\t exponential_glrlm_GrayLevelNonUniformity : 16781.923076923078\n\t exponential_glrlm_GrayLevelNonUniformityNormalized : 1.0\n\t exponential_glrlm_GrayLevelVariance : 0.0\n\t exponential_glrlm_HighGrayLevelRunEmphasis : 1.0\n\t exponential_glrlm_LongRunEmphasis : 1066.8652765132351\n\t exponential_glrlm_LongRunHighGrayLevelEmphasis : 1066.8652765132351\n\t exponential_glrlm_LongRunLowGrayLevelEmphasis : 1066.8652765132351\n\t exponential_glrlm_LowGrayLevelRunEmphasis : 1.0\n\t exponential_glrlm_RunEntropy : 3.8894019033772294\n\t exponential_glrlm_RunLengthNonUniformity : 3085.5415034000534\n\t exponential_glrlm_RunLengthNonUniformityNormalized : 0.13490702442463276\n\t exponential_glrlm_RunPercentage : 0.22109114125450333\n\t exponential_glrlm_RunVariance : 305.23345003467443\n\t exponential_glrlm_ShortRunEmphasis : 0.2825505064199943\n\t exponential_glrlm_ShortRunHighGrayLevelEmphasis : 0.2825505064199943\n\t exponential_glrlm_ShortRunLowGrayLevelEmphasis : 0.2825505064199943\n\t exponential_glszm_GrayLevelNonUniformity : 1.0\n\t exponential_glszm_GrayLevelNonUniformityNormalized : 1.0\n\t exponential_glszm_GrayLevelVariance : 0.0\n\t exponential_glszm_HighGrayLevelZoneEmphasis : 1.0\n\t exponential_glszm_LargeAreaEmphasis : 5761569025.0\n\t exponential_glszm_LargeAreaHighGrayLevelEmphasis : 5761569025.0\n\t exponential_glszm_LargeAreaLowGrayLevelEmphasis : 5761569025.0\n\t exponential_glszm_LowGrayLevelZoneEmphasis : 1.0\n\t exponential_glszm_SizeZoneNonUniformity : 1.0\n\t exponential_glszm_SizeZoneNonUniformityNormalized : 1.0\n\t exponential_glszm_SmallAreaEmphasis : 1.7356383229306188e-10\n\t exponential_glszm_SmallAreaHighGrayLevelEmphasis : 1.7356383229306188e-10\n\t exponential_glszm_SmallAreaLowGrayLevelEmphasis : 1.7356383229306188e-10\n\t exponential_glszm_ZoneEntropy : -3.203426503814917e-16\n\t exponential_glszm_ZonePercentage : 1.3174362690204861e-05\n\t exponential_glszm_ZoneVariance : 0.0\n\t exponential_ngtdm_Busyness : 0\n\t exponential_ngtdm_Coarseness : 1000000\n\t exponential_ngtdm_Complexity : 0.0\n\t exponential_ngtdm_Contrast : nan\n\t exponential_ngtdm_Strength : 0\n\t gradient_firstorder_10Percentile : 6.552529811859131\n\t gradient_firstorder_90Percentile : 79.73537445068376\n\t gradient_firstorder_Energy : 369599250.9041974\n\t gradient_firstorder_Entropy : 1.6336264261373945\n\t gradient_firstorder_InterquartileRange : 17.916515350341797\n\t gradient_firstorder_Kurtosis : 28.62715235992783\n\t gradient_firstorder_Maximum : 657.1744995117188\n\t gradient_firstorder_MeanAbsoluteDeviation : 32.36497612332689\n\t gradient_firstorder_Mean : 34.91383343928888\n\t gradient_firstorder_Median : 16.09368133544922\n\t gradient_firstorder_Minimum : 0.0\n\t gradient_firstorder_Range : 657.1744995117188\n\t gradient_firstorder_RobustMeanAbsoluteDeviation : 9.937286303290502\n\t gradient_firstorder_RootMeanSquared : 69.7799009847386\n\t gradient_firstorder_Skewness : 4.497976400610363\n\t gradient_firstorder_TotalEnergy : 169189110.2161548\n\t gradient_firstorder_Uniformity : 0.5325619243101924\n\t gradient_firstorder_Variance : 3650.2588160135183\n\t gradient_glcm_Autocorrelation : 6.933450466376813\n\t gradient_glcm_ClusterProminence : 9333.899726704618\n\t gradient_glcm_ClusterShade : 345.2559922509719\n\t gradient_glcm_ClusterTendency : 18.223458579115682\n\t gradient_glcm_Contrast : 4.184361841382233\n\t gradient_glcm_Correlation : 0.624556925089636\n\t gradient_glcm_DifferenceAverage : 0.7894691755330057\n\t gradient_glcm_DifferenceEntropy : 1.579125711847289\n\t gradient_glcm_DifferenceVariance : 3.4547538334570493\n\t gradient_glcm_Id : 0.80538678516785\n\t gradient_glcm_Idm : 0.788644424086381\n\t gradient_glcm_Idmn : 0.9948588196629764\n\t gradient_glcm_Idn : 0.9751871467185557\n\t gradient_glcm_Imc1 : -0.21281794064058815\n\t gradient_glcm_Imc2 : 0.6173879886141381\n\t gradient_glcm_InverseVariance : 0.19835210316407353\n\t gradient_glcm_JointAverage : 1.850159833300446\n\t gradient_glcm_JointEnergy : 0.40262914449059156\n\t gradient_glcm_JointEntropy : 2.7734673161613297\n\t gradient_glcm_MaximumProbability : 0.6209696845393444\n\t gradient_glcm_SumAverage : 3.700319666600895\n\t gradient_glcm_SumEntropy : 2.1618364066528333\n\t gradient_glcm_SumSquares : 5.601955105124478\n\t gradient_gldm_DependenceEntropy : 5.3936780679040375\n\t gradient_gldm_DependenceNonUniformity : 4814.780989394638\n\t gradient_gldm_DependenceNonUniformityNormalized : 0.06343167102818836\n\t gradient_gldm_DependenceVariance : 64.36197576128146\n\t gradient_gldm_GrayLevelNonUniformity : 40424.112864765164\n\t gradient_gldm_GrayLevelVariance : 5.828303553409875\n\t gradient_gldm_HighGrayLevelEmphasis : 9.471194255977867\n\t gradient_gldm_LargeDependenceEmphasis : 293.222409590936\n\t gradient_gldm_LargeDependenceHighGrayLevelEmphasis : 413.62356893485276\n\t gradient_gldm_LargeDependenceLowGrayLevelEmphasis : 281.827172538753\n\t gradient_gldm_LowGrayLevelEmphasis : 0.75685538407968\n\t gradient_gldm_SmallDependenceEmphasis : 0.0397743825011135\n\t gradient_gldm_SmallDependenceHighGrayLevelEmphasis : 3.048147641198116\n\t gradient_gldm_SmallDependenceLowGrayLevelEmphasis : 0.005975754099816438\n\t gradient_glrlm_GrayLevelNonUniformity : 10931.832260445084\n\t gradient_glrlm_GrayLevelNonUniformityNormalized : 0.28788034959346537\n\t gradient_glrlm_GrayLevelVariance : 11.404866645748246\n\t gradient_glrlm_HighGrayLevelRunEmphasis : 20.852173796696793\n\t gradient_glrlm_LongRunEmphasis : 35.413788413006216\n\t gradient_glrlm_LongRunHighGrayLevelEmphasis : 68.55618742077287\n\t gradient_glrlm_LongRunLowGrayLevelEmphasis : 33.97166807154809\n\t gradient_glrlm_LowGrayLevelRunEmphasis : 0.524809935880292\n\t gradient_glrlm_RunEntropy : 4.311191410563482\n\t gradient_glrlm_RunLengthNonUniformity : 15555.585184433636\n\t gradient_glrlm_RunLengthNonUniformityNormalized : 0.41727270890563023\n\t gradient_glrlm_RunPercentage : 0.4566102364798103\n\t gradient_glrlm_RunVariance : 26.422056240238096\n\t gradient_glrlm_ShortRunEmphasis : 0.666080543436871\n\t gradient_glrlm_ShortRunHighGrayLevelEmphasis : 19.177007375026843\n\t gradient_glrlm_ShortRunLowGrayLevelEmphasis : 0.2628561720530534\n\t gradient_glszm_GrayLevelNonUniformity : 188.47568710359408\n\t gradient_glszm_GrayLevelNonUniformityNormalized : 0.06641144718237987\n\t gradient_glszm_GrayLevelVariance : 26.25120506772195\n\t gradient_glszm_HighGrayLevelZoneEmphasis : 93.49929527836504\n\t gradient_glszm_LargeAreaEmphasis : 1054446.0362931641\n\t gradient_glszm_LargeAreaHighGrayLevelEmphasis : 1132398.6585623678\n\t gradient_glszm_LargeAreaLowGrayLevelEmphasis : 1035595.5659030067\n\t gradient_glszm_LowGrayLevelZoneEmphasis : 0.05758103223292853\n\t gradient_glszm_SizeZoneNonUniformity : 878.2431289640592\n\t gradient_glszm_SizeZoneNonUniformityNormalized : 0.309458466865419\n\t gradient_glszm_SmallAreaEmphasis : 0.5757739954581328\n\t gradient_glszm_SmallAreaHighGrayLevelEmphasis : 63.696896196526055\n\t gradient_glszm_SmallAreaLowGrayLevelEmphasis : 0.024942475955789155\n\t gradient_glszm_ZoneEntropy : 6.623054533169185\n\t gradient_glszm_ZonePercentage : 0.0373888413148014\n\t gradient_glszm_ZoneVariance : 1053730.6905667372\n\t gradient_ngtdm_Busyness : 148.22463333007568\n\t gradient_ngtdm_Coarseness : 9.768803742196272e-05\n\t gradient_ngtdm_Complexity : 297.6770132033684\n\t gradient_ngtdm_Contrast : 0.009768077369662061\n\t gradient_ngtdm_Strength : 0.25722239700170363\n\t logarithm_firstorder_10Percentile : 1126.0619439185223\n\t logarithm_firstorder_90Percentile : 1716.6199170053296\n\t logarithm_firstorder_Energy : 180611309723.54266\n\t logarithm_firstorder_Entropy : 5.223669389368686\n\t logarithm_firstorder_InterquartileRange : 239.74881282711704\n\t logarithm_firstorder_Kurtosis : 16.138637449479127\n\t logarithm_firstorder_Maximum : 2224.677620126024\n\t logarithm_firstorder_MeanAbsoluteDeviation : 385.495671035698\n\t logarithm_firstorder_Mean : 1338.0575939543517\n\t logarithm_firstorder_Median : 1532.5518472009746\n\t logarithm_firstorder_Minimum : -2651.223477250649\n\t logarithm_firstorder_Range : 4875.901097376673\n\t logarithm_firstorder_RobustMeanAbsoluteDeviation : 108.8372511712761\n\t logarithm_firstorder_RootMeanSquared : 1542.5429978612833\n\t logarithm_firstorder_Skewness : -3.691383035034909\n\t logarithm_firstorder_TotalEnergy : 82677296321.20178\n\t logarithm_firstorder_Uniformity : 0.03930810583320225\n\t logarithm_firstorder_Variance : 589040.7755119667\n\t logarithm_glcm_Autocorrelation : 26508.002934507193\n\t logarithm_glcm_ClusterProminence : 160119140.59165066\n\t logarithm_glcm_ClusterShade : -619984.8610696786\n\t logarithm_glcm_ClusterTendency : 3068.7314401469916\n\t logarithm_glcm_Contrast : 769.2885304018232\n\t logarithm_glcm_Correlation : 0.6028602076752391\n\t logarithm_glcm_DifferenceAverage : 10.636546409069314\n\t logarithm_glcm_DifferenceEntropy : 4.109789545372847\n\t logarithm_glcm_DifferenceVariance : 632.9109072698425\n\t logarithm_glcm_Id : 0.3425502519745584\n\t logarithm_glcm_Idm : 0.2718903367396026\n\t logarithm_glcm_Idmn : 0.9852379521185645\n\t logarithm_glcm_Idn : 0.9585401585835205\n\t logarithm_glcm_Imc1 : -0.17099356698592405\n\t logarithm_glcm_Imc2 : 0.8050640835577052\n\t logarithm_glcm_InverseVariance : 0.2554111141815059\n\t logarithm_glcm_JointAverage : 161.03768275323623\n\t logarithm_glcm_JointEnergy : 0.0038763822920516557\n\t logarithm_glcm_JointEntropy : 9.51248094865817\n\t logarithm_glcm_MaximumProbability : 0.012814705613063974\n\t logarithm_glcm_SumAverage : 322.0753655064722\n\t logarithm_glcm_SumEntropy : 6.228113618379317\n\t logarithm_glcm_SumSquares : 959.504992637203\n\t logarithm_gldm_DependenceEntropy : 8.056808822921736\n\t logarithm_gldm_DependenceNonUniformity : 10527.325222317371\n\t logarithm_gldm_DependenceNonUniformityNormalized : 0.13869080063655057\n\t logarithm_gldm_DependenceVariance : 6.194269535111575\n\t logarithm_gldm_GrayLevelNonUniformity : 2983.681773269218\n\t logarithm_gldm_GrayLevelVariance : 942.6312432325672\n\t logarithm_gldm_HighGrayLevelEmphasis : 26873.444252684276\n\t logarithm_gldm_LargeDependenceEmphasis : 20.82190896515381\n\t logarithm_gldm_LargeDependenceHighGrayLevelEmphasis : 601609.1495948883\n\t logarithm_gldm_LargeDependenceLowGrayLevelEmphasis : 0.025635550861666724\n\t logarithm_gldm_LowGrayLevelEmphasis : 0.0007293947447791735\n\t logarithm_gldm_SmallDependenceEmphasis : 0.25163907269162794\n\t logarithm_gldm_SmallDependenceHighGrayLevelEmphasis : 5808.0293325952625\n\t logarithm_gldm_SmallDependenceLowGrayLevelEmphasis : 0.00010262313194816811\n\t logarithm_glrlm_GrayLevelNonUniformity : 2557.0297680841063\n\t logarithm_glrlm_GrayLevelNonUniformityNormalized : 0.03768633660647172\n\t logarithm_glrlm_GrayLevelVariance : 1014.6006147905612\n\t logarithm_glrlm_HighGrayLevelRunEmphasis : 26627.31992221852\n\t logarithm_glrlm_LongRunEmphasis : 1.5307120830484915\n\t logarithm_glrlm_LongRunHighGrayLevelEmphasis : 41854.568978511736\n\t logarithm_glrlm_LongRunLowGrayLevelEmphasis : 0.0018215785671516042\n\t logarithm_glrlm_LowGrayLevelRunEmphasis : 0.0006670544873593476\n\t logarithm_glrlm_RunEntropy : 5.790889975950008\n\t logarithm_glrlm_RunLengthNonUniformity : 56902.57876511606\n\t logarithm_glrlm_RunLengthNonUniformityNormalized : 0.8282188284543147\n\t logarithm_glrlm_RunPercentage : 0.8913611650190268\n\t logarithm_glrlm_RunVariance : 0.22354997387711226\n\t logarithm_glrlm_ShortRunEmphasis : 0.9229312713033427\n\t logarithm_glrlm_ShortRunHighGrayLevelEmphasis : 24421.697069497637\n\t logarithm_glrlm_ShortRunLowGrayLevelEmphasis : 0.0006177759033249211\n\t logarithm_glszm_GrayLevelNonUniformity : 472.9883424057036\n\t logarithm_glszm_GrayLevelNonUniformityNormalized : 0.02278473637485927\n\t logarithm_glszm_GrayLevelVariance : 1990.6728641642794\n\t logarithm_glszm_HighGrayLevelZoneEmphasis : 23017.69854039212\n\t logarithm_glszm_LargeAreaEmphasis : 550.9002842140758\n\t logarithm_glszm_LargeAreaHighGrayLevelEmphasis : 16469856.242304543\n\t logarithm_glszm_LargeAreaLowGrayLevelEmphasis : 0.18076464251490768\n\t logarithm_glszm_LowGrayLevelZoneEmphasis : 0.0004261497433364194\n\t logarithm_glszm_SizeZoneNonUniformity : 8365.102798786069\n\t logarithm_glszm_SizeZoneNonUniformityNormalized : 0.40296270527414946\n\t logarithm_glszm_SmallAreaEmphasis : 0.6603787056507894\n\t logarithm_glszm_SmallAreaHighGrayLevelEmphasis : 14112.27156887759\n\t logarithm_glszm_SmallAreaLowGrayLevelEmphasis : 0.00024615706104739516\n\t logarithm_glszm_ZoneEntropy : 8.071588135124431\n\t logarithm_glszm_ZonePercentage : 0.27348659508596274\n\t logarithm_glszm_ZoneVariance : 537.5303918355354\n\t logarithm_ngtdm_Busyness : 0.3436500847933997\n\t logarithm_ngtdm_Coarseness : 7.652775163466875e-05\n\t logarithm_ngtdm_Complexity : 118858.43501991949\n\t logarithm_ngtdm_Contrast : 0.728253587142613\n\t logarithm_ngtdm_Strength : 4.658099223740942\n\t square_firstorder_10Percentile : 0.22012373819602735\n\t square_firstorder_90Percentile : 2.8163464669488767\n\t square_firstorder_Energy : 28451396.85009354\n\t square_firstorder_Entropy : 0.15374371311019622\n\t square_firstorder_InterquartileRange : 1.262129599478997\n\t square_firstorder_Kurtosis : 188.24561785015814\n\t square_firstorder_Maximum : 341.44448062520354\n\t square_firstorder_MeanAbsoluteDeviation : 3.8562686948826737\n\t square_firstorder_Mean : 3.180198641161655\n\t square_firstorder_Median : 1.0211657440573105\n\t square_firstorder_Minimum : 0.0\n\t square_firstorder_Range : 341.44448062520354\n\t square_firstorder_RobustMeanAbsoluteDeviation : 0.5462165881349054\n\t square_firstorder_RootMeanSquared : 19.360501572688772\n\t square_firstorder_Skewness : 12.98153953620211\n\t square_firstorder_TotalEnergy : 13024015.892071627\n\t square_firstorder_Uniformity : 0.9719289330218517\n\t square_firstorder_Variance : 364.71535774883785\n\t square_glcm_Autocorrelation : 1.43466645224299\n\t square_glcm_ClusterProminence : 475.76350232492314\n\t square_glcm_ClusterShade : 25.301856643438967\n\t square_glcm_ClusterTendency : 1.5428613344947653\n\t square_glcm_Contrast : 0.32668770554314724\n\t square_glcm_Correlation : 0.6293393270025732\n\t square_glcm_DifferenceAverage : 0.06220039444860632\n\t square_glcm_DifferenceEntropy : 0.19023193407024908\n\t square_glcm_DifferenceVariance : 0.321958538484149\n\t square_glcm_Id : 0.9867564879472658\n\t square_glcm_Idm : 0.9852020046680571\n\t square_glcm_Idmn : 0.9986704223849799\n\t square_glcm_Idn : 0.9966931475835282\n\t square_glcm_Imc1 : -0.34599541587781385\n\t square_glcm_Imc2 : 0.30665875102071216\n\t square_glcm_InverseVariance : 0.008650500996229143\n\t square_glcm_JointAverage : 1.0633035685863734\n\t square_glcm_JointEnergy : 0.9581682134569659\n\t square_glcm_JointEntropy : 0.25875386944006074\n\t square_glcm_MaximumProbability : 0.9788421340780272\n\t square_glcm_SumAverage : 2.126607137172747\n\t square_glcm_SumEntropy : 0.2255024089444963\n\t square_glcm_SumSquares : 0.4673872600094783\n\t square_gldm_DependenceEntropy : 2.7452456881813028\n\t square_gldm_DependenceNonUniformity : 20735.26377708978\n\t square_gldm_DependenceNonUniformityNormalized : 0.273173885476448\n\t square_gldm_DependenceVariance : 40.18152926320275\n\t square_gldm_GrayLevelNonUniformity : 73774.26566102364\n\t square_gldm_GrayLevelVariance : 0.522526996194409\n\t square_gldm_HighGrayLevelEmphasis : 1.6595085962716554\n\t square_gldm_LargeDependenceEmphasis : 475.83612410249657\n\t square_gldm_LargeDependenceHighGrayLevelEmphasis : 491.080416309861\n\t square_gldm_LargeDependenceLowGrayLevelEmphasis : 475.6127254610099\n\t square_gldm_LowGrayLevelEmphasis : 0.9872865884689784\n\t square_gldm_SmallDependenceEmphasis : 0.006105705162935011\n\t square_gldm_SmallDependenceHighGrayLevelEmphasis : 0.11525662697825809\n\t square_gldm_SmallDependenceLowGrayLevelEmphasis : 0.0036390351826917485\n\t square_glrlm_GrayLevelNonUniformity : 16078.075164635286\n\t square_glrlm_GrayLevelNonUniformityNormalized : 0.7897298458574679\n\t square_glrlm_GrayLevelVariance : 3.42580710292659\n\t square_glrlm_HighGrayLevelRunEmphasis : 6.063645571324997\n\t square_glrlm_LongRunEmphasis : 621.9886281365987\n\t square_glrlm_LongRunHighGrayLevelEmphasis : 642.3886076012616\n\t square_glrlm_LongRunLowGrayLevelEmphasis : 621.6773072090893\n\t square_glrlm_LowGrayLevelRunEmphasis : 0.8906341950782226\n\t square_glrlm_RunEntropy : 4.1180615761857595\n\t square_glrlm_RunLengthNonUniformity : 3622.991078526701\n\t square_glrlm_RunLengthNonUniformityNormalized : 0.16440781322464654\n\t square_glrlm_RunPercentage : 0.23567921440261866\n\t square_glrlm_RunVariance : 312.66983077201473\n\t square_glrlm_ShortRunEmphasis : 0.3826552819265955\n\t square_glrlm_ShortRunHighGrayLevelEmphasis : 4.497315789108662\n\t square_glrlm_ShortRunLowGrayLevelEmphasis : 0.28938536232702144\n\t square_glszm_GrayLevelNonUniformity : 23.31336405529954\n\t square_glszm_GrayLevelNonUniformityNormalized : 0.10743485739769373\n\t square_glszm_GrayLevelVariance : 8.833018326997813\n\t square_glszm_HighGrayLevelZoneEmphasis : 40.857142857142854\n\t square_glszm_LargeAreaEmphasis : 25805070.069124423\n\t square_glszm_LargeAreaHighGrayLevelEmphasis : 25811861.940092165\n\t square_glszm_LargeAreaLowGrayLevelEmphasis : 25804982.2606999\n\t square_glszm_LowGrayLevelZoneEmphasis : 0.07749207044227117\n\t square_glszm_SizeZoneNonUniformity : 52.77880184331797\n\t square_glszm_SizeZoneNonUniformityNormalized : 0.2432202849922487\n\t square_glszm_SmallAreaEmphasis : 0.5070475865095879\n\t square_glszm_SmallAreaHighGrayLevelEmphasis : 21.977174119472476\n\t square_glszm_SmallAreaLowGrayLevelEmphasis : 0.029840580095199055\n\t square_glszm_ZoneEntropy : 5.7022887421841615\n\t square_glszm_ZonePercentage : 0.002858836703774455\n\t square_glszm_ZoneVariance : 25682715.18741107\n\t square_ngtdm_Busyness : 46.133050768198984\n\t square_ngtdm_Coarseness : 0.0008386331874682433\n\t square_ngtdm_Complexity : 4.5293160895989795\n\t square_ngtdm_Contrast : 0.00024004531465658484\n\t square_ngtdm_Strength : 0.5132444838923854\n\t squareroot_firstorder_10Percentile : 235.11273891475977\n\t squareroot_firstorder_90Percentile : 519.8538256086994\n\t squareroot_firstorder_Energy : 15346582389.0\n\t squareroot_firstorder_Entropy : 4.3778398594269134\n\t squareroot_firstorder_InterquartileRange : 128.61458807335265\n\t squareroot_firstorder_Kurtosis : 24.122110190857306\n\t squareroot_firstorder_Maximum : 1014.2903923433367\n\t squareroot_firstorder_MeanAbsoluteDeviation : 141.3724638929884\n\t squareroot_firstorder_Mean : 351.72055996048084\n\t squareroot_firstorder_Median : 407.2272093070403\n\t squareroot_firstorder_Minimum : -1773.3313283196685\n\t squareroot_firstorder_Range : 2787.6217206630054\n\t squareroot_firstorder_RobustMeanAbsoluteDeviation : 56.404558624025334\n\t squareroot_firstorder_RootMeanSquared : 449.645907851719\n\t squareroot_firstorder_Skewness : -4.2030837427990555\n\t squareroot_firstorder_TotalEnergy : 7025107905.12085\n\t squareroot_firstorder_Uniformity : 0.07006435664458606\n\t squareroot_firstorder_Variance : 78474.09014888239\n\t squareroot_glcm_Autocorrelation : 7412.317141918767\n\t squareroot_glcm_ClusterProminence : 4522756.395413008\n\t squareroot_glcm_ClusterShade : -36713.76697943887\n\t squareroot_glcm_ClusterTendency : 420.2881881391892\n\t squareroot_glcm_Contrast : 86.8530180329359\n\t squareroot_glcm_Correlation : 0.6585401554694603\n\t squareroot_glcm_DifferenceAverage : 4.213537905196021\n\t squareroot_glcm_DifferenceEntropy : 3.2399750573845063\n\t squareroot_glcm_DifferenceVariance : 65.43709359621646\n\t squareroot_glcm_Id : 0.45110157061077977\n\t squareroot_glcm_Idm : 0.3905860732895841\n\t squareroot_glcm_Idmn : 0.9938981072488935\n\t squareroot_glcm_Idn : 0.9676142251690005\n\t squareroot_glcm_Imc1 : -0.18843766162326403\n\t squareroot_glcm_Imc2 : 0.7792119163634053\n\t squareroot_glcm_InverseVariance : 0.33120724031159704\n\t squareroot_glcm_JointAverage : 85.60933214018853\n\t squareroot_glcm_JointEnergy : 0.011267735226216715\n\t squareroot_glcm_JointEntropy : 7.902424249197957\n\t squareroot_glcm_MaximumProbability : 0.030392400563967373\n\t squareroot_glcm_SumAverage : 171.21866428037706\n\t squareroot_glcm_SumEntropy : 5.289816365405065\n\t squareroot_glcm_SumSquares : 126.78530154303122\n\t squareroot_gldm_DependenceEntropy : 7.752012099915153\n\t squareroot_gldm_DependenceNonUniformity : 7089.039364995719\n\t squareroot_gldm_DependenceNonUniformityNormalized : 0.09339357571959316\n\t squareroot_gldm_DependenceVariance : 11.738192489328025\n\t squareroot_gldm_GrayLevelNonUniformity : 5318.234991107305\n\t squareroot_gldm_GrayLevelVariance : 125.66634347906644\n\t squareroot_gldm_HighGrayLevelEmphasis : 7449.611988670048\n\t squareroot_gldm_LargeDependenceEmphasis : 43.27979711481457\n\t squareroot_gldm_LargeDependenceHighGrayLevelEmphasis : 339032.5590672551\n\t squareroot_gldm_LargeDependenceLowGrayLevelEmphasis : 0.0467791607096169\n\t squareroot_gldm_LowGrayLevelEmphasis : 0.0011033785684882505\n\t squareroot_gldm_SmallDependenceEmphasis : 0.13862629699739298\n\t squareroot_gldm_SmallDependenceHighGrayLevelEmphasis : 850.4074118847162\n\t squareroot_gldm_SmallDependenceLowGrayLevelEmphasis : 9.636566853422051e-05\n\t squareroot_glrlm_GrayLevelNonUniformity : 4116.42836976184\n\t squareroot_glrlm_GrayLevelNonUniformityNormalized : 0.06542343962250755\n\t squareroot_glrlm_GrayLevelVariance : 145.6226164337838\n\t squareroot_glrlm_HighGrayLevelRunEmphasis : 7362.380325082167\n\t squareroot_glrlm_LongRunEmphasis : 2.192697966794881\n\t squareroot_glrlm_LongRunHighGrayLevelEmphasis : 16667.858991283698\n\t squareroot_glrlm_LongRunLowGrayLevelEmphasis : 0.0032493175436772524\n\t squareroot_glrlm_LowGrayLevelRunEmphasis : 0.0010427542282265838\n\t squareroot_glrlm_RunEntropy : 5.257678999066076\n\t squareroot_glrlm_RunLengthNonUniformity : 47808.490275021104\n\t squareroot_glrlm_RunLengthNonUniformityNormalized : 0.7364095745390469\n\t squareroot_glrlm_RunPercentage : 0.8224541810866822\n\t squareroot_glrlm_RunVariance : 0.5302054747517478\n\t squareroot_glrlm_ShortRunEmphasis : 0.8711937526543301\n\t squareroot_glrlm_ShortRunHighGrayLevelEmphasis : 6362.81163600089\n\t squareroot_glrlm_ShortRunLowGrayLevelEmphasis : 0.0009348739079733901\n\t squareroot_glszm_GrayLevelNonUniformity : 263.0289998027224\n\t squareroot_glszm_GrayLevelNonUniformityNormalized : 0.025944860899854254\n\t squareroot_glszm_GrayLevelVariance : 398.11958325862616\n\t squareroot_glszm_HighGrayLevelZoneEmphasis : 5880.471789307556\n\t squareroot_glszm_LargeAreaEmphasis : 12427.473564805681\n\t squareroot_glszm_LargeAreaHighGrayLevelEmphasis : 98031021.85815743\n\t squareroot_glszm_LargeAreaLowGrayLevelEmphasis : 1.891178860228763\n\t squareroot_glszm_LowGrayLevelZoneEmphasis : 0.0007118158467039592\n\t squareroot_glszm_SizeZoneNonUniformity : 3864.3136713355693\n\t squareroot_glszm_SizeZoneNonUniformityNormalized : 0.381171204511301\n\t squareroot_glszm_SmallAreaEmphasis : 0.6422651775051036\n\t squareroot_glszm_SmallAreaHighGrayLevelEmphasis : 3447.5680500073763\n\t squareroot_glszm_SmallAreaLowGrayLevelEmphasis : 0.00038991620348618523\n\t squareroot_glszm_ZoneEntropy : 7.990483501006231\n\t squareroot_glszm_ZonePercentage : 0.1335616889532969\n\t squareroot_glszm_ZoneVariance : 12371.41574600558\n\t squareroot_ngtdm_Busyness : 0.5946341122788487\n\t squareroot_ngtdm_Coarseness : 0.00010351779920040416\n\t squareroot_ngtdm_Complexity : 18805.304407144384\n\t squareroot_ngtdm_Contrast : 0.061320087141165845\n\t squareroot_ngtdm_Strength : 2.062894688132224\n\t wavelet-LLH_firstorder_10Percentile : -102.54706174375652\n\t wavelet-LLH_firstorder_90Percentile : 64.5032664870463\n\t wavelet-LLH_firstorder_Energy : 2209959919.8115044\n\t wavelet-LLH_firstorder_Entropy : 3.6774666474038535\n\t wavelet-LLH_firstorder_InterquartileRange : 52.538195697208096\n"
],
[
"import pandas as pd\ndf = pd.DataFrame.from_dict(result)",
"_____no_output_____"
],
[
"n1_img = nib.load('/Users/farnoosh/Documents/Projects/Data/nifti/BA4075-MASS/1_no_series_description.nii')",
"_____no_output_____"
],
[
"img_data = n1_img.get_data()\n\n# Convert to numpy ndarray (dtype: uint16)\nimg_data_arr = np.asarray(img_data)\nimg_data_arr.flatten()",
"_____no_output_____"
],
[
"np.sum(img_data_arr.flatten())",
"_____no_output_____"
],
[
"set(img_data_arr.flatten())",
"_____no_output_____"
],
[
"radiomics.__version__",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ad5964e1ed6027291fb5782d5b6e7c77acd0d9 | 4,461 | ipynb | Jupyter Notebook | DEMO/load_pretraining_models_tutorial.ipynb | markcheung/DeepPurpose | 4232906e9772eaf4001e23d3f784ac1bc8ad527d | [
"BSD-3-Clause"
] | null | null | null | DEMO/load_pretraining_models_tutorial.ipynb | markcheung/DeepPurpose | 4232906e9772eaf4001e23d3f784ac1bc8ad527d | [
"BSD-3-Clause"
] | null | null | null | DEMO/load_pretraining_models_tutorial.ipynb | markcheung/DeepPurpose | 4232906e9772eaf4001e23d3f784ac1bc8ad527d | [
"BSD-3-Clause"
] | 2 | 2021-01-16T10:00:40.000Z | 2021-05-29T06:15:40.000Z | 25.346591 | 215 | 0.536427 | [
[
[
"import os\nos.chdir('../')",
"_____no_output_____"
],
[
"from DeepPurpose import utils, models, dataset",
"_____no_output_____"
]
],
[
[
"There are two ways to load the pretrained model, the first way is to load from local model directory. \n\nA model directory should consist of two files: \n\nconfig.pkl that describes the configuration of the model and \nmodel.pt, which is the model weights. \n\nIf you use model.save(MODEL_DIR) to save the model, then, it should be good.\n\nThe below code exemplifies suppose your model is in the 'path', then, you can load the model using path_dir parameter.",
"_____no_output_____"
]
],
[
[
"path = utils.download_pretrained_model('Morgan_AAC_DAVIS')\nnet = models.model_pretrained(path_dir = path)",
"Beginning Downloading Morgan_AAC_DAVIS Model...\nDownloading finished... Beginning to extract zip file...\npretrained model Successfully Downloaded...\n"
],
[
"net.config",
"_____no_output_____"
]
],
[
[
"For models that provided by us, you can directly use the pre-designated model names. The full list is in the Github README https://github.com/kexinhuang12345/DeepPurpose/blob/master/README.md#pretrained-models",
"_____no_output_____"
]
],
[
[
"net = models.model_pretrained(model = 'MPNN_CNN_DAVIS')\nnet.config",
"Beginning Downloading MPNN_CNN_DAVIS Model...\nDownloading finished... Beginning to extract zip file...\npretrained model Successfully Downloaded...\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ad631eb3d1ee33e0263177697e79f9978fae7c | 11,552 | ipynb | Jupyter Notebook | LectureNotes/MC/MC.ipynb | enigne/ScientificComputingBridging | 920f3c9688ae0e7d17cffce5763289864b9cac80 | [
"MIT"
] | 2 | 2021-05-04T01:15:32.000Z | 2021-11-08T15:08:27.000Z | LectureNotes/MC/MC.ipynb | enigne/ScientificComputingBridging | 920f3c9688ae0e7d17cffce5763289864b9cac80 | [
"MIT"
] | null | null | null | LectureNotes/MC/MC.ipynb | enigne/ScientificComputingBridging | 920f3c9688ae0e7d17cffce5763289864b9cac80 | [
"MIT"
] | null | null | null | 30.16188 | 84 | 0.481129 | [
[
[
"from scipy.integrate import solve_ivp\nimport matplotlib.pyplot as plt\nimport numpy as np",
"_____no_output_____"
],
[
"saveFigure = False",
"_____no_output_____"
]
],
[
[
"# SIR example",
"_____no_output_____"
],
[
"## Deterministic model",
"_____no_output_____"
]
],
[
[
"def SIR(t, y, b, d, beta, u, v):\n N = y[0]+y[1]+y[2]\n return [b*N - d*y[0] - beta*y[1]/N*y[0] - v*y[0],\n beta*y[1]/N*y[0] - u*y[1] - d*y[1],\n u*y[1] - d*y[2] + v*y[0]]",
"_____no_output_____"
],
[
"# Time interval for the simulation\nt0 = 0\nt1 = 120\nt_span = (t0, t1)\nt_eval = np.linspace(t_span[0], t_span[1], 10000)\n\n# Initial conditions, \nN = 1000\nI = 5\nR = 0\nS = N - I\ny0 = [S, I , R]\n\n# Parameters\nb = 0.002/365\nd = 0.0016/365\nbeta = 0.3\nu = 1.0/7.0\nv = 0.0\n\n# Solve for SIR equation\nsol = solve_ivp(lambda t,y: SIR(t, y, b, d, beta, u, v),\n t_span, y0, method='RK45',t_eval=t_eval)\n\n# plot\nfig, ax = plt.subplots(1, figsize=(6, 4.5))\n# plot y1 and y2 together\nax.plot(sol.t.T,sol.y.T )\nax.set_ylabel('Number of predator and prey')\nax.set_xlabel('time')\nax.legend(['Susceptible', 'Infectious', 'Recover'])\n\nif saveFigure:\n filename = 'SIR_deterministic.pdf'\n fig.savefig(filename, format='pdf', dpi=1000, bbox_inches='tight')",
"_____no_output_____"
]
],
[
[
"## Stochastic model",
"_____no_output_____"
]
],
[
[
"import numpy as np\n# Plotting modules\nimport matplotlib.pyplot as plt\n\ndef sample_discrete(probs):\n \"\"\"\n Randomly sample an index with probability given by probs.\n \"\"\"\n # Generate random number\n q = np.random.rand()\n \n # Find index\n i = 0\n p_sum = 0.0\n while p_sum < q:\n p_sum += probs[i]\n i += 1\n return i - 1\n\n# Function to draw time interval and choice of reaction\ndef gillespie_draw(params, propensity_func, population):\n \"\"\"\n Draws a reaction and the time it took to do that reaction.\n \"\"\"\n # Compute propensities\n props = propensity_func(params, population)\n \n # Sum of propensities\n props_sum = props.sum()\n \n # Compute time\n time = np.random.exponential(1.0 / props_sum)\n \n # Compute discrete probabilities of each reaction\n rxn_probs = props / props_sum\n \n # Draw reaction from this distribution\n rxn = sample_discrete(rxn_probs)\n \n return rxn, time\n\n\ndef gillespie_ssa(params, propensity_func, update, population_0, \n time_points):\n \"\"\"\n Uses the Gillespie stochastic simulation algorithm to sample\n from proability distribution of particle counts over time.\n \n Parameters\n ----------\n params : arbitrary\n The set of parameters to be passed to propensity_func.\n propensity_func : function\n Function of the form f(params, population) that takes the current\n population of particle counts and return an array of propensities\n for each reaction.\n update : ndarray, shape (num_reactions, num_chemical_species)\n Entry i, j gives the change in particle counts of species j\n for chemical reaction i.\n population_0 : array_like, shape (num_chemical_species)\n Array of initial populations of all chemical species.\n time_points : array_like, shape (num_time_points,)\n Array of points in time for which to sample the probability\n distribution.\n \n Returns\n -------\n sample : ndarray, shape (num_time_points, num_chemical_species)\n Entry i, j is the count of chemical species j at time\n time_points[i].\n \"\"\"\n\n # Initialize output\n pop_out = np.empty((len(time_points), update.shape[1]), dtype=np.int)\n\n # Initialize and perform simulation\n i_time = 1\n i = 0\n t = time_points[0]\n population = population_0.copy()\n pop_out[0,:] = population\n while i < len(time_points):\n while t < time_points[i_time]:\n # draw the event and time step\n event, dt = gillespie_draw(params, propensity_func, population)\n \n # Update the population\n population_previous = population.copy()\n population += update[event,:]\n \n # Increment time\n t += dt\n\n # Update the index\n i = np.searchsorted(time_points > t, True)\n \n # Update the population\n pop_out[i_time:min(i,len(time_points))] = population_previous\n \n # Increment index\n i_time = i\n \n return pop_out\n\ndef simple_propensity(params, population):\n \"\"\"\n Returns an array of propensities given a set of parameters\n and an array of populations.\n \"\"\"\n # Unpack parameters\n beta, b, d, u, v = params\n \n # Unpack population\n S, I, R = population\n \n N = S + I + R\n \n return np.array([beta*I*S/N, \n u*I,\n v*S,\n d*S,\n d*I,\n d*R,\n b*N])",
"_____no_output_____"
]
],
[
[
"#### Solve SIR in stochastic method",
"_____no_output_____"
]
],
[
[
"# Column changes S, I, R\nsimple_update = np.array([[-1, 1, 0],\n [0, -1, 1],\n [-1, 0, 1],\n [-1, 0, 0],\n [0, -1, 0],\n [0, 0, -1],\n [1, 0, 0]], dtype=np.int)\n\n# Specify parameters for calculation\nparams = np.array([0.3, 0.002/365, 0.0016/365, 1/7.0, 0])\ntime_points = np.linspace(0, 120, 500)\npopulation_0 = np.array([995, 5, 0])\nn_simulations = 100\n\n# Seed random number generator for reproducibility\nnp.random.seed(42)\n\n# Initialize output array\npops = np.empty((n_simulations, len(time_points), 3))\n\n# Run the calculations\nfor i in range(n_simulations):\n pops[i,:,:] = gillespie_ssa(params, simple_propensity, simple_update,\n population_0, time_points)",
"_____no_output_____"
],
[
"# Set up subplots\nfig, ax = plt.subplots(1, 1, figsize=(6, 4.5))\n\nfor j in range(3):\n ax.plot(time_points, pops[4,:,j], '-',\n color='C'+str(j))\nax.set_ylabel('Number of predator and prey')\nax.set_xlabel('time')\nax.legend(['Susceptible', 'Infectious', 'Recover'])\n\nif saveFigure:\n filename = 'SIR_stochastic1.pdf'\n fig.savefig(filename, format='pdf', dpi=1000, bbox_inches='tight')",
"_____no_output_____"
],
[
"# Set up subplots\nfig, ax = plt.subplots(1, 1, figsize=(6, 4.5))\nax.plot(time_points, pops[:,:,0].mean(axis=0), lw=6)\nax.plot(time_points, pops[:,:,1].mean(axis=0), lw=6)\nax.plot(time_points, pops[:,:,2].mean(axis=0), lw=6)\n\nax.set_ylabel('Number of predator and prey')\nax.set_xlabel('time')\nax.legend(['Susceptible', 'Infectious', 'Recover'])\n\nfor j in range(3):\n for i in range(n_simulations):\n ax.plot(time_points, pops[i,:,j], '-', lw=0.3, alpha=0.2, \n color='C'+str(j))\n\nif saveFigure:\n filename = 'SIR_stochasticAll.pdf'\n fig.savefig(filename, format='pdf', dpi=1000, bbox_inches='tight')",
"_____no_output_____"
]
],
[
[
"# Simulate interest rate path by the CIR model ",
"_____no_output_____"
]
],
[
[
"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef cir(r0, K, theta, sigma, T=1., N=10,seed=777):\n np.random.seed(seed)\n dt = T/float(N) \n rates = [r0]\n for i in range(N):\n dr = K*(theta-rates[-1])*dt + \\\n sigma*math.sqrt(abs(rates[-1]))*np.random.normal()\n rates.append(rates[-1] + dr)\n return range(N+1), rates\n\nfig, ax = plt.subplots(1, 1, figsize=(6, 4.5))\n\nfor i in range(30):\n x, y = cir(72, 0.001, 0.01, 0.012, 10., N=200, seed=100+i)\n ax.plot(x, y)\nax.set_ylabel('Assets price')\nax.set_xlabel('time')\nax.autoscale(enable=True, axis='both', tight=True)\n\nif saveFigure:\n filename = 'CIR.pdf'\n fig.savefig(filename, format='pdf', dpi=1000, bbox_inches='tight')",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ad70b7b92614ccf308bc2d69de8cd5d456e1ab | 10,230 | ipynb | Jupyter Notebook | pandas/using_sql_only.ipynb | ItsVinodAdari/Data-Science | 2d90f5368b39dc1a3c7a6b2ed07ac453cc6c6f87 | [
"MIT"
] | null | null | null | pandas/using_sql_only.ipynb | ItsVinodAdari/Data-Science | 2d90f5368b39dc1a3c7a6b2ed07ac453cc6c6f87 | [
"MIT"
] | 2 | 2020-06-01T08:27:45.000Z | 2021-08-23T20:16:24.000Z | pandas/using_sql_only.ipynb | vinodh17k/Data-Science | 2d90f5368b39dc1a3c7a6b2ed07ac453cc6c6f87 | [
"MIT"
] | null | null | null | 29.396552 | 169 | 0.394135 | [
[
[
"import pandas as pd\nimport sqlite3\n\n# creating connection to database\nconn = sqlite3.connect(\"../datasets/database.sqlite\")\n\n# fetching actual tables in database and \n# tables [reviews,artists,genres,labels,years,content]\n# WHERE type='table' AND name NOT LIKE 'sqlite_%'\ntables = pd.read_sql(\n \"SELECT name FROM sqlite_master\", conn)\ntables",
"_____no_output_____"
],
[
"# case statement by condition expression\nyears = pd.read_sql(\n 'SELECT reviewid, IFNULL(year,0), CASE WHEN year < 2010 THEN \"the year less than 2010\" ELSE \"the year more than 2010\" END AS yeartext FROM years', conn)\n# select *, CASE WHEN year > 2010 THEN \"the year is above 2010\" ELSE \"the year below 2010\" END AS yeartext from years\n# fetching years column without null\nyears_without_null = pd.read_sql('SELECT * FROM years WHERE year IS NOT NULL', conn)\n\n# fecthing DISTINCT(different values only) years \ndistinct_years = pd.read_sql('SELECT DISTINCT year FROM years', conn)\nyears",
"_____no_output_____"
],
[
"# ordering by year ascending(ASC)\nasc_years = pd.read_sql('SELECT * FROM years WHERE year IS NOT NULL ORDER BY year', conn)\n\n# using aggregate function COUNT and null function\nyears_count = pd.read_sql('SELECT COUNT(year), IFNULL(year,0000) FROM years GROUP BY year', conn)",
"_____no_output_____"
],
[
"# fetching reviews and artists using INNER JOIN table by conn\nreviews = pd.read_sql(\"SELECT * FROM reviews INNER JOIN artists WHERE reviews.reviewid LIMIT '10'\", conn)\n\n# fetching 5 last rows as first index rows with asc\nlast_five_rows_of_years = pd.read_sql('SELECT * FROM (SELECT * FROM years ORDER BY reviewid DESC LIMIT 5) ORDER BY reviewid ASC', conn)\nlast_five_rows_of_years",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
e7ad82cf55f0790356e4ed06348426993b45eda8 | 74,461 | ipynb | Jupyter Notebook | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis | 9c68eabd3770290b5c77ec416cb749ef704da475 | [
"MIT"
] | null | null | null | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis | 9c68eabd3770290b5c77ec416cb749ef704da475 | [
"MIT"
] | null | null | null | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis | 9c68eabd3770290b5c77ec416cb749ef704da475 | [
"MIT"
] | null | null | null | 47.977448 | 15,644 | 0.750903 | [
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n## for correlation matrices\nimport seaborn as sns\n%matplotlib inline\n## for linear models\nimport statsmodels.api as sm\nfrom pandas.plotting import scatter_matrix\nfrom sklearn.metrics import roc_curve, auc\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\nfrom yellowbrick.classifier import ConfusionMatrix\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn import preprocessing\n\n# from imblearn.over_sampling import SMOTE\n\nfrom sklearn.metrics import classification_report\nfrom imblearn.over_sampling import RandomOverSampler\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.over_sampling import SMOTE\n\nfrom sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score, balanced_accuracy_score, confusion_matrix\n\n%run ../pyfiles/data_cleaning.py\n%run ../pyfiles/grid_search.py\n%run ../pyfiles/modeling.py\n%run ../pyfiles/unmetDemand.py",
"_____no_output_____"
],
[
"# # Set global random seed\n# np.random.seed(123)",
"_____no_output_____"
]
],
[
[
"### Import data and drop redundant data (rates)",
"_____no_output_____"
]
],
[
[
"# import data\ndf = pd.read_csv('../../data/deepsolar_tract.csv', encoding = \"utf-8\")",
"_____no_output_____"
]
],
[
[
"### Clean Data",
"_____no_output_____"
]
],
[
[
"df = drop_redundant_columns(df)",
"_____no_output_____"
],
[
"# Create our target column 'has_tiles', and drop additional redundant columns\n\ndf = create_has_tiles_target_column(df)",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"# # # Figure out which variables are highly correlated, remove the most correlated ones one by one\n\n# corr = pd.DataFrame((df.corr() > 0.8).sum())\n# corr.sort_values(by = 0, ascending = False)[0:5]",
"_____no_output_____"
],
[
"# # # Add highly correlated variables to list 'to_drop'\n# to_drop = ['poverty_family_count','education_population','population', 'household_count','housing_unit_occupied_count', 'electricity_price_overall']",
"_____no_output_____"
],
[
"# Drop highly colinear variables\n# df = df.drop(to_drop, axis = 1)",
"_____no_output_____"
],
[
"# VIF score",
"_____no_output_____"
]
],
[
[
"### Checking for missing values",
"_____no_output_____"
]
],
[
[
"nulls = pd.DataFrame(df.isna().sum())\nnulls.columns = [\"missing\"]\nnulls[nulls['missing']>0].head()",
"_____no_output_____"
],
[
"# drop all missing values\ndf = df.dropna(axis = 0)",
"_____no_output_____"
],
[
"# Check class imbalance\ndf.has_tiles.value_counts()",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
]
],
[
[
"### Train test split",
"_____no_output_____"
]
],
[
[
"X = df.drop('has_tiles', axis = 1)\ny = df['has_tiles']",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify = y)",
"_____no_output_____"
]
],
[
[
"## Sampling Techniques",
"_____no_output_____"
]
],
[
[
"# smote, undersampling, or oversampling\nX_train, y_train = pick_sampling_method(X_train, y_train, method = 'oversampling')",
"_____no_output_____"
],
[
"y_train.value_counts()",
"_____no_output_____"
]
],
[
[
"### Scale Data ",
"_____no_output_____"
]
],
[
[
"scaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)",
"_____no_output_____"
],
[
"X_train.shape",
"_____no_output_____"
]
],
[
[
"## Modeling",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import classification_report",
"_____no_output_____"
]
],
[
[
"### Vanilla Decision Tree 0.74 ",
"_____no_output_____"
]
],
[
[
"## DUMMY\ndummy = DecisionTreeClassifier()\ndummy.fit(X_train, y_train)",
"_____no_output_____"
],
[
"y_pred = dummy.predict(X_test)",
"_____no_output_____"
],
[
"print(\"Precision: {}\".format(precision_score(y_test, y_pred)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred)))",
"Precision: 0.8467012423109396\nRecall: 0.84375\nAccuracy: 0.7623844731977819\nF1 Score: 0.8452230449702004\n"
],
[
"print(classification_report(y_test, y_pred))",
" precision recall f1-score support\n\n 0 0.24 0.82 0.37 2500\n 1 0.79 0.21 0.33 8320\n\n accuracy 0.35 10820\n macro avg 0.51 0.51 0.35 10820\nweighted avg 0.66 0.35 0.34 10820\n\n"
]
],
[
[
"### Decision Tree with Hyperparameter Tuning",
"_____no_output_____"
]
],
[
[
"dt = find_hyperparameters(pipe_dt, params_dt, X_train, y_train)",
"_____no_output_____"
],
[
"dt.best_params_\nbest_dt = dt.best_estimator_\n# Decision Tree: {'dt__max_depth': 2, 'dt__min_samples_leaf': 1, 'dt__min_samples_split': 2}",
"_____no_output_____"
],
[
"best_dt.fit(X_train, y_train)\nbest_dt.score(X_test, y_test)\n# Decision Tree: 0.755637707948244",
"_____no_output_____"
],
[
"y_pred_dt = best_dt.predict(X_test)\nprint(\"Precision: {}\".format(precision_score(y_test, y_pred_dt)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred_dt)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred_dt)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred_dt)))",
"Precision: 0.9131785238869989\nRecall: 0.7420673076923077\nAccuracy: 0.7474121996303142\nF1 Score: 0.8187785955838471\n"
]
],
[
[
"## Final Model",
"_____no_output_____"
]
],
[
[
"# with oversampling",
"_____no_output_____"
],
[
"rf = RandomForestClassifier(max_features = 'sqrt', max_depth = 5, min_samples_leaf = 5, n_estimators = 30)\nrf.fit(X_train, y_train)\ny_pred = rf.predict(X_test)",
"_____no_output_____"
],
[
"print(\"Precision: {}\".format(precision_score(y_test, y_pred)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred)))\nprint(\"Balanced Accuracy: {}\".format(balanced_accuracy_score(y_test, y_pred)))",
"Precision: 0.9180549302116164\nRecall: 0.7352163461538461\nAccuracy: 0.7459334565619223\nF1 Score: 0.8165253954481745\nBalanced Accuracy: 0.758408173076923\n"
],
[
"cm = ConfusionMatrix(rf, fontsize = 'x-large', classes = ['No Solar', 'Solar'])\ncm.score(X_test, y_test)\ncm.show()",
"C:\\Users\\allis\\Anaconda3\\lib\\site-packages\\sklearn\\base.py:197: FutureWarning: From version 0.24, get_params will raise an AttributeError if a parameter cannot be retrieved as an instance attribute. Previously it would return None.\n FutureWarning)\nC:\\Users\\allis\\Anaconda3\\lib\\site-packages\\yellowbrick\\classifier\\base.py:232: YellowbrickWarning: could not determine class_counts_ from previously fitted classifier\n YellowbrickWarning,\n"
]
],
[
[
"### Vanilla Random Forests",
"_____no_output_____"
]
],
[
[
"rf = RandomForestClassifier()",
"_____no_output_____"
],
[
"rf.fit(X_train, y_train)\ny_pred = rf.predict(X_test)",
"_____no_output_____"
],
[
"print(\"Precision: {}\".format(precision_score(y_test, y_pred)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred)))\nprint(\"Balanced Accuracy: {}\".format(balanced_accuracy_score(y_test, y_pred)))",
"Precision: 0.8665596698383584\nRecall: 0.9085336538461538\nAccuracy: 0.8220887245841035\nF1 Score: 0.8870504019245439\nBalanced Accuracy: 0.7214668269230768\n"
],
[
"cm_rf = ConfusionMatrix(rf, classes = ['No Solar', 'Solar'], label_encoder={0: 'No Solar', 1: 'Solar'})\ncm_rf.score(X_test, y_test)\ncm_rf.poof()",
"C:\\Users\\allis\\Anaconda3\\lib\\site-packages\\sklearn\\base.py:197: FutureWarning: From version 0.24, get_params will raise an AttributeError if a parameter cannot be retrieved as an instance attribute. Previously it would return None.\n FutureWarning)\nC:\\Users\\allis\\Anaconda3\\lib\\site-packages\\yellowbrick\\classifier\\base.py:232: YellowbrickWarning: could not determine class_counts_ from previously fitted classifier\n YellowbrickWarning,\n"
],
[
"# vanilla with smote\n# Precision: 0.8955014655282274\n# Recall: 0.8445913461538461\n# Accuracy: 0.804713493530499\n# F1 Score: 0.8693016638832188\n# Balanced Accuracy: 0.758295673076923",
"_____no_output_____"
],
[
"# vanilla with oversampling\n# Precision: 0.8665596698383584\n# Recall: 0.9085336538461538\n# Accuracy: 0.8220887245841035\n# F1 Score: 0.8870504019245439\n# Balanced Accuracy: 0.7214668269230768",
"_____no_output_____"
]
],
[
[
"### Random Forests with Hyperparameter Tuning",
"_____no_output_____"
]
],
[
[
"### Random Forests\nrf = find_hyperparameters(pipe_rf, params_rf, X_train, y_train)",
"_____no_output_____"
],
[
"print(rf.best_params_)\nbest_rf = rf.best_estimator_\n\n#first hyperparamter tuning: {'rf__max_features': 'sqrt', 'rf__min_samples_leaf': 20, 'rf__n_estimators': 30}\n# Second tuning: {'rf__min_samples_leaf': 5, 'rf__n_estimators': 50}",
"{'rf__min_samples_leaf': 5, 'rf__n_estimators': 50}\n"
],
[
"best_rf.fit(X_train, y_train)\nbest_rf.score(X_test, y_test)\n# Random Forests: 0.793807763401109",
"_____no_output_____"
],
[
"y_pred_rf = best_rf.predict(X_test)\nprint(\"Precision: {}\".format(precision_score(y_test, y_pred_rf)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred_rf)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred_rf)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred_rf)))\nprint(\"Balanced Accuracy: {}\".format(balanced_accuracy_score(y_test, y_pred_rf)))",
"Precision: 0.8924837003321442\nRecall: 0.8719951923076923\nAccuracy: 0.8207948243992607\nF1 Score: 0.8821204936470303\nBalanced Accuracy: 0.7611975961538462\n"
]
],
[
[
"### Vanilla SVC",
"_____no_output_____"
]
],
[
[
"svc = SVC()\nsvc.fit(X_train, y_train)",
"_____no_output_____"
],
[
"y_pred_svc = svc.predict(X_test)",
"_____no_output_____"
],
[
"print(\"Precision: {}\".format(precision_score(y_test, y_pred_svc)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred_svc)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred_svc)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred_svc)))",
"Precision: 0.9094472225976483\nRecall: 0.8087740384615385\nAccuracy: 0.7910351201478744\nF1 Score: 0.8561613334181563\n"
]
],
[
[
"### SVC with Hyperparameter Tuning",
"_____no_output_____"
]
],
[
[
"svc = find_hyperparameters(pipe_svc, params_svc, X_train, y_train)",
"_____no_output_____"
],
[
"print(svc.best_params_)\nbest_svc = svc.best_estimator_",
"_____no_output_____"
],
[
"best_svc.fit(X_train, y_train)\nbest_svc.score(X_test, y_test)",
"_____no_output_____"
],
[
"y_pred_svc = best_svc.predict(X_test)\nprint(\"Precision: {}\".format(precision_score(y_test, y_pred_svc)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred_svc)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred_svc)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred_svc)))",
"_____no_output_____"
]
],
[
[
"### Vanilla KNN",
"_____no_output_____"
]
],
[
[
"knn = KNeighborsClassifier()\nknn.fit(X_train, y_train)",
"_____no_output_____"
],
[
"y_pred_knn = knn.predict(X_test)\nprint(\"Precision: {}\".format(precision_score(y_test, y_pred_knn)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred_knn)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred_knn)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred_knn)))",
"Precision: 0.9354388413889374\nRecall: 0.6443509615384615\nAccuracy: 0.6923290203327171\nF1 Score: 0.7630773610419187\n"
]
],
[
[
"### KNN with Hyperparameter Tuning",
"_____no_output_____"
]
],
[
[
"knn = find_hyperparameters(pipe_knn, params_knn, X_train, y_train)",
"_____no_output_____"
],
[
"print(knn.best_params_)\nbest_knn = knn.best_estimator_",
"_____no_output_____"
],
[
"best_knn.fit(X_train, y_train)\nbest_knn.score(X_test, y_test)",
"_____no_output_____"
],
[
"y_pred_knn = best_knn.predict(X_test)\nprint(\"Precision: {}\".format(precision_score(y_test, y_pred_knn)))\nprint(\"Recall: {}\".format(recall_score(y_test, y_pred_knn)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_test, y_pred_knn)))\nprint(\"F1 Score: {}\".format(f1_score(y_test, y_pred_knn)))",
"_____no_output_____"
]
],
[
[
"### Preliminary Conclusions: Model Performance Comparisons",
"_____no_output_____"
],
[
"Based on comparisons of both accuracy and balanced accuracy scores, our Random Forest Classifier model performed the best with oversampling methods and hyperparameter tuning. \n",
"_____no_output_____"
]
],
[
[
"falsepositives = isFalsePositive(df, X_test, y_test, rf)",
"_____no_output_____"
],
[
"inversefalsepositives = scaler.inverse_transform(falsepositives)\ninversefalsepositives = pd.DataFrame(inversefalsepositives)\ninversefalsepositives = inversefalsepositives.set_axis(falsepositives.columns, axis=1, inplace=False)",
"_____no_output_____"
],
[
"len(inversefalsepositives)",
"_____no_output_____"
],
[
"ozdf = pd.read_csv(\"../data/ListOfOppurtunityZonesWithoutAKorHI.csv\", encoding = \"utf-8\")\nozdf = ozdf.rename(columns={\"Census Tract Number\": \"Census_Tract_Number\", \"Tract Type\": \"Tract_Type\", \"ACS Data Source\": \"ACS_Data_Source\"})\n# results = pd.merge(inversefalsepositives, ozdf, left_on = inversefalsepositives.fips, right_on = ozdf.Census_Tract_Number)",
"_____no_output_____"
],
[
"results.to_csv('../data/results.csv')",
"_____no_output_____"
]
],
[
[
"### Running Model on Entire Dataset",
"_____no_output_____"
]
],
[
[
"ozdf = ozdf['Census_Tract_Number']",
"_____no_output_____"
],
[
"merged = df.merge(ozdf, how = 'left', left_on='fips',right_on='Census_Tract_Number')",
"_____no_output_____"
],
[
"merged = merged.dropna()",
"_____no_output_____"
],
[
"merged.drop('fips', axis = 1, inplace = True)",
"_____no_output_____"
],
[
"merged['has_tiles'].value_counts()",
"_____no_output_____"
],
[
"X_ozdf = merged.drop('has_tiles', axis = 1)\ny_ozdf = merged['has_tiles']",
"_____no_output_____"
],
[
"y_pred_ozdf = rf.predict(X_ozdf)",
"_____no_output_____"
],
[
"y_pred_ozdf",
"_____no_output_____"
],
[
"y_pred_ozdf = pd.Series(y_pred_ozdf)",
"_____no_output_____"
],
[
"y_pred_ozdf.value_counts()",
"_____no_output_____"
],
[
"final = merged.merge(y_pred_ozdf.rename('y_pred'), how = 'left', on = merged.index)",
"_____no_output_____"
],
[
"final = final[final['y_pred'] == 1]",
"_____no_output_____"
]
],
[
[
"### Experimenting with Final Model",
"_____no_output_____"
]
],
[
[
"y_pred_all = rf.predict(X)\ny_pred_all = pd.Series(y_pred_all)",
"_____no_output_____"
],
[
"predictions = df.merge(y_pred_all.rename('pred_'), how = 'left', on = df.index)",
"_____no_output_____"
],
[
"predictions = predictions.merge(ozdf, how = 'left', left_on='fips',right_on='Census_Tract_Number')",
"_____no_output_____"
],
[
"final_zones = predictions.dropna()",
"_____no_output_____"
],
[
"(final_zones.pred_).unique()",
"_____no_output_____"
],
[
"predictions['pred_'].value_counts()",
"_____no_output_____"
],
[
"y_pred_train = rf.predict(X_train)",
"_____no_output_____"
],
[
"print(\"Precision: {}\".format(precision_score(y_train, y_pred_train)))\nprint(\"Recall: {}\".format(recall_score(y_train, y_pred_train)))\nprint(\"Accuracy: {}\".format(accuracy_score(y_train, y_pred_train)))\nprint(\"F1 Score: {}\".format(f1_score(y_train, y_pred_train)))",
"Precision: 0.7939935224261458\nRecall: 0.7292449145157898\nAccuracy: 0.7700189297196599\nF1 Score: 0.760243077308608\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ad8df886dd42ac2856d48c6dcb89d29e969bb4 | 98,389 | ipynb | Jupyter Notebook | Example_EDF_vs_Uncontrolled.ipynb | zach401/eEnergy_acnsim_abstract | ab301617f7b339eabe6a91479816a98eb7308078 | [
"BSD-3-Clause"
] | 1 | 2021-04-04T06:30:25.000Z | 2021-04-04T06:30:25.000Z | Example_EDF_vs_Uncontrolled.ipynb | zach401/eEnergy_acnsim_abstract | ab301617f7b339eabe6a91479816a98eb7308078 | [
"BSD-3-Clause"
] | null | null | null | Example_EDF_vs_Uncontrolled.ipynb | zach401/eEnergy_acnsim_abstract | ab301617f7b339eabe6a91479816a98eb7308078 | [
"BSD-3-Clause"
] | null | null | null | 223.104308 | 52,890 | 0.884103 | [
[
[
"<a href=\"https://colab.research.google.com/github/zach401/acnsim-edf-vs-uncontrolled/blob/master/Example_EDF_vs_Uncontrolled.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"*If running in a new enviroment, such as Google Colab, run this first.*",
"_____no_output_____"
]
],
[
[
"!git clone https://github.com/zach401/acnportal.git\n!pip install acnportal/.",
"fatal: destination path 'acnportal' already exists and is not an empty directory.\nProcessing ./acnportal\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (1.19.5)\nRequirement already satisfied: pandas<1.2.0,>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (1.1.5)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (3.2.2)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (2.23.0)\nRequirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (2018.9)\nRequirement already satisfied: typing_extensions in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (3.7.4.3)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from acnportal==0.3.2) (0.22.2.post1)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas<1.2.0,>=1.1.0->acnportal==0.3.2) (2.8.1)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->acnportal==0.3.2) (2.4.7)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->acnportal==0.3.2) (1.3.1)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->acnportal==0.3.2) (0.10.0)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->acnportal==0.3.2) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->acnportal==0.3.2) (2021.5.30)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->acnportal==0.3.2) (1.24.3)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->acnportal==0.3.2) (3.0.4)\nRequirement already satisfied: scipy>=0.17.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->acnportal==0.3.2) (1.4.1)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->acnportal==0.3.2) (1.0.1)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas<1.2.0,>=1.1.0->acnportal==0.3.2) (1.15.0)\nBuilding wheels for collected packages: acnportal\n Building wheel for acnportal (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for acnportal: filename=acnportal-0.3.2-cp37-none-any.whl size=138186 sha256=3368733c1dec9d05de7908b976c4e4a822ef7b38cfa5a8c88fdbe873ea4a51eb\n Stored in directory: /tmp/pip-ephem-wheel-cache-4zjo5oug/wheels/6d/6a/19/10aef74a8c705c23f53e3e1d696420b07fcdbc88af47701336\nSuccessfully built acnportal\nInstalling collected packages: acnportal\n Found existing installation: acnportal 0.3.2\n Uninstalling acnportal-0.3.2:\n Successfully uninstalled acnportal-0.3.2\nSuccessfully installed acnportal-0.3.2\n"
]
],
[
[
"# ACN-Sim Example\n## Comparing EDF and Uncontrolled Charging\n### by Zachary Lee\n#### Last updated: 04/19/2019\n\nIn this example we implement a custom version of the Earliest Deadline First algorithm and compare it with Uncontrolled Charging. We show how easy it is to implement a custom algorithm using ACN-Sim as well as the simplicity of running a common experiment.",
"_____no_output_____"
],
[
"## Custom Algorithm\n\nAll custom algorithms inherit from the abstract class BaseAlgorithm. It is the responsibility of all derived classes to implement the schedule method. This method takes as an input a list of EVs which are currently connected to the system but have not yet finished charging. Its output is a dictionary which maps a station_id to a list of charging rates. Each charging rate is valid for one period measured relative to the current period.\n\nFor Example: \n * schedule[‘abc’][0] is the charging rate for station ‘abc’ during the current period \n * schedule[‘abc’][1] is the charging rate for the next period \n * and so on. ",
"_____no_output_____"
],
[
"#### def __init__(self, increment=1):\n\nWe can override the __init__() method if we need to pass additional configuration information to the algorithm. In this case we pass in the increment which will be used when searching for a feasible rate.",
"_____no_output_____"
],
[
"#### schedule(self, active_evs)\n\nWe next need to override the schedule() method. The signature of this method should remain the same, as it is called internally in Simulator. If an algorithm needs additional parameters consider passing them through the constructor.",
"_____no_output_____"
]
],
[
[
"from acnportal.algorithms import BaseAlgorithm\n\nclass EarliestDeadlineFirstAlgo(BaseAlgorithm):\n \"\"\" Algorithm which assigns charging rates to each EV in order or departure time.\n\n Implements abstract class BaseAlgorithm.\n\n For this algorithm EVs will first be sorted by departure time. We will then allocate as much\n current as possible to each EV in order until the EV is finished charging or an infrastructure\n limit is met.\n\n Args:\n increment (number): Minimum increment of charging rate. Default: 1.\n \"\"\"\n def __init__(self, increment=1):\n super().__init__()\n self._increment = increment\n\n def schedule(self, active_evs):\n schedule = {ev.station_id: [0] for ev in active_evs}\n\n # Next, we sort the active_evs by their departure time.\n sorted_evs = sorted(active_evs, key=lambda x: x.departure)\n\n # We now iterate over the sorted list of EVs.\n for ev in sorted_evs:\n # First try to charge the EV at its maximum rate. Remember that each schedule value\n # must be a list, even if it only has one element.\n schedule[ev.station_id] = [self.interface.max_pilot_signal(ev.station_id)]\n\n # If this is not feasible, we will reduce the rate.\n # interface.is_feasible() is one way to interact with the constraint set\n # of the network. We will explore another more direct method in lesson 3.\n while not self.interface.is_feasible(schedule, 0):\n\n # Since the maximum rate was not feasible, we should try a lower rate.\n schedule[ev.station_id][0] -= self._increment\n\n # EVs should never charge below 0 (i.e. discharge) so we will clip the value at 0.\n if schedule[ev.station_id][0] < 0:\n schedule[ev.station_id] = [0]\n break\n return schedule",
"_____no_output_____"
]
],
[
[
"Note the structure of the schedule dict which is returned should be something like:\n\n```\n{\n 'CA-301': [32, 32, 32, 16, 16, ..., 8],\n 'CA-302': [8, 13, 13, 15, 6, ..., 0],\n ...,\n 'CA-408': [24, 24, 24, 24, 0, ..., 0]\n}\n```\nFor the special case when an algorithm only calculates a target rate for the next time interval instead of an entire schedule of rates, the structure should be:\n\n```\n{\n 'CA-301': [32],\n 'CA-302': [8],\n ...,\n 'CA-408': [24]\n}\n```\n\nNote that these are single element lists and NOT floats or integers.",
"_____no_output_____"
],
[
"## Running the Algorithm\n\nNow that we have implemented our algorithm, we can try it out. ACN-Sim provides useful utilities to make defining an experiment and running a simulation extremely simple. ",
"_____no_output_____"
]
],
[
[
"import pytz\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style='ticks', palette='Set2')\nfrom copy import deepcopy\n\nfrom acnportal.algorithms import SortedSchedulingAlgo, UncontrolledCharging\nfrom acnportal.algorithms import earliest_deadline_first\nfrom acnportal.acnsim.events import acndata_events\nfrom acnportal.acnsim.network.sites import CaltechACN\nfrom acnportal.acnsim.analysis import *\nfrom acnportal.acnsim import Simulator\n\nfrom datetime import datetime\n\n# -- Experiment Parameters ---------------------------------------------------------------------------------------------\ntimezone = pytz.timezone('America/Los_Angeles')\nstart = datetime(2018, 9, 5).astimezone(timezone)\nend = datetime(2018, 9, 6).astimezone(timezone)\nperiod = 5 # minute\nvoltage = 220 # volts\nmax_rate = 32 # amps\nsite = 'caltech'\n\n# -- Network -----------------------------------------------------------------------------------------------------------\ncn = CaltechACN(basic_evse=True)\n\n# -- Events ------------------------------------------------------------------------------------------------------------\nAPI_KEY = 'DEMO_TOKEN'\nevents = acndata_events.generate_events(API_KEY, site, start, end, period, voltage, max_rate)\n\n\n# -- Scheduling Algorithm ----------------------------------------------------------------------------------------------\nschEDF = EarliestDeadlineFirstAlgo(increment=1)\nschUC = UncontrolledCharging()",
"WARNING: CaltechACN will be removed in a future release. Please use caltech_acn().\n"
],
[
"%%capture\n# -- Simulator ---------------------------------------------------------------------------------------------------------\nsimEDF = Simulator(deepcopy(cn), schEDF, deepcopy(events), start, period=period)\nsimEDF.run()",
"_____no_output_____"
],
[
"%%capture\n# For comparison we will also run the builtin UncontrolledCharging algorithm\nsimUC = Simulator(deepcopy(cn), schUC, deepcopy(events), start, period=period)\nsimUC.run()",
"_____no_output_____"
]
],
[
[
"## Results\n\nWe can now compare the two algorithms side by side by looking that the plots of aggregated current. \n\nWe can see from this plot that UncontrolledCharging peaks before EDF and at a higher rate. This is because UncontrolledCharging does not factor in the constraints of infrastructure.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline \nplt.plot(aggregate_current(simEDF), label='Earliest Deadline First', alpha=0.75)\nplt.plot(aggregate_current(simUC), label='Uncontrolled Charging', alpha=0.75)\nplt.xlim(125, 325)\nplt.legend()\nplt.xlabel('Time (periods)')\nplt.ylabel('Current (A)')\nplt.title('Total Aggregate Current')\nplt.show()",
"_____no_output_____"
]
],
[
[
"To see this more clearly, we can example line currents in the three-phase system. Here we plot the line currents at the secondary side of the Caltech ACN transformer. We also include the current limit for these lines as a grey dashed line. We can see that in the uncontrolled case, the current in line A exceeds its limit, while in our EDF algorithm, all currents are below their limits. ",
"_____no_output_____"
]
],
[
[
"cc_EDF = constraint_currents(simEDF)\ncc_UC = constraint_currents(simUC)\n\nfig, axes = plt.subplots(1, 2, sharey=True, sharex=True, figsize=(5,2.5))\nfig.subplots_adjust(wspace=0.07)\naxes[0].set_xlim(125, 325)\n\nfor line in 'ABC': \n axes[0].plot(cc_EDF['Secondary {0}'.format(line)], label=line)\n axes[1].plot(cc_UC['Secondary {0}'.format(line)], label=line)\n\naxes[0].axhline(420, color='gray', linestyle='--')\naxes[1].axhline(420, color='gray', linestyle='--')\n \naxes[1].legend()\naxes[0].set_xlabel('Time (periods)')\naxes[1].set_xlabel('Time (periods)')\naxes[0].set_ylabel('Current (A)')\nsns.despine()\nplt.show()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7ad8ec5d42a6a7458fe5a83673aa7176e1d73eb | 4,794 | ipynb | Jupyter Notebook | #01. Data Tables & Basic Concepts of Programming/01session-Copy1.ipynb | jesusmartinezprofesor/machine-learning-program | 8d1148986d10a88d13dd4a486e01fd13f8d060c0 | [
"MIT"
] | null | null | null | #01. Data Tables & Basic Concepts of Programming/01session-Copy1.ipynb | jesusmartinezprofesor/machine-learning-program | 8d1148986d10a88d13dd4a486e01fd13f8d060c0 | [
"MIT"
] | null | null | null | #01. Data Tables & Basic Concepts of Programming/01session-Copy1.ipynb | jesusmartinezprofesor/machine-learning-program | 8d1148986d10a88d13dd4a486e01fd13f8d060c0 | [
"MIT"
] | null | null | null | 30.535032 | 269 | 0.544639 | [
[
[
"<font size=\"+5\">#01. Data Tables, Plots & Basic Concepts of Programming</font>",
"_____no_output_____"
],
[
"<ul>\n <li>Doubts? → Ask me in <img src=\"https://emoji.gg/assets/emoji/3970-discord.png\" style=\"height: 1em; vertical-align: middle;\"> <a href=\"https://discord.gg/cmB3KGsqMy\">Discord</a></li>\n <li>Tutorials → <img src=\"https://openmoji.org/php/download_asset.php?type=emoji&emoji_hexcode=E044&emoji_variant=color\" style=\"height: 1em; vertical-align: middle;\"> <a href=\"https://www.youtube.com/channel/UCovCte2I3loteQE_kRsfQcw\">YouTube</a></li>\n <li>Book Private Lessons → <span style=\"color: orange\">@</span> <a href=\"https://sotastica.com/reservar\">sotastica</a></li>\n</ul>",
"_____no_output_____"
]
],
[
[
"# Define a Variable\n\n> Asign an `object` (numbers, text) to a `variable`.\n\n\n\n# The Registry (_aka The Environment_)\n\n> Place where Python goes to **recognise what we type**.\n\n\n\n# Use of Functions\n\n## Predefined Functions in Python (_Built-in_ Functions)\n\n> https://docs.python.org/3/library/functions.html\n\n\n\n## Discipline to Search Solutions in Google\n\n> Apply the following steps when **looking for solutions in Google**:\n>\n> 1. **Necesity**: How to load an Excel in Python?\n> 2. **Search in Google**: by keywords\n> - `load excel python`\n> - ~~how to load excel in python~~\n> 3. **Solution**: What's the `function()` that loads an Excel in Python?\n> - A Function to Programming is what the Atom to Phisics.\n> - Every time you want to do something in programming\n> - **You will need a `function()`** to make it\n> - Theferore, you must **detect parenthesis `()`**\n> - Out of all the words that you see in a website\n> - Because they indicate the presence of a `function()`.\n\n## External Functions\n\n> Download [this Excel](https://github.com/sotastica/data/raw/main/internet_usage_spain.xlsx).\n> Apply the above discipline and make it happen 🚀\n> I want to see the table, c'mon 👇\n\n\n\n## The Elements of Programming\n\n> - `Library`: where the code of functions are stored.\n> - `Function`: execute several lines of code with one `word()`.\n> - `Parameter`: to **configure** the function's behaviour.\n> - `Object`: **data structure** to store information.\n\n\n\n## Code Syntax\n\n**What happens inside the computer when we run the code?**\n\n> In which order Python reads the line of code?\n> - From left to right.\n> - From up to down.\n> Which elements are being used in the previous line of code?\n\n\n\n## Functions inside Objects\n\n> - The `dog` makes `guau()`: `dog.guau()`\n> - The `cat` makes `miau()`: `cat.miau()`\n> - What could a `DataFrame` make? `object.` + `[tab key]`\n\n\n\n## Conclusion | Types of Functions\n\n> 1. Buit-in (Predefined) Functions\n> 2. External Functions from Libraries\n> 3. Functions within Objects\n\n# Accessing `Objects`\n\n> Objects are **data structures** that store information. \n> Which **syntax** do we use to access the information?\n\n## Dot Notation `.`\n\n\n\n## Square Brackets `[]`\n\n\n\n# Filter & Masking\n\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
]
] |
e7ad999f6b9dc7d0b9732b63231180d2807c5fd2 | 5,508 | ipynb | Jupyter Notebook | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis | 58eda66a2b77d17f8443a286af4a7090111b072c | [
"MIT"
] | 10 | 2020-05-24T12:09:54.000Z | 2021-03-03T10:14:52.000Z | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis | 58eda66a2b77d17f8443a286af4a7090111b072c | [
"MIT"
] | 6 | 2020-05-24T13:14:09.000Z | 2022-03-12T00:53:24.000Z | src/bayes/practice/mean/two/independent/medical_checkup.ipynb | shigeodayo/ex_design_analysis | 58eda66a2b77d17f8443a286af4a7090111b072c | [
"MIT"
] | 1 | 2020-05-26T05:42:52.000Z | 2020-05-26T05:42:52.000Z | 25.036364 | 228 | 0.514887 | [
[
[
"# Medical Checkup Problem",
"_____no_output_____"
]
],
[
[
"# Enable the commands below when running this program on Google Colab.\n# !pip install arviz==0.7\n# !pip install pymc3==3.8\n# !pip install Theano==1.0.4\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport pymc3 as pm\n\nplt.style.use('seaborn-darkgrid')\nnp.set_printoptions(precision=3)\npd.set_option('display.precision', 3)",
"_____no_output_____"
],
[
"EXPERIMENT_GROUP = [56, 55, 55, 62, 54, 63, 47, 58, 56, 56, 57, 52, 53, 50, 50, 57, 57, 55, 60, 65, 53, 43, 60, 51, 52, 60, 54, 49, 56, 54, 55, 57, 53, 58, 54, 57, 60, 57, 53, 61, 60, 58, 56, 52, 62, 52, 66, 63, 54, 50]\nCONTROL_GROUP = [33, 37, 59, 41, 42, 61, 46, 25, 32, 35, 55, 44, 45, 41, 33, 61, 46, 16, 48, 34, 27, 37, 28, 31, 32, 20, 50, 42, 26, 55, 45, 36, 51, 51, 50, 48, 47, 39, 36, 35, 32, 38, 25, 66, 54, 27, 35, 34, 49, 39]",
"_____no_output_____"
],
[
"# Data vsualization\nplt.boxplot([EXPERIMENT_GROUP, CONTROL_GROUP], labels=['EXPERIMENT GROUP', 'CONTROL GROUP'])\nplt.ylabel('Biomarker')\nplt.show()",
"_____no_output_____"
],
[
"# Summary\ndata = pd.DataFrame([EXPERIMENT_GROUP, CONTROL_GROUP], index=['Experiment', 'Control']).transpose()\n# display(data)\ndata.describe()",
"_____no_output_____"
]
],
[
[
"## Bayesian analysis",
"_____no_output_____"
]
],
[
[
"with pm.Model() as model:\n # Prior distribution\n mu = pm.Uniform('mu', 0, 100, shape=2)\n sigma = pm.Uniform('sigma', 0, 50)\n\n # Likelihood\n y_pred = pm.Normal('y_pred', mu=mu, sd=sigma, observed=data.values)\n\n # Difference of mean\n delta_mu = pm.Deterministic('mu1 - mu2', mu[0] - mu[1])\n\n trace = pm.sample(21000, chains=5)",
"_____no_output_____"
],
[
"chain = trace[1000:]\npm.traceplot(chain)\nplt.show()",
"_____no_output_____"
],
[
"pm.summary(chain)",
"_____no_output_____"
]
],
[
[
"### RQ1: 第1群の平均値が第2群の平均値より高い確率",
"_____no_output_____"
]
],
[
[
"print('p(mu1 - mu2 > 0) = {:.3f}'.format((chain['mu'][:,0] - chain['mu'][:,1] > 0).mean()))\n# 「罹患群の平均値が健常群の平均値より大きい」という研究仮説が正しい確率は100%",
"_____no_output_____"
]
],
[
[
"### RQ2: 第1群と第2群の平均値の差の点推定、平均値の差の区間推定",
"_____no_output_____"
]
],
[
[
"print('Point estimation (difference of mean): {:.3f}'.format(chain['mu1 - mu2'].mean()))\n# 平均値差に関するEAP推定値\nhpd_0025 = np.quantile(chain['mu1 - mu2'], 0.025)\nhpd_0975 = np.quantile(chain['mu1 - mu2'], 0.975)\nprint('Credible Interval (95%): ({:.3f}, {:.3f})'.format(hpd_0025, hpd_0975))\n# 平均値差は95%の確率で上記の区間に入る",
"_____no_output_____"
]
],
[
[
"### RQ3: 平均値の差の片側区間推定の下限・上限",
"_____no_output_____"
]
],
[
[
"hpd_005 = np.quantile(chain['mu1 - mu2'], 0.05)\nhpd_0950 = np.quantile(chain['mu1 - mu2'], 0.95)\nprint('At most (95%): {:.3f}'.format(hpd_0950)) # 95%の確信で高々これだけの差がある\nprint('At least (95%): {:.3f}'.format(hpd_005)) # 95%の確信で少なくともこれだけの差がある",
"_____no_output_____"
]
],
[
[
"### RQ4: 平均値の差が基準点cより大きい確率",
"_____no_output_____"
]
],
[
[
"print('p(mu1 - mu2 > 10) = {:.3f}'.format((chain['mu'][:,0] - chain['mu'][:,1] > 10).mean()))\nprint('p(mu1 - mu2 > 12) = {:.3f}'.format((chain['mu'][:,0] - chain['mu'][:,1] > 12).mean()))\nprint('p(mu1 - mu2 > 14) = {:.3f}'.format((chain['mu'][:,0] - chain['mu'][:,1] > 14).mean()))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ada27f2e27b4c4b59e463dd902696a4e0167f2 | 2,509 | ipynb | Jupyter Notebook | 00-check-setup.ipynb | fraunhofer-iais/UoC-ml-school-2019 | e651bc9d6245c2d48229dd8ba18022f3abba25b6 | [
"Apache-2.0"
] | 2 | 2020-06-14T15:01:31.000Z | 2021-03-14T11:16:08.000Z | 00-check-setup.ipynb | fraunhofer-iais/UoC-ml-school-2019 | e651bc9d6245c2d48229dd8ba18022f3abba25b6 | [
"Apache-2.0"
] | null | null | null | 00-check-setup.ipynb | fraunhofer-iais/UoC-ml-school-2019 | e651bc9d6245c2d48229dd8ba18022f3abba25b6 | [
"Apache-2.0"
] | null | null | null | 26.978495 | 237 | 0.586289 | [
[
[
"# Congratulations Already!\n\n- This is a Jupyter Notebook. It is made of executable cells.\n- Some cells have text (in Markdown), some have executable code!\n- Abdullah will be demonstrating how to use it soon, but if he is too boring or unclear, [read through this](https://nbviewer.jupyter.org/github/jupyter/notebook/blob/master/docs/source/examples/Notebook/Notebook%20Basics.ipynb)\n\n---\n# Acquire the `data.zip`\n\n- Somehow, from someone, you will get a `data.zip` file.\n- Unzip it.\n- Copy all the contents to the directory where you have cloned this repository.\n + directory `prepared` to `data/prepared`\n + directory `models` to `data/models`\n- **Once done** copying the directories, run the code cells below. They should not throw any errors.",
"_____no_output_____"
]
],
[
[
"from pathlib import Path",
"_____no_output_____"
],
[
"dir_pickles = Path.cwd().joinpath(\"data/prepared/pickles/20190909-vggish_embedding\")\n\nassert all(\n dir_pickles.joinpath(f'{split_name}.tfrecord').exists() for split_name in ['trn', 'val']\n), 'Missing prepared tfrecord files in `data/prepared`'",
"_____no_output_____"
],
[
"from audioset.vggish_smoke_test import *",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7ada44aa2242c831d21175f78f95553f5e0359e | 409,756 | ipynb | Jupyter Notebook | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set | 426c42da2d9da70f7ecc2c39048f5f8aa6740b46 | [
"MIT"
] | 2 | 2021-08-10T13:38:19.000Z | 2021-09-27T03:06:40.000Z | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set | 426c42da2d9da70f7ecc2c39048f5f8aa6740b46 | [
"MIT"
] | null | null | null | yolo-fastest_inference/inference_one_picture.ipynb | Lebhoryi/keras-YOLOv3-model-set | 426c42da2d9da70f7ecc2c39048f5f8aa6740b46 | [
"MIT"
] | 2 | 2021-12-30T09:03:26.000Z | 2021-12-30T09:03:27.000Z | 619.903177 | 193,724 | 0.943154 | [
[
[
"## inference yolo-fastest model with one image",
"_____no_output_____"
]
],
[
[
"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = \"2\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport cv2\nfrom matplotlib import pyplot as plt\n%matplotlib inline\n\nimport time\nimport colorsys\nimport numpy as np\nfrom pathlib import Path\nimport tensorflow as tf\nfrom tensorflow import keras\n\ntf.__version__",
"_____no_output_____"
],
[
"img_path = \"../example/person.jpg\"\nmodel_path = \"../weights/yolo-fastest.h5\"\nclass_path = \"../configs/voc_classes.txt\"\ntflite_path = \"../weights/yolo-fastest.tflite\"\n\n# 预选框\nanchors = [[26, 48], [67, 84], [72, 175], [189, 126], [137, 236], [265, 259]]\nanchors = np.array(anchors)\nnum_classes = 20\nmodel_image_size = (320, 320)\nconf_threshold, elim_grid_sense = 0.5, False\nclasses_path = \"../configs/voc_classes.txt\"",
"_____no_output_____"
],
[
"img = cv2.imread(img_path)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nimg_shape = img.shape[:-1] # height, width\nprint(img.shape)\nplt.imshow(img)\nplt.show()",
"(424, 640, 3)\n"
]
],
[
[
"## 1. preprocess input data",
"_____no_output_____"
]
],
[
[
"img_resize = cv2.resize(img, model_image_size)\nimg_bn = img_resize / 255\nimg_bn = img_bn.astype(\"float32\")\ninput_data = np.expand_dims(img_bn, axis=0)\ninput_data.shape",
"_____no_output_____"
]
],
[
[
"## 2.1 load keras model",
"_____no_output_____"
]
],
[
[
"# load model\nmodel = keras.models.load_model(model_path, compile=False)\nyolo_output = model.predict(input_data)\n\n# keep large-scale feature map is first\nyolo_output = sorted(yolo_output, key=lambda x:len(x[0]))\nyolo_output[0].shape, yolo_output[1].shape",
"_____no_output_____"
]
],
[
[
"## 2.2 load tflite model",
"_____no_output_____"
]
],
[
[
"class YoloFastest(object):\n def __init__(self, landmark_model_path):\n self.interp_joint = tf.lite.Interpreter(landmark_model_path)\n self.interp_joint.allocate_tensors()\n\n # input & input shape\n self.in_idx_joint = self.interp_joint.get_input_details()[0]['index']\n # [b, h, w, c]: [1, 320, 320, 3]\n self.input_shape = self.interp_joint.get_input_details()[0]['shape']\n\n # output\n self.out_idx = self.interp_joint.get_output_details()[0]['index']\n self.out_idx2 = self.interp_joint.get_output_details()[1]['index']\n\n\n def predict_joint(self, img_norm):\n \"\"\"inference tflite model\"\"\"\n self.interp_joint.set_tensor(self.in_idx_joint, img_norm.reshape(self.input_shape))\n self.interp_joint.invoke()\n output = self.interp_joint.get_tensor(self.out_idx)\n output2 = self.interp_joint.get_tensor(self.out_idx2)\n return [output, output2]\n\n\n def __call__(self, img):\n yolo_output = self.predict_joint(img)\n return yolo_output",
"_____no_output_____"
],
[
"yolo_fastest = YoloFastest(tflite_path)\nyolo_output = yolo_fastest(input_data)\nyolo_output[1].shape",
"_____no_output_____"
]
],
[
[
"## 3. yolo decode",
"_____no_output_____"
]
],
[
[
"def yolo_decode(prediction, anchors, num_classes, input_dims, scale_x_y=None, use_softmax=False):\n '''Decode final layer features to bounding box parameters.'''\n num_anchors = len(anchors) # anchors *3\n grid_size = prediction.shape[1:3] # 10*10 grids in a image\n\n # shape: (10*10*3, 25); (20*20*3, 25)\n prediction = np.reshape(prediction,\n (grid_size[0] * grid_size[1] * num_anchors, num_classes + 5))\n\n # generate x_y_offset grid map\n x_y_offset = [[[j, i]] * num_anchors for i in range(grid_size[0]) for j in range(grid_size[0])]\n # shape: (10*10*3, 2)\n x_y_offset = np.array(x_y_offset).reshape(grid_size[0] * grid_size[1] * num_anchors , 2)\n# print(f\"x_y_offset shape: {x_y_offset.shape}\")\n\n # sigmoid: expit(x) = 1 / (1 + exp(-x))\n x_y_tmp = 1 / (1 + np.exp(-prediction[..., :2]))\n # shape: (300, 2)\n box_xy = (x_y_tmp + x_y_offset) / np.array(grid_size)[::-1]\n\n # Log space transform of the height and width\n # anchors = np.array(anchors.tolist()*(grid_size[0] * grid_size[1]))\n anchors_expand = np.tile(anchors, (grid_size[0]*grid_size[1], 1))\n # shape: (300, 2)\n box_wh = (np.exp(prediction[..., 2:4]) * anchors_expand) / np.array(input_dims)[::-1]\n\n # sigmoid function; objectness score\n # shape: (300, 1)\n objectness = 1 / (1 + np.exp(-prediction[..., 4]))\n objectness = np.expand_dims(objectness, axis=-1)\n\n # sigmoid function\n # shape: (300, 20)\n if use_softmax:\n class_scores = np.exp(prediction[..., 5:]) / np.sum(np.exp(prediction[..., 5:]))\n else:\n class_scores = 1 / (1 + np.exp(-prediction[..., 5:]))\n\n return np.concatenate([box_xy, box_wh, objectness, class_scores], axis=-1)",
"_____no_output_____"
],
[
"def yolo3_decode(predictions, anchors, num_classes, input_dims, elim_grid_sense=False):\n \"\"\"\n YOLOv3 Head to process predictions from YOLOv3 models\n\n :param num_classes: Total number of classes\n :param anchors: YOLO style anchor list for bounding box assignment\n :param input_dims: Input dimensions of the image\n :param predictions: A list of three tensors with shape (N, 19, 19, 255), (N, 38, 38, 255) and (N, 76, 76, 255)\n :return: A tensor with the shape (N, num_boxes, 85)\n \"\"\"\n # weather right dims of prediction outputs\n assert len(predictions) == len(anchors)//3, 'anchor numbers does not match prediction.'\n\n if len(predictions) == 3: # assume 3 set of predictions is YOLOv3\n anchor_mask = [[6,7,8], [3,4,5], [0,1,2]]\n scale_x_y = [1.05, 1.1, 1.2] if elim_grid_sense else [None, None, None]\n elif len(predictions) == 2: # 2 set of predictions is YOLOv3-tiny or yolo-fastest\n anchor_mask = [[3,4,5], [0,1,2]]\n scale_x_y = [1.05, 1.05] if elim_grid_sense else [None, None]\n else:\n raise ValueError('Unsupported prediction length: {}'.format(len(predictions)))\n\n results = []\n for i, prediction in enumerate(predictions):\n results.append(yolo_decode(prediction, anchors[anchor_mask[i]], num_classes, input_dims, \n scale_x_y=scale_x_y[i], use_softmax=False))\n\n return np.concatenate(results, axis=0)\n\npredictions_bn = yolo3_decode(yolo_output, anchors, num_classes, model_image_size, elim_grid_sense)\npredictions_bn.shape",
"_____no_output_____"
]
],
[
[
"## 4. Post-processing output",
"_____no_output_____"
]
],
[
[
"def nms_boxes(boxes, classes, scores, iou_threshold, confidence=0.1):\n # center_xy, box_wh\n x = boxes[:, 0]\n y = boxes[:, 1]\n w = boxes[:, 2]\n h = boxes[:, 3]\n xmin, ymin = x - w/2, y - h/2\n xmax, ymax = x + w/2, y + h/2\n\n order = np.argsort(scores)[::-1]\n all_areas = w * h\n \n keep_index = [] # valid index\n \n while order.size > 0:\n keep_index.append(order[0]) # 永远保留置信度最高的索引\n # 最大置信度的左上角坐标分别与剩余所有的框的左上角坐标进行比较,分别保存较大值\n inter_xmin = np.maximum(xmin[order[0]], xmin[order[1:]])\n inter_ymin = np.maximum(ymin[order[0]], ymin[order[1:]])\n inter_xmax = np.minimum(xmax[order[0]], xmax[order[1:]])\n inter_ymax = np.minimum(ymax[order[0]], ymax[order[1:]])\n\n # 当前类所有框的面积\n # x1=3,x2=5,习惯上计算x方向长度就是x=3、4、5这三个像素,即5-3+1=3,\n # 而不是5-3=2,所以需要加1\n inter_w = np.maximum(0., inter_xmax - inter_xmin + 1)\n inter_h = np.maximum(0., inter_ymax - inter_ymin + 1)\n inter = inter_w * inter_h\n\n #计算重叠度IOU:重叠面积/(面积1+面积2-重叠面积)\n iou = inter / (all_areas[order[0]] + all_areas[order[1:]] - inter)\n\n # 计算iou的时候, 并没有计算第一个数, 所以索引对应的是order[1:]之后的, 所以需要加1\n indexs = np.where(iou <= iou_threshold)[0]\n order = order[indexs+1]\n\n keep_boxes = boxes[keep_index]\n keep_classes = classes[keep_index]\n keep_scores = scores[keep_index]\n \n return keep_boxes, keep_classes, keep_scores",
"_____no_output_____"
],
[
"def yolo_handle_predictions(predictions, image_shape, confidence=0.1, iou_threshold=0.4, use_cluster_nms=False, use_wbf=False):\n boxes = predictions[..., :4]\n box_confidences = np.expand_dims(predictions[..., 4], -1)\n box_class_probs = predictions[..., 5:]\n\n # filter boxes with confidence threshold\n box_scores = box_confidences * box_class_probs\n box_classes = np.argmax(box_scores, axis=-1) # max probability index(class)\n box_class_scores = np.max(box_scores, axis=-1) # max scores\n pos = np.where(box_class_scores >= confidence)\n\n boxes = boxes[pos]\n classes = box_classes[pos]\n scores = box_class_scores[pos]\n \n # rescale predicition boxes back to original image shap\n image_shape = image_shape[::-1] # width, height\n boxes[..., :2] *= image_shape # xy\n boxes[..., 2:] *= image_shape # wh\n \n n_boxes, n_classes, n_scores = nms_boxes(boxes, classes, scores, iou_threshold, confidence=confidence)\n\n if n_boxes.size:\n classes = n_classes.astype('int32')\n return n_boxes, classes, n_scores\n else:\n return [], [], []\n \nconfidence, iou_threshold = 0.5, 0.4\nboxes, classes, scores = yolo_handle_predictions(predictions_bn, img_shape,\n confidence=confidence,\n iou_threshold=iou_threshold)\nboxes, classes, scores",
"_____no_output_____"
],
[
"def yolo_adjust_boxes(boxes, img_shape):\n '''\n change box format from (x,y,w,h) top left coordinate to\n (xmin,ymin,xmax,ymax) format\n '''\n if boxes is None or len(boxes) == 0:\n return []\n\n image_shape = np.array(img_shape, dtype='float32')\n height, width = image_shape\n\n adjusted_boxes = []\n for box in boxes:\n x, y, w, h = box\n\n xmin = x - w/2\n ymin = y - h/2\n xmax = x + w/2\n ymax = y + h/2\n\n ymin = max(0, np.floor(ymin + 0.5).astype('int32'))\n xmin = max(0, np.floor(xmin + 0.5).astype('int32'))\n ymax = min(height, np.floor(ymax + 0.5).astype('int32'))\n xmax = min(width, np.floor(xmax + 0.5).astype('int32'))\n adjusted_boxes.append([xmin,ymin,xmax,ymax])\n\n return np.array(adjusted_boxes,dtype=np.int32)\n\nboxes_real = yolo_adjust_boxes(boxes, img_shape)\nboxes_real",
"_____no_output_____"
]
],
[
[
"## 5. draw predictions in image",
"_____no_output_____"
]
],
[
[
"def get_classes(classes_path):\n '''loads the classes'''\n with open(classes_path) as f:\n class_names = f.read().split()\n return class_names\n\n\ndef get_colors(class_names):\n # Generate colors for drawing bounding boxes.\n hsv_tuples = [(x / len(class_names), 1., 1.)\n for x in range(len(class_names))]\n colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n colors = list(\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n colors))\n np.random.seed(10101) # Fixed seed for consistent colors across runs.\n np.random.shuffle(colors) # Shuffle colors to decorrelate adjacent classes.\n np.random.seed(None) # Reset seed to default.\n return colors\n\nclass_names = get_classes(classes_path)\ncolors = get_colors(class_names)\nlen(class_names)",
"_____no_output_____"
],
[
"def draw_label(image, text, color, coords):\n font = cv2.FONT_HERSHEY_PLAIN\n font_scale = 1.\n (text_width, text_height) = cv2.getTextSize(text, font, fontScale=font_scale, thickness=1)[0]\n\n padding = 5\n rect_height = text_height + padding * 2\n rect_width = text_width + padding * 2\n\n (x, y) = coords\n\n cv2.rectangle(image, (x, y), (x + rect_width, y - rect_height), color, cv2.FILLED)\n cv2.putText(image, text, (x + padding, y - text_height + padding), font,\n fontScale=font_scale,\n color=(255, 255, 255),\n lineType=cv2.LINE_AA)\n\n return image",
"_____no_output_____"
],
[
"def draw_boxes(image, boxes, classes, scores, class_names, colors, show_score=True):\n if boxes is None or len(boxes) == 0:\n return image\n if classes is None or len(classes) == 0:\n return image\n\n for box, cls, score in zip(boxes, classes, scores):\n xmin, ymin, xmax, ymax = map(int, box)\n\n class_name = class_names[cls]\n if show_score:\n label = '{} {:.2f}'.format(class_name, score)\n else:\n label = '{}'.format(class_name)\n# print(label, (xmin, ymin), (xmax, ymax))\n\n # if no color info, use black(0,0,0)\n if colors == None:\n color = (0,0,0)\n else:\n color = colors[cls]\n cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 1, cv2.LINE_AA)\n image = draw_label(image, label, color, (xmin, ymin))\n\n return image\n\n\nimg_copy = img.copy()\nimage_array = draw_boxes(img_copy, boxes_real, classes, scores, class_names, colors)\nplt.imshow(image_array)\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7adb9ddfb27b58ff22ccc730c903652a886e83f | 55,092 | ipynb | Jupyter Notebook | pandas_for_everyone/1_Introduction.ipynb | o3c9/playgrounds | 1363dca0ece0283b5cb1f5c4e26b7a12cf5badab | [
"MIT"
] | null | null | null | pandas_for_everyone/1_Introduction.ipynb | o3c9/playgrounds | 1363dca0ece0283b5cb1f5c4e26b7a12cf5badab | [
"MIT"
] | 2 | 2021-12-09T01:31:34.000Z | 2022-02-17T20:48:11.000Z | pandas_for_everyone/1_Introduction.ipynb | o3c9/playgrounds | 1363dca0ece0283b5cb1f5c4e26b7a12cf5badab | [
"MIT"
] | null | null | null | 43.516588 | 14,436 | 0.552113 | [
[
[
"## Pandas DataFrame Basics\n\nLoading CSV/TSV data to pandas, then examine the data frame object using `shape`, `columns`, `dtypes` and `info()`.",
"_____no_output_____"
]
],
[
[
"# Data can be downloaded from https://raw.githubusercontent.com/jennybc/gapminder/master/inst/extdata/gapminder.tsv\n\nimport pandas as pd\n\ndf = pd.read_csv(\"gapminder.tsv\", sep=\"\\t\")",
"_____no_output_____"
],
[
"type(df)",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
]
],
[
[
"### Subsetting DataFrame\n\n`loc` uses the index label and `iloc` uses the index number. Don't get confused!",
"_____no_output_____"
]
],
[
[
"df[[\"country\", \"year\", \"pop\"]].head()",
"_____no_output_____"
],
[
"df.loc[0] # using index label",
"_____no_output_____"
],
[
"df.loc[-1] # label \"-1\" doesn't exist",
"_____no_output_____"
],
[
"df.iloc[0] # using row index number",
"_____no_output_____"
],
[
"df.iloc[-1]",
"_____no_output_____"
],
[
"df.loc[:5, [\"country\", \"year\"]]",
"_____no_output_____"
],
[
"df.iloc[:5, [0, 2]]",
"_____no_output_____"
]
],
[
[
"### Summarization\n\n",
"_____no_output_____"
]
],
[
[
"df.groupby(\"year\")[\"lifeExp\"].mean()",
"_____no_output_____"
],
[
"df.groupby(\"year\").mean()",
"_____no_output_____"
],
[
"df_grouped_by = df.groupby([\"year\", \"continent\"])[[\"lifeExp\", \"gdpPercap\"]].mean()",
"_____no_output_____"
],
[
"# To flatten group by, you can use `reset_index`\n\ndf_grouped_by.reset_index()",
"_____no_output_____"
]
],
[
[
"### Basic Plot",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline\n\ndf.groupby(\"year\")[\"lifeExp\"].mean().plot()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7add5d388ea34928d4d53347c2ae79cf5f43f04 | 2,366 | ipynb | Jupyter Notebook | content/04/02c_developing a regex.ipynb | Theo-Faucher/ledatascifi-2022 | d9ac62cf7f0ff27b5a47ed7933e5603a2b4cdf39 | [
"MIT"
] | 1 | 2021-05-28T17:24:51.000Z | 2021-05-28T17:24:51.000Z | content/04/02c_developing a regex.ipynb | Theo-Faucher/ledatascifi-2022 | d9ac62cf7f0ff27b5a47ed7933e5603a2b4cdf39 | [
"MIT"
] | 15 | 2021-02-01T06:23:48.000Z | 2021-04-26T12:40:41.000Z | content/04/02c_developing a regex.ipynb | Theo-Faucher/ledatascifi-2022 | d9ac62cf7f0ff27b5a47ed7933e5603a2b4cdf39 | [
"MIT"
] | 35 | 2021-02-01T17:41:34.000Z | 2021-09-28T00:41:45.000Z | 22.75 | 194 | 0.494505 | [
[
[
"# Developing a regex\n\n1. Think of the PATTERN you want to capture in general terms. \"I want three letter words.\"\n2. Write `pattern = \"\\w{3}\"` and then try it on a few practice strings. **The goal is to BREAK your pattern, find out where it fails, and notice new parts of the pattern you missed.**\n",
"_____no_output_____"
]
],
[
[
"import re\npattern = \"\\w{3}\"\nre.findall(pattern,\"hey there guy\") # whoops, \"the\" isnt a 3 letter word",
"_____no_output_____"
],
[
"# tried but failed: \n# \"(\\w{3}) \" <-- a space\n# \"(\\w{3})\\b\" <-- a word boundary should work! why not?\npattern = r\"(\\w{3})\\b\" # trying that raw string notation thing \nre.findall(pattern,\"hey there guy\") \n# it made the `\\b` work!, but pattern still it is failing...",
"_____no_output_____"
],
[
"pattern = r\"\\b(\\w{3})\\b\" # make sur the word has a boundary before it\nre.findall(pattern,\"hey there guy\") # got it!",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7adeb05ee2caef072f6654a1ce2d9c6bdd4e154 | 19,203 | ipynb | Jupyter Notebook | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals | adc5b8ab29965857cb2cc606e15110269b5fb8e5 | [
"BSD-3-Clause"
] | 1 | 2017-12-30T18:03:29.000Z | 2017-12-30T18:03:29.000Z | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals | adc5b8ab29965857cb2cc606e15110269b5fb8e5 | [
"BSD-3-Clause"
] | null | null | null | Notebooks/Day 2 - Feature Engineering and Supervised Learning/Feature Engineering.ipynb | ahouseholder/machine-learning-for-security-professionals | adc5b8ab29965857cb2cc606e15110269b5fb8e5 | [
"BSD-3-Clause"
] | 1 | 2021-11-03T13:29:50.000Z | 2021-11-03T13:29:50.000Z | 41.745652 | 659 | 0.616883 | [
[
[
"<img src=\"../../img/logo_white_bkg_small.png\" align=\"left\" /> \n# Feature Engineering\nThis worksheet covers concepts covered in the first part of day 2 - Feature Engineering. It should take no more than 30-40 minutes to complete. Please raise your hand if you get stuck. \n\n## Import the Libraries\nFor this exercise, we will be using:\n* Pandas (http://pandas.pydata.org/pandas-docs/stable/)\n* Numpy (https://docs.scipy.org/doc/numpy/reference/)\n* Matplotlib (http://matplotlib.org/api/pyplot_api.html)\n* Scikit-learn (http://scikit-learn.org/stable/documentation.html)\n* YellowBrick (http://www.scikit-yb.org/en/latest/)\n* Seaborn (https://seaborn.pydata.org)",
"_____no_output_____"
]
],
[
[
"# Load Libraries - Make sure to run this cell!\nimport pandas as pd\nimport numpy as np\nimport re\nfrom collections import Counter\nfrom sklearn import feature_extraction, tree, model_selection, metrics\nfrom yellowbrick.features import Rank2D\nfrom yellowbrick.features import RadViz\nfrom yellowbrick.features import ParallelCoordinates\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## Feature Engineering\n\nThis worksheet is a step-by-step guide on how to detect domains that were generated using \"Domain Generation Algorithm\" (DGA). We will walk you through the process of transforming raw domain strings to Machine Learning features and creating a decision tree classifer which you will use to determine whether a given domain is legit or not. Once you have implemented the classifier, the worksheet will walk you through evaluating your model. \n\nOverview 2 main steps:\n\n1. **Feature Engineering** - from raw domain strings to numeric Machine Learning features using DataFrame manipulations\n2. **Machine Learning Classification** - predict whether a domain is legit or not using a Decision Tree Classifier\n\n\n \n\n**DGA - Background**\n\n\"Various families of malware use domain generation\nalgorithms (DGAs) to generate a large number of pseudo-random\ndomain names to connect to a command and control (C2) server.\nIn order to block DGA C2 traffic, security organizations must\nfirst discover the algorithm by reverse engineering malware\nsamples, then generate a list of domains for a given seed. The\ndomains are then either preregistered, sink-holed or published\nin a DNS blacklist. This process is not only tedious, but can\nbe readily circumvented by malware authors. An alternative\napproach to stop malware from using DGAs is to intercept DNS\nqueries on a network and predict whether domains are DGA\ngenerated. Much of the previous work in DGA detection is based\non finding groupings of like domains and using their statistical\nproperties to determine if they are DGA generated. However,\nthese techniques are run over large time windows and cannot be\nused for real-time detection and prevention. In addition, many of\nthese techniques also use contextual information such as passive\nDNS and aggregations of all NXDomains throughout a network.\nSuch requirements are not only costly to integrate, they may not\nbe possible due to real-world constraints of many systems (such\nas endpoint detection). An alternative to these systems is a much\nharder problem: detect DGA generation on a per domain basis\nwith no information except for the domain name. Previous work\nto solve this harder problem exhibits poor performance and many\nof these systems rely heavily on manual creation of features;\na time consuming process that can easily be circumvented by\nmalware authors...\" \n[Citation: Woodbridge et. al 2016: \"Predicting Domain Generation Algorithms with Long Short-Term Memory Networks\"]\n\nA better alternative for real-world deployment would be to use \"featureless deep learning\" - We have a separate notebook where you can see how this can be implemented!( https://www.endgame.com/blog/technical-blog/using-deep-learning-detect-dgas, https://github.com/endgameinc/dga_predict)\n\n**However, let's learn the basics first!!!**\n",
"_____no_output_____"
],
[
"## Worksheet for Part 1 - Feature Engineering",
"_____no_output_____"
]
],
[
[
"## Load data\ndf = pd.read_csv('../../Data/dga_data_small.csv')\ndf.drop(['host', 'subclass'], axis=1, inplace=True)\nprint(df.shape)\ndf.sample(n=5).head() # print a random sample of the DataFrame",
"_____no_output_____"
],
[
"df[df.isDGA == 'legit'].head()",
"_____no_output_____"
],
[
"# Google's 10000 most common english words will be needed to derive a feature called ngrams...\n# therefore we already load them here.\ntop_en_words = pd.read_csv('../../Data/google-10000-english.txt', header=None, names=['words'])\ntop_en_words.sample(n=5).head()\n# Source: https://github.com/first20hours/google-10000-english\nd = top_en_words",
"_____no_output_____"
]
],
[
[
"## Part 1 - Feature Engineering\n\nOption 1 to derive Machine Learning features is to manually hand-craft useful contextual information of the domain string. An alternative approach (not covered in this notebook) is \"Featureless Deep Learning\", where an embedding layer takes care of deriving features - a huge step towards more \"AI\".\n\nPrevious academic research has focused on the following features that are based on contextual information:\n\n**List of features**:\n\n1. Length [\"length\"]\n2. Number of digits [\"digits\"]\n3. Entropy [\"entropy\"] - use ```H_entropy``` function provided \n4. Vowel to consonant ratio [\"vowel-cons\"] - use ```vowel_consonant_ratio``` function provided\n5. N-grams [\"n-grams\"] - use ```ngram``` functions provided\n\n**Tasks**: \nSplit into A and B parts, see below...\n\n\nPlease run the following function cell and then continue reading the next markdown cell with more details on how to derive those features. Have fun!\n\n",
"_____no_output_____"
]
],
[
[
"def H_entropy (x):\n # Calculate Shannon Entropy\n prob = [ float(x.count(c)) / len(x) for c in dict.fromkeys(list(x)) ] \n H = - sum([ p * np.log2(p) for p in prob ]) \n return H\n\ndef vowel_consonant_ratio (x):\n # Calculate vowel to consonant ratio\n x = x.lower()\n vowels_pattern = re.compile('([aeiou])')\n consonants_pattern = re.compile('([b-df-hj-np-tv-z])')\n vowels = re.findall(vowels_pattern, x)\n consonants = re.findall(consonants_pattern, x)\n try:\n ratio = len(vowels) / len(consonants)\n except: # catch zero devision exception \n ratio = 0 \n return ratio",
"_____no_output_____"
]
],
[
[
"### Tasks - A - Feature Engineering\n\nPlease try to derive a new pandas 2D DataFrame with a new column for each of feature. Focus on ```length```, ```digits```, ```entropy``` and ```vowel-cons``` here. Also make sure to encode the ```isDGA``` column as integers. [pandas.Series.str](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.html), [pandas.Series.replace](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html) and [pandas.Series,apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html) can be very helpful to quickly derive those features. Functions you need to apply here are provided in above cell.\n\nThe ```ngram``` is a bit more complicated, see next instruction cell to add this feature...\n",
"_____no_output_____"
]
],
[
[
"# Derive Features\n\n\n# Encode strings of target variable as integers\n\n# Check intermediate 2D pandas DataFrame\ndf.sample(n=5).head()\n",
"_____no_output_____"
]
],
[
[
"### Tasks - B - Feature Engineering\n\nFinally, let's tackle the **ngram** feature. There are multiple steps involved to derive this feature. Here in this notebook, we use an implementation outlined in the this academic paper [Schiavoni 2014: \"Phoenix: DGA-based Botnet Tracking and Intelligence\" - see section: Linguistic Features](http://s2lab.isg.rhul.ac.uk/papers/files/dimva2014.pdf).\n\n\n- **What are ngrams???** Imagine a string like 'facebook', if I were to derive all n-grams for n=2 (aka bi-grams) I would get '['fa', 'ac', 'ce', 'eb', 'bo', 'oo', 'ok']', so you see that you slide with one step from the left and just group 2 characters together each time, a tri-gram for 'facebook' would yielfd '['fac', 'ace', 'ceb', 'ebo', 'boo', 'ook']'. Ngrams have a long history in natural language processing, but are also used a lot for example in detecting malicious executable (raw byte ngrams in this case).\n\nSteps involved:\n\n1. We have the 10000 most common english words (see data file we loaded, we call this DataFrame ```top_en_words``` in this notebook). Now we run the ```ngrams``` functions on a list of all these words. The output here is a list that contains ALL 1-grams, bi-grams and tri-grams of these 10000 most common english words.\n2. We use the ```Counter``` function from collections to derive a dictionary ```d``` that contains the counts of all unique 1-grams, bi-grams and tri-grams.\n3. Our ```ngram_feature``` function will do the core magic. It takes your domain as input, splits it into ngrams (n is a function parameter) and then looks up these ngrams in the english dictionary ```d``` we derived in step 2. Function returns the normalized sum of all ngrams that were contained in the english dictionary. For example, running ```ngram_feature('facebook', d, 2)``` will return 171.28 (this value is just like the one published in the Schiavoni paper).\n4. Finally ```average_ngram_feature``` wraps around ```ngram_feature```. You will use this function as your task is to derive a feature that gives the average of the ngram_feature for n=1,2 and 3. Input to this function should be a simple list with entries calling ```ngram_feature``` with n=1,2 and 3, hence a list of 3 ngram_feature results. \n5. **YOUR TURN: Apply ```average_ngram_feature``` to you domain column in the DataFrame thereby adding ```ngram``` to the df.**\n6. **YOUR TURN: Finally drop the ```domain``` column from your DataFrame**.\n\n\nPlease run the following function cell and then write your code in the following cell.\n",
"_____no_output_____"
]
],
[
[
"# For simplicity let's just copy the needed function in here again\n# Load dictionary of common english words from part 1\nfrom six.moves import cPickle as pickle\nwith open('../../Data/d_common_en_words' + '.pickle', 'rb') as f:\n d = pickle.load(f)\n\ndef H_entropy (x):\n # Calculate Shannon Entropy\n prob = [ float(x.count(c)) / len(x) for c in dict.fromkeys(list(x)) ] \n H = - sum([ p * np.log2(p) for p in prob ]) \n return H\n\ndef vowel_consonant_ratio (x):\n # Calculate vowel to consonant ratio\n x = x.lower()\n vowels_pattern = re.compile('([aeiou])')\n consonants_pattern = re.compile('([b-df-hj-np-tv-z])')\n vowels = re.findall(vowels_pattern, x)\n consonants = re.findall(consonants_pattern, x)\n try:\n ratio = len(vowels) / len(consonants)\n except: # catch zero devision exception \n ratio = 0 \n return ratio\n\n# ngrams: Implementation according to Schiavoni 2014: \"Phoenix: DGA-based Botnet Tracking and Intelligence\"\n# http://s2lab.isg.rhul.ac.uk/papers/files/dimva2014.pdf\n\ndef ngrams(word, n):\n # Extract all ngrams and return a regular Python list\n # Input word: can be a simple string or a list of strings\n # Input n: Can be one integer or a list of integers \n # if you want to extract multipe ngrams and have them all in one list\n \n l_ngrams = []\n if isinstance(word, list):\n for w in word:\n if isinstance(n, list):\n for curr_n in n:\n ngrams = [w[i:i+curr_n] for i in range(0,len(w)-curr_n+1)]\n l_ngrams.extend(ngrams)\n else:\n ngrams = [w[i:i+n] for i in range(0,len(w)-n+1)]\n l_ngrams.extend(ngrams)\n else:\n if isinstance(n, list):\n for curr_n in n:\n ngrams = [word[i:i+curr_n] for i in range(0,len(word)-curr_n+1)]\n l_ngrams.extend(ngrams)\n else:\n ngrams = [word[i:i+n] for i in range(0,len(word)-n+1)]\n l_ngrams.extend(ngrams)\n# print(l_ngrams)\n return l_ngrams\n\ndef ngram_feature(domain, d, n):\n # Input is your domain string or list of domain strings\n # a dictionary object d that contains the count for most common english words\n # finally you n either as int list or simple int defining the ngram length\n \n # Core magic: Looks up domain ngrams in english dictionary ngrams and sums up the \n # respective english dictionary counts for the respective domain ngram\n # sum is normalized\n \n l_ngrams = ngrams(domain, n)\n# print(l_ngrams)\n count_sum=0\n for ngram in l_ngrams:\n if d[ngram]:\n count_sum+=d[ngram]\n try:\n feature = count_sum/(len(domain)-n+1)\n except:\n feature = 0\n return feature\n \ndef average_ngram_feature(l_ngram_feature):\n # input is a list of calls to ngram_feature(domain, d, n)\n # usually you would use various n values, like 1,2,3...\n return sum(l_ngram_feature)/len(l_ngram_feature)",
"_____no_output_____"
],
[
"#Your code here..",
"_____no_output_____"
]
],
[
[
"#### Breakpoint: Load Features and Labels\n\nIf you got stuck in Part 1, please simply load the feature matrix we prepared for you, so you can move on to Part 2 and train a Decision Tree Classifier.",
"_____no_output_____"
]
],
[
[
"df_final = pd.read_csv('../../Data/our_data_dga_features_final_df.csv')\nprint(df_final.isDGA.value_counts())\ndf_final.sample(5)",
"_____no_output_____"
]
],
[
[
"### Visualizing the Results\nAt this point, we've created a dataset which has many features that can be used for classification. Using YellowBrick, your final step is to visualize the features to see which will be of value and which will not. \n\nFirst, let's create a Rank2D visualizer to compute the correlations between all the features. Detailed documentation available here: http://www.scikit-yb.org/en/latest/examples/methods.html#feature-analysis",
"_____no_output_____"
]
],
[
[
"feature_names = ['length','digits','entropy','vowel-cons','ngrams']\nfeatures = df_final[feature_names]\ntarget = df_final.isDGA",
"_____no_output_____"
],
[
"#Your code here...",
"_____no_output_____"
]
],
[
[
"Now let's use a Seaborn pairplot as well. This will really show you which features have clear dividing lines between the classes. Docs are available here: http://seaborn.pydata.org/generated/seaborn.pairplot.html",
"_____no_output_____"
]
],
[
[
"#Your code here... ",
"_____no_output_____"
]
],
[
[
"Finally, let's try making a RadViz of the features. This visualization will help us see whether there is too much noise to make accurate classifications. ",
"_____no_output_____"
]
],
[
[
"#Your code here...",
"_____no_output_____"
]
],
[
[
"## Congrats!\nCongrats! You've now extracted features from the dataset and are ready to begin creating some supervised models!",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7adf7d1350e826176bd806b0e77a6e3deb78527 | 469,713 | ipynb | Jupyter Notebook | ml/pdp_plots.ipynb | jkcm/mesoscale-morphology | 7ee3f97d880878659ba2acb0418b53569b54ccb9 | [
"MIT"
] | null | null | null | ml/pdp_plots.ipynb | jkcm/mesoscale-morphology | 7ee3f97d880878659ba2acb0418b53569b54ccb9 | [
"MIT"
] | null | null | null | ml/pdp_plots.ipynb | jkcm/mesoscale-morphology | 7ee3f97d880878659ba2acb0418b53569b54ccb9 | [
"MIT"
] | null | null | null | 986.792017 | 134,488 | 0.951402 | [
[
[
"# loadings best model\nbest_random_cv = pickle.load(open(r'/home/disk/eos4/jkcm/Data/MEASURES/models/random_CV_search_pca_0.472_8747447530989.pickle', 'rb'))",
"_____no_output_____"
],
[
"import pickle\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.inspection import plot_partial_dependence\n\n%load_ext autoreload\n%autoreload 2\nprint(\"we workin'!\")",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\nwe workin'!\n"
],
[
"labels={0: 'Closed-cellular MCC', 1: 'Clustered cumulus', 2: 'Disorganized MCC',\n 3: 'Open-cellular MCC', 4: 'Solid Stratus', 5: 'Suppressed Cu'}",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(10,10), ncols=8, nrows=6, sharey='row')\n# fig = plt.figure()\n# plt.close(fig)\nshort_labels = {0: 'Closed MCC ', 1: 'Clust. Cu', 2: 'Disorg. MCC',\n 3: 'Open MCC', 4: 'Solid St', 5: 'Supp. Cu'}\n\ncols = ['\"temperature\"\\nPC1', 'PC2\\n\"stability\"', '\"l.s. subs.\"\\nPC3', 'PC4\\n\"windiness\"', '\"moisture\"\\nPC5', 'PC6\\n\"warm adv.\"', \n '\"surface div.\"\\nPC7', 'PC8\\n\"surface pres.\"']\n\nordering = [4, 0, 2, 3, 1, 5]\n\nprobs = {4: 0.1, 0: 0.12, 2: 0.18, 3: 0.03, 1: 0.32, 5: 0.25}\n \nct = 1\nsigs = []\npd_dict = {}\nfor i,cat in enumerate(ordering):\n pdp = pickle.load(open(f'/home/disk/eos4/jkcm/Data/MEASURES/pdp/ver1_pdp_target{cat}.0.pickle', \"rb\" ));\n pd_dict[cat] = pdp\n plt.close(pdp.figure_)\n pdp.plot(ax=ax[i,:])\n ax[i,0].set_ylabel(short_labels[cat])#+'\\n likelihood')\n \n mean_prob = probs[cat]\n for axi in ax[i,:]:\n line_data = axi.get_children()[1].get_ydata()\n sig = np.ptp(line_data)/mean_prob\n sigs.append(sig)\n if sig < 0.5:\n axi.set_facecolor('silver')\n else:\n axi.set_facecolor('lightcoral')\n \n \n \nfor axi in ax[:,1:].flatten():\n axi.set_ylabel('')\n\n# for i, lab in short_labels.items():\n# ax[i,0]\n \nfor j, mode in enumerate(cols):\n ax[0,j].set_title(mode)\n \nfig.suptitle('archetypal eyeball floater morphologies', y=0.08)\n# fig.show()\nfig.subplots_adjust(hspace=0.24)\nptps = []\n\nfig.savefig('/home/disk/p/jkcm/plots/dissertation/pdplots_1d.png', bbox_inches='tight')",
"_____no_output_____"
],
[
"wal",
"_____no_output_____"
],
[
"#load classified data\ndf = pickle.load(open(f'/home/disk/eos4/jkcm/Data/MEASURES/models/rf_ver1_classified_data.pickle', \"rb\" ))\nvars_to_use = ['MERRA2_sfc_div', 'MERRA2_div_700', 'MERRA2_SST', 'MERRA2_EIS', 'MERRA2_LTS', 'MERRA2_RH_700', \n 'MERRA2_WSPD_10M', 'MERRA2_PS', 'MERRA2_TQV', 'MERRA2_T2M', 'MERRA2_M', 'MERRA2_T_adv', 'MERRA2_T_700'] # these are the variables to train on\nvar_labels = [ 'Sfc. div.', '700mb div', 'SST', 'EIS', 'LTS', '700mb RH', \n '10m wspd.', 'Sfc. pres.', 'Col. Q$_V$', '2m T', 'MCAO idx', 'T$_{adv}$', '700mb T']\nvar_units = [ 's$^{-1}$', 's$^{-1}$', 'K', 'K', 'K', '%', \n 'm s$^{-1}$', 'Pa', 'kg m$^{-3}$', 'K', 'K', 'K s$^{-1}$', 'K']\n\n# var_dict = \n\n\nordering = [4, 0, 2, 3, 1, 5]\n\n\n\nshort_labels = {0: 'Closed MCC ', 1: 'Clust. Cu', 2: 'Disorg. MCC',\n 3: 'Open MCC', 4: 'Solid St', 5: 'Supp. Cu'}\ndf.columns",
"_____no_output_____"
],
[
"varlist = ['MERRA2_EIS', 'MERRA2_LTS']\nvarlist = vars_to_use\nvarlist = ['MERRA2_EIS', 'MERRA2_sfc_div', 'MERRA2_RH_700', 'MERRA2_TQV']\n\nfig, ax = plt.subplots(figsize=(20,10), nrows=len(short_labels), ncols=len(varlist), sharey='row', sharex='col')\nfor i, var in enumerate(varlist):\n df['quantile'], bins = pd.qcut(df[var], 20, retbins=True)\n df_grouped = df.groupby(['quantile'])\n bins_mids = (bins[1:]+bins[:-1])/2\n deciles, d_bins = pd.qcut(df[var], 10, retbins=True)\n dec_bin_mids = (d_bins[1:]+d_bins[:-1])/2\n# for j, (cloud_name, cloud_type) in enumerate(short_labels.items()):\n for j, cloud_name in enumerate(ordering):\n cloud_type = short_labels[cloud_name]\n probs = []\n for dec in sorted(df_grouped.groups.keys()):\n subs = df_grouped.get_group(dec)\n a = sum(subs.rf_pred==cloud_name)/len(subs)\n probs.append(a)\n ax[j, i].plot(bins_mids[1:-1], probs[1:-1])\n if i == 0:\n ax[j,i].set_ylabel(cloud_type)\n if j == 0:\n ax[j,i].set_title(var_labels[i])\n if j == len(short_labels)-1:\n ax[j,i].set_xlabel(f'{var_labels[i]} \\n({var_units[i]})') \n# ylims = ax[j,i].get_ylim()\n ax[j,i].set_xlim((bins_mids[1], bins_mids[-2]))\n for b in d_bins:\n ax[j,i].axvline(b, ymax=0.1, c='k')",
"_____no_output_____"
],
[
"pca_data = pickle.load(open('/home/disk/eos4/jkcm/Data/MEASURES/classified_data/PCA_data.pickle', \"rb\" ))\ndf_pca = pd.DataFrame(pca_data['x_train'], columns = [f'PC{i+1}' for i in range(8)])\ndf_pca['cat'] = pca_data['y_train']\ncols = ['\"temperature\"', '\"stability\"', '\"l.s. subs.\"', '\"windiness\"', '\"moisture\"', '\"warm adv.\"', \n '\"surface div.\"', '\"surface pres.\"']",
"_____no_output_____"
],
[
"varlist = ['MERRA2_EIS', 'MERRA2_LTS']\nvarlist = vars_to_use\nvarlist = [f'PC{i+1}' for i in range(8)]\n\nfig, ax = plt.subplots(figsize=(20,10), nrows=len(short_labels), ncols=len(varlist), sharey='row', sharex='col')\nfor i, var in enumerate(varlist):\n df_pca['quantile'], bins = pd.qcut(df_pca[var], 20, retbins=True)\n df_grouped = df_pca.groupby(['quantile'])\n bins_mids = (bins[1:]+bins[:-1])/2\n deciles, d_bins = pd.qcut(df_pca[var], 10, retbins=True)\n dec_bin_mids = (d_bins[1:]+d_bins[:-1])/2\n# for j, (cloud_name, cloud_type) in enumerate(short_labels.items()):\n for j, cloud_name in enumerate(ordering):\n cloud_type = short_labels[cloud_name]\n probs = []\n for dec in sorted(df_grouped.groups.keys()):\n subs = df_grouped.get_group(dec)\n a = sum(subs.cat==cloud_name)/len(subs)\n probs.append(a)\n ax[j, i].plot(bins_mids[1:-1], probs[1:-1])\n if i == 0:\n ax[j,i].set_ylabel(cloud_type)\n if j == 0:\n ax[j,i].set_title(cols[i])\n if j == len(short_labels)-1:\n ax[j,i].set_xlabel(f'{cols[i]}') \n# ylims = ax[j,i].get_ylim()\n ax[j,i].set_xlim((bins_mids[1], bins_mids[-2]))\n for b in d_bins:\n ax[j,i].axvline(b, ymax=0.1, c='k')",
"_____no_output_____"
],
[
"ptps = []\nfor axi in ax.flatten():\n line_data = axi.get_children()[1].get_ydata()\n pdp = np.ptp(line_data)/np.max(line_data)\n ptps.append(pdp)\n# if np.ptp(line_data) < 0.1:\n# ax.set_facecolor('grey')",
"_____no_output_____"
],
[
"plt.hist(ptps, cumulative=True, density=True)",
"_____no_output_____"
],
[
"\nmodel_save_dict = pickle.load(open(f'/home/disk/eos4/jkcm/Data/MEASURES/models/simple_rf_pca_model.pickle', \"rb\" )) \n\nrf = model_save_dict['model']",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(10,20), ncols=3, nrows=6)#, sharey='col', sharex='col')\nshort_labels = {0: 'Closed MCC ', 1: 'Clust. Cu', 2: 'Disorg. MCC',\n 3: 'Open MCC', 4: 'Solid St', 5: 'Supp. Cu'}\n\ncols = ['\"temperature\"', '\"stability\"', '\"l.s. subsidence\"', '\"windiness\"', '\"moisture\"', '\"warm adv.\"', \n '\"surface divergence\"', '\"surface pressure\"', '', '', '', '', '']\nnew_names = [f'PC{i+1} ({c})' for i,c in enumerate(cols)]\nordering = [4, 0, 2, 3, 1, 5]\nct = 1\nfor i,cat in enumerate(ordering):\n try:\n pdp = pickle.load(open(f'/home/disk/eos4/jkcm/Data/MEASURES/pdp/ver1_pdp_target_2d_{cat}.pickle', \"rb\" ));\n except IOError as e:\n print(e)\n continue\n pdp.feature_names = new_names\n plt.close(pdp.figure_)\n pdp.plot(ax=ax[i,:])\n oldlab = ax[i,0].get_ylabel()\n# ax[i,0].set_ylabel(short_labels[cat]+'\\n\\n\\n' + oldlab)\n ax[i,0].set_title(short_labels[cat])\n \n \n \n \n \nfig.subplots_adjust(hspace=0.4, wspace=0.4)\nfor axi in ax[:,1:].flatten():\n fig.delaxes(axi)\n\n\nax[3,0].set_position(ax[0,1].get_position())\nax[4,0].set_position(ax[1,1].get_position())\nax[5,0].set_position(ax[2,1].get_position())\n\n# ax2.set_position(pos1)\n\n\n\n \n# ax.\n \nfig.savefig('/home/disk/p/jkcm/plots/dissertation/pdplots_2d.png', bbox_inches='tight')\n\n# for axi in ax[:,1:].flatten():\n# axi.set_ylabel('')\n\n# for i, lab in short_labels.items():\n# ax[i,0]\n \n# for j, mode in enumerate(cols):\n# ax[0,j].set_title(mode)\n# fig.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7ae01f0e2e7d1cd05a7fcd1bc64debbc249fe03 | 10,488 | ipynb | Jupyter Notebook | docs/quickstart.ipynb | provingground-curly/scarlet | 60a66510a535d763975a40a0b8cb35df017b92d3 | [
"MIT"
] | null | null | null | docs/quickstart.ipynb | provingground-curly/scarlet | 60a66510a535d763975a40a0b8cb35df017b92d3 | [
"MIT"
] | null | null | null | docs/quickstart.ipynb | provingground-curly/scarlet | 60a66510a535d763975a40a0b8cb35df017b92d3 | [
"MIT"
] | null | null | null | 30.488372 | 333 | 0.584096 | [
[
[
"# Quick Start Guide\nThis tutorial shows how to quickly get started using scarlet to reduce a sample image cube.\nIn order to run this tutorial you will need either `astropy` (http://www.astropy.org) or `sep` (https://github.com/kbarbary/sep) installed to open/create the source catalog and `matplotlib` (https://matplotlib.org) to display the images",
"_____no_output_____"
]
],
[
[
"# Import Packages and setup\nimport logging\n\nimport numpy as np\n\nimport scarlet\nimport scarlet.display\n\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\n# use a better colormap and don't interpolate the pixels\nmatplotlib.rc('image', cmap='inferno')\nmatplotlib.rc('image', interpolation='none')",
"_____no_output_____"
]
],
[
[
"## Load and display the sample data",
"_____no_output_____"
],
[
"### Load the sample data and source catalog\nLoading the source catalog requires astropy. If you don't have astropy installed you'll have to do the source detection yourself. For example, using `sep`:\n\n```python3\nimport sep\ndef makeCatalog(img):\n detect = img.mean(axis=0) # simple average for detection\n bkg = sep.Background(detect)\n catalog = sep.extract(detect, 1.5, err=bkg.globalrms)\n bg_rms = np.array([sep.Background(band).globalrms for band in img])\n return catalog, bg_rms\ncatalog, bg_rms = makeCatalog(images)\n```\n\nOtherwise you can just load the \"true\" catalog:",
"_____no_output_____"
]
],
[
[
"# Load the sample images\ndata = np.load(\"../data/test_sim/data.npz\")\nimages = data[\"images\"]\nfilters = data[\"filters\"]\n\nfrom astropy.table import Table as ApTable\ncatalog = ApTable.read(\"../data/test_sim/true_catalog.fits\")\nbg_rms = np.array([20]*len(images))",
"_____no_output_____"
]
],
[
[
"### Display a raw image cube\nThis is an example of how to display an RGB image from an image cube of multiband data. In this case the image uses a $sin^{-1}$ function to normalize the flux and maps i,r,g (filters 3,2,1) $\\rightarrow$ RGB.",
"_____no_output_____"
]
],
[
[
"# Use Asinh scaling for the images\nnorm = scarlet.display.Asinh(img=images, Q=20)\n# Map i,r,g -> RGB\nfilter_indices = [3,2,1]\n# Convert the image to an RGB image\nimg_rgb = scarlet.display.img_to_rgb(images, filter_indices=filter_indices, norm=norm)\nplt.imshow(img_rgb)\nfor src in catalog:\n plt.plot(src[\"x\"], src[\"y\"], \"rx\", mew=2)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Initialize the sources\nEach source is a list of fundamental `scarlet.Component` instances and must be based on `scarlet.Source` or a derived class, in this case `ExtendedSource`, which enforces that the source is monotonic and symmetric.",
"_____no_output_____"
]
],
[
[
"sources = [scarlet.ExtendedSource((src['y'],src['x']), images, bg_rms) for src in catalog]",
"_____no_output_____"
]
],
[
[
".. warning::\n\n Note in the code above that coordinates in *scarlet* use the traditional C/numpy notation (y,x) as opposed to the mathematical (x,y) ordering. A common error when first starting out with *scarlet* is to mix the order of x and y in your catalog or source list, which can have adverse affects on the results of the deblender.",
"_____no_output_____"
]
],
[
[
"## Create and fit the model\nThe `scarlet.Blend` class represent the sources as a tree and has the machinery to fit all of the sources to the given images. In this example the code is set to run for a maximum of 200 iterations, but will end early if the likelihood and all of the constraints converge.",
"_____no_output_____"
]
],
[
[
"blend = scarlet.Blend(sources)\nblend.set_data(images, bg_rms=bg_rms)\nblend.fit(200)\nprint(\"scarlet ran for {0} iterations\".format(blend.it))",
"_____no_output_____"
]
],
[
[
"## View the results",
"_____no_output_____"
],
[
"### View the full model\nFirst we load the model for the entire blend and its residual. Then we display the model using the same $sinh^{-1}$ stretch as the full image and a linear stretch for the residual.",
"_____no_output_____"
]
],
[
[
"# Load the model and calculate the residual\nmodel = blend.get_model()\nresidual = images-model\n# Create RGB images\nmodel_rgb = scarlet.display.img_to_rgb(model, filter_indices=filter_indices, norm=norm)\nresidual_rgb = scarlet.display.img_to_rgb(residual, filter_indices=filter_indices)\n\n# Show the data, model, and residual\nfig = plt.figure(figsize=(15,5))\nax = [fig.add_subplot(1,3,n+1) for n in range(3)]\nax[0].imshow(img_rgb)\nax[0].set_title(\"Data\")\nax[1].imshow(model_rgb)\nax[1].set_title(\"Model\")\nax[2].imshow(residual_rgb)\nax[2].set_title(\"Residual\")\n\nfor k,component in enumerate(blend.components):\n y,x = component.center\n ax[0].text(x, y, k, color=\"b\")\n ax[1].text(x, y, k, color=\"b\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"### View the source models\nIt can also be useful to view the model for each source. For each source we extract the portion of the image contained in the sources bounding box, the true simulated source flux, and the model of the source, scaled so that all of the images have roughly the same pixel scale.",
"_____no_output_____"
]
],
[
[
"def get_true_image(m, catalog, filters):\n \"\"\"Create the true multiband image for a source\n \"\"\"\n img = np.array([catalog[m][\"intensity_\"+f] for f in filters])\n return img\n\n# We can only show the true values if the input catalog has the true intensity data for the sources\n# in other words, if you used SEP to build your catalog you do not have the true data.\nif \"intensity_\"+filters[0] in catalog.colnames:\n has_truth = True\n axes = 3\nelse:\n has_truth = False\n axes = 2\n\nfor k,src in enumerate(blend.components):\n # Get the model for a single source\n model = blend.get_model(k=k)[src.bb]\n _rgb = scarlet.display.img_to_rgb(model, filter_indices=filter_indices, norm=norm)\n # Get the patch from the original image\n _img = images[src.bb]\n _img_rgb = scarlet.display.img_to_rgb(_img, filter_indices=filter_indices, norm=norm)\n # Set the figure size\n ratio = src.shape[2]/src.shape[1]\n fig_height = 3*src.shape[1]/20\n fig_width = max(3*fig_height*ratio,2)\n fig = plt.figure(figsize=(fig_width, fig_height))\n # Generate and show the figure\n ax = [fig.add_subplot(1,3,n+1) for n in range(3)]\n ax[0].imshow(_img_rgb)\n ax[0].set_title(\"Data\")\n ax[1].imshow(_rgb)\n ax[1].set_title(\"model {0}\".format(k))\n if has_truth:\n # Get the true image for the same source\n truth = get_true_image(k, catalog, filters)[src.bb]\n true_rgb = scarlet.display.img_to_rgb(truth, filter_indices=filter_indices, norm=norm)\n ax[2].imshow(true_rgb)\n ax[2].set_title(\"truth\")\n plt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"raw",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"raw"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ae298f46931913f37dcc1b69989aef2f8eaee3 | 253,390 | ipynb | Jupyter Notebook | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io | eafffcaa2a61bbb06b201a85fdf88188101d7b57 | [
"Apache-2.0"
] | null | null | null | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io | eafffcaa2a61bbb06b201a85fdf88188101d7b57 | [
"Apache-2.0"
] | null | null | null | _notebooks/2021-07-01-windows-store-eda-2.ipynb | sanchit-agarwal/sanchit-agarwal.github.io | eafffcaa2a61bbb06b201a85fdf88188101d7b57 | [
"Apache-2.0"
] | null | null | null | 268.137566 | 68,284 | 0.920056 | [
[
[
"# \"Windows Store dataset Exploatory Data Analysis II\"\n> \"Exploatory Data Analysis (EDA) on The Windows Store dataset from Kaggle: https://www.kaggle.com/vishnuvarthanrao/windows-store Part 2\"\n- toc: false\n- badges: false\n",
"_____no_output_____"
],
[
"Hi everyone, this is part 2 of the series \"Window Store Explonatory Data Analysis (EDA)\". If you haven't checked out part 2 already then please use this link to access the article:\n\nhttps://www.kaggle.com/sanchitagarwal/windows-store-eda-1",
"_____no_output_____"
],
[
"A quick look at the data revealed that the majority of the data (97%) are free apps (price = 0), so I decided to stratify the dataset into categories \"Free\" and \"Paid\" based on the value of the PRICE column; The intutition being that the behviour of the population intenting to purchase an application and the resultant characterstics will be significantly different than those who aren't. Nevertheless, later on, I shall seek correlation between both the stratas.\n\nLets start with the \"Paid\" category first.\n\n<b>P.S: SQL related code have been commented and replaced with Kaggle appropriate code.</b>",
"_____no_output_____"
]
],
[
[
"#import pymssql\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import dates\n%matplotlib inline\nimport seaborn as sns",
"_____no_output_____"
],
[
"\"\"\"server = \"You seriously thought\"\nuser = \"that I'm stupid enough to\"\npassword = \"expose my credentials to the public ? \"\n\nconnection = pymssql.connect(server, user, password, \"master\")\n\nwith connection:\n with connection.cursor(as_dict = True) as cursor:\n sql = \"SELECT * FROM windows_store WHERE price != 0.0\"\n cursor.execute(sql)\n result = cursor.fetchall()\n #print(result)\n paid_apps_df = pd.DataFrame(result)\"\"\"\n\napps_df = pd.read_csv(\"../input/windows-store/msft.csv\")\napps_df[\"Price\"].fillna(value = \"Free\", inplace = True)\n\npaid_apps_df = apps_df.loc[apps_df.Price != \"Free\"]\npaid_apps_df['Date'] = pd.to_datetime(paid_apps_df['Date']) \n\npaid_apps_df['Price'] = paid_apps_df['Price'].replace(\"[\\₹,\\,]\",\"\",regex=True).astype(float)\npaid_apps_df.head()",
"/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:19: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:21: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n"
]
],
[
[
"<b>P.S</b>: Its important to convert the DATE column into pandas datetime datatype to avoid any conflicts when doing datetime analysis through Pandas.",
"_____no_output_____"
]
],
[
[
"paid_apps_df.describe()",
"_____no_output_____"
]
],
[
[
"In the RATING column we can see that the average rating for paid apps is a mere 2.47, a horrondous result considering that one would expect a better user experience on apps which have been paid for. \n\nIn the PRICE column, the range is pretty large (5449 - 54 = 5395), and so is the standard deviation, meaning there is a lot of variance in the prices. Interesting thing to know is that both the 50th & 75th percentile equals 269, meaning that 269 is the most commonly used to price apps. This can be verified by finding the mode of the PRICE column. \n",
"_____no_output_____"
]
],
[
[
"paid_apps_df[\"Price\"].mode()",
"_____no_output_____"
]
],
[
[
"Voila!!",
"_____no_output_____"
]
],
[
[
"paid_apps_df.Category.describe()",
"_____no_output_____"
],
[
"paid_apps_df.Category.unique()",
"_____no_output_____"
]
],
[
[
"\"Book\" being the top category in paid apps confirms books to be the most popular product a person is willing to pay for, though abeit by a very small margin (56/158 = 0.3544 * 100 = 35.44%). Also to note that there are 8 records with NULL entry for the CATEGORY column.\n\nNow lets do some plotting!",
"_____no_output_____"
]
],
[
[
"df_plot_count = paid_apps_df[[\"Rating\", \"Date\"]].groupby(pd.Grouper(key=\"Date\", freq='Y')).count()\n#print(df_plot_count)\nplt.figure(figsize=(15,6))\nplt.title(\"Paid Apps launched per year\")\n\nplot = sns.lineplot(data=df_plot_count)\nplot.xaxis.set_major_formatter(dates.DateFormatter(\"%Y\"))\nplot.set(ylabel = \"Count\")\nplot.legend(labels=[\"Count\"])\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"This graph shows that the number of paid apps launched is increasing almost exponentially. This tells us the increase in popularity of Windows app ecosystem. \n\nI am interested in knowing if there is any seasonality trend amongest PRICE, RATING and NO_OF_PEOPLE.",
"_____no_output_____"
]
],
[
[
"df_plot = paid_apps_df[[\"Date\", \"Rating\", 'No of people Rated', \"Price\"]]\ndf_plot.set_index('Date', inplace=True)\n\ndf_plot = df_plot.groupby(pd.Grouper(freq='M')).mean().dropna(how=\"all\")\n\nplt.figure(figsize=(15,6))\n\nplt.title(\"PRICE Seasonality analysis\")\nplot = sns.lineplot(data= df_plot[\"Price\"])\nplot.set(ylabel = \"Price\")\nplot.xaxis.set_minor_locator(dates.MonthLocator())\nplot.xaxis.set_major_formatter(dates.DateFormatter(\"%Y\"))\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"From 2011 to 2013, the increase was almost linear but later on there are sudden surges followed by a decrease, like a sine wave.\n\nAlso to note that for years 2013, 2015, 2017, 2018 and 2020, surge in price are detected in the first months (Jan, Feb, March). What could cause this pattern to reemerge ? Something to ponder about.\n\nLastly, from 2020 onwards, the prices are in the low territory compared to previous year's. I believe this can be attributed to the change in pricing strategy (where apps are free to download with additional content available to purchase) and/or increase in piracy. ",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15,6))\n\nplt.title(\"RATING seasonality analysis\")\nplot = sns.lineplot(data= df_plot[[\"Rating\"]])\nplot.xaxis.set_minor_locator(dates.MonthLocator())\nplot.set(ylabel = \"Rating\")\nplot.xaxis.set_major_formatter(dates.DateFormatter(\"%Y\"))\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"We can see that there is an increase in volatility as we move further down the x-axis. This could be attributed to the increase in number of apps published through the years as explored in the first graph.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15,6))\n\nplt.title(\"No of people seasonality analysis\")\nplot = sns.lineplot(data= df_plot[[\"No of people Rated\"]])\nplot.xaxis.set_minor_locator(dates.MonthLocator())\nplot.xaxis.set_major_formatter(dates.DateFormatter(\"%Y\"))\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"This graph and the previous graph are almost similar (which makes perfect sense since the set of people who rated the apps is subset of set of people who have downloaded the app, i.e not all people who downloaded the app may have rated the app but those who have rated the app have definitely downloaded it!).\n\nNothing new to explore here.\n\nNow lets find any correlation between PRICE and RATING.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15,6))\n\nplt.title(\"Correlation between Price & Rating\")\n\nplot = sns.scatterplot(y=paid_apps_df[\"Price\"], x=paid_apps_df[\"Rating\"])\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"For the 4 rating, the range of price is the largest, while the perfect 5 rating has been achieved by relatively inexpensive apps. This affirms the fact that the mere price tag of an application is not the sole indication of the user experience. This is further stated by the 3 rating achieved by the humongously priced \"5449\" app. ",
"_____no_output_____"
],
[
"Thats it for now. In the next article I will continue with my analysis of the \"Free apps\" strata of the dataset. Please don't hesitate to share your feedbacks. Thanks!",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e7ae442846c7f0fd51190df2408f5afc0991462e | 13,969 | ipynb | Jupyter Notebook | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io | b6e0571ee9dc353f405d0772aa94b92f28c60710 | [
"MIT"
] | null | null | null | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io | b6e0571ee9dc353f405d0772aa94b92f28c60710 | [
"MIT"
] | null | null | null | src/public/ps/ps4.ipynb | jonahweissman/uvatoc.github.io | b6e0571ee9dc353f405d0772aa94b92f28c60710 | [
"MIT"
] | null | null | null | 31.320628 | 597 | 0.533825 | [
[
[
"# **cs3102 Fall 2019**\n\n## Problem Set 4 (Jupyter Part): Computing Models and Universality\n\n \n**Purpose** \nThe goal of this part of Problem Set 4 is to develop your understanding of universality by building the EVAL function discussed in Class 9. For better readability, we will be using some simple data structures (tuples and lists) throughout this notebook. To make this as formal as the algorithm discussed in class, you should \"flatten\" each of these datastructures (convert them into a bitstring by just listing all of the contained bits in order).\n\nNote: you should not use any loops in this notebook.",
"_____no_output_____"
],
[
"## NAND and Procedures\n\nWe begin by giving you NAND. The asserts ensure that we only work with 0s and 1s",
"_____no_output_____"
]
],
[
[
"def checkBoolean(b):\n \"\"\"Tests a value is a valid Boolean. We use the int values 0 and 1 to represent \n Boolean False and True. (Technically, checkBoolean should not be allowed in a \n \"straightline\" program since it is a function call, but we are just using it to\n check assertions.)\n \"\"\"\n assert b == 0 or b == 1\n \ndef NAND(a,b):\n checkBoolean(a)\n checkBoolean(b)\n return 1 - (a * b)",
"_____no_output_____"
],
[
"assert(NAND(0, 0) == 1)\nassert(NAND(0, 1) == 1)\nassert(NAND(1, 0) == 1)\nassert(NAND(1, 1) == 0)",
"_____no_output_____"
]
],
[
[
"Next, we provide several of the boolean functions we've discussed so far. You're welcome to use any of these throughout this notebook.",
"_____no_output_____"
]
],
[
[
"def NOT(a):\n checkBoolean(a)\n return NAND(a, a)\n\ndef AND(a, b):\n checkBoolean(a)\n checkBoolean(b)\n temp = NAND(a, b)\n return NAND(temp, temp)\n\ndef OR(a, b):\n checkBoolean(a)\n checkBoolean(b)\n temp1 = NAND(a,a)\n temp2 = NAND(b,b)\n return NAND(temp1, temp2)\n\ndef XOR(a, b):\n checkBoolean(a)\n checkBoolean(b)\n or_ab = OR(a, b)\n and_ab = AND(a, b)\n not_and_ab = NOT(and_ab)\n return AND(or_ab, not_and_ab)\n\ndef IF(cond,a,b):\n checkBoolean(cond)\n checkBoolean(a)\n checkBoolean(b)\n \n not_cond = NAND(cond, cond)\n temp1 = NAND(cond, a)\n temp2 = NAND(not_cond, b)\n return NAND(temp1, temp2)\n\ndef LOOKUP1(x0, x1, i0):\n [checkBoolean(x) for x in (x0, x1, i0)] # not strightline code, but just checking\n return IF(i0, x1, x0)\n\ndef LOOKUP2(x0,x1,x2,x3,i0,i1):\n [checkBoolean(x) for x in (x0, x1, x2, x3, i0, i1)] # just checking\n first_half = LOOKUP1(x0, x1, i1)\n second_half = LOOKUP1(x2, x3, i1)\n return IF(i0, second_half, first_half)\n\ndef LOOKUP3(x0,x1,x2,x3,x4,x5,x6,x7,i0,i1,i2):\n [checkBoolean(x) for x in (x0, x1, x2, x3, x4, x5, x6, x7, i0, i1, i2)] # just checking\n first_half = LOOKUP2(x0, x1, x2, x3, i1, i2)\n second_half = LOOKUP2(x4, x5, x6, x7, i1, i2)\n return IF(i0, second_half, first_half)",
"_____no_output_____"
]
],
[
[
"## Representing a program as bits\n\nNext we represent the `IF` program as a list of triples. For readability, we'll write this as integers, and convert to bits.\n\nThis first cell provides two functions for converting triples of integers into triples of bitstrings. You should understand why they exist.",
"_____no_output_____"
]
],
[
[
"def int2bits(number, num_bits):\n binary = tuple()\n for i in range(num_bits):\n bit = number % 2\n number = number // 2\n binary = tuple([bit]) + binary\n return binary\n\ndef prog2bits(prog, num_bits):\n bits_prog = []\n for triple in prog:\n bits0 = int2bits(triple[0], num_bits)\n bits1 = int2bits(triple[1], num_bits)\n bits2 = int2bits(triple[2], num_bits)\n triple_bits = (bits0,bits1,bits2)\n bits_prog.append(triple_bits)\n return bits_prog",
"_____no_output_____"
]
],
[
[
"Now we give `IF` as a list of triples. It is first given as a list of triples of integers, then converted into a list of triples of 3-bit strings.\n\nNote that this program has 3 inputs, 1 output, 7 variables (including those 3 inputs and 1 output), and 4 lines of code.",
"_____no_output_____"
]
],
[
[
"if_program = [(3,0,0),(4,0,1),(5,3,2),(6,4,5)]\n\nif_program = prog2bits(if_program, 3)\n\nprint(\"The IF program represented as triples of bitstrings:\")\nprint(if_program)",
"The IF program represented as triples of bitstrings:\n[((0, 1, 1), (0, 0, 0), (0, 0, 0)), ((1, 0, 0), (0, 0, 0), (0, 0, 1)), ((1, 0, 1), (0, 1, 1), (0, 1, 0)), ((1, 1, 0), (1, 0, 0), (1, 0, 1))]\n"
]
],
[
[
"For the remainder of this notebook we will build and use the `EVAL_3_7_4_1` function for NAND programs with 3 input bits, 7 internal variables, 4 lines, and 1 output bit. As mentioned in Class 9, to do EVAL we will have a table we called `T` that will contain the value of all the variables throughout our evaluation (row `i` of `T` will contain the value of variable `i`), note that the length of `T` should therefore be equal to the number of variables in the program (in this case 7). To find the value of a variable, we mentioned the function `GET`, which was very similar to lookup. \n\n**Problem J1.** Implement the function `GET_7` below, which will index into the table `T` of 7 rows (since the programs we're evaluating will have 7 variables). You may use `LOOKUP`.",
"_____no_output_____"
]
],
[
[
"def GET_7(T, i):\n assert(len(T) == 7) # not straightline, just checking\n assert(len(i) == 3) # not straightline, just checking\n # gives the value of the variable indexed by the length 3 bitstring from a 6-bit table\n \n #TODO: Replace the body of this function to implement GET_7 correctly\n \n return 0\n\nT = (0,0,0,1,0,0,0)\ni = (0,1,1)\nassert(GET_7(T,i) == 1)\nprint(\"Jolly good!\")\n \nT = (1,1,1,1,0,1,1)\ni = (1,0,0)\nassert(GET_7(T,i) == 0)\nprint(\"Cheerio!\")",
"Jolly good!\nCheerio!\n"
]
],
[
[
"We use `GET` to retrieve one element from the table `T`. We will use `UPDATE` to change one of the elements from table `T`. Before we can implement `UPDATE`, we will want to implement an `EQUAL_3` function. This will determine whether two given 3-bit numbers are equal\n\n**Problem J2.** Implement the function `EQUAL_3` below, which will return 1 if two given 3-bit numbers are the same, and 0 otherwise.",
"_____no_output_____"
]
],
[
[
"def EQUAL_3(i, j):\n assert(len(i) == len(j) == 3)\n #TODO: Replace the body of this function to implement EQUAL_3 correctly\n\n return 0\n\nassert(EQUAL_3((0,0,0),(0,0,0)))\nassert(EQUAL_3((0,0,1),(0,0,1)))\nassert(EQUAL_3((1,0,1),(1,0,1)))\nassert(not EQUAL_3((1,1,1),(0,0,0)))\nassert(not EQUAL_3((1,1,0),(0,0,0)))\nprint(\"Huzzah!\")\n ",
"Huzzah!\n"
]
],
[
[
"**Problem J3.** Implement the function `UPDATE_7` below, which will change the given index (given by the triple of bits `i`) of the 7-row table `T` to become the bit `b`. You will likely need `EQUAL_3` and `IF` to do this.",
"_____no_output_____"
]
],
[
[
"def UPDATE_7(T, b, i):\n assert(len(T) == 7)\n \n #TODO: Replace the body of this function to implement UPDATE_7 correctly\n\n t0 = 0\n t1 = 0\n t2 = 0\n t3 = 0\n t4 = 0\n t5 = 0\n t6 = 0\n return (t0,t1,t2,t3,t4,t5,t6)\n\n\n\ndef pseudo_update_7(T, b, i):\n # This update works by manipulating indices directly. It is meant to show you what your update should return.\n index = i[2] + 2*i[1] + 4*i[0]\n return T[:index] + tuple([b]) + T[index+1:]\n\nT = (0,0,0,1,0,0,0)\ni= (0,1,1)\nassert(pseudo_update_7(T, 0, i) == UPDATE_7(T, 0, i))\nprint(\"GRRRRRREAT!!\")\nT = (1,1,1,1,0,1,1)\ni = (1,0,0)\nassert(pseudo_update_7(T, 1, i) == UPDATE_7(T, 1, i))\nprint(\"Fabulous\")\nT = (1,1,1,1,1,1,0)\ni = (1,1,0)\nassert(pseudo_update_7(T, 1, i) == UPDATE_7(T, 1, i))\nprint(\"Correct!\")\nT = (1,0,0,0,0,0,0)\ni = (0,0,0)\nassert(pseudo_update_7(T, 0, i) == UPDATE_7(T, 0, i))\nprint(\"You got it!\")",
"GRRRRRREAT!!\nFabulous\nCorrect!\nYou got it!\n"
]
],
[
[
"We finally have enough to implement our `EVAL_3_7_4_1` function!\n\n**Problem J4.** Implement `EVAL_3_7_4_1`.",
"_____no_output_____"
]
],
[
[
"def EVAL_3_7_4_1(program, in0, in1, in2):\n assert(len(program) == 4)\n T = (0,0,0,0,0,0,0)\n # TODO: fill in the body of this function.\n return T[6]\n\n\n\ncond,a,b = 0,1,0 \nassert(EVAL_3_7_4_1(if_program, cond, a, b) == IF(cond,a,b))\nprint(\"Gucci!\")\n\ncond,a,b = 1,1,0 \nassert(EVAL_3_7_4_1(if_program, cond, a, b) == IF(cond,a,b))\nprint(\"Sweet!\")\n\ncond,a,b = 0,0,1 \nassert(EVAL_3_7_4_1(if_program, cond, a, b) == IF(cond,a,b))\nprint(\"Cool Beans!\")\n\ncond,a,b = 1,0,1 \nassert(EVAL_3_7_4_1(if_program, cond, a, b) == IF(cond,a,b))\nprint(\"You Rock!\")",
"_____no_output_____"
]
],
[
[
"If we were to slightly modify our procedure for converting programs into a list of triples, we can use `EVAL_3_7_4_1` to evaluate any program that uses no more than 3 inputs, 7 variables, 4 lines, and 1 output. \n\n**Problem J5.** Write `OR` as a list of triples so that we can evaluate it using `EVAL_3_7_4_1` above. Note that `OR` requires fewer inputs, variables, and lines of code than `IF` does. You'll need to do something about that. You may use the `prog2bits` function we provided above.",
"_____no_output_____"
]
],
[
[
"or_program = [] # TODO: fill this in\n\na,b = 0,0\nassert(EVAL_3_7_4_1(or_program, a, b, 0) == OR(a,b))\na,b = 0,1\nassert(EVAL_3_7_4_1(or_program, a, b, 0) == OR(a,b))\na,b = 1,0\nassert(EVAL_3_7_4_1(or_program, a, b, 0) == OR(a,b))\na,b = 1,1\nassert(EVAL_3_7_4_1(or_program, a, b, 0) == OR(a,b))\n\nprint(\"You did it!!\")",
"you did it!!\n"
]
],
[
[
"### End of Jupyter Notebook for Problem Set 4\n\nYou should submit your completed notebook, as well as your PDF file created by modifying `ps4.tex` for PS4 in collab.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7ae4efdd17bdf6382ea927fdc23aceed11975c7 | 19,681 | ipynb | Jupyter Notebook | Signal_Nerveux.ipynb | DillmannFrench/SNT | 179dd7c3fed806aca8685cee1c3ab172bb5c289f | [
"Apache-2.0"
] | 1 | 2021-07-27T06:01:46.000Z | 2021-07-27T06:01:46.000Z | Signal_Nerveux.ipynb | DillmannFrench/SNT | 179dd7c3fed806aca8685cee1c3ab172bb5c289f | [
"Apache-2.0"
] | null | null | null | Signal_Nerveux.ipynb | DillmannFrench/SNT | 179dd7c3fed806aca8685cee1c3ab172bb5c289f | [
"Apache-2.0"
] | null | null | null | 41.608879 | 382 | 0.627102 | [
[
[
"# Programmation d'un objet connecté\n\nCe premier TP a pour objectif de vous familiariser avec l'IOT (Internet of thinks). A travers une recherche où vous allez apprendre à vous servir d'un microcontrôleur, vous allez être capables de réaliser différentes tâches en les automatisant. L'objectif est de vous permettre de prendre des mesures de tension et de courant sur votre montage.\n\nPour bien commencer téléchargez le <a href=\"Signal_Nerveux.ipynb\">notebook</a>.\n\n\n\n## 1) Quelques concepts\n\nLes termes en gras sont à utiliser dans votre notebook pour expliquer ce que vous avez réalisé.\n\nPour programmer un système informatique embarqué, on doit organiser la tâche à accomplir sous forme d'un **code**. C'est une serie d'instructions qui comprends notamment des **fonctions** spécifiques aux entrées et aux sorties. On écrit un **programme** dans un langage qui puisse être interprété par le système.\n\nPour l'execution de celui-ci, il faut le **téléverser** dans le système à travers un **port** de communication. On parle aussi de remplaçage du logiciel pilote dans le microprocesseur pour décrire cette étape d'implémentation.\n\nDans ce cours nous allons voire quelques compétences qui seront utiles pour être autonome avec ce type d'instrument.\n",
"_____no_output_____"
],
[
"## 1.1) Bases de syntaxe\n\nCe paragraphe est important car il corrige beaucoup d'erreurs dans les codes que vous avez rendu pendant les congés de la Toussaint. \n\n#### Fonctions :\n\nUne fonction est un outil de programmation qui permet de transformer des données en entrée (appelées arguments) par des résultats en sortie. Sa syntaxe est très formelle : \n\n~~~python\ndef NOM_DE_LA_FONCTION (argument1):\n # Ecriture d'une série de lignes de commandes qui doivent être alignées les unes par rapport aux autres\n return résultat\n~~~\n\nNotez bien les deux points après la déclaration de l'argument, ainsi que l'indentation (l'espace au début de la ligne où se trouve la commande \n\n~~~python\n return\n~~~\n\nqui renvoie le produit de la transformation que l'on attends de la fonction.\n\nPour cette activité les codes à téléverser sur le microcontrôleur sont écris en `C++`. \n\nEn langage `C++` la syntaxe est légèrement différente de celle de Python. Par exemple la fonction `loop` qui va chercher les informations en permanence au niveau de capteurs (entrées) pour les transformer en actions (sorties) s'écrit comme cela :\n\n~~~cpp\nvoid loop() {\n/* Exécution d'une série de lignes de commandes finies par un caractère \";\" */ \n}\n~~~\n\nOn remarque que la manière de définir les commentaires, indispensables à la bonne compréhension d'une fonction, sont semblables dans chacun des langages. Un caractère dièse '#' pour python et les caractères ' /* ' pour le `C++`. \n\n<font color=\"red\"> Donné à l'examen de SNT commun en 2020 </font>\n\nLe `C++` permet également d'ecrire des fonctions sous la forme suivante :\n\n~~~cpp\n#define ADC_TO_VOLTS(value) ((value / 1023.0) * 4.9)\n~~~\n\ncette fonction ci s'appelle une **macro** elle applique un produit en croix pour transformer la valeur ('value') lue par le programme en une autre. Dans le cas ou cette valeur serait de 1023 (le maximum) cela correspondrait à la tension de 4.9 Volt.\n\n#### Retraits :\n\nUn autre point commun, est l'utilisation de caractères pour cerner le début et la fin d'une fonction. En `C++` on doit vérifier que les accolades que l'on a ouvertes sont bien fermées à la fin de la fonction.\n\nPour Python, c'est la même chose sauf que ces caractères sont... invisibles. Il faut donc signaler par des indentations (un retrait à droite) que l'on entre et l'on sort d'une fonction. \n\n<font color=\"red\">Retenir : le langage Python est plus regardant sur le fait de faire un bon retour à la ligne bien soigné avec des retraits propres et tabulés.</font>\n",
"_____no_output_____"
],
[
"### 1.2) L'interface homme-machine\n\nLes programmes à téléverser sont des codes écris dans un langage de haut niveau (le `C++`) qui doit être *compilé* par un EDI (un **Environnement de Développement Intégré** ). \n\nLa suite d'instructions d'un logiciel de programmation est appelée à être **compilée** ce qui veut dire transformée en un langage adapté à la machine avant d'être téléversée sur la machine elle même en langage machine.\n\nDès que le programme a été compilé de façon satisfaisante, il doit être implémenté sur le microcontrôleur. On appelle cette opération l'étape de *téléversement*. Il est indispensable que la liaison USB entre l'ordinateur ou se trouve l'EDI et la carte soit correctement reliée.",
"_____no_output_____"
],
[
"## 2) Les exemples à tester\n\nPour les exemples suivants vous n'avez qu'a recopier le code et remplacer le code existant (en général ne contenant que les déclarations des deux fonctions *setup* et *loop*) par le code qui est sur ce site.\n\nNous allons commencer par un exemple simple, on va utiliser l'un des programmes de démonstration modifié. \n\n<p><img src=\"https://act-exp-arduino.pagesperso-orange.fr/doigt.jpg\" alt=\"Test d'entrée\" width=350 /></p>\n\nNotre système nerveux est un émetteur de signaux.\n\n### 2.1) Lecture d'un port analogique\n\nL'exemple suivant est extrait de la bibliothèque des exemples de base.\n___\n\n\n\n \n**Procédure**\n\n- sélectionner le code suivant et le recopier tel quel dans la fenêtre de l'IDE.\n\n- vérifier que le débit de communication est bien de 115200 bauds.\n\n- lancer le téléversement à l'aide du bouton \"Play\" (à côté du bouton \"valider\" dans la barre au dessus du code \"sketch\")\n\n- le câble USB est bien connecté, une DEL verte sur la platine à côté d'un instruction \"RX\" clignoter pendant la durée du transfert.\n\n\n\n___\n\n#### Code C++ à copier à partir de la ligne suivante\n\n~~~ cpp\nvoid setup() {\n \n Serial.begin(115200); // 1\n}\n\n// la fonction suivante est destinée à être exécutée en permanence\nvoid loop() {\n \n int sensorValue = analogRead(A0); // 2\n \n Serial.println(sensorValue); // 3\n \n delay(1); // Attends 1 seconde pour des raisons de stabilité\n}\n~~~\n\nCe code peut être téléversé tel quel dans l'IDE Arduino. On ouvre ensuite le moniteur série et on vérifie que le débit de communication est le même. Ces chiffres devraient apparaitre sur celui-ci. Ces chiffres sont compris entre 0 et 1023 et doivent être 'traduis' en volt grâce à une fonction. \nA l'aide d'un fil de cuivre qui est fixé sur le pin noté A0 on capte le signal environnant par effet d'antenne.\nOn peut visualiser ce signal en ouvrant le traceur série de l'interface Arduino.\n\n<p><img src=\"https://act-exp-arduino.pagesperso-orange.fr/tuto1.png\" alt=\"Ajustements\" width=350 /></p>\n\n\nPendant la mise au point (ça ne va pas se téléverser bien du premier coup). Il vous est conseillé de vérifier le protocole de communication entre l'ordinateur et la carte.\n\n<p><img src=\"https://act-exp-arduino.pagesperso-orange.fr/tuto2.png\" alt=\"Visualisation\" width=350 /></p>\n",
"_____no_output_____"
],
[
"#### Question 1) :\n\n<font color=\"green\">Faire le tri des commentaires</font>\n \n \nReplacez les commentaires du code `C++` dans le *bon ordre* en vous servant des flèches haut et bas du notebook",
"_____no_output_____"
],
[
"- A) Commentaire portant sur l'opération à réaliser sur la valeur acquise par le port de communication spécifique :\n\n~~~cpp\n// Renvoyer la valeur qui est lue sur le port de communication série :\n~~~",
"_____no_output_____"
],
[
"- B) Commentaire portant sur la mise en place (setup) d'un protocole de communication :\n\n~~~cpp\n// initialise le port de communication série à 115200 bauds\n~~~",
"_____no_output_____"
],
[
"- C) Commentaire portant sur la déclaration de la borne de communication destinée à recevoir un signal :\n\n~~~cpp\n// Lis la valeur du port analogique qui se trouve au pin 0 :\n~~~",
"_____no_output_____"
],
[
"On retrouve deux sortes de fonctions principales :\n\n~~~ c\nvoid setup() \nvoid loop()\n~~~\n\nLa première définit la vitesse à laquelle les bits vont être envoyés quant à la deuxième elle constitue le coeur du programme puis-ce que c'est elle qui demande la lecture du signal qui se trouve sur le pin 0, grâce à la fonction `analogRead()` et qui imprime dans la console série le résultat grâce à une autre fonction `Serial.println()`.\n\n",
"_____no_output_____"
],
[
"#### Question 2) :\n\n\n<font color=\"green\"> Faire apparaître un signal quand on touche la partie conductrice d'un câble relié à l'entrée analogique A0, est un phénomène physique de quelle nature ? </font>\n\n\nComment explique-t-on qu’il y ai des pics verticaux dans la fenêtre \"moniteur série\" ? \nEn observant votre moniteur, ou celui de quelqu'un qui a fait l'expérience correctement dans la classe, entrez votre réponse dans la cellule suivante : \n\n",
"_____no_output_____"
],
[
"#### Question 3) :\n\n\n<font color=\"green\"> Quand vous posez votre doigt sur le câble que se passe t'il ? </font>\n\nQu’observe-t-on sur le oscillogramme quand l’élève le pince avec les doigts (à mains nues, mouillées, ou avec du gél hydroalcolique dessus) : ",
"_____no_output_____"
],
[
"\n#### Question 4) :\n\n\n\n<font color=\"green\"> Est-ce qu'à partir de ce que vous avez appris pendant la séance expérimentale, vous pouvez formuler une hypothèse sur la variation de l'intensité du signal reçu ? </font>\n\nFormulez une hypothèse qui s’appuie sur le fait que le signal reçu est transmis par votre doigt à l'entrée A0. En utilisant tout ce que vous avez vu en cours sur les signaux en physique, entrez votre réponse dans la cellule suivante : ",
"_____no_output_____"
],
[
"### 2.2) La programmation d'un gradateur de lumière\n\nNous allons nous intéresser à la génération d'une tension variable aux bornes d'une diode.\n\nDans le programme suivant on va voire comment utiliser une des sortie digitales qui se trouve alignées avec le bouton 'reset'. Ces sorties ne doivent **jamais** être reliées de l'une à l'autre sous peine de détruire la platine. \n\n#### Code C++ à copier à partir de la ligne suivante\n\n\n~~~cpp\n/*\n\n Gradateur de lumière\n\n Cet exemple montre comment estomper progressivement la lueur d'une LED sur la broche 9 en utilisant la fonction : \n \n analogWrite()\n \n Description de la fonction.\n\n La fonction analogWrite() utilise PWM (Impulsion modulée en amplitude), donc si vous voulez changer la broche en utilisant une autre carte, assurez-vous d'utiliser une autre broche compatible PWM. \n \n Sur la plupart des Arduino, les broches PWM sont identifiés par un signe \"~\", \n comme ~3, ~5, ~6, ~9, ~10 et ~11.\n \n Dans la carte PlugUino la tilde à disparut mais le pins D10 est PWM on pourra vérifier que les autres sont bien ajustables\n\n Cet exemple appartient au domaine public\n \n http://www.arduino.cc/en/Tutorial/Fade\n*/\n\nint led = 9; // déclaration du pin \"PWM\" qui alimente la DEL\nint brightness = 0; // niveau de luminosité de la DEL\nint fadeAmount = 5; // combiens d'étapes de variation pour la DEL\n\n// la routine de configuration s'exécute une fois lorsque vous appuyez sur reset :\nvoid setup() {\n // déclare que la broche 9 est une sortie :\n pinMode(led, OUTPUT);\n}\n\n// la routine de la boucle se répète encore et encore, pour toujours :\nvoid loop() {\n // régler la luminosité de la broche 9 :\n analogWrite(led, brightness);\n\n // modifier la luminosité pour la prochaine fois à travers la boucle :\n brightness = brightness + fadeAmount;\n\n // inverser le sens du fondu lumineux une fois que l'on est parvenu aux extrémités :\n if (brightness <= 0 || brightness >= 255) {\n fadeAmount = -fadeAmount;\n }\n // attendre 30 millisecondes pour voir l'effet de gradation\n delay(30);\n}\n~~~\n",
"_____no_output_____"
],
[
"Disposer une diode électroluminescente entre la sortie 9 et la masse (bande noire).\nObserver ce qui se passe quand on modifie l'argument de la fonction `delay( )`",
"_____no_output_____"
],
[
"#### Montage dont on pourrait s'inspirer\n\nLe schéma suivant représente les liens entre une platine Arduino et ses points de connection en bordure, ainsi qu'une plaque de prototypage rapide où les élèments éssentiels sont :\n- La DEL à brancher dans le bon sens (partie plate à la masse)\n- La résistance de protection de 220 Ohm en série avec la DEL\n- Les câbles qui sont reliés à la masse\n- Le câble jaune qui correspond à la consigne ",
"_____no_output_____"
],
[
"<p><img src=\"https://act-exp-arduino.pagesperso-orange.fr/diode_simple.png\" alt=\"Premier montage\" width=550 /></p>\nSur ce schéma on retrouve la diode commandée par la sortie 9. Si le programme est correctement téléversé elle doit s'allumer et s'éteindre lentement, on appelle cela la gradation. ",
"_____no_output_____"
],
[
"#### Composants optionnels ?\n\nLe composant électrique schématisé par un petit cylindre noir est appellé un *condensateur*. Si vous le souhaitez je peux vous prêter un condensateur de 0,1 mF pendant l'activité pour votre montage. \n**Notez le bien : ce composant ne semble pas indispensable pour avoir une belle impression visuelle, vous procurant une satisfaisante sentation de gradadion de lumière.** \nLa DEL peut en effet clignoter plus vite que votre œil n'est capable d'envoyer des informations à votre cortex visuel (persistance rétinienne). Donc, apparament, vous n'avez pas besoin faire l'expérience avec condensateur.",
"_____no_output_____"
],
[
"## 3) Conclusion\n\nPendant cette activité vous avez pris une mesure de l'éléctricité au bout de vote doigt\n\n\n## 4) Annexes :\n\n Joker : Un montage semblable en remplaçant la DEL par un résistor. Et en ajoutant un filtre Résistor-Condensateur (son rôle sera expliqué en términale). Cette fois-ci la tension varie bien (au sens physique du terme) entre 0 V et 5 V.",
"_____no_output_____"
],
[
"<p><img src=\"https://act-exp-arduino.pagesperso-orange.fr/points.jpeg\" alt=\"Image sur PlugUino\" /></p>",
"_____no_output_____"
],
[
"- Le point $A$ correspond à l'entrée du signal filtré programmé comme pour le gradateur de lumière. Sa tension `SIG2` est le signal qui correspond à A1\n- Le point $B$ est le point de contact entre la résistance inconnue et la charge de référence, sa tension `SIG1` est le signal qui correspond à A2\n- Le point $C$ est le point de masse `GND` commune représenté comme un triangle hachuré.\n- Le point $D$ est l'entrée du PWM sur le filtre RC. C'est le seul cable qui sorte du brochage des sorties digitales. Ce canal alimente le générateur variable $E_v$\n- La masse est signalée par les pins qui sont en noir et qui sont reliés à ground\n\nOn remarque que sur la photo le filtre à été soudé et fixé sur une platine de test, dans le montage présenté en cours il est constitué de deux composants qui ne sont pas soudés pour les rendre indépendants. Une résistance de $1\\,k\\Omega$ en série avec une capacité de $470\\,\\mu F$ convient pour obtenir une tension lissée dont la valeur maximale est fonction du filtre.\n\n",
"_____no_output_____"
],
[
"La représentation schématique du circuit devient donc la suivante. \n<p><img src=\"https://act-exp-arduino.pagesperso-orange.fr/circuit_4eme3.png\" alt=\"Schéma implémenté\" /></p>",
"_____no_output_____"
],
[
"On retrouve :\n\n- Le point $A$ qui est envoyé sur l'entrée analogique $A_1$\n- Le point $B$ qui est envoyé sur l'entrée analogique $A_2$\n- Le point $C$ qui est la masse\n- Le point $D$ qui correspond à la sortie digitale $D_{10}$",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7ae6065d354f3c7e56b949036ae96cb41e7e0ad | 35,784 | ipynb | Jupyter Notebook | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning | 47f4109eddae94c1ce978d63d7672972762ac815 | [
"Apache-2.0"
] | null | null | null | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning | 47f4109eddae94c1ce978d63d7672972762ac815 | [
"Apache-2.0"
] | 1 | 2019-11-04T11:53:51.000Z | 2019-11-04T11:53:51.000Z | notebooks/04-convolutional-neural-networks/02-deep-convolutional-models/02-residual-networks.ipynb | pedro-abundio-wang/deep-learning-specialization | 47f4109eddae94c1ce978d63d7672972762ac815 | [
"Apache-2.0"
] | null | null | null | 45.584713 | 795 | 0.597949 | [
[
[
"# Residual Networks\n\nWelcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](https://arxiv.org/pdf/1512.03385.pdf), allow you to train much deeper networks than were previously practically feasible.\n\n**In this assignment, you will:**\n- Implement the basic building blocks of ResNets. \n- Put together these building blocks to implement and train a state-of-the-art neural network for image classification. \n\nThis assignment will be done in Keras. \n\nBefore jumping into the problem, let's run the cell below to load the required packages.",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nfrom resnets_utils import *\n\nfrom keras import layers\nfrom keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D\nfrom keras.models import Model, load_model\nfrom keras.preprocessing import image\nfrom keras.utils import layer_utils\nfrom keras.utils.data_utils import get_file\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\nfrom keras.initializers import glorot_uniform\n\nimport pydot\nfrom IPython.display import SVG\n\nimport scipy.misc\n\nfrom matplotlib.pyplot import imshow\n%matplotlib inline\n\nimport keras.backend as K\nK.set_image_data_format('channels_last')\nK.set_learning_phase(1)",
"_____no_output_____"
]
],
[
[
"## 1 - The problem of very deep neural networks\n\nLast week, you built your first convolutional neural network. In recent years, neural networks have become deeper, with state-of-the-art networks going from just a few layers (e.g., AlexNet) to over a hundred layers.\n\nThe main benefit of a very deep network is that it can represent very complex functions. It can also learn features at many different levels of abstraction, from edges (at the lower layers) to very complex features (at the deeper layers). However, using a deeper network doesn't always help. A huge barrier to training them is vanishing gradients: very deep networks often have a gradient signal that goes to zero quickly, thus making gradient descent unbearably slow. More specifically, during gradient descent, as you backprop from the final layer back to the first layer, you are multiplying by the weight matrix on each step, and thus the gradient can decrease exponentially quickly to zero (or, in rare cases, grow exponentially quickly and \"explode\" to take very large values). \n\nDuring training, you might therefore see the magnitude (or norm) of the gradient for the earlier layers descrease to zero very rapidly as training proceeds: ",
"_____no_output_____"
],
[
"<img src=\"images/vanishing_grad_kiank.png\" style=\"width:450px;height:220px;\">\n<caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'> : **Vanishing gradient** <br> The speed of learning decreases very rapidly for the early layers as the network trains </center></caption>\n\nYou are now going to solve this problem by building a Residual Network!",
"_____no_output_____"
],
[
"## 2 - Building a Residual Network\n\nIn ResNets, a \"shortcut\" or a \"skip connection\" allows the gradient to be directly backpropagated to earlier layers: \n\n<img src=\"images/skip_connection_kiank.png\" style=\"width:650px;height:200px;\">\n<caption><center> <u> <font color='purple'> **Figure 2** </u><font color='purple'> : A ResNet block showing a **skip-connection** <br> </center></caption>\n\nThe image on the left shows the \"main path\" through the network. The image on the right adds a shortcut to the main path. By stacking these ResNet blocks on top of each other, you can form a very deep network. \n\nWe also saw in lecture that having ResNet blocks with the shortcut also makes it very easy for one of the blocks to learn an identity function. This means that you can stack on additional ResNet blocks with little risk of harming training set performance. (There is also some evidence that the ease of learning an identity function--even more than skip connections helping with vanishing gradients--accounts for ResNets' remarkable performance.)\n\nTwo main types of blocks are used in a ResNet, depending mainly on whether the input/output dimensions are same or different. You are going to implement both of them. ",
"_____no_output_____"
],
[
"### 2.1 - The identity block\n\nThe identity block is the standard block used in ResNets, and corresponds to the case where the input activation (say $a^{[l]}$) has the same dimension as the output activation (say $a^{[l+2]}$). To flesh out the different steps of what happens in a ResNet's identity block, here is an alternative diagram showing the individual steps:\n\n<img src=\"images/idblock2_kiank.png\" style=\"width:650px;height:150px;\">\n<caption><center> <u> <font color='purple'> **Figure 3** </u><font color='purple'> : **Identity block.** Skip connection \"skips over\" 2 layers. </center></caption>\n\nThe upper path is the \"shortcut path.\" The lower path is the \"main path.\" In this diagram, we have also made explicit the CONV2D and ReLU steps in each layer. To speed up training we have also added a BatchNorm step. Don't worry about this being complicated to implement--you'll see that BatchNorm is just one line of code in Keras! \n\nIn this exercise, you'll actually implement a slightly more powerful version of this identity block, in which the skip connection \"skips over\" 3 hidden layers rather than 2 layers. It looks like this: \n\n<img src=\"images/idblock3_kiank.png\" style=\"width:650px;height:150px;\">\n<caption><center> <u> <font color='purple'> **Figure 4** </u><font color='purple'> : **Identity block.** Skip connection \"skips over\" 3 layers.</center></caption>\n\nHere're the individual steps.\n\nFirst component of main path: \n- The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\" and its name should be `conv_name_base + '2a'`. Use 0 as the seed for the random initialization. \n- The first BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2a'`.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\nSecond component of main path:\n- The second CONV2D has $F_2$ filters of shape $(f,f)$ and a stride of (1,1). Its padding is \"same\" and its name should be `conv_name_base + '2b'`. Use 0 as the seed for the random initialization. \n- The second BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2b'`.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\nThird component of main path:\n- The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\" and its name should be `conv_name_base + '2c'`. Use 0 as the seed for the random initialization. \n- The third BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2c'`. Note that there is no ReLU activation function in this component. \n\nFinal step: \n- The shortcut and the input are added together.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\n**Exercise**: Implement the ResNet identity block. We have implemented the first component of the main path. Please read over this carefully to make sure you understand what it is doing. You should implement the rest. \n- To implement the Conv2D step: [See reference](https://keras.io/layers/convolutional/#conv2d)\n- To implement BatchNorm: [See reference](https://keras.io/layers/normalization/) (axis: Integer, the axis that should be normalized (typically the channels axis))\n- For the activation, use: Activation('relu')(X)\n- To add the value passed forward by the shortcut: [See reference](https://keras.io/layers/merge/#add)",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: identity_block\n\ndef identity_block(X, f, filters, stage, block):\n \"\"\"\n Implementation of the identity block as defined in Figure 3\n \n Arguments:\n X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)\n f -- integer, specifying the shape of the middle CONV's window for the main path\n filters -- python list of integers, defining the number of filters in the CONV layers of the main path\n stage -- integer, used to name the layers, depending on their position in the network\n block -- string/character, used to name the layers, depending on their position in the network\n \n Returns:\n X -- output of the identity block, tensor of shape (n_H, n_W, n_C)\n \"\"\"\n \n # defining name basis\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n \n # Retrieve Filters\n F1, F2, F3 = filters\n \n # Save the input value. You'll need this later to add back to the main path. \n X_shortcut = X\n \n # First component of main path\n X = Conv2D(filters = F1, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(name = bn_name_base + '2a')(X)\n X = Activation('relu')(X)\n \n ### START CODE HERE ###\n \n # Second component of main path (≈3 lines)\n X = Conv2D(filters = F2, kernel_size = (f, f), strides = (1,1), padding = 'same', name = conv_name_base + '2b', kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(name = bn_name_base + '2b')(X)\n X = Activation('relu')(X)\n\n # Third component of main path (≈2 lines)\n X = Conv2D(filters = F3, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2c', kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(name = bn_name_base + '2c')(X)\n\n # Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n \n ### END CODE HERE ###\n \n return X",
"_____no_output_____"
],
[
"tf.reset_default_graph()\nwith tf.Session() as test:\n X = np.random.randn(3, 4, 4, 6)\n np.random.seed(1)\n A_prev = tf.placeholder(\"float\", [3, 4, 4, 6])\n A = identity_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')\n test.run(tf.global_variables_initializer())\n out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})\n print(\"out = \" + str(out[0][1][1][0]))",
"_____no_output_____"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **out**\n </td>\n <td>\n [0.9482299 0. 1.1610144 2.747859 0. 1.36677 ]\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"## 2.2 - The convolutional block\n\nYou've implemented the ResNet identity block. Next, the ResNet \"convolutional block\" is the other type of block. You can use this type of block **when the input and output dimensions don't match up**. The difference with the identity block is that there is a CONV2D layer in the shortcut path: \n\n<img src=\"images/convblock_kiank.png\" style=\"width:650px;height:150px;\">\n<caption><center> <u> <font color='purple'> **Figure 4** </u><font color='purple'> : **Convolutional block** </center></caption>\n\nThe CONV2D layer in the shortcut path is used to resize the input $x$ to a different dimension, so that the dimensions match up in the final addition needed to add the shortcut value back to the main path. (This plays a similar role as the matrix $W_s$ discussed in lecture.) For example, to reduce the activation dimensions's height and width by a factor of 2, you can use a 1x1 convolution with a stride of 2. The CONV2D layer on the shortcut path does not use any non-linear activation function. Its main role is to just apply a (learned) linear function that reduces the dimension of the input, so that the dimensions match up for the later addition step. \n\nThe details of the convolutional block are as follows. \n\nFirst component of main path:\n- The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (s,s). Its padding is \"valid\" and its name should be `conv_name_base + '2a'`. \n- The first BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2a'`.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\nSecond component of main path:\n- The second CONV2D has $F_2$ filters of (f,f) and a stride of (1,1). Its padding is \"same\" and it's name should be `conv_name_base + '2b'`.\n- The second BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2b'`.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\nThird component of main path:\n- The third CONV2D has $F_3$ filters of (1,1) and a stride of (1,1). Its padding is \"valid\" and it's name should be `conv_name_base + '2c'`.\n- The third BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2c'`. Note that there is no ReLU activation function in this component. \n\nShortcut path:\n- The CONV2D has $F_3$ filters of shape (1,1) and a stride of (s,s). Its padding is \"valid\" and its name should be `conv_name_base + '1'`.\n- The BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '1'`. \n\nFinal step: \n- The shortcut and the main path values are added together.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n \n**Exercise**: Implement the convolutional block. We have implemented the first component of the main path; you should implement the rest. As before, always use 0 as the seed for the random initialization, to ensure consistency with our grader.\n- [Conv Hint](https://keras.io/layers/convolutional/#conv2d)\n- [BatchNorm Hint](https://keras.io/layers/normalization/#batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis))\n- For the activation, use: Activation('relu')(X)\n- [Addition Hint](https://keras.io/layers/merge/#add)",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: convolutional_block\n\ndef convolutional_block(X, f, filters, stage, block, s = 2):\n \"\"\"\n Implementation of the convolutional block as defined in Figure 4\n \n Arguments:\n X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)\n f -- integer, specifying the shape of the middle CONV's window for the main path\n filters -- python list of integers, defining the number of filters in the CONV layers of the main path\n stage -- integer, used to name the layers, depending on their position in the network\n block -- string/character, used to name the layers, depending on their position in the network\n s -- Integer, specifying the stride to be used\n \n Returns:\n X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C)\n \"\"\"\n \n # defining name basis\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n \n # Retrieve Filters\n F1, F2, F3 = filters\n \n # Save the input value\n X_shortcut = X\n\n\n ##### MAIN PATH #####\n # First component of main path \n X = Conv2D(F1, (1, 1), strides = (s,s), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(name = bn_name_base + '2a')(X)\n X = Activation('relu')(X)\n \n ### START CODE HERE ###\n\n # Second component of main path (≈3 lines)\n X = Conv2D(F2, (f, f), strides = (1,1), padding = 'same', name = conv_name_base + '2b', kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(name = bn_name_base + '2b')(X)\n X = Activation('relu')(X)\n\n # Third component of main path (≈2 lines)\n X = Conv2D(F3, (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2c', kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(name = bn_name_base + '2c')(X)\n\n ##### SHORTCUT PATH #### (≈2 lines)\n X_shortcut = Conv2D(F3, (1, 1), strides = (s,s), padding = 'valid', name = conv_name_base + '1', kernel_initializer = glorot_uniform(seed=0))(X_shortcut)\n X_shortcut = BatchNormalization(name = bn_name_base + '1')(X_shortcut)\n\n # Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n \n ### END CODE HERE ###\n \n return X",
"_____no_output_____"
],
[
"tf.reset_default_graph()\n\nwith tf.Session() as test:\n np.random.seed(1)\n A_prev = tf.placeholder(\"float\", [3, 4, 4, 6])\n X = np.random.randn(3, 4, 4, 6)\n A = convolutional_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')\n test.run(tf.global_variables_initializer())\n out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})\n print(\"out = \" + str(out[0][1][1][0]))",
"_____no_output_____"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **out**\n </td>\n <td>\n [0.09018461 1.2348977 0.46822017 0.0367176 0. 0.655166 ]\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"## 3 - Building your first ResNet model (50 layers)\n\nYou now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the architecture of this neural network. \"ID BLOCK\" in the diagram stands for \"Identity block,\" and \"ID BLOCK x3\" means you should stack 3 identity blocks together.\n\n<img src=\"images/resnet_kiank.png\" style=\"width:850px;height:150px;\">\n<caption><center> <u> <font color='purple'> **Figure 5** </u><font color='purple'> : **ResNet-50 model** </center></caption>\n\nThe details of this ResNet-50 model are:\n- Zero-padding pads the input with a pad of (3,3)\n- Stage 1:\n - The 2D Convolution has 64 filters of shape (7,7) and uses a stride of (2,2). Its name is \"conv1\".\n - BatchNorm is applied to the channels axis of the input.\n - MaxPooling uses a (3,3) window and a (2,2) stride.\n- Stage 2:\n - The convolutional block uses three set of filters of size [64,64,256], \"f\" is 3, \"s\" is 1 and the block is \"a\".\n - The 2 identity blocks use three set of filters of size [64,64,256], \"f\" is 3 and the blocks are \"b\" and \"c\".\n- Stage 3:\n - The convolutional block uses three set of filters of size [128,128,512], \"f\" is 3, \"s\" is 2 and the block is \"a\".\n - The 3 identity blocks use three set of filters of size [128,128,512], \"f\" is 3 and the blocks are \"b\", \"c\" and \"d\".\n- Stage 4:\n - The convolutional block uses three set of filters of size [256, 256, 1024], \"f\" is 3, \"s\" is 2 and the block is \"a\".\n - The 5 identity blocks use three set of filters of size [256, 256, 1024], \"f\" is 3 and the blocks are \"b\", \"c\", \"d\", \"e\" and \"f\".\n- Stage 5:\n - The convolutional block uses three set of filters of size [512, 512, 2048], \"f\" is 3, \"s\" is 2 and the block is \"a\".\n - The 2 identity blocks use three set of filters of size [256, 256, 2048], \"f\" is 3 and the blocks are \"b\" and \"c\".\n- The 2D Average Pooling uses a window of shape (2,2) and its name is \"avg_pool\".\n- The flatten doesn't have any hyperparameters or name.\n- The Fully Connected (Dense) layer reduces its input to the number of classes using a softmax activation. Its name should be `'fc' + str(classes)`.\n\n**Exercise**: Implement the ResNet with 50 layers described in the figure above. We have implemented Stages 1 and 2. Please implement the rest. (The syntax for implementing Stages 3-5 should be quite similar to that of Stage 2.) Make sure you follow the naming convention in the text above. \n\nYou'll need to use this function: \n- Average pooling [see reference](https://keras.io/layers/pooling/#averagepooling2d)\n\nHere're some other functions we used in the code below:\n- Conv2D: [See reference](https://keras.io/layers/convolutional/#conv2d)\n- BatchNorm: [See reference](https://keras.io/layers/normalization/#batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis))\n- Zero padding: [See reference](https://keras.io/layers/convolutional/#zeropadding2d)\n- Max pooling: [See reference](https://keras.io/layers/pooling/#maxpooling2d)\n- Fully conected layer: [See reference](https://keras.io/layers/core/#dense)\n- Addition: [See reference](https://keras.io/layers/merge/#add)",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: ResNet50\n\ndef ResNet50(input_shape = (64, 64, 3), classes = 6):\n \"\"\"\n Implementation of the popular ResNet50 the following architecture:\n CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3\n -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER\n Arguments:\n input_shape -- shape of the images of the dataset\n classes -- integer, number of classes\n Returns:\n model -- a Model() instance in Keras\n \"\"\"\n \n # Define the input as a tensor with shape input_shape\n X_input = Input(input_shape)\n \n # Zero-Padding\n X = ZeroPadding2D((3, 3))(X_input)\n \n # Stage 1\n X = Conv2D(64, (7, 7), strides = (2, 2), name = 'conv1', kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis = 3, name = 'bn_conv1')(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((3, 3), strides=(2, 2))(X)\n\n # Stage 2\n X = convolutional_block(X, f = 3, filters = [64, 64, 256], stage = 2, block='a', s = 1)\n X = identity_block(X, 3, [64, 64, 256], stage=2, block='b')\n X = identity_block(X, 3, [64, 64, 256], stage=2, block='c')\n\n ### START CODE HERE ###\n\n # Stage 3 (≈4 lines)\n X = convolutional_block(X, f = 3, filters = [128,128,512], stage = 3, block='a', s = 2)\n X = identity_block(X, 3, [128,128,512], stage=3, block='b')\n X = identity_block(X, 3, [128,128,512], stage=3, block='c')\n X = identity_block(X, 3, [128,128,512], stage=3, block='d')\n\n # Stage 4 (≈6 lines)\n X = convolutional_block(X, f = 3, filters = [256, 256, 1024], stage = 4, block='a', s = 2)\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='b')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='c')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='d')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='e')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='f')\n\n # Stage 5 (≈3 lines)\n X = convolutional_block(X, f = 3, filters = [512, 512, 2048], stage = 5, block='a', s = 2)\n X = identity_block(X, 3, [512, 512, 2048], stage=5, block='b')\n X = identity_block(X, 3, [512, 512, 2048], stage=5, block='c')\n\n # AVGPOOL (≈1 line). Use \"X = AveragePooling2D(...)(X)\"\n X = AveragePooling2D(pool_size=(2, 2), name = \"avg_pool\")(X)\n \n ### END CODE HERE ###\n\n # output layer\n X = Flatten()(X)\n X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer = glorot_uniform(seed=0))(X)\n \n \n # Create model\n model = Model(inputs = X_input, outputs = X, name='ResNet50')\n\n return model",
"_____no_output_____"
]
],
[
[
"Run the following code to build the model's graph. If your implementation is not correct you will know it by checking your accuracy when running `model.fit(...)` below.",
"_____no_output_____"
]
],
[
[
"model = ResNet50(input_shape = (64, 64, 3), classes = 6)",
"_____no_output_____"
]
],
[
[
"As seen in the Keras Tutorial Notebook, prior training a model, you need to configure the learning process by compiling the model.",
"_____no_output_____"
]
],
[
[
"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"The model is now ready to be trained. The only thing you need is a dataset.",
"_____no_output_____"
],
[
"Let's load the SIGNS Dataset.\n\n<img src=\"images/signs_data_kiank.png\" style=\"width:450px;height:250px;\">\n<caption><center> <u> <font color='purple'> **Figure 6** </u><font color='purple'> : **SIGNS dataset** </center></caption>\n",
"_____no_output_____"
]
],
[
[
"X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()\n\n# Normalize image vectors\nX_train = X_train_orig/255.\nX_test = X_test_orig/255.\n\n# Convert training and test labels to one hot matrices\nY_train = convert_to_one_hot(Y_train_orig, 6).T\nY_test = convert_to_one_hot(Y_test_orig, 6).T\n\nprint (\"number of training examples = \" + str(X_train.shape[0]))\nprint (\"number of test examples = \" + str(X_test.shape[0]))\nprint (\"X_train shape: \" + str(X_train.shape))\nprint (\"Y_train shape: \" + str(Y_train.shape))\nprint (\"X_test shape: \" + str(X_test.shape))\nprint (\"Y_test shape: \" + str(Y_test.shape))",
"_____no_output_____"
]
],
[
[
"Run the following cell to train your model on 2 epochs with a batch size of 32. On a CPU it should take you around 5min per epoch. ",
"_____no_output_____"
]
],
[
[
"model.fit(X_train, Y_train, epochs = 50, batch_size = 32)",
"_____no_output_____"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n ** Epoch 1/50**\n </td>\n <td>\n loss: between 1 and 5, acc: between 0.2 and 0.5, although your results can be different from ours.\n </td>\n </tr>\n <tr>\n <td>\n ** Epoch 2/50**\n </td>\n <td>\n loss: between 0.5 and 1, acc: between 0.5 and 0.9, you should see your loss decreasing and the accuracy increasing.\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"Let's see how this model (trained on only two epochs) performs on the test set.",
"_____no_output_____"
]
],
[
[
"preds = model.evaluate(X_test, Y_test)\nprint (\"Loss = \" + str(preds[0]))\nprint (\"Test Accuracy = \" + str(preds[1]))\nmodel.save('ResNet50.h5')",
"_____no_output_____"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **Test Accuracy**\n </td>\n <td>\n between 0.9 and 1.0\n </td>\n </tr>\n\n</table>",
"_____no_output_____"
],
[
"For the purpose of this assignment, we've asked you to train the model only for two epochs. You can see that it achieves poor performances. Please go ahead and submit your assignment; to check correctness, the online grader will run your code only for a small number of epochs as well.",
"_____no_output_____"
],
[
"After you have finished this official (graded) part of this assignment, you can also optionally train the ResNet for more iterations, if you want. We get a lot better performance when we train for ~20 epochs, but this will take more than an hour when training on a CPU. \n\nUsing a GPU, we've trained our own ResNet50 model's weights on the SIGNS dataset. You can load and run our trained model on the test set in the cells below. It may take ≈1min to load the model.",
"_____no_output_____"
]
],
[
[
"model = load_model('ResNet50.h5')",
"_____no_output_____"
],
[
"preds = model.evaluate(X_test, Y_test)\nprint (\"Loss = \" + str(preds[0]))\nprint (\"Test Accuracy = \" + str(preds[1]))",
"_____no_output_____"
]
],
[
[
"ResNet50 is a powerful model for image classification when it is trained for an adequate number of iterations. We hope you can use what you've learnt and apply it to your own classification problem to perform state-of-the-art accuracy.\n\nCongratulations on finishing this assignment! You've now implemented a state-of-the-art image classification system! ",
"_____no_output_____"
],
[
"You can also print a summary of your model by running the following code.",
"_____no_output_____"
]
],
[
[
"model.summary()",
"_____no_output_____"
]
],
[
[
"Finally, run the code below to visualize your ResNet50. You can also download a .png picture of your model by going to \"File -> Open...-> model.png\".",
"_____no_output_____"
]
],
[
[
"plot_model(model, to_file='model.png')",
"_____no_output_____"
]
],
[
[
"<font color='blue'>\n**What you should remember:**\n- Very deep \"plain\" networks don't work in practice because they are hard to train due to vanishing gradients. \n- The skip-connections help to address the Vanishing Gradient problem. They also make it easy for a ResNet block to learn an identity function. \n- There are two main type of blocks: The identity block and the convolutional block. \n- Very deep Residual Networks are built by stacking these blocks together.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7ae6e7732941d52ad371fb0cd643078291df27c | 37,786 | ipynb | Jupyter Notebook | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n | 8d4857750f2b5e8e6889acbb4b1e2f98ad7ce34e | [
"Apache-2.0"
] | null | null | null | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n | 8d4857750f2b5e8e6889acbb4b1e2f98ad7ce34e | [
"Apache-2.0"
] | null | null | null | site/zh-cn/guide/data_performance.ipynb | justaverygoodboy/docs-l10n | 8d4857750f2b5e8e6889acbb4b1e2f98ad7ce34e | [
"Apache-2.0"
] | null | null | null | 31.228099 | 281 | 0.477346 | [
[
[
"##### Copyright 2019 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# 使用 tf.data API 获得更高性能",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td><a target=\"_blank\" href=\"https://tensorflow.google.cn/guide/data_performance\" class=\"\"><img src=\"https://tensorflow.google.cn/images/tf_logo_32px.png\" class=\"\">View on TensorFlow.org </a></td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/data_performance.ipynb\" class=\"\"><img src=\"https://tensorflow.google.cn/images/colab_logo_32px.png\" class=\"\">在 Google Colab 中运行</a></td>\n <td><a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/data_performance.ipynb\" class=\"\"><img src=\"https://tensorflow.google.cn/images/GitHub-Mark-32px.png\" class=\"\">在 GitHub 上查看源代码</a></td>\n <td><a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/zh-cn/guide/data_performance.ipynb\" class=\"\"><img src=\"https://tensorflow.google.cn/images/download_logo_32px.png\" class=\"\">下载笔记本</a></td>\n</table>",
"_____no_output_____"
],
[
"## 概述\n\nGPU 和 TPU 能够极大缩短执行单个训练步骤所需的时间。为了达到最佳性能,需要高效的输入流水线,以在当前步骤完成之前为下一步提供数据。`tf.data` API 有助于构建灵活高效的输入流水线。本文档演示了如何使用 `tf.data` API 构建高性能的 TensorFlow 输入流水线。\n\n继续之前,请阅读“[构建 TensorFlow 输入流水线](https://render.githubusercontent.com/view/data.ipynb)”指南,了解如何使用 `tf.data` API。",
"_____no_output_____"
],
[
"## 资源\n\n- [构建 TensorFlow 输入流水线](https://render.githubusercontent.com/view/data.ipynb)\n- `tf.data.Dataset` API\n- [使用 TF Profiler 分析<code>tf.data</code> 性能](https://render.githubusercontent.com/view/data_performance_analysis.md)",
"_____no_output_____"
],
[
"## 设置",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\nimport time",
"_____no_output_____"
]
],
[
[
"在本指南中,您将迭代数据集并衡量性能。制定可重现的性能基准可能很困难,不同的因素会对其产生影响:\n\n- 当前的 CPU 负载\n- 网络流量\n- 缓存等复杂机制\n\n因此,要提供可重现的基准,需要构建人工样本。",
"_____no_output_____"
],
[
"### 数据集\n\n定义一个继承自 `tf.data.Dataset` 的类,称为 `ArtificialDataset`。此数据集:\n\n- 会生成 `num_samples` 样本(默认数量为 3)\n- 会在第一项模拟打开文件之前休眠一段时间\n- 会在生成每一个模拟从文件读取数据的项之前休眠一段时间",
"_____no_output_____"
]
],
[
[
"class ArtificialDataset(tf.data.Dataset):\n def _generator(num_samples):\n # Opening the file\n time.sleep(0.03)\n \n for sample_idx in range(num_samples):\n # Reading data (line, record) from the file\n time.sleep(0.015)\n \n yield (sample_idx,)\n \n def __new__(cls, num_samples=3):\n return tf.data.Dataset.from_generator(\n cls._generator,\n output_types=tf.dtypes.int64,\n output_shapes=(1,),\n args=(num_samples,)\n )",
"_____no_output_____"
]
],
[
[
"此数据集类似 `tf.data.Dataset.range`,在开头和每个样本之间添加了固定延迟。",
"_____no_output_____"
],
[
"### 训练循环\n\n编写一个虚拟的训练循环,以测量迭代数据集所用的时间。训练时间是模拟的。",
"_____no_output_____"
]
],
[
[
"def benchmark(dataset, num_epochs=2):\n start_time = time.perf_counter()\n for epoch_num in range(num_epochs):\n for sample in dataset:\n # Performing a training step\n time.sleep(0.01)\n tf.print(\"Execution time:\", time.perf_counter() - start_time)",
"_____no_output_____"
]
],
[
[
"## 优化性能\n\n为了展示如何优化性能,下面我们将优化 `ArtificialDataset` 的性能。",
"_____no_output_____"
],
[
"### 朴素的方法\n\n先从不使用任何技巧的朴素流水线开始,按原样迭代数据集。",
"_____no_output_____"
]
],
[
[
"benchmark(ArtificialDataset())",
"_____no_output_____"
]
],
[
[
"从后台可以看到执行时间的花费情况:\n\n\n\n可以看到,执行一个训练步骤涉及以下操作:\n\n- 打开文件(如果尚未打开)\n- 从文件获取数据条目\n- 使用数据进行训练\n\n但是,在类似这里的朴素同步实现中,当流水线在获取数据时,模型会处于空闲状态。相反,当模型在进行训练时,输入流水线会处于空闲状态。因此,训练步骤的用时是打开、读取和训练时间的总和。\n\n接下来的各部分将基于此输入流水线,演示设计高效 TensorFlow 输入流水线的最佳做法。",
"_____no_output_____"
],
[
"### 预提取\n\n预提取会与训练步骤的预处理和模型执行重叠。在模型执行第 `s` 步训练的同时,输入流水线会读取第 `s+1` 步的数据。这样做能够最大程度减少训练的单步用时(而非总和),并减少提取数据所需的时间。\n\n`tf.data` API 提供了 `tf.data.Dataset.prefetch` 转换。它可以用来将数据的生成时间和使用时间分离。特别是,该转换会使用后台线程和内部缓冲区在请求元素之前从输入数据集中预提取这些元素。要预提取的元素数量应等于(或可能大于)单个训练步骤使用的批次数。您可以手动调整这个值,或者将其设置为 `tf.data.experimental.AUTOTUNE`,这将提示 `tf.data` 运行时在运行期间动态调整该值。\n\n注意,只要有机会将“生产者”的工作和“使用者”的工作重叠,预提取转换就能带来好处。",
"_____no_output_____"
]
],
[
[
"benchmark(\n ArtificialDataset()\n .prefetch(tf.data.experimental.AUTOTUNE)\n)",
"_____no_output_____"
]
],
[
[
"\n\n这次您可以看到,在针对样本 0 运行训练步骤的同时,输入流水线正在读取样本 1 的数据,依此类推。",
"_____no_output_____"
],
[
"### 并行数据提取\n\n在实际设置中,输入数据可能会远程存储(例如,GCS 或 HDFS)。由于在本地存储空间和远程存储空间之间存在以下差异,在本地读取数据时运行良好的数据集流水线可能会在远程读取数据时成为 I/O 瓶颈:\n\n- **到达第一字节用时**:从远程存储空间中读取文件的第一个字节所花费的时间要比从本地存储空间中读取所花费的时间长几个数量级。\n- **读取吞吐量**:虽然远程存储空间通常提供较大的聚合带宽,但读取单个文件可能只能使用此带宽的一小部分。\n\n此外,将原始字节加载到内存中后,可能还需要对数据进行反序列化和/或解密(例如 [protobuf](https://developers.google.com/protocol-buffers/)),这需要进行额外计算。无论数据是本地存储还是远程存储,都会存在此开销,但如果没有高效地预提取数据,在远程情况下会更糟。\n\n为了减轻各种数据提取开销的影响,可以使用 `tf.data.Dataset.interleave` 转换来并行化数据加载步骤,从而交错其他数据集(如数据文件读取器)的内容。可以通过 `cycle_length` 参数指定想要重叠的数据集数量,并通过 `num_parallel_calls` 参数指定并行度级别。与 `prefetch` 转换类似,`interleave` 转换也支持 `tf.data.experimental.AUTOTUNE`,它将让 `tf.data` 运行时决定要使用的并行度级别。",
"_____no_output_____"
],
[
"#### 顺序交错\n\n`tf.data.Dataset.interleave` 转换的默认参数会使其按顺序交错两个数据集中的单个样本。",
"_____no_output_____"
]
],
[
[
"benchmark(\n tf.data.Dataset.range(2)\n .interleave(ArtificialDataset)\n)",
"_____no_output_____"
]
],
[
[
"\n\n该图可以展示 `interleave` 转换的行为,从两个可用的数据集中交替预提取样本。但是,这里不涉及性能改进。",
"_____no_output_____"
],
[
"#### 并行交错\n\n现在,使用 `interleave` 转换的 `num_parallel_calls` 参数。这样可以并行加载多个数据集,从而减少等待打开文件的时间。",
"_____no_output_____"
]
],
[
[
"benchmark(\n tf.data.Dataset.range(2)\n .interleave(\n ArtificialDataset,\n num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n)",
"_____no_output_____"
]
],
[
[
"\n\n这次,两个数据集的读取并行进行,从而减少了全局数据处理时间。",
"_____no_output_____"
],
[
"### 并行数据转换\n\n准备数据时,可能需要对输入元素进行预处理。为此,`tf.data` API 提供了 `tf.data.Dataset.map` 转换,该转换会将用户定义的函数应用于输入数据集的每个元素。由于输入元素彼此独立,可以在多个 CPU 核心之间并行预处理。为了实现这一点,类似 `prefetch` 和 `interleave` 转换,`map` 转换也提供了`num_parallel_calls` 参数来指定并行度级别。\n\n`num_parallel_calls` 参数最佳值的选择取决于您的硬件、训练数据的特性(如数据大小和形状)、映射函数的开销,以及同一时间在 CPU 上进行的其他处理。一个简单的试探法是使用可用的 CPU 核心数。但是,对于 `prefetch` 和 `interleave` 转换,`map` 转换支持 `tf.data.experimental.AUTOTUNE`,它将让 `tf.data` 运行时决定要使用的并行度级别。",
"_____no_output_____"
]
],
[
[
"def mapped_function(s):\n # Do some hard pre-processing\n tf.py_function(lambda: time.sleep(0.03), [], ())\n return s",
"_____no_output_____"
]
],
[
[
"#### 顺序映射\n\n首先使用不具有并行度的 `map` 转换作为基准示例。",
"_____no_output_____"
]
],
[
[
"benchmark(\n ArtificialDataset()\n .map(mapped_function)\n)",
"_____no_output_____"
]
],
[
[
"\n\n对于[朴素方法](#The-naive-approach)来说,单次迭代的用时就是花费在打开、读取、预处理(映射)和训练步骤上的时间总和。",
"_____no_output_____"
],
[
"#### 并行映射\n\n现在,使用相同的预处理函数,但将其并行应用于多个样本。",
"_____no_output_____"
]
],
[
[
"benchmark(\n ArtificialDataset()\n .map(\n mapped_function,\n num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n)",
"_____no_output_____"
]
],
[
[
"\n\n现在,您可以在图上看到预处理步骤重叠,从而减少了单次迭代的总时间。",
"_____no_output_____"
],
[
"### 缓存\n\n`tf.data.Dataset.cache` 转换可以在内存中或本地存储空间中缓存数据集。这样可以避免一些运算(如文件打开和数据读取)在每个周期都被执行。",
"_____no_output_____"
]
],
[
[
"benchmark(\n ArtificialDataset()\n .map( # Apply time consuming operations before cache\n mapped_function\n ).cache(\n ),\n 5\n)",
"_____no_output_____"
]
],
[
[
"\n\n缓存数据集时,仅在第一个周期执行一次 `cache` 之前的转换(如文件打开和数据读取)。后续周期将重用通过 `cache` 转换缓存的数据。\n\n如果传递到 `map` 转换的用户定义函数开销很大,可在 `map` 转换后应用 `cache` 转换,只要生成的数据集仍然可以放入内存或本地存储空间即可。如果用户定义函数增加了存储数据集所需的空间(超出缓存容量),在 `cache` 转换后应用该函数,或者考虑在训练作业之前对数据进行预处理以减少资源使用。",
"_____no_output_____"
],
[
"### 向量化映射\n\n调用传递给 `map` 转换的用户定义函数会产生与调度和执行用户定义函数相关的开销。我们建议对用户定义函数进行向量化处理(即,让它一次运算一批输入)并在 `map` 转换*之前*应用 `batch` 转换。\n\n为了说明这种良好做法,不适合使用您的人工数据集。调度延迟大约为 10 微妙(10e-6 秒),远远小于 `ArtificialDataset` 中使用的数十毫秒,因此很难看出它的影响。\n\n在本示例中,我们使用基本 `tf.data.Dataset.range` 函数并将训练循环简化为最简形式。",
"_____no_output_____"
]
],
[
[
"fast_dataset = tf.data.Dataset.range(10000)\n\ndef fast_benchmark(dataset, num_epochs=2):\n start_time = time.perf_counter()\n for _ in tf.data.Dataset.range(num_epochs):\n for _ in dataset:\n pass\n tf.print(\"Execution time:\", time.perf_counter() - start_time)\n \ndef increment(x):\n return x+1",
"_____no_output_____"
]
],
[
[
"#### 标量映射",
"_____no_output_____"
]
],
[
[
"fast_benchmark(\n fast_dataset\n # Apply function one item at a time\n .map(increment)\n # Batch\n .batch(256)\n)",
"_____no_output_____"
]
],
[
[
"\n\n上图说明了正在发生的事情(样本较少)。您可以看到已将映射函数应用于每个样本。虽然此函数速度很快,但会产生一些开销影响时间性能。",
"_____no_output_____"
],
[
"#### 向量化映射",
"_____no_output_____"
]
],
[
[
"fast_benchmark(\n fast_dataset\n .batch(256)\n # Apply function on a batch of items\n # The tf.Tensor.__add__ method already handle batches\n .map(increment)\n)",
"_____no_output_____"
]
],
[
[
"\n\n这次,映射函数被调用了一次,并被应用于一批样本。虽然该函数可能需要花费更多时间执行,但开销仅出现了一次,从而改善了整体时间性能。",
"_____no_output_____"
],
[
"### 减少内存占用\n\n许多转换(包括 `interleave`、`prefetch` 和 `shuffle`)会维护元素的内部缓冲区。如果传递给 `map` 转换的用户定义函数更改了元素大小,则映射转换和缓冲元素的转换的顺序会影响内存使用量。通常,我们建议选择能够降低内存占用的顺序,除非需要不同的顺序以提高性能。\n\n#### 缓存部分计算\n\n建议在 `map` 转换后缓存数据集,除非此转换会使数据过大而不适合放在内存中。如果映射函数可以分成两个部分,则能实现折衷:一个耗时的部分和一个消耗内存的部分。在这种情况下,您可以按如下方式将转换链接起来:\n\n```python\ndataset.map(time_consuming_mapping).cache().map(memory_consuming_mapping)\n```\n\n这样,耗时部分仅在第一个周期执行,从而避免了使用过多缓存空间。",
"_____no_output_____"
],
[
"## 最佳做法总结\n\n以下是设计高效 TensorFlow 输入流水线的最佳做法总结:\n\n- [使用 `prefetch` 转换](#Pipelining)使生产者和使用者的工作重叠。\n- 使用 `interleave` 转换实现[并行数据读取转换](#Parallelizing-data-extraction)。\n- 通过设置 `num_parallel_calls` 参数实现[并行 `map` 转换](#Parallelizing-data-transformation)。\n- 第一个周期[使用 `cache` 转换](#Caching)将数据缓存在内存中。\n- [向量化](#Map-and-batch)传递给 `map` 转换的用户定义函数\n- 应用 `interleave`、`prefetch` 和 `shuffle` 转换时[减少内存使用量](#Reducing-memory-footprint)。",
"_____no_output_____"
],
[
"## 重现图表\n\n注:本笔记本的剩余部分是关于如何重现上述图表的,请随意使用以下代码,但请了解其并非本教程的主要内容。\n\n要更深入地了解 `tf.data.Dataset` API,您可以使用自己的流水线。下面是用来绘制本指南中图像的代码。这可以作为一个好的起点,展示了一些常见困难的解决方法,例如:\n\n- 执行时间的可重现性;\n- 映射函数的 Eager Execution;\n- `interleave` 转换的可调用对象。",
"_____no_output_____"
]
],
[
[
"import itertools\nfrom collections import defaultdict\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"### 数据集\n\n与 `ArtificialDataset` 类似,您可以构建一个返回每步用时的数据集。",
"_____no_output_____"
]
],
[
[
"class TimeMeasuredDataset(tf.data.Dataset):\n # OUTPUT: (steps, timings, counters)\n OUTPUT_TYPES = (tf.dtypes.string, tf.dtypes.float32, tf.dtypes.int32)\n OUTPUT_SHAPES = ((2, 1), (2, 2), (2, 3))\n \n _INSTANCES_COUNTER = itertools.count() # Number of datasets generated\n _EPOCHS_COUNTER = defaultdict(itertools.count) # Number of epochs done for each dataset\n \n def _generator(instance_idx, num_samples):\n epoch_idx = next(TimeMeasuredDataset._EPOCHS_COUNTER[instance_idx])\n \n # Opening the file\n open_enter = time.perf_counter()\n time.sleep(0.03)\n open_elapsed = time.perf_counter() - open_enter\n \n for sample_idx in range(num_samples):\n # Reading data (line, record) from the file\n read_enter = time.perf_counter()\n time.sleep(0.015)\n read_elapsed = time.perf_counter() - read_enter\n \n yield (\n [(\"Open\",), (\"Read\",)],\n [(open_enter, open_elapsed), (read_enter, read_elapsed)],\n [(instance_idx, epoch_idx, -1), (instance_idx, epoch_idx, sample_idx)]\n )\n open_enter, open_elapsed = -1., -1. # Negative values will be filtered\n \n \n def __new__(cls, num_samples=3):\n return tf.data.Dataset.from_generator(\n cls._generator,\n output_types=cls.OUTPUT_TYPES,\n output_shapes=cls.OUTPUT_SHAPES,\n args=(next(cls._INSTANCES_COUNTER), num_samples)\n )",
"_____no_output_____"
]
],
[
[
"此数据集会提供形状为 `[[2, 1], [2, 2], [2, 3]]` 且类型为 `[tf.dtypes.string, tf.dtypes.float32, tf.dtypes.int32]` 的样本。每个样本为:\n\n```\n( [(\"Open\"), (\"Read\")], [(t0, d), (t0, d)], [(i, e, -1), (i, e, s)] )\n```\n\n其中:\n\n- `Open` 和 `Read` 是步骤标识符\n- `t0` 是相应步骤开始时的时间戳\n- `d` 是在相应步骤中花费的时间\n- `i` 是实例索引\n- `e` 是周期索引(数据集被迭代的次数)\n- `s` 是样本索引",
"_____no_output_____"
],
[
"### 迭代循环\n\n使迭代循环稍微复杂一点,以汇总所有计时。这仅适用于生成上述样本的数据集。",
"_____no_output_____"
]
],
[
[
"def timelined_benchmark(dataset, num_epochs=2):\n # Initialize accumulators\n steps_acc = tf.zeros([0, 1], dtype=tf.dtypes.string)\n times_acc = tf.zeros([0, 2], dtype=tf.dtypes.float32)\n values_acc = tf.zeros([0, 3], dtype=tf.dtypes.int32)\n \n start_time = time.perf_counter()\n for epoch_num in range(num_epochs):\n epoch_enter = time.perf_counter()\n for (steps, times, values) in dataset:\n # Record dataset preparation informations\n steps_acc = tf.concat((steps_acc, steps), axis=0)\n times_acc = tf.concat((times_acc, times), axis=0)\n values_acc = tf.concat((values_acc, values), axis=0)\n \n # Simulate training time\n train_enter = time.perf_counter()\n time.sleep(0.01)\n train_elapsed = time.perf_counter() - train_enter\n \n # Record training informations\n steps_acc = tf.concat((steps_acc, [[\"Train\"]]), axis=0)\n times_acc = tf.concat((times_acc, [(train_enter, train_elapsed)]), axis=0)\n values_acc = tf.concat((values_acc, [values[-1]]), axis=0)\n \n epoch_elapsed = time.perf_counter() - epoch_enter\n # Record epoch informations\n steps_acc = tf.concat((steps_acc, [[\"Epoch\"]]), axis=0)\n times_acc = tf.concat((times_acc, [(epoch_enter, epoch_elapsed)]), axis=0)\n values_acc = tf.concat((values_acc, [[-1, epoch_num, -1]]), axis=0)\n time.sleep(0.001)\n \n tf.print(\"Execution time:\", time.perf_counter() - start_time)\n return {\"steps\": steps_acc, \"times\": times_acc, \"values\": values_acc}",
"_____no_output_____"
]
],
[
[
"### 绘图方法\n\n最后,定义一个函数,根据 `timelined_benchmark` 函数返回的值绘制时间线。",
"_____no_output_____"
]
],
[
[
"def draw_timeline(timeline, title, width=0.5, annotate=False, save=False):\n # Remove invalid entries (negative times, or empty steps) from the timelines\n invalid_mask = np.logical_and(timeline['times'] > 0, timeline['steps'] != b'')[:,0]\n steps = timeline['steps'][invalid_mask].numpy()\n times = timeline['times'][invalid_mask].numpy()\n values = timeline['values'][invalid_mask].numpy()\n \n # Get a set of different steps, ordered by the first time they are encountered\n step_ids, indices = np.stack(np.unique(steps, return_index=True))\n step_ids = step_ids[np.argsort(indices)]\n\n # Shift the starting time to 0 and compute the maximal time value\n min_time = times[:,0].min()\n times[:,0] = (times[:,0] - min_time)\n end = max(width, (times[:,0]+times[:,1]).max() + 0.01)\n \n cmap = mpl.cm.get_cmap(\"plasma\")\n plt.close()\n fig, axs = plt.subplots(len(step_ids), sharex=True, gridspec_kw={'hspace': 0})\n fig.suptitle(title)\n fig.set_size_inches(17.0, len(step_ids))\n plt.xlim(-0.01, end)\n \n for i, step in enumerate(step_ids):\n step_name = step.decode()\n ax = axs[i]\n ax.set_ylabel(step_name)\n ax.set_ylim(0, 1)\n ax.set_yticks([])\n ax.set_xlabel(\"time (s)\")\n ax.set_xticklabels([])\n ax.grid(which=\"both\", axis=\"x\", color=\"k\", linestyle=\":\")\n \n # Get timings and annotation for the given step\n entries_mask = np.squeeze(steps==step)\n serie = np.unique(times[entries_mask], axis=0)\n annotations = values[entries_mask]\n \n ax.broken_barh(serie, (0, 1), color=cmap(i / len(step_ids)), linewidth=1, alpha=0.66)\n if annotate:\n for j, (start, width) in enumerate(serie):\n annotation = \"\\n\".join([f\"{l}: {v}\" for l,v in zip((\"i\", \"e\", \"s\"), annotations[j])])\n ax.text(start + 0.001 + (0.001 * (j % 2)), 0.55 - (0.1 * (j % 2)), annotation,\n horizontalalignment='left', verticalalignment='center')\n if save:\n plt.savefig(title.lower().translate(str.maketrans(\" \", \"_\")) + \".svg\")",
"_____no_output_____"
]
],
[
[
"### 对映射函数使用包装器\n\n要在 Eager 上下文中运行映射函数,必须将其包装在 `tf.py_function` 调用中。",
"_____no_output_____"
]
],
[
[
"def map_decorator(func):\n def wrapper(steps, times, values):\n # Use a tf.py_function to prevent auto-graph from compiling the method\n return tf.py_function(\n func,\n inp=(steps, times, values),\n Tout=(steps.dtype, times.dtype, values.dtype)\n )\n return wrapper",
"_____no_output_____"
]
],
[
[
"### 流水线对比",
"_____no_output_____"
]
],
[
[
"_batch_map_num_items = 50\n\ndef dataset_generator_fun(*args):\n return TimeMeasuredDataset(num_samples=_batch_map_num_items)",
"_____no_output_____"
]
],
[
[
"#### 朴素流水线",
"_____no_output_____"
]
],
[
[
"@map_decorator\ndef naive_map(steps, times, values):\n map_enter = time.perf_counter()\n time.sleep(0.001) # Time consuming step\n time.sleep(0.0001) # Memory consuming step\n map_elapsed = time.perf_counter() - map_enter\n\n return (\n tf.concat((steps, [[\"Map\"]]), axis=0),\n tf.concat((times, [[map_enter, map_elapsed]]), axis=0),\n tf.concat((values, [values[-1]]), axis=0)\n )\n\nnaive_timeline = timelined_benchmark(\n tf.data.Dataset.range(2)\n .flat_map(dataset_generator_fun)\n .map(naive_map)\n .batch(_batch_map_num_items, drop_remainder=True)\n .unbatch(),\n 5\n)",
"_____no_output_____"
]
],
[
[
"### 优化后的流水线",
"_____no_output_____"
]
],
[
[
"@map_decorator\ndef time_consuming_map(steps, times, values):\n map_enter = time.perf_counter()\n time.sleep(0.001 * values.shape[0]) # Time consuming step\n map_elapsed = time.perf_counter() - map_enter\n\n return (\n tf.concat((steps, tf.tile([[[\"1st map\"]]], [steps.shape[0], 1, 1])), axis=1),\n tf.concat((times, tf.tile([[[map_enter, map_elapsed]]], [times.shape[0], 1, 1])), axis=1),\n tf.concat((values, tf.tile([[values[:][-1][0]]], [values.shape[0], 1, 1])), axis=1)\n )\n\n\n@map_decorator\ndef memory_consuming_map(steps, times, values):\n map_enter = time.perf_counter()\n time.sleep(0.0001 * values.shape[0]) # Memory consuming step\n map_elapsed = time.perf_counter() - map_enter\n\n # Use tf.tile to handle batch dimension\n return (\n tf.concat((steps, tf.tile([[[\"2nd map\"]]], [steps.shape[0], 1, 1])), axis=1),\n tf.concat((times, tf.tile([[[map_enter, map_elapsed]]], [times.shape[0], 1, 1])), axis=1),\n tf.concat((values, tf.tile([[values[:][-1][0]]], [values.shape[0], 1, 1])), axis=1)\n )\n\n\noptimized_timeline = timelined_benchmark(\n tf.data.Dataset.range(2)\n .interleave( # Parallelize data reading\n dataset_generator_fun,\n num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n .batch( # Vectorize your mapped function\n _batch_map_num_items,\n drop_remainder=True)\n .map( # Parallelize map transformation\n time_consuming_map,\n num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n .cache() # Cache data\n .map( # Reduce memory usage\n memory_consuming_map,\n num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n .prefetch( # Overlap producer and consumer works\n tf.data.experimental.AUTOTUNE\n )\n .unbatch(),\n 5\n)",
"_____no_output_____"
],
[
"draw_timeline(naive_timeline, \"Naive\", 15)",
"_____no_output_____"
],
[
"draw_timeline(optimized_timeline, \"Optimized\", 15)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7ae795a90fa71f96e6e1330bcf2b5227de82e27 | 36,448 | ipynb | Jupyter Notebook | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy | 053daf3f91fd7d59c702b8127d1e069e1951bb85 | [
"MIT"
] | null | null | null | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy | 053daf3f91fd7d59c702b8127d1e069e1951bb85 | [
"MIT"
] | null | null | null | notebook.ipynb | abhiWriteCode/Tutorial-for-spaCy | 053daf3f91fd7d59c702b8127d1e069e1951bb85 | [
"MIT"
] | null | null | null | 28.94996 | 3,017 | 0.462851 | [
[
[
"<a href=\"https://colab.research.google.com/github/abhiWriteCode/Tutorial-for-spaCy/blob/master/notebook.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# spaCy\n\nspaCy is a free, open-source library for advanced Natural\nLanguage Processing (NLP) in Python. It's designed\nspecifically for production use and helps you build\napplications that process and \"understand\" large volumes\nof text. **Documentation**: [spacy.io](spacy.io)",
"_____no_output_____"
],
[
"### Install and import",
"_____no_output_____"
]
],
[
[
"# To install\n!pip install spacy -q\n\n# imports\nimport spacy",
"\u001b[K 100% |████████████████████████████████| 17.3MB 2.0MB/s \n\u001b[31mfeaturetools 0.4.1 has requirement pandas>=0.23.0, but you'll have pandas 0.22.0 which is incompatible.\u001b[0m\n\u001b[31mdatascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.\u001b[0m\n\u001b[31malbumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.8 which is incompatible.\u001b[0m\n\u001b[?25h"
]
],
[
[
"## Statistical models",
"_____no_output_____"
],
[
"### Download statistical models\n\nPredict part-of-speech tags, dependency labels, named\nentities and more. See here for available models:\n[spacy.io/models](spacy.io/models)",
"_____no_output_____"
]
],
[
[
"!python -m spacy download en_core_web_sm",
"Requirement already satisfied: en_core_web_sm==2.0.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz#egg=en_core_web_sm==2.0.0 in /usr/local/lib/python3.6/dist-packages (2.0.0)\n\n\u001b[93m Linking successful\u001b[0m\n /usr/local/lib/python3.6/dist-packages/en_core_web_sm -->\n /usr/local/lib/python3.6/dist-packages/spacy/data/en_core_web_sm\n\n You can now load the model via spacy.load('en_core_web_sm')\n\n"
]
],
[
[
"### Check that your installed models are up to date",
"_____no_output_____"
]
],
[
[
"!python -m spacy validate",
"\n\u001b[93m Installed models (spaCy v2.0.18)\u001b[0m\n /usr/local/lib/python3.6/dist-packages/spacy\n\n TYPE NAME MODEL VERSION \n package en-core-web-sm en_core_web_sm \u001b[38;5;2m2.0.0\u001b[0m \u001b[38;5;2m✔\u001b[0m \n link en en_core_web_sm \u001b[38;5;2m2.0.0\u001b[0m \u001b[38;5;2m✔\u001b[0m \n link en_core_web_sm en_core_web_sm \u001b[38;5;2m2.0.0\u001b[0m \u001b[38;5;2m✔\u001b[0m \n"
]
],
[
[
"### Loading statistical models",
"_____no_output_____"
]
],
[
[
"import spacy\n\n# Load the installed model \"en_core_web_sm\"\nnlp = spacy.load(\"en_core_web_sm\")",
"_____no_output_____"
]
],
[
[
"## Documents and tokens",
"_____no_output_____"
],
[
"### Processing text\n\nProcessing text with the nlp object returns a Doc object\nthat holds all information about the tokens, their linguistic\nfeatures and their relationships",
"_____no_output_____"
],
[
"### Accessing token attributes",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"This is a text\")\n\n# Token texts\n[token.text for token in doc]",
"_____no_output_____"
]
],
[
[
"## Spans",
"_____no_output_____"
],
[
"### Accessing spans\n\nSpan indices are **exclusive**. So `doc[2:4]` is a span starting at\ntoken 2, up to – but not including! – token 4.",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"This is a text\")\nspan = doc[2:4]\nspan.text",
"_____no_output_____"
]
],
[
[
"## Linguistic features\n\nAttributes return label IDs. For string labels, use the\nattributes with an underscore. For example, `token.pos_` .",
"_____no_output_____"
],
[
"### Part-of-speech tags \n\n*PREDICTED BY STATISTICAL MODEL*",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"This is a text.\")\n\n# Coarse-grained part-of-speech tags\nprint([token.pos_ for token in doc])\n\n# Fine-grained part-of-speech tags\nprint([token.tag_ for token in doc])",
"['DET', 'VERB', 'DET', 'NOUN', 'PUNCT']\n['DT', 'VBZ', 'DT', 'NN', '.']\n"
]
],
[
[
"### Syntactic dependencies\n\n*PREDICTED BY STATISTICAL MODEL*",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"This is a text.\")\n\n# Dependency labels\nprint([token.dep_ for token in doc])\n\n# Syntactic head token (governor)\nprint([token.head.text for token in doc])",
"['nsubj', 'ROOT', 'det', 'attr', 'punct']\n['is', 'is', 'text', 'is', 'is']\n"
]
],
[
[
"### Named entities\n\n*PREDICTED BY STATISTICAL MODEL*",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"Larry Page founded Google\")\n\n# Text and label of named entity span\nprint([(ent.text, ent.label_) for ent in doc.ents])",
"[('Larry Page', 'PERSON'), ('Google', 'ORG')]\n"
]
],
[
[
"## Syntax iterators",
"_____no_output_____"
],
[
"### Sentences \n\n*USUALLY NEEDS THE DEPENDENCY PARSER*",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"This a sentence. This is another one.\")\n# doc.sents is a generator that yields sentence spans\nprint([sent.text for sent in doc.sents])",
"['This a sentence.', 'This is another one.']\n"
]
],
[
[
"### Base noun phrases \n*NEEDS THE TAGGER AND PARSER*",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"I have a red car\")\n\n# doc.noun_chunks is a generator that yields spans\nprint([chunk.text for chunk in doc.noun_chunks])",
"['I', 'a red car']\n"
]
],
[
[
"## Label explanations",
"_____no_output_____"
]
],
[
[
"print(spacy.explain(\"RB\"))\n\nprint(spacy.explain(\"GPE\"))",
"adverb\nCountries, cities, states\n"
]
],
[
[
"## Visualizing\n\nIf you're in a Jupyter notebook, use displacy.render .\nOtherwise, use displacy.serve to start a web server and\nshow the visualization in your browser.",
"_____no_output_____"
]
],
[
[
"from IPython.display import display, SVG",
"_____no_output_____"
],
[
"from spacy import displacy",
"_____no_output_____"
]
],
[
[
"### Visualize dependencies",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"This is a sentence\")\ndiagram = displacy.render(doc, style=\"dep\")\n\ndisplay(SVG(diagram))",
"_____no_output_____"
]
],
[
[
"### Visualize named entities",
"_____no_output_____"
]
],
[
[
"doc = nlp(\"Larry Page founded Google\")\ndiagram = displacy.render(doc, style=\"ent\")\n\ndisplay(SVG(diagram))",
"_____no_output_____"
]
],
[
[
"## Word vectors and similarity\n\nTo use word vectors, you need to install the larger models\nending in `md` or `lg` , for example `en_core_web_lg` .",
"_____no_output_____"
],
[
"### Comparing similarity",
"_____no_output_____"
]
],
[
[
"doc1 = nlp(\"I like cats\")\ndoc2 = nlp(\"I like dogs\")\n\n# Compare 2 documents\nprint(doc1.similarity(doc2))\n\n# Compare 2 tokens\nprint(doc1[2].similarity(doc2[2]))\n\n# Compare tokens and spans\nprint(doc1[0].similarity(doc2[1:3]))",
"0.9133257426978459\n0.7518883\n0.19759766442466106\n"
]
],
[
[
"### Accessing word vectors",
"_____no_output_____"
]
],
[
[
"# Vector as a numpy array\ndoc = nlp(\"I like cats\")\n\nprint(doc[2].vector.shape)\n# The L2 norm of the token's vector\nprint(doc[2].vector_norm)",
"(384,)\n24.809391\n"
]
],
[
[
"## Pipeline components\n\nFunctions that take a `Doc` object, modify it and return it.",
"_____no_output_____"
],
[
"`Text` --> | `tokenizer`, `tagger`, `parser`, `ner`, ... | --> `Doc`\n",
"_____no_output_____"
],
[
"### Pipeline information",
"_____no_output_____"
]
],
[
[
"nlp = spacy.load(\"en_core_web_sm\")\nprint(nlp.pipe_names)\n\nprint(nlp.pipeline)",
"['tagger', 'parser', 'ner']\n[('tagger', <spacy.pipeline.Tagger object at 0x7f7972874ef0>), ('parser', <spacy.pipeline.DependencyParser object at 0x7f79728cb150>), ('ner', <spacy.pipeline.EntityRecognizer object at 0x7f797282c4c0>)]\n"
]
],
[
[
"### Custom components",
"_____no_output_____"
]
],
[
[
"# Function that modifies the doc and returns it\ndef custom_component(doc):\n print(\"Do something to the doc here!\")\n return doc\n\n# Add the component first in the pipeline\nnlp.add_pipe(custom_component, first=True)",
"_____no_output_____"
]
],
[
[
"Components can be added `first` , `last` (default), or\n `before` or `after` an existing component.",
"_____no_output_____"
],
[
"## Extension attributes\n\nCustom attributes that are registered on the global `Doc` , `Token` and `Span` classes and become available as `.[link text](https://)_`",
"_____no_output_____"
]
],
[
[
"import os\nos._exit(00)",
"_____no_output_____"
],
[
"from spacy.tokens import Doc, Token, Span\nimport spacy\nnlp = spacy.load(\"en_core_web_sm\")\n\ndoc = nlp(\"The sky over New York is blue\")",
"_____no_output_____"
]
],
[
[
"### Attribute extensions \n*WITH DEFAULT VALUE*",
"_____no_output_____"
]
],
[
[
"# Register custom attribute on Token class\nToken.set_extension(\"is_color\", default=False)\n\n# Overwrite extension attribute with default value\ndoc[6]._.is_color = True ",
"_____no_output_____"
]
],
[
[
"### Property extensions \n*WITH GETTER & SETTER*",
"_____no_output_____"
]
],
[
[
"# Register custom attribute on Doc class\nget_reversed = lambda doc: doc.text[::-1]\nDoc.set_extension(\"reversed\", getter=get_reversed)\n\n# Compute value of extension attribute with getter\ndoc._.reversed",
"_____no_output_____"
]
],
[
[
"### Method extensions \n*CALLABLE METHOD*",
"_____no_output_____"
]
],
[
[
"# Register custom attribute on Span class\nhas_label = lambda span, label: span.label_ == label\nSpan.set_extension(\"has_label\", method=has_label)\n\n# Compute value of extension attribute with method\ndoc[3:5]._.has_label(\"GPE\")",
"_____no_output_____"
]
],
[
[
"## Rule-based matching",
"_____no_output_____"
],
[
"### Using the matcher",
"_____no_output_____"
]
],
[
[
"# Matcher is initialized with the shared vocab\nfrom spacy.matcher import Matcher\n\n# Each dict represents one token and its attributes\nmatcher = Matcher(nlp.vocab)\n\n# Add with ID, optional callback and pattern(s)\npattern = [{\"LOWER\": \"new\"}, {\"LOWER\": \"york\"}]\nmatcher.add(\"CITIES\", None, pattern)\n\n# Match by calling the matcher on a Doc object\ndoc = nlp(\"I live in New York\")\nmatches = matcher(doc)\n\n# Matches are (match_id, start, end) tuples\nfor match_id, start, end in matches:\n # Get the matched span by slicing the Doc\n \n span = doc[start:end]\n print(span.text)",
"New York\n"
]
],
[
[
"## Rule-based matching",
"_____no_output_____"
],
[
"### Token patterns",
"_____no_output_____"
]
],
[
[
"# \"love cats\", \"loving cats\", \"loved cats\"\npattern1 = [{\"LEMMA\": \"love\"}, {\"LOWER\": \"cats\"}]\n\n# \"10 people\", \"twenty people\"\npattern2 = [{\"LIKE_NUM\": True}, {\"TEXT\": \"people\"}]\n\n# \"book\", \"a cat\", \"the sea\" (noun + optional article)\npattern3 = [{\"POS\": \"DET\", \"OP\": \"?\"}, {\"POS\": \"NOUN\"}]",
"_____no_output_____"
]
],
[
[
"### Operators and quantifiers",
"_____no_output_____"
],
[
"Can be added to a token dict as the `\"OP\"` key\n\n* `!` Negate pattern and match **exactly 0 times**.\n\n* `?` Make pattern optional and match **0 or 1 times**.\n\n* `+` Require pattern to match **1 or more times**.\n\n* `*` Allow pattern to match **0 or more times**. ",
"_____no_output_____"
],
[
"## Glossary\n\n\n| | |\n|---|---|\n| Tokenization | Segmenting text into words, punctuation etc |\n| Lemmatization | Assigning the base forms of words, for example:\"was\" → \"be\" or \"rats\" → \"rat\". |\n| Sentence Boundary Detection | Finding and segmenting individual sentences |\n| Part-of-speech (POS) Tagging | Assigning word types to tokens like verb or noun |\n| Dependency Parsing | Assigning syntactic dependency labels describing the relations between individual tokens, like subject or object. |\n| Named Entity Recognition (NER) | Labeling named \"real-world\" objects, like persons, companies or locations. |\n| Text Classification | Assigning categories or labels to a whole document, or parts of a document. |\n| Statistical model | Process for making predictions based on examples |\n| Training | Updating a statistical model with new examples. |",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
e7ae830bbe9d1446ac091a0c0cf58630f2f38ef0 | 2,087 | ipynb | Jupyter Notebook | docs/auto_examples/make_gif.ipynb | tmuntianu/supereeg | cd6e3ca1a898f091ef2696281c9ea32d1baf3eea | [
"MIT"
] | 27 | 2018-03-30T22:15:18.000Z | 2022-03-18T02:53:18.000Z | docs/auto_examples/make_gif.ipynb | tmuntianu/supereeg | cd6e3ca1a898f091ef2696281c9ea32d1baf3eea | [
"MIT"
] | 86 | 2018-03-30T02:58:18.000Z | 2021-07-07T01:45:31.000Z | docs/auto_examples/make_gif.ipynb | tmuntianu/supereeg | cd6e3ca1a898f091ef2696281c9ea32d1baf3eea | [
"MIT"
] | 16 | 2018-03-30T03:04:00.000Z | 2020-03-20T16:51:29.000Z | 38.648148 | 721 | 0.603737 | [
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"\n# Make gif\n\n\nIn this example, we load in a single subject example, remove electrodes that exceed\na kurtosis threshold (in place), load a model, and predict activity at all\nmodel locations. We then convert the reconstruction to a nifti and plot 3 consecutive timepoints\nfirst with the plot_glass_brain and then create .png files and compile as a gif.\n\n\n",
"_____no_output_____"
]
],
[
[
"# Code source: Lucy Owen & Andrew Heusser\n# License: MIT\n\n# load\nimport supereeg as se\n\n# load example data\nbo = se.load('example_data')\n\n# load example model\nmodel = se.load('example_model')\n\n# the default will replace the electrode location with the nearest voxel and reconstruct at all other locations\nreconstructed_bo = model.predict(bo)\n\n# print out info on new brain object\nreconstructed_bo.info()\n\n# convert to nifti\nreconstructed_nifti = reconstructed_bo.to_nii(template='gray', vox_size=20)\n\n# make gif, default time window is 0 to 10, but you can specifiy by setting a range with index\n# reconstructed_nifti.make_gif('/your/path/to/gif/', index=np.arange(100), name='sample_gif')",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7ae874c377943ffe8f7dc4cf7dbef65c4a0e5f8 | 45,224 | ipynb | Jupyter Notebook | _notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb | XCS224U-Spring2021-TeamTextSumm/ohmeow_website | b1d69d6540a0de4af30299c082a27180cb5d2ce4 | [
"Apache-2.0"
] | null | null | null | _notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb | XCS224U-Spring2021-TeamTextSumm/ohmeow_website | b1d69d6540a0de4af30299c082a27180cb5d2ce4 | [
"Apache-2.0"
] | null | null | null | _notebooks/2020-04-04-understanding-cross-entropy-loss.ipynb | XCS224U-Spring2021-TeamTextSumm/ohmeow_website | b1d69d6540a0de4af30299c082a27180cb5d2ce4 | [
"Apache-2.0"
] | null | null | null | 45.178821 | 15,120 | 0.638002 | [
[
[
"# \"Loss Functions: Cross Entropy Loss and You!\"\n> \"Meet multi-classification's favorite loss function\"\n\n- toc: true \n- badges: true\n- comments: true\n- author: Wayde Gilliam\n- image: images/articles/understanding-cross-entropy-loss-logo.png",
"_____no_output_____"
]
],
[
[
"# only run this cell if you are in collab\n!pip install fastai",
"_____no_output_____"
],
[
"import torch\nfrom torch.nn import functional as F\nfrom fastai2.vision.all import *",
"_____no_output_____"
]
],
[
[
"We've been doing multi-classification since week one, and last week, we learned about how a NN \"learns\" by evaluating its predictions as measured by something called a \"loss function.\" \n\nSo for multi-classification tasks, what is our loss function?",
"_____no_output_____"
]
],
[
[
"path = untar_data(URLs.PETS)/'images'\n\ndef is_cat(x): return x[0].isupper()\ndls = ImageDataLoaders.from_name_func(\n path, get_image_files(path), valid_pct=0.2, seed=42,\n label_func=is_cat, item_tfms=Resize(224))\n\nlearn = cnn_learner(dls, resnet34, metrics=error_rate)\nlearn.loss_func",
"_____no_output_____"
]
],
[
[
"## Negative Log-Likelihood & CrossEntropy Loss\n\nTo understand `CrossEntropyLoss`, we need to first understand something called `Negative Log-Likelihood`",
"_____no_output_____"
],
[
"### Negative Log-Likelihood (NLL) Loss",
"_____no_output_____"
],
[
"Let's imagine a model who's objective is to predict the label of an example given five possible classes to choose from. Our predictions might look like this ...",
"_____no_output_____"
]
],
[
[
"preds = torch.randn(3, 5); preds",
"_____no_output_____"
]
],
[
[
"Because this is a supervised task, we know the actual labels of our three training examples above (e.g., the label of the first example is the first class, the label of the 2nd example the 4th class, and so forth)",
"_____no_output_____"
]
],
[
[
"targets = torch.tensor([0, 3, 4])",
"_____no_output_____"
]
],
[
[
"**Step 1**: Convert the predictions for each example into probabilities using `softmax`. This describes how confident your model is in predicting what it belongs to respectively for each class",
"_____no_output_____"
]
],
[
[
"probs = F.softmax(preds, dim=1); probs",
"_____no_output_____"
]
],
[
[
"If we sum the probabilities across each example, you'll see they add up to 1",
"_____no_output_____"
]
],
[
[
"probs.sum(dim=1)",
"_____no_output_____"
]
],
[
[
"**Step 2**: Calculate the \"negative log likelihood\" for each example where `y` = the probability of the correct class\n\n`loss = -log(y)`\n\nWe can do this in one-line using something called ***tensor/array indexing***",
"_____no_output_____"
]
],
[
[
"example_idxs = range(len(preds)); example_idxs",
"_____no_output_____"
],
[
"correct_class_probs = probs[example_idxs, targets]; correct_class_probs",
"_____no_output_____"
],
[
"nll = -torch.log(correct_class_probs); nll",
"_____no_output_____"
]
],
[
[
"**Step 3**: The loss is the mean of the individual NLLs",
"_____no_output_____"
]
],
[
[
"nll.mean()",
"_____no_output_____"
]
],
[
[
"... or using PyTorch",
"_____no_output_____"
]
],
[
[
"F.nll_loss(torch.log(probs), targets)",
"_____no_output_____"
]
],
[
[
"### Cross Entropy Loss",
"_____no_output_____"
],
[
"... or we can do this all at once using PyTorch's `CrossEntropyLoss`",
"_____no_output_____"
]
],
[
[
"F.cross_entropy(preds, targets)",
"_____no_output_____"
]
],
[
[
"As you can see, cross entropy loss simply combines the `log_softmax` operation with the `negative log-likelihood` loss",
"_____no_output_____"
],
[
"## So why not use accuracy?",
"_____no_output_____"
]
],
[
[
"# this function is actually copied verbatim from the utils package in fastbook (see footnote 1)\ndef plot_function(f, tx=None, ty=None, title=None, min=-2, max=2, figsize=(6,4)):\n x = torch.linspace(min,max)\n fig,ax = plt.subplots(figsize=figsize)\n ax.plot(x,f(x))\n if tx is not None: ax.set_xlabel(tx)\n if ty is not None: ax.set_ylabel(ty)\n if title is not None: ax.set_title(title)",
"_____no_output_____"
],
[
"def f(x): return -torch.log(x)\n\nplot_function(f, 'x (prob correct class)', '-log(x)', title='Negative Log-Likelihood', min=0, max=1)",
"_____no_output_____"
]
],
[
[
"NLL loss will be higher the smaller the probability *of the correct class*\n\n**What does this all mean?** The lower the confidence it has in predicting the correct class, the higher the loss. It will:\n\n1) Penalize correct predictions that it isn't confident about more so than correct predictions it is very confident about.\n\n2) And vice-versa, it will penalize incorrect predictions it is very confident about more so than incorrect predictions it isn't very confident about\n\n**Why is this better than accuracy?**\n\nBecause accuracy simply tells you whether you got it right or wrong (a 1 or a 0), whereast NLL incorporates the confidence as well. That information provides you're model with a much better insight w/r/t to how well it is really doing in a single number (INF to 0), resulting in gradients that the model can actually use!\n\n*Rember that a loss function returns a number.* That's it!\n\nOr the more technical explanation from fastbook:\n\n>\"The gradient of a function is its slope, or its steepness, which can be defined as rise over run -- that is, how much the value of function goes up or down, divided by how much you changed the input. We can write this in maths: `(y_new-y_old) / (x_new-x_old)`. Specifically, it is defined when `x_new` is very similar to `x_old`, meaning that their difference is very small. **But accuracy only changes at all when a prediction changes from a 3 to a 7, or vice versa.** So the problem is that a small change in weights from `x_old` to `x_new` isn't likely to cause any prediction to change, so `(y_new - y_old)` will be zero. **In other words, the gradient is zero almost everywhere.**\n\n>As a result, **a very small change in the value of a weight will often not actually change the accuracy at all**. This means it is not useful to use accuracy as a loss function. When we use accuracy as a loss function, most of the time our gradients will actually be zero, and the model will not be able to learn from that number. That is not much use at all!\" {% fn 1 %}",
"_____no_output_____"
],
[
"## Summary",
"_____no_output_____"
],
[
"So to summarize, `accuracy` is a great metric for human intutition but not so much for your your model. If you're doing multi-classification, your model will do much better with something that will provide it gradients it can actually use in improving your parameters, and that something is `cross-entropy loss`.",
"_____no_output_____"
],
[
"## References\n\n1. https://pytorch.org/docs/stable/nn.html#crossentropyloss\n2. http://wiki.fast.ai/index.php/Log_Loss\n3. https://ljvmiranda921.github.io/notebook/2017/08/13/softmax-and-the-negative-log-likelihood/\n4. https://ml-cheatsheet.readthedocs.io/en/latest/loss_functions.html#cross-entropy\n5. https://machinelearningmastery.com/loss-and-loss-functions-for-training-deep-learning-neural-networks/",
"_____no_output_____"
],
[
"{{ 'fastbook [chaper 4](https://github.com/fastai/fastbook/blob/dc1bf74f2639aa39b16461f20406587baccb13b3/04_mnist_basics.ipynb)' | fndetail: 1 }}",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
e7ae9877ec93583701833db27bfa9810969ea9ca | 195,879 | ipynb | Jupyter Notebook | datascience/data_check/data_analysis.ipynb | VimeshShahama/Cyber---SDGP | 9c624d4932a07541dbc56bc8c7ba60c5e4662d31 | [
"CC0-1.0"
] | 1 | 2021-05-18T10:55:32.000Z | 2021-05-18T10:55:32.000Z | datascience/data_check/data_analysis.ipynb | VimeshShahama/Cyber---SDGP | 9c624d4932a07541dbc56bc8c7ba60c5e4662d31 | [
"CC0-1.0"
] | null | null | null | datascience/data_check/data_analysis.ipynb | VimeshShahama/Cyber---SDGP | 9c624d4932a07541dbc56bc8c7ba60c5e4662d31 | [
"CC0-1.0"
] | 2 | 2021-03-29T19:00:55.000Z | 2021-04-02T13:18:07.000Z | 262.924832 | 98,756 | 0.894828 | [
[
[
"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport os\nimport datetime\n%matplotlib inline",
"_____no_output_____"
],
[
"df = pd.read_csv('F:/iit_D/Year 2/SDGP/togithub/Cyber---SDGP/dataset/dateindex1.csv')\ndf.head(5)",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 105191 entries, 0 to 105190\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 datetime 105191 non-null object \n 1 G(i) 105191 non-null float64\ndtypes: float64(1), object(1)\nmemory usage: 1.6+ MB\n"
],
[
"df.describe()",
"_____no_output_____"
],
[
"#seperate date and time\ndf[\"New_Date\"] = pd.to_datetime(df[\"datetime\"]).dt.date\ndf[\"New_Time\"] = pd.to_datetime(df[\"datetime\"]).dt.time",
"_____no_output_____"
],
[
"df1 = df\ndf1.head(2)",
"_____no_output_____"
],
[
"#When was the higest\ndf1[df1[\"G(i)\"] == df[\"G(i)\"].max()]",
"_____no_output_____"
],
[
"# Minimum\ndf1[df1[\"G(i)\"] == df[\"G(i)\"].min()]",
"_____no_output_____"
],
[
"sns.distplot(df1[\"G(i)\"])",
"c:\\python\\python3.9.0\\lib\\site-packages\\seaborn\\distributions.py:2557: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).\n warnings.warn(msg, FutureWarning)\n"
],
[
"df1[\"Year\"] = pd.DatetimeIndex(df['New_Date']).year",
"_____no_output_____"
],
[
"sns.lineplot(x=df1[\"Year\"],y=df1[\"G(i)\"], data=df1)",
"_____no_output_____"
],
[
"# Regression\nsns.jointplot(x=df1[\"Year\"],\n y=df1[\"G(i)\"],\n data=df1,\n kind=\"reg\")",
"_____no_output_____"
],
[
"\nsns.jointplot(x=df1[\"Year\"],\n y=df1[\"G(i)\"],\n data=df1,\n kind=\"kde\")",
"_____no_output_____"
],
[
"sns.lineplot(x=df1[\"New_Time\"],y=df1[\"G(i)\"], data=df1)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7aec24cbc5ab7b4085c100320518f385f7fb789 | 34,625 | ipynb | Jupyter Notebook | ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb | romilshah525/SIH-2019 | 35555a4826e097a4a1178e7a1a8580dc4f80a64e | [
"MIT"
] | null | null | null | ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb | romilshah525/SIH-2019 | 35555a4826e097a4a1178e7a1a8580dc4f80a64e | [
"MIT"
] | 6 | 2021-07-20T06:46:21.000Z | 2022-03-08T23:26:58.000Z | ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (3)-checkpoint.ipynb | romilshah525/Water.io | 35555a4826e097a4a1178e7a1a8580dc4f80a64e | [
"MIT"
] | null | null | null | 30.506608 | 1,551 | 0.522484 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport pandas as pd\nfrom matplotlib.pylab import rcParams\nrcParams['figure.figsize'] = 15, 6\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"ori=pd.read_csv('website_data_20190225.csv')\nori.drop(['STATE','DISTRICT','WLCODE','SITE_TYPE','TEH_NAME','LAT','LON'],axis=1,inplace=True)\nori.replace(to_replace=\"'0\",value=0,inplace=True)\nori.head()",
"_____no_output_____"
],
[
"dataset=pd.DataFrame().reindex_like(ori)\ndataset1=pd.DataFrame().reindex_like(ori)\ndataset.dropna(inplace=True)\ndataset1.dropna(inplace=True)\n\n# j=0\n# for i in range(0,ori.shape[0]):\n# if ori['STATE'][i]=='RJ':\n# dataset.loc[j] = ori.iloc[i]\n# j+=1\n# dataset.drop(['STATE'],axis=1,inplace=True)\n\n# j=0\n# for i in range(0,ori.shape[0]):\n# if ori['DISTRICT'][i]=='Ajmer':\n# dataset.loc[j] = ori.iloc[i]\n# j+=1\n# dataset.drop(['DISTRICT'],axis=1,inplace=True)\n\nj=0\nfor i in range(0,ori.shape[0]):\n if ori['BLOCK_NAME'][i]=='Arain':\n dataset.loc[j] = ori.iloc[i]\n j+=1\ndataset1.drop(['BLOCK_NAME','SITE_NAME'],axis=1,inplace=True)\ndataset.drop(['BLOCK_NAME','SITE_NAME'],axis=1,inplace=True)\n\n# j=0\n# for i in range(0,dataset1.shape[0]):\n# if dataset1['SITE_NAME'][i]=='Sanpla':\n# dataset.loc[j] = dataset1.iloc[i]\n# j+=1\n# lat=dataset[\"LAT\"][0]\n# lon=dataset[\"LON\"][0]\n# dataset.drop(['SITE_NAME','LAT','LON'],axis=1,inplace=True)\n \ndataset.head()",
"_____no_output_____"
],
[
"for i in range(0,dataset.shape[0]):\n dataset['MONSOON'][i]=float(dataset['MONSOON'][i])\n dataset['POMRB'][i]=float(dataset['POMRB'][i])\n dataset['POMKH'][i]=float(dataset['POMKH'][i])\n dataset['PREMON'][i]=float(dataset['PREMON'][i])\n dataset['YEAR_OBS'][i]=int(dataset['YEAR_OBS'][i])\ndataset['YEAR_OBS']=(dataset['YEAR_OBS']).apply(np.int64)",
"_____no_output_____"
],
[
"dataset.head()",
"_____no_output_____"
],
[
"i=0\nj=0\nn=dataset.shape[0]\n# print(n)\nwhile(i<(len(dataset['YEAR_OBS'].unique()))):\n while((j<n-1)and((dataset.iloc[j:j+1,0:1].values==dataset.iloc[j+1:j+2,0:1].values)[0][0])):\n# print('A')\n# print(dataset.iloc[i:i+1,0:1].values)\n# print(dataset.iloc[i+1:i+2,0:1].values)\n first=list((dataset.iloc[i,1:].values))\n second=list((dataset.iloc[j+1,1:].values))\n dataset.loc[i:i+1,'MONSOON':'PREMON']=list(x+y for x, y in zip(first, second))\n# dataset.drop(dataset.iloc[i+1:i+2,:],inplace=True,axis=0)\n# dataset.drop(labels=[i+1],inplace=True)\n j+=1\n i+=1\n j+=1\n d=dataset.iloc[j:j+1,1:].values\n dataset.update(pd.DataFrame({'MONSOON': d[0][0]}, index=[i]))\n# dataset",
"_____no_output_____"
],
[
",'POMRB': d[0][1],'POMKH': d[0][2],'PREMON': d[0][3]",
"_____no_output_____"
],
[
"j=1\ntype(dataset.iloc[j:j+1,1:].values)\nd=dataset.iloc[j:j+1,1:].values\nd[0][0]",
"_____no_output_____"
],
[
"from datetime import datetime\ndataset['YEAR_OBS']=pd.to_datetime(dataset['YEAR_OBS'],yearfirst=True,format='%Y',infer_datetime_format=True)\nindexedDataset=dataset.set_index(['YEAR_OBS'])\nindexedDataset",
"_____no_output_____"
],
[
"first=list(indexedDataset['MONSOON'])\nsecond=list(indexedDataset['POMRB'])\nthird=list(indexedDataset['POMKH'])\nfourth=list(indexedDataset['PREMON'])\ntype(first[0])\n# indexedDataset['MONSOON']=pd.core.frame.DataFrame(x+y+z+w for x,y,z,w in zip(first,second,third,fourth))\n# indexedDataset.drop(['POMRB','POMKH','PREMON'],axis=1,inplace=True)\n# indexedDataset = indexedDataset.iloc[::-1]\n# indexedDataset",
"_____no_output_____"
],
[
"list((x+y+z+w for x,y,z,w in zip(first,second,third,fourth)))",
"_____no_output_____"
],
[
"plt.xlabel('Years')\nplt.ylabel('Water-Level')\nplt.plot(indexedDataset)",
"_____no_output_____"
]
],
[
[
"- A stationary time series is one whose statistical properties such as mean, variance, autocorrelation, etc. are all constant over time. Most statistical forecasting methods are based on the assumption that the time series can be rendered approximately stationary (i.e., \"stationarized\") through the use of mathematical transformations. A stationarized series is relatively easy to predict: you simply predict that its statistical properties will be the same in the future as they have been in the past!",
"_____no_output_____"
],
[
"- We can check stationarity using the following:\n\n- - Plotting Rolling Statistics: We can plot the moving average or moving variance and see if it varies with time. This is more of a visual technique.\n- - Dickey-Fuller Test: This is one of the statistical tests for checking stationarity. Here the null hypothesis is that the TimeSeries is non-stationary. The test results comprise of a Test Statistic and some Critical Values for difference confidence levels. If the ‘Test Statistic’ is less than the ‘Critical Value’, we can reject the null hypothesis and say that the series is stationary.",
"_____no_output_____"
]
],
[
[
"from statsmodels.tsa.stattools import adfuller\ndef test_stationary(timeseries):\n \n #Determing rolling statistics\n moving_average=timeseries.rolling(window=12).mean()\n standard_deviation=timeseries.rolling(window=12).std()\n \n #Plot rolling statistics:\n plt.plot(timeseries,color='blue',label=\"Original\")\n plt.plot(moving_average,color='red',label='Mean')\n plt.plot(standard_deviation,color='black',label='Standard Deviation')\n plt.legend(loc='best') #best for axes\n plt.title('Rolling Mean & Deviation')\n# plt.show()\n plt.show(block=False)\n \n #Perform Dickey-Fuller test:\n print('Results Of Dickey-Fuller Test')\n tstest=adfuller(timeseries['MONSOON'],autolag='AIC')\n tsoutput=pd.Series(tstest[0:4],index=['Test Statistcs','P-value','#Lags used',\"#Obs. used\"])\n #Test Statistics should be less than the Critical Value for Stationarity\n #lesser the p-value, greater the stationarity\n # print(list(dftest))\n for key,value in tstest[4].items():\n tsoutput['Critical Value (%s)'%key]=value\n print((tsoutput))",
"_____no_output_____"
],
[
"test_stationary(indexedDataset)",
"_____no_output_____"
]
],
[
[
"- There are 2 major reasons behind non-stationaruty of a TS:\n- - Trend – varying mean over time. For eg, in this case we saw that on average, the number of passengers was growing over time.\n- - Seasonality – variations at specific time-frames. eg people might have a tendency to buy cars in a particular month because of pay increment or festivals.",
"_____no_output_____"
],
[
"## Indexed Dataset Logscale",
"_____no_output_____"
]
],
[
[
"indexedDataset_logscale=np.log(indexedDataset)\ntest_stationary(indexedDataset_logscale)",
"_____no_output_____"
]
],
[
[
"## Dataset Log Minus Moving Average (dl_ma)",
"_____no_output_____"
]
],
[
[
"rolmeanlog=indexedDataset_logscale.rolling(window=12).mean()\ndl_ma=indexedDataset_logscale-rolmeanlog\ndl_ma.head(12)",
"_____no_output_____"
],
[
"dl_ma.dropna(inplace=True)\ndl_ma.head(12)",
"_____no_output_____"
],
[
"test_stationary(dl_ma)",
"_____no_output_____"
]
],
[
[
"## Exponential Decay Weighted Average (edwa)",
"_____no_output_____"
]
],
[
[
"edwa=indexedDataset_logscale.ewm(halflife=12,min_periods=0,adjust=True).mean()\nplt.plot(indexedDataset_logscale)\nplt.plot(edwa,color='red')",
"_____no_output_____"
]
],
[
[
"## Dataset Logscale Minus Moving Exponential Decay Average (dlmeda)",
"_____no_output_____"
]
],
[
[
"dlmeda=indexedDataset_logscale-edwa\ntest_stationary(dlmeda)",
"_____no_output_____"
]
],
[
[
"## Eliminating Trend and Seasonality",
"_____no_output_____"
],
[
"- Differencing – taking the differece with a particular time lag\n- Decomposition – modeling both trend and seasonality and removing them from the model.",
"_____no_output_____"
],
[
"# Differencing",
"_____no_output_____"
],
[
"## Dataset Log Div Shifting (dlds)",
"_____no_output_____"
]
],
[
[
"#Before Shifting\nindexedDataset_logscale.head()",
"_____no_output_____"
],
[
"#After Shifting\nindexedDataset_logscale.shift().head()",
"_____no_output_____"
],
[
"dlds=indexedDataset_logscale-indexedDataset_logscale.shift()\ndlds.dropna(inplace=True)\ntest_stationary(dlds)",
"_____no_output_____"
]
],
[
[
"# Decomposition",
"_____no_output_____"
]
],
[
[
"from statsmodels.tsa.seasonal import seasonal_decompose\ndecompostion= seasonal_decompose(indexedDataset_logscale,freq=10)\n\ntrend=decompostion.trend\nseasonal=decompostion.seasonal\nresidual=decompostion.resid\n\nplt.subplot(411)\nplt.plot(indexedDataset_logscale,label='Original')\nplt.legend(loc='best')\n\nplt.subplot(412)\nplt.plot(trend,label='Trend')\nplt.legend(loc='best')\n\nplt.subplot(413)\nplt.plot(seasonal,label='Seasonal')\nplt.legend(loc='best')\n\nplt.subplot(414)\nplt.plot(residual,label='Residual')\nplt.legend(loc='best')\n\nplt.tight_layout() #To Show Multiple Grpahs In One Output, Use plt.subplot(abc)",
"_____no_output_____"
]
],
[
[
"- Here trend, seasonality are separated out from data and we can model the residuals. Lets check stationarity of residuals:",
"_____no_output_____"
]
],
[
[
"decomposedlogdata=residual\ndecomposedlogdata.dropna(inplace=True)\ntest_stationary(decomposedlogdata)",
"_____no_output_____"
]
],
[
[
"# Forecasting a Time Series",
"_____no_output_____"
],
[
"- ARIMA stands for Auto-Regressive Integrated Moving Averages. The ARIMA forecasting for a stationary time series is nothing but a linear (like a linear regression) equation. The predictors depend on the parameters (p,d,q) of the ARIMA model:\n\n- - Number of AR (Auto-Regressive) terms (p): AR terms are just lags of dependent variable. For instance if p is 5, the predictors for x(t) will be x(t-1)….x(t-5).\n- - Number of MA (Moving Average) terms (q): MA terms are lagged forecast errors in prediction equation. For instance if q is 5, the predictors for x(t) will be e(t-1)….e(t-5) where e(i) is the difference between the moving average at ith instant and actual value.\n- - Number of Differences (d): These are the number of nonseasonal differences, i.e. in this case we took the first order difference. So either we can pass that variable and put d=0 or pass the original variable and put d=1. Both will generate same results.\n\n\n- An importance concern here is how to determine the value of ‘p’ and ‘q’. We use two plots to determine these numbers.\n\n- - Autocorrelation Function (ACF): It is a measure of the correlation between the the TS with a lagged version of itself-. For instance at lag 5, ACF would compare series at time instant ‘t1’…’t2’ with series at instant ‘t1-5’…’t2-5’ (t1-5 and t2 being end points).\n- - Partial Autocorrelation Function (PACF): This measures the correlation between the TS with a lagged version of itself but after eliminating the variations already explained by the intervening comparisons. Eg at lag 5, it will check the correlation but remove the effects already explained by lags 1 to 4.",
"_____no_output_____"
],
[
"## ACF & PACF Plots",
"_____no_output_____"
]
],
[
[
"from statsmodels.tsa.stattools import acf,pacf\nlag_acf=acf(dlds,nlags=20)\nlag_pacf=pacf(dlds,nlags=20,method='ols')\n\nplt.subplot(121)\nplt.plot(lag_acf)\nplt.axhline(y=0, linestyle='--',color='gray')\nplt.axhline(y=1.96/np.sqrt(len(dlds)),linestyle='--',color='gray')\nplt.axhline(y=-1.96/np.sqrt(len(dlds)),linestyle='--',color='gray')\nplt.title('AutoCorrelation Function')\n\nplt.subplot(122)\nplt.plot(lag_pacf)\nplt.axhline(y=0, linestyle='--',color='gray')\nplt.axhline(y=1.96/np.sqrt(len(dlds)),linestyle='--',color='gray')\nplt.axhline(y=-1.96/np.sqrt(len(dlds)),linestyle='--',color='gray')\nplt.title('PartialAutoCorrelation Function')\n\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"- In this plot, the two dotted lines on either sides of 0 are the confidence interevals. These can be used to determine the ‘p’ and ‘q’ values as:\n\n- - p – The lag value where the PACF chart crosses the upper confidence interval for the first time. If we notice closely, in this case p=2.\n- - q – The lag value where the ACF chart crosses the upper confidence interval for the first time. If we notice closely, in this case q=2.",
"_____no_output_____"
]
],
[
[
"from statsmodels.tsa.arima_model import ARIMA\n\nmodel=ARIMA(indexedDataset_logscale,order=(5,1,0))\nresults_AR=model.fit(disp=-1)\nplt.plot(dlds)\nplt.plot(results_AR.fittedvalues,color='red')\nplt.title('RSS: %.4f'%sum((results_AR.fittedvalues-dlds['MONSOON'])**2))\nprint('Plotting AR Model')",
"_____no_output_____"
],
[
"model = ARIMA(indexedDataset_logscale, order=(0, 1, 2)) #0,1,2\nresults_MA = model.fit(disp=-1) \nplt.plot(dlds)\nplt.plot(results_MA.fittedvalues, color='red')\nplt.title('RSS: %.4f'%sum((results_MA.fittedvalues-dlds['MONSOON'])**2))\nprint('Plotting MA Model')",
"_____no_output_____"
],
[
"model = ARIMA(indexedDataset_logscale, order=(5, 1, 2)) \nresults_ARIMA = model.fit(disp=-1) \nplt.plot(dlds)\nplt.plot(results_ARIMA.fittedvalues, color='red')\nplt.title('RSS: %.4f'%sum((results_ARIMA.fittedvalues-dlds['MONSOON'])**2))\nprint('Plotting Combined Model')",
"_____no_output_____"
]
],
[
[
"# Taking it back to original scale from residual scale",
"_____no_output_____"
]
],
[
[
"#storing the predicted results as a separate series\npredictions_ARIMA_diff = pd.Series(results_ARIMA.fittedvalues, copy=True)\npredictions_ARIMA_diff.head()",
"_____no_output_____"
]
],
[
[
"- Notice that these start from ‘1949-02-01’ and not the first month. Why? This is because we took a lag by 1 and first element doesn’t have anything before it to subtract from. The way to convert the differencing to log scale is to add these differences consecutively to the base number. An easy way to do it is to first determine the cumulative sum at index and then add it to the base number.",
"_____no_output_____"
]
],
[
[
"#convert to cummuative sum\npredictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum()\npredictions_ARIMA_diff_cumsum",
"_____no_output_____"
],
[
"predictions_ARIMA_log = pd.Series(indexedDataset_logscale['MONSOON'].ix[0], index=indexedDataset_logscale.index)\npredictions_ARIMA_log",
"_____no_output_____"
],
[
"predictions_ARIMA_log = predictions_ARIMA_log.add(predictions_ARIMA_diff_cumsum,fill_value=0)\npredictions_ARIMA_log",
"_____no_output_____"
]
],
[
[
"- Here the first element is base number itself and from there on the values cumulatively added.",
"_____no_output_____"
]
],
[
[
"#Last step is to take the exponent and compare with the original series.\npredictions_ARIMA = np.exp(predictions_ARIMA_log)\nplt.plot(indexedDataset)\nplt.plot(predictions_ARIMA)\nplt.title('RMSE: %.4f'% np.sqrt(sum((predictions_ARIMA-indexedDataset['MONSOON'])**2)/len(indexedDataset)))",
"_____no_output_____"
]
],
[
[
"- Finally we have a forecast at the original scale.",
"_____no_output_____"
]
],
[
[
"results_ARIMA.plot_predict(1,26)\n\n#start = !st month\n#end = 10yrs forcasting = 144+12*10 = 264th month\n\n#Two models corresponds to AR & MA",
"_____no_output_____"
],
[
"x=results_ARIMA.forecast(steps=5)\nprint(x)\n#values in residual equivalent",
"_____no_output_____"
],
[
"for i in range(0,5):\n print(x[0][i],end='')\n print('\\t',x[1][i],end='')\n print('\\t',x[2][i])",
"_____no_output_____"
],
[
"np.exp(results_ARIMA.forecast(steps=5)[0])",
"_____no_output_____"
],
[
"predictions_ARIMA_diff = pd.Series(results_ARIMA.forecast(steps=5)[0], copy=True)\npredictions_ARIMA_diff.head()",
"_____no_output_____"
],
[
"predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum()\npredictions_ARIMA_diff_cumsum.head()",
"_____no_output_____"
],
[
"predictions_ARIMA_log=[]\nfor i in range(0,len(predictions_ARIMA_diff_cumsum)):\n predictions_ARIMA_log.append(predictions_ARIMA_diff_cumsum[i]+3.411478)\npredictions_ARIMA_log",
"_____no_output_____"
],
[
"#Last step is to take the exponent and compare with the original series.\npredictions_ARIMA = np.exp(predictions_ARIMA_log)\nplt.subplot(121)\nplt.plot(indexedDataset)\nplt.subplot(122)\nplt.plot(predictions_ARIMA)\nplt.tight_layout()\n# plt.title('RMSE: %.4f'% np.sqrt(sum((predictions_ARIMA-indexedDataset['MONSOON'])**2)/len(indexedDataset)))",
"_____no_output_____"
],
[
"np.exp(predictions_ARIMA_log)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7aedaae38958aac48068501b626ab4bdf317499 | 278,674 | ipynb | Jupyter Notebook | first_analysis/plot.ipynb | Brook1711/openda1 | 1d67912083ecf60b04daa6d9cf377339d179b1aa | [
"Apache-2.0"
] | null | null | null | first_analysis/plot.ipynb | Brook1711/openda1 | 1d67912083ecf60b04daa6d9cf377339d179b1aa | [
"Apache-2.0"
] | null | null | null | first_analysis/plot.ipynb | Brook1711/openda1 | 1d67912083ecf60b04daa6d9cf377339d179b1aa | [
"Apache-2.0"
] | 1 | 2021-07-18T16:01:56.000Z | 2021-07-18T16:01:56.000Z | 33.350168 | 14,547 | 0.398993 | [
[
[
"import pandas as pd\nimport json \nimport numpy as np\nimport ast\nfrom datetime import datetime\nimport plotly.graph_objs as go\nfrom plotly.offline import plot\nimport plotly.offline as offline\nfrom pandas.core.indexes import interval\nimport plotly.figure_factory as ff\npyolt=plot\nimport plotly.express as px\nimport math",
"_____no_output_____"
],
[
"from main import data_analysis",
"_____no_output_____"
],
[
"df = pd.read_excel('./data/data.xlsx') \ndf_junior = pd.read_excel('./data/junior.xlsx') \ndf_senior = pd.read_excel('./data/senior.xlsx') \ndata_entity = data_analysis(df)\ndata_entity_junior = data_analysis(df = df_junior, name = 'junior')\ndata_entity_senior = data_analysis(df = df_senior, name = 'senior')",
"init complete\ninit complete\ninit complete\n"
],
[
"# s1=np.random.RandomState(12)\n# #柯西分布\n# x1=s1.standard_cauchy(200)-4\n# #泊松分布\n# x2=s1.uniform(1,10,200)\n# #Gamma分布\n# x3=s1.standard_gamma(3,200)+4\n# #指数分布\n# x4=s1.exponential(3,200)+8\nx1 = list(data_entity.df.loc[:,'interval'])\nx2 = list(data_entity_junior.df.loc[:,'interval'])\nx3 = list(data_entity_senior.df.loc[:,'interval'])\nlayout={\"title\": \"学生用时分布\", \n \"xaxis_title\": \"学生用时,单位秒\",\n \"yaxis_title\": \"学生个数\",\n # x轴坐标倾斜60度\n \"xaxis\": {\"tickangle\": 60}\n }\n\n#数据组\nhist_data=[x1,x2,x3]\n\ngroup_labels=['all','junior','senior']\n\nfig=ff.create_distplot(hist_data,group_labels,bin_size=100,histnorm = 'probability')\nplot(fig,filename='./plot/时间分布直方图.html')\noffline.iplot(fig) ",
"_____no_output_____"
],
[
"data1 = go.Bar(x = list(range(data_entity.problem_num)), y = [len(group) for group in data_entity.addition_list], name = 'all')\ndata2 = go.Bar(x = list(range(data_entity_junior.problem_num)), y = [len(group) for group in data_entity_junior.addition_list], name = 'junior') \ndata3 = go.Bar(x = list(range(data_entity_senior.problem_num)), y = [len(group) for group in data_entity_senior.addition_list], name = 'senior') \n\n\n\nlayout={\"title\": \"不同题目的编码数量\", \n \"xaxis_title\": \"题目编号\",\n \"yaxis_title\": \"编码个数\",\n # x轴坐标倾斜60度\n \"xaxis\": {\"tickangle\": 60}\n }\nfig = go.Figure(data=[data1, data2, data3],layout=layout)\nplot(fig,filename=\"./plot/plot_problem.html\",auto_open=False,image='png',image_height=800,image_width=1500)\noffline.iplot(fig) ",
"_____no_output_____"
],
[
"data_entity.success_df",
"_____no_output_____"
],
[
"list(data_entity_junior.success_df['accuracy'])",
"_____no_output_____"
],
[
"data_entity_senior.success_df",
"_____no_output_____"
],
[
"data1 = go.Bar(x = data_entity.problem_num_list, y = list(data_entity.success_df['accuracy']), name = 'all')\ndata2 = go.Bar(x = data_entity_junior.problem_num_list, y = list(data_entity_junior.success_df['accuracy']), name = 'junior') \ndata3 = go.Bar(x = data_entity_senior.problem_num_list, y = list(data_entity_senior.success_df['accuracy']), name = 'senior') \n\n\n\nlayout={\"title\": \"不同题目的正确率\", \n \"xaxis_title\": \"题目编号\",\n \"yaxis_title\": \"正确率\",\n # x轴坐标倾斜60度\n \"xaxis\": {\"tickangle\": 20}\n }\nfig = go.Figure(data=[data1, data2, data3],layout=layout)\nplot(fig,filename=\"./plot/plot_problem_accuracy.html\",auto_open=False,image='png',image_height=800,image_width=1500)\noffline.iplot(fig) ",
"_____no_output_____"
],
[
"data1",
"_____no_output_____"
],
[
"data_entity.row_num",
"_____no_output_____"
],
[
"data_entity_junior.row_num",
"_____no_output_____"
],
[
"data_entity_senior.row_num",
"_____no_output_____"
]
],
[
[
"#### 第10题(index=9)正确答案分布\n",
"_____no_output_____"
]
],
[
[
"x=[str(['02_09', '05_06']),str(['02_05', '06_09']),str(['02_06', '05_09'])]\ndata1 = go.Bar(x = x, y = [480/662,68/662,39/662], name = 'all')\ndata2 = go.Bar(x = x, y = [158/267,37/267,4/267], name = 'junior') \ndata3 = go.Bar(x = x, y = [322/395,31/395,24/395], name = 'senior') \n\n\n\nlayout={\"title\": \"第10题(index=9)的正确答案分布,浇花(1)\", \n \"xaxis_title\": \"答案编码\",\n \"yaxis_title\": \"分布率\",\n # x轴坐标倾斜60度\n \"xaxis\": {\"tickangle\": 0}\n }\nfig = go.Figure(data=[data1, data2, data3],layout=layout)\nplot(fig,filename=\"./plot/plot_problem_浇花(1)_accuracy.html\",auto_open=False,image='png',image_height=800,image_width=1500)\noffline.iplot(fig) ",
"_____no_output_____"
],
[
"x=[str(['2_16', '6_15', '12_14']),str(['2_15', '6_16', '12_14']),str(['2_12', '6_14', '15_16'])\\\n ,str(['2_12', '6_15', '14_16']),str(['2_14', '6_12', '15_16']),str(['2_16', '6_15', '12_14'])\\\n ,str(['2_16', '6_14', '12_15']),str(['2_15', '6_14', '12_16']),str(['2_14', '6_16', '12_15'])\\\n ,str(['2_15', '6_12', '14_16']),str(['2_6', '12_14', '15_16']),str(['2_6', '12_16', '14_15'])\\\n ,str(['2_6', '12_15', '14_16']),str(['2_16', '6_12', '14_15']),str(['2_12', '6_16', '14_15'])]\ndata1 = go.Bar(x = x, y = np.array([225,60,51\\\n ,29,25,33\\\n ,15,15,8\\\n ,7,3,2\\\n ,0,0,0])/data_entity.row_num, name = 'all')\ndata2 = go.Bar(x = x, y = np.array([63,19,26\\\n ,4,15,7\\\n ,4,6,2\\\n ,2,0,0\\\n ,0,0,0])/data_entity_junior.row_num, name = 'junior') \ndata3 = go.Bar(x = x, y = np.array([162,41,25\\\n ,25,10,15\\\n ,11,9,6\\\n ,5,3,2\\\n ,0,0,0])/data_entity_senior.row_num, name = 'senior') \n\n\n\nlayout={\"title\": \"第11题(index=10)的正确答案分布,浇花(2)\", \n \"xaxis_title\": \"答案编码\",\n \"xaxis_range\": [0,6000],\n \"yaxis_title\": \"分布率\",\n # x轴坐标倾斜60度\n \"xaxis\": {\"tickangle\": 60}\n }\nfig = go.Figure(data=[data1, data2, data3],layout=layout)\nplot(fig,filename=\"./plot/plot_problem_浇花(2)_accuracy.html\",auto_open=False,image='png',image_height=800,image_width=1500)\noffline.iplot(fig) ",
"_____no_output_____"
],
[
"list(np.array([1,2,3])/10)",
"_____no_output_____"
],
[
"### plot index =18 \ndf_18 = pd.read_excel('./output/default/18_count.xlsx')\nverify_list = list(pd.read_excel('./output/default/18_count.xlsx').iloc[:,1])\nnot_in_list = []\nfor i in range(8):\n if int(bin(i)[2:].replace('1','2')) not in verify_list:\n not_in_list.append(int(bin(i)[2:].replace('1','2')))\n# print(str(int(bin(i)[2:].replace('1','2'))).zfill(6))\ndefult_pd = list(pd.read_excel('./output/default/18_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\nx = [str(int(float)).zfill(3) for float in list(defult_pd.loc[:,'list'])]\nx += not_in_list\nx",
"_____no_output_____"
],
[
"defult_pd = list(pd.read_excel('./output/default/18_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\ndefult_pd = pd.DataFrame(index = [str(int(float)).zfill(3) for float in list(defult_pd.loc[:,'list'])],data={'count':list(defult_pd.loc[:,'count']),'success':list(defult_pd.loc[:,'success'])})\n\n\njunior_pd = list(pd.read_excel('./output/junior/18_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\njunior_pd = pd.DataFrame(index = [str(int(float)).zfill(3) for float in list(junior_pd.loc[:,'list'])],data={'count':list(junior_pd.loc[:,'count']),'success':list(junior_pd.loc[:,'success'])})\n\n\nsenior_pd = list(pd.read_excel('./output/senior/18_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\nsenior_pd = pd.DataFrame(index = [str(int(float)).zfill(3) for float in list(senior_pd.loc[:,'list'])],data={'count':list(senior_pd.loc[:,'count']),'success':list(senior_pd.loc[:,'success'])})\n",
"_____no_output_____"
],
[
"y1 =[]\ny2 = []\ny3 = []\nfor ans in x:\n if ans in list(defult_pd.index):\n y1.append(defult_pd.loc[ans,'count'])\n else:\n y1.append(0)\nfor ans in x:\n if ans in list(junior_pd.index):\n y2.append(junior_pd.loc[ans,'count'])\n else:\n y2.append(0)\n \nfor ans in x:\n if ans in list(senior_pd.index):\n y3.append(senior_pd.loc[ans,'count'])\n else:\n y3.append(0)",
"_____no_output_____"
],
[
"#### plot index 18\n\n\ndata1 = go.Bar(x = x, y = np.array(y1)/data_entity.row_num, name = 'all')\ndata2 = go.Bar(x = x, y = np.array(y2)/data_entity_junior.row_num, name = 'junior') \ndata3 = go.Bar(x = x, y = np.array(y3)/data_entity_senior.row_num, name = 'senior') \n\n\n\nlayout={\"title\": \"第16题(index=18)的正确答案分布,供水系统(1)\", \n \"xaxis_title\": \"答案编码\",\n \"yaxis_title\": \"分布率\",\n # x轴坐标倾斜60度\n \"xaxis\": {\"tickangle\": 60}\n }\nfig = go.Figure(data=[data1, data2, data3],layout=layout)\nplot(fig,filename=\"./plot/plot_problem_供水系统(1)_accuracy.html\",auto_open=False,image='png',image_height=800,image_width=1500)\noffline.iplot(fig) ",
"_____no_output_____"
],
[
"df_19 = pd.read_excel('./output/default/19_count.xlsx')\nverify_list = list(pd.read_excel('./output/default/19_count.xlsx').iloc[:,1])\nnot_in_list = []\nfor i in range(64):\n if int(bin(i)[2:].replace('1','2')) not in verify_list:\n not_in_list.append(int(bin(i)[2:].replace('1','2')))\n# print(str(int(bin(i)[2:].replace('1','2'))).zfill(6))\ndefult_pd = list(pd.read_excel('./output/default/19_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\nx = [str(int(float)).zfill(6) for float in list(defult_pd.loc[:,'list'])]\nx += not_in_list\n",
"_____no_output_____"
],
[
"defult_pd = list(pd.read_excel('./output/default/19_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\ndefult_pd = pd.DataFrame(index = [str(int(float)).zfill(6) for float in list(defult_pd.loc[:,'list'])],data={'count':list(defult_pd.loc[:,'count']),'success':list(defult_pd.loc[:,'success'])})\n\n\njunior_pd = list(pd.read_excel('./output/junior/19_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\njunior_pd = pd.DataFrame(index = [str(int(float)).zfill(6) for float in list(junior_pd.loc[:,'list'])],data={'count':list(junior_pd.loc[:,'count']),'success':list(junior_pd.loc[:,'success'])})\n\n\nsenior_pd = list(pd.read_excel('./output/senior/19_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\nsenior_pd = pd.DataFrame(index = [str(int(float)).zfill(6) for float in list(senior_pd.loc[:,'list'])],data={'count':list(senior_pd.loc[:,'count']),'success':list(senior_pd.loc[:,'success'])})\n",
"_____no_output_____"
],
[
"y1 =[]\ny2 = []\ny3 = []\nfor ans in x:\n if ans in list(defult_pd.index):\n y1.append(defult_pd.loc[ans,'count'])\n else:\n y1.append(0)\nfor ans in x:\n if ans in list(junior_pd.index):\n y2.append(junior_pd.loc[ans,'count'])\n else:\n y2.append(0)\n \nfor ans in x:\n if ans in list(senior_pd.index):\n y3.append(senior_pd.loc[ans,'count'])\n else:\n y3.append(0)",
"_____no_output_____"
],
[
"#### plot index 19\n\n\ndata1 = go.Bar(x = x, y = np.array(y1)/data_entity.row_num, name = 'all')\ndata2 = go.Bar(x = x, y = np.array(y2)/data_entity_junior.row_num, name = 'junior') \ndata3 = go.Bar(x = x, y = np.array(y3)/data_entity_senior.row_num, name = 'senior') \n\n\n\nlayout={\"title\": \"第17题(index=19)的正确答案分布,供水系统(2)\", \n \"xaxis_title\": \"答案编码\",\n \"yaxis_title\": \"分布率\",\n # x轴坐标倾斜60度\n \"xaxis\": {\"tickangle\": 60}\n }\nfig = go.Figure(data=[data1, data2, data3],layout=layout)\nplot(fig,filename=\"./plot/plot_problem_供水系统(2)_accuracy.html\",auto_open=False,image='png',image_height=800,image_width=1500)\noffline.iplot(fig) ",
"_____no_output_____"
]
],
[
[
"#### 寻找第19题所有的正确答案",
"_____no_output_____"
]
],
[
[
"# 所有可能的五角星(0,a)和三角形(1,b)组合\nseq_list = []\nfor i in range(8):\n for j in range(int(math.pow(2,i+1))):\n temp=str(bin(j))[2:].zfill(i+1).replace('0','a')\n temp = temp.replace('1', 'b')\n seq_list.append(temp)\n# 所有可能的长方形(1)和圆形(0)组合\ntrans_list = []\nfor i in range(3):\n for j in range(int(math.pow(2,i+1))):\n trans_list.append(str(bin(j))[2:].zfill(i+1))\n# 正确序列 \nverify_str = '10100010010'",
"_____no_output_____"
],
[
"right_ans = []\ncnt = 0\nfor seq in seq_list:\n for star in trans_list:\n for trian in trans_list:\n cnt +=1\n if seq.replace('a', star).replace('b', trian) == verify_str:\n right_ans.append([seq.replace('a','0').replace('b','1'), star, trian])\nright_ans",
"_____no_output_____"
],
[
"### plot index =22 \n\ndefult_pd = list(pd.read_excel('./output/default/22_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\nx = [str_ for str_ in list(defult_pd.loc[:,'list'])]\nx ",
"_____no_output_____"
],
[
"defult_pd = list(pd.read_excel('./output/default/22_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\ndefult_pd = pd.DataFrame(index = [str_ for str_ in list(defult_pd.loc[:,'list'])],data={'count':list(defult_pd.loc[:,'count']),'success':list(defult_pd.loc[:,'success'])})\n\n\njunior_pd = list(pd.read_excel('./output/junior/22_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\njunior_pd = pd.DataFrame(index = [str_ for str_ in list(junior_pd.loc[:,'list'])],data={'count':list(junior_pd.loc[:,'count']),'success':list(junior_pd.loc[:,'success'])})\n\n\nsenior_pd = list(pd.read_excel('./output/senior/22_count.xlsx').groupby('success'))[1][1].sort_values(by = ['count'], ascending = False)\nsenior_pd = pd.DataFrame(index = [str_ for str_ in list(senior_pd.loc[:,'list'])],data={'count':list(senior_pd.loc[:,'count']),'success':list(senior_pd.loc[:,'success'])})\n",
"_____no_output_____"
],
[
"data1 = go.Bar(x = x, y = np.array(y1)/data_entity.row_num, name = 'all')\ndata2 = go.Bar(x = x, y = np.array(y2)/data_entity_junior.row_num, name = 'junior') \ndata3 = go.Bar(x = x, y = np.array(y3)/data_entity_senior.row_num, name = 'senior') \n\n\n\nlayout={\"title\": \"第19题(index=22)的正确答案分布,对应的形状(2)\", \n \"xaxis_title\": \"答案编码\",\n \"yaxis_title\": \"分布率\",\n # x轴坐标倾斜60度\n \"xaxis\": {\"tickangle\": 20}\n }\nfig = go.Figure(data=[data1, data2, data3],layout=layout)\nplot(fig,filename=\"./plot/plot_problem_对应的形状(2)_accuracy.html\",auto_open=False,image='png',image_height=800,image_width=1500)\noffline.iplot(fig) ",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e7aee53fd07d6cdc971029f69a4bda1912c649a4 | 264,436 | ipynb | Jupyter Notebook | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb | soltaniehha/deep-learning-specialization-coursera | 5374ce67ade927a3744fbcce91d44ae06042cbb2 | [
"MIT"
] | 3 | 2019-12-14T04:48:44.000Z | 2020-02-13T18:35:17.000Z | 02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb | ashishgupta1350/deep-learning-specialization-coursera | 8fd8ad74a9b2d8321bb0a701c5c0f3ec4abad144 | [
"MIT"
] | 1 | 2020-01-10T08:21:59.000Z | 2020-01-10T08:21:59.000Z | Coursera/02-Improving-Deep-Neural-Networks/week1/Programming-Assignments/Initialization/Initialization.ipynb | lev1khachatryan/ASDS_DL | ca00ce7b4cfb722f9bce545820cdb661ff8b643e | [
"MIT"
] | 2 | 2020-09-11T20:45:37.000Z | 2020-12-14T01:26:32.000Z | 234.63709 | 56,148 | 0.904177 | [
[
[
"# Table of Contents\n <p><div class=\"lev1 toc-item\"><a href=\"#Initialization\" data-toc-modified-id=\"Initialization-1\"><span class=\"toc-item-num\">1 </span>Initialization</a></div><div class=\"lev2 toc-item\"><a href=\"#1---Neural-Network-model\" data-toc-modified-id=\"1---Neural-Network-model-11\"><span class=\"toc-item-num\">1.1 </span>1 - Neural Network model</a></div><div class=\"lev2 toc-item\"><a href=\"#2---Zero-initialization\" data-toc-modified-id=\"2---Zero-initialization-12\"><span class=\"toc-item-num\">1.2 </span>2 - Zero initialization</a></div><div class=\"lev2 toc-item\"><a href=\"#3---Random-initialization\" data-toc-modified-id=\"3---Random-initialization-13\"><span class=\"toc-item-num\">1.3 </span>3 - Random initialization</a></div><div class=\"lev2 toc-item\"><a href=\"#4---He-initialization\" data-toc-modified-id=\"4---He-initialization-14\"><span class=\"toc-item-num\">1.4 </span>4 - He initialization</a></div><div class=\"lev2 toc-item\"><a href=\"#5---Conclusions\" data-toc-modified-id=\"5---Conclusions-15\"><span class=\"toc-item-num\">1.5 </span>5 - Conclusions</a></div>",
"_____no_output_____"
],
[
"# Initialization\n\nWelcome to the first assignment of \"Improving Deep Neural Networks\". \n\nTraining your neural network requires specifying an initial value of the weights. A well chosen initialization method will help learning. \n\nIf you completed the previous course of this specialization, you probably followed our instructions for weight initialization, and it has worked out so far. But how do you choose the initialization for a new neural network? In this notebook, you will see how different initializations lead to different results. \n\nA well chosen initialization can:\n- Speed up the convergence of gradient descent\n- Increase the odds of gradient descent converging to a lower training (and generalization) error \n\nTo get started, run the following cell to load the packages and the planar dataset you will try to classify.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nimport sklearn.datasets\nfrom init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation\nfrom init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n# load image dataset: blue/red dots in circles\ntrain_X, train_Y, test_X, test_Y = load_dataset()",
"_____no_output_____"
]
],
[
[
"You would like a classifier to separate the blue dots from the red dots.",
"_____no_output_____"
],
[
"## 1 - Neural Network model ",
"_____no_output_____"
],
[
"You will use a 3-layer neural network (already implemented for you). Here are the initialization methods you will experiment with: \n- *Zeros initialization* -- setting `initialization = \"zeros\"` in the input argument.\n- *Random initialization* -- setting `initialization = \"random\"` in the input argument. This initializes the weights to large random values. \n- *He initialization* -- setting `initialization = \"he\"` in the input argument. This initializes the weights to random values scaled according to a paper by He et al., 2015. \n\n**Instructions**: Please quickly read over the code below, and run it. In the next part you will implement the three initialization methods that this `model()` calls.",
"_____no_output_____"
]
],
[
[
"def model(X, Y, learning_rate = 0.01, num_iterations = 15000, print_cost = True, initialization = \"he\"):\n \"\"\"\n Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.\n \n Arguments:\n X -- input data, of shape (2, number of examples)\n Y -- true \"label\" vector (containing 0 for red dots; 1 for blue dots), of shape (1, number of examples)\n learning_rate -- learning rate for gradient descent \n num_iterations -- number of iterations to run gradient descent\n print_cost -- if True, print the cost every 1000 iterations\n initialization -- flag to choose which initialization to use (\"zeros\",\"random\" or \"he\")\n \n Returns:\n parameters -- parameters learnt by the model\n \"\"\"\n \n grads = {}\n costs = [] # to keep track of the loss\n m = X.shape[1] # number of examples\n layers_dims = [X.shape[0], 10, 5, 1]\n \n # Initialize parameters dictionary.\n if initialization == \"zeros\":\n parameters = initialize_parameters_zeros(layers_dims)\n elif initialization == \"random\":\n parameters = initialize_parameters_random(layers_dims)\n elif initialization == \"he\":\n parameters = initialize_parameters_he(layers_dims)\n\n # Loop (gradient descent)\n\n for i in range(0, num_iterations):\n\n # Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.\n a3, cache = forward_propagation(X, parameters)\n \n # Loss\n cost = compute_loss(a3, Y)\n\n # Backward propagation.\n grads = backward_propagation(X, Y, cache)\n \n # Update parameters.\n parameters = update_parameters(parameters, grads, learning_rate)\n \n # Print the loss every 1000 iterations\n if print_cost and i % 1000 == 0:\n print(\"Cost after iteration {}: {}\".format(i, cost))\n costs.append(cost)\n \n # plot the loss\n plt.plot(costs)\n plt.ylabel('cost')\n plt.xlabel('iterations (per hundreds)')\n plt.title(\"Learning rate =\" + str(learning_rate))\n plt.show()\n \n return parameters",
"_____no_output_____"
]
],
[
[
"## 2 - Zero initialization\n\nThere are two types of parameters to initialize in a neural network:\n- the weight matrices $(W^{[1]}, W^{[2]}, W^{[3]}, ..., W^{[L-1]}, W^{[L]})$\n- the bias vectors $(b^{[1]}, b^{[2]}, b^{[3]}, ..., b^{[L-1]}, b^{[L]})$\n\n**Exercise**: Implement the following function to initialize all parameters to zeros. You'll see later that this does not work well since it fails to \"break symmetry\", but lets try it anyway and see what happens. Use np.zeros((..,..)) with the correct shapes.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters_zeros \n\ndef initialize_parameters_zeros(layers_dims):\n \"\"\"\n Arguments:\n layer_dims -- python array (list) containing the size of each layer.\n \n Returns:\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])\n b1 -- bias vector of shape (layers_dims[1], 1)\n ...\n WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])\n bL -- bias vector of shape (layers_dims[L], 1)\n \"\"\"\n \n parameters = {}\n L = len(layers_dims) # number of layers in the network\n \n for l in range(1, L):\n ### START CODE HERE ### (≈ 2 lines of code)\n parameters['W' + str(l)] = np.zeros((layers_dims[l], layers_dims[l-1]))\n parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))\n ### END CODE HERE ###\n return parameters",
"_____no_output_____"
],
[
"parameters = initialize_parameters_zeros([3,2,1])\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[0. 0. 0.]\n [0. 0. 0.]]\nb1 = [[0.]\n [0.]]\nW2 = [[0. 0.]]\nb2 = [[0.]]\n"
]
],
[
[
"**Expected Output**:\n\n<table> \n <tr>\n <td>\n **W1**\n </td>\n <td>\n [[ 0. 0. 0.]\n [ 0. 0. 0.]]\n </td>\n </tr>\n <tr>\n <td>\n **b1**\n </td>\n <td>\n [[ 0.]\n [ 0.]]\n </td>\n </tr>\n <tr>\n <td>\n **W2**\n </td>\n <td>\n [[ 0. 0.]]\n </td>\n </tr>\n <tr>\n <td>\n **b2**\n </td>\n <td>\n [[ 0.]]\n </td>\n </tr>\n\n</table> ",
"_____no_output_____"
],
[
"Run the following code to train your model on 15,000 iterations using zeros initialization.",
"_____no_output_____"
]
],
[
[
"parameters = model(train_X, train_Y, initialization = \"zeros\")\nprint (\"On the train set:\")\npredictions_train = predict(train_X, train_Y, parameters)\nprint (\"On the test set:\")\npredictions_test = predict(test_X, test_Y, parameters)",
"Cost after iteration 0: 0.6931471805599453\nCost after iteration 1000: 0.6931471805599453\nCost after iteration 2000: 0.6931471805599453\nCost after iteration 3000: 0.6931471805599453\nCost after iteration 4000: 0.6931471805599453\nCost after iteration 5000: 0.6931471805599453\nCost after iteration 6000: 0.6931471805599453\nCost after iteration 7000: 0.6931471805599453\nCost after iteration 8000: 0.6931471805599453\nCost after iteration 9000: 0.6931471805599453\nCost after iteration 10000: 0.6931471805599455\nCost after iteration 11000: 0.6931471805599453\nCost after iteration 12000: 0.6931471805599453\nCost after iteration 13000: 0.6931471805599453\nCost after iteration 14000: 0.6931471805599453\n"
]
],
[
[
"The performance is really bad, and the cost does not really decrease, and the algorithm performs no better than random guessing. Why? Lets look at the details of the predictions and the decision boundary:",
"_____no_output_____"
]
],
[
[
"print (\"predictions_train = \" + str(predictions_train))\nprint (\"predictions_test = \" + str(predictions_test))",
"predictions_train = [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0]]\npredictions_test = [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]\n"
],
[
"plt.title(\"Model with Zeros initialization\")\naxes = plt.gca()\naxes.set_xlim([-1.5,1.5])\naxes.set_ylim([-1.5,1.5])\nplot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)",
"_____no_output_____"
]
],
[
[
"The model is predicting 0 for every example. \n\nIn general, initializing all the weights to zero results in the network failing to break symmetry. This means that every neuron in each layer will learn the same thing, and you might as well be training a neural network with $n^{[l]}=1$ for every layer, and the network is no more powerful than a linear classifier such as logistic regression. ",
"_____no_output_____"
],
[
"<font color='blue'>\n**What you should remember**:\n- The weights $W^{[l]}$ should be initialized randomly to break symmetry. \n- It is however okay to initialize the biases $b^{[l]}$ to zeros. Symmetry is still broken so long as $W^{[l]}$ is initialized randomly. \n",
"_____no_output_____"
],
[
"## 3 - Random initialization\n\nTo break symmetry, lets intialize the weights randomly. Following random initialization, each neuron can then proceed to learn a different function of its inputs. In this exercise, you will see what happens if the weights are intialized randomly, but to very large values. \n\n**Exercise**: Implement the following function to initialize your weights to large random values (scaled by \\*10) and your biases to zeros. Use `np.random.randn(..,..) * 10` for weights and `np.zeros((.., ..))` for biases. We are using a fixed `np.random.seed(..)` to make sure your \"random\" weights match ours, so don't worry if running several times your code gives you always the same initial values for the parameters. ",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters_random\n\ndef initialize_parameters_random(layers_dims):\n \"\"\"\n Arguments:\n layer_dims -- python array (list) containing the size of each layer.\n \n Returns:\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])\n b1 -- bias vector of shape (layers_dims[1], 1)\n ...\n WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])\n bL -- bias vector of shape (layers_dims[L], 1)\n \"\"\"\n \n np.random.seed(3) # This seed makes sure your \"random\" numbers will be the as ours\n parameters = {}\n L = len(layers_dims) # integer representing the number of layers\n \n for l in range(1, L):\n ### START CODE HERE ### (≈ 2 lines of code)\n parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * 10\n parameters['b' + str(l)] = np.zeros((layers_dims[l],1))\n ### END CODE HERE ###\n\n return parameters",
"_____no_output_____"
],
[
"parameters = initialize_parameters_random([3, 2, 1])\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[ 17.88628473 4.36509851 0.96497468]\n [-18.63492703 -2.77388203 -3.54758979]]\nb1 = [[0.]\n [0.]]\nW2 = [[-0.82741481 -6.27000677]]\nb2 = [[0.]]\n"
]
],
[
[
"**Expected Output**:\n\n<table> \n <tr>\n <td>\n **W1**\n </td>\n <td>\n [[ 17.88628473 4.36509851 0.96497468]\n [-18.63492703 -2.77388203 -3.54758979]]\n </td>\n </tr>\n <tr>\n <td>\n **b1**\n </td>\n <td>\n [[ 0.]\n [ 0.]]\n </td>\n </tr>\n <tr>\n <td>\n **W2**\n </td>\n <td>\n [[-0.82741481 -6.27000677]]\n </td>\n </tr>\n <tr>\n <td>\n **b2**\n </td>\n <td>\n [[ 0.]]\n </td>\n </tr>\n\n</table> ",
"_____no_output_____"
],
[
"Run the following code to train your model on 15,000 iterations using random initialization.",
"_____no_output_____"
]
],
[
[
"parameters = model(train_X, train_Y, initialization = \"random\")\nprint (\"On the train set:\")\npredictions_train = predict(train_X, train_Y, parameters)\nprint (\"On the test set:\")\npredictions_test = predict(test_X, test_Y, parameters)",
"Cost after iteration 0: inf\nCost after iteration 1000: 0.6250884962121392\n"
]
],
[
[
"If you see \"inf\" as the cost after the iteration 0, this is because of numerical roundoff; a more numerically sophisticated implementation would fix this. But this isn't worth worrying about for our purposes. \n\nAnyway, it looks like you have broken symmetry, and this gives better results. than before. The model is no longer outputting all 0s. ",
"_____no_output_____"
]
],
[
[
"print (predictions_train)\nprint (predictions_test)",
"[[1 0 1 1 0 0 1 1 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 1\n 1 1 1 1 1 1 1 0 1 1 1 1 0 1 0 1 1 1 1 0 0 1 1 1 1 0 1 1 0 1 0 1 1 1 1 0\n 0 0 0 0 1 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1 0 1 1 0 1 0 1 1 0 1 1 0\n 1 0 1 1 0 0 1 0 0 1 1 0 1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 1 0 1 1 0 0 1 1 0\n 0 0 1 0 1 0 1 0 1 1 1 0 0 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 1 1 0 1 1 1\n 1 0 1 0 1 0 1 1 1 1 0 1 1 0 1 1 0 1 1 0 1 0 1 1 1 0 1 1 1 0 1 0 1 0 0 1\n 0 1 1 0 1 1 0 1 1 0 1 1 1 0 1 1 1 1 0 1 0 0 1 1 0 1 1 1 0 0 0 1 1 0 1 1\n 1 1 0 1 1 0 1 1 1 0 0 1 0 0 0 1 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 1\n 1 1 1 1 0 0 0 1 1 1 1 0]]\n[[1 1 1 1 0 1 0 1 1 0 1 1 1 0 0 0 0 1 0 1 0 0 1 0 1 0 1 1 1 1 1 0 0 0 0 1\n 0 1 1 0 0 1 1 1 1 1 0 1 1 1 0 1 0 1 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 0 1 0\n 1 1 1 1 1 0 1 0 0 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0]]\n"
],
[
"plt.title(\"Model with large random initialization\")\naxes = plt.gca()\naxes.set_xlim([-1.5,1.5])\naxes.set_ylim([-1.5,1.5])\nplot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)",
"_____no_output_____"
]
],
[
[
"**Observations**:\n- The cost starts very high. This is because with large random-valued weights, the last activation (sigmoid) outputs results that are very close to 0 or 1 for some examples, and when it gets that example wrong it incurs a very high loss for that example. Indeed, when $\\log(a^{[3]}) = \\log(0)$, the loss goes to infinity.\n- Poor initialization can lead to vanishing/exploding gradients, which also slows down the optimization algorithm. \n- If you train this network longer you will see better results, but initializing with overly large random numbers slows down the optimization.\n\n<font color='blue'>\n**In summary**:\n- Initializing weights to very large random values does not work well. \n- Hopefully intializing with small random values does better. The important question is: how small should be these random values be? Lets find out in the next part! ",
"_____no_output_____"
],
[
"## 4 - He initialization\n\nFinally, try \"He Initialization\"; this is named for the first author of He et al., 2015. (If you have heard of \"Xavier initialization\", this is similar except Xavier initialization uses a scaling factor for the weights $W^{[l]}$ of `sqrt(1./layers_dims[l-1])` where He initialization would use `sqrt(2./layers_dims[l-1])`.)\n\n**Exercise**: Implement the following function to initialize your parameters with He initialization.\n\n**Hint**: This function is similar to the previous `initialize_parameters_random(...)`. The only difference is that instead of multiplying `np.random.randn(..,..)` by 10, you will multiply it by $\\sqrt{\\frac{2}{\\text{dimension of the previous layer}}}$, which is what He initialization recommends for layers with a ReLU activation. ",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters_he\n\ndef initialize_parameters_he(layers_dims):\n \"\"\"\n Arguments:\n layer_dims -- python array (list) containing the size of each layer.\n \n Returns:\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])\n b1 -- bias vector of shape (layers_dims[1], 1)\n ...\n WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])\n bL -- bias vector of shape (layers_dims[L], 1)\n \"\"\"\n \n np.random.seed(3)\n parameters = {}\n L = len(layers_dims) - 1 # integer representing the number of layers\n \n for l in range(1, L + 1):\n ### START CODE HERE ### (≈ 2 lines of code)\n parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * (np.sqrt(2. / layers_dims[l-1]))\n parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))\n ### END CODE HERE ###\n \n return parameters",
"_____no_output_____"
],
[
"parameters = initialize_parameters_he([2, 4, 1])\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[ 1.78862847 0.43650985]\n [ 0.09649747 -1.8634927 ]\n [-0.2773882 -0.35475898]\n [-0.08274148 -0.62700068]]\nb1 = [[0.]\n [0.]\n [0.]\n [0.]]\nW2 = [[-0.03098412 -0.33744411 -0.92904268 0.62552248]]\nb2 = [[0.]]\n"
]
],
[
[
"**Expected Output**:\n\n<table> \n <tr>\n <td>\n **W1**\n </td>\n <td>\n [[ 1.78862847 0.43650985]\n [ 0.09649747 -1.8634927 ]\n [-0.2773882 -0.35475898]\n [-0.08274148 -0.62700068]]\n </td>\n </tr>\n <tr>\n <td>\n **b1**\n </td>\n <td>\n [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]]\n </td>\n </tr>\n <tr>\n <td>\n **W2**\n </td>\n <td>\n [[-0.03098412 -0.33744411 -0.92904268 0.62552248]]\n </td>\n </tr>\n <tr>\n <td>\n **b2**\n </td>\n <td>\n [[ 0.]]\n </td>\n </tr>\n\n</table> ",
"_____no_output_____"
],
[
"Run the following code to train your model on 15,000 iterations using He initialization.",
"_____no_output_____"
]
],
[
[
"parameters = model(train_X, train_Y, initialization = \"he\")\nprint (\"On the train set:\")\npredictions_train = predict(train_X, train_Y, parameters)\nprint (\"On the test set:\")\npredictions_test = predict(test_X, test_Y, parameters)",
"Cost after iteration 0: 0.8830537463419761\nCost after iteration 1000: 0.6879825919728063\nCost after iteration 2000: 0.6751286264523371\nCost after iteration 3000: 0.6526117768893807\nCost after iteration 4000: 0.6082958970572938\nCost after iteration 5000: 0.5304944491717495\nCost after iteration 6000: 0.4138645817071795\nCost after iteration 7000: 0.31178034648444414\nCost after iteration 8000: 0.2369621533032257\nCost after iteration 9000: 0.18597287209206845\nCost after iteration 10000: 0.1501555628037181\nCost after iteration 11000: 0.12325079292273548\nCost after iteration 12000: 0.09917746546525937\nCost after iteration 13000: 0.08457055954024273\nCost after iteration 14000: 0.07357895962677366\n"
],
[
"plt.title(\"Model with He initialization\")\naxes = plt.gca()\naxes.set_xlim([-1.5,1.5])\naxes.set_ylim([-1.5,1.5])\nplot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)",
"_____no_output_____"
]
],
[
[
"**Observations**:\n- The model with He initialization separates the blue and the red dots very well in a small number of iterations.\n",
"_____no_output_____"
],
[
"## 5 - Conclusions",
"_____no_output_____"
],
[
"You have seen three different types of initializations. For the same number of iterations and same hyperparameters the comparison is:\n\n<table> \n <tr>\n <td>\n **Model**\n </td>\n <td>\n **Train accuracy**\n </td>\n <td>\n **Problem/Comment**\n </td>\n\n </tr>\n <td>\n 3-layer NN with zeros initialization\n </td>\n <td>\n 50%\n </td>\n <td>\n fails to break symmetry\n </td>\n <tr>\n <td>\n 3-layer NN with large random initialization\n </td>\n <td>\n 83%\n </td>\n <td>\n too large weights \n </td>\n </tr>\n <tr>\n <td>\n 3-layer NN with He initialization\n </td>\n <td>\n 99%\n </td>\n <td>\n recommended method\n </td>\n </tr>\n</table> ",
"_____no_output_____"
],
[
"<font color='blue'>\n**What you should remember from this notebook**:\n- Different initializations lead to different results\n- Random initialization is used to break symmetry and make sure different hidden units can learn different things\n- Don't intialize to values that are too large\n- He initialization works well for networks with ReLU activations. ",
"_____no_output_____"
]
],
[
[
"%load_ext version_information\n%version_information numpy, matplotlib, sklearn",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
e7af04fd69f6b82bcdecc68caae90d6618b73cbb | 7,562 | ipynb | Jupyter Notebook | Task 1.2/Task_1_2.ipynb | cosmin-z/ADM-HW3 | fac8cb2288c734b0c1e30e23757a0c0e14268544 | [
"MIT"
] | null | null | null | Task 1.2/Task_1_2.ipynb | cosmin-z/ADM-HW3 | fac8cb2288c734b0c1e30e23757a0c0e14268544 | [
"MIT"
] | null | null | null | Task 1.2/Task_1_2.ipynb | cosmin-z/ADM-HW3 | fac8cb2288c734b0c1e30e23757a0c0e14268544 | [
"MIT"
] | null | null | null | 27.59854 | 1,305 | 0.504232 | [
[
[
"import requests\nimport os\nimport time\n",
"_____no_output_____"
],
[
"folder = '/Users/anton/Desktop/ADM/Homework3/html'\nfolder = 'dataset'",
"_____no_output_____"
],
[
"# 400 sub-folders\nfor k in range (1, 401):\n path = '{}/page_{}'.format(folder, k)\n os.makedirs(path)",
"_____no_output_____"
],
[
"urls_txt = 'https.txt'",
"_____no_output_____"
],
[
"headers = {\n 'user-agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36\",\n 'accept': \"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8\",\n 'referer': \"https://myanimelist.net/\"\n} ",
"_____no_output_____"
],
[
"def htmls_by_urls(urls_txt, folder):\n # urls_txt: string 'https.txt' from previous task\n # folder: string; eg '/Users/anton/Desktop/ADM/Homework3/html'\n \n with open(urls_txt, 'r', encoding='utf-8') as f:\n lines = f.readlines()\n # list of urls\n list_txt = [line.strip() for line in lines]\n \n i = 0 #you can use this index to start downloading from each point do you want\n \n while i < 20000:\n url = list_txt[i]\n # folder where we save html\n al_folder = '{}/page_{}/{}.html'.format(folder, i//50 +1, i+1)\n # download html\n html = requests.get(url, headers)\n \n if(html.status_code != 200) : \n time.sleep(120) #we sleep for two minutes because the server thinks we are bots\n print('error', html.status_code)\n else:\n i += 1\n with open(al_folder, 'w', encoding='utf-8') as g:\n g.write(html.text)\n",
"_____no_output_____"
],
[
"htmls_by_urls(urls_txt, folder)",
"18943\n18944\n18945\n18946\n18947\n18948\n18949\n18950\nerror 403\n18950\nerror 403\n18950\nerror 403\n18950\n18951\n18952\n18953\n18954\n18955\n18956\n18957\n18958\n18959\n18960\n18961\n18962\n18963\n18964\n18965\n18966\n18967\n18968\n18969\n18970\n18971\n18972\n18973\n18974\n18975\n18976\n18977\n18978\n18979\n18980\n18981\n18982\n18983\n18984\n18985\n18986\n18987\n18988\n18989\n18990\n18991\n18992\n18993\n18994\n18995\n18996\n18997\n18998\n18999\n19000\n19001\n19002\n19003\n19004\n19005\n19006\n19007\n19008\n19009\n19010\n19011\n19012\n19013\n19014\n19015\n19016\n19017\n19018\n19019\n19020\n19021\n19022\n19023\n19024\n19025\n19026\n19027\n19028\n19029\n19030\n19031\n19032\n19033\n19034\n19035\n19036\n19037\n19038\n19039\n19040\n19041\n19042\n19043\n19044\n19045\n19046\n19047\n19048\n19049\n19050\n19051\n19052\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7af06294be18773e48027d1002e76151780f471 | 34,708 | ipynb | Jupyter Notebook | examples/vision/ipynb/nerf.ipynb | k-w-w/keras-io | 49351e21cc51ea161e9b6cad69d231766f5ad81b | [
"Apache-2.0"
] | 1,542 | 2020-05-06T20:23:07.000Z | 2022-03-31T15:25:03.000Z | examples/vision/ipynb/nerf.ipynb | k-w-w/keras-io | 49351e21cc51ea161e9b6cad69d231766f5ad81b | [
"Apache-2.0"
] | 625 | 2020-05-07T10:21:15.000Z | 2022-03-31T17:19:35.000Z | examples/vision/ipynb/nerf.ipynb | k-w-w/keras-io | 49351e21cc51ea161e9b6cad69d231766f5ad81b | [
"Apache-2.0"
] | 1,616 | 2020-05-07T06:28:33.000Z | 2022-03-31T13:35:35.000Z | 37.726087 | 128 | 0.558863 | [
[
[
"# 3D volumetric rendering with NeRF\n\n**Authors:** [Aritra Roy Gosthipaty](https://twitter.com/arig23498), [Ritwik Raha](https://twitter.com/ritwik_raha)<br>\n**Date created:** 2021/08/09<br>\n**Last modified:** 2021/08/09<br>\n**Description:** Minimal implementation of volumetric rendering as shown in NeRF.",
"_____no_output_____"
],
[
"## Introduction\n\nIn this example, we present a minimal implementation of the research paper\n[**NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis**](https://arxiv.org/abs/2003.08934)\nby Ben Mildenhall et. al. The authors have proposed an ingenious way\nto *synthesize novel views of a scene* by modelling the *volumetric\nscene function* through a neural network.\n\nTo help you understand this intuitively, let's start with the following question:\n*would it be possible to give to a neural\nnetwork the position of a pixel in an image, and ask the network\nto predict the color at that position?*\n\n|  |\n| :---: |\n| **Figure 1**: A neural network being given coordinates of an image\nas input and asked to predict the color at the coordinates. |\n\nThe neural network would hypothetically *memorize* (overfit on) the\nimage. This means that our neural network would have encoded the entire image\nin its weights. We could query the neural network with each position,\nand it would eventually reconstruct the entire image.\n\n|  |\n| :---: |\n| **Figure 2**: The trained neural network recreates the image from scratch. |\n\nA question now arises, how do we extend this idea to learn a 3D\nvolumetric scene? Implementing a similar process as above would\nrequire the knowledge of every voxel (volume pixel). Turns out, this\nis quite a challenging task to do.\n\nThe authors of the paper propose a minimal and elegant way to learn a\n3D scene using a few images of the scene. They discard the use of\nvoxels for training. The network learns to model the volumetric scene,\nthus generating novel views (images) of the 3D scene that the model\nwas not shown at training time.\n\nThere are a few prerequisites one needs to understand to fully\nappreciate the process. We structure the example in such a way that\nyou will have all the required knowledge before starting the\nimplementation.",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"# Setting random seed to obtain reproducible results.\nimport tensorflow as tf\n\ntf.random.set_seed(42)\n\nimport os\nimport glob\nimport imageio\nimport numpy as np\nfrom tqdm import tqdm\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport matplotlib.pyplot as plt\n\n# Initialize global variables.\nAUTO = tf.data.AUTOTUNE\nBATCH_SIZE = 5\nNUM_SAMPLES = 32\nPOS_ENCODE_DIMS = 16\nEPOCHS = 20",
"_____no_output_____"
]
],
[
[
"## Download and load the data\n\nThe `npz` data file contains images, camera poses, and a focal length.\nThe images are taken from multiple camera angles as shown in\n**Figure 3**.\n\n|  |\n| :---: |\n| **Figure 3**: Multiple camera angles <br>\n[Source: NeRF](https://arxiv.org/abs/2003.08934) |\n\n\nTo understand camera poses in this context we have to first allow\nourselves to think that a *camera is a mapping between the real-world\nand the 2-D image*.\n\n|  |\n| :---: |\n| **Figure 4**: 3-D world to 2-D image mapping through a camera <br>\n[Source: Mathworks](https://www.mathworks.com/help/vision/ug/camera-calibration.html) |\n\nConsider the following equation:\n\n<img src=\"https://i.imgur.com/TQHKx5v.pngg\" width=\"100\" height=\"50\"/>\n\nWhere **x** is the 2-D image point, **X** is the 3-D world point and\n**P** is the camera-matrix. **P** is a 3 x 4 matrix that plays the\ncrucial role of mapping the real world object onto an image plane.\n\n<img src=\"https://i.imgur.com/chvJct5.png\" width=\"300\" height=\"100\"/>\n\nThe camera-matrix is an *affine transform matrix* that is\nconcatenated with a 3 x 1 column `[image height, image width, focal length]`\nto produce the *pose matrix*. This matrix is of\ndimensions 3 x 5 where the first 3 x 3 block is in the camera’s point\nof view. The axes are `[down, right, backwards]` or `[-y, x, z]`\nwhere the camera is facing forwards `-z`.\n\n|  |\n| :---: |\n| **Figure 5**: The affine transformation. |\n\nThe COLMAP frame is `[right, down, forwards]` or `[x, -y, -z]`. Read\nmore about COLMAP [here](https://colmap.github.io/).",
"_____no_output_____"
]
],
[
[
"# Download the data if it does not already exist.\nfile_name = \"tiny_nerf_data.npz\"\nurl = \"https://people.eecs.berkeley.edu/~bmild/nerf/tiny_nerf_data.npz\"\nif not os.path.exists(file_name):\n data = keras.utils.get_file(fname=file_name, origin=url)\n\ndata = np.load(data)\nimages = data[\"images\"]\nim_shape = images.shape\n(num_images, H, W, _) = images.shape\n(poses, focal) = (data[\"poses\"], data[\"focal\"])\n\n# Plot a random image from the dataset for visualization.\nplt.imshow(images[np.random.randint(low=0, high=num_images)])\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Data pipeline\n\nNow that you've understood the notion of camera matrix\nand the mapping from a 3D scene to 2D images,\nlet's talk about the inverse mapping, i.e. from 2D image to the 3D scene.\n\nWe'll need to talk about volumetric rendering with ray casting and tracing,\nwhich are common computer graphics techniques.\nThis section will help you get to speed with these techniques.\n\nConsider an image with `N` pixels. We shoot a ray through each pixel\nand sample some points on the ray. A ray is commonly parameterized by\nthe equation `r(t) = o + td` where `t` is the parameter, `o` is the\norigin and `d` is the unit directional vector as shown in **Figure 6**.\n\n|  |\n| :---: |\n| **Figure 6**: `r(t) = o + td` where t is 3 |\n\nIn **Figure 7**, we consider a ray, and we sample some random points on\nthe ray. These sample points each have a unique location `(x, y, z)`\nand the ray has a viewing angle `(theta, phi)`. The viewing angle is\nparticularly interesting as we can shoot a ray through a single pixel\nin a lot of different ways, each with a unique viewing angle. Another\ninteresting thing to notice here is the noise that is added to the\nsampling process. We add a uniform noise to each sample so that the\nsamples correspond to a continuous distribution. In **Figure 7** the\nblue points are the evenly distributed samples and the white points\n`(t1, t2, t3)` are randomly placed between the samples.\n\n|  |\n| :---: |\n| **Figure 7**: Sampling the points from a ray. |\n\n**Figure 8** showcases the entire sampling process in 3D, where you\ncan see the rays coming out of the white image. This means that each\npixel will have its corresponding rays and each ray will be sampled at\ndistinct points.\n\n|  |\n| :---: |\n| **Figure 8**: Shooting rays from all the pixels of an image in 3-D |\n\nThese sampled points act as the input to the NeRF model. The model is\nthen asked to predict the RGB color and the volume density at that\npoint.\n\n|  |\n| :---: |\n| **Figure 9**: Data pipeline <br>\n[Source: NeRF](https://arxiv.org/abs/2003.08934) |",
"_____no_output_____"
]
],
[
[
"\ndef encode_position(x):\n \"\"\"Encodes the position into its corresponding Fourier feature.\n\n Args:\n x: The input coordinate.\n\n Returns:\n Fourier features tensors of the position.\n \"\"\"\n positions = [x]\n for i in range(POS_ENCODE_DIMS):\n for fn in [tf.sin, tf.cos]:\n positions.append(fn(2.0 ** i * x))\n return tf.concat(positions, axis=-1)\n\n\ndef get_rays(height, width, focal, pose):\n \"\"\"Computes origin point and direction vector of rays.\n\n Args:\n height: Height of the image.\n width: Width of the image.\n focal: The focal length between the images and the camera.\n pose: The pose matrix of the camera.\n\n Returns:\n Tuple of origin point and direction vector for rays.\n \"\"\"\n # Build a meshgrid for the rays.\n i, j = tf.meshgrid(\n tf.range(width, dtype=tf.float32),\n tf.range(height, dtype=tf.float32),\n indexing=\"xy\",\n )\n\n # Normalize the x axis coordinates.\n transformed_i = (i - width * 0.5) / focal\n\n # Normalize the y axis coordinates.\n transformed_j = (j - height * 0.5) / focal\n\n # Create the direction unit vectors.\n directions = tf.stack([transformed_i, -transformed_j, -tf.ones_like(i)], axis=-1)\n\n # Get the camera matrix.\n camera_matrix = pose[:3, :3]\n height_width_focal = pose[:3, -1]\n\n # Get origins and directions for the rays.\n transformed_dirs = directions[..., None, :]\n camera_dirs = transformed_dirs * camera_matrix\n ray_directions = tf.reduce_sum(camera_dirs, axis=-1)\n ray_origins = tf.broadcast_to(height_width_focal, tf.shape(ray_directions))\n\n # Return the origins and directions.\n return (ray_origins, ray_directions)\n\n\ndef render_flat_rays(ray_origins, ray_directions, near, far, num_samples, rand=False):\n \"\"\"Renders the rays and flattens it.\n\n Args:\n ray_origins: The origin points for rays.\n ray_directions: The direction unit vectors for the rays.\n near: The near bound of the volumetric scene.\n far: The far bound of the volumetric scene.\n num_samples: Number of sample points in a ray.\n rand: Choice for randomising the sampling strategy.\n\n Returns:\n Tuple of flattened rays and sample points on each rays.\n \"\"\"\n # Compute 3D query points.\n # Equation: r(t) = o+td -> Building the \"t\" here.\n t_vals = tf.linspace(near, far, num_samples)\n if rand:\n # Inject uniform noise into sample space to make the sampling\n # continuous.\n shape = list(ray_origins.shape[:-1]) + [num_samples]\n noise = tf.random.uniform(shape=shape) * (far - near) / num_samples\n t_vals = t_vals + noise\n\n # Equation: r(t) = o + td -> Building the \"r\" here.\n rays = ray_origins[..., None, :] + (\n ray_directions[..., None, :] * t_vals[..., None]\n )\n rays_flat = tf.reshape(rays, [-1, 3])\n rays_flat = encode_position(rays_flat)\n return (rays_flat, t_vals)\n\n\ndef map_fn(pose):\n \"\"\"Maps individual pose to flattened rays and sample points.\n\n Args:\n pose: The pose matrix of the camera.\n\n Returns:\n Tuple of flattened rays and sample points corresponding to the\n camera pose.\n \"\"\"\n (ray_origins, ray_directions) = get_rays(height=H, width=W, focal=focal, pose=pose)\n (rays_flat, t_vals) = render_flat_rays(\n ray_origins=ray_origins,\n ray_directions=ray_directions,\n near=2.0,\n far=6.0,\n num_samples=NUM_SAMPLES,\n rand=True,\n )\n return (rays_flat, t_vals)\n\n\n# Create the training split.\nsplit_index = int(num_images * 0.8)\n\n# Split the images into training and validation.\ntrain_images = images[:split_index]\nval_images = images[split_index:]\n\n# Split the poses into training and validation.\ntrain_poses = poses[:split_index]\nval_poses = poses[split_index:]\n\n# Make the training pipeline.\ntrain_img_ds = tf.data.Dataset.from_tensor_slices(train_images)\ntrain_pose_ds = tf.data.Dataset.from_tensor_slices(train_poses)\ntrain_ray_ds = train_pose_ds.map(map_fn, num_parallel_calls=AUTO)\ntraining_ds = tf.data.Dataset.zip((train_img_ds, train_ray_ds))\ntrain_ds = (\n training_ds.shuffle(BATCH_SIZE)\n .batch(BATCH_SIZE, drop_remainder=True, num_parallel_calls=AUTO)\n .prefetch(AUTO)\n)\n\n# Make the validation pipeline.\nval_img_ds = tf.data.Dataset.from_tensor_slices(val_images)\nval_pose_ds = tf.data.Dataset.from_tensor_slices(val_poses)\nval_ray_ds = val_pose_ds.map(map_fn, num_parallel_calls=AUTO)\nvalidation_ds = tf.data.Dataset.zip((val_img_ds, val_ray_ds))\nval_ds = (\n validation_ds.shuffle(BATCH_SIZE)\n .batch(BATCH_SIZE, drop_remainder=True, num_parallel_calls=AUTO)\n .prefetch(AUTO)\n)",
"_____no_output_____"
]
],
[
[
"## NeRF model\n\nThe model is a multi-layer perceptron (MLP), with ReLU as its non-linearity.\n\nAn excerpt from the paper:\n\n*\"We encourage the representation to be multiview-consistent by\nrestricting the network to predict the volume density sigma as a\nfunction of only the location `x`, while allowing the RGB color `c` to be\npredicted as a function of both location and viewing direction. To\naccomplish this, the MLP first processes the input 3D coordinate `x`\nwith 8 fully-connected layers (using ReLU activations and 256 channels\nper layer), and outputs sigma and a 256-dimensional feature vector.\nThis feature vector is then concatenated with the camera ray's viewing\ndirection and passed to one additional fully-connected layer (using a\nReLU activation and 128 channels) that output the view-dependent RGB\ncolor.\"*\n\nHere we have gone for a minimal implementation and have used 64\nDense units instead of 256 as mentioned in the paper.",
"_____no_output_____"
]
],
[
[
"\ndef get_nerf_model(num_layers, num_pos):\n \"\"\"Generates the NeRF neural network.\n\n Args:\n num_layers: The number of MLP layers.\n num_pos: The number of dimensions of positional encoding.\n\n Returns:\n The `tf.keras` model.\n \"\"\"\n inputs = keras.Input(shape=(num_pos, 2 * 3 * POS_ENCODE_DIMS + 3))\n x = inputs\n for i in range(num_layers):\n x = layers.Dense(units=64, activation=\"relu\")(x)\n if i % 4 == 0 and i > 0:\n # Inject residual connection.\n x = layers.concatenate([x, inputs], axis=-1)\n outputs = layers.Dense(units=4)(x)\n return keras.Model(inputs=inputs, outputs=outputs)\n\n\ndef render_rgb_depth(model, rays_flat, t_vals, rand=True, train=True):\n \"\"\"Generates the RGB image and depth map from model prediction.\n\n Args:\n model: The MLP model that is trained to predict the rgb and\n volume density of the volumetric scene.\n rays_flat: The flattened rays that serve as the input to\n the NeRF model.\n t_vals: The sample points for the rays.\n rand: Choice to randomise the sampling strategy.\n train: Whether the model is in the training or testing phase.\n\n Returns:\n Tuple of rgb image and depth map.\n \"\"\"\n # Get the predictions from the nerf model and reshape it.\n if train:\n predictions = model(rays_flat)\n else:\n predictions = model.predict(rays_flat)\n predictions = tf.reshape(predictions, shape=(BATCH_SIZE, H, W, NUM_SAMPLES, 4))\n\n # Slice the predictions into rgb and sigma.\n rgb = tf.sigmoid(predictions[..., :-1])\n sigma_a = tf.nn.relu(predictions[..., -1])\n\n # Get the distance of adjacent intervals.\n delta = t_vals[..., 1:] - t_vals[..., :-1]\n # delta shape = (num_samples)\n if rand:\n delta = tf.concat(\n [delta, tf.broadcast_to([1e10], shape=(BATCH_SIZE, H, W, 1))], axis=-1\n )\n alpha = 1.0 - tf.exp(-sigma_a * delta)\n else:\n delta = tf.concat(\n [delta, tf.broadcast_to([1e10], shape=(BATCH_SIZE, 1))], axis=-1\n )\n alpha = 1.0 - tf.exp(-sigma_a * delta[:, None, None, :])\n\n # Get transmittance.\n exp_term = 1.0 - alpha\n epsilon = 1e-10\n transmittance = tf.math.cumprod(exp_term + epsilon, axis=-1, exclusive=True)\n weights = alpha * transmittance\n rgb = tf.reduce_sum(weights[..., None] * rgb, axis=-2)\n\n if rand:\n depth_map = tf.reduce_sum(weights * t_vals, axis=-1)\n else:\n depth_map = tf.reduce_sum(weights * t_vals[:, None, None], axis=-1)\n return (rgb, depth_map)\n",
"_____no_output_____"
]
],
[
[
"## Training\n\nThe training step is implemented as part of a custom `keras.Model` subclass\nso that we can make use of the `model.fit` functionality.",
"_____no_output_____"
]
],
[
[
"\nclass NeRF(keras.Model):\n def __init__(self, nerf_model):\n super().__init__()\n self.nerf_model = nerf_model\n\n def compile(self, optimizer, loss_fn):\n super().compile()\n self.optimizer = optimizer\n self.loss_fn = loss_fn\n self.loss_tracker = keras.metrics.Mean(name=\"loss\")\n self.psnr_metric = keras.metrics.Mean(name=\"psnr\")\n\n def train_step(self, inputs):\n # Get the images and the rays.\n (images, rays) = inputs\n (rays_flat, t_vals) = rays\n\n with tf.GradientTape() as tape:\n # Get the predictions from the model.\n rgb, _ = render_rgb_depth(\n model=self.nerf_model, rays_flat=rays_flat, t_vals=t_vals, rand=True\n )\n loss = self.loss_fn(images, rgb)\n\n # Get the trainable variables.\n trainable_variables = self.nerf_model.trainable_variables\n\n # Get the gradeints of the trainiable variables with respect to the loss.\n gradients = tape.gradient(loss, trainable_variables)\n\n # Apply the grads and optimize the model.\n self.optimizer.apply_gradients(zip(gradients, trainable_variables))\n\n # Get the PSNR of the reconstructed images and the source images.\n psnr = tf.image.psnr(images, rgb, max_val=1.0)\n\n # Compute our own metrics\n self.loss_tracker.update_state(loss)\n self.psnr_metric.update_state(psnr)\n return {\"loss\": self.loss_tracker.result(), \"psnr\": self.psnr_metric.result()}\n\n def test_step(self, inputs):\n # Get the images and the rays.\n (images, rays) = inputs\n (rays_flat, t_vals) = rays\n\n # Get the predictions from the model.\n rgb, _ = render_rgb_depth(\n model=self.nerf_model, rays_flat=rays_flat, t_vals=t_vals, rand=True\n )\n loss = self.loss_fn(images, rgb)\n\n # Get the PSNR of the reconstructed images and the source images.\n psnr = tf.image.psnr(images, rgb, max_val=1.0)\n\n # Compute our own metrics\n self.loss_tracker.update_state(loss)\n self.psnr_metric.update_state(psnr)\n return {\"loss\": self.loss_tracker.result(), \"psnr\": self.psnr_metric.result()}\n\n @property\n def metrics(self):\n return [self.loss_tracker, self.psnr_metric]\n\n\ntest_imgs, test_rays = next(iter(train_ds))\ntest_rays_flat, test_t_vals = test_rays\n\nloss_list = []\n\n\nclass TrainMonitor(keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs=None):\n loss = logs[\"loss\"]\n loss_list.append(loss)\n test_recons_images, depth_maps = render_rgb_depth(\n model=self.model.nerf_model,\n rays_flat=test_rays_flat,\n t_vals=test_t_vals,\n rand=True,\n train=False,\n )\n\n # Plot the rgb, depth and the loss plot.\n fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(20, 5))\n ax[0].imshow(keras.preprocessing.image.array_to_img(test_recons_images[0]))\n ax[0].set_title(f\"Predicted Image: {epoch:03d}\")\n\n ax[1].imshow(keras.preprocessing.image.array_to_img(depth_maps[0, ..., None]))\n ax[1].set_title(f\"Depth Map: {epoch:03d}\")\n\n ax[2].plot(loss_list)\n ax[2].set_xticks(np.arange(0, EPOCHS + 1, 5.0))\n ax[2].set_title(f\"Loss Plot: {epoch:03d}\")\n\n fig.savefig(f\"images/{epoch:03d}.png\")\n plt.show()\n plt.close()\n\n\nnum_pos = H * W * NUM_SAMPLES\nnerf_model = get_nerf_model(num_layers=8, num_pos=num_pos)\n\nmodel = NeRF(nerf_model)\nmodel.compile(\n optimizer=keras.optimizers.Adam(), loss_fn=keras.losses.MeanSquaredError()\n)\n\n# Create a directory to save the images during training.\nif not os.path.exists(\"images\"):\n os.makedirs(\"images\")\n\nmodel.fit(\n train_ds,\n validation_data=val_ds,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n callbacks=[TrainMonitor()],\n steps_per_epoch=split_index // BATCH_SIZE,\n)\n\n\ndef create_gif(path_to_images, name_gif):\n filenames = glob.glob(path_to_images)\n filenames = sorted(filenames)\n images = []\n for filename in tqdm(filenames):\n images.append(imageio.imread(filename))\n kargs = {\"duration\": 0.25}\n imageio.mimsave(name_gif, images, \"GIF\", **kargs)\n\n\ncreate_gif(\"images/*.png\", \"training.gif\")",
"_____no_output_____"
]
],
[
[
"## Visualize the training step\n\nHere we see the training step. With the decreasing loss, the rendered\nimage and the depth maps are getting better. In your local system, you\nwill see the `training.gif` file generated.\n\n",
"_____no_output_____"
],
[
"## Inference\n\nIn this section, we ask the model to build novel views of the scene.\nThe model was given `106` views of the scene in the training step. The\ncollections of training images cannot contain each and every angle of\nthe scene. A trained model can represent the entire 3-D scene with a\nsparse set of training images.\n\nHere we provide different poses to the model and ask for it to give us\nthe 2-D image corresponding to that camera view. If we infer the model\nfor all the 360-degree views, it should provide an overview of the\nentire scenery from all around.",
"_____no_output_____"
]
],
[
[
"# Get the trained NeRF model and infer.\nnerf_model = model.nerf_model\ntest_recons_images, depth_maps = render_rgb_depth(\n model=nerf_model,\n rays_flat=test_rays_flat,\n t_vals=test_t_vals,\n rand=True,\n train=False,\n)\n\n# Create subplots.\nfig, axes = plt.subplots(nrows=5, ncols=3, figsize=(10, 20))\n\nfor ax, ori_img, recons_img, depth_map in zip(\n axes, test_imgs, test_recons_images, depth_maps\n):\n ax[0].imshow(keras.preprocessing.image.array_to_img(ori_img))\n ax[0].set_title(\"Original\")\n\n ax[1].imshow(keras.preprocessing.image.array_to_img(recons_img))\n ax[1].set_title(\"Reconstructed\")\n\n ax[2].imshow(\n keras.preprocessing.image.array_to_img(depth_map[..., None]), cmap=\"inferno\"\n )\n ax[2].set_title(\"Depth Map\")",
"_____no_output_____"
]
],
[
[
"## Render 3D Scene\n\nHere we will synthesize novel 3D views and stitch all of them together\nto render a video encompassing the 360-degree view.",
"_____no_output_____"
]
],
[
[
"\ndef get_translation_t(t):\n \"\"\"Get the translation matrix for movement in t.\"\"\"\n matrix = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, t],\n [0, 0, 0, 1],\n ]\n return tf.convert_to_tensor(matrix, dtype=tf.float32)\n\n\ndef get_rotation_phi(phi):\n \"\"\"Get the rotation matrix for movement in phi.\"\"\"\n matrix = [\n [1, 0, 0, 0],\n [0, tf.cos(phi), -tf.sin(phi), 0],\n [0, tf.sin(phi), tf.cos(phi), 0],\n [0, 0, 0, 1],\n ]\n return tf.convert_to_tensor(matrix, dtype=tf.float32)\n\n\ndef get_rotation_theta(theta):\n \"\"\"Get the rotation matrix for movement in theta.\"\"\"\n matrix = [\n [tf.cos(theta), 0, -tf.sin(theta), 0],\n [0, 1, 0, 0],\n [tf.sin(theta), 0, tf.cos(theta), 0],\n [0, 0, 0, 1],\n ]\n return tf.convert_to_tensor(matrix, dtype=tf.float32)\n\n\ndef pose_spherical(theta, phi, t):\n \"\"\"\n Get the camera to world matrix for the corresponding theta, phi\n and t.\n \"\"\"\n c2w = get_translation_t(t)\n c2w = get_rotation_phi(phi / 180.0 * np.pi) @ c2w\n c2w = get_rotation_theta(theta / 180.0 * np.pi) @ c2w\n c2w = np.array([[-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) @ c2w\n return c2w\n\n\nrgb_frames = []\nbatch_flat = []\nbatch_t = []\n\n# Iterate over different theta value and generate scenes.\nfor index, theta in tqdm(enumerate(np.linspace(0.0, 360.0, 120, endpoint=False))):\n # Get the camera to world matrix.\n c2w = pose_spherical(theta, -30.0, 4.0)\n\n #\n ray_oris, ray_dirs = get_rays(H, W, focal, c2w)\n rays_flat, t_vals = render_flat_rays(\n ray_oris, ray_dirs, near=2.0, far=6.0, num_samples=NUM_SAMPLES, rand=False\n )\n\n if index % BATCH_SIZE == 0 and index > 0:\n batched_flat = tf.stack(batch_flat, axis=0)\n batch_flat = [rays_flat]\n\n batched_t = tf.stack(batch_t, axis=0)\n batch_t = [t_vals]\n\n rgb, _ = render_rgb_depth(\n nerf_model, batched_flat, batched_t, rand=False, train=False\n )\n\n temp_rgb = [np.clip(255 * img, 0.0, 255.0).astype(np.uint8) for img in rgb]\n\n rgb_frames = rgb_frames + temp_rgb\n else:\n batch_flat.append(rays_flat)\n batch_t.append(t_vals)\n\nrgb_video = \"rgb_video.mp4\"\nimageio.mimwrite(rgb_video, rgb_frames, fps=30, quality=7, macro_block_size=None)",
"_____no_output_____"
]
],
[
[
"### Visualize the video\n\nHere we can see the rendered 360 degree view of the scene. The model\nhas successfully learned the entire volumetric space through the\nsparse set of images in **only 20 epochs**. You can view the\nrendered video saved locally, named `rgb_video.mp4`.\n\n",
"_____no_output_____"
],
[
"## Conclusion\n\nWe have produced a minimal implementation of NeRF to provide an intuition of its\ncore ideas and methodology. This method has been used in various\nother works in the computer graphics space.\n\nWe would like to encourage our readers to use this code as an example\nand play with the hyperparameters and visualize the outputs. Below we\nhave also provided the outputs of the model trained for more epochs.\n\n| Epochs | GIF of the training step |\n| :--- | :---: |\n| **100** |  |\n| **200** |  |\n\n## Reference\n\n- [NeRF repository](https://github.com/bmild/nerf): The official\n repository for NeRF.\n- [NeRF paper](https://arxiv.org/abs/2003.08934): The paper on NeRF.\n- [Manim Repository](https://github.com/3b1b/manim): We have used\n manim to build all the animations.\n- [Mathworks](https://www.mathworks.com/help/vision/ug/camera-calibration.html):\n Mathworks for the camera calibration article.\n- [Mathew's video](https://www.youtube.com/watch?v=dPWLybp4LL0): A\n great video on NeRF.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e7af165a3630e7641c2c5dce95a3e27a29eadd7e | 3,532 | ipynb | Jupyter Notebook | Examples/notebooks/Cells.ipynb | paulbrodersen/BrainRender | 772684d5fb52cd827e88357cda995f36c0ad2e60 | [
"MIT"
] | null | null | null | Examples/notebooks/Cells.ipynb | paulbrodersen/BrainRender | 772684d5fb52cd827e88357cda995f36c0ad2e60 | [
"MIT"
] | null | null | null | Examples/notebooks/Cells.ipynb | paulbrodersen/BrainRender | 772684d5fb52cd827e88357cda995f36c0ad2e60 | [
"MIT"
] | null | null | null | 30.448276 | 152 | 0.587769 | [
[
[
"# Cells\nIn this examples I'll show how to render a large number of cells in your scene. \nThis can be useful when visualizing the results of tracking experiments after they have been aligned to the allen brain atlas reference frame. \n\n<img src=\"https://raw.githubusercontent.com/BrancoLab/BrainRender/master/Docs/Media/cells.gif\" width=\"600\" height=\"350\">\n\n\n\n### set up",
"_____no_output_____"
]
],
[
[
"# We begin by adding the current path to sys.path to make sure that the imports work correctly\nimport sys\nsys.path.append('../')\nimport os\nimport pandas as pd\n\nfrom vtkplotter import *\n\n# Import variables\nfrom brainrender import * # <- these can be changed to personalize the look of your renders\n\n# Import brainrender classes and useful functions\nfrom brainrender.scene import Scene\nfrom brainrender.Utils.data_io import listdir\n",
"_____no_output_____"
]
],
[
[
"## Get data\nTo keep things interesting, we will generate N random \"cells\" in a number of regions of interest. \nThese coordinates will then be used to render the cells. \nIf you have your coordinates saved in a file (e.g. a .csv or .h5 or .pkl), you can use `Scene.add_cells_from_file` and skip this next step. ",
"_____no_output_____"
]
],
[
[
"# Create a scene\nscene = Scene()\n\n# Define in which regions to crate the cells and how many\nregions = [\"MOs\", \"VISp\", \"ZI\"]\nN = 1000 # getting 1k cells per region, but brainrender can deal with >1M cells easily. \n\n# Render brain regions and add transparency slider.\nscene.add_brain_regions(regions, colors=\"ivory\", alpha=.8)\nscene.add_slider(brain_regions=regions)\n\nprint(\"\\nRunning a quick experiment to get cell coordinates...\")\ncells = [] # to store x,y,z coordinates\nfor region in regions:\n region_cells = scene.get_n_random_points_in_region(region=region, N=N)\n cells.extend(region_cells)\nx,y,z = [c[0] for c in cells], [c[1] for c in cells], [c[2] for c in cells]\ncells = pd.DataFrame(dict(x=x, y=y, z=z))\n# render cells\nprint(\"\\nRendering...\")\nscene.add_cells(cells, color=\"red\")\nscene.render() # <- this wont actually render things in a notebook",
"_____no_output_____"
],
[
"vp = Plotter(axes=0)\nvp.show(scene.get_actors())",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7af1e8f1035574aa3f67953535526f71b7fb1ae | 7,662 | ipynb | Jupyter Notebook | notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb | andrewRowlinson/expected-goals-thesis | c6945f2919666933bd5e35692f838f85a82073e0 | [
"MIT"
] | 23 | 2020-06-03T09:16:33.000Z | 2021-10-01T17:00:39.000Z | notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb | eddwebster/expected-goals-thesis | c6945f2919666933bd5e35692f838f85a82073e0 | [
"MIT"
] | null | null | null | notebooks/create-data/04_statsbomb_freeze_frame_features.ipynb | eddwebster/expected-goals-thesis | c6945f2919666933bd5e35692f838f85a82073e0 | [
"MIT"
] | 4 | 2020-07-10T10:11:09.000Z | 2021-12-30T19:41:14.000Z | 31.146341 | 131 | 0.567215 | [
[
[
"import pandas as pd\nimport numpy as np\nimport os\nfrom mplsoccer.pitch import Pitch\nfrom shapely.geometry import MultiPoint, Polygon, Point",
"_____no_output_____"
]
],
[
[
"Load the data",
"_____no_output_____"
]
],
[
[
"STATSBOMB = os.path.join('..', '..', 'data', 'statsbomb')\ndf_statsbomb_event = pd.read_parquet(os.path.join(STATSBOMB, 'event.parquet'))\ndf_statsbomb_freeze = pd.read_parquet(os.path.join(STATSBOMB, 'freeze.parquet'))",
"_____no_output_____"
]
],
[
[
"Filter shots",
"_____no_output_____"
]
],
[
[
"df_statsbomb_shot = df_statsbomb_event[df_statsbomb_event.type_name == 'Shot'].copy()",
"_____no_output_____"
]
],
[
[
"# Features based on StatsBomb freeze frame",
"_____no_output_____"
],
[
"Features based on freeze frame - this takes a while as looping over 20k+ shots:\n- space around goaly\n- space around shooter\n- number of players in shot angle to goal",
"_____no_output_____"
],
[
"Filter out penalty goals from freeze frames",
"_____no_output_____"
]
],
[
[
"non_penalty_id = df_statsbomb_shot.loc[(df_statsbomb_shot.sub_type_name != 'Penalty'), 'id']\ndf_statsbomb_freeze = df_statsbomb_freeze[df_statsbomb_freeze.id.isin(non_penalty_id)].copy()",
"_____no_output_____"
]
],
[
[
"Add the shot taker to the freeze frame",
"_____no_output_____"
]
],
[
[
"cols_to_keep = ['id','player_id','player_name','position_id','position_name','x','y','match_id']\nfreeze_ids = df_statsbomb_freeze.id.unique()\ndf_shot_taker = df_statsbomb_shot.loc[df_statsbomb_shot.id.isin(freeze_ids), cols_to_keep].copy()\ndf_shot_taker['player_teammate'] = True\ndf_shot_taker['event_freeze_id'] = 0\ndf_shot_taker.rename({'position_id': 'player_position_id', 'position_name': 'player_position_name'}, axis=1, inplace=True)\ndf_statsbomb_freeze = pd.concat([df_statsbomb_freeze, df_shot_taker])",
"_____no_output_____"
]
],
[
[
"Calculate features",
"_____no_output_____"
]
],
[
[
"statsbomb_pitch = Pitch()\n\n# store the results in lists\narea_goal = []\narea_shot = []\nn_angle = []\n\n# loop through the freeze frames create a voronoi and calculate the area around the goalkeeper/ shot taker\nfor shot_id in df_statsbomb_freeze.id.unique():\n subset = df_statsbomb_freeze.loc[df_statsbomb_freeze.id == shot_id,\n ['x', 'y', 'player_teammate', 'event_freeze_id', \n 'player_position_id','player_position_name']].copy()\n team1, team2 = statsbomb_pitch.voronoi(subset.x, subset.y, subset.player_teammate)\n subset['rank'] = subset.groupby('player_teammate')['x'].cumcount()\n \n # goal keeper voronoi\n if (subset.player_position_name=='Goalkeeper').sum() > 0:\n goalkeeper_voronoi = team2[subset.loc[subset.player_position_id == 1, 'rank'].values[0]]\n area_goal.append(Polygon(goalkeeper_voronoi).area)\n else:\n area_goal.append(0)\n \n # shot voronoi\n shot_taker_voronoi = team1[subset.loc[subset.event_freeze_id == 0, 'rank'].values[0]]\n area_shot.append(Polygon(shot_taker_voronoi).area)\n \n # calculate number of players in the angle to the goal\n shot_taker = subset.loc[subset.event_freeze_id == 0, ['x', 'y']]\n verts = np.zeros((3, 2))\n verts[0, 0] = shot_taker.x\n verts[0, 1] = shot_taker.y\n verts[1:, :] = statsbomb_pitch.goal_right\n angle = Polygon(verts).buffer(0) # the angle to the goal polygon, buffer added as sometimes shot is on the goal line\n players = MultiPoint(subset.loc[subset.event_freeze_id!=0, ['x', 'y']].values.tolist()) # points for players\n intersection = players.intersection(angle) # intersection between angle and players\n if isinstance(intersection, MultiPoint): # calculate number of players\n n_players = len(players.intersection(angle))\n elif isinstance(intersection, Point):\n n_players = 1\n else:\n n_players = 0\n n_angle.append(n_players)\n \n# create a dataframe\ndf_freeze_features = pd.DataFrame({'id': df_statsbomb_freeze.id.unique(), 'area_shot': area_shot,\n 'area_goal': area_goal, 'n_angle': n_angle})",
"_____no_output_____"
]
],
[
[
"Add on goalkeeper position",
"_____no_output_____"
]
],
[
[
"gk_position = df_statsbomb_freeze.loc[(df_statsbomb_freeze.player_position_name == 'Goalkeeper') &\n (df_statsbomb_freeze.player_teammate == False), ['id', 'x', 'y']]\ngk_position.rename({'x': 'goalkeeper_x','y': 'goalkeeper_y'}, axis=1, inplace=True)\ndf_freeze_features = df_freeze_features.merge(gk_position, how='left', on='id', validate='1:1')",
"_____no_output_____"
]
],
[
[
"Save features",
"_____no_output_____"
]
],
[
[
"df_freeze_features.to_parquet(os.path.join(STATSBOMB, 'freeze_features.parquet'))\ndf_freeze_features.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 21536 entries, 0 to 21535\nData columns (total 6 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 id 21536 non-null object \n 1 area_shot 21536 non-null float64\n 2 area_goal 21536 non-null float64\n 3 n_angle 21536 non-null int64 \n 4 goalkeeper_x 21477 non-null float64\n 5 goalkeeper_y 21477 non-null float64\ndtypes: float64(4), int64(1), object(1)\nmemory usage: 1.2+ MB\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7af3228502fb1269a1310bdaee533044e8dd261 | 8,584 | ipynb | Jupyter Notebook | intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb | cgentemann/tutorials | 04f04ed43f6e35d70c9037e54624b5b476ed9666 | [
"Apache-2.0"
] | null | null | null | intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb | cgentemann/tutorials | 04f04ed43f6e35d70c9037e54624b5b476ed9666 | [
"Apache-2.0"
] | null | null | null | intro_python/python_tutorials/jupyter-notebook_intro/Widget Basics.ipynb | cgentemann/tutorials | 04f04ed43f6e35d70c9037e54624b5b476ed9666 | [
"Apache-2.0"
] | null | null | null | 20.438095 | 402 | 0.532269 | [
[
[
"# Simple Widget Introduction",
"_____no_output_____"
],
[
"## What are widgets?",
"_____no_output_____"
],
[
"Widgets are elements that exists in both the front-end and the back-end.\n\n",
"_____no_output_____"
],
[
"## What can they be used for?",
"_____no_output_____"
],
[
"You can use widgets to build **interactive GUIs** for your notebooks. \nYou can also use widgets to **synchronize stateful and stateless information** between Python and JavaScript.",
"_____no_output_____"
],
[
"## Using widgets ",
"_____no_output_____"
],
[
"To use the widget framework, you need to **import `IPython.html.widgets`**.",
"_____no_output_____"
]
],
[
[
"from ipywidgets import *",
"_____no_output_____"
]
],
[
[
"### repr",
"_____no_output_____"
],
[
"Widgets have their own display `repr` which allows them to be displayed using IPython's display framework. Constructing and returning an `IntSlider` automatically displays the widget (as seen below). Widgets are **displayed inside the `widget area`**, which sits between the code cell and output. **You can hide all of the widgets** in the `widget area` by clicking the grey *x* in the margin.",
"_____no_output_____"
]
],
[
[
"IntSlider(min=0, max=10)",
"_____no_output_____"
]
],
[
[
"### display()",
"_____no_output_____"
],
[
"You can also explicitly display the widget using `display(...)`.",
"_____no_output_____"
]
],
[
[
"from IPython.display import display\nw = IntSlider(min=0, max=10)\ndisplay(w)",
"_____no_output_____"
]
],
[
[
"### Multiple display() calls",
"_____no_output_____"
],
[
"If you display the same widget twice, the displayed instances in the front-end **will remain in sync** with each other.",
"_____no_output_____"
]
],
[
[
"display(w)",
"_____no_output_____"
]
],
[
[
"## Why does displaying the same widget twice work?",
"_____no_output_____"
],
[
"Widgets are **represented in the back-end by a single object**. Each time a widget is displayed, **a new representation** of that same object is created in the front-end. These representations are called **views**.\n\n",
"_____no_output_____"
],
[
"### Closing widgets",
"_____no_output_____"
],
[
"You can close a widget by calling its `close()` method.",
"_____no_output_____"
]
],
[
[
"display(w)",
"_____no_output_____"
],
[
"w.close()",
"_____no_output_____"
]
],
[
[
"## Widget properties",
"_____no_output_____"
],
[
"All of the IPython widgets **share a similar naming scheme**. To read the value of a widget, you can query its `value` property.",
"_____no_output_____"
]
],
[
[
"w = IntSlider(min=0, max=10)\ndisplay(w)",
"_____no_output_____"
],
[
"w.value",
"_____no_output_____"
]
],
[
[
"Similarly, to set a widget's value, you can set its `value` property.",
"_____no_output_____"
]
],
[
[
"w.value = 100",
"_____no_output_____"
]
],
[
[
"### Keys",
"_____no_output_____"
],
[
"In addition to `value`, most widgets share `keys`, `description`, `disabled`, and `visible`. To see the entire list of synchronized, stateful properties, of any specific widget, you can **query the `keys` property**.",
"_____no_output_____"
]
],
[
[
"w.keys",
"_____no_output_____"
]
],
[
[
"### Shorthand for setting the initial values of widget properties",
"_____no_output_____"
],
[
"While creating a widget, you can set some or all of the initial values of that widget by **defining them as keyword arguments in the widget's constructor** (as seen below).",
"_____no_output_____"
]
],
[
[
"Text(value='Hello World!', disabled=True)",
"_____no_output_____"
]
],
[
[
"## Linking two similar widgets",
"_____no_output_____"
],
[
"If you need to display the same value two different ways, you'll have to use two different widgets. Instead of **attempting to manually synchronize the values** of the two widgets, you can use the `traitlet` `link` function **to link two properties together**. Below, the values of three widgets are linked together.",
"_____no_output_____"
]
],
[
[
"from traitlets import link\na = FloatText()\nb = FloatSlider(min=0.0, max=10.0)\nc = FloatProgress(min=0, max=10)\ndisplay(a,b,c)\n\n\nblink = link((a, 'value'), (b, 'value'))\nclink = link((a, 'value'), (c, 'value'))",
"_____no_output_____"
],
[
"a.value = 5",
"_____no_output_____"
]
],
[
[
"### Unlinking widgets",
"_____no_output_____"
],
[
"Unlinking the widgets is simple. All you have to do is call `.unlink` on the link object.",
"_____no_output_____"
]
],
[
[
"clink.unlink()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
e7af35845da72e875507d07e7f885f178ac57a94 | 51,834 | ipynb | Jupyter Notebook | Neural Network Error-Function.ipynb | Haytam222/Neural-Network | e5552eed739cb451042ce0a071b14e4ce02931f5 | [
"MIT"
] | 7 | 2020-07-28T15:51:49.000Z | 2021-12-20T00:01:31.000Z | Neural Network Error-Function.ipynb | Haytam222/Neural-Network | e5552eed739cb451042ce0a071b14e4ce02931f5 | [
"MIT"
] | null | null | null | Neural Network Error-Function.ipynb | Haytam222/Neural-Network | e5552eed739cb451042ce0a071b14e4ce02931f5 | [
"MIT"
] | null | null | null | 95.988889 | 12,456 | 0.812015 | [
[
[
"## Import",
"_____no_output_____"
]
],
[
[
"# Matplotlib\nimport matplotlib.pyplot as plt\n# Tensorflow\nimport tensorflow as tf\n# Numpy and Pandas\nimport numpy as np\nimport pandas as pd\n# Ohter import\nimport sys\n\n\nfrom sklearn.preprocessing import StandardScaler\n",
"Limited tf.compat.v2.summary API due to missing TensorBoard installation\nLimited tf.summary API due to missing TensorBoard installation\n"
]
],
[
[
"## Be sure to used Tensorflow 2.0",
"_____no_output_____"
]
],
[
[
"assert hasattr(tf, \"function\") # Be sure to use tensorflow 2.0",
"_____no_output_____"
]
],
[
[
"## Load the dataset: Fashion MNIST",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# Fashio MNIST\nfashion_mnist = tf.keras.datasets.fashion_mnist\n(images, targets), (_, _) = fashion_mnist.load_data()\n# Get only a subpart of the dataset\n# Get only a subpart\nimages = images[:10000]\ntargets = targets [:10000]\n\nimages = images.reshape(-1, 784)\nimages = images.astype(float)\nscaler = StandardScaler()\nimages = scaler.fit_transform(images)\n\nprint(images.shape)\nprint(targets.shape)",
"(10000, 784)\n(10000,)\n"
]
],
[
[
"## Plot one of the data",
"_____no_output_____"
]
],
[
[
"targets_names = [\"T-shirt/top\", \"Trouser\", \"Pullover\", \"Dress\", \"Coat\", \"Sandal\", \n \"Shirt\", \"Sneaker\", \"Bag\", \"Ankle boot\"\n]\n# Plot one image\nplt.imshow(images[10].reshape(28, 28), cmap=\"binary\")\n#plt.title(targets_names[targets[10]])\nplt.title(targets_names[targets[10]])\nplt.show()",
"_____no_output_____"
],
[
"#print(\"First line of one image\", images[11][0])\nprint(\"First line of one image\", images[11])\nprint(\"Associated target\", targets[11])",
"First line of one image [-0.01426971 -0.02645579 -0.029489 -0.04635542 -0.06156617 -0.07641125\n -0.10509579 -0.16410192 -0.23986957 -0.36929666 -0.57063232 -0.6909092\n -0.7582382 -0.74450346 -0.17093142 0.80572169 0.60465021 0.69474334\n 0.01007169 -0.32085836 -0.20882718 -0.14379861 -0.11434416 -0.09302065\n 0.08584529 -0.04969764 -0.03368099 -0.01591863 -0.0181322 -0.02297209\n -0.03365679 -0.05814043 -0.08287213 -0.13053264 -0.2464668 -0.35905423\n -0.48335079 -0.63909239 -0.83575443 -0.98917162 -1.08347998 -1.07712864\n 0.7931674 1.2496451 1.35025207 1.68512162 1.97595936 1.43181167\n 2.97956664 4.68907298 4.88750284 0.23595608 -0.11565956 0.14562865\n -0.06100298 -0.03312088 -0.01964757 -0.02793878 -0.0481181 -0.07617253\n -0.12670992 -0.26684818 -0.39945708 -0.49720396 -0.62326614 -0.8195795\n -0.99379417 -1.04759214 -1.10371252 -1.10221791 1.08283564 1.22639277\n 1.35310524 1.34234162 1.66433217 2.15862735 2.75297169 3.22113197\n 4.62472272 3.87445967 -0.16599094 0.32418594 -0.087733 -0.0526323\n -0.02862848 -0.04242726 -0.06957184 -0.10501986 -0.21177968 -0.36570732\n -0.50377706 -0.63129117 -0.7545061 -0.92782181 -1.04671762 -1.04884575\n -1.10753111 -1.03315535 1.43294532 1.33033833 1.39162212 1.50249446\n 1.41472555 1.48664927 2.19750146 2.5207204 3.23681206 0.32439317\n -0.22921786 0.08719395 -0.11524194 -0.06595022 -0.03978101 -0.06151816\n -0.09394236 -0.14485093 -0.28258668 -0.45013464 -0.60762152 -0.70866125\n -0.80845132 -0.97106764 -1.06309306 -1.04395211 -1.11950469 -0.35989804\n 1.56262616 1.30932327 1.41614857 1.49002634 1.44030778 1.4974615\n 2.02811047 2.22341936 2.1189369 0.28273308 0.22687411 -0.22359138\n -0.07278968 -0.09631577 -0.05785819 -0.08665899 -0.12303533 -0.19276323\n -0.34094366 -0.53007774 -0.6636926 -0.76166986 -0.85810993 -1.01973474\n -1.10359032 -1.13389127 -1.13797187 0.19728184 1.30491585 1.12589712\n 1.56101992 1.5471799 1.35519155 1.61848413 1.8686844 1.86320923\n 0.84284685 1.09578392 0.74105846 -0.28563328 -0.1131897 -0.11759717\n -0.07138681 -0.10484842 -0.15218768 -0.23983624 -0.39446008 -0.58540856\n -0.70817066 -0.80613957 -0.8912735 -1.04743568 -1.11648233 -1.16203361\n -1.16480491 0.86892733 1.27412159 0.8998086 0.74428789 1.13274167\n 1.14002008 1.64475384 1.22579108 1.87626568 0.72713619 -0.21425058\n -0.44976207 -0.3588039 -0.26052139 -0.14642704 -0.09057754 -0.12852483\n -0.17658578 -0.27962415 -0.43604854 -0.62328729 -0.74417079 -0.83698675\n -0.91538507 -1.05836072 -1.09984451 -1.18744141 -1.19142578 1.24141786\n 1.39079751 1.49192297 1.27955426 1.30948745 1.17061076 0.86607308\n 1.27421913 0.79750725 -0.86719519 -0.69061632 -0.50423389 -0.42229875\n -0.30440602 -0.16353165 -0.09817535 -0.14372941 -0.20517067 -0.30866173\n -0.4655249 -0.65221334 -0.76683863 -0.85659993 -0.93256978 -1.06226401\n -1.15171237 -1.21294298 -0.55403601 1.46120819 0.97836915 1.05122066\n 1.2521523 1.05790293 1.35951983 0.90500191 1.55701257 0.82622186\n -0.93881345 -0.7662494 -0.57465574 -0.48552019 -0.34738009 -0.18855983\n -0.10483514 -0.16127624 -0.22554475 -0.32839989 -0.48754623 -0.66943952\n -0.77552861 -0.86498292 -0.94273549 -1.06015652 -1.18041842 -1.23791689\n 0.42552833 1.46179792 0.99490898 0.75506225 0.87837333 0.82699162\n 1.09938829 0.76830616 1.48553714 -0.13338616 0.50592885 -0.83182562\n -0.65812 -0.54406795 -0.39662058 -0.21430757 -0.11419072 -0.17789518\n -0.23568605 -0.33542269 -0.5026126 -0.67620553 -0.77596799 -0.86788207\n -0.94980187 -1.03197874 -1.22037631 -1.30832137 1.13203817 1.20044543\n 1.26727922 1.22318096 1.33469514 1.2591838 1.27789102 0.95415321\n 1.45083593 -1.14975179 -0.0817779 1.07590662 -0.71352465 -0.61851141\n -0.45102226 -0.23988228 -0.1324622 -0.1914184 -0.23850724 -0.33502594\n -0.50210849 -0.67112987 -0.76673944 -0.8616405 -0.96676107 -1.0848351\n -1.3330483 -0.93497502 1.45610367 1.06754889 1.26636853 1.12103986\n 0.83294083 1.32533583 0.96137914 0.8823002 1.43281281 1.19611371\n -0.78940528 1.86544193 -0.74636813 -0.65262812 -0.50618527 -0.26376513\n -0.14691646 -0.20208667 -0.24647794 -0.34047837 -0.50463299 -0.66562681\n -0.76193944 -0.87453007 -1.02396861 -1.2315534 -1.51364781 -0.22477969\n 1.36864633 0.97874683 1.13715509 1.05688341 0.99487436 1.40832046\n 0.59156431 0.94867054 1.34348434 1.46512153 0.55580094 1.79155088\n 1.05012863 -0.67067287 -0.54930031 -0.2968015 -0.15491047 -0.21450816\n -0.261535 -0.36080841 -0.53730463 -0.70325988 -0.81421065 -0.94111069\n -1.08418556 -1.34365865 -1.53886075 1.09326051 0.72413821 1.27757173\n 1.36520155 1.17770547 1.0023395 1.39555822 0.29493432 1.10901936\n 1.36430898 1.27440447 1.52040376 1.40357315 1.72718391 0.1853037\n -0.57266526 -0.33349732 -0.18106813 -0.27035229 -0.32539614 -0.42952929\n -0.61751986 -0.7906786 -0.89035399 -0.99618473 -1.1655271 -1.43209714\n -0.09950582 1.43909587 0.80004613 0.88559108 1.40804576 1.33663711\n 1.00766279 1.4018325 0.27208395 1.09470572 1.42729615 1.26618628\n 1.41174747 1.45821099 1.71015214 1.01925997 0.4601322 -0.36757044\n -0.24958781 -0.3531048 -0.40241884 -0.49907564 -0.69135965 -0.85359971\n -0.9331706 -1.0059672 -1.2177602 -1.54149264 1.06742005 1.19680318\n 1.16583857 1.04905231 0.80970041 1.20411735 1.24623527 0.93697892\n 0.42037146 1.01432568 1.45360261 1.25038614 1.51241082 1.47613898\n 0.92463771 -0.70060342 -0.62144365 -0.39567218 -0.31147884 -0.40192164\n -0.45021433 -0.54773943 -0.75003079 -0.889456 -0.98063839 -1.07747814\n -1.29340698 -0.73928768 1.42310729 1.18867558 1.29652988 1.37945647\n 1.18486113 0.53438163 0.56912652 1.05669556 0.45154219 0.81022867\n 1.44123053 1.22117476 1.51323768 1.10025946 -0.84443622 -0.71082151\n -0.62981211 -0.41576178 -0.33145798 -0.4375847 -0.49080625 -0.59254976\n -0.79668158 -0.93801891 -1.02130727 -1.11492415 -1.35022588 0.83375288\n 0.9741596 0.4062541 0.82345526 0.99971607 1.41325802 1.38631373\n 0.82115561 1.03621816 1.37633608 1.41019057 1.43307373 1.33830106\n 1.56303358 1.2326212 -0.83324214 -0.68996128 -0.60036851 -0.41411856\n -0.30332172 -0.43661943 -0.50963747 -0.61804526 -0.82143658 -0.95207361\n -1.007129 -1.12351256 -0.74667893 1.42122933 1.13385827 1.18497379\n 0.92903272 0.59292314 0.58084998 0.65192725 1.31203334 1.15530336\n 0.60156289 1.43433833 1.57231525 1.361918 1.57407123 1.10104004\n -0.82047003 -0.6717897 -0.59381484 -0.40266963 -0.27443878 -0.40163268\n -0.47645656 -0.57112574 -0.75359002 -0.90482991 -1.00654795 -1.10010001\n 0.84646653 1.33590939 1.12318718 1.05983988 1.30375784 1.41841835\n 1.3363515 0.78329442 0.72603604 1.06772811 1.03728983 0.94268209\n 1.58352665 1.40736874 1.56396874 0.96402622 -0.79100683 -0.64317699\n -0.55055123 -0.35674061 -0.26298786 -0.36483148 -0.35501478 -0.56550535\n -0.76427867 -0.88093481 -0.95714593 0.26300404 1.49151056 0.60123139\n 1.23314614 1.143365 1.10292773 1.21793326 1.30989735 1.11852481\n 1.34363077 1.37704795 -0.41238875 0.42876074 1.77110004 1.48771853\n 1.67709496 0.81572133 -0.7339355 -0.57912664 -0.47893486 -0.30785098\n -0.2529033 -0.35287467 -0.42241314 -0.53742101 -0.69523159 -0.48322565\n 0.57649233 1.85134507 0.9703557 0.90721107 0.53503501 1.08207286\n 1.22790733 1.24437467 1.30849615 1.11971627 1.34908479 -0.64304466\n -1.38817988 0.69940517 1.86107934 1.56810302 1.7514223 0.72922458\n -0.67125106 -0.50747585 -0.42746762 -0.27689345 -0.21764707 -0.31533525\n 1.09716701 3.09682197 2.34175977 2.00796236 1.85994557 1.78597139\n 1.49141381 0.76297629 1.11039359 0.69358239 1.21783558 1.32207011\n 1.30769119 1.4354789 -0.5426532 -1.36111624 -1.24797109 0.81824301\n 1.96644103 1.71151651 1.86841471 0.54069192 -0.61478549 -0.41894205\n -0.37391927 -0.23491109 -0.18236822 0.34035482 4.02444776 3.30920932\n 2.29452031 1.8472915 1.73635327 1.85955328 1.58154728 1.45891677\n 0.75783736 1.06110739 1.11682494 1.46006007 1.55251473 0.62714951\n -1.26069746 -1.21787971 -1.12506426 0.83640561 2.11376884 1.84866534\n 1.99153545 0.45817771 -0.55353411 -0.33494561 -0.31442902 -0.19052615\n -0.14160236 2.93079659 5.14991601 3.31015404 2.4402553 1.95391685\n 1.96093639 2.10885636 1.66470037 1.5670484 1.42605195 1.03439231\n 0.57767735 1.22668387 1.64488703 -1.0901502 -1.14072666 -1.04099027\n -1.03382637 0.81150532 2.25649299 2.09431908 2.11219737 0.25860424\n -0.50542985 -0.27819146 -0.26277875 -0.15540351 -0.09737914 0.22730653\n 4.98953189 4.07372805 2.88331858 2.24493644 2.21334692 2.30127177\n 1.80874389 1.60351937 1.52082639 1.52471192 1.38291296 1.67601794\n -0.24487056 -0.97710244 -1.02967184 -0.98082293 -0.93945674 0.89027942\n 2.46430504 2.25517974 2.33765721 0.20729654 -0.45056135 -0.14513081\n -0.21182513 -0.11366213 -0.05702124 -0.09821816 -0.1785151 0.31968873\n 1.37577775 1.90665939 2.4520196 2.67288921 2.2232822 1.87944656\n 1.67634924 1.53152839 1.4299862 -0.162791 -0.81210479 -0.85896501\n -0.91661542 -0.87628179 -0.83240929 0.60715159 2.67395709 2.65972227\n 2.0834714 -0.26792583 -0.40009454 -0.14170013 -0.15920537 -0.08310377\n -0.02780774 -0.0459571 -0.09752313 -0.20921424 -0.33708195 -0.41731463\n -0.42712608 0.50525833 1.05313252 1.08014246 0.48423045 -0.21840563\n -0.76160286 -0.69278859 -0.64574229 -0.68429498 -0.73804133 -0.66329112\n -0.60337338 -0.47578426 1.14396189 0.57528488 0.0308716 -0.39704551\n -0.28848398 -0.1579693 -0.0929556 -0.03456268]\nAssociated target 9\n"
]
],
[
[
"# Create the model\n",
"_____no_output_____"
],
[
"# Create the model",
"_____no_output_____"
]
],
[
[
"# Flatten\nmodel = tf.keras.models.Sequential()\n#model.add(tf.keras.layers.Flatten(input_shape=[28, 28]))\n\n# Add the layers\nmodel.add(tf.keras.layers.Dense(256, activation=\"relu\"))\nmodel.add(tf.keras.layers.Dense(128, activation=\"relu\"))\nmodel.add(tf.keras.layers.Dense(10, activation=\"softmax\"))\n\nmodel_output = model.predict(images[0:1])\nprint(model_output, targets[0:1])",
"[[0.17820482 0.05316375 0.07201441 0.1023543 0.02913541 0.17055362\n 0.06326886 0.24632096 0.02520118 0.05978273]] [9]\n"
]
],
[
[
"## Model Summary",
"_____no_output_____"
]
],
[
[
"model.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) multiple 200960 \n_________________________________________________________________\ndense_1 (Dense) multiple 32896 \n_________________________________________________________________\ndense_2 (Dense) multiple 1290 \n=================================================================\nTotal params: 235,146\nTrainable params: 235,146\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"## Compile the model",
"_____no_output_____"
]
],
[
[
"# Compile the model\nmodel.compile(\n loss=\"sparse_categorical_crossentropy\",\n optimizer=\"sgd\",\n metrics=[\"accuracy\"]\n)",
"_____no_output_____"
]
],
[
[
"## Caterogical cross entropy",
"_____no_output_____"
]
],
[
[
"images_test = images[:5]\nlabels_test = targets[:5]\n\nprint(images_test.shape)\nprint(labels_test)\n\noutputs_test = model.predict(images_test)\n\nprint(outputs_test.shape)\nprint(\"Output\", outputs_test)\n\n#print(\"\\nLabels\", labels_test)\n\nfiltered_outputs_test = outputs_test[np.arange(5), labels_test]\nprint(\"\\nFiltered output\", filtered_outputs_test)\n\nlog_filtered_output = np.log(filtered_outputs_test)\nprint(\"\\nLog Filtered output\", log_filtered_output)\n\nprint(\"Mean\", log_filtered_output.mean())\nprint(\"Mean\", -log_filtered_output.mean())",
"(5, 784)\n[9 0 0 3 0]\n(5, 10)\nOutput [[0.00155602 0.00106303 0.00698406 0.00284724 0.01145798 0.03515041\n 0.01286932 0.0088392 0.04853413 0.8706986 ]\n [0.7814132 0.00516847 0.01360413 0.0021324 0.01019276 0.00489966\n 0.15709291 0.00928725 0.01079097 0.00541825]\n [0.07476368 0.22221217 0.0560216 0.36471143 0.03012619 0.0860177\n 0.05936769 0.04129038 0.03758162 0.02790763]\n [0.24922626 0.1875557 0.11506705 0.19797364 0.03391237 0.02039414\n 0.09415954 0.03401936 0.0236186 0.04407331]\n [0.12672135 0.25767553 0.00981988 0.46853614 0.06494886 0.01375138\n 0.0213926 0.01535748 0.01641455 0.00538218]]\n\nFiltered output [0.8706986 0.7814132 0.07476368 0.19797364 0.12672135]\n\nLog Filtered output [-0.13845943 -0.2466512 -2.5934231 -1.6196214 -2.0657647 ]\nMean -1.3327839\nMean 1.3327839\n"
]
],
[
[
"## Train the model",
"_____no_output_____"
]
],
[
[
"history = model.fit(images, targets, epochs=1)",
"10000/10000==============================] - 1s 60us/sample - loss: 1.0488 - acc: 0.6868\n"
],
[
"loss_curve = history.history[\"loss\"]\nacc_curve = history.history[\"accuracy\"]\n\nplt.plot(loss_curve)\nplt.title(\"Loss\")\nplt.show()\n\nplt.plot(acc_curve)\nplt.title(\"Accuracy\")\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7af3650e2dc6f731295b49441e67b79b7180879 | 460,329 | ipynb | Jupyter Notebook | jiuqu/student_count_predict.ipynb | LeonKennedy/jupyter_space | 0fc79a5318596c5519a8f65318553528106126f1 | [
"MIT"
] | null | null | null | jiuqu/student_count_predict.ipynb | LeonKennedy/jupyter_space | 0fc79a5318596c5519a8f65318553528106126f1 | [
"MIT"
] | null | null | null | jiuqu/student_count_predict.ipynb | LeonKennedy/jupyter_space | 0fc79a5318596c5519a8f65318553528106126f1 | [
"MIT"
] | null | null | null | 232.372034 | 190,356 | 0.862981 | [
[
[
"import pandas as pd\nimport numpy as np\nfrom scipy import linalg\nimport sys\nimport os\nfrom qkids import Week\nfrom qkids.DatabasePool import get_schedule_connection\nsys.path.append(\"..\")\nfrom schedule.DataFarm import DataFarm\nimport matplotlib.pyplot as plt\nfrom qkids import Week",
"_____no_output_____"
]
],
[
[
"# get historical actual data",
"_____no_output_____"
]
],
[
[
"datafarm = DataFarm()\nhistorical_data = datafarm.run()",
"_____no_output_____"
],
[
"week_data = historical_data.sum().sort_index()\nweek_data = week_data # 2018年以来 没周人数\n\n\nvacation_week_weight = {'201826':0.5,\n '201827':0.6,\n '201828':0.7,\n '201829':0.8,\n '201830':0.9,\n '201831':0.9,\n '201832':0.9,\n '201833':1,\n '201834':1,\n '201835':1,\n '201904': 0.4,\n '201905': 0.4,\n '201906': -0.1,\n '201907': 0.5,\n '201908': 0.5, # 虽然没有全天 但是暑假券还能用\n '201909': 0.5 # 虽然没有全天 但是暑假券还能用\n }\nwhole_day_week = pd.Series(0, index = week_data.index, dtype='float') # 寒暑假课\nfor i, value in vacation_week_weight.items():\n whole_day_week[i] = value",
"_____no_output_____"
],
[
"# 每周数据\nplt.figure(0)\nweek_data.plot(figsize=(80, 19), label='111', kind='bar')",
"_____no_output_____"
]
],
[
[
"### $y_i = c_1e^{-x_i} + c_2x_i + c_3z_i$",
"_____no_output_____"
]
],
[
[
"y = week_data.values\nx = np.r_[1:len(y)+1]\nz = whole_day_week.values\n# A = np.c_[np.exp(-x)[:, np.newaxis], x[:, np.newaxis], z[:, np.newaxis]]\nA = np.c_[x[:, np.newaxis], z[:, np.newaxis]]\nc, resid, rank, sigma = linalg.lstsq(A, y)\nxi2 = np.r_[1:len(y):10j]\nyi2 = c[0]*x + c[1]*z\n\nplt.figure(1, figsize=(80,30))\nplt.bar(x, y)\nplt.plot(x,yi2, 'r')\n# plt.axis([0,1.1,3.0,5.5])\nplt.xlabel('$x_i$')\nplt.title('Data fitting with linalg.lstsq')\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### 减去寒暑假影响后 使用exponentially weighted windows",
"_____no_output_____"
]
],
[
[
"plt.figure(2, figsize=(80, 19))\nbase_data = week_data - c[1]*z \nbase_data.plot(style='b--')\nbase_data.ewm(span=5).mean().plot(style='r')",
"_____no_output_____"
]
],
[
[
"#### 细粒度拟合 (roomtype, chapter)",
"_____no_output_____"
]
],
[
[
"historical_data.groupby(level=[1,2]).sum()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7af407d58ee0c4c73d9af4b83244dddfab2716a | 869,377 | ipynb | Jupyter Notebook | examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb | LSSTDESC/ssi-tools | 9805ec128fe8c8b02367810002155860c4600f63 | [
"BSD-3-Clause"
] | 2 | 2021-08-22T09:59:39.000Z | 2022-03-10T02:49:16.000Z | examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb | LSSTDESC/fsi-tools | 9805ec128fe8c8b02367810002155860c4600f63 | [
"BSD-3-Clause"
] | 1 | 2021-06-11T11:36:56.000Z | 2021-06-11T11:36:56.000Z | examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb | LSSTDESC/fsi-tools | 9805ec128fe8c8b02367810002155860c4600f63 | [
"BSD-3-Clause"
] | 1 | 2022-03-08T14:44:45.000Z | 2022-03-08T14:44:45.000Z | 1,646.547348 | 520,888 | 0.961019 | [
[
[
"from desc_dc2_dm_data import REPOS\nfrom lsst.daf.persistence import Butler\n\nimport matplotlib.pyplot as plt\n\n%matplotlib inline",
"_____no_output_____"
],
[
"import numpy as np\nimport fitsio\n\nfrom ssi_tools.layout_utils import make_hexgrid_for_tract\n\nimport lsst.geom as geom",
"_____no_output_____"
]
],
[
[
"## First Let's Get the Butler and a Tract",
"_____no_output_____"
]
],
[
[
"butler = Butler(REPOS['2.2i_dr6_wfd'])\nskymap = butler.get(\"deepCoadd_skyMap\")",
"_____no_output_____"
],
[
"# this list is hard coded - the gen 2 butler doesn't have a method for introspection\nmeta = {}\nmeta[\"all_tracts\"] = \"\"\"2723 2730 2897 2904 3076 3083 3259 3266 3445 3452 3635 3642 3830 3837 4028 4035 4230 4428 4435 4636 4643 4851 4858 5069\n2724 2731 2898 2905 3077 3084 3260 3267 3446 3453 3636 3643 3831 4022 4029 4224 4231 4429 4436 4637 4644 4852 4859 5070\n2725 2732 2899 2906 3078 3085 3261 3268 3447 3454 3637 3825 3832 4023 4030 4225 4232 4430 4437 4638 4645 4853 4860 5071\n2726 2733 2900 2907 3079 3086 3262 3441 3448 3631 3638 3826 3833 4024 4031 4226 4233 4431 4438 4639 4646 4854 5065 5072\n2727 2734 2901 2908 3080 3256 3263 3442 3449 3632 3639 3827 3834 4025 4032 4227 4234 4432 4439 4640 4647 4855 5066 5073\n2728 2735 2902 3074 3081 3257 3264 3443 3450 3633 3640 3828 3835 4026 4033 4228 4235 4433 4440 4641 4648 4856 5067 5074\n2729 2896 2903 3075 3082 3258 3265 3444 3451 3634 3641 3829 3836 4027 4034 4229 4236 4434 4441 4642 4850 4857 5068\"\"\".split()",
"_____no_output_____"
],
[
"ti = skymap[4030]",
"_____no_output_____"
]
],
[
[
"## Make a Grid of objects\n\nWe will use the `fsi_tools` package to make a hexagonal grid of object positions.",
"_____no_output_____"
]
],
[
[
"grid = make_hexgrid_for_tract(ti, rng=10)",
"_____no_output_____"
],
[
"plt.figure()\nplt.plot(grid[\"x\"], grid[\"y\"], '.')\nax = plt.gca()\nax.set_aspect('equal')\nplt.xlim(0, 640)\nplt.ylim(0, 640)",
"_____no_output_____"
]
],
[
[
"Neat!",
"_____no_output_____"
],
[
"## Building the Source Catalog",
"_____no_output_____"
]
],
[
[
"srcs = fitsio.read(\n \"/global/cfs/cdirs/lsst/groups/fake-source-injection/DC2/catalogs/\"\n \"cosmoDC2_v1.1.4_small_fsi_catalog.fits\",\n)",
"_____no_output_____"
],
[
"msk = srcs[\"rmagVar\"] <= 25\nsrcs = srcs[msk]",
"_____no_output_____"
],
[
"rng = np.random.RandomState(seed=10)\ninds = rng.choice(len(srcs), size=len(grid), replace=True)\n\ntract_sources = srcs[inds].copy()\ntract_sources[\"raJ2000\"] = np.deg2rad(grid[\"ra\"])\ntract_sources[\"decJ2000\"] = np.deg2rad(grid[\"dec\"])",
"_____no_output_____"
]
],
[
[
"## Now Cut to Just the First Patch",
"_____no_output_____"
]
],
[
[
"patch = ti[0]\n\n# TODO: we may want to expand this box to account for nbrs light\nmsk = patch.getOuterBBox().contains(grid[\"x\"], grid[\"y\"])\n\nprint(\"found %d objects in patch %s\" % (np.sum(msk), \"%d,%d\" % patch.getIndex()))",
"found 4741 objects in patch 0,0\n"
]
],
[
[
"## Run the Stack FSI Code",
"_____no_output_____"
]
],
[
[
"fitsio.write(\"ssi.fits\", tract_sources[msk], clobber=True)",
"_____no_output_____"
],
[
"%%time\n\n!insertFakes.py \\\n /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/desc_dm_drp/v19.0.0-v1/rerun/run2.2i-coadd-wfd-dr6-v1 \\\n --output test/ \\\n --id tract=4030 patch=0,0 \\\n filter=r -c fakeType=ssi.fits \\\n --clobber-config --no-versions",
"CameraMapper INFO: Loading exposure registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/registry.sqlite3\nCameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/CALIB/calibRegistry.sqlite3\nCameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/CALIB/calibRegistry.sqlite3\nCameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/desc_dm_drp/v19.0.0-v1/CALIB/calibRegistry.sqlite3\nLsstCamMapper WARN: Unable to find valid calib root directory\nLsstCamMapper WARN: Unable to find valid calib root directory\nCameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/CALIB/calibRegistry.sqlite3\nCameraMapper INFO: Loading exposure registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/registry.sqlite3\nCameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/CALIB/calibRegistry.sqlite3\nLsstCamMapper WARN: Unable to find valid calib root directory\nCameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/CALIB/calibRegistry.sqlite3\nCameraMapper INFO: Loading exposure registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/registry.sqlite3\nCameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/shared/DC2-prod/Run2.2i/desc_dm_drp/v19.0.0/CALIB/calibRegistry.sqlite3\nCameraMapper INFO: Loading exposure registry from /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/desc_dm_drp/v19.0.0-v1/registry.sqlite3\nCameraMapper INFO: Loading calib registry from /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/desc_dm_drp/v19.0.0-v1/CALIB/calibRegistry.sqlite3\nroot INFO: Running: /global/homes/b/beckermr/.conda/envs/dmstack2020.40w/lsst_home/stack/miniconda/Linux64/pipe_tasks/20.0.0-28-g282f9e7e+feda6aebd8/bin/insertFakes.py /global/cfs/cdirs/lsst/production/DC2_ImSim/Run2.2i/desc_dm_drp/v19.0.0-v1/rerun/run2.2i-coadd-wfd-dr6-v1 --output test/ --id tract=4030 patch=0,0 filter=r -c fakeType=fsi.fits --clobber-config --no-versions\ninsertFakes INFO: Adding fakes to: tract: 4030, patch: 0,0, filter: r\ninsertFakes INFO: Adding mask plane with bitmask 131072\nnumexpr.utils INFO: Note: NumExpr detected 64 cores but \"NUMEXPR_MAX_THREADS\" not set, so enforcing safe limit of 8.\ninsertFakes INFO: Removing 0 rows with HLR = 0 for either the bulge or disk\ninsertFakes INFO: Removing 0 rows of galaxies with nBulge or nDisk outside of 0.30 <= n <= 6.20\ninsertFakes INFO: Making 4738 fake galaxy images\n/global/homes/b/beckermr/.conda/envs/dmstack2020.40w/lib/python3.7/site-packages/galsim/errors.py:420: GalSimWarning: A component to be convolved is not analytic in real space. Cannot use real space convolution. Switching to DFT method.\n warnings.warn(message, GalSimWarning)\ninsertFakes INFO: Making 0 fake star images\nCPU times: user 17.8 s, sys: 3.4 s, total: 21.2 s\nWall time: 16min 46s\n"
]
],
[
[
"## Make an Image",
"_____no_output_____"
]
],
[
[
"butler = Butler(\"./test/\")\n\ncutoutSize = geom.ExtentI(1001, 1001)\nra = np.mean(tract_sources[msk][\"raJ2000\"]) / np.pi * 180.0\ndec = np.mean(tract_sources[msk][\"decJ2000\"]) / np.pi * 180.0\npoint = geom.SpherePoint(ra, dec, geom.degrees)\n\nskymap = butler.get(\"deepCoadd_skyMap\")\ntractInfo = skymap.findTract(point)\npatchInfo = tractInfo.findPatch(point)\nxy = geom.PointI(tractInfo.getWcs().skyToPixel(point))\nbbox = geom.BoxI(xy - cutoutSize//2, cutoutSize)\ncoaddId = {\n 'tract': tractInfo.getId(), \n 'patch': \"%d,%d\" % patchInfo.getIndex(),\n 'filter': 'r'\n}\nprint(coaddId)\n\nimage = butler.get(\"deepCoadd_sub\", bbox=bbox, immediate=True, dataId=coaddId)\nfake_image = butler.get(\"fakes_deepCoadd_sub\", bbox=bbox, immediate=True, dataId=coaddId)\n\nfig, axes = plt.subplots(ncols=3, figsize=(15, 5))\naxes[0].imshow(np.arcsinh(image.maskedImage.image.array/np.sqrt(image.variance.array)))\naxes[0].set_title(\"image\")\naxes[1].imshow(np.arcsinh(fake_image.maskedImage.image.array/np.sqrt(image.variance.array)))\naxes[1].set_title(\"FSI image\")\naxes[2].imshow(np.arcsinh((fake_image.maskedImage.image.array - image.maskedImage.image.array)/1e-3))\naxes[2].set_title(\"diff. image\")\nplt.show()",
"{'tract': 4030, 'patch': '0,0', 'filter': 'r'}\n"
]
],
[
[
"## Run Detection and Matching\n\nWe're using `sep`, via the DES Y6 settings from `esheldon/sxdes`, here for simplicity. Eventually, one should use the stack itself. ",
"_____no_output_____"
]
],
[
[
"import sep\nfrom sxdes import run_sep\nimport esutil.numpy_util\nfrom ssi_tools.matching import do_balrogesque_matching\n\nsep.set_extract_pixstack(1_000_000)\n\ndef _run_sep_and_add_radec(ti, img, err=None, minerr=None):\n if err is None:\n err = np.sqrt(img.variance.array.copy())\n img = img.image.array.copy()\n \n if minerr is not None:\n msk = err < minerr\n err[msk] = minerr\n \n cat, seg = run_sep(\n img,\n err,\n )\n cat = esutil.numpy_util.add_fields(cat, [(\"ra\", \"f8\"), (\"dec\", \"f8\")])\n wcs = ti.getWcs()\n cat[\"ra\"], cat[\"dec\"] = wcs.pixelToSkyArray(cat[\"x\"], cat[\"y\"], degrees=True)\n return cat, seg\n",
"_____no_output_____"
],
[
"orig_det_cat, orig_det_seg = _run_sep_and_add_radec(ti, image)\n\nfsi_det_cat, fsi_det_seg = _run_sep_and_add_radec(ti, fake_image)\n\nfsi_truth_cat, fsi_truth_seg = _run_sep_and_add_radec(\n ti,\n (fake_image.image.array - image.image.array).copy(),\n np.zeros_like(np.sqrt(fake_image.variance.array.copy())),\n minerr=np.mean(np.sqrt(fake_image.variance.array.copy())),\n)\nprint(\"found truth srcs:\", fsi_truth_cat.shape)",
"truth srcs: (289,)\n"
],
[
"match_flag, match_index = do_balrogesque_matching(\n fsi_det_cat, orig_det_cat, fsi_truth_cat, \"flux_auto\",\n)",
"_____no_output_____"
],
[
"ms = 2\ntst = np.arcsinh(fake_image.maskedImage.image.array/np.sqrt(image.variance.array))\nvmin = tst.min()\nvmax = tst.max()\n\nfig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15, 10))\n\nfor ax in axes.ravel()[:-1]:\n ax.set_xlabel(\"x [pixels]\")\n ax.set_ylabel(\"y [pixels]\")\n\n\naxes[0, 0].imshow(\n np.arcsinh(image.maskedImage.image.array/np.sqrt(image.variance.array)), \n vmin=vmin, vmax=vmax,\n origin='lower',\n)\naxes[0, 0].set_title(\"image\")\naxes[0, 0].plot(orig_det_cat[\"x\"], orig_det_cat[\"y\"], '.r', ms=ms)\nu = np.random.uniform(size=orig_det_seg.max()+1)\naxes[1, 0].imshow(\n u[orig_det_seg],\n origin='lower',\n)\naxes[1, 0].set_title(\"image seg map\")\n\naxes[0, 1].imshow(\n np.arcsinh(fake_image.maskedImage.image.array/np.sqrt(image.variance.array)),\n vmin=vmin, vmax=vmax,\n origin='lower', \n) \naxes[0, 1].set_title(\"FSI image\")\naxes[0, 1].plot(fsi_det_cat[\"x\"], fsi_det_cat[\"y\"], '.r', ms=ms)\nu = np.random.uniform(size=fsi_det_seg.max()+1)\naxes[1, 1].imshow(\n u[fsi_det_seg], \n origin='lower',\n)\naxes[1, 1].set_title(\"FSI image seg map\")\n\naxes[0, 2].imshow(\n np.arcsinh((fake_image.maskedImage.image.array - image.maskedImage.image.array)/np.sqrt(image.variance.array)),\n origin='lower', \n)\naxes[0, 2].set_title(\"diff. image\")\naxes[0, 2].plot(fsi_truth_cat[\"x\"], fsi_truth_cat[\"y\"], '.r', ms=ms)\n\ncoadd_zp = 2.5*np.log10(image.getPhotoCalib().getInstFluxAtZeroMagnitude())\nmsk = match_flag < 2\ntrue_mag = coadd_zp - 2.5*np.log10(fsi_truth_cat[\"flux_auto\"][match_index[msk]])\nobs_mag = coadd_zp - 2.5*np.log10(fsi_det_cat[\"flux_auto\"][msk])\ndmag = obs_mag - true_mag\naxes[1, 2].plot(true_mag, dmag, '.k')\naxes[1, 2].set_xlim(25, 19)\naxes[1, 2].set_xlabel(\"true r-band mag auto\")\naxes[1, 2].set_ylabel(\"obs - true r-band mag auto\")\n\nfig.savefig(\"fsi_matched.pdf\")\nplt.show()\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e7af44e0d1a3fec68aef9a6e7fe89114ab8729dc | 92,833 | ipynb | Jupyter Notebook | base_functions.ipynb | sameerkulkarni/financial_simulations | 2f058d885d14ff39948c6030c298998ca92d4f72 | [
"MIT"
] | null | null | null | base_functions.ipynb | sameerkulkarni/financial_simulations | 2f058d885d14ff39948c6030c298998ca92d4f72 | [
"MIT"
] | null | null | null | base_functions.ipynb | sameerkulkarni/financial_simulations | 2f058d885d14ff39948c6030c298998ca92d4f72 | [
"MIT"
] | null | null | null | 120.562338 | 11,054 | 0.80843 | [
[
[
"<a href=\"https://colab.research.google.com/github/sameerkulkarni/financial_simulations/blob/master/base_functions.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Financial Simulations\n\nMeasure different investment strategies",
"_____no_output_____"
],
[
"## Helper Functions\nRun me before running any of the lower cells.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nfindata = pd.read_csv(\"https://raw.githubusercontent.com/sameerkulkarni/financial_simulations/master/returns.csv\", sep=\",\")\n# Add data of monthly rate of change in adj close.\nfindata['Scale'] = findata['Adj Close'].pct_change() +1\n# Adjust the scale to inflation every month.\nfindata['Scale_InfAdj'] = findata['Scale'] - (findata['Inflation']/1200)\nfindata = findata.drop(['Open', 'High', 'Low'], axis=1)\nfin_index = pd.Index(findata['Date'])\n\n# Number of times to run any of the simulations below\nNUM_SAMPLES=10000\n\ndef pretty_plot_fn(distribution, heighlight_value, message):\n plt.hist(distribution, bins=100)\n plt.title(message)\n plt.axvline(heighlight_value,color='r')\n plt.show()\n\n# The three functions below calucate the rate of returs given a start point and \n# a duration. e.g. A value of 1.07 would mean a 7% average return on investment\n# annually over the investment period.\n\n# 1. Basic Strategy: Invest once; for the entire duration.\ndef calculate_returns(startpoint, duration):\n begin = findata.loc[startpoint]['Adj Close']\n end = findata.loc[startpoint+(duration*12)]['Adj Close']\n total_returns = 1+ ((end-begin)/begin)\n avg_returns = (total_returns**(1.0/duration))\n return avg_returns\n\n# 2. Secondary strategy: If the intended retirement would cause an average\n# return of less than expected_returns, then wait a max of extended_duration\n# years and retire as soon as it reaches expected_returns. If waiting does\n# not reachexpected returns, retire at the end of the extended_duration.\ndef flexible_end_date(startpoint, duration, extended_duration=2, expected_returns=1.065):\n begin = findata.loc[startpoint]['Adj Close']\n intended_end_month= startpoint+(duration*12)\n end = findata.loc[intended_end_month]['Adj Close']\n total_returns = 1+ ((end-begin)/begin)\n avg_returns = (total_returns**(1.0/duration))\n # print(\"%2d, %2d, %3.3f, %3.3f, %1.3f, %1.3f\" %(startpoint, intended_end_month, begin, end, total_returns, avg_returns))\n if (avg_returns > expected_returns):\n return avg_returns\n for i in range(intended_end_month,intended_end_month+(extended_duration*12)):\n end = findata.loc[i]['Adj Close']\n total_returns= 1+ ((end-begin)/begin)\n avg_returns = (total_returns**(1.0/((i-startpoint)/12)))\n # print(\"%2d, %2d, %3.3f, %3.3f, %1.3f, %1.3f\" %(startpoint, i, begin, end, total_returns, avg_returns))\n if avg_returns >= expected_returns:\n return avg_returns\n return avg_returns\n\n# 3. Capped Gains Strategy: Here your returns are capped between [0,9] on a yearly \n# basis. Note that this is an extremely uncommon investment vehicle, and \n# there is a high chance that this is something you would not want to pick\n# if at all available.\ndef capped_gains_strategy(startpoint, duration):\n returns=[]\n for i in range(0,duration):\n start_month=startpoint +(i*12)\n end_month=startpoint +((i+1)*12)\n begin = findata.loc[start_month]['Adj Close']\n end = findata.loc[end_month]['Adj Close']\n yearly_return = 1+ ((end-begin)/begin)\n if yearly_return < 1:\n yearly_return = 1\n if yearly_return > 1.095:\n yearly_return = 1.095\n returns.append(yearly_return)\n # print(returns)\n avg_returns = np.average(returns)\n return avg_returns\n\n# The next three functions also take into account inflation for each of the\n# months that we are taking the returns into account. In months of large market\n# fluctuations, inflation also changes, this would allow one to take into \n# account real investment returns for those months. e.g. if the market drops\n# a lot, hypothesis is that that consumer goods would also see a significant \n# drop. It would be very useful to take this into account.\ndef current_return(month, investment_type=\"snp500\"):\n # investment_type: 0=s&p500, 1=capped_s&p500, 2=bank, 3=bonds(tbd)\n if investment_type == \"capped_snp500\":\n return max(1, min((1+(.09/12)), findata.loc[month]['Scale_InfAdj']))\n if investment_type == \"savings_account\":\n return (1.0 - (findata.loc[month]['Inflation']/1200))\n if investment_type == \"bonds\":\n # If invested in a bond, assume that you are unaffected by inflation.\n return 1.0\n if investment_type == \"snp500\":\n return findata.loc[month]['Scale_InfAdj']\n # Default case is if investing in an s&p 500. \n return findata.loc[month]['Scale_InfAdj']\n\n# Regular investment\ndef future_value(initial_amount, investment_amount, num_months, start_month, investment_type=0):\n # initial_amount: Initial amount to start the investment with.\n # investment_amount: Amount to be invested every month.\n # num_months: Number of months to invest.\n # start_month: When do you start investing the money.\n # investment_type: 0=s&p500, 1=capped_s&p500, 2=bank, 3=bonds(tbd)\n current_amount=initial_amount\n for i in range(start_month, (start_month+num_months)):\n current_amount+=investment_amount\n current_amount*=current_return(i, investment_type)\n return current_amount\n\ndef weighted_return(initial_rampup_duration, initial_amount, total_duration, trickle_invest, start_month, investment_type=0):\n # initial_rampup_horizon: Number of months to split the initital investment time.\n # initial_amount: Total amount in units to be invested initially.\n # total_horizon: Total investment horizon.\n # trickle_invest: \n investment_during_rampup = (initial_amount/initial_rampup_duration)+trickle_invest\n amount_after_initial_rampup=future_value(0,investment_during_rampup,initial_rampup_duration,start_month, investment_type)\n final_amount=future_value(amount_after_initial_rampup, trickle_invest, total_duration-initial_rampup_duration, start_month+initial_rampup_duration, investment_type)\n return final_amount",
"_____no_output_____"
]
],
[
[
"## One shot investment strategies\n\nThe strategies below mimic the one time investments. e.g. If you have a pot of money that you need to invest into the market for \"num_years\".",
"_____no_output_____"
]
],
[
[
"num_years = 25 #@param {type:\"slider\", min:1, max:60, step:1.0}\nstart_points=[random.randint(0,(92-num_years)*12) for i in range(NUM_SAMPLES)]\nyearly_returns = [calculate_returns(start_points[i],num_years) for i in range(len(start_points))]\nref_returns=np.median(yearly_returns)\npretty_plot_fn(yearly_returns, ref_returns, \"S&P 500 Returns for %d years (%1.3f).\"%(num_years,ref_returns))\nprint(\"%1.4f\"%ref_returns)",
"_____no_output_____"
],
[
"num_years = 16 #@param {type:\"slider\", min:1, max:60, step:1.0}\nflexible_years = 3 #@param {type:\"slider\", min:0, max:15, step:1.0}\n# min_acceptable_return is the avg. return that you would be comfortable \n# retiring with, a value of 1.03 means that your investment kept pace with \n# inflation (avg inflation assumed to be 1.03), 1.1 would mean that you would \n# like an average return of 10% per year (values above 1.07 may be unrealistic).\nmin_acceptable_return = 1.065 #@param {type:\"slider\", min:1.03, max:1.1, step:0.05}\nstart_points=[random.randint(0,(92-(num_years+flexible_years))*12) for i in range(NUM_SAMPLES)]\nyearly_returns = [flexible_end_date(start_points[i],num_years,flexible_years, min_acceptable_return) for i in range(len(start_points))]\nref_returns=np.median(yearly_returns)\npretty_plot_fn(yearly_returns, ref_returns, \"S&P 500 Returns for %d years (%1.3f).\"%(num_years,ref_returns))\nprint(\"%1.4f\"%ref_returns)",
"_____no_output_____"
],
[
"num_years = 15 #@param {type:\"slider\", min:1, max:60, step:1.0}\nstart_points=[random.randint(0,(92-num_years)*12) for i in range(NUM_SAMPLES)]\nyearly_returns = [capped_gains_strategy(start_points[i],num_years) for i in range(len(start_points))]\nref_returns=np.median(yearly_returns)\npretty_plot_fn(yearly_returns, ref_returns, \"CappedReturns for %d years (%1.3f).\"%(num_years,ref_returns))\nprint(\"%1.4f\"%ref_returns)",
"_____no_output_____"
]
],
[
[
"## Systematic monthly investments\n\nThese simulations simulate a typical method of saving. One would start with \nan initial investment amount (\"intial_amount\"), and would then invest some more\namount on a monthly basis (\"monthly_amount\").\n\nThese simulations also account for inflations during the months question, and \nthus try to paint the most accurate picture available. The final value is presented in current year dollar amounts to make it easier to visualize.\n",
"_____no_output_____"
]
],
[
[
"# Number of years one has before retirement.\nnum_years = 20 #@param {type:\"slider\", min:1, max:60, step:1.0}\n# The amount of money that one has at present that you would like to invest.\ninitial_amount=100 #@param {type:\"slider\", min:10, max:200, step:1.0}\n# If the amount of money is large it would be advisable to split the intial \n# amount of money over \"initial_rampup_months\" number of months. \ninitial_rampup_months=6 #@param {type:\"slider\", min:1, max:60, step:1.0}\n# Amount of money that one would like to invest every month.\nmonthly_amount=4 #@param {type:\"slider\", min:1, max:100, step:1.0}",
"_____no_output_____"
],
[
"# Invest in S&P 500\ninvestment_type = \"snp500\" #@param ['snp500', 'savings_account', 'bonds', 'capped_snp500']\nstart_points=[random.randint(1,(92-num_years)*12) for i in range(NUM_SAMPLES)]\nfinal_networths = [weighted_return(initial_rampup_months, initial_amount, (num_years*12), monthly_amount, start_points[i],investment_type) for i in range(len(start_points))]\nref_nw=np.median(final_networths)\npretty_plot_fn(final_networths, ref_nw, \"%s Net worths after %d years (%1.3f).\"%(investment_type, num_years,ref_nw))\nprint(\"Median final Networth = $%4.4f\"%ref_nw)",
"_____no_output_____"
],
[
"investment_type = \"bonds\" #@param ['snp500', 'savings_account', 'bonds', 'capped_snp500']\nstart_points=[random.randint(1,(92-num_years)*12) for i in range(NUM_SAMPLES)]\nfinal_networths = [weighted_return(initial_rampup_months, initial_amount, (num_years*12), monthly_amount, start_points[i],investment_type) for i in range(len(start_points))]\nref_nw=np.median(final_networths)\npretty_plot_fn(final_networths, ref_nw, \"%s Net worths after %d years (%1.3f).\"%(investment_type, num_years,ref_nw))\nprint(\"Median final Networth = $%4.4f\"%ref_nw)",
"_____no_output_____"
],
[
"investment_type = \"savings_account\" #@param ['snp500', 'savings_account', 'bonds', 'capped_snp500']\nstart_points=[random.randint(1,(92-num_years)*12) for i in range(NUM_SAMPLES)]\nfinal_networths = [weighted_return(initial_rampup_months, initial_amount, (num_years*12), monthly_amount, start_points[i],investment_type) for i in range(len(start_points))]\nref_nw=np.median(final_networths)\npretty_plot_fn(final_networths, ref_nw, \"%s Net worths after %d years (%1.3f).\"%(investment_type, num_years,ref_nw))\nprint(\"Median final Networth = $%4.4f\"%ref_nw)",
"_____no_output_____"
]
],
[
[
"## COVID-19 ish simulations\n\nGiven the current financial situation, the current markets are a-typical. Thus the simlations below show returns around past recessions.",
"_____no_output_____"
]
],
[
[
"# Bear Markets finder (more than 20% drop from the previous high)\n# https://www.investopedia.com/terms/b/bearmarket.asp\n# Top 11 Bear market dates = http://www.nbcnews.com/id/37740147/ns/business-stocks_and_economy/t/historic-bear-markets/#.XoCWDzdKh24\n\nbear_market_dates=['1929-09-01', '1946-05-01', '1961-12-01', '1968-11-01', '1973-01-01', '1980-11-01', '1987-08-01', '2000-03-01', '2007-10-01']\nbear_market_months=[fin_index.get_loc(bear_date) for bear_date in bear_market_dates]\nprint(bear_market_months)",
"[20, 220, 407, 490, 540, 634, 715, 866, 957]\n"
],
[
"num_years = 20 #@param {type:\"slider\", min:1, max:60, step:1.0}\ninitial_rampup_months=6 #@param {type:\"slider\", min:1, max:60, step:1.0}\ninitial_amount=100 #@param {type:\"slider\", min:10, max:200, step:1.0}\nmonthly_invest=4 #@param {type:\"slider\", min:1, max:100, step:1.0}\nmonth_offset=-1\nstart_points=[month+month_offset for month in bear_market_months[:8]]\n# print(start_points)\n\n# investment_type: 0=s&p500, 1=capped_s&p500, 2=bank, 3=bonds(tbd)\nfor toi in ['bonds', 'snp500', 'savings_account', 'capped_snp500']:\n tinvest = monthly_invest\n if toi == 1:\n tinvest-=1\n final_networths = [weighted_return(initial_rampup_months, initial_amount, (num_years*12), tinvest, start_points[i], toi) for i in range(len(start_points))]\n # final_networths = np.sort(final_networths)\n avg_nw=np.average(final_networths)\n med_nw=np.median(final_networths)\n print('Type of investment : %s \\t Median Networths : %f'%(toi, med_nw))\n print(final_networths)\n print()\n",
"Type of investment : bonds \t Median Networths : 1060.000000\n[1060.0, 1060.0, 1060.0, 1060.0, 1060.0, 1060.0, 1060.0, 1060.0]\n\nType of investment : snp500 \t Median Networths : 1801.054272\n[816.5663844902134, 2505.1719497440636, 667.5065392020023, 1260.9234851984277, 1670.8253135172877, 3687.5137888154172, 2003.5642632748668, 1931.2832309902376]\n\nType of investment : savings_account \t Median Networths : 730.257284\n[696.1735462599163, 869.8343344777593, 506.7790551959012, 599.3995860136782, 635.9306876121261, 764.341021261995, 792.0727576830466, 862.5957613877551]\n\nType of investment : capped_snp500 \t Median Networths : 1873.484482\n[1786.0115717087594, 1931.146211157738, 1685.5720432858795, 1757.0481212765123, 1815.8227519742852, 2002.1863753151677, 1949.9080441941733, 1960.2129454778546]\n\n"
],
[
"findata.loc[-5:]",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.