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
list
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
list
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
list
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
list
cell_types
list
cell_type_groups
list
ec4cf909f88396b978cfc7a1bada4f6dca38f5f1
5,870
ipynb
Jupyter Notebook
ipynb/03c-laboratorio-computacional-ans.ipynb
gcpeixoto/FMECD
9bca72574c6630d1594396fffef31cfb8d58dec2
[ "CC0-1.0" ]
null
null
null
ipynb/03c-laboratorio-computacional-ans.ipynb
gcpeixoto/FMECD
9bca72574c6630d1594396fffef31cfb8d58dec2
[ "CC0-1.0" ]
null
null
null
ipynb/03c-laboratorio-computacional-ans.ipynb
gcpeixoto/FMECD
9bca72574c6630d1594396fffef31cfb8d58dec2
[ "CC0-1.0" ]
null
null
null
34.940476
334
0.563884
[ [ [ "# Laboratório Computacional 3\n\nNo laboratório computacional, você praticará o que aprendeu. Resolva os problemas com o auxílio do Python pesquisando apenas as informações essenciais de que precisa. Não use respostas prontas.", "_____no_output_____" ], [ "**Problema:** Programe uma função `multadd` que multiplique cada item de uma lista $L$ lista por $k$ e some $c$. Por exemplo:\n\n```python\nL = [1,2,3]\nmultadd(lista,2,1)\n[3,5,7] # este é o resultado neste caso\n```", "_____no_output_____" ] ], [ [ "# opção 1\ndef multadd(L,k,c):\n return [i*k + c for i in L]\nmultadd([1,2,3],2,1)", "_____no_output_____" ], [ "# opçao 2\nL, k, c = [1,2,3], 2, 1\nmultadd = list(map(lambda x: x*k + c,L))\nmultadd", "_____no_output_____" ] ], [ [ "**Problema:** Gere uma lista aleatória de 100 inteiros não-nulos $L$ contendo números pares e ímpares. Em seguida, programe uma função `f(L)` que retorne uma tupla $(a,b,c,d,e)$ em que: \n\n- $a$ é a quantidade de números pares na lista\n- $b$ é a sublista de $L$ que contém apenas números pares\n- $c$ é a quantidade de números ímpares na lista\n- $d$ é a sublista de $L$ que contém apenas números ímpares\n- $e$ é um teste lógico que deve retornar `True` se $a + c$ = $|L|$, onde $|L|$ é a cardinalidade (número de elementos de $L$).\n\nEnfim, crie uma função `g(L,t)` que imprima os conteúdos da tupla `t` (exceto $b$ e $d$) em um template que mostre o seguinte: \n\n```python\n|L| = . \na = .\nc = .\ne = True\n```\n\n**Nota:** importe `sample` ou `randint` de `random`. Observe que, acima, os pontos `.` servem apenas para denotar *placeholders* (substitutos) que devem ser substituídos pelos números inteiros obteníveis no seu cômputo.\n", "_____no_output_____" ] ], [ [ "from random import sample\n\nL = sample(range(0,1000),100)\n\ndef f(L): \n b, d, e = [], [], False\n for x in L:\n if x % 2 == 0:\n b.append(x)\n elif x % 2 == 1:\n d.append(x)\n\n a, c = len(b), len(d)\n\n if a + c == len(L):\n e = True \n \n return (a,b,c,d,e)\n\ndef imprime(L,tup):\n a,c,e = tup[0],tup[2],tup[4]\n print('|L| = {}\\na = {}\\nc = {}\\ne = {}'.format(len(L),a,c,e))\n \ntup = f(L); imprime(L,tup)", "_____no_output_____" ] ], [ [ "**Problema:** Neste capítulo, apresentamos um exemplo relacionado ao teste aleatório de pessoas que entram em um hospital ao longo de um dia. Naquele exemplo, calculamos a probabilidade de a pessoa ser doadora universal, bem como de ter outro tipo sanguíneo no sistema ABO. Utilize essas informações para fazer o que se pede:\n\n1. Defina a probabilidade total diária $m_A$ de uma pessoa que entra no hospital ter sangue do tipo $A$ como:\n\n$$m_A = P(A+) + P(A-)$$\n\nonde \n\n- $P(A+)$ é a probabilidade de pessoas que entram no hospital cujo sangue é $A+$.\n- $P(A-)$ é a probabilidade de pessoas que entram no hospital cujo sangue é $A-$.\n\n2. Crie uma função que calcule $m_A$ a partir de um teste aleatório equivalente ao mostrado na sala. Considere $N \\geq 500$ pessoas. \n\n3. Melhore o código apresentado criando uma função que realize o teste aleatório e lhe retorne as probabilidades. Seu dado de entrada será praticamente o valor de $N$ e a saída um objeto iterável a seu critério (`dict`, por exemplo).\n\n4. Crie uma estrutura de repetição para que a função seja executada por até $q \\geq 3$ vezes supondo que o teste aleatório seja repetido a cada novo dia no hospital. Considere que a cada dia subsequente, $N$ novas pessoas entrem no hospital. \n\n5. Calcule a probabilidade $m_A$ para o dia 1, dia 2, ... dia $q$ (note que elas podem ser diferentes) e armazene os dados em alguma estrutura que você ache melhor.\n\n6. Determine o valor médio de probabilidades\n\n$$M = \\dfrac{m_A^1 + m_A^2 + \\cdots m_A^q}{q},$$\n\nonde $m_A^j$, $j = 1,2,\\ldots,q$ é a probabilidade $m_A$ para o $j$-ésimo dia.\n \n \n**Nota:** a solução deste problema não é única, assim como não o é a forma de programar. ", "_____no_output_____" ], [ "**Problema:** Considerando o problema anterior, você conseguiria fazer o mesmo para pessoas com sangue tipo $AB$, $B$ e $O$? Se sim, quão diferente são os valores de $M$ para cada grupo durante períodos de análise iguais de até $q$ dias?", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec4d016edb1d36c2d35d291524ef6fd9c7ad5805
24,465
ipynb
Jupyter Notebook
notebooks/2-CNN/8-Speech/SpeechSynthesis_Test.ipynb
So-AI-love/deep-learning-workshop
b0b176dccbd9ecc6bafa4955b0476675a5337c3f
[ "MIT" ]
486
2016-06-23T09:12:57.000Z
2022-03-03T11:23:38.000Z
notebooks/2-CNN/8-Speech/SpeechSynthesis_Test.ipynb
So-AI-love/deep-learning-workshop
b0b176dccbd9ecc6bafa4955b0476675a5337c3f
[ "MIT" ]
4
2016-06-24T03:36:02.000Z
2020-05-15T06:59:54.000Z
notebooks/2-CNN/8-Speech/SpeechSynthesis_Test.ipynb
So-AI-love/deep-learning-workshop
b0b176dccbd9ecc6bafa4955b0476675a5337c3f
[ "MIT" ]
133
2016-07-23T02:50:53.000Z
2022-03-19T03:41:46.000Z
32.62
137
0.557776
[ [ [ "import os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.misc # for image resizing\n\n#import scipy.io.wavfile\n\n# pip install soundfile librosa python_speech_features\nimport soundfile\n\nfrom IPython.display import Audio as audio_playback_widget", "_____no_output_____" ], [ "#f = './data/raw-from-phone.wav' # un-normalized\nf = './data/num_phone_en-UK_m_Martin14.wav' # has been normed", "_____no_output_____" ], [ "# Read in the original file\nsamples, sample_rate = soundfile.read(f)\n\nsamples = samples / np.max(samples) # Norm the signal\n\ndef show_waveform(sound):\n n_samples = sound.shape[0]\n\n plt.figure(figsize=(12,2))\n plt.plot(np.arange(0.0, n_samples)/sample_rate, sound)\n plt.xticks( np.arange(0.0, n_samples/sample_rate, 0.5), rotation=90 )\n\n plt.grid(True)\n\n plt.show()\n\nshow_waveform(samples)\naudio_playback_widget(f)", "_____no_output_____" ], [ "n_fft = 512\n\nfft_step = 0.010 # 10ms\nfft_window = 0.025 # 25ms", "_____no_output_____" ], [ "import librosa\n\n#hop_length=int(fft_step*sample_rate) # number audio of frames between STFT columns\n#win_length=int(fft_window*sample_rate) # number audio of frames between STFT columns\n\nwin_length=None # defaults to n_fft\nhop_length=None # defaults to win_length/4\n\nspectrum_complex = librosa.stft(samples, n_fft=n_fft, \n hop_length=hop_length, win_length=win_length,\n window='hann', center=True, \n dtype=np.complex64) # This has real and imaginary parts each as float32\n\nspectrum_complex.shape", "_____no_output_____" ], [ "samples_defft = librosa.istft(spectrum_complex, \n hop_length=hop_length, win_length=win_length)", "_____no_output_____" ], [ "def quick_view_and_play(stub, samples_here, show_waveform_graph=True):\n f = './tmp/%s.wav' % (stub,)\n soundfile.write(f, samples_here/np.max(samples_here), samplerate=sample_rate)\n if show_waveform_graph:\n show_waveform(samples_here)\n return audio_playback_widget(f)", "_____no_output_____" ], [ "# This proves that audio->sfft(complex)->defft(complex)->audio is pretty much identical\nquick_view_and_play('defft', samples_defft)", "_____no_output_____" ], [ "spectrum_real = np.absolute(spectrum_complex)\n# effectively, all phase information==0\n\nsamples_re_defft = librosa.istft(spectrum_real, hop_length=hop_length, win_length=win_length)\n\n# This has a strange 'phasing effect' (as might be expected...)\nquick_view_and_play('re-defft', samples_re_defft)", "_____no_output_____" ], [ "def show_spectrum( spectrum, title='Spectrum' ):\n fig, ax = plt.subplots(nrows=1,ncols=1, figsize=(20,4))\n\n cax = ax.matshow(spectrum, interpolation='nearest', aspect='auto', cmap=plt.cm.afmhot, origin='lower')\n fig.colorbar(cax)\n plt.title(title)\n plt.show()\n \nshow_spectrum( np.log(spectrum_real), title='Spectrum (Absolute value)' )", "_____no_output_____" ], [ "def real_spectrum_to_samples( spectrum_re, iters=20 ):\n # Initially pick random phases\n phases = 2.0 * np.pi * np.random.random_sample(spectrum_re.shape) - np.pi\n #phases = np.zeros_like( spectrum_re )\n\n for i in range(iters):\n spectrum_complex_guess = spectrum_re * np.exp(1.j*phases)\n\n samples_reim = librosa.istft(spectrum_complex_guess, \n hop_length=hop_length, win_length=win_length,\n window='hann', center=True, \n )\n\n re_calc_fft = librosa.stft(samples_reim, n_fft=n_fft, \n hop_length=hop_length, win_length=win_length,\n window='hann', center=True, \n dtype=np.complex64)\n\n phases_next = np.angle( re_calc_fft ) # What are the phases just reported? Next iteration, use these\n #phases = (phases+phases_next)/2.0\n \n # Find the phase difference in the range (-pi, +pi)\n phases_diff = (phases_next - phases + np.pi) % (2 * np.pi ) - np.pi\n \n phases_clipped = np.clip( phases_diff, a_min=-np.pi/8.0, a_max=+np.pi/8.0)\n phases = phases + phases_clipped\n \n print( [ '%+.4f' % p for p in phases_clipped[30:40, int(5.3/fft_step)] ] )\n #print( np.abs(phases_diff).mean() )\n \n return samples_reim\n \nsamples_reim_defft = real_spectrum_to_samples( spectrum_real )\n\nquick_view_and_play('reim-defft', samples_reim_defft)", "_____no_output_____" ], [ "import python_speech_features\nn_mel_freq_components = 64\n#n_mel_freq_components = 256\n\n# create_mel_filters\n#mel_inversion_filter = python_speech_features.get_filterbanks(nfft=n_fft, samplerate=sample_rate,\n# nfilt=n_mel_freq_components,\n# lowfreq = 300.0, highfreq = 8000.0)\n# #lowfreq = 0, highfreq = None)\n#\n#mel_filter = mel_inversion_filter.T / mel_inversion_filter.sum(axis=1)\n#mel_filter.shape\n\nmel_filters_from_fft = python_speech_features.get_filterbanks(nfft=n_fft, samplerate=sample_rate,\n nfilt=n_mel_freq_components,\n #lowfreq = 10.0, highfreq = None)\n #lowfreq = 300.0, highfreq = 8000.0)\n #lowfreq = 10, highfreq = None)\n )\n\n#mel_filters_from_fft = np.identity( 257 ) # This is uncompressed : just as a check\n\nmel_filters_from_fft.shape # (64, 257)\nmel_filters_from_fft[10:15,10:20]", "_____no_output_____" ], [ "#mel_filters_from_fft[15,:]\n#mel_filters_from_fft.sum(axis=0) # Total attention paid to each of the FFT bins\nmel_filters_from_fft.sum(axis=1) # Amount of FFT contribution to each mel bin\n\n# To share out the weight in a given mel bin, need to scale it down\nmel_filters_to_fft = (mel_filters_from_fft / mel_filters_from_fft.sum(axis=1, keepdims=True)).T\n#mel_filters_psuedoinverse\n\nspectrum_identity = mel_filters_to_fft.dot(mel_filters_from_fft) # Should be ~I(257,257)\n#spectrum_identity[5:10, 5:10] # demonstrates identity and some smear at low frequencies\nspectrum_identity[27:35, 27:35] # demonstrates 'smear' but not over/under emphasis", "_____no_output_____" ], [ "def make_mel(spectrogram, mel_filter_from_fft, shorten_factor=1.0):\n #spectrogram = np.square(spectrogram) # Convert to 'power' ?\n mel_spec = mel_filter_from_fft.dot( spectrogram )\n \n mel_spec = scipy.ndimage.zoom(mel_spec.astype('float32'), \n [1, 1./shorten_factor], # Shorten in time direction\n mode='nearest', order=1,\n ).astype('float32')\n #print(np.min(mel_spec), np.max(mel_spec), )\n \n #mel_spec_bounded = np.clip(mel_spec, a_min=np.exp(-15.0), a_max=None)\n return mel_spec #_bounded\n\ndef mel_to_spectrogram(mel_spec, mel_filter_to_fft, shorten_factor=1.0):\n \"\"\"\n takes in an mel spectrogram and returns a normal spectrogram for inversion \n \"\"\"\n mel_spec_uncompressed = scipy.ndimage.zoom(mel_spec.astype('float32'), \n #[shorten_factor,1], \n [1, shorten_factor], \n mode='nearest', order=1,\n ).astype('float32')\n\n spectrum_recovered = mel_filter_to_fft.dot( mel_spec_uncompressed )\n \n #uncompressed_spec = uncompressed_spec -4\n \n #spectrum_recovered = np.sqrt( spectrum_recovered ) # Convert from 'power'\n \n return np.clip(spectrum_recovered, a_min=np.exp(-12.0), a_max=None)", "_____no_output_____" ], [ "shorten_factor=1.0 # This is a time-wise compression factor : 1.0 is none\n#shorten_factor=4.0 # This is a time-wise compression factor : 4.0 seems harsh\n\nmel_spec = make_mel(spectrum_real, mel_filters_from_fft, shorten_factor=shorten_factor)\n\n#spectrum_real\nmel_spec.shape", "_____no_output_____" ], [ "# plot the compressed spec\nshow_spectrum( np.log(mel_spec), 'mel Spectrogram')", "_____no_output_____" ], [ "spectrogram_from_mel = mel_to_spectrogram(mel_spec, mel_filters_to_fft, shorten_factor=shorten_factor)\n#spectrogram_from_mel = spectrum_identity.dot(spectrum_real)", "_____no_output_____" ], [ "# plot the recovered spec\nshow_spectrum( np.log(spectrogram_from_mel), 'Recovered Spectrogram')", "_____no_output_____" ], [ "# And this is the original 'real' one, for comparison \n#show_spectrum( np.log( np.clip(spectrum_real, a_min=np.exp(-12.0), a_max=None)), title='Original Spectrum' )\nshow_spectrum( np.log( spectrum_real ), title='Original Spectrum' )", "_____no_output_____" ], [ "samples_via_mel = real_spectrum_to_samples( spectrogram_from_mel, iters=20 )\n\nquick_view_and_play('via-mel', samples_via_mel)", "_____no_output_____" ], [ "#['+0.0027', '+0.0111', '+0.0081', '+0.0105', '+0.0106', '+0.0172', '+0.0040', '+0.0095', '+0.0237', '+0.0258']", "_____no_output_____" ] ], [ [ "### Turn mp3 into mels", "_____no_output_____" ] ], [ [ "import librosa\nlibrosa.__version__ # '0.5.1'", "_____no_output_____" ], [ "filename_in = './librivox/guidetomen_02_rowland_64kb.mp3'\nfilename_out = filename_in.replace('.mp3', '.mel')\n\n#import audioread\n#with audioread.audio_open(filename) as f:\n# print(f.channels, f.samplerate, f.duration)#print(os.listdir(f))\n\n# Requires 'dnf install ffmpeg' for .mp3 decoding\n\n#samples, sample_rate = librosa.core.load(filename_in, sr=None)\nsamples, sample_rate = librosa.core.load(filename_in, sr=24000)\nsamples = samples/np.max(samples) # Force amplitude of waveform into range ~-1 ... +1.0\n\nsample_rate, samples.shape, samples.shape[0]/sample_rate", "_____no_output_____" ], [ "#quick_view_and_play('librivox-orig', samples) # Rather large computation for this graph...\naudio_playback_widget(filename_in)", "_____no_output_____" ], [ "fft_step = 12.5/1000. # 12.5ms\nfft_window = 50.0/1000. # 50ms\n\nn_fft = 512*4\n\nhop_length = int(fft_step*sample_rate)\nwin_length = int(fft_window*sample_rate)\n\nn_mels = 80\nfmin = 125 # Hz\n#fmax = ~8000\n\nhop_length, win_length", "_____no_output_____" ], [ "# https://librosa.github.io/librosa/generated/librosa.feature.melspectrogram.html\n#S = librosa.feature.melspectrogram(y=samples, sr=sample_rate, n_mels=n_mels, fmin=fmin)", "_____no_output_____" ], [ "spectra_complex = librosa.stft(samples, n_fft=n_fft, \n hop_length=hop_length, \n win_length=win_length, window='hann', )\n\npower_spectra = np.abs(spectra_complex)**2\nmelspectra = librosa.feature.melspectrogram(S=power_spectra, n_mels=n_mels, fmin=fmin)\n\nspectra_complex.shape, melspectra.shape", "_____no_output_____" ], [ "#dir(librosa)\nimport librosa.display", "_____no_output_____" ], [ "plt.figure(figsize=(10, 4))\nlibrosa.display.specshow(librosa.power_to_db(melspectra[:,0:1024], ref=np.max), \n y_axis='mel', fmin=125, x_axis='time', \n hop_length=hop_length, sr=sample_rate)\nplt.colorbar(format='%+2.0f dB')\nplt.title('Mel spectrogram')\nplt.show()\n# Section Two Of ... The Guide to Men ,,, This Librivox recording is in the Public Domain ...\n# Bachelors ... Somehow ... Just at the psychological moment when a bachelor fancies he's going to die (etc) ", "_____no_output_____" ], [ "melspectra.min(), melspectra.max(), melspectra.mean(), melspectra.std()", "_____no_output_____" ], [ "# ?? Is the following appropriate for us?\n#melspectra_floored = np.maximum(0.01, melspectra)\nmelspectra_floored = np.maximum(0.001, melspectra)\n\nmelout = np.log(melspectra_floored)\nmelout.min(), melout.max(), melout.mean(), melout.std()", "_____no_output_____" ], [ "plt.figure(figsize=(10, 4))\nlibrosa.display.specshow(melout[:, 0:1024], y_axis='mel', fmin=125, x_axis='time')\nplt.colorbar(format='%+2.0f dB')\nplt.title('Mel spectrogram')\nplt.show()", "_____no_output_____" ], [ "import pickle\n\ndata_dictionary = dict(\n sample_rate=sample_rate, \n hop_length=hop_length, win_length=win_length,\n fmin=fmin, \n mel=melout,\n)\n\npickle.dump(data_dictionary, open(filename_out, 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\nprint(\"Created dataset : %s\" % (filename_out, ))", "_____no_output_____" ], [ "# Interesting, in that it allows vector-valued (x,y) with various penalty term choices :\n# https://librosa.github.io/librosa/generated/librosa.core.dtw.html#librosa-core-dtw", "_____no_output_____" ], [ "# Do the inverse operation on spectra_complex... and listen to it\nsamples_defft = librosa.istft(spectra_complex, hop_length=hop_length, win_length=win_length)", "_____no_output_____" ], [ "quick_view_and_play('librivox-recreated', samples_defft, show_waveform_graph=False)", "_____no_output_____" ], [ "spectra_just_amplitudes = np.abs(spectra_complex) # + 0.j\nsamples_defft_real = librosa.istft(spectra_just_amplitudes, hop_length=hop_length, win_length=win_length)\nquick_view_and_play('librivox-recreated-poorly', samples_defft_real, show_waveform_graph=False)", "_____no_output_____" ] ], [ [ "### Build dataset from a series of mp3 files\n\nFor each file in turn, pull out blocks of spectra each 1024 spectra long (~12sec).\nFirst 64 of these will be discarded, so 'step increment' should be (1024-64=960)\nIgnore tail block.\n\nhttps://medium.com/@chengweizhang2012/an-easy-guide-to-build-new-tensorflow-datasets-and-estimator-with-keras-model-9b0f6b4c1b0d\n\nhttps://github.com/Tony607/Keras_catVSdog_tf_estimator/blob/master/keras_estimator_vgg16-cat_vs_dog-TFRecord.ipynb\n\nhttps://www.tensorflow.org/programmers_guide/datasets\n\nhttp://warmspringwinds.github.io/tensorflow/tf-slim/2016/12/21/tfrecords-guide/\n\nhttps://indico.io/blog/tensorflow-data-inputs-part1-placeholders-protobufs-queues/", "_____no_output_____" ] ], [ [ "import numpy as np\nimport tensorflow as tf\n\nimport librosa\nlibrosa.__version__ # '0.5.1'", "_____no_output_____" ], [ "sample_rate= 24000 # input will be standardised to this rate\n\nfft_step = 12.5/1000. # 12.5ms\nfft_window = 50.0/1000. # 50ms\n\nn_fft = 512*4\n\nhop_length = int(fft_step*sample_rate)\nwin_length = int(fft_window*sample_rate)\n\nn_mels = 80\nfmin = 125 # Hz\n#fmax = ~8000\n\nwin_length, hop_length", "_____no_output_____" ], [ "# And for the training windowing :\nsteps_total, steps_leadin = 1024, 64\n\n# Test the flatten idea\n#a = np.array([3.4, 55.4, 34.23])\na = np.array([[3.4, 55.4,],[34.23, 342.1221]])\na.flatten().tolist()", "_____no_output_____" ], [ "# Based on http://warmspringwinds.github.io/tensorflow/tf-slim/2016/12/21/tfrecords-guide/\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List( value=[value] ))\ndef _floats_feature(np_arr):\n return tf.train.Feature(float_list=tf.train.FloatList( value=np_arr.flatten().tolist() ))\n\ndef convert_wavs_to_spectra_learnable_records(filename_in):\n filename_base = filename_in.replace('.mp3', '_%s.tfrecords')\n\n samples, _sample_rate = librosa.core.load(filename_in, sr=sample_rate)\n samples = samples/np.max(samples) # Force amplitude of waveform into range ~-1 ... +1.0\n\n spectra_complex = librosa.stft(samples, n_fft=n_fft, \n hop_length=hop_length, \n win_length=win_length, window='hann', )\n\n power_spectra = np.abs(spectra_complex)**2\n melspectra = librosa.feature.melspectrogram(S=power_spectra, n_mels=n_mels, fmin=fmin)\n\n with tf.python_io.TFRecordWriter(filename_base % ('train',)) as writer_train, \\\n tf.python_io.TFRecordWriter(filename_base % ('valid',)) as writer_valid, \\\n tf.python_io.TFRecordWriter(filename_base % ('test',)) as writer_test :\n \n # Ok, now create a series of Examples with these features\n for offset in range(0, melspectra.shape[1]-steps_total, steps_total-steps_leadin):\n example = tf.train.Example(features=tf.train.Features(feature={\n #'height': _int64_feature(height),\n #'width': _int64_feature(width),\n #'image_raw': _bytes_feature(img_raw),\n #'mask_raw': _bytes_feature(annotation_raw)\n 'mel': _floats_feature(melspectra[:, offset:offset+steps_total]),\n 'spectra_real': _floats_feature( spectra_complex[:, offset:offset+steps_total].imag ),\n 'spectra_imag': _floats_feature( spectra_complex[:, offset:offset+steps_total].imag ),\n }))\n\n w = writer_train # Allocate these between the various train/validation/test files\n if np.random.random()>0.8:\n w = writer_valid\n if np.random.random()>0.5:\n w = writer_test\n\n w.write(example.SerializeToString())", "_____no_output_____" ], [ "for i in [1,2,3,]:\n convert_wavs_to_spectra_learnable_records('./librivox/guidetomen_%02d_rowland_64kb.mp3' % (i,))\nprint(\"DONE!\")", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "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", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
ec4d03867ea427f6149cb85a98b70de124bcd43c
9,786
ipynb
Jupyter Notebook
Chapter01/Excercises/Excercise_05_Data _Integration_merge.ipynb
TrainingByPackt/Master-Data-Science-with-Python-
cd5e1bd30a886d8b4ae3e4835bf3c657c29a52a3
[ "MIT" ]
28
2019-06-25T15:03:13.000Z
2022-03-28T20:53:01.000Z
Chapter01/Excercises/Excercise_05_Data _Integration_merge.ipynb
TrainingByPackt/Master-Data-Science-with-Python-
cd5e1bd30a886d8b4ae3e4835bf3c657c29a52a3
[ "MIT" ]
null
null
null
Chapter01/Excercises/Excercise_05_Data _Integration_merge.ipynb
TrainingByPackt/Master-Data-Science-with-Python-
cd5e1bd30a886d8b4ae3e4835bf3c657c29a52a3
[ "MIT" ]
93
2019-06-26T02:34:00.000Z
2022-03-29T16:21:48.000Z
26.520325
146
0.35234
[ [ [ "### 1.\tImport the pandas and load the two dataset(mark.csv and student.csv) into the pandas dataframe. ", "_____no_output_____" ] ], [ [ "import pandas as pd\ndf1 = pd.read_csv('https://raw.githubusercontent.com/TrainingByPackt/Data-Science-with-Python/master/Chapter01/Data/mark.csv',header = 0)\ndf2 = pd.read_csv('https://raw.githubusercontent.com/TrainingByPackt/Data-Science-with-Python/master/Chapter01/Data/student.csv',header = 0)", "_____no_output_____" ] ], [ [ "### 2.\tPrint out the top 5 rows of df1", "_____no_output_____" ] ], [ [ "df1.head()", "_____no_output_____" ] ], [ [ "### 3.\tPrint out the top 5 rows of df2", "_____no_output_____" ] ], [ [ "df2.head()", "_____no_output_____" ] ], [ [ "### 4.\tPerform data integration to both the dataframe with respect to the column ‘Student_id’ key word ‘pd.merge()’", "_____no_output_____" ] ], [ [ "df = pd.merge(df1, df2, on = 'Student_id')", "_____no_output_____" ] ], [ [ "### 5.\tPrint out the top 5 rows of df", "_____no_output_____" ] ], [ [ "df.head()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec4d0610294c2eda7deba61bc799787edba563f6
558,642
ipynb
Jupyter Notebook
End-to-End Data Analysis practice/Data Analysis of Wine Quality.ipynb
ColdTeapot273K/data-stuff
f9f889e148d9cbdb9fd8434d26d120f919e6deb7
[ "MIT" ]
null
null
null
End-to-End Data Analysis practice/Data Analysis of Wine Quality.ipynb
ColdTeapot273K/data-stuff
f9f889e148d9cbdb9fd8434d26d120f919e6deb7
[ "MIT" ]
null
null
null
End-to-End Data Analysis practice/Data Analysis of Wine Quality.ipynb
ColdTeapot273K/data-stuff
f9f889e148d9cbdb9fd8434d26d120f919e6deb7
[ "MIT" ]
null
null
null
150.617956
211,948
0.83097
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('darkgrid')", "_____no_output_____" ] ], [ [ "# Questions for these datasets:\n\nQ1: Is a certain type of wine (red or white) associated with higher quality?\n\nQ2: What level of acidity (pH value) receives the highest average rating?\n\nAcidity Levels:\nHigh: Lowest 25% of pH values\nModerately High: 25% – 50% of pH values\nMedium: 50% – 75% of pH values\nLow: 75% – max pH value\n\nQ3: Do wines with higher alcoholic content receive better ratings?\nWe shall consider two groups of wine samples:\n\nLow alcohol (samples with an alcohol content less than the median)\nHigh alcohol (samples with an alcohol content greater than or equal to the median)\n\nQ4: Do sweeter wines (more residual sugar) receive better ratings?\n\nQ5:How significant are other chemicals for wine quality rating?", "_____no_output_____" ] ], [ [ "red_df = pd.read_csv('datasets/wine_quality/winequality-red.csv', sep=';')\n\nwhite_df = pd.read_csv('datasets/wine_quality/winequality-white.csv', sep=';')", "_____no_output_____" ], [ "red_df.head()", "_____no_output_____" ], [ "white_df.head()", "_____no_output_____" ], [ "# check which columns have missing values, as well as the number of entries/features\nred_df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1599 entries, 0 to 1598\nData columns (total 12 columns):\nfixed acidity 1599 non-null float64\nvolatile acidity 1599 non-null float64\ncitric acid 1599 non-null float64\nresidual sugar 1599 non-null float64\nchlorides 1599 non-null float64\nfree sulfur dioxide 1599 non-null float64\ntotal sulfur dioxide 1599 non-null float64\ndensity 1599 non-null float64\npH 1599 non-null float64\nsulphates 1599 non-null float64\nalcohol 1599 non-null float64\nquality 1599 non-null int64\ndtypes: float64(11), int64(1)\nmemory usage: 150.0 KB\n" ], [ "white_df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 4898 entries, 0 to 4897\nData columns (total 12 columns):\nfixed acidity 4898 non-null float64\nvolatile acidity 4898 non-null float64\ncitric acid 4898 non-null float64\nresidual sugar 4898 non-null float64\nchlorides 4898 non-null float64\nfree sulfur dioxide 4898 non-null float64\ntotal sulfur dioxide 4898 non-null float64\ndensity 4898 non-null float64\npH 4898 non-null float64\nsulphates 4898 non-null float64\nalcohol 4898 non-null float64\nquality 4898 non-null int64\ndtypes: float64(11), int64(1)\nmemory usage: 459.3 KB\n" ], [ "# check for duplicates in the data\nsum(red_df.duplicated())", "_____no_output_____" ], [ "# drop duplicates\nred_df.drop_duplicates(inplace=True)\n# confirm correction by rechecking for duplicates in the data\nsum(red_df.duplicated())", "_____no_output_____" ], [ "sum(white_df.duplicated())", "_____no_output_____" ], [ "white_df.drop_duplicates(inplace=True)\nsum(white_df.duplicated())", "_____no_output_____" ], [ "# just looking around\nred_df.describe()", "_____no_output_____" ], [ "white_df.describe()", "_____no_output_____" ], [ "# color column to merge both datasets\nred_df['color'] = 'red'\nred_df", "_____no_output_____" ], [ "white_df['color'] = 'white'\nwhite_df", "_____no_output_____" ], [ "wine_df = red_df.append(white_df, ignore_index=True, sort=True)\nwine_df", "_____no_output_____" ], [ "# look around, some distributions\nwine_df.hist(figsize=(8, 8));", "_____no_output_____" ], [ "pd.plotting.scatter_matrix(wine_df, figsize=(8, 8));", "_____no_output_____" ] ], [ [ "# Q1: Is a certain type of wine (red or white) associated with higher quality?", "_____no_output_____" ] ], [ [ "colors = ['#800020', '#FFBF00']\ncolor_means = wine_df.groupby('color')['quality'].mean()\ncolor_means.plot(kind='bar', title='Average Wine Quality by Color', color=colors, alpha=.7)\nplt.xlabel('Color', fontsize=18)\nplt.ylabel('Quality', fontsize=18);", "_____no_output_____" ], [ "counts = wine_df.groupby(['quality', 'color']).count()\ncounts", "_____no_output_____" ], [ "#We’re missing a red wine value for a the 9 rating. Even though this number is a 0, we need it for our plot. Run the last two cells after running the cell below.\n\n# get counts for each rating and color\ncolor_counts = wine_df.groupby(['color', 'quality']).count()['pH']\ncolor_counts\n\n# get total counts for each color\ncolor_totals = wine_df.groupby('color').count()['pH']\ncolor_totals\n\n# get proportions by dividing red rating counts by total # of red samples\nred_proportions = color_counts['red'] / color_totals['red']\nred_proportions\n\n# get proportions by dividing white rating counts by total # of white samples\nwhite_proportions = color_counts['white'] / color_totals['white']\nwhite_proportions\n\nred_proportions['9'] = 0\nred_proportions\n\nind = np.arange(len(red_proportions)) # the x locations for the groups\nwidth = 0.35 # the width of the bars\n\n# plot bars\nred_bars = plt.bar(ind, red_proportions, width, color=colors[0], alpha=.7, label='Red Wine')\nwhite_bars = plt.bar(ind + width, white_proportions, width, color=colors[1], alpha=.7, label='White Wine')\n\n# title and labels\nplt.ylabel('Proportion')\nplt.xlabel('Quality')\nplt.title('Proportion by Wine Color and Quality')\nlocations = ind + width / 2 # xtick locations\nlabels = ['3', '4', '5', '6', '7', '8', '9'] # xtick labels\nplt.xticks(locations, labels)\n\n# legend\nplt.legend();", "_____no_output_____" ] ], [ [ "# /Q1: Is a certain type of wine (red or white) associated with higher quality?\n\nSomewhat, as it seems", "_____no_output_____" ], [ "# Q2: What level of acidity (pH value) receives the highest average rating?", "_____no_output_____" ] ], [ [ "wine_df['pH'].describe() # View the min, 25%, 50%, 75%, max pH values", "_____no_output_____" ], [ "bin_edges = [2.72, 3.11, 3.21, 3.33, 4.01] # Fill in this list with five values you just found\n\nbin_names = [ 'high', 'moderately high' , 'medium', 'low' ] # Name each acidity level category\n\n# Creates acidity_levels column\nwine_df['acidity levels'] = pd.cut(df['pH'], bin_edges, labels=bin_names)\n\n# Checks for successful creation of this column\nwine_df.head()\n\n# Find the mean quality of each acidity level with groupby\nwine_df.groupby('acidity levels').mean()['quality']", "_____no_output_____" ] ], [ [ "# /Q2: What level of acidity (pH value) receives the highest average rating?\n\nMedium-to-Low", "_____no_output_____" ], [ "# Q3: Do wines with higher alcoholic content receive better ratings?", "_____no_output_____" ] ], [ [ "# get the median amount of alcohol content\nwine_df['alcohol'].describe()", "_____no_output_____" ], [ "# select samples with alcohol content less than the median\nlow_alcohol = wine_df[wine_df['alcohol'] < 10.549241]\n\n# select samples with alcohol content greater than or equal to the median\nhigh_alcohol = wine_df[wine_df['alcohol'] >= 10.549241]\n\n# ensure these queries included each sample exactly once\nnum_samples = wine_df.shape[0]\nnum_samples == low_alcohol['quality'].count() + high_alcohol['quality'].count() # should be True\n\n# get mean quality rating for the low alcohol and high alcohol groups\nbin_edges = [8,10.5,14.9]\nbin_names = ['low', 'high']\nwine_df['alcohol levels'] = pd.cut(wine_df['alcohol'], bin_edges, labels=bin_names)\nwine_df.groupby('alcohol levels').mean()['quality']", "_____no_output_____" ], [ "# Use query to select each group and get its mean quality\nmedian = wine_df['alcohol'].median()\nlow = wine_df['alcohol < {}'.format(median))\nhigh = wine_df.query('alcohol >= {}'.format(median))\n\nmean_quality_low = low['quality'].mean()\nmean_quality_high = high['quality'].mean()\n\n# Create a bar chart with proper labels\nlocations = [1, 2]\nheights = [mean_quality_low, mean_quality_high]\nlabels = ['Low', 'High']\nplt.bar(locations, heights, tick_label=labels)\nplt.title('Average Quality Ratings by Alcohol Content')\nplt.xlabel('Alcohol Content')\nplt.ylabel('Average Quality Rating');", "_____no_output_____" ] ], [ [ "# /Q3: Do wines with higher alcoholic content receive better ratings?\n\nKind of, but not drasticaly(on average)", "_____no_output_____" ], [ "# Q4:Do sweeter wines receive higher ratings?", "_____no_output_____" ] ], [ [ "# Use query to select each group and get its mean quality\nmedian = wine_df['residual sugar'].median()\nlowsugar = wine_df.loc[wine_df['residual sugar'] < median]\nhighsugar = wine_df.loc[wine_df['residual sugar'] >= median]\n\nnum_samples = wine_df.shape[0]\nnum_samples == lowsugar['quality'].count() + highsugar['quality'].count() # should be True\n\nmean_lowsugar = lowsugar['quality'].mean()\nmean_highsugar = highsugar['quality'].mean()\n\n# Create a bar chart with proper labels\nlocations = [1, 2]\nheights = [mean_lowsugar, mean_highsugar]\nlabels = ['Low Sugar', 'High Sugar']\nplt.bar(locations, heights, tick_label=labels)\nplt.title ('Average Quality Ratings by Sugar Level')\nplt.xlabel('Sugar Content')\nplt.ylabel('Average Quality Rating');\nmean_highsugar-mean_lowsugar", "_____no_output_____" ] ], [ [ "# /Q4:Do sweeter wines receive higher ratings?\n\nOn average no", "_____no_output_____" ], [ "# Q5:How significant are other chemicals for wine quality rating?", "_____no_output_____" ] ], [ [ "red_df.groupby(['quality']).mean()", "_____no_output_____" ], [ "red_df.plot(x='quality', y='volatile acidity', kind='scatter');", "_____no_output_____" ], [ "red_df.plot(x='quality', y='alcohol', kind='scatter');", "_____no_output_____" ], [ "white_df.groupby(['quality']).mean()", "_____no_output_____" ], [ "white_df.plot(x='quality', y='volatile acidity', kind='scatter');", "_____no_output_____" ], [ "white_df.plot(x='quality', y='alcohol', kind='scatter');", "_____no_output_____" ], [ "#Some considerable variance of means appears to be observed only among these parameters\ndf = wine_df[['quality', 'citric acid', 'volatile acidity', 'chlorides', 'pH', 'alcohol', 'free sulfur dioxide', 'total sulfur dioxide']].copy() \ndf.groupby(['quality']).mean()\n#pd.plotting.scatter_matrix(df, figsize=(8, 8))\n#df.info()\n", "_____no_output_____" ], [ "wine_df['linguistic quality estimate'] = '1mediocre'\nwine_df.loc[wine_df['quality'] > 4, 'linguistic quality estimate'] = '2decent'\nwine_df.loc[wine_df['quality'] > 7, 'linguistic quality estimate'] = '3good'\n\n#ling_df = wine_df.groupby(['linguistic quality estimate'])\ndf_1 = wine_df[wine_df['linguistic quality estimate'] == '1mediocre']\ndf_2 = wine_df[wine_df['linguistic quality estimate'] == '2decent']\ndf_3 = wine_df[wine_df['linguistic quality estimate'] == '3good']\n\nwine_df.groupby(['linguistic quality estimate']).mean()", "_____no_output_____" ], [ "#wine_df.plot(x='linguistic quality estimate', y='volatile acidity', kind='box');\n#fig, ax = plt.subplots(figsize=(8, 6))\n#ax.box(df_1['volatile acidity']);\n\n\nplt.boxplot([df_1['volatile acidity'], df_2['volatile acidity'], df_3['volatile acidity']]);", "_____no_output_____" ], [ "plt.boxplot([df_1['chlorides'], df_2['chlorides'], df_3['chlorides']]);", "_____no_output_____" ], [ "plt.boxplot([df_1['citric acid'], df_2['citric acid'], df_3['citric acid']]);", "_____no_output_____" ], [ "plt.boxplot([df_1['free sulfur dioxide'], df_2['free sulfur dioxide'], df_3['free sulfur dioxide']]);", "_____no_output_____" ], [ "plt.boxplot([df_1['total sulfur dioxide'], df_2['total sulfur dioxide'], df_3['total sulfur dioxide']]);", "_____no_output_____" ] ], [ [ "# /Q5:How significant are other chemicals for wine quality rating?\n\nIn general, the most significant chemicals for quality rating in these datasets appear to be volatile acidity, chlorides, citric acid, free sulfur dioxide and total sulfur dioxide.\nAnd, in general, the higher quality wines exhibit smaller content and smaller spread of the aforementioned characteristics", "_____no_output_____" ], [ "# Conclusions:\n\n/Q1: Is a certain type of wine (red or white) associated with higher quality?\n\nSomewhat, as it seems\n\n/Q2: What level of acidity (pH value) receives the highest average rating?\n\nMedium-to-Low\n\n/Q3: Do wines with higher alcoholic content receive better ratings?\n\nKind of, but not drasticaly(on average)\n\n/Q4:Do sweeter wines receive higher ratings?\n\nOn average no\n\n/Q5:How significant are other chemicals for wine quality rating?\n\nIn general, the most significant chemicals for quality rating in these datasets appear to be volatile acidity, chlorides, citric acid, free sulfur dioxide and total sulfur dioxide.\nAnd, in general, the higher quality wines exhibit smaller content and smaller spread of the aforementioned characteristics\n\nSome final remarks:\nThe distinctness of taste/flavour of wine is the result of complex combination of, sometimes unique, organic/non-organic chemical compounds, I don't think we can reliably estimate the relative significance of wine quality factors with these datasets, since they don't have features for such aromatic compounds.", "_____no_output_____" ], [ "Some unfinished experiments:", "_____no_output_____" ] ], [ [ "#wine_df.groupby().count()\n#totals = wine_df.groupby(['linguistic quality estimate']).count()['volatile acidity']\n#proportions = counts / totals\n#proportion1 = \nfig, ax = plt.subplots(figsize=(8, 6))\n#ax.plot(kind='bar', df_1['volatile acidity']/len(df_1.index), alpha=0.5, label='1mediocre')\n#ax.plot(kind='bar', df_2['volatile acidity']/len(df_2.index), alpha=0.5, label='2decent')\n#ax.plot(kind='bar', df_3['volatile acidity']/len(df_3.index), alpha=0.5, label='3good')\nax.hist(df_1['volatile acidity'], density=True, histtype='step', stacked=True);\nax.hist(df_2['volatile acidity'], density=True, histtype='step', stacked=True);\nax.hist(df_3['volatile acidity'], density=True, histtype='step', stacked=True);\n#ax.scatter(df_2['volatile acidity'])\n#ax.set_title('Dsitributions of linguistic ratings')\n#ax.set_xlabel('volatile acidity')\n#ax.set_ylabel('proportion')\n#ax.legend(loc='upper right')\n#plt.show()", "_____no_output_____" ], [ "wine_df.plot(x='quality', y='volatile acidity', kind='density', xlim=0);", "_____no_output_____" ], [ "wine_df.plot(x='quality', y='residual sugar', kind='density', xlim=0, ylim=0);", "_____no_output_____" ], [ "wine_df.groupby(pd.cut(wine_df['quality'], np.arange(0, 10, 2))).mean()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ] ]
ec4d148a303abde94dca342c8b46d55442c6da2f
12,801
ipynb
Jupyter Notebook
nlp_amazon_review/GluonNLP_BERT/gluonnlp_bert.ipynb
tyohei/amazon-sagemaker-examples-jp
570498c631241685d6d874139c99b1fcbcb284e7
[ "Apache-2.0" ]
null
null
null
nlp_amazon_review/GluonNLP_BERT/gluonnlp_bert.ipynb
tyohei/amazon-sagemaker-examples-jp
570498c631241685d6d874139c99b1fcbcb284e7
[ "Apache-2.0" ]
null
null
null
nlp_amazon_review/GluonNLP_BERT/gluonnlp_bert.ipynb
tyohei/amazon-sagemaker-examples-jp
570498c631241685d6d874139c99b1fcbcb284e7
[ "Apache-2.0" ]
null
null
null
33.775726
247
0.591048
[ [ [ "# GluonNLP の BERT モデル を利用した感情分析\n\n## 概要\n\nこのノートブックでは、Amazon の商品レビューに対する感情分析、つまり、そのレビューが Positive (Rating が 5 or 4) か、Negative (Rating が 1 or 2)なのかを判定します。これは文書を Positive か Negative に分類する2クラスの分類問題となります。そこで、BERT (Bidirectional Encoder Representations from Transformers) モデルを利用して解きます。\n\n### BERT とは\n\nBERT は大規模なコーパスで学習された汎用的な自然言語処理のためのモデルです。今回対象とする文書の分類問題だけでなく、文書のペアを分類するような質問応答の問題に対しても、転移学習を行うことで良い精度を示しています。BERT は大規模なモデルであり、学習には多くの時間が必要です。\n\n### GluonNLPとは\nMXNet をより簡単に利用するためのライブラリとして Gluon が開発されています。Gluon には、自然言語処理に特化した GluonNLP という派生のライブラリがあります。その中には、BERT モデルの学習済みモデルも提供されており、BERT の事前の学習時間の削減や、実装の効率化に有効です。詳細はURLをごらんください。\n\nhttps://gluon-nlp.mxnet.io/index.html\n\n\n## データの準備\n\nAmazon の商品レビューデータセットは [Registry of Open Data on AWS](https://registry.opendata.aws/) で公開されており、 \n以下からダウンロード可能です。このノートブックでは、日本語のデータセットをダウンロードします。\n- データセットの概要 \nhttps://registry.opendata.aws/amazon-reviews/\n\n- 日本語のデータセット(readme.htmlからたどることができます) \nhttps://s3.amazonaws.com/amazon-reviews-pds/tsv/amazon_reviews_multilingual_JP_v1_00.tsv.gz\n\n以下では、データをダウンロードして解凍 (unzip) します。", "_____no_output_____" ] ], [ [ "import urllib.request\nimport os\nimport gzip\nimport shutil\n\ndownload_url = \"https://s3.amazonaws.com/amazon-reviews-pds/tsv/amazon_reviews_multilingual_JP_v1_00.tsv.gz\" \ndir_name = \"data\"\nfile_name = \"amazon_review.tsv.gz\"\ntsv_file_name = \"amazon_review.tsv\"\nfile_path = os.path.join(dir_name,file_name)\ntsv_file_path = os.path.join(dir_name,tsv_file_name)\n\nos.makedirs(dir_name, exist_ok=True)\n\nif os.path.exists(file_path):\n print(\"File {} already exists. Skipped download.\".format(file_name))\nelse:\n urllib.request.urlretrieve(download_url, file_path)\n print(\"File downloaded: {}\".format(file_path))\n \nif os.path.exists(tsv_file_path):\n print(\"File {} already exists. Skipped unzip.\".format(tsv_file_name))\nelse:\n with gzip.open(file_path, mode='rb') as fin:\n with open(tsv_file_path, 'wb') as fout:\n shutil.copyfileobj(fin, fout)\n print(\"File uznipped: {}\".format(tsv_file_path))", "_____no_output_____" ] ], [ [ "## データの前処理\n\nダウンロードしたデータには学習に不要なデータや直接利用できないデータもあります。以下の前処理で利用できるようにします。\n\n1. ダウンロードしたデータには不要なデータも含まれているので削除し、2クラス分類 (positive が 1, negative が 0)となるように評価データを加工します。\n2. 学習データ、テストデータに分けて、学習用にS3にデータをアップロードします。\n\n### データの加工\n\n今回利用しないデータは以下の2つです。必要なデータだけ選んで保存します。\n- 評価データ `star_rating` と レビューのテキストデータ `review_body` 以外のデータ\n- 評価が 3 のデータ (positive でも negative でもないデータ)\n\nまた、評価が1, 2 のデータはラベル 0 (negative) に、評価が4, 5 のデータはラベル 1 (positive) にします。BERTには、Tokenizer という分かち書きのための機能が備わっています。従って、学習を実行する直前に分かち書きを行うようにし、ここでは行いません。", "_____no_output_____" ] ], [ [ "import pandas as pd\ndf = pd.read_csv(tsv_file_path, sep ='\\t')\ndf_pos_neg = df.loc[:, [\"star_rating\", \"review_body\"]]\ndf_pos_neg = df_pos_neg[df_pos_neg.star_rating != 3]\ndf_pos_neg.loc[df_pos_neg.star_rating < 3, \"star_rating\"] = 0\ndf_pos_neg.loc[df_pos_neg.star_rating > 3, \"star_rating\"] = 1", "_____no_output_____" ] ], [ [ "### データの分割\n\nすべてのデータを学習データとすると、データを使って作成したモデルが良いのか悪いのか評価するデータが別途必要になります。\nそこで、データを学習データ、テストデータに分割して利用します。学習データはモデルの学習に利用し、最終的に作成されたモデルに対してテストデータによる評価を行います。\n\n`train_ratio` で設定した割合のデータを学習データとし、残ったデータをテストデータに分割して利用します。学習データは、後にSageMakerで利用するために、`savetxt` を利用してスペース区切りの csv に保存します。", "_____no_output_____" ] ], [ [ "import numpy as np\n\n# Swap positions of \"review_body\",\"star_rating\" because transform.py requires this order.\nlabeled_df = df_pos_neg.loc[:, [\"review_body\",\"star_rating\"]]\ndata_size = len(labeled_df.index)\ntrain_ratio = 0.9\ntrain_index = np.random.choice(data_size, int(data_size*train_ratio), replace=False)\ntest_index = np.setdiff1d(np.arange(data_size), train_index)\n\nnp.savetxt('train.tsv',labeled_df.iloc[train_index].values, fmt=\"%s\\t%i\") \n\nprint(\"Data is splitted into:\")\nprint(\"Training data: {} records.\".format(len(train_index)))\nprint(\"Test data: {} records.\".format(len(test_index)))", "_____no_output_____" ] ], [ [ "### データのアップロード\n\nSageMaker での学習に利用するために、学習データを S3 にアップロードします。SageMaker Python SDK の upload_data を利用すると、S3 にファイルをアップロードできます。アップロード先のバケットは `sagemaker-{リージョン名}-{アカウントID}`で、バケットがない場合は自動作成されます。もし存在するバケットにアップロードする場合は、このバケット名を引数で指定できます。", "_____no_output_____" ] ], [ [ "import sagemaker\n\nsess = sagemaker.Session()\n\ns3_train_data = sess.upload_data(path='train.tsv', key_prefix='amazon-review-data')\nprint(\"Training data is uploaded to {}\".format(s3_train_data))\n\ndata_channels = {'train': s3_train_data}", "_____no_output_____" ] ], [ [ "## 学習の実行\n\n### 学習コードの作成\n\nGluonNLP を利用した BERT の学習とデプロイ用のコードを `train_and_deploy.py` として作成します。コード作成にあたっては、GluonNLP の公式ページのチュートリアルのコードを流用可能です。\n\nhttps://gluon-nlp.mxnet.io/examples/sentence_embedding/bert.html\n\nただし、この公式チュートリアルはペアの文書を分類する前提になっています。今回はペアを利用しないため、以下の点を修正して利用します。\n\n```python\npair = False\n```\n\n### GluonNLP のインストール\n\nノートブックインスタンス、学習用インスタンス、推論用インスタンスのいずれも GluonNLP がインストールされていません。GluonNLP で書かれたスクリプトを実行するために、以下の手順でインストールします。\n\n1. ノートブックインスタンス上で pip することで GluonNLP をインストールします (`./lib` にインストール)\n2. 学習時に `dependencies=['lib']` と指定すれば、学習用インスタンスにコピーされます\n3. 同様にデプロイ時に `dependencies=['lib']` と指定すれば、推論用インスタンスにコピーされます\n\nまずは、以下を実行してノートブックインスタンスにインストールしましょう。", "_____no_output_____" ] ], [ [ "!pip install gluonnlp -t ./lib", "_____no_output_____" ] ], [ [ "### 学習ジョブの実行\n\nMXNet のコンテナを呼び出し、学習用のインスタンスを指定して、学習を実行します。上記で説明したように、`dependencies=['lib']`を指定します。`hyperparameters`で渡すパラメータは train_and_deploy.py でパースして利用することができます。BERTのモデルの学習は非常に時間がかかるため、1エポックだけ回すようにします。\n\nfit()を指定すれば、S3のデータを渡して学習することが可能です。", "_____no_output_____" ] ], [ [ "from sagemaker.mxnet import MXNet\n\ngluon_bert = MXNet(\"train_and_deploy.py\", \n role=sagemaker.get_execution_role(), \n source_dir = \"src\",\n train_instance_count=1, \n train_instance_type=\"ml.m4.xlarge\",\n framework_version=\"1.4.1\",\n dependencies=['lib'],\n distributions={'parameter_server': {'enabled': True}},\n py_version = \"py3\",\n hyperparameters={'batch-size': 16, \n 'epochs': 1, \n 'log-interval': 1})", "_____no_output_____" ], [ "gluon_bert.fit(data_channels)", "_____no_output_____" ] ], [ [ "## 推論の実行\n\n学習が終わると、作成されたモデルをデプロイして、推論を実行することができます。デプロイは deploy を呼び出すだけでできます。`---`といった出力があるときはデプロイ中で、`!`が出力されるとデプロイが完了です。\n\n### 推論のコード\n\nSageMakerがサポートしている機械学習フレームワークコンテナで推論を行う場合は、モデルの読み込みや前処理・後処理を容易に実装できます。MXNet の場合は、モデル読み込みに `model_fn`、前処理・後処理に `transform_fn` を実装します。model_fnでは学習したモデルだけでなく、Tokenizerも読み込んでおき、`transformer_fn`で利用します。\n\n```python\ndef model_fn(model_dir):\n bert_tokenizer = nlp.data.BERTTokenizer(vocabulary, lower=True)\n bert_classifier = gluon.SymbolBlock.imports(\n '%s/model-symbol.json' % model_dir,\n ['data0', 'data1', 'data2'],\n '%s/model-0000.params' % model_dir,\n )\n return {\"net\": bert_classifier, \"tokenizer\": bert_tokenizer}\n\ndef transform_fn(net, data, input_content_type, output_content_type):\n \n bert_classifier = net[\"net\"]\n bert_tokenizer = net[\"tokenizer\"]\n \n parsed = json.loads(data)\n logging.info(\"Received_data: {}\".format(parsed))\n tokens = bert_tokenizer(parsed)\n logging.info(\"Tokens: {}\".format(tokens))\n token_ids = bert_tokenizer.convert_tokens_to_ids(tokens)\n valid_length = len(token_ids)\n segment_ids = mx.nd.zeros([1, valid_length])\n\n output = bert_classifier(mx.nd.array([token_ids]), \n segment_ids, \n mx.nd.array([valid_length]).astype('float32'))\n response_body = json.dumps(output.asnumpy().tolist()[0])\n return response_body, output_content_type\n```\n", "_____no_output_____" ] ], [ [ "predictor = gluon_bert.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')", "_____no_output_____" ] ], [ [ "デプロイが終わったら推論を実行してみましょう。ここでは negative なレビューを 5件、 positive なレビューを 5件ランダムに選択して推論を実行します。1エポックしか実行しない場合、良い精度を得ることは難しいと思います。ぜひ多くのエポックを試してみてください。", "_____no_output_____" ] ], [ [ "import mxnet as mx\n\nnum_test = 5\ntest_data = labeled_df.iloc[test_index]\n\nneg_test_data = test_data[test_data.star_rating == 0]\npos_test_data = test_data[test_data.star_rating == 1]\n\nneg_index = np.random.choice(neg_test_data.index, num_test)\npos_index = np.random.choice(pos_test_data.index, num_test)\n\nfor i in neg_index:\n pred = predictor.predict(neg_test_data.loc[i, \"review_body\"])\n prob = mx.nd.softmax(mx.nd.array(pred).reshape([1,2]))\n pred_label =np.argmax(prob, axis = 1)\n print(\"Ground Truth: {}, Prediction: {} (probability: {})\"\n .format(0, pred_label.asscalar(), prob[0, pred_label[0]].asscalar()))\n print(neg_test_data.loc[i, \"review_body\"])\n print()\n \n\nfor i in pos_index:\n pred = predictor.predict(pos_test_data.loc[i, \"review_body\"])\n prob = mx.nd.softmax(mx.nd.array(pred).reshape([1,2]))\n pred_label =np.argmax(prob, axis = 1)\n print(\"Ground Truth: {}, Prediction: {} (probability: {})\"\n .format(1, pred_label.asscalar(), prob[0, pred_label[0]].asscalar()))\n print(pos_test_data.loc[i, \"review_body\"])\n print()", "_____no_output_____" ] ], [ [ "### 不要になったエンドポイントを削除", "_____no_output_____" ] ], [ [ "predictor.delete_endpoint()", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec4d1b0f24ae7b78faca04bc32a3273fd0498ffc
118,373
ipynb
Jupyter Notebook
02_Code/CSVP_Integrated_Simulation_Framework_TRSC.ipynb
KaSchr/CSVP_Code_Supplement
bf5522b7c343f1853c4feba43c7d29a41eac8dc8
[ "MIT" ]
2
2021-09-07T07:42:32.000Z
2022-01-04T04:02:18.000Z
02_Code/CSVP_Integrated_Simulation_Framework_TRSC.ipynb
KaSchr/CSVP_Code_Supplement
bf5522b7c343f1853c4feba43c7d29a41eac8dc8
[ "MIT" ]
null
null
null
02_Code/CSVP_Integrated_Simulation_Framework_TRSC.ipynb
KaSchr/CSVP_Code_Supplement
bf5522b7c343f1853c4feba43c7d29a41eac8dc8
[ "MIT" ]
null
null
null
64.054654
501
0.446825
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec4d23fa758e63d2b1454063e7a179d400dfa183
1,177
ipynb
Jupyter Notebook
_downloads/plot_simple.ipynb
scipy-lectures/scipy-lectures.github.com
637a0d9cc2c95ed196550371e44a4cc6e150c830
[ "CC-BY-4.0" ]
48
2015-01-13T22:15:34.000Z
2022-01-04T20:17:41.000Z
_downloads/plot_simple.ipynb
scipy-lectures/scipy-lectures.github.com
637a0d9cc2c95ed196550371e44a4cc6e150c830
[ "CC-BY-4.0" ]
1
2017-04-25T09:01:00.000Z
2017-04-25T13:48:56.000Z
_downloads/plot_simple.ipynb
scipy-lectures/scipy-lectures.github.com
637a0d9cc2c95ed196550371e44a4cc6e150c830
[ "CC-BY-4.0" ]
21
2015-03-16T17:52:23.000Z
2021-02-19T00:02:13.000Z
21.796296
158
0.461342
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\nA simple example\n=================\n\n\n", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n\nX = np.linspace(-np.pi, np.pi, 100)\nY = np.sin(X)\n\nplt.plot(X, Y, linewidth=2)\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ] ]
ec4d2c875a9ace1fcb1906064be220838ba53a91
350,291
ipynb
Jupyter Notebook
Project/SageMaker Project.ipynb
Youfengxu/udacity-ml-eng-sentiment-analysis
e368f5fd3ce937b3cd8058aa1da65eed01f872d9
[ "MIT" ]
null
null
null
Project/SageMaker Project.ipynb
Youfengxu/udacity-ml-eng-sentiment-analysis
e368f5fd3ce937b3cd8058aa1da65eed01f872d9
[ "MIT" ]
null
null
null
Project/SageMaker Project.ipynb
Youfengxu/udacity-ml-eng-sentiment-analysis
e368f5fd3ce937b3cd8058aa1da65eed01f872d9
[ "MIT" ]
null
null
null
180.74871
235,836
0.843544
[ [ [ "# Creating a Sentiment Analysis Web App\n## Using PyTorch and SageMaker\n\n_Deep Learning Nanodegree Program | Deployment_\n\n---\n\nNow that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to enter a movie review. The web page will then send the review off to our deployed model which will predict the sentiment of the entered review.\n\n## Instructions\n\nSome template code has already been provided for you, and you will need to implement additional functionality to successfully complete this notebook. You will not need to modify the included code beyond what is requested. Sections that begin with '**TODO**' in the header indicate that you need to complete or implement some portion within them. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `# TODO: ...` comment. Please be sure to read the instructions carefully!\n\nIn addition to implementing code, there will be questions for you to answer which relate to the task and your implementation. Each section where you will answer a question is preceded by a '**Question:**' header. Carefully read each question and provide your answer below the '**Answer:**' header by editing the Markdown cell.\n\n> **Note**: Code and Markdown cells can be executed using the **Shift+Enter** keyboard shortcut. In addition, a cell can be edited by typically clicking it (double-click for Markdown cells) or by pressing **Enter** while it is highlighted.\n\n## General Outline\n\nRecall the general outline for SageMaker projects using a notebook instance.\n\n1. Download or otherwise retrieve the data.\n2. Process / Prepare the data.\n3. Upload the processed data to S3.\n4. Train a chosen model.\n5. Test the trained model (typically using a batch transform job).\n6. Deploy the trained model.\n7. Use the deployed model.\n\nFor this project, you will be following the steps in the general outline with some modifications. \n\nFirst, you will not be testing the model in its own step. You will still be testing the model, however, you will do it by deploying your model and then using the deployed model by sending the test data to it. One of the reasons for doing this is so that you can make sure that your deployed model is working correctly before moving forward.\n\nIn addition, you will deploy and use your trained model a second time. In the second iteration you will customize the way that your trained model is deployed by including some of your own code. In addition, your newly deployed model will be used in the sentiment analysis web app.", "_____no_output_____" ] ], [ [ "# Make sure that we use SageMaker 1.x\n!pip install sagemaker==1.72.0", "Collecting sagemaker==1.72.0\n Downloading sagemaker-1.72.0.tar.gz (297 kB)\n |████████████████████████████████| 297 kB 22.4 MB/s \n\u001b[?25h Preparing metadata (setup.py) ... \u001b[?25ldone\n\u001b[?25hRequirement already satisfied: boto3>=1.14.12 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (1.21.12)\nRequirement already satisfied: numpy>=1.9.0 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (1.19.5)\nRequirement already satisfied: protobuf>=3.1 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (3.17.2)\nRequirement already satisfied: scipy>=0.19.0 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (1.5.3)\nRequirement already satisfied: protobuf3-to-dict>=0.1.5 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (0.1.5)\nCollecting smdebug-rulesconfig==0.1.4\n Downloading smdebug_rulesconfig-0.1.4-py2.py3-none-any.whl (10 kB)\nRequirement already satisfied: importlib-metadata>=1.4.0 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (4.5.0)\nRequirement already satisfied: packaging>=20.0 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (21.3)\nRequirement already satisfied: s3transfer<0.6.0,>=0.5.0 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from boto3>=1.14.12->sagemaker==1.72.0) (0.5.0)\nRequirement already satisfied: jmespath<1.0.0,>=0.7.1 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from boto3>=1.14.12->sagemaker==1.72.0) (0.10.0)\nRequirement already satisfied: botocore<1.25.0,>=1.24.12 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from boto3>=1.14.12->sagemaker==1.72.0) (1.24.12)\nRequirement already satisfied: typing-extensions>=3.6.4 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from importlib-metadata>=1.4.0->sagemaker==1.72.0) (3.10.0.0)\nRequirement already satisfied: zipp>=0.5 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from importlib-metadata>=1.4.0->sagemaker==1.72.0) (3.4.1)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from packaging>=20.0->sagemaker==1.72.0) (2.4.7)\nRequirement already satisfied: six>=1.9 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from protobuf>=3.1->sagemaker==1.72.0) (1.16.0)\nRequirement already satisfied: python-dateutil<3.0.0,>=2.1 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from botocore<1.25.0,>=1.24.12->boto3>=1.14.12->sagemaker==1.72.0) (2.8.1)\nRequirement already satisfied: urllib3<1.27,>=1.25.4 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from botocore<1.25.0,>=1.24.12->boto3>=1.14.12->sagemaker==1.72.0) (1.26.8)\nBuilding wheels for collected packages: sagemaker\n Building wheel for sagemaker (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for sagemaker: filename=sagemaker-1.72.0-py2.py3-none-any.whl size=388327 sha256=11ea1c2d6ac912bbf1b48e401862639e02a37530d2fddc344ab1b0ae814c80cf\n Stored in directory: /home/ec2-user/.cache/pip/wheels/c3/58/70/85faf4437568bfaa4c419937569ba1fe54d44c5db42406bbd7\nSuccessfully built sagemaker\nInstalling collected packages: smdebug-rulesconfig, sagemaker\n Attempting uninstall: smdebug-rulesconfig\n Found existing installation: smdebug-rulesconfig 1.0.1\n Uninstalling smdebug-rulesconfig-1.0.1:\n Successfully uninstalled smdebug-rulesconfig-1.0.1\n Attempting uninstall: sagemaker\n Found existing installation: sagemaker 2.77.1\n Uninstalling sagemaker-2.77.1:\n Successfully uninstalled sagemaker-2.77.1\nSuccessfully installed sagemaker-1.72.0 smdebug-rulesconfig-0.1.4\n" ] ], [ [ "## Step 1: Downloading the data\n\nAs in the XGBoost in SageMaker notebook, we will be using the [IMDb dataset](http://ai.stanford.edu/~amaas/data/sentiment/)\n\n> Maas, Andrew L., et al. [Learning Word Vectors for Sentiment Analysis](http://ai.stanford.edu/~amaas/data/sentiment/). In _Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies_. Association for Computational Linguistics, 2011.", "_____no_output_____" ] ], [ [ "%mkdir ../data\n!wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n!tar -zxf ../data/aclImdb_v1.tar.gz -C ../data", "mkdir: cannot create directory ‘../data’: File exists\n--2022-03-27 08:12:23-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\nResolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10\nConnecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 84125825 (80M) [application/x-gzip]\nSaving to: ‘../data/aclImdb_v1.tar.gz’\n\n../data/aclImdb_v1. 100%[===================>] 80.23M 28.4MB/s in 2.8s \n\n2022-03-27 08:12:26 (28.4 MB/s) - ‘../data/aclImdb_v1.tar.gz’ saved [84125825/84125825]\n\n" ] ], [ [ "## Step 2: Preparing and Processing the data\n\nAlso, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a training set and a testing set.", "_____no_output_____" ] ], [ [ "import os\nimport glob\n\ndef read_imdb_data(data_dir='../data/aclImdb'):\n data = {}\n labels = {}\n \n for data_type in ['train', 'test']:\n data[data_type] = {}\n labels[data_type] = {}\n \n for sentiment in ['pos', 'neg']:\n data[data_type][sentiment] = []\n labels[data_type][sentiment] = []\n \n path = os.path.join(data_dir, data_type, sentiment, '*.txt')\n files = glob.glob(path)\n \n for f in files:\n with open(f) as review:\n data[data_type][sentiment].append(review.read())\n # Here we represent a positive review by '1' and a negative review by '0'\n labels[data_type][sentiment].append(1 if sentiment == 'pos' else 0)\n \n assert len(data[data_type][sentiment]) == len(labels[data_type][sentiment]), \\\n \"{}/{} data size does not match labels size\".format(data_type, sentiment)\n \n return data, labels", "_____no_output_____" ], [ "data, labels = read_imdb_data()\nprint(\"IMDB reviews: train = {} pos / {} neg, test = {} pos / {} neg\".format(\n len(data['train']['pos']), len(data['train']['neg']),\n len(data['test']['pos']), len(data['test']['neg'])))", "IMDB reviews: train = 12500 pos / 12500 neg, test = 12500 pos / 12500 neg\n" ] ], [ [ "Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records.", "_____no_output_____" ] ], [ [ "from sklearn.utils import shuffle\n\ndef prepare_imdb_data(data, labels):\n \"\"\"Prepare training and test sets from IMDb movie reviews.\"\"\"\n \n #Combine positive and negative reviews and labels\n data_train = data['train']['pos'] + data['train']['neg']\n data_test = data['test']['pos'] + data['test']['neg']\n labels_train = labels['train']['pos'] + labels['train']['neg']\n labels_test = labels['test']['pos'] + labels['test']['neg']\n \n #Shuffle reviews and corresponding labels within training and test sets\n data_train, labels_train = shuffle(data_train, labels_train)\n data_test, labels_test = shuffle(data_test, labels_test)\n \n # Return a unified training data, test data, training labels, test labets\n return data_train, data_test, labels_train, labels_test", "_____no_output_____" ], [ "train_X, test_X, train_y, test_y = prepare_imdb_data(data, labels)\nprint(\"IMDb reviews (combined): train = {}, test = {}\".format(len(train_X), len(test_X)))", "IMDb reviews (combined): train = 25000, test = 25000\n" ] ], [ [ "Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loaded correctly.", "_____no_output_____" ] ], [ [ "print(train_X[100])\nprint(train_y[100])", "I watched both Bourne Identity and Bourne Supremacy on DVD before seeing this in the theater. I'd been waiting for this since before they started filming. I wasn't disappointed.<br /><br />Minor spoilers below- <br /><br />Overall it was good, but it also lacked the continuity of the first two. Identity and Supremacy both flowed gracefully between adrenaline rush action to introspective drama. This movie felt choppy at times. The plot-building down-times were slightly too drawn out. That caused the following action to feel too frenetic.<br /><br />Camera: Speaking of frenetic, the trademark Greengrass shaky cam was present and very annoying to me. I know its has been talked/whined about to nausea on the message board, but it doesn't mean it's not relevant. All the martial arts training the actors went through was totally wasted. The ridiculous camera cuts and wiggling camera ruined most of the fighting in the movie. It is a cheap, student director trick to make the film feel unsettled. I'd expect those techniques to be used in some horror flick made for high school kids, but not in this classy, adult, action series. Too much extreme close-up also. Do some framing. Get some interesting shots. Constant close-up feels like lazy directing to me.<br /><br />Story: The story was VERY confusing at first. They thrust new names and faces upon you from the get go. Gave me the feeling that you get when you come into a movie late and know you've missed some crucial information. Felt rushed or compressed for time reasons. After you catch up however the story is quite good. It's enjoyable following leads along with Bourne. HOWEVER, I did NOT care for the whole last scene of Supremacy (Landy/Bourne on the phone) being in the middle of Ultimatum thing. It basically makes the movie a half-prequel. I thought that was awkward.<br /><br />Cast/Characters: The star of the movie is the action. Obviously there are only two originals left. Bourne and Nicky Parsons. Them teaming up was kind of odd to me. I think they just wanted to give Bourne someone to protect to and confide in. Unless I completely missed something, they never even tell you why they teamed up. The other assassins in the movie were pretty quiet. This felt like Gilroy/Greengrass/whoever wanting to not leave open ends. Understandable but disappointing. Seriously, Damon with Clive Owen in Identity and Marton Csokas in Supremacy.. Those scenes were phenomenal. These assassins are as uninteresting as Castel (the first fella Bourne fights in Identity). The cast in general has degraded as the the series went on. Clive Owen was practically an afterthought. That's a measure of strength for that first cast. The second, they basically trade Chris Cooper for Joan Allen.... Not exactly equal. This one trades Brian Cox and Franka Potente for 3 actors to be named later. Nothing against David Strathairn, Scott Glenn, or Albert Finney, but they're not the first names that come to mind for this kind of series. Aside from a couple pauses that seemed to long, the acting was right on.<br /><br />As a whole, it was successful. Felt like they wanted to get the series over with though. If they would have trimmed or rearranged the slower parts, eliminated Scott Glenn's part entirely, zoomed out, and taken the camera away from the seizure victim, it would have been perfect.<br /><br />ENDING SPOILER<br /><br />I don't see why they leave Bourne alive at the end. It was my understanding this was the conclusion. They clearly made reference to the very beginning of the series with his silhouette floating motionless. I thought that was going to be it. A full circle type of ending. I did like Nicky reacting to the news report though.<br /><br />SPOILER SPECIFICS WARNING - QUOTE FROM MOVIE BELOW -<br /><br />Bourne's last line at the end \"Look at this.. Look at what they make you give.\" quoting the first assassin he killed, I loved that. The final scene was great. (Except that it was Vosen {Strathairn} that shot at Bourne. Why would he do that? Just out for vengeance? If he was angry enough to murder, why not shoot Pamela Landy after she faxes his top secret file? That didn't make sense.)\n1\n" ] ], [ [ "The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis.", "_____no_output_____" ] ], [ [ "import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import *\n\nimport re\nfrom bs4 import BeautifulSoup\n\ndef review_to_words(review):\n nltk.download(\"stopwords\", quiet=True)\n stemmer = PorterStemmer()\n \n text = BeautifulSoup(review, \"html.parser\").get_text() # Remove HTML tags\n text = re.sub(r\"[^a-zA-Z0-9]\", \" \", text.lower()) # Convert to lower case\n words = text.split() # Split string into words\n words = [w for w in words if w not in stopwords.words(\"english\")] # Remove stopwords\n words = [PorterStemmer().stem(w) for w in words] # stem\n \n return words", "_____no_output_____" ] ], [ [ "The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set.", "_____no_output_____" ] ], [ [ "# TODO: Apply review_to_words to a review (train_X[100] or any other review)\ntokenized_sample = review_to_words(train_X[100])\nprint(tokenized_sample)", "['watch', 'bourn', 'ident', 'bourn', 'supremaci', 'dvd', 'see', 'theater', 'wait', 'sinc', 'start', 'film', 'disappoint', 'minor', 'spoiler', 'overal', 'good', 'also', 'lack', 'continu', 'first', 'two', 'ident', 'supremaci', 'flow', 'grace', 'adrenalin', 'rush', 'action', 'introspect', 'drama', 'movi', 'felt', 'choppi', 'time', 'plot', 'build', 'time', 'slightli', 'drawn', 'caus', 'follow', 'action', 'feel', 'frenet', 'camera', 'speak', 'frenet', 'trademark', 'greengrass', 'shaki', 'cam', 'present', 'annoy', 'know', 'talk', 'whine', 'nausea', 'messag', 'board', 'mean', 'relev', 'martial', 'art', 'train', 'actor', 'went', 'total', 'wast', 'ridicul', 'camera', 'cut', 'wiggl', 'camera', 'ruin', 'fight', 'movi', 'cheap', 'student', 'director', 'trick', 'make', 'film', 'feel', 'unsettl', 'expect', 'techniqu', 'use', 'horror', 'flick', 'made', 'high', 'school', 'kid', 'classi', 'adult', 'action', 'seri', 'much', 'extrem', 'close', 'also', 'frame', 'get', 'interest', 'shot', 'constant', 'close', 'feel', 'like', 'lazi', 'direct', 'stori', 'stori', 'confus', 'first', 'thrust', 'new', 'name', 'face', 'upon', 'get', 'go', 'gave', 'feel', 'get', 'come', 'movi', 'late', 'know', 'miss', 'crucial', 'inform', 'felt', 'rush', 'compress', 'time', 'reason', 'catch', 'howev', 'stori', 'quit', 'good', 'enjoy', 'follow', 'lead', 'along', 'bourn', 'howev', 'care', 'whole', 'last', 'scene', 'supremaci', 'landi', 'bourn', 'phone', 'middl', 'ultimatum', 'thing', 'basic', 'make', 'movi', 'half', 'prequel', 'thought', 'awkward', 'cast', 'charact', 'star', 'movi', 'action', 'obvious', 'two', 'origin', 'left', 'bourn', 'nicki', 'parson', 'team', 'kind', 'odd', 'think', 'want', 'give', 'bourn', 'someon', 'protect', 'confid', 'unless', 'complet', 'miss', 'someth', 'never', 'even', 'tell', 'team', 'assassin', 'movi', 'pretti', 'quiet', 'felt', 'like', 'gilroy', 'greengrass', 'whoever', 'want', 'leav', 'open', 'end', 'understand', 'disappoint', 'serious', 'damon', 'clive', 'owen', 'ident', 'marton', 'csoka', 'supremaci', 'scene', 'phenomen', 'assassin', 'uninterest', 'castel', 'first', 'fella', 'bourn', 'fight', 'ident', 'cast', 'gener', 'degrad', 'seri', 'went', 'clive', 'owen', 'practic', 'afterthought', 'measur', 'strength', 'first', 'cast', 'second', 'basic', 'trade', 'chri', 'cooper', 'joan', 'allen', 'exactli', 'equal', 'one', 'trade', 'brian', 'cox', 'franka', 'potent', '3', 'actor', 'name', 'later', 'noth', 'david', 'strathairn', 'scott', 'glenn', 'albert', 'finney', 'first', 'name', 'come', 'mind', 'kind', 'seri', 'asid', 'coupl', 'paus', 'seem', 'long', 'act', 'right', 'whole', 'success', 'felt', 'like', 'want', 'get', 'seri', 'though', 'would', 'trim', 'rearrang', 'slower', 'part', 'elimin', 'scott', 'glenn', 'part', 'entir', 'zoom', 'taken', 'camera', 'away', 'seizur', 'victim', 'would', 'perfect', 'end', 'spoileri', 'see', 'leav', 'bourn', 'aliv', 'end', 'understand', 'conclus', 'clearli', 'made', 'refer', 'begin', 'seri', 'silhouett', 'float', 'motionless', 'thought', 'go', 'full', 'circl', 'type', 'end', 'like', 'nicki', 'react', 'news', 'report', 'though', 'spoiler', 'specif', 'warn', 'quot', 'movi', 'bourn', 'last', 'line', 'end', 'look', 'look', 'make', 'give', 'quot', 'first', 'assassin', 'kill', 'love', 'final', 'scene', 'great', 'except', 'vosen', 'strathairn', 'shot', 'bourn', 'would', 'vengeanc', 'angri', 'enough', 'murder', 'shoot', 'pamela', 'landi', 'fax', 'top', 'secret', 'file', 'make', 'sens']\n" ] ], [ [ "**Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do to the input?", "_____no_output_____" ], [ "**Answer:**\nThe method also converts the review into lower case, splits the review string into a list of words, and removes any stop words (words that do not add much meaning) from the list.", "_____no_output_____" ], [ "The method below applies the `review_to_words` method to each of the reviews in the training and testing datasets. In addition it caches the results. This is because performing this processing step can take a long time. This way if you are unable to complete the notebook in the current session, you can come back without needing to process the data a second time.", "_____no_output_____" ] ], [ [ "import pickle\n\ncache_dir = os.path.join(\"../cache\", \"sentiment_analysis\") # where to store cache files\nos.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists\n\ndef preprocess_data(data_train, data_test, labels_train, labels_test,\n cache_dir=cache_dir, cache_file=\"preprocessed_data.pkl\"):\n \"\"\"Convert each review to words; read from cache if available.\"\"\"\n\n # If cache_file is not None, try to read from it first\n cache_data = None\n if cache_file is not None:\n try:\n with open(os.path.join(cache_dir, cache_file), \"rb\") as f:\n cache_data = pickle.load(f)\n print(\"Read preprocessed data from cache file:\", cache_file)\n except:\n pass # unable to read from cache, but that's okay\n \n # If cache is missing, then do the heavy lifting\n if cache_data is None:\n # Preprocess training and test data to obtain words for each review\n #words_train = list(map(review_to_words, data_train))\n #words_test = list(map(review_to_words, data_test))\n words_train = [review_to_words(review) for review in data_train]\n words_test = [review_to_words(review) for review in data_test]\n \n # Write to cache file for future runs\n if cache_file is not None:\n cache_data = dict(words_train=words_train, words_test=words_test,\n labels_train=labels_train, labels_test=labels_test)\n with open(os.path.join(cache_dir, cache_file), \"wb\") as f:\n pickle.dump(cache_data, f)\n print(\"Wrote preprocessed data to cache file:\", cache_file)\n else:\n # Unpack data loaded from cache file\n words_train, words_test, labels_train, labels_test = (cache_data['words_train'],\n cache_data['words_test'], cache_data['labels_train'], cache_data['labels_test'])\n \n return words_train, words_test, labels_train, labels_test", "_____no_output_____" ], [ "# Preprocess data\ntrain_X, test_X, train_y, test_y = preprocess_data(train_X, test_X, train_y, test_y)", "Read preprocessed data from cache file: preprocessed_data.pkl\n" ] ], [ [ "## Transform the data\n\nIn the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of course, some of the words that appear in the reviews occur very infrequently and so likely don't contain much information for the purposes of sentiment analysis. The way we will deal with this problem is that we will fix the size of our working vocabulary and we will only include the words that appear most frequently. We will then combine all of the infrequent words into a single category and, in our case, we will label it as `1`.\n\nSince we will be using a recurrent neural network, it will be convenient if the length of each review is the same. To do this, we will fix a size for our reviews and then pad short reviews with the category 'no word' (which we will label `0`) and truncate long reviews.", "_____no_output_____" ], [ "### (TODO) Create a word dictionary\n\nTo begin with, we need to construct a way to map words that appear in the reviews to integers. Here we fix the size of our vocabulary (including the 'no word' and 'infrequent' categories) to be `5000` but you may wish to change this to see how it affects the model.\n\n> **TODO:** Complete the implementation for the `build_dict()` method below. Note that even though the vocab_size is set to `5000`, we only want to construct a mapping for the most frequently appearing `4998` words. This is because we want to reserve the special labels `0` for 'no word' and `1` for 'infrequent word'.", "_____no_output_____" ] ], [ [ "import numpy as np\n\ndef build_dict(data, vocab_size = 5000):\n \"\"\"Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer.\"\"\"\n \n # TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and that a\n # sentence is a list of words.\n \n word_count = {} # A dict storing the words that appear in the reviews along with how often they occur\n for sentence in data:\n for word in sentence:\n if(word in word_count):\n word_count[word] +=1\n else: word_count[word] = 1\n # TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and\n # sorted_words[-1] is the least frequently appearing word.\n \n sorted_words = None\n sorted_words = sorted(word_count.items(), key=lambda item:item[1], reverse=True)\n sorted_words = [item[0] for item in sorted_words]\n word_dict = {} # This is what we are building, a dictionary that translates words into integers\n for idx, word in enumerate(sorted_words[:vocab_size - 2]): # The -2 is so that we save room for the 'no word'\n word_dict[word] = idx + 2 # 'infrequent' labels\n \n return word_dict", "_____no_output_____" ], [ "word_dict = build_dict(train_X)", "_____no_output_____" ] ], [ [ "**Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set?", "_____no_output_____" ], [ "**Answer:**", "_____no_output_____" ] ], [ [ "# TODO: Use this space to determine the five most frequently appearing words in the training set.\ntop_five_words = sorted(word_dict.items(), key=lambda item:item[1])[:5]\ntop_five_words = [item[0] for item in top_five_words]\nprint(top_five_words)", "['movi', 'film', 'one', 'like', 'time']\n" ] ], [ [ "### Save `word_dict`\n\nLater on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use.", "_____no_output_____" ] ], [ [ "data_dir = '../data/pytorch' # The folder we will use for storing data\nif not os.path.exists(data_dir): # Make sure that the folder exists\n os.makedirs(data_dir)", "_____no_output_____" ], [ "with open(os.path.join(data_dir, 'word_dict.pkl'), \"wb\") as f:\n pickle.dump(word_dict, f)", "_____no_output_____" ] ], [ [ "### Transform the reviews\n\nNow that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`.", "_____no_output_____" ] ], [ [ "def convert_and_pad(word_dict, sentence, pad=500):\n NOWORD = 0 # We will use 0 to represent the 'no word' category\n INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict\n \n working_sentence = [NOWORD] * pad\n \n for word_index, word in enumerate(sentence[:pad]):\n if word in word_dict:\n working_sentence[word_index] = word_dict[word]\n else:\n working_sentence[word_index] = INFREQ\n \n return working_sentence, min(len(sentence), pad)\n\ndef convert_and_pad_data(word_dict, data, pad=500):\n result = []\n lengths = []\n \n for sentence in data:\n converted, leng = convert_and_pad(word_dict, sentence, pad)\n result.append(converted)\n lengths.append(leng)\n \n return np.array(result), np.array(lengths)", "_____no_output_____" ], [ "train_X, train_X_len = convert_and_pad_data(word_dict, train_X)\ntest_X, test_X_len = convert_and_pad_data(word_dict, test_X)", "_____no_output_____" ] ], [ [ "As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set?", "_____no_output_____" ] ], [ [ "# Use this cell to examine one of the processed reviews to make sure everything is working as intended.\ntrain_X[100]", "_____no_output_____" ] ], [ [ "**Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem?", "_____no_output_____" ], [ "**Answer:** To transform the data, both methods use word_dict, which was created using only the training set. If the most frequently appearing words in the testing set differs significantly from those in the training set, many important words in the testing set might be labeled as infrequent. This will affect the accuracy of the resulting model.", "_____no_output_____" ], [ "## Step 3: Upload the data to S3\n\nAs in the XGBoost notebook, we will need to upload the training dataset to S3 in order for our training code to access it. For now we will save it locally and we will upload to S3 later on.\n\n### Save the processed training dataset locally\n\nIt is important to note the format of the data that we are saving as we will need to know it when we write the training code. In our case, each row of the dataset has the form `label`, `length`, `review[500]` where `review[500]` is a sequence of `500` integers representing the words in the review.", "_____no_output_____" ] ], [ [ "import pandas as pd\n \npd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \\\n .to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False)", "_____no_output_____" ] ], [ [ "### Uploading the training data\n\n\nNext, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model.", "_____no_output_____" ] ], [ [ "import sagemaker\n\nsagemaker_session = sagemaker.Session()\n\nbucket = sagemaker_session.default_bucket()\nprefix = 'sagemaker/sentiment_rnn'\n\nrole = sagemaker.get_execution_role()", "_____no_output_____" ], [ "input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix)", "_____no_output_____" ] ], [ [ "**NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also in the S3 training bucket) and that we will need to make sure it gets saved in the model directory.", "_____no_output_____" ], [ "## Step 4: Build and Train the PyTorch Model\n\nIn the XGBoost notebook we discussed what a model is in the SageMaker framework. In particular, a model comprises three objects\n\n - Model Artifacts,\n - Training Code, and\n - Inference Code,\n \neach of which interact with one another. In the XGBoost example we used training and inference code that was provided by Amazon. Here we will still be using containers provided by Amazon with the added benefit of being able to include our own custom code.\n\nWe will start by implementing our own neural network in PyTorch along with a training script. For the purposes of this project we have provided the necessary model object in the `model.py` file, inside of the `train` folder. You can see the provided implementation by running the cell below.", "_____no_output_____" ] ], [ [ "!pygmentize train/model.py", "\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mnn\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnn\u001b[39;49;00m\r\n\r\n\u001b[34mclass\u001b[39;49;00m \u001b[04m\u001b[32mLSTMClassifier\u001b[39;49;00m(nn.Module):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m This is the simple RNN model we will be using to perform Sentiment Analysis.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n\r\n \u001b[34mdef\u001b[39;49;00m \u001b[32m__init__\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, embedding_dim, hidden_dim, vocab_size):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m Initialize the model by settingg up the various layers.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n \u001b[36msuper\u001b[39;49;00m(LSTMClassifier, \u001b[36mself\u001b[39;49;00m).\u001b[32m__init__\u001b[39;49;00m()\r\n\r\n \u001b[36mself\u001b[39;49;00m.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=\u001b[34m0\u001b[39;49;00m)\r\n \u001b[36mself\u001b[39;49;00m.lstm = nn.LSTM(embedding_dim, hidden_dim)\r\n \u001b[36mself\u001b[39;49;00m.dense = nn.Linear(in_features=hidden_dim, out_features=\u001b[34m1\u001b[39;49;00m)\r\n \u001b[36mself\u001b[39;49;00m.sig = nn.Sigmoid()\r\n \r\n \u001b[36mself\u001b[39;49;00m.word_dict = \u001b[34mNone\u001b[39;49;00m\r\n\r\n \u001b[34mdef\u001b[39;49;00m \u001b[32mforward\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, x):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m Perform a forward pass of our model on some input.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n x = x.t()\r\n lengths = x[\u001b[34m0\u001b[39;49;00m,:]\r\n reviews = x[\u001b[34m1\u001b[39;49;00m:,:]\r\n embeds = \u001b[36mself\u001b[39;49;00m.embedding(reviews)\r\n lstm_out, _ = \u001b[36mself\u001b[39;49;00m.lstm(embeds)\r\n out = \u001b[36mself\u001b[39;49;00m.dense(lstm_out)\r\n out = out[lengths - \u001b[34m1\u001b[39;49;00m, \u001b[36mrange\u001b[39;49;00m(\u001b[36mlen\u001b[39;49;00m(lengths))]\r\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mself\u001b[39;49;00m.sig(out.squeeze())\r\n" ] ], [ [ "The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training script so that if we wish to modify them we do not need to modify the script itself. We will see how to do this later on. To start we will write some of the training code in the notebook so that we can more easily diagnose any issues that arise.\n\nFirst we will load a small portion of the training data set to use as a sample. It would be very time consuming to try and train the model completely in the notebook as we do not have access to a gpu and the compute instance that we are using is not particularly powerful. However, we can work on a small bit of the data to get a feel for how our training script is behaving.", "_____no_output_____" ] ], [ [ "import torch\nimport torch.utils.data\n\n# Read in only the first 250 rows\ntrain_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250)\n\n# Turn the input pandas dataframe into tensors\ntrain_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze()\ntrain_sample_X = torch.from_numpy(train_sample.drop([0], axis=1).values).long()\n\n# Build the dataset\ntrain_sample_ds = torch.utils.data.TensorDataset(train_sample_X, train_sample_y)\n# Build the dataloader\ntrain_sample_dl = torch.utils.data.DataLoader(train_sample_ds, batch_size=50)", "_____no_output_____" ] ], [ [ "### (TODO) Writing the training method\n\nNext we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later.", "_____no_output_____" ] ], [ [ "def train(model, train_loader, epochs, optimizer, loss_fn, device):\n for epoch in range(1, epochs + 1):\n model.train()\n total_loss = 0\n for batch in train_loader: \n batch_X, batch_y = batch\n \n batch_X = batch_X.to(device)\n batch_y = batch_y.to(device)\n \n # TODO: Complete this train method to train the model provided.\n model.zero_grad()\n output = model(batch_X)\n loss = loss_fn(output, batch_y)\n loss.backward()\n optimizer.step()\n total_loss += loss.data.item()\n print(\"Epoch: {}, BCELoss: {}\".format(epoch, total_loss / len(train_loader)))\n", "_____no_output_____" ] ], [ [ "Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early when they are easier to diagnose.", "_____no_output_____" ] ], [ [ "import torch.optim as optim\nfrom train.model import LSTMClassifier\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = LSTMClassifier(32, 100, 5000).to(device)\noptimizer = optim.Adam(model.parameters())\nloss_fn = torch.nn.BCELoss()\n\ntrain(model, train_sample_dl, 5, optimizer, loss_fn, device)", "Epoch: 1, BCELoss: 0.6937717318534851\nEpoch: 2, BCELoss: 0.685172438621521\nEpoch: 3, BCELoss: 0.6776299476623535\nEpoch: 4, BCELoss: 0.6692437171936035\nEpoch: 5, BCELoss: 0.6590696215629578\n" ] ], [ [ "In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one) for a `requirements.txt` file and install any required Python libraries, after which the training script will be run.", "_____no_output_____" ], [ "### (TODO) Training the model\n\nWhen a PyTorch model is constructed in SageMaker, an entry point must be specified. This is the Python file which will be executed when the model is trained. Inside of the `train` directory is a file called `train.py` which has been provided and which contains most of the necessary code to train our model. The only thing that is missing is the implementation of the `train()` method which you wrote earlier in this notebook.\n\n**TODO**: Copy the `train()` method written above and paste it into the `train/train.py` file where required.\n\nThe way that SageMaker passes hyperparameters to the training script is by way of arguments. These arguments can then be parsed and used in the training script. To see how this is done take a look at the provided `train/train.py` file.", "_____no_output_____" ] ], [ [ "from sagemaker.pytorch import PyTorch\n\nestimator = PyTorch(entry_point=\"train.py\",\n source_dir=\"train\",\n role=role,\n framework_version='0.4.0',\n #py_version='py3',\n train_instance_count=1,\n train_instance_type='ml.m5.4xlarge',\n hyperparameters={\n 'epochs': 10,\n 'hidden_dim': 200,\n })", "_____no_output_____" ], [ "estimator.fit({'training': input_data})", "'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.\n'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n" ] ], [ [ "## Step 5: Testing the model\n\nAs mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly.\n\n## Step 6: Deploy the model for testing\n\nNow that we have trained our model, we would like to test it to see how it performs. Currently our model takes input of the form `review_length, review[500]` where `review[500]` is a sequence of `500` integers which describe the words present in the review, encoded using `word_dict`. Fortunately for us, SageMaker provides built-in inference code for models with simple inputs such as this.\n\nThere is one thing that we need to provide, however, and that is a function which loads the saved model. This function must be called `model_fn()` and takes as its only parameter a path to the directory where the model artifacts are stored. This function must also be present in the python file which we specified as the entry point. In our case the model loading function has been provided and so no changes need to be made.\n\n**NOTE**: When the built-in inference code is run it must import the `model_fn()` method from the `train.py` file. This is why the training code is wrapped in a main guard ( ie, `if __name__ == '__main__':` )\n\nSince we don't need to change anything in the code that was uploaded during training, we can simply deploy the current model as-is.\n\n**NOTE:** When deploying a model you are asking SageMaker to launch an compute instance that will wait for data to be sent to it. As a result, this compute instance will continue to run until *you* shut it down. This is important to know since the cost of a deployed endpoint depends on how long it has been running for.\n\nIn other words **If you are no longer using a deployed endpoint, shut it down!**\n\n**TODO:** Deploy the trained model.", "_____no_output_____" ] ], [ [ "# TODO: Deploy the trained model\npredictor = estimator.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\n'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n" ] ], [ [ "## Step 7 - Use the model for testing\n\nOnce deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is.", "_____no_output_____" ] ], [ [ "test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1)", "_____no_output_____" ], [ "# We split the data into chunks and send each chunk seperately, accumulating the results.\n\ndef predict(data, rows=512):\n split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))\n predictions = np.array([])\n for array in split_array:\n predictions = np.append(predictions, predictor.predict(array))\n \n return predictions", "_____no_output_____" ], [ "predictions = predict(test_X.values)\npredictions = [round(num) for num in predictions]", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(test_y, predictions)", "_____no_output_____" ] ], [ [ "**Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis?", "_____no_output_____" ], [ "**Answer:**This model performs better than XGBoost. The LSTM classifer used in this model is able to take into account the ordering of words, which will be able to provide context for each word that appears. It is therefore more suitable for sentiment analysis compared the the XGBoost.", "_____no_output_____" ], [ "### (TODO) More testing\n\nWe now have a trained model which has been deployed and which we can send processed reviews to and which returns the predicted sentiment. However, ultimately we would like to be able to send our model an unprocessed review. That is, we would like to send the review itself as a string. For example, suppose we wish to send the following review to our model.", "_____no_output_____" ] ], [ [ "test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.'", "_____no_output_____" ] ], [ [ "The question we now need to answer is, how do we send this review to our model?\n\nRecall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews.\n - Removed any html tags and stemmed the input\n - Encoded the review as a sequence of integers using `word_dict`\n \ntIn order process the review we will need to repeat these two steps.\n\n**TODO**: Using the `review_to_words` and `convert_and_pad` methods from section one, convert `test_review` into a numpy array `test_data` suitable to send to our model. Remember that our model expects input of the form `review_length, review[500]`. So make sure you produce two variables from processing: \n- A sequence of length 500 which represents the converted review\n- The length of the review", "_____no_output_____" ] ], [ [ "# TODO: Convert test_review into a form usable by the model and save the results in test_data\ntest_data = None\ntest_words = review_to_words(test_review)\ntest_data, test_data_length = convert_and_pad(word_dict,test_words)\ntest_data = np.expand_dims(np.array([test_data_length]+test_data),axis=0)\n", "_____no_output_____" ] ], [ [ "Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review.", "_____no_output_____" ] ], [ [ "predictor.predict(np.array(test_data))", "_____no_output_____" ] ], [ [ "Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive.", "_____no_output_____" ], [ "### Delete the endpoint\n\nOf course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delete it.", "_____no_output_____" ] ], [ [ "predictor.delete_endpoint()", "_____no_output_____" ] ], [ [ "## Step 6 (again) - Deploy the model for the web app\n\nNow that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review.\n\nAs we saw above, by default the estimator which we created, when deployed, will use the entry script and directory which we provided when creating the model. However, since we now wish to accept a string as input and our model expects a processed review, we need to write some custom inference code.\n\nWe will store the code that we write in the `serve` directory. Provided in this directory is the `model.py` file that we used to construct our model, a `utils.py` file which contains the `review_to_words` and `convert_and_pad` pre-processing functions which we used during the initial data processing, and `predict.py`, the file which will contain our custom inference code. Note also that `requirements.txt` is present which will tell SageMaker what Python libraries are required by our custom inference code.\n\nWhen deploying a PyTorch model in SageMaker, you are expected to provide four functions which the SageMaker inference container will use.\n - `model_fn`: This function is the same function that we used in the training script and it tells SageMaker how to load our model.\n - `input_fn`: This function receives the raw serialized input that has been sent to the model's endpoint and its job is to de-serialize and make the input available for the inference code.\n - `output_fn`: This function takes the output of the inference code and its job is to serialize this output and return it to the caller of the model's endpoint.\n - `predict_fn`: The heart of the inference script, this is where the actual prediction is done and is the function which you will need to complete.\n\nFor the simple website that we are constructing during this project, the `input_fn` and `output_fn` methods are relatively straightforward. We only require being able to accept a string as input and we expect to return a single value as output. You might imagine though that in a more complex application the input or output may be image data or some other binary data which would require some effort to serialize.\n\n### (TODO) Writing inference code\n\nBefore writing our custom inference code, we will begin by taking a look at the code which has been provided.", "_____no_output_____" ] ], [ [ "!pygmentize serve/predict.py", "\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36margparse\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mjson\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mos\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpickle\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msys\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msagemaker_containers\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpandas\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mpd\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mnumpy\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnp\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mnn\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnn\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36moptim\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36moptim\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mutils\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mdata\u001b[39;49;00m\r\n\r\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mmodel\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m LSTMClassifier\r\n\r\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mutils\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m review_to_words, convert_and_pad\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32mmodel_fn\u001b[39;49;00m(model_dir):\r\n \u001b[33m\"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\u001b[39;49;00m\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mLoading model.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n\r\n \u001b[37m# First, load the parameters used to create the model.\u001b[39;49;00m\r\n model_info = {}\r\n model_info_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mmodel_info.pth\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(model_info_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model_info = torch.load(f)\r\n\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mmodel_info: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(model_info))\r\n\r\n \u001b[37m# Determine the device and construct the model.\u001b[39;49;00m\r\n device = torch.device(\u001b[33m\"\u001b[39;49;00m\u001b[33mcuda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34mif\u001b[39;49;00m torch.cuda.is_available() \u001b[34melse\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcpu\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n model = LSTMClassifier(model_info[\u001b[33m'\u001b[39;49;00m\u001b[33membedding_dim\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m], model_info[\u001b[33m'\u001b[39;49;00m\u001b[33mhidden_dim\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m], model_info[\u001b[33m'\u001b[39;49;00m\u001b[33mvocab_size\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m])\r\n\r\n \u001b[37m# Load the store model parameters.\u001b[39;49;00m\r\n model_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mmodel.pth\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(model_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model.load_state_dict(torch.load(f))\r\n\r\n \u001b[37m# Load the saved word_dict.\u001b[39;49;00m\r\n word_dict_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mword_dict.pkl\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(word_dict_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model.word_dict = pickle.load(f)\r\n\r\n model.to(device).eval()\r\n\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mDone loading model.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m model\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32minput_fn\u001b[39;49;00m(serialized_input_data, content_type):\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mDeserializing the input data.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mif\u001b[39;49;00m content_type == \u001b[33m'\u001b[39;49;00m\u001b[33mtext/plain\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m:\r\n data = serialized_input_data.decode(\u001b[33m'\u001b[39;49;00m\u001b[33mutf-8\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m data\r\n \u001b[34mraise\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mRequested unsupported ContentType in content_type: \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m + content_type)\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32moutput_fn\u001b[39;49;00m(prediction_output, accept):\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mSerializing the generated output.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mstr\u001b[39;49;00m(prediction_output)\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32mpredict_fn\u001b[39;49;00m(input_data, model):\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mInferring sentiment of input data.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n\r\n device = torch.device(\u001b[33m\"\u001b[39;49;00m\u001b[33mcuda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34mif\u001b[39;49;00m torch.cuda.is_available() \u001b[34melse\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcpu\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n \r\n \u001b[34mif\u001b[39;49;00m model.word_dict \u001b[35mis\u001b[39;49;00m \u001b[34mNone\u001b[39;49;00m:\r\n \u001b[34mraise\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mModel has not been loaded properly, no word_dict.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \r\n \u001b[37m# TODO: Process input_data so that it is ready to be sent to our model.\u001b[39;49;00m\r\n \u001b[37m# You should produce two variables:\u001b[39;49;00m\r\n \u001b[37m# data_X - A sequence of length 500 which represents the converted review\u001b[39;49;00m\r\n \u001b[37m# data_len - The length of the review\u001b[39;49;00m\r\n\r\n input_words = review_to_words(input_data)\r\n input_words, input_words_length = convert_and_pad(model.word_dict, input_words)\r\n\r\n data_X = input_words\r\n data_len = input_words_length\r\n\r\n \u001b[37m# Using data_X and data_len we construct an appropriate input tensor. Remember\u001b[39;49;00m\r\n \u001b[37m# that our model expects input data of the form 'len, review[500]'.\u001b[39;49;00m\r\n data_pack = np.hstack((data_len, data_X))\r\n data_pack = data_pack.reshape(\u001b[34m1\u001b[39;49;00m, -\u001b[34m1\u001b[39;49;00m)\r\n \r\n data = torch.from_numpy(data_pack)\r\n data = data.to(device)\r\n\r\n \u001b[37m# Make sure to put the model into evaluation mode\u001b[39;49;00m\r\n model.eval()\r\n\r\n \u001b[37m# TODO: Compute the result of applying the model to the input data. The variable `result` should\u001b[39;49;00m\r\n \u001b[37m# be a numpy array which contains a single integer which is either 1 or 0\u001b[39;49;00m\r\n result = model(data).detach().cpu().numpy()\r\n result = np.rint(result)\r\n\r\n \r\n \u001b[34mreturn\u001b[39;49;00m result\r\n" ] ], [ [ "As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. \n\n**Note**: Our model expects input data of the form 'len, review[500]'. So make sure you produce two variables from processing: \n- `data_X`: A sequence of length 500 which represents the converted review\n- `data_len`: - The length of the review\n\nMake sure that you save the completed file as `predict.py` in the `serve` directory.\n\n**TODO**: Complete the `predict_fn()` method in the `serve/predict.py` file.", "_____no_output_____" ], [ "### Deploying the model\n\nNow that the custom inference code has been written, we will create and deploy our model. To begin with, we need to construct a new PyTorchModel object which points to the model artifacts created during training and also points to the inference code that we wish to use. Then we can call the deploy method to launch the deployment container.\n\n**NOTE**: The default behaviour for a deployed PyTorch model is to assume that any input passed to the predictor is a `numpy` array. In our case we want to send a string so we need to construct a simple wrapper around the `RealTimePredictor` class to accomodate simple strings. In a more complicated situation you may want to provide a serialization object, for example if you wanted to sent image data.", "_____no_output_____" ] ], [ [ "from sagemaker.predictor import RealTimePredictor\nfrom sagemaker.pytorch import PyTorchModel\n\nclass StringPredictor(RealTimePredictor):\n def __init__(self, endpoint_name, sagemaker_session):\n super(StringPredictor, self).__init__(endpoint_name, sagemaker_session, content_type='text/plain')\n\nmodel = PyTorchModel(model_data=estimator.model_data,\n role = role,\n framework_version='0.4.0',\n #py_version='py3',\n entry_point='predict.py',\n source_dir='serve',\n predictor_cls=StringPredictor)\npredictor = model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\n'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n" ] ], [ [ "### Testing the model\n\nNow that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is that the amount of time it takes for our model to process the input and then perform inference is quite long and so testing the entire data set would be prohibitive.", "_____no_output_____" ] ], [ [ "import glob\n\ndef test_reviews(data_dir='../data/aclImdb', stop=250):\n \n results = []\n ground = []\n \n # We make sure to test both positive and negative reviews \n for sentiment in ['pos', 'neg']:\n \n path = os.path.join(data_dir, 'test', sentiment, '*.txt')\n files = glob.glob(path)\n \n files_read = 0\n \n print('Starting ', sentiment, ' files')\n \n # Iterate through the files and send them to the predictor\n for f in files:\n with open(f) as review:\n # First, we store the ground truth (was the review positive or negative)\n if sentiment == 'pos':\n ground.append(1)\n else:\n ground.append(0)\n # Read in the review and convert to 'utf-8' for transmission via HTTP\n review_input = review.read().encode('utf-8')\n # Send the review to the predictor and store the results\n results.append(float(predictor.predict(review_input)))\n \n # Sending reviews to our endpoint one at a time takes a while so we\n # only send a small number of reviews\n files_read += 1\n if files_read == stop:\n break\n \n return ground, results", "_____no_output_____" ], [ "ground, results = test_reviews()", "Starting pos files\nStarting neg files\n" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(ground, results)", "_____no_output_____" ] ], [ [ "As an additional test, we can try sending the `test_review` that we looked at earlier.", "_____no_output_____" ] ], [ [ "predictor.predict(test_review)", "_____no_output_____" ] ], [ [ "Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back.", "_____no_output_____" ], [ "## Step 7 (again): Use the model for the web app\n\n> **TODO:** This entire section and the next contain tasks for you to complete, mostly using the AWS console.\n\nSo far we have been accessing our model endpoint by constructing a predictor object which uses the endpoint and then just using the predictor object to perform inference. What if we wanted to create a web app which accessed our model? The way things are set up currently makes that not possible since in order to access a SageMaker endpoint the app would first have to authenticate with AWS using an IAM role which included access to SageMaker endpoints. However, there is an easier way! We just need to use some additional AWS services.\n\n<img src=\"Web App Diagram.svg\">\n\nThe diagram above gives an overview of how the various services will work together. On the far right is the model which we trained above and which is deployed using SageMaker. On the far left is our web app that collects a user's movie review, sends it off and expects a positive or negative sentiment in return.\n\nIn the middle is where some of the magic happens. We will construct a Lambda function, which you can think of as a straightforward Python function that can be executed whenever a specified event occurs. We will give this function permission to send and recieve data from a SageMaker endpoint.\n\nLastly, the method we will use to execute the Lambda function is a new endpoint that we will create using API Gateway. This endpoint will be a url that listens for data to be sent to it. Once it gets some data it will pass that data on to the Lambda function and then return whatever the Lambda function returns. Essentially it will act as an interface that lets our web app communicate with the Lambda function.\n\n### Setting up a Lambda function\n\nThe first thing we are going to do is set up a Lambda function. This Lambda function will be executed whenever our public API has data sent to it. When it is executed it will receive the data, perform any sort of processing that is required, send the data (the review) to the SageMaker endpoint we've created and then return the result.\n\n#### Part A: Create an IAM Role for the Lambda function\n\nSince we want the Lambda function to call a SageMaker endpoint, we need to make sure that it has permission to do so. To do this, we will construct a role that we can later give the Lambda function.\n\nUsing the AWS Console, navigate to the **IAM** page and click on **Roles**. Then, click on **Create role**. Make sure that the **AWS service** is the type of trusted entity selected and choose **Lambda** as the service that will use this role, then click **Next: Permissions**.\n\nIn the search box type `sagemaker` and select the check box next to the **AmazonSageMakerFullAccess** policy. Then, click on **Next: Review**.\n\nLastly, give this role a name. Make sure you use a name that you will remember later on, for example `LambdaSageMakerRole`. Then, click on **Create role**.\n\n#### Part B: Create a Lambda function\n\nNow it is time to actually create the Lambda function.\n\nUsing the AWS Console, navigate to the AWS Lambda page and click on **Create a function**. When you get to the next page, make sure that **Author from scratch** is selected. Now, name your Lambda function, using a name that you will remember later on, for example `sentiment_analysis_func`. Make sure that the **Python 3.6** runtime is selected and then choose the role that you created in the previous part. Then, click on **Create Function**.\n\nOn the next page you will see some information about the Lambda function you've just created. If you scroll down you should see an editor in which you can write the code that will be executed when your Lambda function is triggered. In our example, we will use the code below. \n\n```python\n# We need to use the low-level library to interact with SageMaker since the SageMaker API\n# is not available natively through Lambda.\nimport boto3\n\ndef lambda_handler(event, context):\n\n # The SageMaker runtime is what allows us to invoke the endpoint that we've created.\n runtime = boto3.Session().client('sagemaker-runtime')\n\n # Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given\n response = runtime.invoke_endpoint(EndpointName = '**ENDPOINT NAME HERE**', # The name of the endpoint we created\n ContentType = 'text/plain', # The data format that is expected\n Body = event['body']) # The actual review\n\n # The response is an HTTP response whose body contains the result of our inference\n result = response['Body'].read().decode('utf-8')\n\n return {\n 'statusCode' : 200,\n 'headers' : { 'Content-Type' : 'text/plain', 'Access-Control-Allow-Origin' : '*' },\n 'body' : result\n }\n```\n\nOnce you have copy and pasted the code above into the Lambda code editor, replace the `**ENDPOINT NAME HERE**` portion with the name of the endpoint that we deployed earlier. You can determine the name of the endpoint using the code cell below.", "_____no_output_____" ] ], [ [ "predictor.endpoint", "_____no_output_____" ] ], [ [ "Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function.\n\n### Setting up API Gateway\n\nNow that our Lambda function is set up, it is time to create a new API using API Gateway that will trigger the Lambda function we have just created.\n\nUsing AWS Console, navigate to **Amazon API Gateway** and then click on **Get started**.\n\nOn the next page, make sure that **New API** is selected and give the new api a name, for example, `sentiment_analysis_api`. Then, click on **Create API**.\n\nNow we have created an API, however it doesn't currently do anything. What we want it to do is to trigger the Lambda function that we created earlier.\n\nSelect the **Actions** dropdown menu and click **Create Method**. A new blank method will be created, select its dropdown menu and select **POST**, then click on the check mark beside it.\n\nFor the integration point, make sure that **Lambda Function** is selected and click on the **Use Lambda Proxy integration**. This option makes sure that the data that is sent to the API is then sent directly to the Lambda function with no processing. It also means that the return value must be a proper response object as it will also not be processed by API Gateway.\n\nType the name of the Lambda function you created earlier into the **Lambda Function** text entry box and then click on **Save**. Click on **OK** in the pop-up box that then appears, giving permission to API Gateway to invoke the Lambda function you created.\n\nThe last step in creating the API Gateway is to select the **Actions** dropdown and click on **Deploy API**. You will need to create a new Deployment stage and name it anything you like, for example `prod`.\n\nYou have now successfully set up a public API to access your SageMaker model. Make sure to copy or write down the URL provided to invoke your newly created public API as this will be needed in the next step. This URL can be found at the top of the page, highlighted in blue next to the text **Invoke URL**.", "_____no_output_____" ], [ "## Step 4: Deploying our web app\n\nNow that we have a publicly available API, we can start using it in a web app. For our purposes, we have provided a simple static html file which can make use of the public api you created earlier.\n\nIn the `website` folder there should be a file called `index.html`. Download the file to your computer and open that file up in a text editor of your choice. There should be a line which contains **\\*\\*REPLACE WITH PUBLIC API URL\\*\\***. Replace this string with the url that you wrote down in the last step and then save the file.\n\nNow, if you open `index.html` on your local computer, your browser will behave as a local web server and you can use the provided site to interact with your SageMaker model.\n\nIf you'd like to go further, you can host this html file anywhere you'd like, for example using github or hosting a static site on Amazon's S3. Once you have done this you can share the link with anyone you'd like and have them play with it too!\n\n> **Important Note** In order for the web app to communicate with the SageMaker endpoint, the endpoint has to actually be deployed and running. This means that you are paying for it. Make sure that the endpoint is running when you want to use the web app but that you shut it down when you don't need it, otherwise you will end up with a surprisingly large AWS bill.\n\n**TODO:** Make sure that you include the edited `index.html` file in your project submission.", "_____no_output_____" ], [ "Now that your web app is working, trying playing around with it and see how well it works.\n\n**Question**: Post a screenshot showing a sample review that you entered into your web app and the predicted sentiment. What was the predicted sentiment of your example review?", "_____no_output_____" ], [ "**Screenshot:**\n\n![image.png](attachment:image.png)\n\n**Answer:**", "_____no_output_____" ], [ "### Delete the endpoint\n\nRemember to always shut down your endpoint if you are no longer using it. You are charged for the length of time that the endpoint is running so if you forget and leave it on you could end up with an unexpectedly large bill.", "_____no_output_____" ] ], [ [ "predictor.delete_endpoint()", "_____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" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
ec4d3c622a476e0eb0c0a2e4daaf4afb83781486
14,287
ipynb
Jupyter Notebook
07-Errors and Exception Handling/04-Unit Testing.ipynb
PseudoCodeNerd/learning-python
1aa02a5c0a5d2f194c20a56a68088012fbfa5da3
[ "MIT" ]
null
null
null
07-Errors and Exception Handling/04-Unit Testing.ipynb
PseudoCodeNerd/learning-python
1aa02a5c0a5d2f194c20a56a68088012fbfa5da3
[ "MIT" ]
null
null
null
07-Errors and Exception Handling/04-Unit Testing.ipynb
PseudoCodeNerd/learning-python
1aa02a5c0a5d2f194c20a56a68088012fbfa5da3
[ "MIT" ]
null
null
null
27.3174
322
0.527123
[ [ [ "# Unit Testing\n\nEqually important as writing good code is writing good tests. Better to find bugs yourself than have them reported to you by end users!\n\nFor this section we'll be working with files outside the notebook. We'll save our code to a .py file, and then save our test script to another .py file. Normally we would code these files using a text editor like Brackets or Atom, or inside an IDE like Spyder or Pycharm. But, since we're here, let's use Jupyter!\n\nRecall that with some IPython magic we can write the contents of a cell to a file using `%%writefile`.<br>\nSomething we haven't seen yet; you can run terminal commands from a jupyter cell using `!`\n\n## Testing tools\n\nThere are dozens of good testing libraries out there. Most are third-party packages that require an install, such as:\n\n* [pylint](https://www.pylint.org/)\n* [pyflakes](https://pypi.python.org/pypi/pyflakes/)\n* [pep8](https://pypi.python.org/pypi/pep8)\n\nThese are simple tools that merely look at your code, and they'll tell you if there are style issues or simple problems like variable names being called before assignment.\n\nA far better way to test your code is to write tests that send sample data to your program, and compare what's returned to a desired outcome.<br>Two such tools are available from the standard library:\n\n* [unittest](https://docs.python.org/3/library/unittest.html)\n* [doctest](https://docs.python.org/3/library/doctest.html)\n\nLet's look at pylint first, then we'll do some heavier lifting with unittest.\n", "_____no_output_____" ], [ "## `pylint`\n\n`pylint` tests for style as well as some very basic program logic.", "_____no_output_____" ], [ "First, if you don't have it already (and you probably do, as it's part of the Anaconda distribution), you should install `pylint`.<br>Once that's done feel free to comment out the cell, you won't need it anymore.", "_____no_output_____" ] ], [ [ "! pip install pylint", "Requirement already satisfied: pylint in c:\\users\\shekh\\anaconda3\\lib\\site-packages (2.2.2)\nRequirement already satisfied: astroid>=2.0.0 in c:\\users\\shekh\\anaconda3\\lib\\site-packages (from pylint) (2.1.0)\nRequirement already satisfied: isort>=4.2.5 in c:\\users\\shekh\\anaconda3\\lib\\site-packages (from pylint) (4.3.4)\nRequirement already satisfied: mccabe in c:\\users\\shekh\\anaconda3\\lib\\site-packages (from pylint) (0.6.1)\nRequirement already satisfied: colorama in c:\\users\\shekh\\anaconda3\\lib\\site-packages (from pylint) (0.4.1)\nRequirement already satisfied: wrapt in c:\\users\\shekh\\anaconda3\\lib\\site-packages (from astroid>=2.0.0->pylint) (1.10.11)\nRequirement already satisfied: lazy-object-proxy in c:\\users\\shekh\\anaconda3\\lib\\site-packages (from astroid>=2.0.0->pylint) (1.3.1)\nRequirement already satisfied: six in c:\\users\\shekh\\anaconda3\\lib\\site-packages (from astroid>=2.0.0->pylint) (1.12.0)\n" ] ], [ [ "Let's save a very simple script:", "_____no_output_____" ] ], [ [ "%%writefile simple1.py\na = 1\nb = 2\nprint(a)\nprint(B)", "Overwriting simple1.py\n" ] ], [ [ "Now let's check it using pylint", "_____no_output_____" ] ], [ [ "! pylint simple1.py", "************* Module simple1\nsimple1.py:1:0: C0111: Missing module docstring (missing-docstring)\nsimple1.py:1:0: C0103: Constant name \"a\" doesn't conform to UPPER_CASE naming style (invalid-name)\nsimple1.py:2:0: C0103: Constant name \"b\" doesn't conform to UPPER_CASE naming style (invalid-name)\nsimple1.py:4:6: E0602: Undefined variable 'B' (undefined-variable)\n\n---------------------------------------------------------------------\n\nYour code has been rated at -10.00/10 (previous run: 8.33/10, -18.33)\n\n\n\n" ] ], [ [ "Pylint first lists some styling issues - it would like to see an extra newline at the end, modules and function definitions should have descriptive docstrings, and single characters are a poor choice for variable names.\n\nMore importantly, however, pylint identified an error in the program - a variable called before assignment. This needs fixing.\n\nNote that pylint scored our program a negative 12.5 out of 10. Let's try to improve that!", "_____no_output_____" ] ], [ [ "%%writefile simple1.py\n\"\"\"\nA very simple script.\n\"\"\"\n\ndef myfunc():\n \"\"\"\n An extremely simple function.\n \"\"\"\n first = 1\n second = 2\n print(first)\n print(second)\n\nmyfunc()", "Overwriting simple1.py\n" ], [ "! pylint simple1.py", "\n----------------------------------------------------------------------\n\nYour code has been rated at 10.00/10 (previous run: -10.00/10, +20.00)\n\n\n\n" ] ], [ [ "Much better! Our score climbed to 8.33 out of 10. Unfortunately, the final newline has to do with how jupyter writes to a file, and there's not much we can do about that here. Still, pylint helped us troubleshoot some of our problems. But what if the problem was more complex?", "_____no_output_____" ] ], [ [ "%%writefile simple2.py\n\"\"\"\nA very simple script.\n\"\"\"\n\ndef myfunc():\n \"\"\"\n An extremely simple function.\n \"\"\"\n first = 1\n second = 2\n print(first)\n print('second')\n\nmyfunc()", "Overwriting simple2.py\n" ], [ "! pylint simple2.py", "************* Module simple2\nsimple2.py:10:4: W0612: Unused variable 'second' (unused-variable)\n\n-----------------------------------\n\nYour code has been rated at 8.33/10\n\n\n\n" ] ], [ [ "pylint tells us there's an unused variable in line 10, but it doesn't know that we might get an unexpected output from line 12! For this we need a more robust set of tools. That's where `unittest` comes in.", "_____no_output_____" ], [ "## `unittest`\n`unittest` lets you write your own test programs. The goal is to send a specific set of data to your program, and analyze the returned results against an expected result. \n\nLet's generate a simple script that capitalizes words in a given string. We'll call it **cap.py**.", "_____no_output_____" ] ], [ [ "%%writefile cap.py\ndef cap_text(text):\n return text.capitalize()", "Overwriting cap.py\n" ] ], [ [ "Now we'll write a test script. We can call it whatever we want, but **test_cap.py** seems an obvious choice.\n\nWhen writing test functions, it's best to go from simple to complex, as each function will be run in order. Here we'll test simple, one-word strings, followed by a test of multiple word strings.", "_____no_output_____" ] ], [ [ "%%writefile test_cap.py\nimport unittest\nimport cap\n\nclass TestCap(unittest.TestCase):\n \n def test_one_word(self):\n text = 'python'\n result = cap.cap_text(text)\n self.assertEqual(result, 'Python')\n \n def test_multiple_words(self):\n text = 'monty python'\n result = cap.cap_text(text)\n self.assertEqual(result, 'Monty Python')\n \nif __name__ == '__main__':\n unittest.main()", "Overwriting test_cap.py\n" ], [ "! python test_cap.py", "..\n----------------------------------------------------------------------\nRan 2 tests in 0.000s\n\nOK\n" ] ], [ [ "What happened? It turns out that the `.capitalize()` method only capitalizes the first letter of the first word in a string. Doing a little research on string methods, we find that `.title()` might give us what we want.", "_____no_output_____" ] ], [ [ "%%writefile cap.py\ndef cap_text(text):\n return text.title() # replace .capitalize() with .title()", "Overwriting cap.py\n" ], [ "! python test_cap.py", "..\n----------------------------------------------------------------------\nRan 2 tests in 0.001s\n\nOK\n" ] ], [ [ "Hey, it passed! But have we tested all cases? Let's add another test to **test_cap.py** to see if it handles words with apostrophes, like *don't*.\n\nIn a text editor this would be easy, but in Jupyter we have to start from scratch.", "_____no_output_____" ] ], [ [ "%%writefile test_cap.py\nimport unittest\nimport cap\n\nclass TestCap(unittest.TestCase):\n \n def test_one_word(self):\n text = 'python'\n result = cap.cap_text(text)\n self.assertEqual(result, 'Python')\n \n def test_multiple_words(self):\n text = 'monty python'\n result = cap.cap_text(text)\n self.assertEqual(result, 'Monty Python')\n \n def test_with_apostrophes(self):\n text = \"monty python's flying circus\"\n result = cap.cap_text(text)\n self.assertEqual(result, \"Monty Python's Flying Circus\")\n \nif __name__ == '__main__':\n unittest.main()", "Overwriting test_cap.py\n" ], [ "! python test_cap.py", "..\n----------------------------------------------------------------------\nRan 2 tests in 0.000s\n\nOK\n" ] ], [ [ "Great! Now we should have a basic understanding of unit testing!", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
ec4d3e287c0509bded1a7136dda6e9f01f5dcdea
29,587
ipynb
Jupyter Notebook
examples/iris.ipynb
songtingstone/gtsne
561e5e97eaf5731d67df21b69a39e5cc51396aa2
[ "Apache-2.0" ]
null
null
null
examples/iris.ipynb
songtingstone/gtsne
561e5e97eaf5731d67df21b69a39e5cc51396aa2
[ "Apache-2.0" ]
null
null
null
examples/iris.ipynb
songtingstone/gtsne
561e5e97eaf5731d67df21b69a39e5cc51396aa2
[ "Apache-2.0" ]
null
null
null
201.272109
27,140
0.927468
[ [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "from sklearn.datasets import load_iris\nfrom matplotlib import pyplot as plt\n\nfrom gtsne import gtsne", "_____no_output_____" ], [ "iris = load_iris()", "_____no_output_____" ], [ "X = iris.data", "_____no_output_____" ], [ "y = iris.target", "_____no_output_____" ], [ "X_2d = gtsne(X)", "_____no_output_____" ], [ "plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
ec4d4a6ce6afb53f43df0a062b4f8c0c9b46c0ff
12,715
ipynb
Jupyter Notebook
examples/02 - CoNLL 2003.ipynb
annabeth-h/spacy_crfsuite
b9f31aac9e727245791197aed4245f03a57a89ba
[ "MIT" ]
12
2020-07-29T17:08:06.000Z
2022-03-28T10:39:39.000Z
examples/02 - CoNLL 2003.ipynb
marzi-heidari/spacy_crfsuite
b9f31aac9e727245791197aed4245f03a57a89ba
[ "MIT" ]
5
2020-07-29T17:08:03.000Z
2022-03-28T07:16:19.000Z
examples/02 - CoNLL 2003.ipynb
marzi-heidari/spacy_crfsuite
b9f31aac9e727245791197aed4245f03a57a89ba
[ "MIT" ]
7
2020-08-06T11:08:30.000Z
2022-01-20T14:25:19.000Z
29.162844
465
0.509162
[ [ [ "! mkdir -p conll03\n! wget -q -O conll03/train.conll https://raw.githubusercontent.com/davidsbatista/NER-datasets/master/CONLL2003/train.txt\n! wget -q -O conll03/valid.conll https://raw.githubusercontent.com/davidsbatista/NER-datasets/master/CONLL2003/valid.txt\n! wget -q -O conll03/test.conll https://raw.githubusercontent.com/davidsbatista/NER-datasets/master/CONLL2003/test.txt", "_____no_output_____" ], [ "! head -n 20 conll03/train.conll", "-DOCSTART- -X- -X- O\r\n\r\nEU NNP B-NP B-ORG\r\nrejects VBZ B-VP O\r\nGerman JJ B-NP B-MISC\r\ncall NN I-NP O\r\nto TO B-VP O\r\nboycott VB I-VP O\r\nBritish JJ B-NP B-MISC\r\nlamb NN I-NP O\r\n. . O O\r\n\r\nPeter NNP B-NP B-PER\r\nBlackburn NNP I-NP I-PER\r\n\r\nBRUSSELS NNP B-NP B-LOC\r\n1996-08-22 CD I-NP O\r\n\r\nThe DT B-NP O\r\nEuropean NNP I-NP B-ORG\r\n" ], [ "from spacy_crfsuite import CRFExtractor\n\ncomponent_config = {\n \"features\": [\n [\n \"low\",\n \"title\",\n \"upper\",\n \"pos\",\n \"pos2\"\n ],\n [\n \"low\",\n \"bias\",\n \"prefix5\",\n \"prefix2\",\n \"suffix5\",\n \"suffix3\",\n \"suffix2\",\n \"upper\",\n \"title\",\n \"digit\",\n \"pos\",\n \"pos2\"\n ],\n [\n \"low\",\n \"title\",\n \"upper\",\n \"pos\",\n \"pos2\"\n ],\n ],\n \"c1\": 0.01,\n \"c2\": 0.22\n}\n\ncrf_extractor = CRFExtractor(component_config=component_config)\ncrf_extractor", "_____no_output_____" ], [ "import spacy\n\nuse_dense_features = crf_extractor.use_dense_features()\n\nif use_dense_features:\n nlp = spacy.load(\"en_core_web_md\")\nelse:\n nlp = spacy.load(\"en_core_web_sm\")", "/Users/talmago/git/spacy_crfsuite/.venv/lib/python3.6/site-packages/spacy/util.py:275: UserWarning: [W031] Model 'en_core_web_sm' (2.2.5) requires spaCy v2.2 and is incompatible with the current spaCy version (2.3.2). This may lead to unexpected results or runtime errors. To resolve this, download a newer compatible model or retrain your custom model with the current spaCy version. For more details and available updates, run: python -m spacy validate\n warnings.warn(warn_msg)\n" ], [ "from tqdm.notebook import tqdm_notebook\n\nfrom spacy_crfsuite import read_file\nfrom spacy_crfsuite.train import gold_example_to_crf_tokens\nfrom spacy_crfsuite.tokenizer import SpacyTokenizer\n\ndef read_examples(file, tokenizer, use_dense_features=False, limit=None):\n examples = []\n it = read_file(file)\n it = it[:limit] if limit else it\n for raw_example in tqdm_notebook(it, desc=file):\n crf_example = gold_example_to_crf_tokens(\n raw_example, \n tokenizer=tokenizer, \n use_dense_features=use_dense_features, \n bilou=False\n )\n examples.append(crf_example)\n return examples\n\n# Spacy tokenizer\ntokenizer = SpacyTokenizer(nlp)\n\n# OPTIONAL: fine-tune hyper-params\n# this is going to take a while, so you might need a coffee break ...\ndev_examples = None\n# dev_examples = read_examples(\"conll03/valid.conll\", tokenizer, use_dense_features=use_dense_features)\n\nif dev_examples:\n rs = crf_extractor.fine_tune(dev_examples, cv=5, n_iter=30, random_state=42)\n print(\"best params:\", rs.best_params_, \", score:\", rs.best_score_)\n crf_extractor.component_config.update(rs.best_params_)", "_____no_output_____" ], [ "train_examples = read_examples(\"conll03/train.conll\", tokenizer=tokenizer, use_dense_features=use_dense_features)\n\ncrf_extractor.train(train_examples, dev_samples=dev_examples)\nprint(crf_extractor.explain())", "_____no_output_____" ], [ "test_examples = read_examples(\"conll03/test.conll\", tokenizer=tokenizer, use_dense_features=use_dense_features)\n\nf1_score, classification_report = crf_extractor.eval(test_examples)\nprint(classification_report)", "_____no_output_____" ], [ "# Example of a spaCy pipeline\nfrom spacy_crfsuite import CRFEntityExtractor\n\n# Add our CRF component to pipeline\nnlp = spacy.load(\"en_core_web_sm\", disable=[\"ner\"])\npipe = CRFEntityExtractor(nlp, crf_extractor=crf_extractor)\nnlp.add_pipe(pipe)\n\n# And use natively ..\ndoc = nlp(\n \"George Walker Bush (born July 6, 1946) is an American politician and businessman \"\n \"who served as the 43rd president of the United States from 2001 to 2009.\")\n\nfor ent in doc.ents:\n print(ent, \"-\", ent.label_)", "George Walker Bush - PER\nAmerican - MISC\nUnited States - LOC\n" ], [ "# Save model to disk ..\nmodel_name = f\"conll03_{nlp._meta['lang']}_{nlp._meta['name']}.bz2\"\ncrf_extractor.to_disk(model_name)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4d4b4a1b023838d369785218f0692ac4f39ae7
3,941
ipynb
Jupyter Notebook
data/imageAugmentationParallel.ipynb
eat-your-broccoli/tensorflow-image-augmentation
e2deb62d4909e5a13b4aea4944ac3a2541f999a8
[ "MIT" ]
null
null
null
data/imageAugmentationParallel.ipynb
eat-your-broccoli/tensorflow-image-augmentation
e2deb62d4909e5a13b4aea4944ac3a2541f999a8
[ "MIT" ]
null
null
null
data/imageAugmentationParallel.ipynb
eat-your-broccoli/tensorflow-image-augmentation
e2deb62d4909e5a13b4aea4944ac3a2541f999a8
[ "MIT" ]
null
null
null
26.993151
98
0.514844
[ [ [ "import tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator\nimport os\nimport scipy\nfrom skimage import io\nimport multiprocessing as mp\nfrom itertools import repeat", "_____no_output_____" ], [ "datagen = ImageDataGenerator(\n rotation_range=20, #rotate between 0 and 20 degree\n width_shift_range=0.1, # shift width\n height_shift_range=0.1,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest', # constant, nearest, reflect\n cval=125,\n brightness_range=[0.7,1.0])\n\n", "_____no_output_____" ], [ "dir = 'downscaledImg/'\naugmentedPath = 'augmentedImg/'\n\n# how many images should be produced per source image\niterations = 5;\n\n# read all classes\nclasses = os.listdir(dir)", "_____no_output_____" ], [ "# process an image\ndef processImage(srcDir, cls, img, targetPath):\n i = 0\n try:\n path = srcDir+cls+'/'+img\n print(path)\n x = io.imread(path)\n x = x.reshape((1, ) + x.shape)\n for batch in datagen.flow(x, batch_size=16,\n save_to_dir=targetPath,\n save_prefix='aug-'+img,\n save_format='png'):\n i+=1\n if i >= iterations: break;\n except BaseException as err:\n print(type(err))\n if(type(err) == KeyboardInterrupt):\n raise Exception(\"stopped process\")\n print(f\"Unexpected {err=}, {type(err)=}\")\n\ndef processImageClass(cls, subThreads):\n print(\"starting with: \"+cls)\n pool = mp.Pool(subThreads)\n targetPath = augmentedPath+cls\n images = os.listdir(dir+cls)\n if not(os.path.exists(targetPath)): os.mkdir(targetPath)\n #for img in images:\n pool.starmap(processImage, zip(repeat(dir), repeat(cls), images, repeat(targetPath)))\n #pool.starmap(processImage, [dir, cls, (images), targetPath])\n #processImage(dir, cls, img, 'hello', targetPath)\n pool.close()\n \n print(\"done with: \"+cls)", "_____no_output_____" ], [ "#define pool for parallel processing\nprocessors = mp.cpu_count()\nif not(os.path.exists(augmentedPath)): os.mkdir(augmentedPath)\nfor cls in classes:\n if(os.path.isdir(dir+cls)):\n processImageClass(cls, processors)\n\nprint('DONE!!!')\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
ec4d50a548ccf276d1546d3620aa75dfc74e2b0e
667,063
ipynb
Jupyter Notebook
models.ipynb
jenliketen/capstone
813472a8f9dad7c2037fc8d864b63a5f711959fa
[ "MIT" ]
null
null
null
models.ipynb
jenliketen/capstone
813472a8f9dad7c2037fc8d864b63a5f711959fa
[ "MIT" ]
null
null
null
models.ipynb
jenliketen/capstone
813472a8f9dad7c2037fc8d864b63a5f711959fa
[ "MIT" ]
null
null
null
140.849451
410,640
0.831122
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom src.exploratory import split, get_correlations\nfrom src.models import *\nfrom scipy import stats", "_____no_output_____" ], [ "import warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "path = \"./data/data_shifted.csv\"\ndata = pd.read_csv(path)\ndata.drop([\"Unnamed: 0\"], axis=1, inplace=True)\ndata # Predictors are from 2007 to 2015; outcome is from 2008 to 2016", "_____no_output_____" ] ], [ [ "Standardizing predictors does wonders for model performance.", "_____no_output_____" ] ], [ [ "X_train, X_test, y_train, y_test = split(data, standardize=True)", "_____no_output_____" ], [ "# X_train, X_test, y_train, y_test = split(data, standardize=False)", "_____no_output_____" ] ], [ [ "### Regression models", "_____no_output_____" ], [ "#### OLS, polynomial degree = 2", "_____no_output_____" ] ], [ [ "ols_model, ols_train_pred, ols_test_pred, ols_mse_train, ols_mse_test, ols_adj_r2_train, ols_adj_r2_test, ols_coefficients = lin_reg(X_train, X_test, y_train, y_test, degree=2)\nprint(\"Training MSE: {}\".format(ols_mse_train))\nprint(\"Test MSE: {}\".format(ols_mse_test))\nprint(\"Training adjusted R\\u00b2: {}\".format(ols_adj_r2_train))\nprint(\"Test adjusted R\\u00b2: {}\".format(ols_adj_r2_test))", "Training MSE: 5.946702359722112\nTest MSE: 6.14720655032082\nTraining adjusted R²: 0.7667320728954188\nTest adjusted R²: 0.7554003132039089\n" ], [ "ols_coefficients", "_____no_output_____" ] ], [ [ "Linear regression with 2nd degree polynomials and interactions fit better than 1st degree (not shown) with minimal overfitting. Here we are squaring all predictors and interacting all pairwise predictors.", "_____no_output_____" ], [ "#### Check linear regression assumptions", "_____no_output_____" ], [ "##### Normality", "_____no_output_____" ] ], [ [ "# See if residuals are normally distributed. H0: normal vs. H1: not normal\nshapiro_test = stats.shapiro(ols_test_pred - y_test)\n#shapiro_test.statistic\nshapiro_test.pvalue", "_____no_output_____" ], [ "(ols_test_pred-y_test).mean()", "_____no_output_____" ] ], [ [ "Residuals are not normal even with polynomial terms; for predictions, linear regression may be ok, but we cannot use the coefficients for inference", "_____no_output_____" ], [ "##### Equal variance", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(20, 50))\nfor i in range(33):\n plt.subplot(11, 3, i+1)\n plt.scatter(X_test.iloc[:, i], ols_test_pred - y_test)\n plt.xlabel(X_test.iloc[:, i].name)\n plt.ylabel(\"Residuals\")", "_____no_output_____" ] ], [ [ "Outcome is quite heteroscedastic. We may want to use sandwich standard errors.", "_____no_output_____" ], [ "#### Huber, polynomial degree = 2", "_____no_output_____" ] ], [ [ "huber_model, huber_train_pred, huber_test_pred, huber_mse_train, huber_mse_test, huber_coefficients = huber_reg(X_train, X_test, y_train, y_test, degree=2)\nprint(\"Training MSE: {}\".format(huber_mse_train))\nprint(\"Test MSE: {}\".format(huber_mse_test))", "Training MSE: 7.16366455825443\nTest MSE: 6.990443607397901\n" ], [ "huber_coefficients", "_____no_output_____" ] ], [ [ "**Correlations**", "_____no_output_____" ] ], [ [ "correlations = get_correlations(X_train)\ncorrelations", "_____no_output_____" ] ], [ [ "Many columns are correlated. We may want to try ridge regression. In practice we will run ridge, lasso, and elastic net.", "_____no_output_____" ], [ "#### Ridge, polynomial degree = 2", "_____no_output_____" ] ], [ [ "ridge_model, ridge_train_pred, ridge_test_pred, ridge_mse_train, ridge_mse_test, ridge_adj_r2_train, ridge_adj_r2_test, ridge_coefficients = ridge_reg(X_train, X_test, y_train, y_test, degree=2)\nprint(\"\\n\")\nprint(\"Training MSE: {}\".format(ridge_mse_train))\nprint(\"Test MSE: {}\".format(ridge_mse_test))\nprint(\"Training adjusted R\\u00b2: {}\".format(ridge_adj_r2_train))\nprint(\"Test adjusted R\\u00b2: {}\".format(ridge_adj_r2_test))", "Lambda: 6.25055192527397\n\n\nTraining MSE: 5.947707498851431\nTest MSE: 6.119597438781176\nTraining adjusted R²: 0.7666926448717908\nTest adjusted R²: 0.7564988902535059\n" ], [ "ridge_coefficients", "_____no_output_____" ] ], [ [ "#### Lasso, polynomial degree = 2", "_____no_output_____" ] ], [ [ "lasso_model, lasso_train_pred, lasso_test_pred, lasso_mse_train, lasso_mse_test, lasso_adj_r2_train, lasso_adj_r2_test, lasso_coefficients, lasso_non_important_coefs = lasso_reg(X_train, X_test, y_train, y_test, degree=2)\nprint(\"\\n\")\nprint(\"Training MSE: {}\".format(lasso_mse_train))\nprint(\"Test MSE: {}\".format(lasso_mse_test))\nprint(\"Training adjusted R\\u00b2: {}\".format(lasso_adj_r2_train))\nprint(\"Test adjusted R\\u00b2: {}\".format(lasso_adj_r2_test))\nprint(\"Number of non-important coefficients: {}\".format(len(lasso_non_important_coefs)))", "Lambda: 0.001\n\n\nTraining MSE: 5.972470056353788\nTest MSE: 6.045340094271558\nTraining adjusted R²: 0.7657212980464466\nTest adjusted R²: 0.759453618236156\nNumber of non-important coefficients: 93\n" ], [ "lasso_coefficients", "_____no_output_____" ], [ "lasso_non_important_coefs", "_____no_output_____" ] ], [ [ "#### Elastic net, polynomial degree = 2", "_____no_output_____" ] ], [ [ "enet_model, enet_train_pred, enet_test_pred, enet_mse_train, enet_mse_test, enet_adj_r2_train, enet_adj_r2_test, enet_coefficients, enet_non_important_coefs = enet_reg(X_train, X_test, y_train, y_test, degree=2)\nprint(\"\\n\")\nprint(\"Training MSE: {}\".format(enet_mse_train))\nprint(\"Test MSE: {}\".format(enet_mse_test))\nprint(\"Training adjusted R\\u00b2: {}\".format(enet_adj_r2_train))\nprint(\"Test adjusted R\\u00b2: {}\".format(enet_adj_r2_test))\nprint(\"Number of non-important coefficients: {}\".format(len(enet_non_important_coefs)))", "Lambda: 0.001\n\n\nTraining MSE: 5.961778000802598\nTest MSE: 6.061797276907464\nTraining adjusted R²: 0.7661407092569027\nTest adjusted R²: 0.7587987806793997\nNumber of non-important coefficients: 49\n" ], [ "enet_coefficients", "_____no_output_____" ], [ "enet_non_important_coefs", "_____no_output_____" ] ], [ [ "### Tree models", "_____no_output_____" ], [ "#### Random forest", "_____no_output_____" ] ], [ [ "rf_model, rf_train_pred, rf_test_pred, rf_mse_train, rf_mse_test, rf_train_score, rf_test_score, oob_score, rf_feature_importances = random_forest(X_train, X_test, y_train, y_test)\nprint(\"\\n\")\nprint(\"Training MSE: {}\".format(rf_mse_train))\nprint(\"Test MSE: {}\".format(rf_mse_test))\nprint(\"Training score: {}\".format(rf_train_score))\nprint(\"Test score: {}\".format(rf_test_score))\nprint(\"OOB score: {}\".format(oob_score))", "Number of trees: 1000\n\n\nTraining MSE: 0.6917329375187263\nTest MSE: 6.56527466080616\nTraining score: 0.9729086209926733\nTest score: 0.7400024151738056\nOOB score: 0.8314601384473717\n" ], [ "rf_feature_importances", "_____no_output_____" ] ], [ [ "#### Gradient boost", "_____no_output_____" ] ], [ [ "gbm_model, gbm_train_pred, gbm_test_pred, gbm_mse_train, gbm_mse_test, gbm_train_score, gbm_test_score, gbm_feature_importances = gbm(X_train, X_test, y_train, y_test)\nprint(\"\\n\")\nprint(\"Training MSE: {}\".format(gbm_mse_train))\nprint(\"Test MSE: {}\".format(gbm_mse_test))\nprint(\"Training score: {}\".format(gbm_train_score))\nprint(\"Test score: {}\".format(gbm_test_score))", "Number of trees: 500\n\n\nTraining MSE: 1.7885255080489371e-26\nTest MSE: 7.696468379442798\nTraining score: 1.0\nTest score: 0.6952049542889058\n" ], [ "gbm_feature_importances", "_____no_output_____" ] ], [ [ "#### Adaboost", "_____no_output_____" ] ], [ [ "ada_model, ada_train_pred, ada_test_pred, ada_mse_train, ada_mse_test, ada_train_score, ada_test_score, ada_feature_importances = adaboost(X_train, X_test, y_train, y_test)\nprint(\"\\n\")\nprint(\"Training MSE: {}\".format(ada_mse_train))\nprint(\"Test MSE: {}\".format(ada_mse_test))\nprint(\"Training score: {}\".format(ada_train_score))\nprint(\"Test score: {}\".format(ada_test_score))", "Number of trees: 1000\n\n\nTraining MSE: 0.014888448193774264\nTest MSE: 5.856976466139195\nTraining score: 0.9994169012765312\nTest score: 0.768052394719909\n" ], [ "ada_feature_importances", "_____no_output_____" ] ], [ [ "### Model performance", "_____no_output_____" ] ], [ [ "model_fit = {\"model_name\": [\"OLS\", \"Huber\", \"Ridge\", \"Lasso\",\" Elastic net\", \"Random forest\", \"Gradient boost\", \"Adaboost\"],\n \"mse_train\": [ols_mse_train, huber_mse_train, ridge_mse_train, lasso_mse_train, enet_mse_train, rf_mse_train, gbm_mse_train, ada_mse_train],\n \"mse_test\": [ols_mse_test, huber_mse_test, ridge_mse_test, lasso_mse_test, enet_mse_test, rf_mse_test, gbm_mse_test, ada_mse_test],\n \"train_score\": [ols_adj_r2_train, \"N/A\", ridge_adj_r2_train, lasso_adj_r2_train, enet_adj_r2_train, rf_train_score, gbm_train_score, ada_train_score],\n \"test_score\": [ols_adj_r2_test, \"N/A\", ridge_adj_r2_test, lasso_adj_r2_test, enet_adj_r2_test, oob_score, gbm_test_score, ada_test_score]}\nmodel_fit = pd.DataFrame.from_dict(model_fit)\nmodel_fit", "_____no_output_____" ] ], [ [ "Everything for linear regresssion is second order with interactions, which uniformly performs better than their first-order counterparts. Worst one is Huber. rf is best. gradient boost is surprisingly worst, probably bc of correlations. regression methods all have similar performance", "_____no_output_____" ], [ "### Final predictions", "_____no_output_____" ], [ "We will use the test set predictions from gradient boost as the final predictions.", "_____no_output_____" ] ], [ [ "X = pd.concat([X_train, X_test], ignore_index=True)\ny = pd.concat([y_train, y_test], ignore_index=True)", "_____no_output_____" ], [ "final_preds = gbm_model.predict(X)\nfinal_preds", "_____no_output_____" ], [ "final_score = gbm_model.score(X, y)\nprint(\"Final model score: {}\".format(final_score))", "Final model score: 0.9244261554526982\n" ] ], [ [ "Overall, gradient boost does a pretty good job. The predictions that are super off tend to have zeross in the actual value.", "_____no_output_____" ] ], [ [ "# Save final model and predictions\n# import pickle\n# filename = \"./final_model.sav\"\n# pickle.dump(gbm_model, open(filename, \"wb\")) \n# To load model, run:\n# loaded_model = pickle.load(open(filename, \"rb\"))\n# np.savetxt(\"final_preds.csv\", final_preds, delimiter=\",\")", "_____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" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
ec4d53baa052acca07926e9fa3adabe3d4baf62f
809,883
ipynb
Jupyter Notebook
retention_20180712/wiki_edit_counts.ipynb
staeiou/wiki-stat-notebooks
ee180faa00ff505d6a4ee04408013107cb1c5ada
[ "MIT" ]
3
2017-01-15T04:30:46.000Z
2021-01-02T03:58:46.000Z
retention/wiki_edit_counts.ipynb
staeiou/wiki-stat-notebooks
ee180faa00ff505d6a4ee04408013107cb1c5ada
[ "MIT" ]
1
2016-07-14T22:40:54.000Z
2016-07-14T22:40:54.000Z
retention_20180712/wiki_edit_counts.ipynb
staeiou/wiki-stat-notebooks
ee180faa00ff505d6a4ee04408013107cb1c5ada
[ "MIT" ]
2
2016-07-14T21:06:42.000Z
2019-02-13T23:39:22.000Z
858.836691
65,482
0.935955
[ [ [ "# Visualizations of editing activity in en.wikipedia.org\n\nBy [Stuart Geiger](http://stuartgeiger.com), Berkeley Institute for Data Science\n\n(C) 2016, Released under [The MIT license](https://opensource.org/licenses/MIT).\n\nThis data is collected and aggregated by Erik Zachte, which is [here](https://stats.wikimedia.org/EN/TablesWikipediaEN.htm) for the English Wikipedia. I have just copied that data from HTML tables into a CSV (which is not done here), then imported it into Pandas dataframes, and plotted it with matplotlib.\n\n## Processing and cleaning data", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import ScalarFormatter\n%matplotlib inline\nmatplotlib.style.use('ggplot')\n", "_____no_output_____" ], [ "# Data by Erik Zachte at https://stats.wikimedia.org/EN/TablesWikipediaEN.htm\ncounts = pd.read_csv(\"edit_counts.tsv\", sep=\"\\t\")\n", "_____no_output_____" ], [ "# Convert dates to datetimes\ncounts.date=pd.to_datetime(counts.date,infer_datetime_format=True)\n", "_____no_output_____" ], [ "# Peek at the dataset\ncounts[0:10]", "_____no_output_____" ] ], [ [ "Some of the columns use 'k' for thousands and 'M' for millions, so we need to convert them.", "_____no_output_____" ] ], [ [ "\ndef units_convert(s):\n \"\"\"\n Convert cells with k and M to times 1,000 and 1,000,000 respectively\n \n I got this solution from \n http://stackoverflow.com/questions/14218728/converting-string-of-numbers-and-letters-to-int-float-in-pandas-dataframe\n \"\"\"\n \n powers = {'k': 1000, 'M': 10 ** 6}\n\n if(s[-1] == 'k' or s[-1] == 'M'):\n try:\n power = s[-1]\n return float(s[:-1]) * powers[power]\n except TypeError:\n return float(s)\n else:\n return float(s)\n \n", "_____no_output_____" ], [ "# Apply this function to the columns that have 'k' or 'M' units, store them as new _float columns\ncounts['edits_float']=counts.edits.apply(units_convert)\ncounts['article_count_float']=counts['article count'].apply(units_convert)", "_____no_output_____" ], [ "# Make sure we've got data types figured out\ncounts.dtypes", "_____no_output_____" ], [ "# Set date column as index\n\ncounts.set_index(['date'])\n\n# Calculate some ratios\n\ncounts['highly_active_to_newcomer_ratio']=counts['>100 edits']/counts['new accts']\ncounts['active_to_newcomer_ratio']=counts['>5 edits']/counts['new accts']\ncounts['highly_active_to_active_ratio']=counts['>100 edits']/(counts['>5 edits']-counts['>100 edits'])\n", "_____no_output_____" ] ], [ [ "## Graphs", "_____no_output_____" ] ], [ [ "matplotlib.style.use(['bmh'])\nfont = {'weight' : 'regular',\n 'size' : 16}\n\nmatplotlib.rc('font', **font)\n\nax1 = counts.plot(x='date',y='>5 edits', figsize=(12,4), \n label=\"Users making >5 edits in a month\", color=\"r\")\n\nax1.set_xlabel(\"Year\")\nax1.set_ylabel(\"Number of users\")\n\nax2 = counts.plot(x='date',y='>100 edits', figsize=(12,4), \n label=\"Users making >100 edits in a month\",color=\"g\")\nax2.set_xlabel(\"Year\")\nax2.set_ylabel(\"Number of editors\")\n\nax3 = counts.plot(x='date',y='new accts', figsize=(12,4), \n label=\"New users making >10 edits in a month\",color=\"b\")\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Number of editors\")\nax3.yaxis.set_major_formatter(ScalarFormatter())", "_____no_output_____" ], [ "ax1 = counts.plot(x='date',y=['>5 edits','>100 edits','new accts'], figsize=(12,4), \n label=\"Users making >5 edits in a month\",color=['r','g','b'],logy=True)\nax1.set_xlim(\"2001-01-01\",\"2005-01-01\")\nax1.set_ylim(0,10000)\nax1.set_xlabel(\"Year\")\nax1.set_ylabel(\"Number of users\")\nax1.yaxis.set_major_formatter(ScalarFormatter())", "_____no_output_____" ], [ "ax1 = counts.plot(x='date',y=['>5 edits','>100 edits','new accts'], figsize=(12,4), \n label=\"Users making >5 edits in a month\",color=['r','g','b'])\n\nax1.set_xlabel(\"Year\")\nax1.set_ylabel(\"Number of users\")\nax1.yaxis.set_major_formatter(ScalarFormatter())", "_____no_output_____" ], [ "ax1 = counts.plot(x='date',y=['>5 edits','>100 edits','new accts'], figsize=(12,4), \n label=\"Users making >5 edits in a month\")\n\nax1.set_xlabel(\"Year\")\nax1.set_ylabel(\"Number of users\")\nax1.yaxis.set_major_formatter(ScalarFormatter())", "_____no_output_____" ], [ "matplotlib.style.use(['bmh'])\nfont = {'weight' : 'regular',\n 'size' : 16}\n\nmatplotlib.rc('font', **font)\n\nax1 = counts.plot(x='date',y='>5 edits', figsize=(12,4), \n label=\"Users making >5 edits in a month\",logy=True)\n\nax1.set_xlabel(\"Year\")\nax1.set_ylabel(\"Number of users\")\nax1.yaxis.set_major_formatter(ScalarFormatter())\nplt.legend(bbox_to_anchor=(.9, .3),\n bbox_transform=plt.gcf().transFigure)\n\nax2 = counts.plot(x='date',y='>100 edits', figsize=(12,4), \n label=\"Users making >100 edits in a month\",color=\"g\", logy=True)\nax2.set_xlabel(\"Year\")\nax2.set_ylabel(\"Number of editors\")\nax2.yaxis.set_major_formatter(ScalarFormatter())\n\nax3 = counts.plot(x='date',y='new accts', figsize=(12,4), \n label=\"New users making >10 edits in a month\",color=\"r\", logy=True)\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Number of editors\")\nax3.yaxis.set_major_formatter(ScalarFormatter())\n", "_____no_output_____" ], [ "ax1 = counts.plot(x='date',y=['>5 edits','>100 edits','new accts'], figsize=(12,4), \n label=\"Users making >5 edits in a month\",logy=True, color=['r','g','b'])\n\nax1.set_xlabel(\"Year\")\nax1.set_ylabel(\"Number of users\")\nax1.yaxis.set_major_formatter(ScalarFormatter())\n", "_____no_output_____" ], [ "ax3 = counts.plot(x='date',y='highly_active_to_active_ratio', figsize=(12,4), \n label=\"Highly active users to active users ratio\",color=\"k\")\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Ratio\")", "_____no_output_____" ], [ "\nax3 = counts.plot(x='date',y='highly_active_to_newcomer_ratio', figsize=(12,4), \n label=\"Highly active users to newcomers ratio\",color=\"k\")\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Ratio\")", "_____no_output_____" ], [ "\nax3 = counts.plot(x='date',y='active_to_newcomer_ratio', figsize=(12,4), \n label=\"Active users to newcomers ratio\",color=\"k\")\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Ratio\")", "_____no_output_____" ], [ "\nax3 = counts.plot(x='date',y='edits_float', figsize=(12,4), \n label=\"Number of edits per month\",color=\"k\")\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Number of editors\")", "_____no_output_____" ], [ "\nax3 = counts.plot(x='date',y='new per day', figsize=(12,4), \n label=\"New articles written per day\",color=\"k\")\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Number of articles\")", "_____no_output_____" ], [ "\nax3 = counts.plot(x='date',y='article_count_float', figsize=(12,4), \n label=\"Number of articles\",color=\"k\")\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Number of articles\")", "_____no_output_____" ], [ "ax3 = counts.plot(x='date',y='article_count_float', figsize=(12,4), \n label=\"Number of articles\",color=\"k\",logy=True)\nax3.set_xlabel(\"Year\")\nax3.set_ylabel(\"Number of articles\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4d5581c52bfc349f1deb20aa1c27e21525b87f
16,844
ipynb
Jupyter Notebook
_notebooks/2020-03-17-data_pipes.ipynb
ineszz/blog
b7128c21c655cd3479f04c525c0ddca36af32051
[ "Apache-2.0" ]
7
2020-02-25T14:51:43.000Z
2021-03-30T13:08:33.000Z
_notebooks/2020-03-17-data_pipes.ipynb
ineszz/blog
b7128c21c655cd3479f04c525c0ddca36af32051
[ "Apache-2.0" ]
9
2020-02-26T07:16:09.000Z
2021-07-31T21:32:33.000Z
_notebooks/2020-03-17-data_pipes.ipynb
ineszz/blog
b7128c21c655cd3479f04c525c0ddca36af32051
[ "Apache-2.0" ]
11
2020-02-27T03:53:13.000Z
2021-11-30T12:21:09.000Z
31.602251
330
0.444847
[ [ [ "# \"Using R-style Data Pipelines in Notebooks\"\n> \"Mutate Pandas data frames simply and elegantly with data pipelines.\"\n- author: jhermann\n- toc: false\n- branch: master\n- badges: true\n- comments: true\n- published: true\n- categories: [python, data-science]\n- image: images/copied_from_nb/img/data-science/data-pipes.png", "_____no_output_____" ], [ "![Cover Image](img/data-science/data-pipes.png)", "_____no_output_____" ], [ "## Overview\nThis post shows how mutating data frames can be written more elegantly (and thus understood more easily) by using *data pipelines*. R users know this concept from the `dplyr` package, and Python offers a similar one named `dfply`.", "_____no_output_____" ], [ "## Setting the Stage\nWe start off with some global definitions…", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd", "_____no_output_____" ] ], [ [ "The sample data (about OS package deployments) is read into the `raw_data` dataframe from a CSV file.", "_____no_output_____" ] ], [ [ "raw_data = pd.read_csv(\"../assets/data/cmdb-packages.csv\", sep=',')\n\nprint('♯ of Records: {}\\n'.format(len(raw_data)))\n\nfor name in raw_data.columns[1:]:\n if not name.startswith('Last '):\n print(name, '=', list(sorted(set(raw_data[name].fillna('')))))\n\nraw_data.head(3).transpose()", "♯ of Records: 146\n\nDistribution = ['Debian 8.11', 'Debian 8.6', 'Debian 8.9', 'jessie']\nArchitecture = ['amd64']\nEnvironment = ['', 'Canary', 'DEV', 'LIVE', 'QA']\nTeam = ['Automation', 'Big Data', 'Email', 'Ops App1', 'Ops Linux', 'Persistence', 'Platform']\nInstalled version = ['41.15-2(amd64)', '42.28-2(amd64)', '42.44-1(amd64)', '45.11-1(amd64)', '48.33-1(amd64)']\n" ], [ "def map_distro(name):\n \"\"\"Helper to create canonical OS names.\"\"\"\n return (name.split('.', 1)[0]\n .replace('Debian 7', 'wheezy')\n .replace('Debian 8', 'jessie')\n .replace('Debian 9', 'stretch')\n .replace('Debian 10', 'buster')\n .replace('squeeze', 'Squeeze [6]')\n .replace('wheezy', 'Wheezy [7]')\n .replace('jessie', 'Jessie [8]')\n .replace('stretch', 'Stretch [9]')\n .replace('buster', 'Buster [10]')\n )", "_____no_output_____" ] ], [ [ "## Data Cleaning With Pandas\n\nThis code cleans up the imported data using the *Pandas* API.\n\nTo get sensible version statistics, we split off the auxiliary information in the version column (anything after `-`), leaving just the *upstream* part of the version string. The environment classifier is also cleaned up a little, and distributions are mapped to a canonical set of names. Some unused columns are dropped.\n\nFinally, a subset of unique version samples is selected.", "_____no_output_____" ] ], [ [ "data = raw_data\ndata = data.assign(Version=data['Installed version'].str.split('-', 1, expand=True)[0])\ndata = data.assign(Environment=data.Environment.fillna('UNDEFINED').str.upper())\ndata = data.assign(Distribution=data.Distribution.apply(map_distro))\ndata = data.drop(columns=['CMDB_Id', 'Last seen', 'Last modified', 'Installed version'])\ndata = data.drop_duplicates(subset='Version', keep='first')\n\ndata.transpose()", "_____no_output_____" ] ], [ [ "## Data Cleaning With Pipelines\n\nThis does the exact same processing as the code above, but is arguably more readable and maintained more easily:\n\n* It has less boilerplate, and makes the use of pipelined processing transparent.\n* Each step clearly states what it does to the data.\n* When steps are copied into other pipelines, the `X` placeholder ensures you use the data of *this* pipeline (the code is more DRY)..", "_____no_output_____" ] ], [ [ "from dfply import *\n\npiped = (raw_data\n >> mutate(Version=X['Installed version'].str.split('-', 1, expand=True)[0])\n >> mutate(Environment=X.Environment.fillna('UNDEFINED').str.upper())\n >> mutate(Distribution=X.Distribution.apply(map_distro))\n >> drop(X.CMDB_Id, X['Last seen'], X['Last modified'], X['Installed version'])\n >> distinct(X.Version)\n)\n\npiped.transpose()", "_____no_output_____" ] ], [ [ "The result is identical to the pure Pandas code, as expected.\n\nTo learn more about `dfply`, read the [dplyr-style Data Manipulation with Pipes in Python](https://towardsdatascience.com/dplyr-style-data-manipulation-with-pipes-in-python-380dcb137000) blog post, which has more examples.", "_____no_output_____" ], [ "## Reference Links\n\n### dfply\n* [dplyr-style Data Manipulation with Pipes in Python – Towards Data Science](https://towardsdatascience.com/dplyr-style-data-manipulation-with-pipes-in-python-380dcb137000)\n* [kieferk/dfply: dplyr-style piping operations for Pandas dataframes](https://github.com/kieferk/dfply)\n\n### Alternatives\n* [has2k1/plydata: A grammar for data manipulation in Python](https://github.com/has2k1/plydata)\n* [shaypal5/pdpipe: Easy pipelines for Pandas dataframes](https://github.com/shaypal5/pdpipe)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec4d664a2b44134150e560d0a2620243262a6a4a
3,824
ipynb
Jupyter Notebook
to_move/jupyter-notebook-integration/app.ipynb
PietroAnsidei/examples
10a6ea1dec9b6e2c3b3746f5022bfd5393e8410c
[ "Apache-2.0" ]
5
2021-07-22T14:20:05.000Z
2022-03-15T02:30:46.000Z
to_move/jupyter-notebook-integration/app.ipynb
PietroAnsidei/examples
10a6ea1dec9b6e2c3b3746f5022bfd5393e8410c
[ "Apache-2.0" ]
1
2021-07-22T14:02:58.000Z
2021-07-22T14:02:58.000Z
to_move/jupyter-notebook-integration/app.ipynb
PietroAnsidei/examples
10a6ea1dec9b6e2c3b3746f5022bfd5393e8410c
[ "Apache-2.0" ]
4
2021-07-25T14:00:36.000Z
2021-11-26T20:36:29.000Z
22.494118
186
0.534257
[ [ [ "# Use Jina inside Jupyter Notebook", "_____no_output_____" ] ], [ [ "!pip install -r requirements.txt", "_____no_output_____" ] ], [ [ "To build a Flow, use `AsyncFlow` instead of `Flow`", "_____no_output_____" ] ], [ [ "from jina import AsyncFlow as Flow", "_____no_output_____" ], [ "Flow().add(name='step1').add(name='step2')", "_____no_output_____" ] ], [ [ "Now let's feed some random data into it and print the output. Notice the `await` below!", "_____no_output_____" ] ], [ [ "def print_blob(req):\n for d in req.docs:\n print(d.text)", "_____no_output_____" ], [ "from jina import Document\n\nwith Flow().add() as f:\n await f.index([Document(content='hello'), Document(content='world')], output_fn=print_blob)", "_____no_output_____" ] ], [ [ "## Build `hello-world` Index in Jupyter Notebook", "_____no_output_____" ], [ "First, let's setup some environment variables for later use:", "_____no_output_____" ] ], [ [ "from pkg_resources import resource_filename\nimport os\nfor k, v in {'RESOURCE_DIR': resource_filename('jina', 'resources'),\n 'SHARDS': 4,\n 'PARALLEL': 4,\n 'REPLICAS': 4,\n 'HW_WORKDIR': 'workdir',\n 'WITH_LOGSERVER': False}.items():\n os.environ[k] = str(v)", "_____no_output_____" ] ], [ [ "`original/index` stores the Fashion-MNIST training data. If you don't have it, [download it from here](https://github.com/zalandoresearch/fashion-mnist/#get-the-data) and unzip it.", "_____no_output_____" ] ], [ [ "from jina.helloworld.helper import load_mnist\n\n# do index\nf = Flow.load_config(resource_filename('jina', '/'.join(('resources', 'helloworld.flow.index.yml'))))\n\nwith f:\n await f.index_ndarray(load_mnist('original/index'), batch_size=1024)", "_____no_output_____" ] ], [ [ "It will take 30s you will see the output log is scrolling and all data has been indexed. Under the current directory, you will find a newly created `workdir` with\n - `chunk_indexer-1`\n - `chunk_indexer-2`\n - `chunk_indexer-3`\n - `chunk_indexer-4`", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec4d6d2aa72d9cdc10d8f50a71bf71412701822a
19,766
ipynb
Jupyter Notebook
Script_for_testing.ipynb
duyduc1110/NPL
ee299f9d6660f46b6413a0071fa89999b739a073
[ "Apache-2.0" ]
null
null
null
Script_for_testing.ipynb
duyduc1110/NPL
ee299f9d6660f46b6413a0071fa89999b739a073
[ "Apache-2.0" ]
null
null
null
Script_for_testing.ipynb
duyduc1110/NPL
ee299f9d6660f46b6413a0071fa89999b739a073
[ "Apache-2.0" ]
null
null
null
66.107023
312
0.640038
[ [ [ "import logging\nfrom gensim.models import word2vec\nprint(word2vec.FAST_VERSION)", "C:\\Users\\MrBonBon\\Miniconda3\\lib\\site-packages\\gensim\\utils.py:1197: UserWarning: detected Windows; aliasing chunkize to chunkize_serial\n warnings.warn(\"detected Windows; aliasing chunkize to chunkize_serial\")\n" ], [ "logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\nsentences = word2vec.LineSentence('text8')\nmodel = word2vec.Word2Vec(sentences, size=300)\nmodel.save('world2vec.model')", "2019-09-11 21:32:13,395 : INFO : collecting all words and their counts\nC:\\Users\\MrBonBon\\Miniconda3\\lib\\site-packages\\smart_open\\smart_open_lib.py:398: UserWarning: This function is deprecated, use smart_open.open instead. See the migration notes for details: https://github.com/RaRe-Technologies/smart_open/blob/master/README.rst#migrating-to-the-new-open-function\n 'See the migration notes for details: %s' % _MIGRATION_NOTES_URL\n2019-09-11 21:32:14,898 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n2019-09-11 21:32:18,216 : INFO : collected 253854 word types from a corpus of 17005207 raw words and 1701 sentences\n2019-09-11 21:32:18,217 : INFO : Loading a fresh vocabulary\n2019-09-11 21:32:18,498 : INFO : min_count=5 retains 71290 unique words (28% of original 253854, drops 182564)\n2019-09-11 21:32:18,498 : INFO : min_count=5 leaves 16718844 word corpus (98% of original 17005207, drops 286363)\n2019-09-11 21:32:18,695 : INFO : deleting the raw counts dictionary of 253854 items\n2019-09-11 21:32:18,741 : INFO : sample=0.001 downsamples 38 most-common words\n2019-09-11 21:32:18,742 : INFO : downsampling leaves estimated 12506280 word corpus (74.8% of prior 16718844)\n2019-09-11 21:32:18,946 : INFO : estimated required memory for 71290 words and 300 dimensions: 206741000 bytes\n2019-09-11 21:32:18,947 : INFO : resetting layer weights\n2019-09-11 21:32:19,772 : INFO : training model with 3 workers on 71290 vocabulary and 300 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n2019-09-11 21:32:21,227 : INFO : EPOCH 1 - PROGRESS: at 0.06% examples, 5332 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:22,230 : INFO : EPOCH 1 - PROGRESS: at 6.47% examples, 326858 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:23,238 : INFO : EPOCH 1 - PROGRESS: at 12.93% examples, 463983 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:24,239 : INFO : EPOCH 1 - PROGRESS: at 19.22% examples, 536000 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:25,239 : INFO : EPOCH 1 - PROGRESS: at 25.46% examples, 581242 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:26,254 : INFO : EPOCH 1 - PROGRESS: at 31.69% examples, 612024 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:27,269 : INFO : EPOCH 1 - PROGRESS: at 38.04% examples, 636142 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:28,284 : INFO : EPOCH 1 - PROGRESS: at 44.39% examples, 653696 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:29,291 : INFO : EPOCH 1 - PROGRESS: at 50.73% examples, 668550 words/s, in_qsize 6, out_qsize 0\n2019-09-11 21:32:30,294 : INFO : EPOCH 1 - PROGRESS: at 56.97% examples, 679168 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:31,299 : INFO : EPOCH 1 - PROGRESS: at 63.32% examples, 689116 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:32,301 : INFO : EPOCH 1 - PROGRESS: at 69.61% examples, 696905 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:33,303 : INFO : EPOCH 1 - PROGRESS: at 75.96% examples, 703475 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:34,311 : INFO : EPOCH 1 - PROGRESS: at 82.25% examples, 708181 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:35,327 : INFO : EPOCH 1 - PROGRESS: at 88.59% examples, 713088 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:36,334 : INFO : EPOCH 1 - PROGRESS: at 94.94% examples, 717437 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:37,343 : INFO : EPOCH 1 - PROGRESS: at 99.82% examples, 710858 words/s, in_qsize 3, out_qsize 0\n2019-09-11 21:32:37,353 : INFO : worker thread finished; awaiting finish of 2 more threads\n2019-09-11 21:32:37,358 : INFO : worker thread finished; awaiting finish of 1 more threads\n2019-09-11 21:32:37,359 : INFO : worker thread finished; awaiting finish of 0 more threads\n2019-09-11 21:32:37,359 : INFO : EPOCH - 1 : training on 17005207 raw words (12508113 effective words) took 17.6s, 711274 effective words/s\n2019-09-11 21:32:38,785 : INFO : EPOCH 2 - PROGRESS: at 0.06% examples, 5441 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:39,788 : INFO : EPOCH 2 - PROGRESS: at 6.17% examples, 316450 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:40,788 : INFO : EPOCH 2 - PROGRESS: at 12.29% examples, 445508 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:41,812 : INFO : EPOCH 2 - PROGRESS: at 18.34% examples, 513134 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:42,820 : INFO : EPOCH 2 - PROGRESS: at 24.40% examples, 557761 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:43,821 : INFO : EPOCH 2 - PROGRESS: at 30.39% examples, 588840 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:44,831 : INFO : EPOCH 2 - PROGRESS: at 36.33% examples, 609877 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:45,832 : INFO : EPOCH 2 - PROGRESS: at 42.33% examples, 626411 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:46,839 : INFO : EPOCH 2 - PROGRESS: at 48.32% examples, 639416 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:47,845 : INFO : EPOCH 2 - PROGRESS: at 54.32% examples, 649950 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:48,849 : INFO : EPOCH 2 - PROGRESS: at 60.38% examples, 659318 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:49,866 : INFO : EPOCH 2 - PROGRESS: at 66.37% examples, 665713 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:50,866 : INFO : EPOCH 2 - PROGRESS: at 72.37% examples, 672195 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:51,879 : INFO : EPOCH 2 - PROGRESS: at 78.48% examples, 676874 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:52,900 : INFO : EPOCH 2 - PROGRESS: at 84.66% examples, 681942 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:53,911 : INFO : EPOCH 2 - PROGRESS: at 90.83% examples, 687022 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:54,919 : INFO : EPOCH 2 - PROGRESS: at 96.88% examples, 690413 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:55,648 : INFO : worker thread finished; awaiting finish of 2 more threads\n2019-09-11 21:32:55,649 : INFO : worker thread finished; awaiting finish of 1 more threads\n2019-09-11 21:32:55,654 : INFO : worker thread finished; awaiting finish of 0 more threads\n2019-09-11 21:32:55,655 : INFO : EPOCH - 2 : training on 17005207 raw words (12507009 effective words) took 18.3s, 683702 effective words/s\n2019-09-11 21:32:57,103 : INFO : EPOCH 3 - PROGRESS: at 0.06% examples, 5342 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:58,113 : INFO : EPOCH 3 - PROGRESS: at 6.23% examples, 315276 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:32:59,114 : INFO : EPOCH 3 - PROGRESS: at 12.29% examples, 441367 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:00,118 : INFO : EPOCH 3 - PROGRESS: at 18.34% examples, 511649 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:01,143 : INFO : EPOCH 3 - PROGRESS: at 24.46% examples, 556203 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:02,149 : INFO : EPOCH 3 - PROGRESS: at 30.45% examples, 586854 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:03,153 : INFO : EPOCH 3 - PROGRESS: at 36.45% examples, 609615 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:04,158 : INFO : EPOCH 3 - PROGRESS: at 42.45% examples, 626016 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:05,161 : INFO : EPOCH 3 - PROGRESS: at 48.44% examples, 639110 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:06,168 : INFO : EPOCH 3 - PROGRESS: at 54.44% examples, 649790 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:07,173 : INFO : EPOCH 3 - PROGRESS: at 60.44% examples, 658476 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:08,174 : INFO : EPOCH 3 - PROGRESS: at 66.43% examples, 665729 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:09,180 : INFO : EPOCH 3 - PROGRESS: at 72.49% examples, 672418 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:10,187 : INFO : EPOCH 3 - PROGRESS: at 78.42% examples, 675863 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:11,187 : INFO : EPOCH 3 - PROGRESS: at 84.42% examples, 680503 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:12,189 : INFO : EPOCH 3 - PROGRESS: at 90.48% examples, 685224 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:13,192 : INFO : EPOCH 3 - PROGRESS: at 96.47% examples, 688433 words/s, in_qsize 5, out_qsize 0\n2019-09-11 21:33:13,977 : INFO : worker thread finished; awaiting finish of 2 more threads\n2019-09-11 21:33:13,983 : INFO : worker thread finished; awaiting finish of 1 more threads\n" ], [ "res = model.most_similar('love', topn = 10)\nfor item in res:\n print(item[0] + ':' + str(item[1]))", "C:\\Users\\MrBonBon\\Miniconda3\\lib\\site-packages\\ipykernel_launcher.py:1: DeprecationWarning: Call to deprecated `most_similar` (Method will be removed in 4.0.0, use self.wv.most_similar() instead).\n \"\"\"Entry point for launching an IPython kernel.\n2019-09-11 21:35:47,058 : INFO : precomputing L2-norms of word weight vectors\n" ], [ "print('%s AND %s ; LIKE %s AND... ' %('King', 'Queen', 'Man'))\nres = model.most_similar(['king','queen'], ['man'], topn = 10)\nfor item in res:\n print(item[0] + ': ' + str(item[1]))", "King AND Queen ; LIKE Man AND... \nelizabeth: 0.5758429765701294\nprince: 0.5752467513084412\nburgundy: 0.5582802295684814\naragon: 0.5577951669692993\nregent: 0.549538254737854\ndukes: 0.5455438494682312\nduke: 0.5453765392303467\nvii: 0.5442549586296082\nkings: 0.5358465909957886\nthrone: 0.531024694442749\n" ], [ "res = model.wv.similarity('king', 'queen')\nprint('CAlculate Cosine Similarity for King and Queen: %s' %res)", "CAlculate Cosine Similarity for King and Queen: 0.6513279346111677\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
ec4d738b0523bedb3fae06d1f03baedfbf9dcba0
12,009
ipynb
Jupyter Notebook
notebooks/Practical_JAX_Tips.ipynb
patel-zeel/probml-notebooks
1ff09bfddb2bd6b3932d81845546770e7e2fce3a
[ "MIT" ]
null
null
null
notebooks/Practical_JAX_Tips.ipynb
patel-zeel/probml-notebooks
1ff09bfddb2bd6b3932d81845546770e7e2fce3a
[ "MIT" ]
1
2022-03-30T20:00:48.000Z
2022-03-30T20:30:42.000Z
notebooks/Practical_JAX_Tips.ipynb
patel-zeel/probml-notebooks
1ff09bfddb2bd6b3932d81845546770e7e2fce3a
[ "MIT" ]
null
null
null
23.547059
206
0.503706
[ [ [ "import jax\nimport jax.numpy as jnp\nfrom IPython.display import display, Latex", "_____no_output_____" ] ], [ [ "## If else condition with `lax`\n\n$$\nf(\\mathbf{x}) = \\sum_{x \\in \\mathbf{x}} \\begin{cases}\n x^2,& \\text{if } x \\gt 5\\\\\n x^3, & \\text{otherwise}\n\\end{cases}\n$$", "_____no_output_____" ] ], [ [ "x = [jnp.array(10.0), jnp.array(2.0)]\n\n\[email protected]\[email protected]_and_grad\ndef f(x):\n bool_val = jax.tree_map(lambda val: val > 5.0, x)\n ans = jax.tree_map(\n lambda val, bool: jax.lax.cond(bool, lambda: val**2, lambda: val**3),\n x,\n bool_val,\n )\n return jax.tree_util.tree_reduce(lambda a, b: a + b, ans)\n\n\nvalue, grad = f(x)\n\ndisplay(Latex(f\"$f(\\mathbf{{x}}) = {value}$\"))\nfor idx in range(len(x)):\n display(Latex(f\"$\\\\frac{{df}}{{dx_{idx}}} = {grad[idx]}$\"))", "_____no_output_____" ] ], [ [ "## Pair-wise distance with `vmap`", "_____no_output_____" ] ], [ [ "# create vour pairwise function\ndef distance(a, b):\n return jnp.linalg.norm(a - b)\n\n\n# map based combinator to operate on all pairs\ndef all_pairs(f):\n f = jax.vmap(f, in_axes=(None, 0))\n f = jax.vmap(f, in_axes=(0, None))\n return f\n\n\n# transform to operate over sets\ndistances = all_pairs(distance)\n\n# Example\nx = jnp.array([1.0, 2.0, 3.0])\ny = jnp.array([3.0, 4.0, 5.0])\ndistances(x, y)", "_____no_output_____" ] ], [ [ "## Compute Hessian with `jax`\n\nLet us consider Linear regression loss function\n\n\\begin{align}\n\\mathcal{L}(\\boldsymbol{\\theta}) &= (\\boldsymbol{y} - X\\boldsymbol{\\theta})^T(\\boldsymbol{y} - X\\boldsymbol{\\theta})\\\\\n\\frac{d\\mathcal{L}}{d\\boldsymbol{\\theta}} &= -2X^T\\boldsymbol{y} + 2X^TX\\boldsymbol{\\theta}\\\\\nH_{\\mathcal{L}}(\\boldsymbol{\\theta}) &= 2X^TX\n\\end{align}", "_____no_output_____" ] ], [ [ "def loss_function_per_point(theta, x, y):\n y_pred = x.T @ theta\n return jnp.square(y_pred - y)\n\n\ndef loss_function(theta, x, y):\n loss_per_point = jax.vmap(loss_function_per_point, in_axes=(None, 0, 0))(\n theta, x, y\n )\n return jnp.sum(loss_per_point)\n\n\ndef gt_loss(theta, x, y):\n return jnp.sum(jnp.square(x @ theta - y))\n\n\ndef gt_grad(theta, x, y):\n return 2 * (x.T @ x @ theta - x.T @ y)\n\n\ndef gt_hess(theta, x, y):\n return 2 * x.T @ x", "_____no_output_____" ] ], [ [ "### Simulate dataset ", "_____no_output_____" ] ], [ [ "key = jax.random.PRNGKey(0)\nkey, subkey1, subkey2 = jax.random.split(key, num=3)\nN = 100\nD = 11\nx = jax.random.uniform(key, shape=(N, D))\ny = jax.random.uniform(subkey1, shape=(N,))\ntheta = jax.random.uniform(subkey2, shape=(D,))", "_____no_output_____" ] ], [ [ "### Verify loss and gradient values", "_____no_output_____" ] ], [ [ "loss_and_grad_function = jax.value_and_grad(loss_function)\n\nloss_val, grad = loss_and_grad_function(theta, x, y)\n\nassert jnp.allclose(loss_val, gt_loss(theta, x, y))\nassert jnp.allclose(grad, gt_grad(theta, x, y))", "_____no_output_____" ] ], [ [ "### Verify hessian matrix", "_____no_output_____" ], [ "#### Way-1 ", "_____no_output_____" ] ], [ [ "hess = jax.hessian(loss_function)(theta, x, y)\n\nassert jnp.allclose(hess, gt_hess(theta, x, y))", "_____no_output_____" ] ], [ [ "#### Way-2", "_____no_output_____" ] ], [ [ "hess = jax.jacfwd(jax.jacrev(loss_function))(theta, x, y)\n\nassert jnp.allclose(hess, gt_hess(theta, x, y))", "_____no_output_____" ] ], [ [ "## `tree_map` in JAX", "_____no_output_____" ], [ "The only requirement for `tree_map` to work is, output should have the same structure as the first argument (as explained [here](https://github.com/deepmind/distrax/issues/147)). For example:", "_____no_output_____" ] ], [ [ "import jax\nimport jax.numpy as jnp\ntry:\n import distrax\nexcept:\n %pip install -qqq distrax\n import distrax\n\ndists = {\"Normal\": distrax.Normal(3.0, 4.0), \"Gamma\": distrax.Gamma(3.0, 4.0)}\nsamples = {\"Normal\": jnp.array(2.0), \"Gamma\": jnp.array(3.0)}\ntry:\n log_probs = jax.tree_map(lambda dist, sample: dist.log_prob(sample), dists, samples)\nexcept Exception as e:\n print(e)", "Custom node type mismatch: expected type: <class 'distrax._src.distributions.normal.Normal'>, value: DeviceArray(2., dtype=float32, weak_type=True).\n" ] ], [ [ "The problem here is that `dists` do not have same structure as `log_probs` (`log_probs` structure matches with `samples`). So, we should keep `samples` as the first argument: ", "_____no_output_____" ] ], [ [ "log_probs = jax.tree_map(lambda sample, dist: dist.log_prob(sample), samples, dists)\nlog_probs", "_____no_output_____" ] ], [ [ "## Use of `lax.scan` to accelerate a training loop", "_____no_output_____" ], [ "Here we create a dummy training loop and check the performance of `lax.scan`. The example also shows how to convert a training loop to `lax.scan` version of it.", "_____no_output_____" ] ], [ [ "value_and_grad_fun = jax.jit(jax.value_and_grad(lambda x: jnp.sum(x**2)))\n\n\ndef training_loop(n_iters, params):\n values = []\n for i in range(n_iters):\n value, grad = value_and_grad_fun(params)\n params = params - learning_rate * grad\n values.append(value)\n return value\n\n\[email protected]\ndef one_step(params, xs):\n value, grad = value_and_grad_fun(params)\n params = params - learning_rate * grad\n return params, value", "_____no_output_____" ], [ "key = jax.random.PRNGKey(0)\nN = 1000\nn_iters = 10000\nlearning_rate = 0.01\n\nparams = jax.random.uniform(key, (N,))", "_____no_output_____" ], [ "training_loop(1, params) # warn up\n%timeit -n 1 -r 1 training_loop(n_iters, params)", "1.26 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)\n" ], [ "%timeit -n 1 -r 1 jax.lax.scan(one_step, params, xs=None, length=n_iters)", "221 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)\n" ] ], [ [ "Note that `xs` array can be passed in case we want to scan over it. An example of it can be found in this [blackjax documentation](https://blackjax-devs.github.io/blackjax/examples/Introduction.html).", "_____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", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
ec4d7cb900d16751cd60eecc796db089dcdfbf54
406,792
ipynb
Jupyter Notebook
demo.ipynb
canerozer/Mask_RCNN
6d16c47ff80d27eff927a17c76278fa78840666f
[ "MIT" ]
1
2018-04-25T19:33:01.000Z
2018-04-25T19:33:01.000Z
demo.ipynb
canerozer/Mask_RCNN
6d16c47ff80d27eff927a17c76278fa78840666f
[ "MIT" ]
null
null
null
demo.ipynb
canerozer/Mask_RCNN
6d16c47ff80d27eff927a17c76278fa78840666f
[ "MIT" ]
null
null
null
1,232.70303
395,032
0.955267
[ [ [ "# Mask R-CNN Demo\n\nA quick intro to using the pre-trained model to detect and segment objects.", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport random\nimport math\nimport numpy as np\nimport skimage.io\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport coco\nimport utils\nimport model as modellib\nimport visualize\n\n%matplotlib inline \n\n# Root directory of the project\nROOT_DIR = os.getcwd()\n\n# Directory to save logs and trained model\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n# Local path to trained weights file\nCOCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n# Download COCO trained weights from Releases if needed\nif not os.path.exists(COCO_MODEL_PATH):\n utils.download_trained_weights(COCO_MODEL_PATH)\n\n# Directory of images to run detection on\nIMAGE_DIR = os.path.join(ROOT_DIR, \"images\")", "\n\n" ] ], [ [ "## Configurations\n\nWe'll be using a model trained on the MS-COCO dataset. The configurations of this model are in the ```CocoConfig``` class in ```coco.py```.\n\nFor inferencing, modify the configurations a bit to fit the task. To do so, sub-class the ```CocoConfig``` class and override the attributes you need to change.", "_____no_output_____" ] ], [ [ "class InferenceConfig(coco.CocoConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n NUM_CLASSES = 81 + 1\n\nconfig = InferenceConfig()\nconfig.display()", "\nConfigurations:\nBACKBONE resnet101\nBACKBONE_STRIDES [4, 8, 16, 32, 64]\nBATCH_SIZE 1\nBBOX_STD_DEV [0.1 0.1 0.2 0.2]\nDETECTION_MAX_INSTANCES 100\nDETECTION_MIN_CONFIDENCE 0.7\nDETECTION_NMS_THRESHOLD 0.3\nGPU_COUNT 1\nGRADIENT_CLIP_NORM 5.0\nIMAGES_PER_GPU 1\nIMAGE_MAX_DIM 1024\nIMAGE_META_SIZE 94\nIMAGE_MIN_DIM 800\nIMAGE_MIN_SCALE 0\nIMAGE_RESIZE_MODE square\nIMAGE_SHAPE [1024 1024 3]\nLEARNING_MOMENTUM 0.9\nLEARNING_RATE 0.001\nLOSS_WEIGHTS {'mrcnn_class_loss': 1.0, 'mrcnn_bbox_loss': 1.0, 'rpn_class_loss': 1.0, 'rpn_bbox_loss': 1.0, 'mrcnn_mask_loss': 1.0}\nMASK_POOL_SIZE 14\nMASK_SHAPE [28, 28]\nMAX_GT_INSTANCES 100\nMEAN_PIXEL [123.7 116.8 103.9]\nMINI_MASK_SHAPE (56, 56)\nNAME coco\nNUM_CLASSES 82\nPOOL_SIZE 7\nPOST_NMS_ROIS_INFERENCE 1000\nPOST_NMS_ROIS_TRAINING 2000\nROI_POSITIVE_RATIO 0.33\nRPN_ANCHOR_RATIOS [0.5, 1, 2]\nRPN_ANCHOR_SCALES (32, 64, 128, 256, 512)\nRPN_ANCHOR_STRIDE 1\nRPN_BBOX_STD_DEV [0.1 0.1 0.2 0.2]\nRPN_NMS_THRESHOLD 0.7\nRPN_TRAIN_ANCHORS_PER_IMAGE 256\nSTEPS_PER_EPOCH 1000\nTRAIN_BN False\nTRAIN_ROIS_PER_IMAGE 200\nUSE_MINI_MASK True\nUSE_RPN_ROIS True\nVALIDATION_STEPS 50\nWEIGHT_DECAY 0.0001\n" ] ], [ [ "## Create Model and Load Trained Weights", "_____no_output_____" ] ], [ [ "# Create model object in inference mode.\nmodel = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n\n# Load weights trained on MS-COCO\nmodel.load_weights(COCO_MODEL_PATH, by_name=True)", "WARNING:tensorflow:From /usr/local/lib/python3.5/dist-packages/keras/backend/tensorflow_backend.py:1213: calling reduce_max (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.\nInstructions for updating:\nkeep_dims is deprecated, use keepdims instead\nWARNING:tensorflow:From /usr/local/lib/python3.5/dist-packages/keras/backend/tensorflow_backend.py:1247: calling reduce_sum (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.\nInstructions for updating:\nkeep_dims is deprecated, use keepdims instead\n" ] ], [ [ "## Class Names\n\nThe model classifies objects and returns class IDs, which are integer value that identify each class. Some datasets assign integer values to their classes and some don't. For example, in the MS-COCO dataset, the 'person' class is 1 and 'teddy bear' is 88. The IDs are often sequential, but not always. The COCO dataset, for example, has classes associated with class IDs 70 and 72, but not 71.\n\nTo improve consistency, and to support training on data from multiple sources at the same time, our ```Dataset``` class assigns it's own sequential integer IDs to each class. For example, if you load the COCO dataset using our ```Dataset``` class, the 'person' class would get class ID = 1 (just like COCO) and the 'teddy bear' class is 78 (different from COCO). Keep that in mind when mapping class IDs to class names.\n\nTo get the list of class names, you'd load the dataset and then use the ```class_names``` property like this.\n```\n# Load COCO dataset\ndataset = coco.CocoDataset()\ndataset.load_coco(COCO_DIR, \"train\")\ndataset.prepare()\n\n# Print class names\nprint(dataset.class_names)\n```\n\nWe don't want to require you to download the COCO dataset just to run this demo, so we're including the list of class names below. The index of the class name in the list represent its ID (first class is 0, second is 1, third is 2, ...etc.)", "_____no_output_____" ] ], [ [ "# COCO Class names\n# Index of the class in the list is its ID. For example, to get ID of\n# the teddy bear class, use: class_names.index('teddy bear')\nclass_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n 'bus', 'train', 'truck', 'boat', 'traffic light',\n 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n 'teddy bear', 'hair drier', 'toothbrush', 'face']", "_____no_output_____" ] ], [ [ "## Run Object Detection", "_____no_output_____" ] ], [ [ "# Load a random image from the images folder\nfile_names = next(os.walk(IMAGE_DIR))[2]\nimage = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))\n\n# Run detection\nresults = model.detect([image], verbose=1)\n\n# Visualize results\nr = results[0]\nvisualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], \n class_names, r['scores'])", "Processing 1 images\nimage shape: (500, 348, 3) min: 0.00000 max: 255.00000 uint8\nmolded_images shape: (1, 1024, 1024, 3) min: -123.70000 max: 151.10000 float64\nimage_metas shape: (1, 94) min: 0.00000 max: 1024.00000 float64\nanchors shape: (1, 261888, 4) min: -0.35390 max: 1.29134 float32\n" ], [ "print(r['rois'])\nprint(r['rois'].shape)", "[[ 82 141 128 194]]\n(1, 4)\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
ec4d7e7f15484033feb85d9719e1a15aec7324d9
243,900
ipynb
Jupyter Notebook
Tutorials/04-tutorial-25.06.2020/notebooks/04-tutorial-task-4-solution.ipynb
pitmonticone/EnergySystemModelling
4179cea3b55b295cf6de971b6444bb3d8c957d9f
[ "CC-BY-4.0" ]
18
2020-06-26T11:42:37.000Z
2022-03-30T20:16:55.000Z
Tutorials/04-tutorial-25.06.2020/notebooks/04-tutorial-task-4-solution.ipynb
hmasrur/EnergySystemModelling
4179cea3b55b295cf6de971b6444bb3d8c957d9f
[ "CC-BY-4.0" ]
null
null
null
Tutorials/04-tutorial-25.06.2020/notebooks/04-tutorial-task-4-solution.ipynb
hmasrur/EnergySystemModelling
4179cea3b55b295cf6de971b6444bb3d8c957d9f
[ "CC-BY-4.0" ]
3
2020-07-23T08:01:43.000Z
2021-04-25T07:16:29.000Z
147.639225
66,020
0.858331
[ [ [ "# Energy System Modelling - Tutorial V.3\n\n**Generator dispatch with SciGRID**\n\n[SciGRID](https://www.scigrid.de/pages/general-information.html) is a project that provides an open source reference model of the European transmission networks. In this tutorial, other than previous simple examples, you will examine the economic dispatch of generators all over Germany and its effect on the power system. The data files for this example and a populated Jupyter notebook are provided in `./data`.\n\nThe dataset comprises time series for loads and the availability of renewable generation at an hourly resolution for the year 2011. Feel free to choose a day to your liking; we will later discuss your different outcomes in groups. A few days might be of particular interest:\n* `2011-01-31` was the least windy day of 2011\n* `2011-02-05` was a stormy day with lots of wind energy production,\n* `2011-07-12` the weather 7 years ago was a very sunny day, and\n* `2011-09-06` was a windy *and* sunny autumn day.", "_____no_output_____" ], [ "***\n## Data sources\n\n* The **grid** is based on [SciGRID](http://scigrid.de/) Version 0.2 which is based on [OpenStreetMap](http://www.openstreetmap.org/).\n\n* The **load size and location** is based on Landkreise (NUTS 3), GDP and population.\n\n* The **load time series** is from ENTSO-E hourly data, scaled up uniformly by factor 1.12 (a simplification of the methodology in Schumacher, Hirth (2015)).\n\n* **Conventional power plant capacities and locations** are taken from the BNetzA list.\n\n* **Wind and solar capacities and locations** are retrieved from [EEG Stammdaten](http://www.energymap.info/download.html), which represents capacities at the end of 2014. Units without PLZ are removed.\n\n* **Wind and solar time series** are derived from REatlas, Andresen et al, \"Validation of Danish wind time series from a new global renewable energy atlas for energy system analysis,\" Energy 93 (2015) 1074 - 1088.\n\n* All times in the dataset are UTC.\n\n* Where SciGRID nodes have been split into 220kV and 380kV substations, all load and generation is attached to the 220kV substation.", "_____no_output_____" ], [ "## Disclaimer\n\nThere are several known problems and inaccuracy that limit the suitability of this example for research purposes. These include:\n\n* Rough approximations have been made for missing grid data, e.g. 220kV-380kV transformers and connections between close sub-stations missing from OSM.\n\n* There appears to be some unexpected congestion in parts of the network, which may mean for example that the load attachment method (by Voronoi cell overlap with Landkreise) isn't working, particularly in regions with a high density of substations.\n\n* Attaching power plants to the nearest high voltage substation may not reflect reality.\n\n* There is no proper n-1 security in the calculations - this can either be simulated with a blanket e.g. 70% reduction in thermal limits (as done here) or a proper [security constrained OPF](http://www.pypsa.org/examples/scigrid-sclopf.ipynb).\n\n* The borders and neighbouring countries are not represented.\n\n* Hydroelectric power stations are not modelled accurately.\n\n* The marginal costs are illustrative, not accurate.\n\n* The ENTSO-E total load for Germany may not be scaled correctly; it is scaled up uniformly by factor 1.12 (a simplification of the methodology in Schumacher, Hirth (2015), which suggests monthly factors).\n\n* Biomass from the EEG Stammdaten are not read in at the moment.\n\n* Power plant start up costs, ramping limits/costs, minimum loading rates are not considered.", "_____no_output_____" ], [ "***\n## Imports", "_____no_output_____" ] ], [ [ "#make the code as Python 3 compatible as possible\n#from __future__ import print_function, division, absolute_import\nimport pypsa\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nplt.rcParams['figure.dpi']= 400\nplt.style.use('bmh')\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Parameters", "_____no_output_____" ], [ "Some general settings:", "_____no_output_____" ] ], [ [ "solver_name = \"glpk\"\ncontingency_factor = 0.7\ngroup_size = 4\nimport_name = \"data\"", "_____no_output_____" ] ], [ [ "Specify the day you wish to look at here (any day in 2011):", "_____no_output_____" ] ], [ [ "day = \"2011-07-11\"", "_____no_output_____" ] ], [ [ "Some settings for plotting:", "_____no_output_____" ] ], [ [ "timesteps = np.arange(0,24,4)\n\nn_graphs = len(timesteps)\nn_cols = 3\n\nif n_graphs % n_cols == 0:\n n_rows = n_graphs // n_cols\nelse:\n n_rows = n_graphs // n_cols + 1\n \nsize = 6 # inches", "_____no_output_____" ] ], [ [ "## Read Data", "_____no_output_____" ] ], [ [ "network = pypsa.Network(import_name=import_name)", "WARNING:pypsa.io:\nImporting PyPSA from older version of PyPSA than current version 0.17.0.\nPlease read the release notes at https://pypsa.org/doc/release_notes.html\ncarefully to prepare your network for import.\n\nINFO:pypsa.io:Imported network data has buses, generators, lines, loads, storage_units, transformers\n" ] ], [ [ "There are some infeasibilities without allowing extension.", "_____no_output_____" ] ], [ [ "network.lines[\"s_nom_original\"] = network.lines.s_nom\n\n# extendable, but no reduction of line capacities\nnetwork.lines.s_nom_extendable = True\nnetwork.lines.s_nom_min = network.lines.s_nom\n\nnetwork.lines.capital_cost = 9999999 # EUR/MVA/km - prohibitively high penalty", "_____no_output_____" ] ], [ [ "Set network snapshots to chosen day.", "_____no_output_____" ] ], [ [ "network.set_snapshots(pd.date_range(start='{} 00:00:00'.format(day), end='{} 23:00:00'.format(day), freq='H'))", "_____no_output_____" ] ], [ [ "***\n## (a) Describe the network as well as its regional and temporal characteristics.", "_____no_output_____" ], [ "### (a)-(i) | Plot the aggregated load curve.", "_____no_output_____" ] ], [ [ "# TASK\nnetwork.loads_t.p_set.sum(axis=1).plot()", "INFO:numexpr.utils:NumExpr defaulting to 8 threads.\n" ] ], [ [ "### (a)-(ii) | Plot the total generation capacities grouped by generation technology. Why is the share of capacity for renewables higher than the share of electricity produced?", "_____no_output_____" ] ], [ [ "network.generators.head()", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize=(16,6))\n\n# TASK\ngroups = network.generators.groupby(\"carrier\").p_nom.sum()\nplt.bar(groups.index,groups)", "_____no_output_____" ] ], [ [ "Renewable generators have lower [capacity factors / full load hours](https://en.wikipedia.org/wiki/Capacity_factor).", "_____no_output_____" ], [ "### (a)-(iii) | Plot the regional distribution of the loads for different snapshots. What are the major load centres?\n> **Hint:** Use the pandas function `groupby`.", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols,\n figsize=(size*n_cols,size*n_rows),\n subplot_kw={\"projection\":ccrs.PlateCarree()})\n\nfor i, timestep in enumerate(timesteps):\n i_row = i // n_cols\n i_col = i % n_cols\n \n ax = axes[i_row,i_col]\n \n # TASK\n load_distribution = network.loads_t.p_set.loc[network.snapshots[timestep]].groupby(network.loads.bus).sum()\n \n network.plot(bus_sizes=0.2*load_distribution,\n ax=ax,title=\"Load distribution\",\n bus_colors='navy',\n line_colors='firebrick',\n color_geomap=True)\n \n ax.set_title(timestep)", "_____no_output_____" ] ], [ [ "### (a)-(iv) | Plot the regional distribution of generation technologies. Comment on what you see.\n\n> **Hint:** Use the pandas functions `groupby` and `reindex`.", "_____no_output_____" ] ], [ [ "techs = [\"Brown Coal\",\"Hard Coal\",\"Oil\",\"Gas\",\n \"Wind Offshore\",\"Wind Onshore\",\"Solar\",\"Waste\",\n \"Nuclear\",\"Storage Hydro\",\"Run of River\", \"Geothermal\"]\n\nwidth_factor = 4\nheight_factor = 4\n\n\nn_graphs_g = len(techs)\n\nn_cols_g = 3\n\nif n_graphs_g % n_cols_g == 0:\n n_rows_g = n_graphs_g // n_cols_g\nelse:\n n_rows_g = n_graphs_g // n_cols_g + 1\n \nfig, axes = plt.subplots(nrows=n_rows_g, ncols=n_cols_g,\n figsize=(width_factor*n_cols_g,height_factor*n_rows_g),\n subplot_kw={\"projection\":ccrs.PlateCarree()})\n\n\nfor i,tech in enumerate(techs):\n i_row = i // n_cols_g\n i_col = i % n_cols_g\n \n ax = axes[i_row,i_col]\n \n # TASK\n gens = network.generators[network.generators.carrier == tech]\n gen_distribution = gens.groupby(\"bus\").p_nom.sum().reindex(network.buses.index, fill_value=0.)\n \n network.plot(ax=ax,\n bus_sizes=0.2*gen_distribution,\n bus_colors='navy',\n line_colors='firebrick',\n color_geomap=True)\n \n ax.set_title(tech)", "_____no_output_____" ] ], [ [ "***\n## (b) Run a linear optimal power flow to obtain the economic dispatch and analyse the results.", "_____no_output_____" ], [ "### (b)-(i) | To approximate n-1 security and allow room for reactive power flows, set the maximum line loading of any line in the network to 70 % of their thermal rating.", "_____no_output_____" ] ], [ [ "# TASK\nnetwork.lines.s_nom = contingency_factor*network.lines.s_nom", "_____no_output_____" ], [ "# set the initial state of charge to zero\nnetwork.storage_units.state_of_charge_initial = 0.\n\nfor i in range(int(24/group_size)):\n \n \n if i>0:\n # set the initial state of charge based on previous round\n network.storage_units.state_of_charge_initial = network.storage_units_t.state_of_charge.loc[network.snapshots[group_size*i-1]]\n \n # solve linear optimal power flow\n network.lopf(network.snapshots[group_size*i:group_size*i+group_size],\n solver_name=solver_name)\n \n # update line capacities\n network.lines.s_nom = network.lines.s_nom_opt", "INFO:pypsa.opf:Performed preliminary steps\nINFO:pypsa.opf:Building pyomo model using `kirchhoff` formulation\nINFO:pypsa.opf:Solving model using glpk\nINFO:pypsa.opf:Optimization successful\n" ] ], [ [ "### (b)-(ii) | Plot the hourly dispatch grouped by carrier for the chosen day. Comment on what you see.", "_____no_output_____" ] ], [ [ "# TASK\np_by_carrier = network.generators_t.p.groupby(network.generators.carrier, axis=1).sum()\n#reorder\ncols = ['Nuclear', 'Run of River', 'Brown Coal', 'Hard Coal', 'Gas',\n 'Storage Hydro', 'Waste', 'Wind Offshore', 'Wind Onshore', 'Solar']\np_by_carrier = p_by_carrier[cols]\np_by_carrier_gw = p_by_carrier / 1e3 # convert MW to GW\n\ncolors = {\"Brown Coal\" : \"sienna\",\n \"Hard Coal\" : \"dimgrey\",\n \"Nuclear\" : \"deeppink\",\n \"Run of River\" : \"lightseagreen\",\n \"Wind Onshore\" : \"navy\",\n \"Solar\" : \"gold\",\n \"Wind Offshore\" : \"royalblue\",\n \"Gas\" : \"darkorange\",\n \"Waste\" : \"forestgreen\",\n \"Storage Hydro\" : \"darkmagenta\"\n }\n\nfig, ax = plt.subplots(figsize=(16,8))\n\np_by_carrier_gw.plot(\n kind=\"area\",\n ax=ax,\n linewidth=0,\n color=[colors[col] for col in p_by_carrier.columns]\n)\n\nax.legend(ncol=5, loc=\"upper left\")\n\nax.set_ylabel(\"GW\")\n\nax.set_ylim(0,100);", "_____no_output_____" ] ], [ [ "### (b)-(iii) | Plot the aggregate dispatch of the pumped hydro storage units and the state of charge throughout the day and describe how they are used throughout the day. ", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(figsize=(12,6))\n\n# TASK\np_storage = network.storage_units_t.p.sum(axis=1)\nstate_of_charge = network.storage_units_t.state_of_charge.sum(axis=1)\n\np_storage.plot(label=\"Pumped hydro dispatch\", ax=ax)\nstate_of_charge.plot(label=\"State of charge\", ax=ax)\n\nax.legend()\nax.set_ylabel(\"MWh\")", "_____no_output_____" ] ], [ [ "### (b)-(iv) | Show the line loadings for different snapshots on the network. Can you identify a regional concentration of highly loaded branches?", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols,\n figsize=(size*n_cols,size*n_rows),\n subplot_kw={\"projection\":ccrs.PlateCarree()})\n\nfor i,timestep in enumerate(timesteps):\n i_row = i // n_cols\n i_col = i % n_cols\n \n ax = axes[i_row,i_col]\n \n # TASK\n loading = network.lines_t.p0.loc[network.snapshots[timestep]]/network.lines.s_nom\n \n network.plot(ax=ax,\n line_colors=abs(loading),\n line_cmap=plt.cm.viridis,\n title=\"Line loading\",\n bus_sizes=0,\n color_geomap=True)\n \n ax.set_title(timestep)", "_____no_output_____" ] ], [ [ "### (b)-(v) | Plot the locational marginal prices for snapshots on the network. What is the interpretation of high and low marginal prices? What do the geographical differences of nodal prices tell you about the regional generation capacity, load centres and the state of the transmission network?", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols,\n figsize=(size*n_cols,size*n_rows),\n subplot_kw={\"projection\":ccrs.PlateCarree()})\n\nfor i,timestep in enumerate(timesteps):\n i_row = i // n_cols\n i_col = i % n_cols\n \n ax = axes[i_row,i_col]\n \n network.plot(ax=ax,\n line_widths=pd.Series(0.5,network.lines.index),\n bus_sizes=0,\n line_colors='firebrick',\n color_geomap=True)\n \n # TASK\n marginal_prices = network.buses_t.marginal_price.loc[network.snapshots[timestep]]\n\n hb = ax.hexbin(\n network.buses.x,\n network.buses.y, \n gridsize=20,\n C=marginal_prices,\n cmap=plt.cm.viridis\n )\n \n ax.set_title(timestep)\n\ncb = fig.colorbar(hb, ax=axes.ravel().tolist())\n\nmini = network.buses_t.marginal_price.min().min()\nmaxi = network.buses_t.marginal_price.max().max()\n\ncb.set_label('Locational Marginal Price (EUR/MWh)') ", "_____no_output_____" ], [ "network.buses_t.marginal_price.min().min()", "_____no_output_____" ], [ "network.buses_t.marginal_price.max().max()", "_____no_output_____" ], [ "network.buses_t.marginal_price.describe()", "_____no_output_____" ], [ "# regional distribution\nnetwork.buses_t.marginal_price.mean().describe()", "_____no_output_____" ], [ "# temporal distribution\nnetwork.buses_t.marginal_price.mean(axis=1).describe()", "_____no_output_____" ] ], [ [ "### (b)-(vi) | In general, when is variable renewable electricity curtailed? Plot the curtailment for on- and offshore wind as well as for solar energy on the chosen day. Would there still be curtailment if there were unlimited transmission capacity? What happens to the nodal prices in this case?", "_____no_output_____" ], [ "> **Hint:** For testing what would happen if there were unlimited transmission capacity, set the cost associated with transmission expansion to zero and rerun LOPF.", "_____no_output_____" ] ], [ [ "carriers = [\"Wind Onshore\", \"Wind Offshore\", \"Solar\"]\n\nn_graphs_g = len(carriers)\nn_cols_g = 3\nn_rows_g = 1\nsize_g = 6\n \nfig, axes = plt.subplots(nrows=n_rows_g, ncols=n_cols_g,\n figsize=(size_g*n_cols_g,size_g*n_rows_g))\n\nfor i,carrier in enumerate(carriers):\n i_col = i % n_cols_g\n \n ax = axes[i_col]\n \n capacity = network.generators.groupby(\"carrier\").sum().at[carrier,\"p_nom\"]\n\n # TASK\n p_available = network.generators_t.p_max_pu.multiply(network.generators.p_nom)\n p_available_by_carrier = p_available.groupby(network.generators.carrier, axis=1).sum()\n p_curtailed_by_carrier = p_available_by_carrier - p_by_carrier\n\n p_df = pd.DataFrame({carrier + \" available\" : p_available_by_carrier[carrier],\n carrier + \" dispatched\" : p_by_carrier[carrier],\n carrier + \" curtailed\" : p_curtailed_by_carrier[carrier]})\n\n p_df[carrier + \" capacity\"] = capacity\n\n p_df[carrier + \" curtailed\"][p_df[carrier + \" curtailed\"] < 0.] = 0.\n\n (p_df[[carrier + \" dispatched\",carrier + \" curtailed\"]]/1e3).plot(kind=\"area\",ax=ax,linewidth=0)\n (p_df[[carrier + \" available\",carrier + \" capacity\"]]/1e3).plot(ax=ax,linewidth=2)\n\n ax.set_xlabel(\"\")\n ax.set_ylabel(\"Power [GW]\")\n ax.legend()\n \n ax.set_title(carrier)", "_____no_output_____" ] ], [ [ "***\n## (c) Perform a non-linear power flow (Newton-Raphson) on the injections determined by the linear optimal power flow.", "_____no_output_____" ], [ "> **Remark:** You can use the function [`network.pf()`](https://pypsa-readthedocs.readthedocs.io/en/readthedocs/power_flow.html). In case you are interested, you can find a description of the Newton-Raphson load flow algorithm [here](http://nptel.ac.in/courses/Webcourse-contents/IIT-KANPUR/power-system/chapter_4/4_10.html). However, you will not need it for the exam.", "_____no_output_____" ], [ "For the non-linear power flow, we set the P to the optimised P from the linear optimal power flow.", "_____no_output_____" ] ], [ [ "network.generators_t.p_set = network.generators_t.p_set.reindex(columns=network.generators.index)\nnetwork.generators_t.p_set = network.generators_t.p", "_____no_output_____" ] ], [ [ "Further, we set all buses to PV, since we do not know what the Q set points are.", "_____no_output_____" ] ], [ [ "network.generators.control = \"PV\"", "_____no_output_____" ] ], [ [ "But we need some PQ buses so that the Jacobian does not break", "_____no_output_____" ] ], [ [ "f = network.generators[network.generators.bus == \"492\"]\nnetwork.generators.loc[f.index,\"control\"] = \"PQ\"", "_____no_output_____" ] ], [ [ "Perform non-linear PF on the results of linear optimal power flow (LOPF).", "_____no_output_____" ] ], [ [ "info = network.pf()", "_____no_output_____" ] ], [ [ "### (c)-(i) | Plot the regional and temporal distribution of reactive power feed-in. What is the consequence of reactive flows in terms of the network's transfer capacity?", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols,\n figsize=(size*n_cols,size*n_rows),\n subplot_kw={\"projection\":ccrs.PlateCarree()})\n\nfor i,timestep in enumerate(timesteps):\n i_row = i // n_cols\n i_col = i % n_cols\n \n ax = axes[i_row,i_col]\n \n # TASK\n q = network.buses_t.q.loc[network.snapshots[timestep]]\n \n bus_colors = pd.Series(\"firebrick\", network.buses.index)\n bus_colors[q<0.] = \"navy\"\n \n network.plot(ax=ax,\n bus_sizes=abs(q),\n bus_colors=bus_colors,\n title=\"Reactive power feed-in (red=+ve, blue=-ve)\",\n line_colors='grey',\n color_geomap=True)\n \n ax.set_title(timestep)", "_____no_output_____" ] ], [ [ "### (c)-(ii) | Analyse whether the chosen security constraint for thermal line loading was sufficient. What happens if you omit the security constraint or require an even higher security constraint?", "_____no_output_____" ], [ "> **Hint:** Using a histogram might be a good option to visualise the distribution of maximum line loadings.", "_____no_output_____" ] ], [ [ "# TASK\n(network.lines_t.p0/network.lines.s_nom*contingency_factor).abs().max().hist(bins=np.arange(0,2,0.1))", "_____no_output_____" ], [ "# TASK \n(network.lines_t.p0 / network.lines.s_nom*contingency_factor).abs().max().max()", "_____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", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
ec4d8d4112f706b0b85c72eac2e57ec7c28c9665
37,007
ipynb
Jupyter Notebook
training&val files/svm_emnist_byclass.ipynb
faizan1234567/Hand-writing-recognition
305ba83c55a9a59d9484e096e8dcbeed56660512
[ "MIT" ]
null
null
null
training&val files/svm_emnist_byclass.ipynb
faizan1234567/Hand-writing-recognition
305ba83c55a9a59d9484e096e8dcbeed56660512
[ "MIT" ]
null
null
null
training&val files/svm_emnist_byclass.ipynb
faizan1234567/Hand-writing-recognition
305ba83c55a9a59d9484e096e8dcbeed56660512
[ "MIT" ]
null
null
null
38.230372
3,418
0.348583
[ [ [ "import sklearn\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime as dt\n\n# Import datasets, classifiers and performance metrics\nfrom sklearn import datasets, svm, metrics\n#fetch original mnist dataset\n# from sklearn.datasets import fetch_mldata\n", "_____no_output_____" ], [ "from google.colab import drive\ndrive.mount('/gdrive')", "Mounted at /gdrive\n" ], [ "test_data = pd.read_csv('/gdrive/MyDrive/OCR/Dataset/emnist-byclass-test.csv')\ntrain_data = pd.read_csv('/gdrive/MyDrive/OCR/Dataset/emnist-byclass-train.csv')", "_____no_output_____" ], [ "train_data.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 697931 entries, 0 to 697930\nColumns: 785 entries, 35 to 0.475\ndtypes: int64(785)\nmemory usage: 4.1 GB\n" ], [ "test_data.head()", "_____no_output_____" ], [ "train_examples = 60000\ntest_examples = 10000", "_____no_output_____" ], [ "X_test = test_data.iloc[:, 1:]\nX_test = X_test.iloc[:test_examples, :]\nY_test = test_data.iloc[:, 0]\nY_test = Y_test.iloc[:test_examples]\nX_train = train_data.iloc[:, 1:]\nX_train = X_train.iloc[:train_examples, :]\nY_train = train_data.iloc[:, 0]\nY_train = Y_train.iloc[:train_examples]\nprint(f'X test shape: {X_test.shape}')\nprint(f'Y test shape: {Y_test.shape}')\n\nprint(f'X test shape: {X_train.shape}')\nprint(f'Y test shape: {Y_train.shape}')\n", "X test shape: (10000, 784)\nY test shape: (10000,)\nX test shape: (60000, 784)\nY test shape: (60000,)\n" ], [ "index = np.random.randint(X_test.shape[0])\ntest_image = X_test.iloc[index, :].values.reshape(28, 28)\ntest_label = Y_test.iloc[index]\nlabels = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n# print(len(labels))\nplt.imshow(test_image.T, cmap= 'gray')\nplt.title(labels[test_label])\nplt.axis('off')", "_____no_output_____" ], [ "from sklearn.preprocessing import scale", "_____no_output_____" ], [ "X_train = scale(X_train)", "_____no_output_____" ], [ "X_test = scale(X_test)", "_____no_output_____" ], [ "param_C = 5\nparam_gamma = 0.05 # by tweaking these params might improve the results", "_____no_output_____" ], [ "def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):\n \"\"\"\n Plots confusion matrix, \n \n cm - confusion matrix\n \"\"\"\n plt.figure(1, figsize=(15, 12), dpi=160)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n plt.show() ", "_____no_output_____" ], [ "# classifier = svm.SVC(C=param_C,gamma=param_gamma)\n# classifier = svm.SVC(kernel='linear')\nclassifier=svm.SVC(kernel='rbf')\n\n\n#We learn the digits on train part\nstart_time = dt.datetime.now()\nprint('Start learning at {}'.format(str(start_time)))\nclassifier.fit(X_train, Y_train)\nend_time = dt.datetime.now() \nprint('Stop learning {}'.format(str(end_time)))\nelapsed_time= end_time - start_time\nprint('Elapsed learning {}'.format(str(elapsed_time)))\n", "_____no_output_____" ], [ "expected = Y_test\npredicted = classifier.predict(X_test)\n\n\nprint(\"Classification report for classifier %s:\\n%s\\n\"\n % (classifier, metrics.classification_report(expected, predicted)))\n \ncm = metrics.confusion_matrix(expected, predicted)\n# print(\"Confusion matrix:\\n%/s\" % cm)\n\n# plot_confusion_matrix(cm)\n\nprint(\"Accuracy={}\".format(metrics.accuracy_score(expected, predicted)))\n", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4d93019744a7c25287e1ae80da6103f548dc87
45,974
ipynb
Jupyter Notebook
site/en-snapshot/swift/tutorials/protocol_oriented_generics.ipynb
ilyaspiridonov/docs-l10n
a061a44e40d25028d0a4458094e48ab717d3565c
[ "Apache-2.0" ]
1
2021-09-23T09:56:29.000Z
2021-09-23T09:56:29.000Z
site/en-snapshot/swift/tutorials/protocol_oriented_generics.ipynb
ilyaspiridonov/docs-l10n
a061a44e40d25028d0a4458094e48ab717d3565c
[ "Apache-2.0" ]
null
null
null
site/en-snapshot/swift/tutorials/protocol_oriented_generics.ipynb
ilyaspiridonov/docs-l10n
a061a44e40d25028d0a4458094e48ab717d3565c
[ "Apache-2.0" ]
1
2020-05-31T15:04:18.000Z
2020-05-31T15:04:18.000Z
38.994063
575
0.511332
[ [ [ "##### Copyright 2019 The TensorFlow Authors. [Licensed under the Apache License, Version 2.0](#scrollTo=Afd8bu4xJOgh).", "_____no_output_____" ] ], [ [ "// #@title Licensed under the Apache License, Version 2.0 (the \"License\"); { display-mode: \"form\" }\n// 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_____" ] ], [ [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/swift/tutorials/protocol_oriented_generics\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/swift/blob/master/docs/site/tutorials/protocol_oriented_generics.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/swift/blob/master/docs/site/tutorials/protocol_oriented_generics.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n</table>", "_____no_output_____" ], [ "# Protocol-oriented programming & generics\n\nThis tutorial will go over protocol-oriented programming, and different examples of how they can be used with generics in day-to-day examples.", "_____no_output_____" ], [ "## Protocols\n\nInheritance is a powerful way to organize code in programming languages that allows you to share code between multiple components of the program.\n\nIn Swift, there are different ways to express inheritance. You may already be familiar with one of those ways, from other languages: class inheritance. However, Swift has another way: protocols.\n\nIn this tutorial, we will explore protocols - an alternative to subclassing that allows you to achieve similar goals through different tradeoffs. In Swift, protocols contain multiple abstract members. Classes, structs and enums can conform to multiple protocols and the conformance relationship can be established retroactively. All that enables some designs that aren't easily expressible in Swift using subclassing. We will walk through the idioms that support the use of protocols (extensions and protocol constraints), as well as the limitations of protocols.\n", "_____no_output_____" ], [ "## Swift 💖's value types!\n\nIn addition to classes which have reference semantics, Swift supports enums and structs that are passed by value. Enums and structs support many features provided by classes. Let's take a look!\n\nFirstly, let's look at how enums are similar to classes:", "_____no_output_____" ] ], [ [ "enum Color: String {\n case red = \"red\"\n case green = \"green\"\n case blue = \"blue\"\n // A computed property. Note that enums cannot contain stored properties.\n var hint: String {\n switch self {\n case .red:\n return \"Roses are this color.\"\n case .green:\n return \"Grass is this color.\"\n case .blue:\n return \"The ocean is this color.\"\n }\n }\n \n // An initializer like for classes.\n init?(color: String) {\n switch color {\n case \"red\":\n self = .red\n case \"green\":\n self = .green\n case \"blue\":\n self = .blue\n default:\n return nil\n }\n }\n}\n\n// Can extend the enum as well!\nextension Color {\n // A function.\n func hintFunc() -> String {\n return self.hint\n }\n}\n\nlet c = Color.red\nprint(\"Give me a hint for c: \\(c.hintFunc())\")\n\nlet invalidColor = Color(color: \"orange\")\nprint(\"is invalidColor nil: \\(invalidColor == nil)\")", "_____no_output_____" ] ], [ [ "Now, let's look at structs. Notice that we cannot inherit structs, but instead can use protocols:", "_____no_output_____" ] ], [ [ "struct FastCar {\n // Can have variables and constants as stored properties.\n var color: Color\n let horsePower: Int\n // Can have computed properties.\n var watts: Float {\n return Float(horsePower) * 745.7\n }\n // Can have lazy variables like in classes!\n lazy var titleCaseColorString: String = {\n let colorString = color.rawValue\n return colorString.prefix(1).uppercased() + \n colorString.lowercased().dropFirst()\n }()\n // A function.\n func description() -> String {\n return \"This is a \\(color) car with \\(horsePower) horse power!\"\n }\n // Can create a variety of initializers.\n init(color: Color, horsePower: Int) {\n self.color = color\n self.horsePower = horsePower\n }\n // Can define extra initializers other than the default one.\n init?(color: String, horsePower: Int) {\n guard let enumColor = Color(color: color) else {\n return nil\n }\n self.color = enumColor\n self.horsePower = horsePower\n }\n}\n\nvar car = FastCar(color: .red, horsePower: 250)\nprint(car.description())\nprint(\"Horse power in watts: \\(car.watts)\")\nprint(car.titleCaseColorString)", "_____no_output_____" ] ], [ [ "Finally, let's see how they are pass by value types unlike classes:", "_____no_output_____" ] ], [ [ "// Notice we have no problem modifying a constant class with \n// variable properties.\nclass A {\n var a = \"a\"\n}\n\nfunc foo(_ a: A) {\n a.a = \"foo\"\n}\nlet a = A()\nprint(a.a)\nfoo(a)\nprint(a.a)\n\n/* \nUncomment the following code to see how an error is thrown.\nStructs are implicitly passed by value, so we cannot modify it.\n> \"error: cannot assign to property: 'car' is a 'let' constant\"\n*/\n\n// func modify(car: FastCar, toColor color: Color) -> Void {\n// car.color = color\n// }\n\n// car = FastCar(color: .red, horsePower: 250)\n// print(car.description())\n// modify(car: &car, toColor: .blue)\n// print(car.description())\n", "_____no_output_____" ] ], [ [ "## Let's use protocols\n\nLet's start by creating protocols for different cars:", "_____no_output_____" ] ], [ [ "protocol Car {\n var color: Color { get set }\n var price: Int { get }\n func turnOn()\n mutating func drive()\n}\n\nprotocol Electric {\n mutating func recharge()\n // percentage of the battery level, 0-100%.\n var batteryLevel: Int { get set }\n}\n\nprotocol Gas {\n mutating func refill()\n // # of liters the car is holding, varies b/w models.\n var gasLevelLiters: Int { get set }\n}", "_____no_output_____" ] ], [ [ "In an object-oriented world (with no multiple inheritance), you may have made `Electric` and `Gas` abstract classes then used class inheritance to make both inherit from `Car`, and then have a specific car model be a base class. However, here both are completely separate protocols with **zero** coupling! This makes the entire system more flexible in how you design it.\n\nLet's define a Tesla:", "_____no_output_____" ] ], [ [ "struct TeslaModelS: Car, Electric {\n var color: Color // Needs to be a var since `Car` has a getter and setter.\n let price: Int\n var batteryLevel: Int\n \n func turnOn() {\n print(\"Starting all systems!\")\n }\n\n mutating func drive() {\n print(\"Self driving engaged!\")\n batteryLevel -= 8\n }\n\n mutating func recharge() {\n print(\"Recharging the battery...\")\n batteryLevel = 100\n }\n}\n\nvar tesla = TeslaModelS(color: .red, price: 110000, batteryLevel: 100)", "_____no_output_____" ] ], [ [ "This specifies a new struct `TeslaModelS` that conforms to both protocols `Car` and `Electric`.\n\nNow let’s define a gas powered car:", "_____no_output_____" ] ], [ [ "struct Mustang: Car, Gas{\n var color: Color\n let price: Int\n var gasLevelLiters: Int\n \n func turnOn() {\n print(\"Starting all systems!\")\n }\n \n mutating func drive() {\n print(\"Time to drive!\")\n gasLevelLiters -= 1\n }\n \n mutating func refill() {\n print(\"Filling the tank...\")\n gasLevelLiters = 25\n }\n}\n\nvar mustang = Mustang(color: .red, price: 30000, gasLevelLiters: 25)", "_____no_output_____" ] ], [ [ "### Extend protocols with default behaviors\n\nWhat you can notice from the examples is that we have some redundancy. Every time we recharge an electric car, we need to set the battery percentage level to 100. Since all electric cars have a max capacity of 100%, but gas cars vary between gas tank capacity, we can default the level to 100 for electric cars.\n\nThis is where extensions in Swift can come in handy:", "_____no_output_____" ] ], [ [ "extension Electric {\n mutating func recharge() {\n print(\"Recharging the battery...\")\n batteryLevel = 100\n }\n}", "_____no_output_____" ] ], [ [ "So now, any new electric car we create will set the battery to 100 when we recharge it. Thus, we have just been able to decorate classes, structs, and enums with unique and default behavior.", "_____no_output_____" ], [ "![Protocol Comic](https://koenig-media.raywenderlich.com/uploads/2015/06/protocols-extend.png)\n\nThanks to [Ray Wenderlich](https://www.raywenderlich.com/814-introducing-protocol-oriented-programming-in-swift-3) for the comic!", "_____no_output_____" ], [ "However, one thing to watch out for is the following. In our first implementation, we define `foo()` as a default implementation on `A`, but not make it required in the protocol. So when we call `a.foo()`, we get \"`A default`\" printed.", "_____no_output_____" ] ], [ [ "protocol Default {}\n\nextension Default {\n func foo() { print(\"A default\")}\n}\n\nstruct DefaultStruct: Default {\n func foo() {\n print(\"Inst\")\n }\n}\n\nlet a: Default = DefaultStruct()\na.foo()", "_____no_output_____" ] ], [ [ "However, if we make `foo()` required on `A`, we get \"`Inst`\":", "_____no_output_____" ] ], [ [ "protocol Default {\n func foo()\n}\n\nextension Default {\n func foo() { \n print(\"A default\")\n }\n}\n\nstruct DefaultStruct: Default {\n func foo() {\n print(\"Inst\")\n }\n}\n\nlet a: Default = DefaultStruct()\na.foo()", "_____no_output_____" ] ], [ [ "This occurs due to a difference between static dispatch in the first example and static dispatch in the second on protocols in Swift. For more info, refer to this [Medium post](https://medium.com/@PavloShadov/https-medium-com-pavloshadov-swift-protocols-magic-of-dynamic-static-methods-dispatches-dfe0e0c85509).", "_____no_output_____" ], [ "### Overriding default behavior\n\nHowever, if we want to, we can still override the default behavior. One important thing to note is that this [doesn’t support dynamic dispatch](https://stackoverflow.com/questions/44703205/swift-protocol-extension-method-is-called-instead-of-method-implemented-in-subcl).\n\nLet’s say we have an older version of an electric car, so the battery health has been reduced to 90%:", "_____no_output_____" ] ], [ [ "struct OldElectric: Car, Electric {\n var color: Color // Needs to be a var since `Car` has a getter and setter.\n let price: Int\n var batteryLevel: Int\n \n func turnOn() {\n print(\"Starting all systems!\")\n }\n \n mutating func drive() {\n print(\"Self driving engaged!\")\n batteryLevel -= 8\n }\n \n mutating func reCharge() {\n print(\"Recharging the battery...\")\n batteryLevel = 90\n }\n}", "_____no_output_____" ] ], [ [ "## Standard library uses of protocols\n\nNow that we have an idea how protocols in Swift work, let's go through some typical examples of using the standard library protocols.\n\n### Extend the standard library\nLet's see how we can add additional functionality to types that exist in Swift already. Since types in Swift aren't built in, but are part of the standard library as structs, this is easy to do.\n\nLet's try and do binary search on an array of elements, while also making sure to check that the array is sorted:", "_____no_output_____" ] ], [ [ "extension Collection where Element: Comparable {\n // Verify that a `Collection` is sorted.\n func isSorted(_ order: (Element, Element) -> Bool) -> Bool {\n var i = index(startIndex, offsetBy: 1)\n \n while i < endIndex {\n // The longer way of calling a binary function like `<(_:_:)`, \n // `<=(_:_:)`, `==(_:_:)`, etc.\n guard order(self[index(i, offsetBy: -1)], self[i]) else {\n return false\n }\n i = index(after: i)\n }\n return true\n }\n \n // Perform binary search on a `Collection`, verifying it is sorted.\n func binarySearch(_ element: Element) -> Index? {\n guard self.isSorted(<=) else {\n return nil\n }\n \n var low = startIndex\n var high = endIndex\n \n while low <= high {\n let mid = index(low, offsetBy: distance(from: low, to: high)/2)\n\n if self[mid] == element {\n return mid\n } else if self[mid] < element {\n low = index(after: mid)\n } else {\n high = index(mid, offsetBy: -1)\n }\n }\n \n return nil\n }\n}\n\nprint([2, 2, 5, 7, 11, 13, 17].binarySearch(5)!)\nprint([\"a\", \"b\", \"c\", \"d\"].binarySearch(\"b\")!)\nprint([1.1, 2.2, 3.3, 4.4, 5.5].binarySearch(3.3)!)", "_____no_output_____" ] ], [ [ "We do this by extending the [`Collection`](https://developer.apple.com/documentation/swift/collection) protocol which defines _\"a sequence whose elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.\"_ Since arrays can be indexed using the square bracket notation, this is the protocol we want to extend.\n\nSimilarly, we only want to add this utility function to arrays whose elements can be compared. This is the reason why we have `where Element: Comparable`. \n\nThe `where` clause is a part of Swift's type system, which we will cover soon, but in short lets us add additional requirements to the extension we are writing, such as to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass.\n\n[`Element`](https://developer.apple.com/documentation/swift/sequence/2908099-element) is the associated type of the elements in a `Collection`-conforming type. `Element` is defined within the [`Sequence`](https://developer.apple.com/documentation/swift/sequence) protocol, but since `Collection` inherits from `Sequence`, it inherits the `Element` associated type.\n\n[`Comparable`](https://developer.apple.com/documentation/swift/comparable) is a protocol that defines _\"a type that can be compared using the relational operators `<`, `<=`, `>=`, and `>`.\"_. Since we are performing binary search on a sorted `Collection`, this of course has to be true or else we don't know whether to recurse/iterate left or right in the binary search.\n\nAs a side note about the implementation, for more info on the `index(_:offsetBy:)` function that was used, refer to the following [documentation](https://developer.apple.com/documentation/swift/string/1786175-index).", "_____no_output_____" ], [ "## Generics + protocols = 💥\nGenerics and protocols can be a powerful tool if used correctly to avoid duplicate code.\n\nFirstly, look over another tutorial, [A Swift Tour](https://colab.research.google.com/github/tensorflow/swift/blob/master/docs/site/tutorials/a_swift_tour.ipynb), which briefly covers generics at the end of the Colab book.\n\nAssuming you have a general idea about generics, let's quickly take a look at some advanced uses.\n\nWhen a single type has multiple requirements such as a type conforming to several protocols, you have several options at your disposal:", "_____no_output_____" ] ], [ [ "typealias ComparableReal = Comparable & FloatingPoint\n\nfunc foo1<T: ComparableReal>(a: T, b: T) -> Bool {\n return a > b\n}\n\nfunc foo2<T: Comparable & FloatingPoint>(a: T, b: T) -> Bool {\n return a > b\n}\n\nfunc foo3<T>(a: T, b: T) -> Bool where T: ComparableReal {\n return a > b\n}\n\nfunc foo4<T>(a: T, b: T) -> Bool where T: Comparable & FloatingPoint {\n return a > b\n}\n\nfunc foo5<T: FloatingPoint>(a: T, b: T) -> Bool where T: Comparable {\n return a > b\n}\n\nprint(foo1(a: 1, b: 2))\nprint(foo2(a: 1, b: 2))\nprint(foo3(a: 1, b: 2))\nprint(foo4(a: 1, b: 2))\nprint(foo5(a: 1, b: 2))", "_____no_output_____" ] ], [ [ "Notice the use of `typealias` at the top. This adds a named alias of an existing type into your program. After a type alias is declared, the aliased name can be used instead of the existing type everywhere in your program. Type aliases do not create new types; they simply allow a name to refer to an existing type.\n\nNow, let's see how we can use protocols and generics together.\n\nLet's imagine we are a computer store with the following requirements on any laptop we sell for determining how we organize them in the back of the store:", "_____no_output_____" ] ], [ [ "enum Box {\n case small\n case medium\n case large\n}\n\nenum Mass {\n case light\n case medium\n case heavy\n}\n\n// Note: `CustomStringConvertible` protocol lets us pretty-print a `Laptop`.\nstruct Laptop: CustomStringConvertible {\n var name: String\n var box: Box\n var mass: Mass\n \n var description: String {\n return \"(\\(self.name) \\(self.box) \\(self.mass))\"\n }\n}", "_____no_output_____" ] ], [ [ "However, we have a new requirement of grouping our `Laptop`s by mass since the shelves have weight restrictions.", "_____no_output_____" ] ], [ [ "func filtering(_ laptops: [Laptop], by mass: Mass) -> [Laptop] {\n return laptops.filter { $0.mass == mass }\n}\n\nlet laptops: [Laptop] = [\n Laptop(name: \"a\", box: .small, mass: .light),\n Laptop(name: \"b\", box: .large, mass: .medium),\n Laptop(name: \"c\", box: .medium, mass: .heavy),\n Laptop(name: \"d\", box: .large, mass: .light)\n]\n\nlet filteredLaptops = filtering(laptops, by: .light)\nprint(filteredLaptops)", "_____no_output_____" ] ], [ [ "However, what if we wanted to filter by something other than `Mass`? \n\nOne option is to do the following:", "_____no_output_____" ] ], [ [ "// Define a protocol which will act as our comparator.\nprotocol DeviceFilterPredicate {\n associatedtype Device\n func shouldKeep(_ item: Device) -> Bool\n}\n\n// Define the structs we will use for passing into our filtering function.\nstruct BoxFilter: DeviceFilterPredicate {\n typealias Device = Laptop\n var box: Box \n \n func shouldKeep(_ item: Laptop) -> Bool {\n return item.box == box\n }\n}\n\nstruct MassFilter: DeviceFilterPredicate {\n typealias Device = Laptop \n var mass: Mass\n \n func shouldKeep(_ item: Laptop) -> Bool {\n return item.mass == mass\n }\n}\n\n// Make sure our filter conforms to `DeviceFilterPredicate` and that we are \n// filtering `Laptop`s.\nfunc filtering<F: DeviceFilterPredicate>(\n _ laptops: [Laptop], \n by filter: F\n) -> [Laptop] where Laptop == F.Device {\n return laptops.filter { filter.shouldKeep($0) }\n}\n\n// Let's test the function out!\nprint(filtering(laptops, by: BoxFilter(box: .large)))\nprint(filtering(laptops, by: MassFilter(mass: .heavy)))", "_____no_output_____" ] ], [ [ "Awesome! Now we are able to filter based on any laptop constraint. However, we are only able to filter `Laptop`s. \n\nWhat about being able to filter anything that is in a box and has mass? Maybe this warehouse of laptops will also be used for servers which have a different customer base:", "_____no_output_____" ] ], [ [ "// Define 2 new protocols so we can filter anything in a box and which has mass.\nprotocol Weighable {\n var mass: Mass { get }\n}\n\nprotocol Boxed {\n var box: Box { get }\n}\n\n// Define the new Laptop and Server struct which have mass and a box.\nstruct Laptop: CustomStringConvertible, Boxed, Weighable {\n var name: String\n var box: Box\n var mass: Mass\n \n var description: String {\n return \"(\\(self.name) \\(self.box) \\(self.mass))\"\n }\n}\n\nstruct Server: CustomStringConvertible, Boxed, Weighable {\n var isWorking: Bool\n var name: String\n let box: Box\n let mass: Mass\n\n var description: String {\n if isWorking {\n return \"(working \\(self.name) \\(self.box) \\(self.mass))\"\n } else {\n return \"(notWorking \\(self.name) \\(self.box) \\(self.mass))\"\n }\n }\n}\n\n// Define the structs we will use for passing into our filtering function.\nstruct BoxFilter<T: Boxed>: DeviceFilterPredicate {\n var box: Box \n \n func shouldKeep(_ item: T) -> Bool {\n return item.box == box\n }\n}\n\nstruct MassFilter<T: Weighable>: DeviceFilterPredicate {\n var mass: Mass\n \n func shouldKeep(_ item: T) -> Bool {\n return item.mass == mass\n }\n}\n\n// Define the new filter function.\nfunc filtering<F: DeviceFilterPredicate, T>(\n _ elements: [T], \n by filter: F\n) -> [T] where T == F.Device {\n return elements.filter { filter.shouldKeep($0) }\n}\n\n\n// Let's test the function out!\nlet servers = [\n Server(isWorking: true, name: \"serverA\", box: .small, mass: .heavy),\n Server(isWorking: false, name: \"serverB\", box: .medium, mass: .medium),\n Server(isWorking: true, name: \"serverC\", box: .large, mass: .light),\n Server(isWorking: false, name: \"serverD\", box: .medium, mass: .light),\n Server(isWorking: true, name: \"serverE\", box: .small, mass: .heavy)\n]\n\nlet products = [\n Laptop(name: \"a\", box: .small, mass: .light),\n Laptop(name: \"b\", box: .large, mass: .medium),\n Laptop(name: \"c\", box: .medium, mass: .heavy),\n Laptop(name: \"d\", box: .large, mass: .light)\n]\n\nprint(filtering(servers, by: BoxFilter(box: .small)))\nprint(filtering(servers, by: MassFilter(mass: .medium)))\n\nprint(filtering(products, by: BoxFilter(box: .small)))\nprint(filtering(products, by: MassFilter(mass: .medium)))", "_____no_output_____" ] ], [ [ "We have now been able to filter an array by not only any property of a specific `struct`, but also be able to filter any struct which has that property!", "_____no_output_____" ], [ "# Tips for good API design\n***This section was taken from the [WWDC 2019: Modern Swift API Design](https://developer.apple.com/videos/play/wwdc2019/415/) talk.***\n\nNow that you understand how protocols behave, it's best to go over when you should use protocols. As powerful as protocols can be, it's not always the best idea to dive in and immediately start with protocols.\n\n* Start with concrete use cases:\n * First explore the use case with concrete types and understand what code it is you want to share and find is being repeated. Then, factor that shared code out with generics. It might mean to create new protocols. Discover a need for generic code.\n* Consider composing new protocols from existing protocols defined in the standard library. Refer to the following [Apple documentation](https://developer.apple.com/documentation/swift/adopting_common_protocols) for a good example of this.\n* Instead of a generic protocol, consider defining a generic type instead.\n\n## Example: defining a custom vector type\nLet's say we want to define a `GeometricVector` protocol on floating-point numbers to use in some geometry app we are making which defines 3 important vector operations:\n\n```swift\nprotocol GeometricVector {\n associatedtype Scalar: FloatingPoint\n static func dot(_ a: Self, _ b: Self) -> Scalar\n var length: Scalar { get }\n func distance(to other: Self) -> Scalar\n}\n```\n\nLet's say we want to store the dimensions of the vector, which the `SIMD` protocol can help us with, so we will make our new type refine the `SIMD` protocol. `SIMD` vectors can be thought of as fixed size vectors that are very fast when you use them to perform vector operations:\n\n```swift\nprotocol GeometricVector: SIMD {\n associatedtype Scalar: FloatingPoint\n static func dot(_ a: Self, _ b: Self) -> Scalar\n var length: Scalar { get }\n func distance(to other: Self) -> Scalar\n}\n```\n\nNow, let us define the default implementations of the operations above:\n\n```swift\nextension GeometricVector {\n static func dot(_ a: Self, _ b: Self) -> Scalar {\n (a * b).sum()\n }\n\n var length: Scalar {\n Self.dot(self, self).squareRoot()\n }\n\n func distance(to other: Self) -> Scalar {\n (self - other).length\n }\n}\n```\n\nAnd then we need to add a conformance to each of the types we want to add these abilities:\n```swift\nextension SIMD2: GeometricVector where Scalar: FloatingPoint { }\nextension SIMD3: GeometricVector where Scalar: FloatingPoint { }\nextension SIMD4: GeometricVector where Scalar: FloatingPoint { }\nextension SIMD8: GeometricVector where Scalar: FloatingPoint { }\nextension SIMD16: GeometricVector where Scalar: FloatingPoint { }\nextension SIMD32: GeometricVector where Scalar: FloatingPoint { }\nextension SIMD64: GeometricVector where Scalar: FloatingPoint { }\n```\n\nThis three-step process of defining the protocol, giving it a default implementation, and then adding a conformance to multiple types is fairly repetitive.\n\n## Was the protocol necessary?\nThe fact that none of the `SIMD` types have unique implementations is a warning sign. So in this case, the protocol isn't really giving us anything.\n\n## Defining it in an extension of `SIMD`\nIf we write the 3 operators in an extension of the `SIMD` protocol, this can solve the problem more succinctly:\n\n```swift\nextension SIMD where Scalar: FloatingPoint {\n static func dot(_ a: Self, _ b: Self) -> Scalar {\n (a * b).sum()\n }\n\n var length: Scalar {\n Self.dot(self, self).squareRoot()\n }\n\n func distance(to other: Self) -> Scalar {\n (self - other).length\n }\n}\n```\n\nUsing less lines of code, we added all the default implementations to all the types of `SIMD`.\n\nSometimes you may be tempted to create this hierarchy of types, but remember that it isn't always necessary. This also means the binary size of your compiled program will be smaller, and your code will be faster to compile. \n\nHowever, this extension approach is great for when you have a few number of methods you want to add. However, it does hit a scalability issue when you are designing a larger API.\n\n## Is-a? Has-a?\nEarlier we said `GeometricVector` would refine `SIMD`. But is this a is-a relationship? The problem is that `SIMD` defines operations which lets us add a scalar 1 to a vector, but it doesn't make sense to define such an operation in the context of geometry. \n\nSo, maybe a has-a relationship would be better by wrapping `SIMD` in a new generic type that can handle any floating point number:\n\n```swift\n// NOTE: `Storage` is the underlying type that is storing the values, \n// just like in a `SIMD` vector.\nstruct GeometricVector<Storage: SIMD> where Storage.Scalar: FloatingPoint {\n typealias Scalar = Storage.Scalar\n var value: Storage\n init(_ value: Storage) { self.value = value }\n}\n```\n\nWe can then be careful and only define the operations that make sense only in the context of geometry:\n\n```swift\nextension GeometricVector {\n static func + (a: Self, b: Self) -> Self {\n Self(a.value + b.value)\n }\n\n static func - (a: Self, b: Self) -> Self {\n Self(a.value - b.value)\n }\n static func * (a: Self, b: Scalar) -> Self {\n Self(a.value * b)\n }\n}\n```\n\nAnd we can still use generic extensions to get the 3 previous operators we wanted to implement which look almost the exact same as before:\n\n```swift\nextension GeometricVector {\n static func dot(_ a: Self, _ b: Self) -> Scalar {\n (a.value * b.value).sum()\n }\n\n var length: Scalar {\n Self.dot(self, self).squareRoot()\n }\n\n func distance(to other: Self) -> Scalar {\n (self - other).length\n }\n}\n```\n\nOverall, we have been able to refine the behavior of our three operations to a type by simply using a struct. With protocols, we faced the issue of writing repetitive conformances to all the `SIMD` vectors, and also weren't able to prevent certain operators like `Scalar + Vector` from being available (which in this case we didn't want). As such, remember that protocols are not a be-all and end-all solution. But sometimes more traditional solutions can prove to be more powerful.", "_____no_output_____" ], [ "# More protocol-oriented programming resources\nHere are additional resources on the topics discussed:\n\n* [WWDC 2015: Protocol-Oriented Programming in Swift](https://developer.apple.com/videos/play/wwdc2015/408/): this was presented using Swift 2, so a lot has changed since then (e.g. name of the protocols they used in the presentation) but this is still a good resource for the theory and uses behind it.\n* [Introducing Protocol-Oriented Programming in Swift 3](https://www.raywenderlich.com/814-introducing-protocol-oriented-programming-in-swift-3): this was written in Swift 3, so some of the code may need to be modified in order to have it compile successfully, but it is another great resource.\n* [WWDC 2019: Modern Swift API Design](https://developer.apple.com/videos/play/wwdc2019/415/): goes over the differences between value and reference types, a use case of when protocols can prove to be the worse choice in API design (same as the \"Tips for Good API Design\" section above), key path member lookup, and property wrappers.\n* [Generics](https://docs.swift.org/swift-book/LanguageGuide/Generics.html): Swift's own documentation for Swift 5 all about generics.", "_____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" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
ec4d9ca12efc00f5458dc82fb16539e0ce19f0f4
215,167
ipynb
Jupyter Notebook
Lectures/Lecture24/Lecture24_Mar05.ipynb
tomgrubbmath/IntroMathSoftware
da15f9f0649989b9c2f12c06015b65b32e728061
[ "MIT" ]
null
null
null
Lectures/Lecture24/Lecture24_Mar05.ipynb
tomgrubbmath/IntroMathSoftware
da15f9f0649989b9c2f12c06015b65b32e728061
[ "MIT" ]
null
null
null
Lectures/Lecture24/Lecture24_Mar05.ipynb
tomgrubbmath/IntroMathSoftware
da15f9f0649989b9c2f12c06015b65b32e728061
[ "MIT" ]
null
null
null
143.444667
42,170
0.888538
[ [ [ "# Lecture 24: Image Classification and the MNIST Digits Dataset\n\n### Please note: This lecture will be recorded and made available for viewing online. If you do not wish to be recorded, please adjust your camera settings accordingly. \n\n# Reminders/Announcements:\n- Done with homework!\n- Please do CAPES!\n - If we get 75% completion by Monday, then Wednesday and Friday's lectures will be cancelled (with free participation points for each) and that time can be spent presenting/working on your final projects.\n- Final Project \"examples\" from last year available\n - Warning: I make no claims that these are \"perfect\" projects (in particular, they are missing participation checks, etc.) but I think the presentations are quite good\n- Some final project remarks:\n - If you have tried getting in touch with your groupmates and have had no response, please email me\n - I recommend *making a plan* with your groupmates by the end of next week (things will be collected on Wednesday of finals week, so presentations should occur *before* then)", "_____no_output_____" ], [ "## MNIST\n\nThe *Modified National Institute of Standards and Technology* (MNIST) database is a large collection of data that can be used for training and evaluating models in machine learning. Why is this important? Well...think of all of the news articles you have seen recently about self driving cars! For such a car to be safely allowed on the road, it has to have a *very good* image recognition mechanism. Otherwise we are left vulnerable to things like this: \n\n![](stop.png)\n\nImage extracted from: https://arxiv.org/pdf/1707.08945.pdf\n\nSubtle modifications to street signs can be easily overcome by human drivers. They are *very difficult* for a computer to deal with. \n\nThis lecture will be a brief introduction to image analysis using MNIST's digits dataset (working with this dataset is commonly called the \"Hello World\" of machine learning)", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom sklearn.datasets import fetch_openml\nmnist = fetch_openml('mnist_784', version = 1)\nmnist.keys()", "_____no_output_____" ], [ "mnist['DESCR']", "_____no_output_____" ] ], [ [ "This dataset has split up the explanatory and explained variables into `data` and `target`", "_____no_output_____" ] ], [ [ "X, y = mnist['data'], mnist['target']", "_____no_output_____" ], [ "print(type(X))\nprint(X.shape)", "<class 'numpy.ndarray'>\n(70000, 784)\n" ], [ "print(type(y))\nprint(y.shape)", "<class 'numpy.ndarray'>\n(70000,)\n" ] ], [ [ "We have 70,000 images, each with 784 features. What do you think these features represent?", "_____no_output_____" ] ], [ [ "import matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nsome_digit = X[0]\nsome_digit_image = some_digit.reshape(28,28)", "_____no_output_____" ], [ "plt.imshow(some_digit_image,cmap = 'binary')\nplt.axis('off')\nplt.show()", "_____no_output_____" ] ], [ [ "This looks like the digit `5`. How can we make sure?", "_____no_output_____" ] ], [ [ "y[0]", "_____no_output_____" ] ], [ [ "Note that we already have to do some preprocessing:", "_____no_output_____" ] ], [ [ "type(y[0])", "_____no_output_____" ], [ "y = y.astype(np.uint8)", "_____no_output_____" ], [ "type(y[0])", "_____no_output_____" ] ], [ [ "Let's do a train/test split, so we can evaluate our models:\n\n## ****** Participation Check ****************************\n\nCreate new arrays `Xtrain,Xtest,ytrain, and ytest` where the `train` arrays consist of the first 60000 entries in the corresponding dataset and the test entries consist of the last 10000 entries of the corresponding dataset. (Be careful! In the real world you may want to shuffle your dataset first...)", "_____no_output_____" ] ], [ [ "Xtrain, ytrain, Xtest, ytest = X[:60000],y[:60000],X[60000:],y[60000:]", "_____no_output_____" ] ], [ [ "## *******************************************************************", "_____no_output_____" ], [ "## Binary Classifiers: The Decision Tree\n\nBefore we try to classify the 10 digits, let's try a much easier problem: whether or not a digit is 8. To do this we will use a *decision tree*. A decision tree is a machine learning model which asks a bunch of yes or no questions to come to a conclusion. Think of the game 20 Questions, except the questions are *fixed* every time you play.\n<img src=\"dt.png\" alt=\"drawing\" width=\"700\"/>\n\nHow does it figure out the best yes/no questions to ask? It tries to *minimize* a quantity called *Gini impurity*. The Gini impurity of a node measures how \"mixed\" that node is.", "_____no_output_____" ], [ "<img src=\"gini.png\" alt=\"drawing\" width=\"700\"/>\n\nThankfully this Gini minimization is all builtin! You can read more here if you want though: https://en.wikipedia.org/wiki/Decision_tree_learning", "_____no_output_____" ] ], [ [ "from sklearn.tree import DecisionTreeClassifier\ntree = DecisionTreeClassifier(random_state = 42) #Initialize a DT\nytrain8 = (ytrain==8) #Set up the \"easier\" classification problem\nytest8 = (ytest == 8) #Set up the \"easier\" test problem\ntree.fit(Xtrain,ytrain8)", "_____no_output_____" ], [ "tree.predict(X[:20])", "_____no_output_____" ], [ "some_digit = X[17]\nsome_digit_image = some_digit.reshape(28,28)\nplt.imshow(some_digit_image,cmap = 'binary')\nplt.axis('off')\nplt.show()", "_____no_output_____" ], [ "y[:20]", "_____no_output_____" ] ], [ [ "Seems pretty good! A more robust test on the accuracy can be found by calling a *confusion matrix*. In general if there are $k$ classes, the confusion matrix will have entry [i,j] equal to the number of times class i was predicted to be class j.", "_____no_output_____" ] ], [ [ "pred = tree.predict(Xtrain)", "_____no_output_____" ], [ "from sklearn.metrics import confusion_matrix\nconfusion_matrix(ytrain8,pred)", "_____no_output_____" ] ], [ [ "It seems like we have a perfect model!!! But...\n\nBe careful!!! You have to always ask yourself how well your model generalizes. Decision trees are *very likely* just going to memorize your training data if you let them run free. If, instead of 20 questions, you played 20000 questions, you would always get the right answer. But your questions would become arbitrary and they would not apply to new scenarios.\n\nIn this case our testing error is actually not awful:", "_____no_output_____" ] ], [ [ "pred = tree.predict(Xtest)\nconfusion_matrix(ytest8,pred)", "_____no_output_____" ] ], [ [ "But we can improve it slightly by \"regularizing\" the model. The `max_depth` parameter essentially puts a bound on the number of questions you are allowed to ask:", "_____no_output_____" ] ], [ [ "tree = DecisionTreeClassifier(max_depth = 9, random_state = 42)\ntree.fit(Xtrain,ytrain8)", "_____no_output_____" ], [ "pred = tree.predict(Xtrain)\nconfusion_matrix(ytrain8,pred)", "_____no_output_____" ], [ "pred = tree.predict(Xtest)\nconfusion_matrix(ytest8,pred)", "_____no_output_____" ] ], [ [ "This looks slightly better, even though we did worse on the training data!\n\nLet's take a look at what we got wrong.", "_____no_output_____" ] ], [ [ "badGuesses = [i for i in range(10000) if pred[i]!=ytest8[i]]\nlen(badGuesses)", "_____no_output_____" ], [ "badGuesses[:6]", "_____no_output_____" ], [ "some_digit = Xtest[61]\nsome_digit_image = some_digit.reshape(28,28)\nplt.imshow(some_digit_image,cmap = 'binary')\nplt.axis('off')\nplt.show()", "_____no_output_____" ], [ "some_digit = Xtest[172]\nsome_digit_image = some_digit.reshape(28,28)\nplt.imshow(some_digit_image,cmap = 'binary')\nplt.axis('off')\nplt.show()", "_____no_output_____" ], [ "some_digit = Xtest[257]\nsome_digit_image = some_digit.reshape(28,28)\nplt.imshow(some_digit_image,cmap = 'binary')\nplt.axis('off')\nplt.show()", "_____no_output_____" ] ], [ [ "As with the lecture on Information Retrieval, you can define further metrics like *recall*, *precision*, *specificity*, etc. But for now I'll leave it here.", "_____no_output_____" ], [ "## Predicting Probabilities\n\nWe can actually do a bit better with Decision Trees; we can predict the *probability* that something is an 8 or not! The idea is to create the same decision tree, and then when you predict, instead of returning a class, return the *proportion* of a class that is in the corresponding leaf node.", "_____no_output_____" ] ], [ [ "probs = tree.predict_proba(Xtest)\nprobs[:15]", "_____no_output_____" ], [ "probs[257]", "_____no_output_____" ], [ "[probs[i] for i in badGuesses[:10]]", "_____no_output_____" ] ], [ [ "This will allow us to combine several classifiers into one. We have 10 digits in question; this would allow us to create *10 distinct classifiers*, have each compute the probability that something *is* a given digit, and then take the one which maximizes probability!\n\n![](trees.png)\n\nIn practice when you do this combination you often use a *softmax*, but I'll leave you with just a reference in case you are interested: https://en.wikipedia.org/wiki/Softmax_function . \n\nThere are various ways of combining binary classifiers to get a *multiclass* classifier, but softmaxing is a common one and a good start.", "_____no_output_____" ], [ "## Multiclass Classification\n\nThankfully Decision Trees can natively handle multiclass classification, so we don't actually need to worry about this! As this problem is a bit more complicated, we can afford to let our model ask a few more questions...", "_____no_output_____" ] ], [ [ "tree = DecisionTreeClassifier(max_depth = 13,random_state = 42)\ntree.fit(Xtrain,ytrain)", "_____no_output_____" ], [ "pred = tree.predict(Xtest)\ncm = confusion_matrix(ytest,pred)", "_____no_output_____" ], [ "cm", "_____no_output_____" ], [ "sum([cm[i,j] for i in range(10) for j in range(10) if i-j])", "_____no_output_____" ], [ "plt.matshow(cm,cmap = plt.cm.gray)\nplt.show()", "_____no_output_____" ] ], [ [ "Can we get anything better out of the confusion matrix?", "_____no_output_____" ] ], [ [ "sums = cm.sum(axis=1,keepdims=True)\nnorm = cm/sums", "_____no_output_____" ], [ "np.fill_diagonal(norm,0)\nplt.matshow(norm,cmap=plt.cm.gray)\nplt.show()", "_____no_output_____" ] ], [ [ "The lighter squares are common mistakes. ", "_____no_output_____" ] ], [ [ "a,b = 4,9\nXaa = Xtest[(ytest == a) & (pred == a)]\nXab = Xtest[(ytest == a) & (pred == b)]\nXba = Xtest[(ytest == b) & (pred == a)]\nXbb = Xtest[(ytest == b) & (pred == b)]", "_____no_output_____" ], [ "#Obtained from Aurelien Geron's Github\ndef plot_digits(instances, images_per_row=10, **options):\n size = 28\n images_per_row = min(len(instances), images_per_row)\n images = [instance.reshape(size,size) for instance in instances]\n n_rows = (len(instances) - 1) // images_per_row + 1\n row_images = []\n n_empty = n_rows * images_per_row - len(instances)\n images.append(np.zeros((size, size * n_empty)))\n for row in range(n_rows):\n rimages = images[row * images_per_row : (row + 1) * images_per_row]\n row_images.append(np.concatenate(rimages, axis=1))\n image = np.concatenate(row_images, axis=0)\n plt.imshow(image, cmap = mpl.cm.binary, **options)\n plt.axis(\"off\")\n", "_____no_output_____" ], [ "plot_digits(Xaa[:25], 5)", "_____no_output_____" ], [ "plot_digits(Xbb[:25], 5)", "_____no_output_____" ], [ "plot_digits(Xab[:25], 5)", "_____no_output_____" ], [ "plot_digits(Xba[:25], 5)", "_____no_output_____" ] ], [ [ "## Ensemble Learning and Random Forests\n\nSuppose you have 3 \"coins\" which flip heads 30% of the time and flip tails 70% of the time. Suppose you play a game: you flip the three coins and if at least two land heads, you mark H; otherwise you mark T. After playing this game 10000 times, how many Ts will you have? \n## ********* Participation Check ***************************\nThe `random.random()` function gives a \"uniform\" random number in the interval `[0,1)`. Write a function `flip` which calls `random.random()` and outputs `'H'` if the number is less than .3 and outputs `'T'` otherwise. \n\nUse `flip` to model the above game and get an approximate answer.", "_____no_output_____" ] ], [ [ "import random\ndef flip():\n n = random.random()\n if n < .3:\n return('H')\n else:\n return('T')\nflip()", "_____no_output_____" ], [ "tails = 0\nfor i in range(10000):\n a,b,c = flip(),flip(),flip()\n t = 0\n for i in (a,b,c):\n if i == 'H':\n t+=1\n if t<=1:\n tails+=1\ntails\n ", "_____no_output_____" ] ], [ [ "## *******************************************************", "_____no_output_____" ], [ "The above game is the core idea behind ensemble learning. If you have one model which is correct 90% of the time, you can try to make other models which are \"independent\" and combine them using majority rules. This can have dramatic effects on your predictive power, while simultaneously *reducing* your risk of overfitting!\n\nThe `RandomForestClassifier` essentially does this using decision trees. They create a bunch (100) of decision trees, throw them *all* at the problem simultaneously, and then see which guess seems the best:", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\nforest = RandomForestClassifier(random_state = 42)\nforest.fit(Xtrain, ytrain)", "_____no_output_____" ], [ "pred = forest.predict(Xtest)\ncm = confusion_matrix(ytest,pred)", "_____no_output_____" ], [ "cm", "_____no_output_____" ], [ "sum([cm[i,j] for i in range(10) for j in range(10) if i-j])", "_____no_output_____" ], [ "sums = cm.sum(axis=1,keepdims=True)\nnorm = cm/sums", "_____no_output_____" ], [ "np.fill_diagonal(norm,0)\nplt.matshow(norm,cmap=plt.cm.gray)\nplt.show()", "_____no_output_____" ] ], [ [ "## What's Next\n\nDecision Trees and Random Forests are *incredibly powerful* and *approachable* tools. As of 2019, Uber (a somewhat large Taxi service) was using these all over the place: https://eng.uber.com/productionizing-distributed-xgboost/ . If you are serious about ML, this is a great model to really dig into.\n\nIf you are *really* serious about ML, then after this you should learn about neural networks (and in particular, convolutional neural networks). One day you might work on something that does this: https://www.youtube.com/watch?v=HS1wV9NMLr8 !", "_____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" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
ec4da341ac4c22c9ba88fbb4f8757ad040947153
8,620
ipynb
Jupyter Notebook
docs/presentation/presentation.ipynb
fuodorov/yacinema
43ad869575fbaab7c7056229538638666aa87110
[ "MIT" ]
null
null
null
docs/presentation/presentation.ipynb
fuodorov/yacinema
43ad869575fbaab7c7056229538638666aa87110
[ "MIT" ]
null
null
null
docs/presentation/presentation.ipynb
fuodorov/yacinema
43ad869575fbaab7c7056229538638666aa87110
[ "MIT" ]
1
2021-09-30T09:49:40.000Z
2021-09-30T09:49:40.000Z
30.13986
441
0.619838
[ [ [ "# ЕТЛ на стероидах в стриминговом сервисе\n\n\n## Дипломная работа по курсу \"Мидл питон-разработчик\"\n\n\n#### Выполнили [Вячеслав Федоров](https://github.com/fuodorov) и [Егор Петров](https://github.com/bigdatacon) в 2022 году", "_____no_output_____" ], [ "## Проблематика", "_____no_output_____" ], [ "### В каком формате передаются «сырые» фильмы?\n\nВ межстудийном обмене обычно используется формат MXF. Видео может быть представлено совсем в сыром виде, например, передаётся каждый кадр. Это всё зажимается в код, который называется PEG 2000 — считается, что он без потерь. Там нет никакого потокового видеосжатия, просто лежит кадр за кадром.\n\nТакие файлы весят от 100 гигабайт до 1 терабайта.", "_____no_output_____" ], [ "### Что значит «потоковое сжатие»?\nЛюбое видео — это последовательность картинок с подложенной под неё аудиодорожкой. Но если просто передавать эти картинки, то видеофайлы будут огромными. Чтобы их уменьшить, используют различные алгоритмы сжатия.\n\nНапример, может быть такой алгоритм:\n\n* Если у нас видео со скоростью 25 кадров в секунду, мы назначаем опорным каждый 25-й кадр. Опорные кадры мы передаём полностью. \n* Все остальные неопорные кадры мы анализируем: что в следующем кадре изменилось относительно предыдущего. Если что-то изменилось, мы это кодируем и передаём. Если не изменилось, мы это не кодируем и не передаём. \n* Получается, что между опорными кадрами передаётся только то, что изменилось. Этих данных может быть много, а может быть и мало. ", "_____no_output_____" ], [ "### Как происходит кодирование? Что такое кодек? \n\nДальше в дело вступает система управления контентом. Нужно завести запись в базе данных, что это такой-то фильм, его снял такой-то режиссёр, в нём играют такие-то актёры. \n\n<!-- У нас есть специальная ферма для транскодирования файлов, туда заводится задача: вот исходные файлы, их нужно скодировать для таких-то выходных устройств. У фермы постоянно идёт какой-то поток, она постоянно всё кодирует — этот файл встаёт в очередь. Когда до него доходит дело, ферма забирает его к себе и там его транскодирует. -->", "_____no_output_____" ], [ "**Что такое «транскодирует»?** Исходный файл, который у нас есть, ни один мобильный телефон, ни один телевизор никогда в жизни не проиграет — он слишком хорош для этих устройств. Для того чтобы это стало возможным, для того чтобы просто сам видеокодек сложился, контейнер был понятен, — для этого нужно преобразовать этот крутой файл в понятные для устройств видеофайлы.", "_____no_output_____" ], [ "**Кодек** — это формат сжатия для видео. Это такая инструкция, что нужно делать со входящим потоком данных, чтобы его уменьшить. Но при этом когда декодирующее устройство его обратно развернёт, оно сможет вывести на экран картинку, и мы будем видеть как будто бы всё то же самое.", "_____no_output_____" ], [ "## Компоненты сервиса", "_____no_output_____" ], [ "<img src=\"img/architecture.png\" width=\"400\" height=\"600\">", "_____no_output_____" ], [ "## S3 Storage\n\n**MinIO** - Это опенсорсное объектное хранилище, совместимое с Amazon S3 API. Выпускается под лицензией Apache v2 и придерживается философии спартанского минимализма.\n\nТо есть у него нет развесистого GUI с дашбордами, графиками и многочисленными меню. MinIO просто запускает свой сервер одной командой, на котором можно просто хранить данные, используя всю мощь S3 API. ", "_____no_output_____" ], [ "<img src=\"img/minio.png\" width=\"400\" height=\"600\">", "_____no_output_____" ], [ "## Movies Streaming Admin\n\n**Django Admin** — это готовый CRUDL интерфейс с поиском, фильтрами и хитрыми настройками.", "_____no_output_____" ], [ "<img src=\"img/admin.png\" width=\"400\" height=\"600\">", "_____no_output_____" ], [ "## Movies Streaming API\n\n**Django Rest Framework (DRF)** — это библиотека, которая работает со стандартными моделями Django для создания гибкого и мощного API для проекта. ", "_____no_output_____" ], [ "<img src=\"img/drf.png\" width=\"400\" height=\"600\">", "_____no_output_____" ], [ "## Movies Streaming Converter\n\n**FFmpeg** - набор свободных библиотек с открытым исходным кодом, которые позволяют записывать, конвертировать и передавать цифровые аудио- и видеозаписи в различных форматах. Он включает libavcodec — библиотеку кодирования и декодирования аудио и видео, и libavformat — библиотеку мультиплексирования и демультиплексирования в медиаконтейнер. Название происходит от названия экспертной группы MPEG и FF, означающего «fast forward».\n\n**FastAPI** - относительно новый веб-фреймворк, написанный на языке программирования Python для создания REST (а если сильно постараться то и GraphQL) API, основанный на новых возможностях Python 3.6+, таких как: подсказки типов (type-hints), нативная асинхронность (asyncio). Помимо всего прочего, FastAPI плотно интегрируется с OpenAPI-schema и автоматически генерирует документацию для вашего API посредством Swagger и ReDoc.", "_____no_output_____" ], [ "<img src=\"img/fastapi.png\" width=\"400\" height=\"600\">", "_____no_output_____" ], [ "## Airflow ETL\n\n**Apache Airflow** - это открытое программное обеспечение для создания, мониторинга и оркестрации сценариев обработки данных.", "_____no_output_____" ], [ "<img src=\"img/airflow.png\" width=\"400\" height=\"600\">", "_____no_output_____" ], [ "**Источники:**\n* [Как устроены онлайн-кинотеатры: техническая сторона](https://thecode.media/zapusk-kino/)\n* [What are microservices?](https://microservices.io/)\n* [MinIo для самых маленьких](https://habr.com/ru/company/veeam/blog/517392/)\n* [Apache Airflow: делаем ETL проще](https://habr.com/ru/post/512386/)", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ec4daac97325d844b56041c2f75653aef809a71b
15,646
ipynb
Jupyter Notebook
Array_manipulation_routines.ipynb
ncondo/numpy_exercises
97006422b419928c0fea6983caf64608ea2f2dbf
[ "MIT" ]
null
null
null
Array_manipulation_routines.ipynb
ncondo/numpy_exercises
97006422b419928c0fea6983caf64608ea2f2dbf
[ "MIT" ]
null
null
null
Array_manipulation_routines.ipynb
ncondo/numpy_exercises
97006422b419928c0fea6983caf64608ea2f2dbf
[ "MIT" ]
1
2020-01-22T21:51:58.000Z
2020-01-22T21:51:58.000Z
21.229308
138
0.376071
[ [ [ "# Array manipulation routines", "_____no_output_____" ] ], [ [ "import numpy as np", "_____no_output_____" ], [ "np.__version__", "_____no_output_____" ] ], [ [ "Q1. Let x be a ndarray [10, 10, 3] with all elements set to zero. Reshape x so that the size of the second dimension equals 150.", "_____no_output_____" ], [ "Q2. Let x be array [[1, 2, 3], [4, 5, 6]]. Convert it to [1 4 2 5 3 6].", "_____no_output_____" ], [ "Q3. Let x be array [[1, 2, 3], [4, 5, 6]]. Get the 5th element.", "_____no_output_____" ], [ "Q4. Let x be an arbitrary 3-D array of shape (3, 4, 5). Permute the dimensions of x such that the new shape will be (4,3,5).\n", "_____no_output_____" ], [ "Q5. Let x be an arbitrary 2-D array of shape (3, 4). Permute the dimensions of x such that the new shape will be (4,3).", "_____no_output_____" ], [ "Q5. Let x be an arbitrary 2-D array of shape (3, 4). Insert a nex axis such that the new shape will be (3, 1, 4).", "_____no_output_____" ], [ "Q6. Let x be an arbitrary 3-D array of shape (3, 4, 1). Remove a single-dimensional entries such that the new shape will be (3, 4).", "_____no_output_____" ], [ "Q7. Lex x be an array <br/>\n[[ 1 2 3]<br/>\n[ 4 5 6].<br/><br/>\nand y be an array <br/>\n[[ 7 8 9]<br/>\n[10 11 12]].<br/>\nConcatenate x and y so that a new array looks like <br/>[[1, 2, 3, 7, 8, 9], <br/>[4, 5, 6, 10, 11, 12]].\n", "_____no_output_____" ], [ "Q8. Lex x be an array <br/>\n[[ 1 2 3]<br/>\n[ 4 5 6].<br/><br/>\nand y be an array <br/>\n[[ 7 8 9]<br/>\n[10 11 12]].<br/>\nConcatenate x and y so that a new array looks like <br/>[[ 1 2 3]<br/>\n [ 4 5 6]<br/>\n [ 7 8 9]<br/>\n [10 11 12]]\n", "_____no_output_____" ], [ "Q8. Let x be an array [1 2 3] and y be [4 5 6]. Convert it to [[1, 4], [2, 5], [3, 6]].", "_____no_output_____" ], [ "Q9. Let x be an array [[1],[2],[3]] and y be [[4], [5], [6]]. Convert x to [[[1, 4]], [[2, 5]], [[3, 6]]].", "_____no_output_____" ], [ "Q10. Let x be an array [1, 2, 3, ..., 9]. Split x into 3 arrays, each of which has 4, 2, and 3 elements in the original order.", "_____no_output_____" ], [ "Q11. Let x be an array<br/>\n[[[ 0., 1., 2., 3.],<br/>\n [ 4., 5., 6., 7.]],<br/>\n \n [[ 8., 9., 10., 11.],<br/>\n [ 12., 13., 14., 15.]]].<br/>\nSplit it into two such that the first array looks like<br/>\n[[[ 0., 1., 2.],<br/>\n [ 4., 5., 6.]],<br/>\n \n [[ 8., 9., 10.],<br/>\n [ 12., 13., 14.]]].<br/>\n \nand the second one look like:<br/>\n \n[[[ 3.],<br/>\n [ 7.]],<br/>\n \n [[ 11.],<br/>\n [ 15.]]].<br/> ", "_____no_output_____" ], [ "Q12. Let x be an array <br />\n[[ 0., 1., 2., 3.],<br>\n [ 4., 5., 6., 7.],<br>\n [ 8., 9., 10., 11.],<br>\n [ 12., 13., 14., 15.]].<br>\nSplit it into two arrays along the second axis.", "_____no_output_____" ], [ "Q13. Let x be an array <br />\n[[ 0., 1., 2., 3.],<br>\n [ 4., 5., 6., 7.],<br>\n [ 8., 9., 10., 11.],<br>\n [ 12., 13., 14., 15.]].<br>\nSplit it into two arrays along the first axis.", "_____no_output_____" ], [ "Q14. Let x be an array [0, 1, 2]. Convert it to <br/>\n[[0, 1, 2, 0, 1, 2],<br/>\n [0, 1, 2, 0, 1, 2]].", "_____no_output_____" ], [ "Q15. Let x be an array [0, 1, 2]. Convert it to <br/>\n[0, 0, 1, 1, 2, 2].", "_____no_output_____" ], [ "Q16. Let x be an array [0, 0, 0, 1, 2, 3, 0, 2, 1, 0].<br/>\nremove the leading the trailing zeros.", "_____no_output_____" ], [ "Q17. Let x be an array [2, 2, 1, 5, 4, 5, 1, 2, 3]. Get two arrays of unique elements and their counts.\n", "_____no_output_____" ], [ "Q18. Lex x be an array <br/>\n[[ 1 2]<br/>\n [ 3 4].<br/>\nFlip x along the second axis.", "_____no_output_____" ], [ "Q19. Lex x be an array <br/>\n[[ 1 2]<br/>\n [ 3 4].<br/>\nFlip x along the first axis.", "_____no_output_____" ], [ "Q20. Lex x be an array <br/>\n[[ 1 2]<br/>\n [ 3 4].<br/>\nRotate x 90 degrees counter-clockwise.", "_____no_output_____" ], [ "Q21 Lex x be an array <br/>\n[[ 1 2 3 4]<br/>\n [ 5 6 7 8].<br/>\nShift elements one step to right along the second axis.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ec4dad6ee9f7987a0b700b68b138df579e818bd0
2,268
ipynb
Jupyter Notebook
Notebooks/09.ipynb
clementmlay/Python4Bioinformatics2020
2ff25365464978506fd7f724c402bef748250ad5
[ "CC-BY-4.0" ]
3
2019-07-14T08:26:45.000Z
2020-01-08T13:28:54.000Z
Notebooks/09.ipynb
clementmlay/Python4Bioinformatics2020
2ff25365464978506fd7f724c402bef748250ad5
[ "CC-BY-4.0" ]
1
2019-03-19T10:03:57.000Z
2019-03-19T10:03:57.000Z
Notebooks/09.ipynb
clementmlay/Python4Bioinformatics2020
2ff25365464978506fd7f724c402bef748250ad5
[ "CC-BY-4.0" ]
33
2019-02-27T13:58:21.000Z
2021-07-05T08:30:41.000Z
36.580645
212
0.658289
[ [ [ "<small><small><i>\nIntroduction to Python for Bioinformatics - available at https://github.com/kipkurui/Python4Bioinformatics.\n</i></small></small>\n\n\n## Reproducible Bioinformatics Research\n\nHow can we use Jupyter Notebooks, Conda environments, Bioconda Channel and GitHub to ensure reproducible Bioinformatics Research? To explore these topics, we'll use various Open learning resource online:\n- [Bioinformatics best practices](https://github.com/griffithlab/rnaseq_tutorial/wiki/Bioinformatics-Best-Practices)\n- [Bioconda promises to ease bioinformatics software installation woes](http://blogs.nature.com/naturejobs/2017/11/03/techblog-bioconda-promises-to-ease-bioinformatics-software-installation-woes/)\n- Read the paper: [Bioconda: A sustainable and comprehensive software distribution for the life sciences](https://doi.org/10.1101/207092)\n\n\n### 1. Conda environments\nWe've seen how you can create a conda environment. But how can you ensure someone else reproduces your set up? We'll also learn how to create environments for different projects. \n\n### 2. Bioconda Chanel\n\nHere, we'll explore some of the useful Bioinformatics packages in this channel, and how we can use them to conduct reproducible research. \n\n\n### 3. GitHub\nYou have a reproducible environment and research notebook, how can your version and make your research accessible by others? This will be a quick introduction to version control with Git and GitHub.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
ec4db215c16d056e3c45aa45e33cf4919f86d037
17,226
ipynb
Jupyter Notebook
04-More-lists.ipynb
JanaLasser/python-introduction
be5b22c65b2ea35ea415f013b4d51a2539b06319
[ "CC-BY-4.0" ]
2
2019-03-05T07:23:26.000Z
2020-06-08T02:41:48.000Z
04-More-lists.ipynb
JanaLasser/python-introduction
be5b22c65b2ea35ea415f013b4d51a2539b06319
[ "CC-BY-4.0" ]
null
null
null
04-More-lists.ipynb
JanaLasser/python-introduction
be5b22c65b2ea35ea415f013b4d51a2539b06319
[ "CC-BY-4.0" ]
null
null
null
23.76
218
0.535586
[ [ [ "<a name=\"top\"></a>Overview:More lists\n===", "_____no_output_____" ], [ "* [Operations on lists](#operationen)\n * [Adding elements](#hinzufügen)\n * [Removing elements](#entfernen)\n * [Empty lists](#leer)\n * [Sorting](#sortieren)\n * [Reverting](#umkehren)\n * [min, max, sum](#functionalitaet)\n \n \n* [Create lists](#erzeugen) \n * [The range() function](#range)\n * [List comprehension](#comprehensions)\n \n \n* [Exercise 04: More lists](#uebung04) ", "_____no_output_____" ], [ "**Learning goals:** At the end of this lesson you will\n* know how to add elements to lists, remove elements from lists and sort lists\n* know how to automatically create lists of numbers\n* understand how to use list comprehension to elegantly create complicated lists ", "_____no_output_____" ], [ "<a name=\"operationen\"></a>Operations on lists\n===", "_____no_output_____" ], [ "##### Modifying elements", "_____no_output_____" ], [ "As you have seen already, we can modify the elements of a list after it has been created:", "_____no_output_____" ] ], [ [ "# create a list\nanimals = ['cat', 'dog', 'bird', 'horse']\nprint(animals)\n\n# assign a new value to the element 2 of the list\nanimals[2] = 'penguin'\nprint(animals)", "_____no_output_____" ] ], [ [ "<a name=\"hinzufuegen\"></a>Adding elements\n---", "_____no_output_____" ], [ "If you want to add items to a list you can use\n* **insert()** to add an item at a certain position (elements after it get shifted backwards)\n* **append()** to add an item to the end of the list\n* **extend()** to append another list to your list", "_____no_output_____" ] ], [ [ "# create two new example lists\nstrings = ['a', 'b', 'c']\nnumbers = [1, 2, 3]", "_____no_output_____" ], [ "print(strings)\n# add a new element to strings at position 2\nstrings.insert(2, 'z')\nprint(strings)", "_____no_output_____" ], [ "print(numbers)\n# append an element to numbers\nnumbers.append(10)\nprint(numbers)", "_____no_output_____" ], [ "# append the list numbers to the list strings\nstrings.extend(numbers)\nprint(strings)", "_____no_output_____" ], [ "numbers.extend(strings)\nprint(numbers)", "_____no_output_____" ] ], [ [ "<a name=\"entfernen\"></a>Removing elements\n---", "_____no_output_____" ], [ "If you want to remove items from a list, you can use\n* **remove()** to remove a certain item by value\n* **del** to remove an item at a certain index\n* **pop()** to remove and return the last item in the list", "_____no_output_____" ] ], [ [ "# create a new list\nthings = ['rock', 'flower', 'photo', 'pc', 'cake', 'stone']\nprint(things)\n\n# remove the element with the value 'stone'\n# from the list\nthings.remove('stone')\nprint(things)", "_____no_output_____" ], [ "# remove the element at index 0\ndel things[0]\nprint(things)", "_____no_output_____" ], [ "# remove the last element of the list\n# we get it as a return value, so we save it\nlast_element = things.pop()\n\n# things now only has three elements left\nprint(things)\n# 'cake' is saved in last_element\nprint(last_element)", "_____no_output_____" ] ], [ [ "[top](#top)", "_____no_output_____" ], [ "<a name=\"leer\"></a>Empty lists\n---", "_____no_output_____" ], [ "Sometimes it can be useful to initialize an empty list that can be filled with items later on.", "_____no_output_____" ] ], [ [ "# we create a filled list\nletters = ['a', 'b', 'c', 'd']\n\n# and an empty list\nalphabet = []\n\n# we fill alphabet by using a for loop\nfor letter in letters:\n alphabet.append(letter + letter)\n \nprint(alphabet)", "_____no_output_____" ], [ "empty_list = []\nprint(len(empty_list))", "_____no_output_____" ] ], [ [ "[top](#top)", "_____no_output_____" ], [ "<a name=\"sortieren\"></a>Sorting\n---", "_____no_output_____" ], [ "We can automatically sort lists based on their elements by using the ```sort()``` function. \nThis only works if relations to sort the elements are actually sensible (e.g. _larger_, _smaller_, _equal_).\nIf not told otherwise, Python will sort strings alphabetically and numbers in ascending order. ", "_____no_output_____" ] ], [ [ "# create an unordered list\nletters = ['b','a','z','c','y']\nprint('original: {}'.format(letters))\n\n# sort the list\nletters.sort()\nprint('alphabetically sorted: {}'.format(letters))", "_____no_output_____" ] ], [ [ "**IMPORTANT:** The order of the elements is changed _permanently_ and the initial ordering is lost!", "_____no_output_____" ], [ "If you do not want this, use the ```sorted()``` function instead:", "_____no_output_____" ] ], [ [ "# using sorted()\n\nletters = ['b','a','z','c','y']\n# Print the letters in alphabetical order but keep the original order\nprint('Letters in alphabetical order')\nfor letter in sorted(letters):\n print(letter)\n \nprint('\\nLetters in reverse alphabetical order') \n# Print the letters in reverse alphabetical order but keep original order\nfor letter in sorted(letters, reverse=True):\n print(letter)\n \nprint('\\nOriginal list order') \n# Show that the original order is preserved\nfor letter in letters:\n print(letter)", "_____no_output_____" ] ], [ [ "[top](#top)", "_____no_output_____" ], [ "<a name=\"umkehren\"></a>Reverse\n---", "_____no_output_____" ], [ "We already saw that we can sort lists in reversed order as well. \nFor ease of writing, there is a function, which does this directly - ```reverse()```:", "_____no_output_____" ] ], [ [ "# create a list\nnumbers = [10, 2, 5, 3]\nprint('original: {}'.format(numbers))\n\n# sort it in ascending order\nnumbers.sort()\nprint('ascending: {}'.format(numbers))\n\n# reverse the order\nnumbers.reverse()\nprint('descending: {}'.format(numbers))", "_____no_output_____" ] ], [ [ "[top](#top)", "_____no_output_____" ], [ "<a name=\"funktionalitaet\"></a>Min, max, sum\n---", "_____no_output_____" ], [ "For lists containing only numbers, we have some special helper functions:\n* **min()** returns the smallest item in a list\n* **max()** returns the largest item in a list\n* **sum()** returns the sum of all items in the list", "_____no_output_____" ] ], [ [ "# create a list\nnumbers = [5, 1, 3, 10, 8, 14, 10]\n\n# find the minimum\nminimum = min(numbers)\n\n# find the maximum\nmaximum = max(numbers)\n\n# calculate the sum\nsum = sum(numbers)\n\nprint('Minimum: {}, maximum: {}, sum: {}'\\\n .format(minimum, maximum, sum))", "_____no_output_____" ] ], [ [ "[top](#top)", "_____no_output_____" ], [ "<a name=\"comprehensions\"></a>Create lists\n===", "_____no_output_____" ], [ "<a name=\"range\"></a>The range() function\n---", "_____no_output_____" ], [ "Creating more complicated lists manually is tedious and takes way too long. For lists containing numbers, there is the ```range()``` function, which automatically creates a list. \nThis function takes the same arguments we used in slicing: _start_, _end_ and _stepsize_ of the list of numbers:", "_____no_output_____" ] ], [ [ "# display all even numbers from 0 to 15\nfor number in range(0, 15, 2):\n print(number)", "_____no_output_____" ] ], [ [ "We can save these numbers into a list:", "_____no_output_____" ] ], [ [ "# create an empty list\neven_numbers = []\n\n# for every iteration of the loop\n# append an element to the list\nfor number in range(0, 15, 2):\n even_numbers.append(number)\n\nprint(even_numbers)", "_____no_output_____" ] ], [ [ "An easier way to do this is by converting the output of ```range()``` to a list. To do this, we can use the ```list()``` function:", "_____no_output_____" ] ], [ [ "# list() converts an iterable container to a list\neven_numbers = list(range(0, 15, 2))\nprint(even_numbers)", "_____no_output_____" ] ], [ [ "[top](#top)", "_____no_output_____" ], [ "<a name=\"comprehensions\"></a>List comprehensions\n---", "_____no_output_____" ], [ "If we want to create a list, that cannot be described using the ```range()``` function, there is one more alternative.\nWe can define lists by using loops and expressions inside square brackets, this is called _list comprehension_:", "_____no_output_____" ] ], [ [ "squares = [number ** 2 for number in range(0, 15, 2)]\nprint(squares)", "_____no_output_____" ] ], [ [ "What did just happen?\n* the part after the **for** keyword initializes a loop that runs ten times and returns the next number every time\n* the part before the **for** keyword performs an operation on the number (in this case we square the number)\n* the square brackets \"channel\" the results into a list which is then assigned to the variable ```squares```", "_____no_output_____" ], [ "List comprehension is a quite powerful and very elegant way of creating lists. \nHowever, the concept is a bit hard to understand, so let's look at a few more examples:", "_____no_output_____" ] ], [ [ "# create a new list containing the numbers 0 to 9\nnumbers = [number for number in range(0,10,1)]\nprint(numbers)\n\n# divide each number by 2 and save in a new list\nhalves = [number / 2 for number in numbers]\nprint(halves)", "_____no_output_____" ], [ "# start at the same list, and add 2 to every number\nnumbers = list(range(10))\nplus_two = [number + 2 for number in numbers]\nprint(plus_two)", "_____no_output_____" ], [ "# fun with strings\nnames = ['Jana', 'Katrin']\nnarcissists = [name + ' the Great' for name in names]\nprint(narcissists)", "_____no_output_____" ] ], [ [ "[top](#top)", "_____no_output_____" ], [ "<a name=\"uebung04\"></a>Exercise 04: More lists\n===", "_____no_output_____" ], [ "2. **Operations on lists**\n 1. Create a list of first names. Start with a list containing your own name, then fill it with the names of at least five more members of the course, using ```append()```, ```insert()``` and ```extend()```.\n 2. Create a second, empty list. Iterate over the names list using ```for``` and ```enumerate()```. Multiply each name with its index and save the results in the empty list.\n 3. **(Optional)** Display both the length and the number of characters in the list together.\n Hint: Strings themselves are collections of characters, you can find their length using ```len()```.\n 4. **(Optional)** Create a list of the first 50 even numbers using the ```range()``` function. Calculate the sum of all these numbers, once using a ```for``` loop and once using the ```sum()``` function.\n \n \n3. **Create lists**\n 1. Create a list of the first 10 numbers to the third power using list comprehension.\n 2. **(Optional)** Create a list of the first 100 elements of the Fibonacci sequence. Which problems do arise, if you try to use list comprehension for this exercise?", "_____no_output_____" ], [ "[top](#top)", "_____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" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
ec4db646db518024e6a5a9f875ead56bf93607e4
159,474
ipynb
Jupyter Notebook
metaGen.ipynb
nvk681/MetaGen
b2023e774332f846b43f352711bca05890a90b9b
[ "MIT" ]
null
null
null
metaGen.ipynb
nvk681/MetaGen
b2023e774332f846b43f352711bca05890a90b9b
[ "MIT" ]
null
null
null
metaGen.ipynb
nvk681/MetaGen
b2023e774332f846b43f352711bca05890a90b9b
[ "MIT" ]
null
null
null
218.757202
120,913
0.835164
[ [ [ "<h1> META GEN </h1>", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')\n%cd drive/MyDrive/dataset/", "Mounted at /content/drive\n/content/drive/MyDrive/dataset\n" ], [ "import sys\nsys.path.insert(0,'')", "_____no_output_____" ], [ "import os\nimport torch\nimport numpy as np\nfrom PIL import Image\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torchvision.models as models\nimport torchvision.transforms as transforms\nimport json\nimport time\nfrom shutil import copyfile\nimport pickle\nimport argparse\nfrom Decoder import RNN\nfrom utils import get_cnn\nimport matplotlib.pyplot as plt\nfrom Vocabulary import Vocabulary\nfrom torchvision import transforms\nfrom torch.autograd import Variable\nfrom Preprocess import load_captions\nfrom DataLoader import shuffle_data,DataLoader", "_____no_output_____" ], [ "\n# def read_captions(filepath):\n# \tcaptions_dict = {}\n# \twith open(filepath) as f:\n# \t\tfor line in f:\n# \t\t\tline_split = line.split(sep='\\t', maxsplit=1)\n# \t\t\tcaption = line_split[1][:-1]\n# \t\t\tid_image = line_split[0].split(sep='#')[0]\n# \t\t\tif id_image not in captions_dict:\n# \t\t\t\tcaptions_dict[id_image] = [caption]\n# \t\t\telse:\n# \t\t\t\tcaptions_dict[id_image].append(caption)\n# \treturn captions_dict\n\n# def get_ids(filepath):\n# \tids = []\n# \twith open(filepath) as f:\n# \t\tfor line in f:\n# \t\t\tids.append(line[:-1])\n# \treturn ids\n\n# def copyfiles(dir_output, dir_input, ids):\n# \tif not os.path.exists(dir_output):\n# \t\tos.makedirs(dir_output)\n# \tfor cur_id in ids:\n# \t\tpath_input = os.path.join(dir_input, cur_id)\n# \t\tpath_output = os.path.join(dir_output, cur_id)\n# \t\ttry:\n# \t\t copyfile(path_input, path_output)\n# \t\texcept OSError:\n# \t\t print(\"File error\") \n\n# def write_captions(dir_output, ids, captions_dict):\n# \toutput_path = os.path.join(dir_output, 'captions.txt')\n# \toutput = []\n# \tfor cur_id in ids:\n# \t\tif cur_id in captions_dict:\n# \t\t\tcur_dict = {cur_id: captions_dict[cur_id]}\n# \t\t\toutput.append(json.dumps(cur_dict))\n\t\t\n# \twith open(output_path, mode='w') as f:\n# \t\tf.write('\\n'.join(output))\n\n# def segregate(dir_images, filepath_token, captions_path_input):\n# \tdir_output = {'train': 'train',\n# \t\t\t\t 'dev' : 'dev',\n# \t\t\t\t 'test' : 'test'\n# \t\t\t\t }\n\t\n# \t# id [caption1, caption2, ..]\n# \tcaptions_dict = read_captions(filepath_token)\n\t\n# \t# train, dev, test images mixture\n# \timages = os.listdir(dir_images)\n\t\n# \t# read ids\n# \tids_train = get_ids(captions_path_input['train'])\n# \tids_dev = get_ids(captions_path_input['dev'])\n# \tids_test = get_ids(captions_path_input['test'])\n\t\n# \t# copy images to respective dirs\n# \tcopyfiles(dir_output['train'], dir_images, ids_train)\n# \tcopyfiles(dir_output['dev'], dir_images, ids_dev)\n# \tcopyfiles(dir_output['test'], dir_images, ids_test)\n\t\n# \t# write id\n# \twrite_captions(dir_output['train'], ids_train, captions_dict)\n# \twrite_captions(dir_output['dev'], ids_dev, captions_dict)\n# \twrite_captions(dir_output['test'], ids_test, captions_dict)\n\n# def load_captions(captions_dir):\n# \tcaption_file = os.path.join(captions_dir, 'captions.txt')\n# \tcaptions_dict = {}\n# \twith open(caption_file) as f:\n# \t\tfor line in f:\n# \t\t\tcur_dict = json.loads(line)\n# \t\t\tfor k, v in cur_dict.items():\n# \t\t\t\tcaptions_dict[k] = v\n# \treturn captions_dict\n\n\n# dir_images = 'Images/Images/'\n# dir_text = ''\n# filename_token = 'Flickr8k.token.txt'\n# filename_train = 'Flickr_8k.trainImages.txt'\n# filename_dev = 'Flickr_8k.devImages.txt'\n# filename_test = 'Flickr_8k.testImages.txt'\n# filepath_token = os.path.join(dir_text, filename_token)\n# captions_path_input = {'train': os.path.join(dir_text, filename_train),\n# 'dev': os.path.join(dir_text, filename_dev),\n# 'test': os.path.join(dir_text, filename_test)\n# }\n\n# tic = time.time()\n# segregate(dir_images, filepath_token, captions_path_input)\n# toc = time.time()\n# print('time: %.2f mins' %((toc-tic)/60))", "_____no_output_____" ], [ "import nltk\nnltk.download('punkt')\nfrom nltk import sent_tokenize", "[nltk_data] Downloading package punkt to /root/nltk_data...\n[nltk_data] Unzipping tokenizers/punkt.zip.\n" ], [ "!python3 train.py -model alexnet -dir train/ -learning_rate 0.1 -epoch 1 #-gpu_device cuda", "Encoder weights Before Training.\n\t\n\ttensor([[ -0.5912, 0.3807, 0.7248, 3.8631, -4.0232, 0.2902, 2.6744,\n 2.9090, -0.2879, -2.8480, 4.5226, -3.1988, -2.8707, 1.6673,\n 0.0601, -0.1299, -7.2960, 1.1182, -2.1403, -0.9099, -0.3911,\n 2.7462, -0.7151, 2.5459, 3.2461, 4.4592, 1.6634, 1.0245,\n -4.5441, -1.0346, 1.6151, 3.7989, 0.2332, 0.2511, 1.2676,\n 0.8533, 3.1740, 0.4307, -1.6192, -0.4018, -6.3081, -4.9989,\n -2.7386, 1.7115, 1.0030, -6.4031, 2.6466, 2.2951, -1.1721,\n 6.1803, 4.3363, 1.5759, -4.1148, -8.1341, 2.0834, 1.7308,\n -0.3298, -2.3669, 0.9915, 1.2312, 0.2921, -2.2881, -4.9219,\n -6.9575, -6.4164, -2.1182, -3.4381, -2.3937, 1.3420, 1.9593,\n 0.1828, -0.0978, 3.3830, 1.5351, -6.9165, 2.0801, -3.8999,\n 2.3808, 3.0052, -4.7453, 2.4001, 2.1260, -4.7021, 1.2000,\n -2.0036, 2.8681, 3.4930, 1.3096, 0.2760, 1.2664, 4.0359,\n 5.9710, 0.2023, 2.1426, -3.0804, 5.4040, -3.9353, -2.1692,\n 2.7039, 4.8669, -11.5148, -1.6841, -1.2221, -3.7869, -0.5418,\n 2.1890, -0.0688, -1.7607, 2.7029, -6.9122, 1.9325, -0.1247,\n 1.8183, -3.1773, 7.7863, 0.4839, 1.4411, 0.2668, -1.4796,\n 3.0497, 0.6809, -4.8180, 2.5539, -0.4796, -3.6932, 5.2657,\n -0.6019, -2.2411, -1.8788, 2.9912, 2.7483, 2.5908, 0.2282,\n 0.8191, 4.4095, 4.7099, 3.1748, -1.6877, -1.3790, -1.9699,\n 2.6332, 0.1141, 2.6754, -1.3771, 0.0323, 3.6221, -5.7189,\n 0.9218, 0.3353, -0.6186, 0.3159, -4.5138, 2.2575, 1.8419,\n 0.8402, -1.7990, 2.2779, -2.6587, 1.8521, -0.7179, 2.6579,\n 4.6631, -5.0550, 1.0985, -3.7382, -2.5633, 1.9376, -1.2044,\n 2.3542, -1.6011, -3.0396, 3.5772, 0.4517, -0.9860, 0.7606,\n 1.4327, 2.3587, -0.7981, -5.2104, -0.2009, -4.3623, 1.7885,\n 2.0351, 1.6519, -4.0684, 0.4667, -1.4826, 3.5244, -0.6289,\n -0.3497, 0.9586, -5.9489, 1.0754, -3.3148, 0.5806, 0.8608,\n 1.4955, -0.7242, 0.8928, 0.5788, 6.1394, 0.4830, -0.9054,\n -0.3675, -0.4510, -3.7168, 0.9870, 4.4756, 1.3452, -2.0148,\n 1.2528, 3.8476, -3.0387, 2.1471, -3.5348, -1.7552, -2.7299,\n 1.3011, 3.8016, 4.1304, 7.1276, 3.1310, -0.6211, -0.4140,\n 8.7846, -4.3151, -0.0563, 0.2739, -0.7783, -0.5975, 2.2605,\n 3.3288, -5.2263, 2.7691, 2.1155, -1.4247, -4.4035, 5.1817,\n -2.9676, -1.8971, 6.2708, 0.0634, 4.4040, 4.0756, 3.7321,\n 1.4549, 1.4652, 0.5997, -1.2207, -0.2114, -1.8518, 0.1691,\n -0.0668, -2.8777, -2.2917, -2.7720, -4.0276, 0.8726, 0.6744,\n -0.8013, 3.0244, -3.7990, 5.3024, 0.3269, 3.9981, -3.5410,\n 7.9413, 0.4378, -3.0489, 3.4967, 2.4617, -1.9956, 2.6149,\n -2.7354, 2.4851, -0.1572, -4.2164, 2.2959, 0.3722, 3.2984,\n -4.4835, 1.1262, -1.8348, 0.5496, 3.6649, -4.1614, 5.5110,\n 3.7002, -0.8123, -0.9346, -1.0496, -6.1244, -0.7058, -4.3442,\n -0.9646, -0.3275, -0.5705, -1.8826, -0.9378, -0.0526, 0.4563,\n -1.5454, 2.0341, -5.9810, 2.8551, 4.7416, -0.2470, -3.4968,\n -1.0899, -3.5911, -1.5745, -0.3748, -4.2448, 3.6712, -4.7885,\n 1.3390, -1.3827, 3.4364, 5.3393, -0.4554, -0.6945, -3.4177,\n -4.7603, 2.0646, -5.6674, 0.3928, 3.1144, -4.1029, -1.7793,\n 0.0921, -3.7049, 0.2515, 1.1208, -3.0514, -2.8965, 0.5481,\n -0.0407, -3.8018, -4.7511, -2.6136, 4.8912, 1.9162, 2.1156,\n 1.5942, -4.8338, -1.2737, 1.9568, 0.5290, -0.6505, -4.4469,\n 2.2162, -3.4679, -3.0896, -1.7554, -0.1661, -1.0771, -0.1431,\n -5.0109, -1.8089, -0.5806, 1.3195, -4.0926, -4.9405, -1.7577,\n 0.4287, 5.5744, 1.4856, 5.6122, -0.9958, -1.0088, 2.3757,\n -1.2869, -0.6829, 0.8234, -4.6994, -5.7878, 7.2020, 0.9021,\n 2.5678, -2.4490, -5.1234, 4.7679, 0.6067, 0.7037, -0.3227,\n -1.9816, -1.1136, -1.5240, -1.7788, -2.9306, 3.3562, -0.5886,\n 2.0734, 2.8949, 0.6973, 5.5722, -3.1806, 0.8041, 4.0589,\n -1.1390, -1.0075, 4.8622, 1.3149, -7.6322, 1.0949, -0.7999,\n 2.8020, 7.2111, -3.1884, 2.6887, 16.9426, 0.5545, 2.2649,\n -1.8697, 0.5064, 0.9058, -0.6923, -0.9588, 0.1044, 2.1496,\n -2.4290, 1.5912, 3.5606, 1.1205, 0.1937, 1.5385, 4.2716,\n 1.6597, -1.0022, -2.3394, 2.6644, 1.5718, 1.6877, 2.8401,\n 0.7947, 1.1404, -1.7146, 4.1398, -4.1482, -1.4598, 2.7297,\n 1.9254, -0.6370, 0.2449, 0.7195, -0.2201, 3.4867, 6.5405,\n 2.3056, 12.1613, 4.1905, -1.1496, -0.0372, -2.1264, -4.9628,\n 2.6942, -2.9289, 5.4163, -0.9910, -0.7571, -3.0526, 0.3535,\n -3.2401, -2.3565, -0.4530, 2.4160, -1.9177, 1.5313, -4.8731,\n 3.1096, -2.0639, 0.6592, 1.4353, -1.4145, -4.0063, -5.1448,\n 0.9442, 2.9718, 5.1533, -1.8196, -1.9817, -0.2755, 2.5216,\n 2.9195, -3.3503, -2.7388, 2.1440, 2.6611, 2.0166, -5.0440,\n 0.6078, 3.6950, -4.6553, -4.7422, -4.7453, 0.1338, -3.0895,\n 1.5717, -0.2730, 4.3929, -5.4225, -3.7655, -1.0626, -1.5258,\n 4.5668, 2.1658, 4.2405, 1.5462, 2.6615, -2.9172, 0.4375,\n -2.5940]])\n\t\t \n\n\nEncoder weights after Training.\n\n\t\t tensor([[ 1.4443e+00, -9.8663e-01, 3.4555e+00, 1.6410e+00, -1.7859e+00,\n 2.5617e+00, 4.1454e+00, -1.5077e-02, 6.1934e-01, -2.6958e+00,\n 6.4314e+00, -2.2688e+00, -2.9661e+00, 6.0185e+00, -1.1114e+00,\n 3.6157e+00, -9.4107e+00, 1.8479e+00, -3.0722e-01, 2.6225e-01,\n 3.8184e+00, 2.0053e+00, -3.5582e-01, 2.3485e+00, 2.1302e+00,\n 3.7854e+00, 2.4653e+00, 9.6644e-01, -5.3382e+00, 1.1629e-02,\n 2.7338e+00, 4.8054e+00, -5.4283e-01, -1.9037e+00, 1.5055e+00,\n 1.3744e+00, 3.8892e+00, 1.5558e+00, -2.2889e+00, -1.6505e+00,\n -6.8677e+00, -2.7093e+00, -1.9460e+00, 2.1466e+00, -2.9442e+00,\n -9.2881e+00, 5.9763e-01, 2.1858e+00, -2.2604e+00, 5.7145e+00,\n 5.1968e+00, 3.5552e+00, -2.1321e+00, -7.9221e+00, 2.2691e+00,\n 1.4785e+00, -8.9469e-01, -8.8677e-01, 1.0319e+00, 4.5455e+00,\n 3.9778e-02, -1.5205e+00, -5.0413e+00, -6.7791e+00, -5.0764e+00,\n -3.4902e+00, -2.3561e+00, -2.6521e+00, -1.5559e+00, 8.8187e-01,\n 3.5359e-01, -7.4654e-01, 2.1673e+00, 8.9101e-01, -5.3734e+00,\n 1.2212e+00, -2.0371e+00, 2.0498e+00, 3.5377e+00, -7.7206e+00,\n 2.4605e+00, 1.3537e+00, -3.8576e+00, 1.1273e-01, -4.2408e-02,\n 4.4686e+00, 3.2300e+00, 4.8839e+00, 1.3286e+00, 5.7129e+00,\n 3.2271e+00, 5.3706e+00, -3.8032e+00, 1.3408e+00, -3.2835e+00,\n 4.6707e+00, -3.6505e+00, -4.3448e-01, 1.8422e+00, 8.4251e+00,\n -1.2530e+01, -7.8202e-01, -1.5516e+00, -5.8842e+00, -1.8844e+00,\n 3.7528e+00, 6.8082e-01, -4.5184e+00, 3.5077e+00, -7.0292e+00,\n 1.2330e+00, 1.2910e+00, 1.9365e+00, -1.1134e+00, 7.8223e+00,\n -1.8689e+00, -1.2812e+00, 1.4097e+00, -1.3952e+00, 3.5438e+00,\n -2.3163e+00, -6.6232e+00, 1.3336e+00, 9.0335e-01, 8.0298e-03,\n 5.2568e+00, -2.8835e+00, -4.5612e+00, -4.6944e+00, 1.9383e+00,\n 2.6790e+00, 3.8375e+00, -7.9733e-01, -7.9038e-01, 1.7828e+00,\n 1.1511e+00, 3.1531e+00, -6.1060e-01, -8.1146e-02, -1.2276e+00,\n 4.9116e+00, -1.4171e+00, 1.7588e+00, -3.0027e+00, -1.2205e-01,\n 2.1546e+00, -5.7514e+00, -3.1313e-01, 9.6594e-01, -4.7120e+00,\n 9.2371e-01, -2.4547e+00, 4.4231e+00, 4.6455e+00, 4.7303e+00,\n -3.6213e-01, 5.9599e+00, -5.4800e+00, -6.4674e-02, -1.4835e+00,\n 2.6891e+00, 4.5520e+00, -3.2098e+00, -6.6648e-01, -1.4242e+00,\n -2.8031e+00, 2.0134e+00, 1.7400e-01, 3.3100e+00, -1.6615e+00,\n -5.4230e+00, 3.7659e+00, 4.0496e-01, -1.7251e+00, -2.4526e+00,\n 4.1027e+00, 2.4367e+00, 1.1498e+00, -4.4628e+00, -7.8675e-01,\n -2.8186e+00, 6.4509e-01, -1.6131e+00, 3.7707e-01, -6.5237e+00,\n -4.2676e-01, -2.3218e+00, 3.3645e+00, 2.0374e+00, 3.3585e-01,\n 2.2117e+00, -6.4012e+00, -1.8386e+00, -3.0938e+00, 1.2513e+00,\n 5.4848e-02, 3.6073e+00, 7.8061e-01, 1.4685e-01, 3.9214e-01,\n 7.6247e+00, -2.2226e+00, -6.7937e-01, 6.4205e-01, -4.9798e+00,\n -3.1345e+00, 1.5375e+00, 3.9561e+00, 1.9409e+00, -5.1613e-01,\n 4.3426e+00, 4.8374e+00, -9.1904e-01, 3.0923e-01, -3.2547e+00,\n -8.1425e-01, -1.9899e+00, -1.6858e-01, 1.8757e+00, 3.5131e+00,\n 8.8893e+00, 3.0297e+00, -1.2907e+00, -1.4621e-01, 8.4999e+00,\n -3.9291e+00, -3.7570e-01, 1.2653e+00, -4.3475e-01, -3.2408e-01,\n 1.7492e+00, 2.5440e+00, -3.7491e+00, 8.7468e-01, 1.4327e+00,\n 6.8967e-01, -2.3465e+00, 1.1380e+01, -5.3427e+00, -1.3555e+00,\n 4.7084e+00, 1.4724e-01, 5.7017e+00, 2.9266e+00, 4.5300e+00,\n 1.1441e+00, -9.3790e-02, 3.2714e+00, 5.4237e-02, 1.1530e+00,\n -2.4742e+00, 2.7335e+00, -2.1134e+00, -3.2671e+00, -3.0011e+00,\n -1.4133e+00, -4.8694e+00, 2.5238e+00, 1.0296e+00, -8.9715e-01,\n 2.2562e+00, -5.3110e+00, 3.4212e+00, -1.7094e+00, 2.3180e+00,\n -1.4603e+00, 8.7325e+00, -1.4402e+00, -2.1690e+00, 1.7565e+00,\n 4.3502e+00, -2.1808e+00, 7.3421e-01, -3.1728e-01, 3.8059e+00,\n 1.0026e+00, -3.9717e+00, 3.5409e+00, -1.2865e+00, 4.3172e+00,\n -4.9924e+00, 2.5211e+00, -2.4911e+00, 1.9627e+00, 4.1921e+00,\n -1.8150e+00, 6.0568e+00, 6.4322e+00, -5.8166e-01, 1.8035e+00,\n -1.2774e-01, -4.3791e+00, -1.9794e+00, -2.6178e+00, -1.1903e+00,\n -8.2914e-01, -2.6502e+00, -1.0553e+00, -1.6185e+00, -7.4214e-01,\n 3.7041e+00, -1.0805e+00, 3.1167e-01, -7.3557e+00, 4.6187e+00,\n -8.9857e-01, -1.8632e-01, -2.5905e+00, 2.5262e+00, -5.6118e+00,\n -1.8358e-01, -1.6218e-01, -5.1033e+00, 4.7489e+00, -6.9478e+00,\n 3.6104e-01, 8.3893e-01, 4.5072e+00, 4.0434e+00, 3.8605e+00,\n 1.5610e+00, -4.4541e+00, -3.6761e+00, 2.3230e+00, -4.7500e+00,\n 2.8951e-01, 2.3943e+00, -5.3914e+00, -3.1042e+00, -1.1809e+00,\n -8.8491e-01, -1.6119e-01, 8.9891e-01, 4.5161e-02, -1.8375e+00,\n 2.7826e-01, 3.4856e+00, -2.8745e+00, -3.0198e+00, -4.4086e+00,\n 4.3560e+00, -3.4087e-01, 7.0016e-01, 2.2979e+00, -7.7024e+00,\n -3.6983e+00, 5.7632e-02, -2.2698e-01, -1.5877e+00, -2.8113e+00,\n 5.9197e-01, -6.2158e+00, -5.5213e-01, -3.2625e+00, -1.4229e+00,\n -2.1732e+00, -2.9549e-01, -6.1459e+00, -3.1469e+00, 1.6329e-01,\n 2.2551e+00, -1.5306e+00, -6.3576e+00, -2.8408e+00, 1.9474e+00,\n 6.4535e+00, 1.2652e+00, 1.6385e+00, -3.8435e+00, -1.1026e+00,\n 3.4030e+00, 1.7124e-02, -5.9609e-01, 2.4425e+00, -2.6659e+00,\n -3.5884e+00, 9.3815e+00, -7.3229e-01, 2.4914e+00, -2.3197e+00,\n -5.7924e+00, 4.5231e+00, -4.7523e-01, 1.4597e+00, -2.1907e+00,\n -2.3717e+00, -4.2876e-01, -7.4771e-01, -2.5796e+00, -1.3091e+00,\n 4.7305e+00, 2.6609e-01, 6.0315e+00, 6.0156e+00, 1.9488e+00,\n 4.8925e+00, -3.2156e+00, 4.9433e-01, 2.3394e+00, -4.3080e-01,\n 4.6001e-01, 3.7578e+00, 1.7746e+00, -9.6773e+00, 1.1530e+00,\n -2.0145e+00, 4.4771e+00, 6.2724e+00, -1.3347e+00, 2.7018e+00,\n 1.5634e+01, 4.5334e-01, -2.2384e+00, -2.5541e+00, -3.2192e+00,\n 1.5025e+00, -1.4213e+00, -1.6136e+00, 6.7843e-01, 2.5778e+00,\n -5.0126e+00, -1.6720e+00, 3.3200e+00, 8.5229e-01, 3.9507e-01,\n -1.3569e+00, 5.8458e+00, -3.6913e+00, 2.3687e+00, -5.7382e+00,\n 4.1537e+00, 1.3269e+00, 4.1487e-01, 6.8198e+00, 8.4555e-01,\n 2.3453e+00, 3.5272e-01, 2.2521e+00, -3.8992e+00, -2.6025e+00,\n 3.4433e+00, 3.3510e+00, -2.8315e+00, 2.8595e-01, -1.9595e+00,\n 8.0315e-01, 5.3530e+00, 2.7269e+00, 8.4941e-02, 1.1479e+01,\n 6.1482e+00, -9.7601e-01, -1.6667e+00, -3.0847e+00, -7.8423e+00,\n 1.9897e+00, -6.3889e-01, 4.3811e+00, -2.3190e+00, 2.2290e+00,\n -2.3227e+00, -1.7250e+00, -2.2262e+00, -3.2058e+00, -5.9372e-01,\n 2.2582e+00, -1.1586e+00, 1.0951e+00, -5.0157e+00, 5.3792e+00,\n -1.2683e+00, -2.0553e+00, 2.2296e+00, 3.9529e-01, -6.2643e+00,\n -7.0105e+00, 2.7493e+00, 1.5043e+00, 9.2322e+00, 3.7259e-02,\n -2.4710e+00, -2.0631e+00, 4.7664e-01, 5.5598e+00, -4.2012e+00,\n -4.3738e+00, 9.3430e-01, 2.8690e+00, 2.5938e+00, -3.3477e+00,\n 2.2196e+00, 7.1553e+00, -4.8662e+00, -1.3476e+00, -8.9077e+00,\n -1.1467e+00, -9.2648e-01, -5.0309e-01, 1.1638e-01, 7.8141e+00,\n -8.3618e+00, -4.3419e+00, -8.9124e-01, -3.1910e+00, 6.4507e+00,\n 3.2408e+00, 5.4773e+00, 5.8220e+00, -5.6917e-01, -5.6932e+00,\n -1.4813e+00, -2.6221e+00]], grad_fn=<AddmmBackward0>)\n\t\t \n\t\t \n\t\tBefore Training\n\t\ttensor([[-0.1244, 0.1315, 0.0661, ..., -0.1880, 0.0619, 0.1923],\n [ 0.0582, 0.1083, 0.0724, ..., -0.0473, -0.1229, 0.0028],\n [-0.0135, 0.0029, 0.0904, ..., -0.0727, 0.0250, -0.0086],\n ...,\n [-0.1305, 0.0363, 0.0131, ..., -0.0118, -0.0341, -0.0602],\n [ 0.0506, 0.0794, -0.0023, ..., -0.1062, -0.0393, 0.0267],\n [-0.0366, 0.0010, -0.0024, ..., 0.0249, 0.0785, 0.0909]])\ntensor([[-0.0339, 0.0074, 0.0520, ..., 0.0260, -0.0275, 0.0462],\n [ 0.0380, 0.0039, 0.0047, ..., -0.0233, -0.0575, -0.0018],\n [ 0.0472, 0.0228, -0.0172, ..., 0.0252, 0.0103, 0.0579],\n ...,\n [-0.0473, -0.1047, -0.0036, ..., 0.0080, 0.0010, 0.0344],\n [-0.0164, 0.0775, -0.0560, ..., -0.0514, -0.0536, 0.0237],\n [-0.4230, 0.1320, 0.1296, ..., 0.3488, 0.1629, 0.0585]])\ntensor([[-2.1904e-01, 1.0868e-01, -3.9726e-02, ..., 6.4443e-02,\n 1.9599e-01, 5.0979e-01],\n [-3.7141e-01, -2.6424e-01, 1.7902e-01, ..., 9.6907e-02,\n 2.6566e-01, 1.6687e-01],\n [-9.2031e-02, -4.9747e-02, -8.3770e-02, ..., -6.1838e-02,\n -1.7571e-02, 4.7975e-01],\n ...,\n [-1.2032e-04, 2.4433e-02, -1.6205e-02, ..., -1.4476e-01,\n -9.4877e-03, 4.5122e-01],\n [-1.8429e-01, 7.1099e-02, -3.3708e-02, ..., 1.0065e-01,\n -5.3863e-02, 4.7419e-01],\n [ 2.7168e-01, 1.0249e-01, 1.8222e-02, ..., -9.2051e-03,\n -9.6114e-02, 9.7052e-02]])\ntensor([0.3604, 0.2980, 0.2943, ..., 0.5685, 0.4257, 0.1421])\ntensor([0.3442, 0.2909, 0.3706, ..., 0.4905, 0.4924, 0.1120])\ntensor([[ 3.1923e-01, 3.6727e-02, 6.3389e-03, ..., 2.7246e-01,\n 4.1735e-01, 7.4878e-01],\n [ 5.3054e-02, -2.5722e-01, -4.2290e-01, ..., -2.4636e-02,\n -3.3682e-01, -2.3221e+00],\n [-3.2128e-01, -1.7862e-02, -6.4748e-02, ..., -1.6890e-01,\n 2.7164e-01, -5.2044e-01],\n ...,\n [ 1.9204e-02, -2.9885e-01, -2.5085e-01, ..., -3.6804e-01,\n -3.6624e-01, -2.4778e+00],\n [ 3.4328e-02, -2.2383e-01, -1.1932e-01, ..., -1.9089e-01,\n -3.9439e-01, -2.6608e+00],\n [ 8.7326e-02, 1.2306e-03, -1.8935e-01, ..., -2.1058e-01,\n -3.6134e-01, -1.9989e+00]])\ntensor([ 0.7361, -3.2305, -0.9682, ..., -2.5869, -2.2449, -2.0103])\n\n\t\tAfter Training\n\t\ttensor([[-0.1289, 0.1302, 0.0708, ..., -0.1939, 0.0632, 0.2022],\n [ 0.0554, 0.1122, 0.0751, ..., -0.0429, -0.1203, 0.0043],\n [-0.0135, 0.0029, 0.0904, ..., -0.0727, 0.0250, -0.0086],\n ...,\n [-0.1337, 0.0341, 0.0160, ..., 0.0066, -0.0373, -0.0570],\n [ 0.0677, 0.0600, 0.0050, ..., -0.1325, -0.0593, 0.0176],\n [-0.0403, 0.0116, 0.0058, ..., 0.0291, 0.0830, 0.0923]])\ntensor([[-3.0454e-02, 1.5894e-03, 5.7909e-02, ..., 2.7037e-02,\n -2.5404e-02, 4.9215e-02],\n [ 2.9461e-02, -3.8808e-04, 7.4555e-03, ..., -1.9786e-02,\n -6.4447e-02, -2.4594e-03],\n [ 4.5011e-02, 2.1539e-02, -4.3563e-03, ..., 3.6569e-02,\n 8.1367e-03, 5.1494e-02],\n ...,\n [-4.9307e-02, -1.0149e-01, -1.4260e-02, ..., 8.2542e-03,\n 4.8378e-03, 3.0536e-02],\n [-1.0090e-02, 8.6628e-02, -4.6727e-02, ..., -5.8588e-02,\n -6.5680e-02, 1.7919e-02],\n [-4.2426e-01, 1.1944e-01, 1.3343e-01, ..., 3.6951e-01,\n 1.6299e-01, 6.1188e-02]])\ntensor([[-0.2351, 0.1264, -0.0473, ..., 0.0567, 0.1953, 0.5427],\n [-0.4042, -0.2849, 0.1931, ..., 0.1097, 0.2628, 0.1769],\n [-0.0920, -0.0440, -0.0948, ..., -0.0635, -0.0360, 0.5120],\n ...,\n [ 0.0226, 0.0371, -0.0213, ..., -0.1311, -0.0251, 0.4819],\n [-0.1992, 0.1118, -0.0327, ..., 0.1094, -0.0933, 0.4559],\n [ 0.2720, 0.1072, 0.0288, ..., -0.0202, -0.0885, 0.0874]])\ntensor([0.3880, 0.3163, 0.3092, ..., 0.5978, 0.4511, 0.1306])\ntensor([0.3717, 0.3092, 0.3856, ..., 0.5198, 0.5178, 0.1005])\ntensor([[ 3.5198e-01, 4.5830e-02, -1.4333e-04, ..., 3.0570e-01,\n 4.6634e-01, 7.6156e-01],\n [ 8.6201e-02, -3.0044e-01, -3.9556e-01, ..., 3.2411e-02,\n -2.4734e-01, -2.5597e+00],\n [-3.3102e-01, -3.2796e-02, -7.0906e-02, ..., -1.6356e-01,\n 3.2810e-01, -6.0324e-01],\n ...,\n [ 4.9895e-02, -3.1912e-01, -2.4441e-01, ..., -3.3909e-01,\n -2.9526e-01, -2.7194e+00],\n [ 7.7721e-02, -2.1900e-01, -1.2892e-01, ..., -1.7008e-01,\n -3.6706e-01, -2.9046e+00],\n [ 9.8990e-02, 9.3403e-03, -2.0431e-01, ..., -1.9609e-01,\n -3.3457e-01, -2.1877e+00]])\ntensor([ 0.7356, -3.5851, -1.1425, ..., -2.8362, -2.4977, -2.2010])\n\t\t \n" ], [ "sample = [\"270724499_107481c88f\", \"293879742_5fe0ffd894\", \"533713007_bf9f3e25b4\", \"166507476_9be5b9852a\"]\n!python3 test.py -model alexnet -i test/293879742_5fe0ffd894.jpg -epoch 200 \n!python3 test.py -model alexnet -i test/293879742_5fe0ffd894.jpg -epoch 230 ", " <start> a dog jumps for a tennis ball in a park <end>\n <start> a dog with a muzzle jumps in the air . <end>\n" ], [ "im = plt.imread(\"test/293879742_5fe0ffd894.jpg\")\nfig, ax = plt.subplots()\nim = ax.imshow(im)\nplt.show()", "_____no_output_____" ], [ "#Score: 0.24207828621261024\n#Image: 270724499_107481c88f\nimport nltk\ndef convert(lst):\n return ([i for item in lst for i in item.split()])\n\nhypothesis = ['a', 'brown', 'and', 'white', 'dog', 'is', 'running', 'through', 'a', 'field', 'of', 'grass', 'and', 'a', 'yellow', 'dog']\ninput = [\n \"A dog with a blue ball running in a field\",\n \"a small tan dog running on the grass with a ball in his mouth\"\n \"Dog running towards camera with a ball in its mouth\"\n \"small dog running in the grass with a toy in its mouth\"\n \"The dog is running with a colorful ball\",\n]\n\nreference = []\nfor i in input:\n reference.append(convert(i))\n\n#there may be several references\nBLEUscore = nltk.translate.bleu_score.sentence_bleu(reference, hypothesis)\nprint(BLEUscore)\n\n", "0.24207828621261024\n" ], [ "#Score: 0.28780044859364345\n#Image: 293879742_5fe0ffd894\nimport nltk\ndef convert(lst):\n return ([i for item in lst for i in item.split()])\n\nhypothesis = convert(\"a dog with a muzzle jumps in the air\")\ninput = [\n \"A brown dog is jumping over a fence and another dog is chasing it\",\n \"A brown dog jumps over a wire fence and another dog follows him\",\n \"A dog jumping off a fence and another dog on the grass in the background\",\n \"A dog jumping over a gate followed by another dog\",\n \"A small tan dog is jumping over a chain linked fence\" \n]\n\nreference = []\nfor i in input:\n reference.append(convert(i))\n\n#there may be several references\nBLEUscore = nltk.translate.bleu_score.sentence_bleu(reference, hypothesis)\nprint(BLEUscore)\n\n", "0.28780044859364345\n" ], [ "!nvidia-smi", "Wed Mar 23 16:03:45 2022 \n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |\n|-------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|===============================+======================+======================|\n| 0 Tesla K80 Off | 00000000:00:04.0 Off | 0 |\n| N/A 58C P8 32W / 149W | 3MiB / 11441MiB | 0% Default |\n| | | N/A |\n+-------------------------------+----------------------+----------------------+\n \n+-----------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=============================================================================|\n| No running processes found |\n+-----------------------------------------------------------------------------+\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4dbbb2fbcfb17b2acaf37e8b824391af1181cf
11,667
ipynb
Jupyter Notebook
session3/session3.ipynb
zhiweih/pb-exercises
c5e64075c47503a40063aa836c06a452af14246d
[ "BSD-2-Clause" ]
153
2017-09-27T01:10:19.000Z
2022-03-17T12:13:59.000Z
session3/session3.ipynb
zhiweih/pb-exercises
c5e64075c47503a40063aa836c06a452af14246d
[ "BSD-2-Clause" ]
3
2018-11-10T20:04:13.000Z
2022-02-15T23:12:53.000Z
session3/session3.ipynb
zhiweih/pb-exercises
c5e64075c47503a40063aa836c06a452af14246d
[ "BSD-2-Clause" ]
85
2017-10-09T16:18:00.000Z
2022-02-09T14:21:08.000Z
33.817391
1,361
0.674724
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec4dc2d46a613509be12a09bf570f80bbac2a2b4
5,136
ipynb
Jupyter Notebook
.ipynb_checkpoints/compareTADs-checkpoint.ipynb
labtanaka/schloissnig_axolotl
d18f2a77c9f2cd9a1dbb339477a371c8738548b0
[ "MIT" ]
null
null
null
.ipynb_checkpoints/compareTADs-checkpoint.ipynb
labtanaka/schloissnig_axolotl
d18f2a77c9f2cd9a1dbb339477a371c8738548b0
[ "MIT" ]
null
null
null
.ipynb_checkpoints/compareTADs-checkpoint.ipynb
labtanaka/schloissnig_axolotl
d18f2a77c9f2cd9a1dbb339477a371c8738548b0
[ "MIT" ]
null
null
null
54.063158
2,018
0.58528
[ [ [ "%matplotlib inline\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n# Load the set of putative axolotl genes and save the coordinates of the TADs for each gene symbol\namexTADs = dict()\nwith open('/groups/tanaka/Projects/axolotl-genome/AmexG_v6.0/AmexG_v6.0_DD/work/manuscript/compare_TADs/ambMex60DD.genes+tads.bed', 'r') as hFile:\n for strLine in hFile.readlines():\n chrID, start, end, genes = strLine.strip().split('\\t')\n for geneID in genes.replace(' [hs]', '').replace(' [nr]', '').split('|'):\n if not amexTADs.get(geneID):\n amexTADs[geneID] = [{'chr': chrID, 'start': int(start), 'end': int(end)}]\n else:\n for tad in amexTADs[geneID]:\n if tad['chr'] != chrID or tad['start'] != start or tad['end'] != end:\n amexTADs[geneID].append({'chr': chrID, 'start': int(start), 'end': int(end)})\n break\nprint(f'Loaded TADs for {len(amexTADs)} axolotl genes')\n\n# Intersect the list of human genes with human TADs to get the list of genes for each TAD\n# Then output the list of axolotl \nhsTADs = dict()\nwith open('/groups/tanaka/Projects/axolotl-genome/AmexG_v6.0/AmexG_v6.0_DD/work/manuscript/compare_TADs/hg19.tads+genes', 'r') as hFile:\n for strLine in hFile.readlines():\n chrID, start, end, genes = strLine.strip().split('\\t')\n for geneID in genes.split(';'):\n tads = amexTADs.get(geneID)\n if tads:\n print(strLine)\n print(tads)\n exit(0)\n ", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
ec4ded51a5a86f45893f26291d29ce1796b7b921
45,321
ipynb
Jupyter Notebook
src/data/collection/data_collection.ipynb
rijks-g4/rijksdraw
c7a9a29de2a9adbc56e916636b9e211a2ace5db1
[ "MIT" ]
null
null
null
src/data/collection/data_collection.ipynb
rijks-g4/rijksdraw
c7a9a29de2a9adbc56e916636b9e211a2ace5db1
[ "MIT" ]
null
null
null
src/data/collection/data_collection.ipynb
rijks-g4/rijksdraw
c7a9a29de2a9adbc56e916636b9e211a2ace5db1
[ "MIT" ]
null
null
null
48.784715
1,426
0.589837
[ [ [ "import os\nimport requests\nimport json\nimport csv", "_____no_output_____" ], [ "# You need to have exported the API_KEY in the same terminal where you start jupyter notebook:\n# e.g. export API_KEY = 'XXXXXXXX'\nAPI_KEY = os.environ['API_KEY']\nLANGUAGE = 'en'\n\nprint(f'API_KEY: {API_KEY}')", "API_KEY: 9HWI0Lk3\n" ], [ "def fetch_collection_page(language: str, api_key: str, object_type: str, imgonly: bool, ps: int, p: int):\n return requests.get(\n f'https://www.rijksmuseum.nl/api/{language}/collection?key={api_key}&type={object_type}&imgonly={imgonly}&ps={ps}&p={p}'\n )\n\ndef save_collection_page(collection_page: dict, output_dir: str) -> None:\n print(f'Saving objects...')\n for artObject in collection_page['artObjects']:\n object_id = artObject['objectNumber']\n with open(os.path.join(output_dir, f'{object_id}.json'), 'w') as f:\n json.dump(artObject, f)", "_____no_output_____" ], [ "RESULTS_PER_PAGE = 100\nIMAGE_ONLY = True\nCOLLECTION_OUTPUT_DIR = './data/collection/'\n\ncurrent_page = 1\nmore_data_exists = True\ntotal_objects = 0\n\nwhile True:\n print(f'Fetching page: {current_page}...')\n page = fetch_collection_page(LANGUAGE, API_KEY, 'painting', IMAGE_ONLY, RESULTS_PER_PAGE, current_page)\n page = page.json()\n len_objects = len(page['artObjects'])\n \n if len_objects == 0:\n print(f'No objects retrieved, breaking...')\n break\n\n print(f'Retrieved objects: {len_objects}')\n\n save_collection_page(page, COLLECTION_OUTPUT_DIR)\n current_page += 1\n total_objects += len_objects\n\n print(f'Current total: {total_objects}')\n \n print()", "Fetching page: 1...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 100\n\nFetching page: 2...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 200\n\nFetching page: 3...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 300\n\nFetching page: 4...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 400\n\nFetching page: 5...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 500\n\nFetching page: 6...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 600\n\nFetching page: 7...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 700\n\nFetching page: 8...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 800\n\nFetching page: 9...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 900\n\nFetching page: 10...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1000\n\nFetching page: 11...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1100\n\nFetching page: 12...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1200\n\nFetching page: 13...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1300\n\nFetching page: 14...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1400\n\nFetching page: 15...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1500\n\nFetching page: 16...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1600\n\nFetching page: 17...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1700\n\nFetching page: 18...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1800\n\nFetching page: 19...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 1900\n\nFetching page: 20...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2000\n\nFetching page: 21...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2100\n\nFetching page: 22...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2200\n\nFetching page: 23...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2300\n\nFetching page: 24...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2400\n\nFetching page: 25...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2500\n\nFetching page: 26...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2600\n\nFetching page: 27...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2700\n\nFetching page: 28...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2800\n\nFetching page: 29...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 2900\n\nFetching page: 30...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3000\n\nFetching page: 31...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3100\n\nFetching page: 32...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3200\n\nFetching page: 33...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3300\n\nFetching page: 34...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3400\n\nFetching page: 35...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3500\n\nFetching page: 36...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3600\n\nFetching page: 37...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3700\n\nFetching page: 38...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3800\n\nFetching page: 39...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 3900\n\nFetching page: 40...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 4000\n\nFetching page: 41...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 4100\n\nFetching page: 42...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 4200\n\nFetching page: 43...\nRetrieved objects: 100\nSaving objects...\nCurrent total: 4300\n\nFetching page: 44...\nRetrieved objects: 80\nSaving objects...\nCurrent total: 4380\n\nFetching page: 45...\nNo objects retrieved, breaking...\n" ], [ "painting_ids = [f.split('.json')[0] for f in os.listdir(COLLECTION_OUTPUT_DIR) if os.path.isfile(os.path.join(COLLECTION_OUTPUT_DIR, f))]\npainting_ids = set(painting_ids)", "_____no_output_____" ], [ "# painting_ids = set()\n\n# CSV_PATH = './202001-rma-csv-collection.csv'\n# PAINTING_TYPE = 'schilderij'\n# with open(CSV_PATH, 'r', encoding='utf-8-sig') as csvFile:\n# reader = csv.DictReader(csvFile)\n# for artObject in reader:\n# objectType = artObject['objectType[1]']\n# objectImage = artObject['objectImage']\n \n# if objectType == PAINTING_TYPE and objectImage != '':\n# objectId = artObject['objectInventoryNumber']\n# painting_ids.add(objectId)", "_____no_output_____" ], [ "def fetch_single(painting_id: str, language: str, api_key: str) -> dict or None:\n response = None\n data = None\n \n try:\n response = requests.get(f'https://www.rijksmuseum.nl/api/{language}/collection/{painting_id}?key={api_key}')\n data = response.json()\n print(data)\n except Exception as e:\n print('exception')\n print(response.text)\n print(e)\n\n return data", "_____no_output_____" ], [ "DETAILED_OUTPUT_DIR = './data/detailed/'\n\nalready_collected = [f.split('.json')[0] for f in os.listdir(DETAILED_OUTPUT_DIR) if os.path.isfile(os.path.join(DETAILED_OUTPUT_DIR, f))]\nalready_collected = set(already_collected)\n\nto_be_collected = painting_ids.difference(already_collected)\nprint(f'To be collected: {len(to_be_collected)}')\n\nfor painting_id in to_be_collected:\n print(f'Processing: {painting_id}...')\n data = fetch_single(painting_id, LANGUAGE, API_KEY)\n \n if data:\n print(f'Saving: {painting_id}...')\n with open(os.path.join(OUTPUT_DIRECTORY, f'{painting_id}.json'), 'w') as f:\n json.dump(data, f)\n else:\n print(f'No data fetched: {painting_id}...')", "To be collected: 4316\nProcessing: SK-A-1526...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1526...\nProcessing: SK-A-1425...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1425...\nProcessing: SK-A-4495...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-4495...\nProcessing: SK-A-725...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-725...\nProcessing: SK-A-303...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-303...\nProcessing: SK-C-448...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-448...\nProcessing: SK-A-2153...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2153...\nProcessing: SK-C-296...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-296...\nProcessing: SK-A-3478...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3478...\nProcessing: SK-A-3361...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3361...\nProcessing: SK-A-1222...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1222...\nProcessing: SK-A-209...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-209...\nProcessing: SK-A-2555...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2555...\nProcessing: SK-A-2724...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2724...\nProcessing: SK-A-4070...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-4070...\nProcessing: SK-A-1338...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1338...\nProcessing: SK-A-1370...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1370...\nProcessing: SK-A-3050...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3050...\nProcessing: SK-A-348...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-348...\nProcessing: SK-A-2199...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2199...\nProcessing: SK-A-1849...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1849...\nProcessing: SK-C-1562...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-1562...\nProcessing: SK-A-150...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-150...\nProcessing: SK-A-530...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-530...\nProcessing: SK-A-653...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-653...\nProcessing: SK-A-2185...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2185...\nProcessing: SK-A-3527...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3527...\nProcessing: SK-A-1520...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1520...\nProcessing: SK-A-2114...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2114...\nProcessing: SK-A-1323...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1323...\nProcessing: SK-A-149...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-149...\nProcessing: SK-A-1548...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1548...\nProcessing: SK-A-1654...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1654...\nProcessing: SK-A-1617...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1617...\nProcessing: SK-A-110...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-110...\nProcessing: SK-A-4885...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-4885...\nProcessing: SK-A-2200...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2200...\nProcessing: SK-A-942...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-942...\nProcessing: SK-A-3492...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3492...\nProcessing: SK-A-2963...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2963...\nProcessing: SK-A-2423...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2423...\nProcessing: SK-C-161...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-161...\nProcessing: SK-A-2717...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2717...\nProcessing: SK-A-571...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-571...\nProcessing: SK-C-1453...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-1453...\nProcessing: SK-A-1398...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1398...\nProcessing: SK-A-280...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-280...\nProcessing: SK-A-2788...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2788...\nProcessing: SK-A-3935...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3935...\nProcessing: SK-A-5049...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-5049...\nProcessing: SK-A-2856...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2856...\nProcessing: SK-A-15...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-15...\nProcessing: SK-C-1767...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-1767...\nProcessing: SK-A-1480...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1480...\nProcessing: SK-A-450...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-450...\nProcessing: SK-C-210...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-210...\nProcessing: SK-A-4164...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-4164...\nProcessing: SK-C-306...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-306...\nProcessing: SK-A-3899...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3899...\nProcessing: SK-A-55...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-55...\nProcessing: SK-A-4493...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-4493...\nProcessing: SK-A-26...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-26...\nProcessing: SK-A-3924...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3924...\nProcessing: SK-C-1529...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-1529...\nProcessing: SK-A-1969...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-1969...\nProcessing: SK-A-2351...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2351...\nProcessing: SK-A-2920...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-2920...\nProcessing: SK-A-4208...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-4208...\nProcessing: SK-A-3801...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3801...\nProcessing: SK-A-48...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-48...\nProcessing: SK-A-3382...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3382...\nProcessing: SK-A-642...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-642...\nProcessing: SK-A-3559...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-3559...\nProcessing: BK-2011-38...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: BK-2011-38...\nProcessing: SK-A-445...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-A-445...\nProcessing: SK-C-1658...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-1658...\nProcessing: SK-C-1531...\nexception\n\nExpecting value: line 1 column 1 (char 0)\nNo data fetched: SK-C-1531...\nProcessing: SK-A-406...\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4df4d2e7cd1364c20949365696b5176b77ea79
17,343
ipynb
Jupyter Notebook
Module2/.ipynb_checkpoints/Module2 - Lab5-checkpoint.ipynb
goswami-rahul/DAT210x-DataScience
b5e52fb313a5431f8f7d3d1ac0b7d7b3150c5600
[ "MIT" ]
null
null
null
Module2/.ipynb_checkpoints/Module2 - Lab5-checkpoint.ipynb
goswami-rahul/DAT210x-DataScience
b5e52fb313a5431f8f7d3d1ac0b7d7b3150c5600
[ "MIT" ]
null
null
null
Module2/.ipynb_checkpoints/Module2 - Lab5-checkpoint.ipynb
goswami-rahul/DAT210x-DataScience
b5e52fb313a5431f8f7d3d1ac0b7d7b3150c5600
[ "MIT" ]
null
null
null
43.3575
1,285
0.547137
[ [ [ "# DAT210x - Programming with Python for DS", "_____no_output_____" ], [ "## Module2 - Lab5", "_____no_output_____" ], [ "Import and alias Pandas:", "_____no_output_____" ] ], [ [ "# .. your code here ..\nimport pandas as pd\npd.show_versions()", "\nINSTALLED VERSIONS\n------------------\ncommit: None\npython: 3.6.3.final.0\npython-bits: 64\nOS: Linux\nOS-release: 4.4.0-104-generic\nmachine: x86_64\nprocessor: x86_64\nbyteorder: little\nLC_ALL: None\nLANG: en_IN\nLOCALE: en_IN.ISO8859-1\n\npandas: 0.20.3\npytest: 3.2.1\npip: 9.0.1\nsetuptools: 36.5.0.post20170921\nCython: 0.26.1\nnumpy: 1.13.3\nscipy: 0.19.1\nxarray: None\nIPython: 6.1.0\nsphinx: 1.6.3\npatsy: 0.4.1\ndateutil: 2.6.1\npytz: 2017.2\nblosc: None\nbottleneck: 1.2.1\ntables: 3.4.2\nnumexpr: 2.6.2\nfeather: None\nmatplotlib: 2.1.0\nopenpyxl: 2.4.8\nxlrd: 1.1.0\nxlwt: 1.3.0\nxlsxwriter: 1.0.2\nlxml: 4.1.0\nbs4: 4.6.0\nhtml5lib: 0.999999999\nsqlalchemy: 1.1.13\npymysql: None\npsycopg2: None\njinja2: 2.9.6\ns3fs: None\npandas_gbq: None\npandas_datareader: None\n" ] ], [ [ "As per usual, load up the specified dataset, setting appropriate header labels.", "_____no_output_____" ] ], [ [ "# .. your code here ..\ndf = pd.read_csv('Datasets/census.data', \n names=['education', 'age', 'capital-gain', 'race', \n 'capital-loss', 'hours-per-week', 'sex', 'classification'], \n na_values='?')\ndf.head()", "_____no_output_____" ] ], [ [ "Excellent.\n\nNow, use basic pandas commands to look through the dataset. Get a feel for it before proceeding!\n\nDo the data-types of each column reflect the values you see when you look through the data using a text editor / spread sheet program? If you see `object` where you expect to see `int32` or `float64`, that is a good indicator that there might be a string or missing value or erroneous value in the column.", "_____no_output_____" ] ], [ [ "# .. your code here ..\ndf.info()\ndf.education.unique()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 29536 entries, 0 to 29535\nData columns (total 8 columns):\neducation 29536 non-null object\nage 29536 non-null int64\ncapital-gain 29532 non-null float64\nrace 29536 non-null object\ncapital-loss 29536 non-null int64\nhours-per-week 29536 non-null int64\nsex 29536 non-null object\nclassification 29536 non-null object\ndtypes: float64(1), int64(3), object(4)\nmemory usage: 3.3+ MB\n" ] ], [ [ "Try use `your_data_frame['your_column'].unique()` or equally, `your_data_frame.your_column.unique()` to see the unique values of each column and identify the rogue values.\n\nIf you find any value that should be properly encoded to NaNs, you can convert them either using the `na_values` parameter when loading the dataframe. Or alternatively, use one of the other methods discussed in the reading.", "_____no_output_____" ] ], [ [ "# .. your code here ..\nedu_cat = ['Preschool', '1st-4th', '5th-6th', '7th-8th', '9th', '10th', \n '11th', '12th', 'Some-college', 'HS-grad', 'Bachelors', 'Masters', 'Doctorate']\ndf['education2'] = df['education'].astype(\"category\", ordered=True, \n categories=edu_cat).cat.codes\n", "_____no_output_____" ] ], [ [ "Look through your data and identify any potential categorical features. Ensure you properly encode any ordinal and nominal types using the methods discussed in the chapter.\n\nBe careful! Some features can be represented as either categorical or continuous (numerical). If you ever get confused, think to yourself what makes more sense generally---to represent such features with a continuous numeric type... or a series of categories?", "_____no_output_____" ] ], [ [ "# .. your code here ..\n", "_____no_output_____" ] ], [ [ "Lastly, print out your dataframe!", "_____no_output_____" ] ], [ [ "# .. your code here ..", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec4e03ef1aa432953f453fed7399f546a718df1c
154,254
ipynb
Jupyter Notebook
notebooks/plot_single_region_timeseries_acrossmodels.ipynb
nih-niddk-mbs/covid-sicr
8524abfb318be4b181b412cc70ec7136af93a22a
[ "MIT" ]
4
2020-04-28T18:00:27.000Z
2022-02-22T16:57:12.000Z
notebooks/plot_single_region_timeseries_acrossmodels.ipynb
nih-niddk-mbs/covid-sicr
8524abfb318be4b181b412cc70ec7136af93a22a
[ "MIT" ]
6
2020-05-07T13:07:06.000Z
2021-03-04T19:55:12.000Z
notebooks/plot_single_region_timeseries_acrossmodels.ipynb
nih-niddk-mbs/covid-sicr
8524abfb318be4b181b412cc70ec7136af93a22a
[ "MIT" ]
6
2020-05-01T17:06:37.000Z
2021-03-30T11:07:08.000Z
363.806604
140,444
0.921383
[ [ [ "### Init stuff", "_____no_output_____" ] ], [ [ "from matplotlib.pyplot import *\nimport matplotlib\nfrom numpy import *\nimport pandas as pd\nimport niddk_covid_sicr as ncs", "_____no_output_____" ] ], [ [ "### Define ROI", "_____no_output_____" ] ], [ [ "roi = 'US_SD'", "_____no_output_____" ] ], [ [ "### Define paths and other", "_____no_output_____" ] ], [ [ "linear_models = ['SICRLM','SICRLM2R','SICRLMQC','SICRLMQC2R']\nnonlinear_models = ['SICRM','SICRM2R','SICRMQC','SICRMQC2R']\n# models = linear_models #+ nonlinear_models\nmodels = ['SICRMQC']\n\nmodels_path = '/Users/carsonc/github/covid-sicr/models/'\ncasepath = '/Users/carsonc/github/covid-sicr/data/covidtimeseries_'\nfits_path = '/Users/carsonc/github/covid-sicr/fits/'", "_____no_output_____" ], [ "%matplotlib inline\n\nfont = {'family' : 'normal',\n 'weight' : 'normal',\n 'size' : 18}\n\nmatplotlib.rc('font', **font)", "_____no_output_____" ], [ "def simpleaxis(ax):\n ax.spines['top'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_visible(False)\n\n\n\ndef plot_ts(ax,c,r,d,x):\n Clb = percentile(c,2.5,axis=0)\n Cm = percentile(c,50,axis=0)\n Cub = percentile(c,97.5,axis=0)\n\n Rlb = percentile(r,2.5,axis=0)\n Rm = percentile(r,50,axis=0)\n Rub = percentile(r,97.5,axis=0)\n\n Dlb = percentile(d,2.5,axis=0)\n Dm = percentile(d,50,axis=0)\n Dub = percentile(d,97.5,axis=0)\n\n mecolor = 'none'\n ax[0].plot(DF[\"new_cases\"].values,'bo',ms=10, markeredgecolor=mecolor,label=\"cases data\")\n ax[1].plot(DF[\"new_recover\"].values,'gs',ms=10, markeredgecolor=mecolor,label=\"recovered data\")\n ax[2].plot(DF[\"new_deaths\"].values,'k^',ms=10, markeredgecolor=mecolor,label=\"deaths data\")\n\n # print(c)\n ax[0].plot(x,Cm,color='b',lw=lw,label=\"case median fit\")\n ax[0].fill_between(x,Clb,Cub,color='b',alpha=a)\n \n ax[1].plot(x,Rm,color='g',lw=lw,label=\"recovered median fit\")\n ax[1].fill_between(x,Rlb,Rub,color='g',alpha=a)\n \n ax[2].plot(x,Dm,color='k',lw=lw,label=\"deaths median fit\")\n ax[2].fill_between(x,Dlb,Dub,color='k',alpha=a)\n \n \n ax[0].plot(x,Clb,color='k')\n ax[0].plot(x,Cub,color='k')\n \n ax[1].plot(x,Rlb,color='k')\n ax[1].plot(x,Rub,color='k')\n \n ax[2].plot(x,Dlb,color='k')\n ax[2].plot(x,Dub,color='k')\n \n for i in range(3):\n ax[i].set_ylabel('counts-per-day')\n ax[i].set_xlabel('day from t0')\n# ax[i].set_xticks(xticks_)\n# ax[i].set_xticklabels(xdates_)\n# ax[i].axvline(tm,linestyle='dashed',color='k',label='mitigation')\n# ax[i].axvline(tfit,color='k')\n if i==0:\n ax[0].plot(0,0,linestyle='none',color='none', label='shaded: 95% C.I.')\n ax[i].legend(loc=2)\n simpleaxis(ax[i])\n \n \n ax[0].set_title('new cases per day')\n ax[1].set_title('new recovered per day')\n ax[2].set_title('new deaths per day')\n \n \n \n return\n\ndef plotXt(ax,Xt,x,c):\n Xtlb = percentile(Xt,2.5,axis=0)\n Xtm = percentile(Xt,50,axis=0)\n Xtub = percentile(Xt,97.5,axis=0)\n \n ax.plot(x,Xtm,color=c,lw=lw,label=\"median\")\n ax.fill_between(x,Xtlb,Xtub,color=c,alpha=a)\n ax.plot(x,Xtlb,color='k')\n ax.plot(x,Xtub,color='k')\n simpleaxis(ax)\n# ax.set_ylabel('secondary infections per infected')\n# ax.set_xticks(xticks_)\n# ax.set_xticklabels(xdates_)\n# ax.set_ylim((0,32))\n# ax.set_yticks(y_)\n# ax.axvline(tm,linestyle='dashed',color='k',label='mitigation')\n# ax.axvline(tfit,color='k')\n return", "_____no_output_____" ] ], [ [ "### Load data ", "_____no_output_____" ] ], [ [ "# if roi[:2]=='US':\n# DF = getDF_covidtrack(roi.split('US_')[1])\n# else:\n# DF = getDF_JHU(roi)", "_____no_output_____" ], [ "csv = casepath + roi + \".csv\"\nDF = pd.read_csv(csv)", "_____no_output_____" ] ], [ [ "### Format data", "_____no_output_____" ] ], [ [ "# filter data frame by April 15th cutoff date\n\n# ind = DF.index[DF.date=='04/15/20'].values[0]\n# DF = DF[DF.index<=ind]\n\n\n# get t0\nt0 = DF.index[DF.new_cases>5].values[0]\nDF = DF[DF.index>=t0]", "_____no_output_____" ] ], [ [ "### get samples", "_____no_output_____" ] ], [ [ "for model_name in models:\n print(model_name)\n samples = ncs.extract_samples(fits_path, models_path, model_name, roi, 1)\n nsamples = shape(samples['mbase'])[0]\n for i in np.arange(1000,1,-1).astype(str):\n try:\n a = samples['lambda['+i+',1]']\n break\n except:\n pass\n nobs = int(i)\n c = zeros((nsamples,1))\n r = zeros((nsamples,1))\n d = zeros((nsamples,1))\n Rt = zeros((nsamples,1))\n CARt = zeros((nsamples,1))\n IFRt = zeros((nsamples,1))\n\n for i in range(1,nobs+1):\n c = np.hstack((c,samples['lambda['+str(i)+',1]'][:,None]))\n r = np.hstack((r,samples['lambda['+str(i)+',2]'][:,None]))\n d = np.hstack((d,samples['lambda['+str(i)+',3]'][:,None]))\n Rt = np.hstack((Rt,samples['Rt['+str(i)+']'][:,None]))\n CARt = np.hstack((CARt,samples['car['+str(i)+']'][:,None]))\n IFRt = np.hstack((IFRt,samples['ifr['+str(i)+']'][:,None]))\n\nc = c[:,1:]\nr = r[:,1:]\nd = d[:,1:]\nRt = Rt[:,1:]\nCARt = CARt[:,1:]\nIFRt = IFRt[:,1:]\n \n \nlw = 4\nf,ax = subplots(2,3,figsize=(15,20))\nax = ax.flatten()\na = 0.1\nx = arange(nobs)\nplot_ts(ax[:3],c,r,d,x)\n\nax[3].set_title(r'R$_t$')\nplotXt(ax[3],Rt,x,'purple')\nax[3].set_ylim((0,20))\nax[3].set_yticks([1,2,4,6,8,10,12])\n\nax[4].set_title(r'CAR$_t$')\nplotXt(ax[4],CARt,x,'orange')\n\nax[5].set_title(r'IFR$_t$')\nplotXt(ax[5],IFRt,x,'red')\nax[5].set_ylim((0,0.15))\nax[5].set_yticks([0.01,0.02,0.04,0.08])\n\nsuptitle(roi + ' - Linear no QC models (fit10)')\nsubplots_adjust(wspace=0.5,hspace=0.5)\n\n", "SICRMQC\n" ], [ "# def fix_date(x):\n# x = datetime.strftime(datetime.strptime(x, '%m/%d/%y'), '%m/%d/%y')\n# return x\n\n# def fix_date_covidtrack(x):\n# x = datetime.strftime(datetime.strptime(str(x), '%Y%m%d'), '%m/%d/%y')\n# return x \n\n# def getDF_covidtrack(roi):\n# url = 'https://raw.githubusercontent.com/COVID19Tracking/covid-tracking-data/master/data/states_daily_4pm_et.csv'\n# df = pd.read_csv(url)\n# DF = pd.DataFrame(columns=['date', \n# 'cum_cases','cum_recover','cum_deaths', \n# 'new_cases', 'new_recover', 'new_deaths'])\n# df = df[df['state']==roi]\n# date = sort(df['date'].values)\n# for i in range(len(date)):\n# DF.loc[i] = pd.Series({\n# 'date':fix_date_covidtrack(date[i]),\n# 'cum_cases':df.loc[df['date']==date[i]]['positive'].values[0],\n# 'cum_recover':df.loc[df['date']==date[i]]['recovered'].values[0],\n# 'cum_deaths':df.loc[df['date']==date[i]]['death'].values[0],\n# })\n# DF[['new_cases', 'new_recover', 'new_deaths']] = \\\n# DF[['cum_cases', 'cum_recover', 'cum_deaths']].diff()\n# if isnan(DF.new_cases.values[0]):\n# DF = DF.iloc[1:]\n# return DF\n\n# def getDF_JHU(roi):\n# url_confirmed = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\"\n# url_recovered = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv\"\n# url_deaths = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv\"\n\n# dfc = pd.read_csv(url_confirmed)\n# dfr = pd.read_csv(url_recovered)\n# dfd = pd.read_csv(url_deaths)\n\n\n# DF = pd.DataFrame(columns=['date', \n# 'cum_cases','cum_recover','cum_deaths', \n# 'new_cases', 'new_recover', 'new_deaths'])\n\n# date = dfc.columns[4:].values\n# try:\n# for i in range(len(date)):\n# DF.loc[i] = pd.Series({\n# 'date':fix_date(date[i]),\n# 'cum_cases':dfc.loc[(dfc['Country/Region']==roi)&(dfc['Province/State'].isnull())][date[i]].values[0],\n# 'cum_recover':dfr.loc[(dfr['Country/Region']==roi)&(dfc['Province/State'].isnull())][date[i]].values[0],\n# 'cum_deaths':dfd.loc[(dfd['Country/Region']==roi)&(dfc['Province/State'].isnull())][date[i]].values[0],\n# })\n# except:\n# for i in range(len(date)):\n# DF.loc[i] = pd.Series({\n# 'date':fix_date(date[i]),\n# 'cum_cases':sum(dfc.loc[(dfc['Country/Region']==roi)][date[i]].values),\n# 'cum_recover':sum(dfr.loc[(dfr['Country/Region']==roi)][date[i]].values),\n# 'cum_deaths':sum(dfd.loc[(dfd['Country/Region']==roi)][date[i]].values),\n# })\n\n# DF[['new_cases', 'new_recover', 'new_deaths']] = \\\n# DF[['cum_cases', 'cum_recover', 'cum_deaths']].diff()\n\n# # print(DF)\n# if isnan(DF.new_cases.values[0]):\n# DF = DF.iloc[1:]\n# return DF\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
ec4e0f7638bf33b1c20e934fc992ccb8a7163bce
71,537
ipynb
Jupyter Notebook
experiments/reconciliation v2.ipynb
TheScienceMuseum/heritage-connector
c8f0970edfe2c43560949fe46f4d4415f4f8bc0b
[ "MIT" ]
15
2020-03-19T09:13:02.000Z
2022-03-29T16:53:53.000Z
experiments/reconciliation v2.ipynb
TheScienceMuseum/heritage-connector
c8f0970edfe2c43560949fe46f4d4415f4f8bc0b
[ "MIT" ]
311
2020-06-11T10:14:06.000Z
2021-12-03T16:56:11.000Z
experiments/reconciliation v2.ipynb
TheScienceMuseum/heritage-connector
c8f0970edfe2c43560949fe46f4d4415f4f8bc0b
[ "MIT" ]
1
2021-11-20T18:48:43.000Z
2021-11-20T18:48:43.000Z
48.401218
972
0.332779
[ [ [ "# Reconciliation v2: using text search", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2\n\nimport sys\nsys.path.append(\"..\")\n\nimport os\n\nfrom heritageconnector.config import config, field_mapping\nfrom heritageconnector.disambiguation.search import wikidata_text_search\nfrom heritageconnector.utils.wikidata import url_to_qid\nfrom heritageconnector.utils.data_transformation import transform_series_str_to_list\nfrom heritageconnector.entity_matching.reconciler import reconciler\n\nimport pandas as pd\npd.set_option('display.max_colwidth', None)\npd.set_option('display.max_columns', None)\n\nfrom collections import Counter\nfrom tqdm import tqdm\n\ntqdm.pandas()", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ] ], [ [ "## 1. load data sample", "_____no_output_____" ] ], [ [ "sample_no = 100\nrandom_state = 42\n\n# load mimsy_people\ndf = pd.read_csv(config.MIMSY_PEOPLE_PATH)\nfor col in ['FIRSTMID_NAME', 'LASTSUFF_NAME']:\n df[col] = df[col].fillna(\"\").astype(str)\n \ndf['FREETEXT'] = df['DESCRIPTION'].astype(str) + \" \" + df['NOTE'].astype(str)\n\n# load people df \npeople_df = df[df['GENDER'].isin(('M', 'F'))]#.sample(sample_no, random_state=random_state)\npeople_df.loc[:, 'JOINED_NAME'] = people_df['FIRSTMID_NAME'] + \" \" + people_df['LASTSUFF_NAME']\n", "_____no_output_____" ] ], [ [ "## 2. get subject items from PID\nWe need to get types of entities that populate the `OCCUPATION` field in Wikidata.", "_____no_output_____" ] ], [ [ "qcode_filter = reconciler.get_subject_items_from_pid(field_mapping.PEOPLE['OCCUPATION']['PID'])\nqcode_filter\n# qcodes for profession, occupation", "_____no_output_____" ] ], [ [ "## 3. get matches for one occupation", "_____no_output_____" ] ], [ [ "search = wikidata_text_search()\nsearch.run_search(\"captain\", instanceof_filter=qcode_filter, include_class_tree=True)", "_____no_output_____" ], [ "# not an occupation\nsearch.run_search(\"conjoined twin\", instanceof_filter=qcode_filter, include_class_tree=True)", "_____no_output_____" ] ], [ [ "## 4. get matches for all occupations\nThis will become a job in `smg_jobs`.", "_____no_output_____" ], [ "### 4.1. create mapping table", "_____no_output_____" ] ], [ [ "def str_col_to_list(series, separator=\";\"):\n return series.fillna(\"\").astype(str).apply(lambda i: [x.strip().lower() for x in i.split(separator)])\n\npeople_df['OCCUPATION_list'] = str_col_to_list(people_df['OCCUPATION'])\n\nall_names = people_df['OCCUPATION_list'].sum()\nall_names = [i for i in all_names if i != \"\"]\nseries_count = pd.Series(Counter(all_names)).sort_values(ascending=False)\n\nprint(len(series_count))\nseries_count.head()", "2216\n" ], [ "map_df = pd.DataFrame(series_count).rename(columns={0: 'count'})\nmap_df.head()", "_____no_output_____" ], [ "def lookup_value(text):\n res_df = search.run_search(text, instanceof_filter=qcode_filter, include_class_tree=True)\n if len(res_df) == 0:\n return []\n else:\n return [url_to_qid(i) for i in res_df['item'].tolist()]\n\nmap_df['qid'] = map_df.index.to_series().progress_apply(lookup_value)", "100%|██████████| 82/82 [00:57<00:00, 1.42it/s]\n" ], [ "map_df", "_____no_output_____" ], [ "map_df.loc[['scientist', 'captain'], 'qid'].values.sum()", "_____no_output_____" ] ], [ [ "### 4.2 populate new field using mapping table", "_____no_output_____" ] ], [ [ "qid_col = \"OCCUPATION\" + \"_qid\"\nlist_col = \"OCCUPATION_list\"\n\npeople_df[qid_col] = people_df[list_col].progress_apply(lambda x: map_df.loc[x, 'qid'].values.sum() if x != [''] else [])", "100%|██████████| 100/100 [00:00<00:00, 1532.23it/s]\n" ], [ "people_df", "_____no_output_____" ] ], [ [ "## 5. Heritage Connector implementation", "_____no_output_____" ] ], [ [ "people_df_processed = people_df.copy()\npeople_df_processed['OCCUPATION'] = transform_series_str_to_list(people_df_processed['OCCUPATION'], separator=\";\")\npeople_df_processed.head(2)", "_____no_output_____" ], [ "rec = reconciler(people_df_processed, table='people')\n#people_df_processed['OCCUPATION_qids'] = \nmap_df = rec.process_column('OCCUPATION', multiple_vals=True)\nmap_df", " 0%| | 0/2216 [00:00<?, ?it/s]" ] ] ]
[ "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", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ec4e174f9ec63c6406b5d78ecbde5dcbc465ca77
2,718
ipynb
Jupyter Notebook
Programming Languages Used in top technologies/2020-2021/2020-2021.ipynb
hritikb/Trend-Analysis-on-GitHub
85e8e8232d402c9f42e21bcfeca63c47415f80bd
[ "MIT" ]
null
null
null
Programming Languages Used in top technologies/2020-2021/2020-2021.ipynb
hritikb/Trend-Analysis-on-GitHub
85e8e8232d402c9f42e21bcfeca63c47415f80bd
[ "MIT" ]
null
null
null
Programming Languages Used in top technologies/2020-2021/2020-2021.ipynb
hritikb/Trend-Analysis-on-GitHub
85e8e8232d402c9f42e21bcfeca63c47415f80bd
[ "MIT" ]
null
null
null
25.641509
136
0.548565
[ [ [ "### Considering the Trending Technologies we will choose some of them to see which programming languages are mostly used for them.", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ], [ "df = pd.read_csv('Github_Data_2020_ready_for_text_analysis.csv')", "_____no_output_____" ], [ "focus = ['open source', 'deep learning', 'data science', 'machine learning', 'guided project', 'web development',\n 'starter project', 'software development']", "_____no_output_____" ], [ "for tech in focus:\n print('\\nFor ' +tech + ' : ', list(set(df[df['clean'].str.contains(tech)]['language'])))", "\nFor open source : ['Python', nan, 'C++', 'HTML', 'Jupyter Notebook', 'JavaScript', 'C']\n\nFor deep learning : ['Python', 'Jupyter Notebook']\n\nFor data science : [nan, 'Python', 'Jupyter Notebook']\n\nFor machine learning : ['Python', 'Jupyter Notebook']\n\nFor guided project : ['JavaScript']\n\nFor web development : [nan, 'JavaScript']\n\nFor starter project : ['Python', 'HTML', 'Java']\n\nFor software development : ['JavaScript']\n" ] ], [ [ "### Open Source is associated with many programming languages and thus justifies its popularity.\n\n### Some lists have nan because many repos are developed with several programming languages.\n\n### Tech related to Data Science is dominated by Python and Jupyter Notebook (representing Julia, Python and R).\n### For web and software development Javascript is most popular.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
ec4e1fa8192ecea6467cfb5bb1c4c64a9d357975
42,447
ipynb
Jupyter Notebook
sbMACROv2.0/.ipynb_checkpoints/filetype-checkpoint.ipynb
trogers1/sbProgram
d01aff3e95a32ebd2b2d9e231a9003bd7d787326
[ "Unlicense" ]
null
null
null
sbMACROv2.0/.ipynb_checkpoints/filetype-checkpoint.ipynb
trogers1/sbProgram
d01aff3e95a32ebd2b2d9e231a9003bd7d787326
[ "Unlicense" ]
6
2019-07-30T21:25:47.000Z
2021-06-01T23:23:50.000Z
sbMACROv2.0/.ipynb_checkpoints/filetype-checkpoint.ipynb
trogers1/sbProgram
d01aff3e95a32ebd2b2d9e231a9003bd7d787326
[ "Unlicense" ]
null
null
null
32.676674
218
0.373101
[ [ [ "import sqlite3\nimport pandas as pd\nimport numpy as np\nfrom pandas import DataFrame", "_____no_output_____" ], [ "conn = sqlite3.connect('sbmacro.db')", "_____no_output_____" ], [ "query1 = 'select name from sqlite_master where type = \"table\"'\nq1_result = pd.read_sql_query(query1, conn)\nq1_result", "_____no_output_____" ], [ "items = pd.read_sql_query('select * from item', conn)\nitems.head(1)", "_____no_output_____" ] ], [ [ "items = pd.read_sql_query('select * from item', conn)\nitems.head(1)", "_____no_output_____" ] ], [ [ "assoc = pd.read_sql_query('select * from assoc_item_sbfile', conn)\nassoc.head(1)", "_____no_output_____" ], [ "sbfile = pd.read_sql_query('select * from sb_file', conn)\nsbfile.head(1)", "_____no_output_____" ], [ "masterdetails = pd.read_sql_query('select * from master_details', conn)", "_____no_output_____" ], [ "# STEP 1: connect masterdetails to items\nitem_ids = items.sb_id.values\nmasterdetails['item_id'] = masterdetails.sb_id.apply(lambda x: items[items.sb_id == x].id.values[0] if x in item_ids else '-')\nmasterdetails.head(1)\n\n", "_____no_output_____" ], [ "# STEP 2: connect item id to sbfile id\nassoc_ids = assoc.item_id.values\nmasterdetails['sbfile_id'] = masterdetails.item_id.apply(lambda x: assoc[assoc.item_id == x].sbfile_id.values[0] if x in assoc_ids else '-')\nmasterdetails.head(1)\n", "/Users/smsawai/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:3: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison\n This is separate from the ipykernel package so we can avoid doing imports until\n" ], [ "# STEP 3: retrieve file type from sb_file table\nsb_file_id = sbfile.id.values\nmasterdetails['file_type'] = masterdetails.item_id.apply(lambda x: sbfile[sbfile.id == x].name.values[0].split('.')[-1] if x in sb_file_id else '-')\nmasterdetails.head(2)\n", "/Users/smsawai/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:3: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison\n This is separate from the ipykernel package so we can avoid doing imports until\n" ], [ "data = masterdetails[['fy', 'casc', 'file_type']]\ndata = data[data.file_type != '-']\n", "_____no_output_____" ], [ "data.groupby(['casc', 'file_type']).count()", "_____no_output_____" ], [ "finaldata = data.groupby(['casc', 'file_type']).count().reset_index()", "_____no_output_____" ], [ "finaldata = finaldata.rename(columns = {'fy': 'total_count'})", "_____no_output_____" ], [ "finaldata", "_____no_output_____" ], [ "cascs = list(set(finaldata.casc))\ndata = []\nfor i in range(len(cascs)):\n data1 = {\n \"casc\":cascs[i],\n \"children\":[\n {\n \"type\": \"\",\n \"children\": [\n {\n \"content\": \"\",\n \"children\": []\n }\n ]\n }\n ]\n }\n matched_data = finaldata[finaldata.casc == cascs[i]]\n filetypes = matched_data.file_type.values\n filecount = matched_data.total_count.values\n for j in range(len(filetypes)):\n data2 = {\n \"filetype\":filetypes[j],\n \"value\":filecount[j]\n }\n data1[\"children\"][0][\"children\"][0][\"children\"].append(data2)\n data.append(data1)\ndata", "_____no_output_____" ], [ "# convert to pandas dataframe\nfinaldata_df = pd.DataFrame(data)\nfinaldata_df.to_json('treemap_data.json', orient = 'records')\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4e2254f4b38596e3f2df8ac6f6a01d9d7b5c51
8,284
ipynb
Jupyter Notebook
notes/C2-Variables_Exercises.ipynb
innamuris/Panoscloned
401a4e276692c65ee96c6fb29b8a5a1445445e29
[ "CC0-1.0" ]
null
null
null
notes/C2-Variables_Exercises.ipynb
innamuris/Panoscloned
401a4e276692c65ee96c6fb29b8a5a1445445e29
[ "CC0-1.0" ]
null
null
null
notes/C2-Variables_Exercises.ipynb
innamuris/Panoscloned
401a4e276692c65ee96c6fb29b8a5a1445445e29
[ "CC0-1.0" ]
null
null
null
23.60114
414
0.550579
[ [ [ "# Exercises for Variables", "_____no_output_____" ], [ "## Exercise 1", "_____no_output_____" ], [ "Repeat the exercise from earlier on, about the daily return of a stock, but use variables instead of the raw numbers. You can initialize the variables to use \\\\$550 for the closing price of the stock on Monday, and then use \\\\$560 as the closing price on Tuesday. Try afterwards to change these numbers and see the results. (Hint: notice what would happen if you use the name `return` for the variable.) ", "_____no_output_____" ] ], [ [ "# your code here", "_____no_output_____" ] ], [ [ "### Solution", "_____no_output_____" ] ], [ [ "price_mon = 550\nprice_tue = 560\ndaily_return = 100 * (price_tue - price_mon) / price_mon\nprint(\"The daily return is\")\nprint(daily_return)", "_____no_output_____" ], [ "# If you uncomment the code below, notice that we cannot call the variable \"return\"\n# as \"return\" is a reserved keyword in Python\n\n# price_mon = 550\n# price_tue = 560\n# return = 100*(price_tue-price_mon)/price_mon\n# print(\"The daily return is\")\n# print(return)", "_____no_output_____" ] ], [ [ "## Exercise 2\n\n", "_____no_output_____" ], [ "Write a Python program to convert centimeters to feet and inches. Remember that one foot is 30.48 centimeters, and one inch is 2.54 centimeters.", "_____no_output_____" ] ], [ [ "# your code here", "_____no_output_____" ] ], [ [ "### Solution", "_____no_output_____" ] ], [ [ "# So, let's take a look at our code from last time:\nprint(\"180 cm is\", int(180//30.48), \"feet and\", round(180%30.48 / 2.54, 1) , \"inches\")", "_____no_output_____" ], [ "# We will now start introducing variables\ncentimeters = 180\nfeet = int(centimeters / 30.48)\ninches = int(centimeters % 30.48 / 2.54)\nprint(centimeters, \"cm is\", feet, \"ft and\", inches, \"inches\")", "_____no_output_____" ], [ "# Now let's introduce more variables to eliminate the \"magic numbers\" 30.48 and 2.54\ncm_per_foot = 30.48\ncm_per_in = 2.54\n# And now let's modify our code from above\ncentimeters = 180\nfeet = int(centimeters / cm_per_foot)\ninches = int(centimeters % cm_per_foot / cm_per_in)\nprint(centimeters, \"cm is\", feet, \"ft and\", inches, \"inches\")\n\n# And if we want to use round instead of int:\ninches = round(centimeters % cm_per_foot / cm_per_in,1)\nprint(centimeters, \"cm is\", feet, \"ft and\", inches, \"inches\")\n", "_____no_output_____" ] ], [ [ "## Exercise 3", "_____no_output_____" ], [ "We want to compute the \"[wind chill index](https://en.wikipedia.org/wiki/Wind_chill)\" as described at Wikipedia\n\n$T_\\mathrm{wc}=35.74+0.6215 T_\\mathrm{a}-35.75 v^{0.16}+0.4275 T_\\mathrm{a} v^{0.16}$\n\nwhere $T_\\mathrm{wc}$ is the wind chill index, based on the Fahrenheit scale; $T_\\mathrm{a}$ is the air temperature in degrees Fahrenheit, and $v$ is the wind speed in miles per hour. (Note: Windchill temperature is defined only for temperatures at or below 50 °F and wind speeds above 3.0 miles per hour.)", "_____no_output_____" ] ], [ [ "# your code here", "_____no_output_____" ] ], [ [ "### Solution", "_____no_output_____" ] ], [ [ "v = 5 # miles per hour\nTa = 32 # air temperature in F\nTwc = 35.74 + 0.6215 * Ta - 35.75 * v**0.16 + 0.4275 * Ta * v**0.16\nprint(\"The windchil index (feels-like) is:\", int(Twc))", "_____no_output_____" ] ], [ [ "## Exercise 4", "_____no_output_____" ], [ "You have a loan with a given principal amount $p$, to be repaid over a period of $n$ years. At the end of each year, you get charged an interest of $r$ for the total amount that you owe. Each year you pay an installment equal to $1/n$-th of the initial principal, plus interest on the *remaining* principal. \n\nAssume that the principal is \\\\$10K, interest rate of 3%, and repayment is over 10 years.\n\nWrite code that computes how much you owe at the end of year 1. Then write code for calculating your payment at the end of year 2.\n\n", "_____no_output_____" ] ], [ [ "# your code here", "_____no_output_____" ] ], [ [ "### Solution", "_____no_output_____" ] ], [ [ "principal = 10000\nrate = 0.03\nyears = 10", "_____no_output_____" ], [ "interest = rate * principal\npayment = principal / years + interest\nprint(\"Payment at the end of year 1\")\nprint(payment)", "_____no_output_____" ], [ "remaining_principal = principal - principal / years\ninterest = rate * remaining_principal\npayment = principal / years + interest\nprint(\"payment at the end of year 2\")\nprint(payment)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ec4e252121b2e33feb049d4819a43c596417c74d
3,528
ipynb
Jupyter Notebook
demos/webfilters/KinaseSearchDemo.ipynb
sbliven/mmtf-pyspark
3d444178bdc0d5128aafdb1326fec12b5d7634b5
[ "Apache-2.0" ]
59
2018-01-28T06:50:56.000Z
2022-02-10T06:07:12.000Z
demos/webfilters/KinaseSearchDemo.ipynb
sbliven/mmtf-pyspark
3d444178bdc0d5128aafdb1326fec12b5d7634b5
[ "Apache-2.0" ]
101
2018-02-01T20:51:10.000Z
2022-01-24T00:50:29.000Z
demos/webfilters/KinaseSearchDemo.ipynb
sbliven/mmtf-pyspark
3d444178bdc0d5128aafdb1326fec12b5d7634b5
[ "Apache-2.0" ]
29
2018-01-29T10:09:51.000Z
2022-01-23T18:53:28.000Z
24
249
0.552154
[ [ [ "# Author Search Demo\n\n![pdbj](https://pdbj.org/content/default.svg)\n\nExample query for human protein-serine/threonine kinases using SIFTS data retrieved with PDBj Mine 2 webservices.\n\n\n## References\n\nThe \"Structure Integration with Function, Taxonomy and Sequence\" is the authoritative source of up-to-date residue-level annotation of structures in the PDB with data available in UniProt, IntEnz, CATH, SCOP, GO, InterPro,Pfam and PubMed.\n[SIFTS](https://www.ebi.ac.uk/pdbe/docs/sifts/overview.html) \n\nData are provided through: \n[Mine 2 SQL](https://pdbj.org/help/mine2-sql)\n\nQueries can be designed with the interactive\n[PDBj Mine 2 query service](https://pdbj.org/mine/sql)\n\n\n\n## Imports", "_____no_output_____" ] ], [ [ "from pyspark.sql import SparkSession\nfrom mmtfPyspark.webfilters import PdbjMineSearch\nfrom mmtfPyspark.mappers import StructureToPolymerChains\nfrom mmtfPyspark.io import mmtfReader", "_____no_output_____" ] ], [ [ "#### Configure Spark ", "_____no_output_____" ] ], [ [ "spark = SparkSession.builder.appName(\"KinaseSearchDemo\").getOrCreate()", "_____no_output_____" ] ], [ [ "## Query for human protein-serine/threonine kinases using SIFTS data", "_____no_output_____" ] ], [ [ "sql = \"SELECT t.pdbid, t.chain FROM sifts.pdb_chain_taxonomy AS t \"\\\n + \"JOIN sifts.pdb_chain_enzyme AS e ON (t.pdbid = e.pdbid AND t.chain = e.chain) \"\\\n + \"WHERE t.scientific_name = 'Homo sapiens' AND e.ec_number = '2.7.11.1'\"", "_____no_output_____" ] ], [ [ "## Read PDB and filter by author", "_____no_output_____" ] ], [ [ "path = \"../../resources/mmtf_reduced_sample/\"\n\npdb = mmtfReader.read_sequence_file(path) \\\n .flatMap(StructureToPolymerChains()) \\\n .filter(PdbjMineSearch(sql))\n\nprint(f\"Number of entries matching query: {pdb.count()}\")", "Number of entries matching query: 119\n" ] ], [ [ "## Terminate Spark Context", "_____no_output_____" ] ], [ [ "spark.stop()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec4e28590352e362c9d3695bbe17294791033625
20,788
ipynb
Jupyter Notebook
docs/GeneDropping.ipynb
OpenMendel/MendelGeneDropping.jl
552cce6a46dd26ac1e50a4682bfaceae184008b1
[ "MIT" ]
1
2019-04-23T17:23:24.000Z
2019-04-23T17:23:24.000Z
docs/GeneDropping.ipynb
OpenMendel/MendelGeneDropping.jl
552cce6a46dd26ac1e50a4682bfaceae184008b1
[ "MIT" ]
2
2018-08-28T18:17:36.000Z
2021-02-16T18:31:20.000Z
docs/GeneDropping.ipynb
OpenMendel/MendelGeneDropping.jl
552cce6a46dd26ac1e50a4682bfaceae184008b1
[ "MIT" ]
1
2017-11-25T22:20:28.000Z
2017-11-25T22:20:28.000Z
49.377672
985
0.607033
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec4e2cbb93ef67517c3cdb2a113461426e149960
10,107
ipynb
Jupyter Notebook
NHDPlus21_Into_SB_For_BIS/Reg10U_NHDPlusV21_IntoSB_BIS.ipynb
dwief-usgs/BCB_IpythonNotebooks
4e37455ed1b2d82acf247badb06fcc70663f14c3
[ "CC0-1.0" ]
1
2017-11-30T20:39:30.000Z
2017-11-30T20:39:30.000Z
NHDPlus21_Into_SB_For_BIS/Reg10U_NHDPlusV21_IntoSB_BIS.ipynb
dwief-usgs/BCB_IpythonNotebooks
4e37455ed1b2d82acf247badb06fcc70663f14c3
[ "CC0-1.0" ]
null
null
null
NHDPlus21_Into_SB_For_BIS/Reg10U_NHDPlusV21_IntoSB_BIS.ipynb
dwief-usgs/BCB_IpythonNotebooks
4e37455ed1b2d82acf247badb06fcc70663f14c3
[ "CC0-1.0" ]
null
null
null
39.174419
998
0.603344
[ [ [ "# This python code builds ScienceBase items that house and describe specific versions of data files from the NHDPlusV2.1 that are being used in the Biogeographic Information System. Data were extracted from ftp://ftp.horizon-systems.com/NHDplus/NHDPlusV21/ and stored within ScienceBase as attachments. Although reorganized, the files stored in the ScienceBase Items were not altered. In future iterations of this code we would like to avoid using local disk space and operations that may be dependent on a local operating system. ", "_____no_output_____" ] ], [ [ "import pysb\nimport urllib\nimport os\nimport getpass\nimport time\nimport subprocess\nfrom zipfile import ZipFile\nimport zipfile", "_____no_output_____" ], [ "#Downloads Files of Interest, The next few steps should be done within memory when we get a chance but didn't find a complete workflow of methods that would get us where we needed to be in memory\nimport urllib.request as ur\nur.urlretrieve('ftp://ftp.horizon-systems.com/NHDplus/NHDPlusV21/Data/NHDPlusMS/NHDPlus10U/NHDPlusV21_MS_10U_NHDPLusAttributes_09.7z', 'NHDPlusV21_MS_10U_NHDPLusAttributes_09.7z')\nur.urlretrieve('ftp://ftp.horizon-systems.com/NHDplus/NHDPlusV21/Data/NHDPlusMS/NHDPlus10U/NHDPlusV21_MS_10U_NHDSnapshot_07.7z', 'NHDPlusV21_MS_10U_NHDSnapshot_07.7z')\nur.urlretrieve('ftp://ftp.horizon-systems.com/NHDplus/NHDPlusV21/Data/NHDPlusMS/NHDPlus10U/NHDPlusV21_MS_10U_NHDPlusCatchment_02.7z', 'NHDPlusV21_MS_10U_NHDPlusCatchment_02.7z')", "_____no_output_____" ], [ "#This code isn't currently doing anything in the SB item creation, but eventually something like this could be used to track the \"last update\" of the NHD file being harvested.\nimport urllib.request\nwith urllib.request.urlopen('ftp://ftp.horizon-systems.com/NHDplus/NHDPlusV21/Data/NHDPlusMS/NHDPlus10U/') as response:\n html = response.read()\n print (html)", "_____no_output_____" ], [ "#Unzips the 7z files. This may only run on windows?\nsubprocess.call(r'\"C:\\Program Files\\7-Zip\\7z.exe\" x ' + 'NHDPlusV21_MS_10U_NHDPLusAttributes_09.7z' )\nsubprocess.call(r'\"C:\\Program Files\\7-Zip\\7z.exe\" x ' + 'NHDPlusV21_MS_10U_NHDSnapshot_07.7z' )\nsubprocess.call(r'\"C:\\Program Files\\7-Zip\\7z.exe\" x ' + 'NHDPlusV21_MS_10U_NHDPlusCatchment_02.7z' )", "_____no_output_____" ], [ "#Selects only the files we are using and zips them into 3 directories (using .zip). The three folders include Hydrography, NHDPlusAttributes, and Catchment\ndataTypes = ['Hydrography', 'NHDPlusAttributes', 'Catchment']\nfor fileType in dataTypes:\n z = ZipFile((fileType + '.zip'), 'w')\n if fileType == 'Hydrography':\n ZipFileList = ['NHDWaterbody.dbf','NHDWaterbody.prj','NHDWaterbody.shp','NHDWaterbody.shx','NHDFlowline.dbf','NHDFlowline.prj','NHDFlowline.shp','NHDFlowline.shx' ]\n for file in ZipFileList:\n procFile = ('NHDPlusMS/NHDPlus10U/NHDSnapshot/Hydrography/' + file)\n z.write(procFile, file)\n elif fileType == 'NHDPlusAttributes':\n ZipFileList = ['elevslope.dbf','PlusFlow.dbf','PlusFlowLineVAA.dbf']\n for file in ZipFileList:\n procFile = ('NHDPlusMS/NHDPlus10U/NHDPlusAttributes/' + file)\n z.write(procFile, file)\n elif fileType == 'Catchment':\n target_dir = r'NHDPlusMS\\NHDPlus10U\\NHDPlusCatchment'\n CatZip = ZipFile('Catchment.zip', 'w', zipfile.ZIP_DEFLATED)\n rootlen = len(target_dir) + 1\n for base, dirs, files in os.walk(target_dir):\n for file in files:\n fn = os.path.join(base, file)\n CatZip.write(fn, fn[rootlen:])", "_____no_output_____" ], [ "#Create ScienceBase Item\n\nloginu=input(\"Username: \") #asks user for username\nsb = pysb.SbSession()\nsb.loginc(str(loginu))\ntime.sleep(2)\n\nret = sb.upload_files_and_create_item(sb.get_my_items_id(), ['Catchment.zip', 'Hydrography.zip', 'NHDPlusAttributes.zip'])\nSbItem = ret['id']\n", "Username: [email protected]\n········\n" ], [ "print (SbItem)", "5983840ce4b0e2f5d4651e72\n" ], [ "#Variables to populate the metadata in the SB Item\n\n#Acquisition Date\nimport datetime\ndNow = datetime.datetime.now()\nAcqDate = dNow.strftime(\"%Y-%m-%d\")\n#AcqDate = dNow.isoformat()\n\n", "_____no_output_____" ], [ "UpdateItem = {'id': SbItem,\n 'title': 'NHDPlusV2.1 Processing Region 10U; Files Used in the Biogeographic Information System',\n 'body': 'A subset of files from within processing region 10U of the NHDPlus Version 2.1. Although reorganized, the files within the attachments are unaltered from the NHDPlus Version 2.1 as they were acquired (see acquisition date listed within this metadata). This item links to python code used to generate the item.',\n 'purpose': 'This item is intended to preseve specific versions of files being used in the Biogeographic Information System.',\n 'dates': [{'type': 'Acquisition', 'dateString': AcqDate, 'label': 'Acquisition'}],\n 'webLinks': [{\"type\":\"sourceCode\",\"typeLabel\":\"Source Code\",\"uri\":\"https://github.com/dwief-usgs/BCB_Ipython_Notebooks/blob/master/NHDPlus21_Into_SB_For_BIS/Reg10U_NHDPlusV21_IntoSB_BIS.ipynb\",\"rel\":\"related\",\"title\":\"Python Code Used to Develop and Populate This SB Item\",\"hidden\":False},{\"type\":\"webLink\",\"typeLabel\":\"Web Link\",\"uri\":\"http://www.horizon-systems.com/NHDPlus/NHDPlusV2_home.php\",\"rel\":\"related\",\"title\":\"Additional Information About the NHDPlusV2\",\"hidden\":False}],\n 'contacts': [{\"name\":\"Horizon Systems\",\"type\":\"Data Owner\",\"contactType\":\"organization\",\"onlineResource\":\"http://www.horizon-systems.com\",\"organization\":{},\"primaryLocation\":{\"streetAddress\":{},\"mailAddress\":{}}},{\"name\":\"Daniel J Wieferich\",\"oldPartyId\":66431,\"type\":\"Contact\",\"contactType\":\"person\",\"email\":\"[email protected]\",\"active\":True,\"jobTitle\":\"Physical Scientist\",\"firstName\":\"Daniel\",\"middleName\":\"J\",\"lastName\":\"Wieferich\",\"organization\":{\"displayText\":\"Biogeographic Characterization\"},\"primaryLocation\":{\"name\":\"CN=Daniel J Wieferich,OU=CSS,OU=Users,OU=OITS,OU=DI,DC=gs,DC=doi,DC=net - Primary Location\",\"building\":\"DFC Bldg 810\",\"buildingCode\":\"KBT\",\"officePhone\":\"3032024594\",\"faxPhone\":\"3032024710\",\"streetAddress\":{\"line1\":\"W 6th Ave Kipling St\",\"city\":\"Lakewood\",\"state\":\"CO\",\"zip\":\"80225\"},\"mailAddress\":{}},\"orcId\":\"0000-0003-1554-7992\"}],\n 'tags': [{\"type\":\"Theme\",\"scheme\":\"BIS\",\"name\":\"NHDPlusV2.1\"},{\"type\":\"Theme\",\"scheme\":\"BIS\",\"name\":\"Reg10U\"}]\n }\n\nupdateItem = sb.updateSbItem(UpdateItem)", "_____no_output_____" ], [ "#Remove unneeded local copies of files\nimport shutil\nimport os\n\nos.remove('Catchment.zip')\nos.remove('Hydrography.zip')\nos.remove('NHDPlusAttributes.zip')\nos.remove('NHDPlusV21_MS_10U_NHDPLusAttributes_09.7z')\nos.remove('NHDPlusV21_MS_10U_NHDPlusCatchment_02.7z')\nos.remove('NHDPlusV21_MS_10U_NHDSnapshot_07.7z')\nshutil.rmtree('NHDPlusMS')", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4e32681bb27239f2f42c89321ad02b9a1223d3
6,886
ipynb
Jupyter Notebook
Instagram/Raw data/Posts/ig_foodies_scraper.ipynb
terenceneo/Social-Analytics
8e2f69640c2dcb107eb3e066dd7d998238acb298
[ "Apache-2.0" ]
1
2020-07-24T07:06:25.000Z
2020-07-24T07:06:25.000Z
Instagram/Raw data/Posts/ig_foodies_scraper.ipynb
terenceneo/Social-Analytics
8e2f69640c2dcb107eb3e066dd7d998238acb298
[ "Apache-2.0" ]
7
2020-07-20T16:33:05.000Z
2020-07-21T05:55:25.000Z
Instagram/Raw data/Posts/ig_foodies_scraper.ipynb
terenceneo/Social-Analytics
8e2f69640c2dcb107eb3e066dd7d998238acb298
[ "Apache-2.0" ]
3
2020-07-19T06:06:13.000Z
2020-12-01T06:06:41.000Z
31.3
173
0.55533
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"></ul></div>", "_____no_output_____" ], [ "This workbook scrapes a foodies' ig page. ", "_____no_output_____" ] ], [ [ "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom bs4 import BeautifulSoup as bs\nimport time\nimport re\nfrom urllib.request import urlopen\nimport json\nfrom pandas.io.json import json_normalize\nimport pandas as pd, numpy as np\nimport datetime as dt\nimport requests", "_____no_output_____" ], [ "# Specify IG username to scrape\nusername = 'sheeatsshecooks'\n\n# Specify location of chromedriver.exe\nbrowser = webdriver.Chrome(executable_path=r'C:\\Users\\LENOVO\\Downloads\\chromedriver_win32\\chromedriver.exe')\n\nbrowser.get('https://www.instagram.com/'+username+'/?hl=en')\n\nPagelength = browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")", "_____no_output_____" ], [ "# Put the user's IG pictures's links into a list called \"links\"\nlinks = []\nsource = browser.page_source\ndata = bs(source, 'html.parser')\nbody = data.find('body')\nfor link in body.findAll('a'):\n if re.match(\"/p\", link.get('href')):\n links.append('https://www.instagram.com' + link.get('href'))\n \n# print(\"Number of Instagram images: \", len(links))\n# print(links)", "_____no_output_____" ], [ "# Put the user's IG pictures's links into a list called \"links\"\n# Put more pictures' links into \"links\" \n\nPagelength = browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight/1.5);\")\nlinks = []\nsource = browser.page_source\ndata = bs(source, 'html.parser')\nbody = data.find('body')\nfor link in body.findAll('a'):\n if re.match(\"/p\", link.get('href')):\n links.append('https://www.instagram.com' + link.get('href'))\n\n# Sleep time is required. If you don't use this IG may interrupt the script and doesn't scroll through pages\n\ntime.sleep(5) \n\nPagelength = browser.execute_script(\"window.scrollTo(document.body.scrollHeight/1.5, document.body.scrollHeight/3.0);\")\nsource = browser.page_source\ndata = bs(source, 'html.parser')\nbody = data.find('body')\nfor link in body.findAll('a'):\n if re.match(\"/p\", link.get('href')):\n links.append('https://www.instagram.com' + link.get('href'))\n \nprint(\"Number of Instagram images: \", len(links))\nprint(links)", "_____no_output_____" ], [ "# Open the pictures in \"links\"\n# Get details eg. timestamp, caption, comments, likes, etc. \n# Put details in dataframe\n\ndef get_date(created):\n return dt.datetime.fromtimestamp(int(created))\n\ndf = pd.DataFrame()\ntimestamp_list = []\ncaption_list = []\nnum_likes_list = [] \nnum_comments_list = []\ncomments_list = []\n \nfor link in links:\n req = requests.get(link).text\n soup = bs(req, \"html.parser\")\n scripts = soup.find_all(\"script\")\n for script in scripts:\n if script.text[:18] == \"window._sharedData\":\n break\n\n data = json.loads(script.contents[0][21:-1])\n \n unix_time = data[\"entry_data\"][\"PostPage\"][0][\"graphql\"][\"shortcode_media\"][\"taken_at_timestamp\"]\n human_time = get_date(unix_time)\n caption = str(data[\"entry_data\"][\"PostPage\"][0][\"graphql\"][\"shortcode_media\"][\"edge_media_to_caption\"][\"edges\"][0][\"node\"][\"text\"])\n num_likes = str(data[\"entry_data\"][\"PostPage\"][0][\"graphql\"][\"shortcode_media\"][\"edge_media_preview_like\"][\"count\"])\n num_comments = str(data[\"entry_data\"][\"PostPage\"][0][\"graphql\"][\"shortcode_media\"][\"edge_media_to_parent_comment\"][\"count\"])\n\n timestamp_list.append(human_time)\n caption_list.append(caption)\n num_likes_list.append(num_likes)\n num_comments_list.append(num_comments)\n \n comments = [] \n for i in range(len(data[\"entry_data\"][\"PostPage\"][0][\"graphql\"][\"shortcode_media\"][\"edge_media_to_parent_comment\"][\"edges\"])):\n comments.append(data[\"entry_data\"][\"PostPage\"][0][\"graphql\"][\"shortcode_media\"][\"edge_media_to_parent_comment\"][\"edges\"][i][\"node\"][\"text\"])\n comments_list.append(comments)\n \ndf[\"timestamp\"] = timestamp_list\ndf[\"caption\"] = caption_list\ndf[\"no. of likes\"] = num_likes_list\ndf[\"no. of comments\"] = num_comments_list\ndf[\"comments\"] = comments_list", "_____no_output_____" ], [ "df.tail()", "_____no_output_____" ], [ "df.to_excel(\"sheeatsshecooks.xlsx\") ", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
ec4e3aee857e8f4fe9d93dc87b09125b9c79b4d1
390,856
ipynb
Jupyter Notebook
climate_starter.ipynb
tobymbern/SQLAlchemy_Flask_HW
c50bffb5cfbed399124da4a0faa438d04bcfcadd
[ "MIT" ]
null
null
null
climate_starter.ipynb
tobymbern/SQLAlchemy_Flask_HW
c50bffb5cfbed399124da4a0faa438d04bcfcadd
[ "MIT" ]
null
null
null
climate_starter.ipynb
tobymbern/SQLAlchemy_Flask_HW
c50bffb5cfbed399124da4a0faa438d04bcfcadd
[ "MIT" ]
null
null
null
102.506163
82,471
0.771159
[ [ [ "%matplotlib notebook\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "import datetime as dt", "_____no_output_____" ] ], [ [ "# Reflect Tables into SQLAlchemy ORM", "_____no_output_____" ] ], [ [ "# Python SQL toolkit and Object Relational Mapper\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\n%ls", "LICENSE hawaii.sqlite \u001b[31mhawaii_stations.csv\u001b[m\u001b[m*\r\nclimate_starter.ipynb \u001b[31mhawaii_measurements.csv\u001b[m\u001b[m*\r\n" ], [ "engine = create_engine(\"sqlite:///hawaii.sqlite\")", "_____no_output_____" ], [ "# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)", "_____no_output_____" ], [ "# We can view all of the classes that automap found\nBase.classes.keys()", "_____no_output_____" ], [ "# Save references to each table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station", "_____no_output_____" ], [ "# Create our session (link) from Python to the DB\nsession = Session(engine)", "_____no_output_____" ] ], [ [ "# Exploratory Climate Analysis", "_____no_output_____" ] ], [ [ "# Design a query to retrieve the last 12 months of precipitation data and plot the results\n\n# Calculate the date 1 year ago from today\n\n# Perform a query to retrieve the data and precipitation scores\n\n# Save the query results as a Pandas DataFrame and set the index to the date column\n\n# Sort the dataframe by date\n\n# Use Pandas Plotting with Matplotlib to plot the data\n\n# Rotate the xticks for the dates\n", "_____no_output_____" ], [ "# Use Pandas to calcualte the summary statistics for the precipitation data\n", "_____no_output_____" ], [ "# How many stations are available in this dataset?\n", "_____no_output_____" ], [ "# What are the most active stations?\n# List the stations and the counts in descending order.\n", "_____no_output_____" ], [ "# Using the station id from the previous query, calculate the lowest temperature recorded, \n# highest temperature recorded, and average temperature most active station?\n", "_____no_output_____" ], [ "# Choose the station with the highest number of temperature observations.\n# Query the last 12 months of temperature observation data for this station and plot the results as a histogram\n", "_____no_output_____" ], [ "# Write a function called `calc_temps` that will accept start date and end date in the format '%Y-%m-%d' \n# and return the minimum, average, and maximum temperatures for that range of dates\ndef calc_temps(start_date, end_date):\n \"\"\"TMIN, TAVG, and TMAX for a list of dates.\n \n Args:\n start_date (string): A date string in the format %Y-%m-%d\n end_date (string): A date string in the format %Y-%m-%d\n \n Returns:\n TMIN, TAVE, and TMAX\n \"\"\"\n \n return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()\nprint(calc_temps('2012-02-28', '2012-03-05'))", "[(62.0, 69.57142857142857, 74.0)]\n" ], [ "# Use your previous function `calc_temps` to calculate the tmin, tavg, and tmax \n# for your trip using the previous year's data for those same dates.\n", "62.0 68.36585365853658 74.0\n" ], [ "# Plot the results from your previous query as a bar chart. \n# Use \"Trip Avg Temp\" as your Title\n# Use the average temperature for the y value\n# Use the peak-to-peak (tmax-tmin) value as the y error bar (yerr)\n", "_____no_output_____" ], [ "# Calculate the rainfall per weather station for your trip dates using the previous year's matching dates.\n# Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation\n\n", "[('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4, 0.31), ('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9, 0.25), ('USC00518838', 'UPPER WAHIAWA 874.3, HI US', 21.4992, -158.0111, 306.6, 0.1), ('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6, 0.060000000000000005), ('USC00511918', 'HONOLULU OBSERVATORY 702.2, HI US', 21.3152, -157.9992, 0.9, 0.0), ('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0, 0.0), ('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9, 0.0), ('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0, 0.0), ('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5, 0.0)]\n" ] ], [ [ "## Optional Challenge Assignment", "_____no_output_____" ] ], [ [ "# Create a query that will calculate the daily normals \n# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)\n\ndef daily_normals(date):\n \"\"\"Daily Normals.\n \n Args:\n date (str): A date string in the format '%m-%d'\n \n Returns:\n A list of tuples containing the daily normals, tmin, tavg, and tmax\n \n \"\"\"\n \n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n return session.query(*sel).filter(func.strftime(\"%m-%d\", Measurement.date) == date).all()\n \ndaily_normals(\"01-01\")", "_____no_output_____" ], [ "# calculate the daily normals for your trip\n# push each tuple of calculations into a list called `normals`\n\n# Set the start and end date of the trip\n\n# Use the start and end date to create a range of dates\n\n# Stip off the year and save a list of %m-%d strings\n\n# Loop through the list of %m-%d strings and calculate the normals for each date\n", "_____no_output_____" ], [ "# Load the previous query results into a Pandas DataFrame and add the `trip_dates` range as the `date` index\n", "_____no_output_____" ], [ "# Plot the daily normals as an area plot with `stacked=False`\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ec4e3d205f66677be05405ce450650463c1a76cb
23,679
ipynb
Jupyter Notebook
pages/workshop/NumPy/Numpy Basics.ipynb
fuyihang98/python-training
495e4e8a20de2c25440bf6fff7e07619c3fa3d21
[ "BSD-3-Clause" ]
1
2022-02-22T04:57:24.000Z
2022-02-22T04:57:24.000Z
pages/workshop/NumPy/Numpy Basics.ipynb
fuyihang98/python-training
495e4e8a20de2c25440bf6fff7e07619c3fa3d21
[ "BSD-3-Clause" ]
null
null
null
pages/workshop/NumPy/Numpy Basics.ipynb
fuyihang98/python-training
495e4e8a20de2c25440bf6fff7e07619c3fa3d21
[ "BSD-3-Clause" ]
null
null
null
20.716535
300
0.498839
[ [ [ "<a name=\"pagetop\"></a>\n<div style=\"width:1000 px\">\n\n<div style=\"float:right; width:98 px; height:98px;\">\n<img src=\"https://raw.githubusercontent.com/Unidata/MetPy/master/src/metpy/plots/_static/unidata_150x150.png\" alt=\"Unidata Logo\" style=\"height: 98px;\">\n</div>\n\n<h1>NumPy Basics</h1>\n<h3>Unidata Python Workshop</h3>\n\n<div style=\"clear:both\"></div>\n</div>\n\n<hr style=\"height:2px;\">\n\n<div style=\"float:right; width:250 px\"><img src=\"http://www.contribute.geeksforgeeks.org/wp-content/uploads/numpy-logo1.jpg\" alt=\"NumPy Logo\" style=\"height: 250px;\"></div>\n\n### Questions\n1. What are arrays?\n2. How can arrays be manipulated effectively in Python?\n\n### Objectives\n1. Create an array of ‘data’.\n2. Perform basic calculations on this data using python math functions.\n3. Slice and index the array", "_____no_output_____" ], [ "NumPy is the fundamental package for scientific computing with Python. It contains among other things:\n- a powerful N-dimensional array object\n- sophisticated (broadcasting) functions\n- useful linear algebra, Fourier transform, and random number capabilities\n\nThe NumPy array object is the common interface for working with typed arrays of data across a wide-variety of scientific Python packages. NumPy also features a C-API, which enables interfacing existing Fortran/C/C++ libraries with Python and NumPy.", "_____no_output_____" ], [ "## Create an array of 'data'\n\nThe NumPy array represents a *contiguous* block of memory, holding entries of a given type (and hence fixed size). The entries are laid out in memory according to the shape, or list of dimension sizes.", "_____no_output_____" ] ], [ [ "# Convention for import to get shortened namespace\nimport numpy as np", "_____no_output_____" ], [ "# Create a simple array from a list of integers\na = np.array([1, 2, 3, 4, 5, 6])\na", "_____no_output_____" ], [ "# See how many dimensions the array has\na.ndim", "_____no_output_____" ], [ "# Print out the shape attribute\na.shape", "_____no_output_____" ], [ "# Print out the data type attribute\na.dtype", "_____no_output_____" ], [ "# This time use a nested list of floats\na = np.array([[1., 2., 3., 4., 5., 6.]])\na", "_____no_output_____" ], [ "# See how many dimensions the array has\na.ndim", "_____no_output_____" ], [ "# Print out the shape attribute\na.shape", "_____no_output_____" ], [ "# Print out the data type attribute\na.dtype", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-warning\">\n<h2>Poll</h2>\nPlease go to <a href=\"http://www.PollEv.com/johnleeman205\">http://www.PollEv.com/johnleeman205</a> to take a quick poll.\n</div>", "_____no_output_____" ], [ "NumPy also provides helper functions for generating arrays of data to save you typing for regularly spaced data. \n\n* `arange(start, stop, interval)` creates a range of values in the interval `[start,stop)` with `step` spacing.\n* `linspace(start, stop, num)` creates a range of `num` evenly spaced values over the range `[start,stop]`.", "_____no_output_____" ], [ "### arange", "_____no_output_____" ] ], [ [ "a = np.arange(6)\nprint(a)", "[0 1 2 3 4 5]\n" ], [ "a = np.arange(3, 15)\nprint(a)", "[ 3 4 5 6 7 8 9 10 11 12 13 14]\n" ], [ "a = np.arange(1, 10, 3)\nprint(a)", "[1 4 7]\n" ] ], [ [ "<div class=\"alert alert-warning\">\n<h2>Poll</h2>\nPlease go to <a href=\"http://www.PollEv.com/johnleeman205\">http://www.PollEv.com/johnleeman205</a> to take a quick poll.\n</div>", "_____no_output_____" ], [ "### linspace", "_____no_output_____" ] ], [ [ "b = np.linspace(5, 15, 5)\nprint(b)", "[ 5. 7.5 10. 12.5 15. ]\n" ], [ "b = np.linspace(2.5, 10.25, 11)\nprint(b)", "[ 2.5 3.275 4.05 4.825 5.6 6.375 7.15 7.925 8.7 9.475\n 10.25 ]\n" ] ], [ [ "<div class=\"alert alert-warning\">\n<h2>Poll</h2>\nPlease go to <a href=\"http://www.PollEv.com/johnleeman205\">http://www.PollEv.com/johnleeman205</a> to take a quick poll.\n</div>", "_____no_output_____" ], [ "## Perform basic calculations with Python\n\n### Basic math\n\nIn core Python, that is *without* NumPy, creating sequences of values and adding them together requires writing a lot of manual loops, just like one would do in C/C++:", "_____no_output_____" ] ], [ [ "a = range(5, 10)\nb = [3 + i * 1.5/4 for i in range(5)]", "_____no_output_____" ], [ "result = []\nfor x, y in zip(a, b):\n result.append(x + y)\nprint(result)", "[8.0, 9.375, 10.75, 12.125, 13.5]\n" ] ], [ [ "That is very verbose and not very intuitive. Using NumPy this becomes:", "_____no_output_____" ] ], [ [ "a = np.arange(5, 10)\nb = np.linspace(3, 4.5, 5)", "_____no_output_____" ], [ "a + b", "_____no_output_____" ] ], [ [ "The four major mathematical operations operate in the same way. They perform an element-by-element calculation of the two arrays. The two must be the same shape though!", "_____no_output_____" ] ], [ [ "a * b", "_____no_output_____" ] ], [ [ "### Constants\n\nNumPy proves us access to some useful constants as well - remember you should never be typing these in manually! Other libraries such as SciPy and MetPy have their own set of constants that are more domain specific.", "_____no_output_____" ] ], [ [ "np.pi", "_____no_output_____" ], [ "np.e", "_____no_output_____" ], [ "# This makes working with radians effortless!\nt = np.arange(0, 2 * np.pi + np.pi / 4, np.pi / 4)\nt", "_____no_output_____" ] ], [ [ "### Array math functions\n\nNumPy also has math functions that can operate on arrays. Similar to the math operations, these greatly simplify and speed up these operations. Be sure to checkout the [listing](https://docs.scipy.org/doc/numpy/reference/routines.math.html) of mathematical functions in the NumPy documentation.", "_____no_output_____" ] ], [ [ "# Calculate the sine function\nsin_t = np.sin(t)\nprint(sin_t)", "_____no_output_____" ], [ "# Round to three decimal places\nprint(np.round(sin_t, 3))", "_____no_output_____" ], [ "# Calculate the cosine function\ncos_t = np.cos(t)\nprint(cos_t)", "_____no_output_____" ], [ "# Convert radians to degrees\ndegrees = np.rad2deg(t)\nprint(degrees)", "_____no_output_____" ], [ "# Integrate the sine function with the trapezoidal rule\nsine_integral = np.trapz(sin_t, t)\nprint(np.round(sine_integral, 3))", "_____no_output_____" ], [ "# Sum the values of the cosine\ncos_sum = np.sum(cos_t)\nprint(cos_sum)", "_____no_output_____" ], [ "# Calculate the cumulative sum of the cosine\ncos_csum = np.cumsum(cos_t)\nprint(cos_csum)", "_____no_output_____" ] ], [ [ "## Index and slice arrays\n\nIndexing is how we pull individual data items out of an array. Slicing extends this process to pulling out a regular set of the items.", "_____no_output_____" ] ], [ [ "# Create an array for testing\na = np.arange(15).reshape(3, 5)", "_____no_output_____" ], [ "a", "_____no_output_____" ] ], [ [ "Indexing in Python is 0-based, so the command below looks for the 2nd item along the first dimension (row) and the 3rd along the second dimension (column).\n\n![](array_index.png)", "_____no_output_____" ] ], [ [ "a[1, 2]", "_____no_output_____" ] ], [ [ "Can also just index on one dimension", "_____no_output_____" ] ], [ [ "a[2]", "_____no_output_____" ] ], [ [ "Negative indices are also allowed, which permit indexing relative to the end of the array.", "_____no_output_____" ] ], [ [ "a[0, -1]", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-warning\">\n<h2>Poll</h2>\nPlease go to <a href=\"http://www.PollEv.com/johnleeman205\">http://www.PollEv.com/johnleeman205</a> to take a quick poll.\n</div>", "_____no_output_____" ], [ "Slicing syntax is written as `start:stop[:step]`, where all numbers are optional.\n- defaults: \n - start = 0\n - stop = len(dim)\n - step = 1\n- The second colon is also optional if no step is used.\n\nIt should be noted that end represents one past the last item; one can also think of it as a half open interval: `[start, end)`", "_____no_output_____" ] ], [ [ "# Get the 2nd and 3rd rows\na[1:3]", "_____no_output_____" ], [ "# All rows and 3rd column\na[:, 2]", "_____no_output_____" ], [ "# ... can be used to replace one or more full slices\na[..., 2]", "_____no_output_____" ], [ "# Slice every other row\na[::2]", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-warning\">\n<h2>Poll</h2>\nPlease go to <a href=\"http://www.PollEv.com/johnleeman205\">http://www.PollEv.com/johnleeman205</a> to take a quick poll.\n</div>", "_____no_output_____" ], [ "<div class=\"alert alert-success\">\n <b>EXERCISE</b>:\n <ul>\n <li>The code below calculates a two point average using a Python list and loop. Convert it do obtain the same results using NumPy slicing</li>\n <li>Bonus points: Can you extend the NumPy version to do a 3 point (running) average?</li>\n </ul>\n</div>", "_____no_output_____" ] ], [ [ "data = [1, 3, 5, 7, 9, 11]\nout = []\n\n# Look carefully at the loop. Think carefully about the sequence of values\n# that data[i] takes--is there some way to get those values as a numpy slice?\n# What about for data[i + 1]?\nfor i in range(len(data) - 1):\n out.append((data[i] + data[i + 1]) / 2)\n\nprint(out)", "_____no_output_____" ], [ "# YOUR CODE GOES HERE", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n <b>SOLUTION</b>\n</div>", "_____no_output_____" ] ], [ [ "# %load solutions/slice.py", "_____no_output_____" ], [ "# YOUR BONUS CODE GOES HERE", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n <b>SOLUTION</b>\n</div>", "_____no_output_____" ] ], [ [ "# %load solutions/slice_bonus.py", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n <b>EXERCISE</b>:\n <ul>\n <li>Given the array of data below, calculate the total of each of the columns (i.e. add each of the three rows together):</li>\n </ul>\n</div>", "_____no_output_____" ] ], [ [ "data = np.arange(12).reshape(3, 4)\n\n# YOUR CODE GOES HERE\n# total = ?", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n <b>SOLUTION</b>\n</div>", "_____no_output_____" ] ], [ [ "# %load solutions/sum_row.py", "_____no_output_____" ] ], [ [ "## Resources\n\nThe goal of this tutorial is to provide an overview of the use of the NumPy library. It tries to hit all of the important parts, but it is by no means comprehensive. For more information, try looking at the:\n- [Tentative NumPy Tutorial](http://wiki.scipy.org/Tentative_NumPy_Tutorial)\n- [NumPy User Guide](http://docs.scipy.org/doc/numpy/user/)\n- [SciPy Lecture Notes](https://scipy-lectures.org/)", "_____no_output_____" ], [ "<a href=\"#pagetop\">Top</a>\n<hr style=\"height:2px;\">", "_____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" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec4e4ecc3128533a1280b7623414a343468d6bc8
4,689
ipynb
Jupyter Notebook
examples/7_custom_callback.ipynb
christosvar/pytorch-wrapper
57c85161bd6e09961cb7a1e69debc8e3e0bf7d29
[ "MIT" ]
111
2018-12-11T08:59:20.000Z
2022-03-16T23:52:26.000Z
examples/7_custom_callback.ipynb
christosvar/pytorch-wrapper
57c85161bd6e09961cb7a1e69debc8e3e0bf7d29
[ "MIT" ]
1
2020-04-16T14:21:47.000Z
2020-04-16T14:21:47.000Z
examples/7_custom_callback.ipynb
christosvar/pytorch-wrapper
57c85161bd6e09961cb7a1e69debc8e3e0bf7d29
[ "MIT" ]
24
2018-12-11T13:36:01.000Z
2022-03-16T23:52:55.000Z
31.05298
158
0.592664
[ [ [ "# Custom Callback (Tensorboard)", "_____no_output_____" ], [ "In this example we will create a custom callback that will log the weights and the gradients of the parameters using Tensorboard.", "_____no_output_____" ], [ "#### Additional libraries\n\nFirst of all we need to install the `tensorflow` and `tensorboard` libraries in order to use Tensorboard.", "_____no_output_____" ] ], [ [ "! pip install tensorflow\n! pip install tensorboard\n", "_____no_output_____" ] ], [ [ "#### Import Statements", "_____no_output_____" ] ], [ [ "from torch.utils.tensorboard import SummaryWriter\n\nfrom pytorch_wrapper.training_callbacks import AbstractCallback\n", "_____no_output_____" ] ], [ [ "#### CallBack definition", "_____no_output_____" ], [ "PyTorchWrapper enables us to inject custom buisness logic in several places of the\ntraining process. In order to do that we need to create a Class that derives\nfrom `pytorch_wrapper.training_callbacks.AbstractCallback` and implement the \nappropriate method(s).\n\nThe possible methods are the following:\n- on_training_start: Called at the beginning of the training process.\n- on_training_end: Called at the end of the training process.\n- on_evaluation_start: Called at the beginning of the evaluation step.\n- on_evaluation_end: Called at the end of the evaluation step.\n- on_epoch_start: Called at the beginning of a new epoch.\n- on_epoch_end: Called at the end of an epoch.\n- on_batch_start: Called just before processing a new batch.\n- on_batch_end: Called after a batch has been processed.\n- post_predict: Called just after prediction during training time.\n- post_loss_calculation: Called just after loss calculation.\n- post_backward_calculation: Called just after backward is called.\n- pre_optimization_step: Called just before the optimization step.\n", "_____no_output_____" ] ], [ [ "class TensorBoardCallBack(AbstractCallback):\n def __init__(self, log_dir):\n super(TensorBoardCallBack, self).__init__()\n self.writer = SummaryWriter(log_dir=log_dir)\n self.n_iter = 0\n self.n_iter_real = 0\n\n def pre_optimization_step(self, training_context):\n \"\"\"\n Called just before the optimization step.\n :param training_context: Dict containing information regarding the training process.\n \"\"\"\n\n model = training_context['system'].model\n self.n_iter_real += 1\n\n if self.n_iter_real % 100 == 0:\n\n self.n_iter += 1\n\n for name, param in model.named_parameters():\n if param.requires_grad:\n self.writer.add_histogram(name, param.detach().cpu().numpy(), self.n_iter)\n\n for name, param in model.named_parameters():\n if param.requires_grad:\n self.writer.add_histogram(name + '-grad', param.grad.detach().cpu().numpy(), self.n_iter)\n", "_____no_output_____" ] ], [ [ "Now we can create this callback and pass it to the `train` method of a `System` object. After training you will be able \nnavigate to the log_dir path and excecute `tensorboard` in order to see the histograms of the weights and gradients that where computed during training.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
ec4e5a5a7ca1c6a52dca84354172fa6979cbe413
91,569
ipynb
Jupyter Notebook
examples/old/BinaryClassificationExample.ipynb
newalexander/supervised-cadres
72ab13efb1abc2b6443f5b6e8cacf85669ff45d6
[ "MIT" ]
3
2019-06-04T13:22:34.000Z
2022-02-21T21:55:20.000Z
examples/old/BinaryClassificationExample.ipynb
newalexander/supervised-cadres
72ab13efb1abc2b6443f5b6e8cacf85669ff45d6
[ "MIT" ]
11
2019-06-21T02:58:15.000Z
2022-02-10T01:15:00.000Z
examples/old/BinaryClassificationExample.ipynb
newalexander/supervised-cadres
72ab13efb1abc2b6443f5b6e8cacf85669ff45d6
[ "MIT" ]
4
2019-02-25T15:14:22.000Z
2020-01-15T15:16:27.000Z
61.046
24,676
0.698817
[ [ [ "In this notebook, we're going to generate some synthetic binary classification data and show how to train supervised cadre models (SCM) on it. We'll train a model with the default parameters, and then we'll show how we can use cross-validation for hyperparameter tuning to get better performance.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport sys\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsys.path.insert(0, '../cadreModels')\n\nfrom classificationBinary import binaryCadreModel\nfrom sklearn.datasets import make_classification\nfrom scipy.stats import zscore, zmap\n\nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "sns.set_style('darkgrid')", "_____no_output_____" ] ], [ [ "Generate data with the `sklearn.datasets.make_classification` function. Bind `X` and `y` into a `pd.DataFrame`.", "_____no_output_____" ] ], [ [ "X, y = make_classification(n_samples=50000, random_state=2125615, n_clusters_per_class=10, \n n_features=50, n_informative=25, n_repeated=15)\n\ndata = pd.DataFrame(X)\ndata.columns = ['f'+str(p) for p in data.columns]\ndata = data.assign(target=y)\nfeatures = data.columns[data.columns != 'target']", "_____no_output_____" ], [ "data.head()", "_____no_output_____" ] ], [ [ "Since the features are continuous, we should standardize them.", "_____no_output_____" ] ], [ [ "D_tr, D_va = train_test_split(data, test_size=0.2, random_state=313616)\n\nD_va[features] = zmap(D_va[features], D_tr[features])\nD_tr[features] = zscore(D_tr[features])", "/home/newa/.conda/envs/my_root/lib/python3.6/site-packages/ipykernel/__main__.py:3: 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: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n app.launch_new_instance()\n/home/newa/.conda/envs/my_root/lib/python3.6/site-packages/pandas/core/indexing.py:537: 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: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self.obj[item] = s\n/home/newa/.conda/envs/my_root/lib/python3.6/site-packages/ipykernel/__main__.py:4: 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: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n" ] ], [ [ "A `binaryCadreModel`'s initialization function takes the following arguments and default values:\n\n* `M=2` -- number of cadres in model\n* `gamma=10.` -- cadre-assignment sharpness\n* `lambda_d=0.01` -- regularization strength for cadre-assignment weight parameter `d`\n* `lambda_W=0.01` -- regularization strength for classification-weight parameter `W`\n* `alpha_d=0.9` -- elastic net mixing weight for cadre-assignment weight parameter `d`\n* `alpha_W=0.9` -- elastic net mixing with for classification-weight parameter `W`\n* `Tmax=10000` -- maximum number of SGD steps to take\n* `record=100` -- during training, how often goodness-of-fit metrics should be evaluated on the data\n* `eta=2e-3` -- initial stepsize / learning rate\n* `Nba=64` -- minibatch size\n* `eps=1e-3` -- convergence tolerance\n* `termination_metric='ROC_AUC'` -- training terminated if the difference between the most recent `termination_metric` value and the second most recent `termination_metric` is less than `eps`", "_____no_output_____" ], [ "Once you initialize a `binaryCadreModel`, you apply the `fit` method to train it. This method takes the following arguments and default values:\n\n* `data` -- `pd.DataFrame` of training data\n* `targetCol` -- string column-name of target feature in `data`\n* `cadreFts=None` -- `pd.Index` of column-names used for cadre-assignment\n* `predictFts=None` -- `pd.Index` of column-names used for target-prediction\n* `dataVa=None` -- optional `pd.DataFrame` of validation data \n* `seed=16162` -- seed for parameter initialization and minibatch generation\n* `store=False` -- whether or not copies `data` and `dataVa` should be added as attributes of the `binaryCadreModel`\n* `progress=False` -- whether or not goodness-of-fit metrics should be printed during training", "_____no_output_____" ], [ "Other attributes of the `binaryCadreModel` include:\n\n* `W` -- matrix of cadre-specific classification weights\n* `W0` -- vector of cadre-specific classification biases\n* `C` -- matrix of cadre centers\n* `d` -- vector of cadre-assignments weights\n* `metrics` -- a `dict` with `'training'` and `'validation'` as keys. Each item is a `pd.DataFrame` of goodness-of-fit metrics evaluated during training. Metrics include loss, accuracy, ROC AUC, and precision-recall (PR) AUC\n* `time` -- list of computer-time values it took for each SGD step to be evaluated\n* `proportions` -- during training, the proportion of the training data assigned to each cadre is recorded. This is a `pd.DataFrame` of those proportions, which lets you see if cadre assignments have converged to a stable distribution.", "_____no_output_____" ], [ "First we're going to train an SCM without really tuning the hyperparameters. Note that `Tmax` is quite large (20001). The number of SGD steps needed for training tends to vary wildly by dataset. Sometimes, only a few hundred are needed. Because of the convergence tolerance `eps`, if you specify too large a `Tmax`, the training will stop after progress slows.", "_____no_output_____" ] ], [ [ "scm = binaryCadreModel(Tmax=20001, record=50, eps=1e-4, lambda_W=1e-3, lambda_d=1e-3, M=10, gamma=1.)\nscm.fit(D_tr, 'target', features, features, D_va, progress=True)", "numbers being printed: SGD iteration, training loss, training accuracy, validation loss, validation accuracy, time\n0\n50 1.2984807 0.517075 1.297145 0.5141 0.16040802001953125\n100 1.1886443 0.550775 1.1874509 0.5463 11.967761516571045\n150 1.1525713 0.565475 1.151257 0.5635 22.949254035949707\n200 1.1297761 0.574425 1.128429 0.5765 33.663105726242065\n250 1.1135666 0.58145 1.1121567 0.5834 43.84789514541626\n300 1.1009313 0.587875 1.099615 0.5928 53.823208808898926\n350 1.0902662 0.593575 1.0889814 0.5989 63.28908324241638\n400 1.0815023 0.598125 1.0802588 0.6023 73.21573829650879\n450 1.0744634 0.602525 1.073235 0.6045 82.95269703865051\n500 1.0682241 0.606975 1.0670334 0.6081 92.10580277442932\n550 1.0628145 0.6104 1.0616798 0.6132 101.66183662414551\n600 1.0579996 0.6147 1.0569385 0.6179 111.35325717926025\n650 1.0539076 0.6175 1.0528872 0.6196 121.34262418746948\n700 1.050068 0.6201 1.0491099 0.6229 131.49778866767883\n750 1.0468949 0.6219 1.0459743 0.6246 140.51393866539001\n800 1.0438342 0.624325 1.042928 0.6255 150.43138599395752\n850 1.0410184 0.6263 1.0401587 0.6274 159.74762153625488\n900 1.0385079 0.62785 1.0377221 0.6302 169.33587527275085\n950 1.0362376 0.63 1.0354745 0.6319 178.9903061389923\n1000 1.0341733 0.6319 1.0333968 0.6332 189.06610560417175\n1050 1.0324463 0.633375 1.0317111 0.6335 199.0310995578766\n1100 1.0306022 0.634475 1.029889 0.6357 209.14070653915405\n1150 1.0289488 0.636575 1.028254 0.6367 219.67273902893066\n1200 1.0274383 0.638225 1.0267512 0.6391 230.64619517326355\n1250 1.026089 0.639075 1.0254306 0.6398 241.1908106803894\n1300 1.0246923 0.6407 1.0240526 0.6419 251.37676692008972\n1350 1.0235015 0.641525 1.0228912 0.6421 261.7817792892456\n1400 1.0224794 0.64255 1.0218996 0.6434 271.5611367225647\n1450 1.0213741 0.6434 1.020763 0.6454 281.3336479663849\n1500 1.0202988 0.64465 1.0196947 0.6457 291.50555992126465\n1550 1.0193259 0.64545 1.0187743 0.6454 301.8103790283203\n1600 1.0184225 0.6461 1.0178884 0.646 311.5369575023651\n1650 1.01746 0.64725 1.0169306 0.6459 321.4680836200714\n1700 1.016701 0.648575 1.0161842 0.646 330.8765652179718\n1750 1.0160935 0.64905 1.0155878 0.6472 340.7576570510864\n1800 1.0153413 0.649925 1.0148764 0.6468 350.72644329071045\n1850 1.0146592 0.650875 1.0142295 0.6472 360.47241163253784\n1900 1.0140145 0.65225 1.0136396 0.6481 370.663964509964\n1950 1.0133808 0.6531 1.0130249 0.6493 380.45010590553284\n2000 1.0128322 0.654 1.0125104 0.6505 390.78141808509827\n2050 1.0123044 0.655025 1.0119956 0.652 401.918123960495\n2100 1.0117325 0.655475 1.0114225 0.6536 411.69665694236755\n2150 1.0112698 0.65605 1.0109704 0.6547 421.62110018730164\n2200 1.010825 0.656625 1.0105476 0.6544 431.1120300292969\n2250 1.0104668 0.657125 1.0102031 0.6555 440.68647050857544\n2300 1.0100971 0.657725 1.0098437 0.6558 450.675719499588\n2350 1.0097644 0.6576 1.0095159 0.6558 460.3006613254547\n2400 1.0094018 0.6576 1.0091656 0.6567 470.0137550830841\n2450 1.0090091 0.65835 1.0087845 0.6576 480.0735487937927\n2500 1.008688 0.658375 1.0084815 0.6583 490.6084771156311\n2550 1.0084109 0.659175 1.0082192 0.659 500.2664301395416\n2600 1.0081751 0.6601 1.0080003 0.6595 510.2110471725464\n2650 1.0079514 0.66075 1.0077859 0.6609 519.0919890403748\n2700 1.0077227 0.661925 1.0075693 0.6616 527.9099519252777\n2750 1.0074484 0.662225 1.0073074 0.6624 537.3427712917328\n2800 1.0071951 0.6634 1.0070647 0.6629 546.765200138092\n2850 1.0069638 0.663575 1.0068378 0.664 555.5264751911163\n2900 1.0066494 0.664225 1.0065564 0.6632 564.8310313224792\n2950 1.006421 0.6652 1.006345 0.6635 574.4652636051178\n3000 1.0062405 0.66555 1.0061991 0.6641 583.8569414615631\n3050 1.0059494 0.66635 1.005922 0.6646 593.2611258029938\n3100 1.0057079 0.66655 1.0057105 0.6657 602.7320125102997\n3150 1.005502 0.666825 1.0055379 0.6658 612.2166702747345\n3200 1.005301 0.667125 1.0053685 0.6662 621.5780584812164\n3250 1.0051064 0.667875 1.005192 0.6665 631.9755754470825\n3300 1.0049787 0.6683 1.0050905 0.6675 641.428147315979\n3350 1.0047683 0.66945 1.0048943 0.6686 651.4228754043579\n3400 1.004645 0.6696 1.0047716 0.6687 661.7682123184204\n3450 1.0044938 0.6697 1.0046428 0.6685 671.3290729522705\n3500 1.004345 0.66995 1.0045022 0.6697 679.9789485931396\n3550 1.0042195 0.67065 1.0043861 0.6698 688.838677406311\n3600 1.0040691 0.670625 1.0042535 0.671 698.3323218822479\n3650 1.0039271 0.67085 1.0041189 0.6711 707.7633645534515\n3700 1.0037835 0.671025 1.003992 0.6708 717.1686017513275\n3750 1.0037214 0.671125 1.0039344 0.6709 727.0570106506348\n3800 1.0036013 0.671825 1.0038103 0.6719 736.6477103233337\n3850 1.0034882 0.67215 1.003703 0.6714 746.4842140674591\n3900 1.0032843 0.6723 1.0034928 0.6719 755.7556331157684\n3950 1.0031608 0.672675 1.003372 0.6722 765.3188097476959\n4000 1.0030643 0.67285 1.0032868 0.6719 775.0872633457184\n4050 1.0029649 0.67365 1.0031915 0.6721 784.9987847805023\n4100 1.0028217 0.673975 1.0030594 0.6722 794.3359611034393\n4150 1.0027512 0.674475 1.0029904 0.6717 803.9905259609222\n4200 1.002605 0.675175 1.0028439 0.6735 813.9735233783722\n4250 1.002497 0.67545 1.0027444 0.6747 823.2619225978851\n4300 1.0023721 0.6758 1.002629 0.6741 832.4009275436401\n4350 1.0023291 0.676375 1.0025992 0.6745 842.8124632835388\n4400 1.0022455 0.676675 1.002525 0.6745 851.8851416110992\n4450 1.0021421 0.677225 1.0024272 0.6745 861.1342124938965\n4500 1.0020936 0.6774 1.0023941 0.6747 870.4169545173645\n4550 1.0020189 0.67765 1.0023285 0.6742 879.427497625351\n4600 1.0019748 0.67765 1.0022922 0.6746 888.7499928474426\n4650 1.0018576 0.678125 1.0021815 0.6749 898.3625662326813\n4700 1.0017458 0.6782 1.0020739 0.6759 907.7317795753479\n4750 1.0016718 0.67865 1.0020099 0.6756 916.5043303966522\n4800 1.0016237 0.6792 1.0019569 0.6751 925.3210892677307\n4850 1.0015059 0.68025 1.0018393 0.6752 934.3281033039093\n4900 1.0014584 0.680175 1.0018041 0.6757 943.5932660102844\n4950 1.0013764 0.680375 1.0017209 0.6762 952.934769153595\n5000 1.0013605 0.6803 1.0017065 0.677 962.6235640048981\n5050 1.0012981 0.680525 1.0016475 0.6762 971.6014995574951\n5100 1.0012498 0.6807 1.0016023 0.6766 980.6819007396698\n5150 1.0012249 0.6811 1.0015798 0.6767 989.9250795841217\n5200 1.001187 0.6813 1.0015426 0.6769 999.1021206378937\ntraining has terminated because: lack of sufficient decrease in validation ROC_AUC\n" ] ], [ [ "Once we've trained a model, we can plot the trajectories of the ROC AUC, PR AUC, and accuracy. These plots suggest that a little bit more training time might have been useful, as the AUCs are still increasing.", "_____no_output_____" ] ], [ [ "scm.metrics['validation'].drop('loss', axis=1).plot()", "_____no_output_____" ], [ "scm.metrics['training']['loss'].plot()", "_____no_output_____" ] ], [ [ "We can use the `scoreMetrics` method to calculate a variety of goodness-of-fit metrics on a new dataset.", "_____no_output_____" ] ], [ [ "scm.scoreMetrics(D_va)", "_____no_output_____" ] ], [ [ "The `entropy` method calculates the conditional entropy of the cadre-assignment random variable. This quantifies the confidence of an observation's most likely cadre-assignment.\n\nEach cadre (value of `M`) gets its own conditional entropy. Conditional entropies close to `log2(M)` indicate lots of uncertainty in cadre-assignment for that cadre, and conditional entropies close to 0 indicate very little uncertainty.\n\nMore detail about the use of conditional entropy can be found in `arXiv:1808.04880`.", "_____no_output_____" ] ], [ [ "np.log2(10)", "_____no_output_____" ] ], [ [ "These conditional entropies are all fairly close to their maximum value. This means that the SCM's classification function should not be treated as being very piecewise linear -- there is a lot of nonlinearity in predicted labels. We could try to fix this by retraining with a larger `gamma` value, or we can simply accept it.\n\nThis particular dataset is fairly nonlinear, I believe, so it's not surprising that the conditional entropies are large.", "_____no_output_____" ] ], [ [ "scm.entropy(D_tr)", "_____no_output_____" ] ], [ [ "The `predictFull` method is the one-step prediction function for a new dataset. It returns:\n\n- `f` -- classification margins\n- `l` -- predicted labels\n- `G` -- cadre-membership probabilities\n- `m` -- predicted cadres\n- `l` -- loss function value", "_____no_output_____" ] ], [ [ "f, l, G, m, l = scm.predictFull(D_va)", "_____no_output_____" ], [ "pd.Series(m).value_counts()", "_____no_output_____" ] ], [ [ "In addition to the `predictFull` method, there are more specific prediction methods:\n- `predictMargin` -- returns `f`\n- `predictClass` -- returns `l`\n- `predictCadre` -- returns `m`", "_____no_output_____" ], [ "Now we're going to use 5-fold cross-validation for better hyperparameter tuning. This involves a lot of training, so we're going to do it in parallel.", "_____no_output_____" ] ], [ [ "from itertools import product\nfrom joblib import Parallel, delayed", "_____no_output_____" ], [ "def scmCrossval(d_tr, d_va, d_te, M, l_W, l_d, cadre_fts, predict_fts, Tmax, record):\n mod = binaryCadreModel(\n Tmax=Tmax, record=record,\n M=M, alpha_d=0.99, alpha_W=0.99, lambda_d=l_d, lambda_W=l_W, gamma=1.)\n \n mod.fit(d_tr, 'target', cadre_fts, predict_fts, d_va, progress=False)\n \n ## evaluate on validation and test sets\n err_va = mod.scoreMetrics(d_va)\n err_te = mod.scoreMetrics(d_te)\n \n ## return everything as a list\n return mod, err_va, err_te", "_____no_output_____" ], [ "from sklearn.model_selection import KFold", "_____no_output_____" ] ], [ [ "These are the possible hyperparameter configurations we are going to search over.", "_____no_output_____" ] ], [ [ "l_ds = np.array([0.01, 0.001])\nl_Ws = np.array([0.01, 0.001])\nMs = np.array([4,6,8,10])\nn_folds = 5", "_____no_output_____" ], [ "kf = KFold(n_splits=n_folds, random_state=1414)\n\nn_jobs = np.minimum(12, n_folds * Ms.shape[0] * l_ds.shape[0] * l_Ws.shape[0])\n\nresults = (Parallel(n_jobs=n_jobs, backend='threading', verbose=11)(delayed(scmCrossval)\n (D_tr.iloc[tr], D_tr.iloc[va], D_va, M, l_W, l_d, features, features, 20001, 1000) \n for (M, l_d, l_W, (fold, (tr, va))) in product(Ms, l_ds, l_Ws, enumerate(kf.split(D_tr)))))", "[Parallel(n_jobs=12)]: Using backend ThreadingBackend with 12 concurrent workers.\n[Parallel(n_jobs=12)]: Done 1 tasks | elapsed: 3.0min\n[Parallel(n_jobs=12)]: Done 2 tasks | elapsed: 3.0min\n[Parallel(n_jobs=12)]: Done 3 tasks | elapsed: 3.0min\n[Parallel(n_jobs=12)]: Done 4 tasks | elapsed: 4.3min\n[Parallel(n_jobs=12)]: Done 5 tasks | elapsed: 5.0min\n[Parallel(n_jobs=12)]: Done 6 tasks | elapsed: 5.7min\n[Parallel(n_jobs=12)]: Done 7 tasks | elapsed: 5.8min\n[Parallel(n_jobs=12)]: Done 8 tasks | elapsed: 6.3min\n[Parallel(n_jobs=12)]: Done 9 tasks | elapsed: 7.0min\n[Parallel(n_jobs=12)]: Done 10 tasks | elapsed: 7.0min\n[Parallel(n_jobs=12)]: Done 11 tasks | elapsed: 8.8min\n[Parallel(n_jobs=12)]: Done 12 tasks | elapsed: 9.0min\n[Parallel(n_jobs=12)]: Done 13 tasks | elapsed: 12.3min\n[Parallel(n_jobs=12)]: Done 14 tasks | elapsed: 13.3min\n[Parallel(n_jobs=12)]: Done 15 tasks | elapsed: 13.3min\n[Parallel(n_jobs=12)]: Done 16 tasks | elapsed: 14.8min\n[Parallel(n_jobs=12)]: Done 17 tasks | elapsed: 14.9min\n[Parallel(n_jobs=12)]: Done 18 tasks | elapsed: 16.0min\n[Parallel(n_jobs=12)]: Done 19 tasks | elapsed: 16.0min\n[Parallel(n_jobs=12)]: Done 20 tasks | elapsed: 16.2min\n[Parallel(n_jobs=12)]: Done 21 tasks | elapsed: 17.3min\n[Parallel(n_jobs=12)]: Done 22 tasks | elapsed: 18.0min\n[Parallel(n_jobs=12)]: Done 23 tasks | elapsed: 18.6min\n[Parallel(n_jobs=12)]: Done 24 tasks | elapsed: 18.6min\n[Parallel(n_jobs=12)]: Done 25 tasks | elapsed: 18.6min\n[Parallel(n_jobs=12)]: Done 26 tasks | elapsed: 20.5min\n[Parallel(n_jobs=12)]: Done 27 tasks | elapsed: 20.8min\n[Parallel(n_jobs=12)]: Done 28 tasks | elapsed: 21.3min\n[Parallel(n_jobs=12)]: Done 29 tasks | elapsed: 21.4min\n[Parallel(n_jobs=12)]: Done 30 tasks | elapsed: 22.7min\n[Parallel(n_jobs=12)]: Done 31 tasks | elapsed: 28.7min\n[Parallel(n_jobs=12)]: Done 32 tasks | elapsed: 29.0min\n[Parallel(n_jobs=12)]: Done 33 tasks | elapsed: 29.2min\n[Parallel(n_jobs=12)]: Done 34 tasks | elapsed: 29.8min\n[Parallel(n_jobs=12)]: Done 35 tasks | elapsed: 30.0min\n[Parallel(n_jobs=12)]: Done 36 tasks | elapsed: 30.8min\n[Parallel(n_jobs=12)]: Done 37 tasks | elapsed: 31.4min\n[Parallel(n_jobs=12)]: Done 38 tasks | elapsed: 31.5min\n[Parallel(n_jobs=12)]: Done 39 tasks | elapsed: 31.5min\n[Parallel(n_jobs=12)]: Done 40 tasks | elapsed: 32.8min\n[Parallel(n_jobs=12)]: Done 41 tasks | elapsed: 33.4min\n[Parallel(n_jobs=12)]: Done 42 tasks | elapsed: 33.4min\n[Parallel(n_jobs=12)]: Done 43 tasks | elapsed: 34.6min\n[Parallel(n_jobs=12)]: Done 44 tasks | elapsed: 35.5min\n[Parallel(n_jobs=12)]: Done 45 tasks | elapsed: 36.1min\n[Parallel(n_jobs=12)]: Done 46 tasks | elapsed: 36.4min\n[Parallel(n_jobs=12)]: Done 47 tasks | elapsed: 36.5min\n[Parallel(n_jobs=12)]: Done 48 tasks | elapsed: 36.8min\n[Parallel(n_jobs=12)]: Done 49 tasks | elapsed: 36.9min\n[Parallel(n_jobs=12)]: Done 50 tasks | elapsed: 37.4min\n[Parallel(n_jobs=12)]: Done 51 tasks | elapsed: 38.3min\n[Parallel(n_jobs=12)]: Done 52 tasks | elapsed: 43.2min\n[Parallel(n_jobs=12)]: Done 53 tasks | elapsed: 44.3min\n[Parallel(n_jobs=12)]: Done 54 tasks | elapsed: 44.5min\n[Parallel(n_jobs=12)]: Done 55 tasks | elapsed: 45.0min\n[Parallel(n_jobs=12)]: Done 56 tasks | elapsed: 46.2min\n[Parallel(n_jobs=12)]: Done 57 tasks | elapsed: 46.4min\n[Parallel(n_jobs=12)]: Done 65 out of 80 | elapsed: 49.3min remaining: 11.4min\n[Parallel(n_jobs=12)]: Done 73 out of 80 | elapsed: 53.4min remaining: 5.1min\n[Parallel(n_jobs=12)]: Done 80 out of 80 | elapsed: 62.7min finished\n" ] ], [ [ "This function lets us organize the cross-validation accuracy of each hyperparameter configuration.", "_____no_output_____" ] ], [ [ "def extract_scores(results):\n results_va, results_te = [], []\n for model, scores_va, scores_te in results:\n results_va.append(scores_va)\n results_va[-1] = results_va[-1].assign(M=model.M, lambda_d=model.lambda_d, lambda_W=model.lambda_W)\n \n results_te.append(scores_te)\n results_te[-1] = results_te[-1].assign(M=model.M, lambda_d=model.lambda_d, lambda_W=model.lambda_W)\n results_va = pd.concat(results_va).reset_index(drop=True)\n results_te = pd.concat(results_te).reset_index(drop=True)\n print(results_va.head())\n print(results_te.head())\n return results_va, results_te", "_____no_output_____" ], [ "scores_va, scores_te = extract_scores(results)", " PR_AUC ROC_AUC accuracy loss M lambda_d lambda_W\n0 0.604021 0.602929 0.551625 0.840378 4 0.01 0.01\n1 0.613960 0.622548 0.584375 0.816942 4 0.01 0.01\n2 0.642983 0.647375 0.604875 0.757063 4 0.01 0.01\n3 0.618331 0.630848 0.599500 0.833157 4 0.01 0.01\n4 0.674285 0.662441 0.618750 0.741088 4 0.01 0.01\n PR_AUC ROC_AUC accuracy loss M lambda_d lambda_W\n0 0.602458 0.598755 0.5457 0.840810 4 0.01 0.01\n1 0.622536 0.622885 0.5847 0.816972 4 0.01 0.01\n2 0.661772 0.661841 0.6108 0.756728 4 0.01 0.01\n3 0.622284 0.629413 0.5864 0.832929 4 0.01 0.01\n4 0.660926 0.645047 0.6035 0.741301 4 0.01 0.01\n" ] ], [ [ "This function decides which hyperparameter configuration has the best validation accuracy on average, as measured by `ROC_AUC`.", "_____no_output_____" ] ], [ [ "def get_best_attributes(scores):\n group = scores.groupby(['M','lambda_d','lambda_W'])\n return group.mean().reset_index().sort_values('ROC_AUC', ascending=False).head()", "_____no_output_____" ], [ "get_best_attributes(scores_va)", "_____no_output_____" ] ], [ [ "Now we'll train a final model on the entire training dataset with the best hyperparameters.", "_____no_output_____" ] ], [ [ "scm_best = binaryCadreModel(Tmax=20001, record=1000, eps=1e-4, lambda_W=0.001, lambda_d=0.001, M=6, gamma=1.)\nscm_best.fit(D_tr, 'target', features, features, D_va, progress=True)", "numbers being printed: SGD iteration, training loss, training accuracy, validation loss, validation accuracy, time\n0\n1000 1.387868 0.5104 1.3802397 0.5102 0.1609952449798584\n2000 1.0543379 0.630375 1.0541757 0.6275 30.08755588531494\n3000 1.0130858 0.66165 1.0136889 0.6566 60.266019105911255\n4000 0.9949055 0.67395 0.9959138 0.6682 91.91009736061096\n5000 0.9844632 0.68165 0.9856071 0.6769 123.66660165786743\n6000 0.97760457 0.687175 0.97879696 0.6824 157.73456501960754\n7000 0.9728447 0.691 0.9740023 0.6861 188.15894436836243\n8000 0.9690816 0.694275 0.9702438 0.6888 219.48974514007568\n9000 0.9660039 0.6967 0.967153 0.6922 250.92584085464478\n10000 0.96339166 0.6987 0.96453387 0.6954 282.02784395217896\n11000 0.961117 0.7006 0.9622772 0.6964 314.2528963088989\n12000 0.9590633 0.7022 0.9602563 0.698 346.16024470329285\n13000 0.9573027 0.703075 0.9585674 0.7004 378.1253855228424\n14000 0.95571285 0.7046 0.9570452 0.7019 411.07925605773926\n15000 0.95418906 0.706775 0.9556563 0.7035 442.9778628349304\n16000 0.95273405 0.707725 0.95427394 0.7045 472.7344973087311\n17000 0.95142037 0.709575 0.95307064 0.7055 503.95069694519043\n18000 0.9501459 0.7117 0.951857 0.7073 536.3612205982208\n19000 0.9489216 0.7123 0.95073915 0.7083 568.5978302955627\n20000 0.9477365 0.71345 0.94964594 0.7099 599.4213716983795\ntraining has terminated because: model took 20001 SGD steps\n" ] ], [ [ "This is the accuracy of the original untuned model.", "_____no_output_____" ] ], [ [ "scm.scoreMetrics(D_va)", "_____no_output_____" ] ], [ [ "This is the accuracy of the tuned model.", "_____no_output_____" ] ], [ [ "scm_best.scoreMetrics(D_va)", "_____no_output_____" ] ], [ [ "We see that, by utilizing proper hyperparameter tuning, we are able to increase our `PR_AUC` and `ROC_AUC` scores by about 5% and our accuracy by about 4%.", "_____no_output_____" ], [ "This function can be used to calculate subpopulation-specific metrics. It can be useful to notice if one subpopulation has particularly good or bad accuracy relative to the population.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import roc_auc_score, average_precision_score", "_____no_output_____" ], [ "def precision_metrics(data, model, data_name, M):\n F, L, __, M, __ = model.predictFull(data)\n temp = pd.DataFrame({'f': np.squeeze(F), 'm': np.squeeze(M), 'l': np.squeeze(L), 'y': data['target'].values})\n scores = {'size': [], 'm': [], 'dataset': [], 'accuracy': [], 'ROC_AUC': [], 'PR_AUC': [], 'proportion': []}\n for m in np.unique(M):\n temp_m = temp.loc[temp['m']==m,:]\n if temp_m.shape[0] < 5: continue\n scores['size'].append(temp_m.shape[0])\n scores['m'].append(m)\n scores['dataset'].append(data_name)\n scores['proportion'].append(temp_m['y'].mean())\n scores['accuracy'].append(np.mean(temp_m['l'] == temp_m['y']))\n scores['ROC_AUC'].append(roc_auc_score(temp_m['y'], temp_m['f']))\n scores['PR_AUC'].append(average_precision_score(temp_m['y'], temp_m['f']))\n return pd.DataFrame(scores)[['dataset', 'm', 'size', 'proportion', 'accuracy', 'ROC_AUC', 'PR_AUC']]", "_____no_output_____" ], [ "precision_metrics(D_va, scm_best, 'synthetic', 6)", "_____no_output_____" ] ], [ [ "In this case, we see that cadre 4 has the best `PR_AUC`, and cadre 0 has the best `ROC_AUC`. Cadre 3 has the worst `ROC_AUC` and `PR_AUC`.", "_____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" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
ec4e69096bda3823407c7fab5d4dc602ec937f89
50,998
ipynb
Jupyter Notebook
Max/MNIST-ORBM.ipynb
garibaldu/multicauseRBM
f64f54435f23d04682ac7c15f895a1cf470c51e8
[ "MIT" ]
null
null
null
Max/MNIST-ORBM.ipynb
garibaldu/multicauseRBM
f64f54435f23d04682ac7c15f895a1cf470c51e8
[ "MIT" ]
null
null
null
Max/MNIST-ORBM.ipynb
garibaldu/multicauseRBM
f64f54435f23d04682ac7c15f895a1cf470c51e8
[ "MIT" ]
null
null
null
111.106754
6,086
0.848661
[ [ [ "from scipy.special import expit\nfrom rbmpy.rbm import RBM\nfrom rbmpy.sampler import VanillaSampler, PartitionedSampler\nfrom rbmpy.trainer import VanillaTrainier\nimport numpy as np\nimport rbmpy.datasets, rbmpy.performance, rbmpy.plotter, rbmpy.mnist, pickle, rbmpy.rbm\n\n%matplotlib inline", "_____no_output_____" ], [ "# load the data\nwith open('./models/bar_model', 'rb') as f1:\n bar_model = pickle.load(f1)\n\nwith open('./models/two_model', 'rb') as f2:\n two_model = pickle.load(f2)\n\nnum_items = 20\nbar = bar_model.visible[:num_items]\ntwo = two_model.visible[:num_items]\ncomposite = datasets.composite_datasets(bar, two)\n\npart_sampler = PartitionedSampler(two_model, bar_model, num_items= num_items)\nvan_two_sampler = VanillaSampler(two_model)\nvan_bar_sampler = VanillaSampler(bar_model)\n\n\nvis_van_a = van_two_sampler.reconstruction_given_visible(composite)\nvis_van_b = van_bar_sampler.reconstruction_given_visible(composite)\n\nvis_target_a = van_two_sampler.reconstruction_given_visible(two)\nvis_target_b = van_bar_sampler.reconstruction_given_visible(bar)\n\n\n \n\nplotter.plot(vis_van_a)\nplotter.plot(vis_target_a)\n\nplotter.plot(vis_van_b)\nplotter.plot(vis_target_b)\n# score_part_a = performance.log_likelyhood_score(vis_part_a, vis_target_a)\n# score_van_a = performance.log_likelyhood_score(vis_van_a, vis_target_a)\n\n# score_part_b = performance.log_likelyhood_score(vis_part_b, vis_target_b)\n# score_van_b = performance.log_likelyhood_score(vis_van_b, vis_target_b)\n", "_____no_output_____" ], [ "vis_part_a, vis_part_b = part_sampler.reconstructions_given_visible(composite, num_samples = 40)\nplotter.plot(vis_part_a)\nplotter.plot(vis_part_b)", "0.0% complete\n5.0% complete\n10.0% complete\n15.0% complete\n20.0% complete\n25.0% complete\n30.0% complete\n35.0% complete\n40.0% complete\n45.0% complete\n50.0% complete\n55.00000000000001% complete\n60.0% complete\n65.0% complete\n70.0% complete\n75.0% complete\n80.0% complete\n85.0% complete\n90.0% complete\n95.0% complete\n" ], [ "from scipy.special import xlogy\nimport math\n\ndef log_likelyhood_score(sample, target):\n \"\"\"Lets find the log likelyhood\"\"\"\n # we need the actual visible pattern that we want to compute the score for\n # if vi|ha is 400 | 786\n # and actual vi is 400 | 786 we are in business\n \n safe_log_sample = np.where(sample != 0, np.log(sample), 0)\n\n sample_off = 1 - sample\n safe_log_off_sample = np.where(sample_off != 0, np.log(sample_off), 0)\n \n score = ((target * safe_log_sample) + ((1 - target) * safe_log_off_sample))\n\n score_sum = score.sum()\n return score_sum\n\nscore_part_a = log_likelyhood_score(vis_part_a, vis_target_a)\nscore_van_a = log_likelyhood_score(vis_van_a, vis_target_a)\n\nscore_part_b = log_likelyhood_score(vis_part_b, vis_target_b)\nscore_van_b = log_likelyhood_score(vis_van_b, vis_target_b)", "/usr/local/lib/python3.4/site-packages/IPython/kernel/__main__.py:10: RuntimeWarning: divide by zero encountered in log\n/usr/local/lib/python3.4/site-packages/IPython/kernel/__main__.py:13: RuntimeWarning: divide by zero encountered in log\n" ], [ "plotter.plot(composite)\nprint(\"Scores:\\n\\tPart_a {}\\tVan_a {}\\n\\tPart_b {}\\tVan_b {}\\n\\tA Win?{}\\tB Win?{}\".format(score_part_a, score_van_a, score_part_b, score_van_b, score_part_a > score_van_a, score_part_b > score_van_b))\n# part_a = performance.score(vis_part_a, vis_target_a, two_model.weights, two_model.visible_bias, two_model.hidden_bias)\n# van_a = performance.score(vis_van_a, vis_target_a, two_model.weights, two_model.visible_bias, two_model.hidden_bias)\n# print((part_a)\n# print(van_a)", "_____no_output_____" ], [ "p = PartitionedSampler(two_model, bar_model, num_items= num_items)\nha, hb= p.visible_to_hidden(composite, 100)\ndef sample(hidden, weights, bias):\n return expit(np.dot(hidden,weights) + bias)\nvis = sample(hb, bar_model.weights, bar_model.visible_bias)\nplotter.plot(vis)\nplotter.plot(composite)", "_____no_output_____" ], [ "van_two_sampler = VanillaSampler(two_model)\nvan_bar_sampler = VanillaSampler(bar_model)", "_____no_output_____" ], [ "vis_van_two = sample((van_two_sampler.visible_to_hidden(composite)), two_model.weights, two_model.visible_bias)\nvis_van_bar = sample((van_bar_sampler.visible_to_hidden(composite)), bar_model.weights, bar_model.visible_bias)\ngoal = sample((van_bar_sampler.visible_to_hidden(bar)), bar_model.weights, bar_model.visible_bias)", "_____no_output_____" ], [ "plotter.plot(vis_van_bar)\nplotter.plot(vis)\nplotter.plot(goal)\n", "_____no_output_____" ], [ "plotter.plot(vis)", "_____no_output_____" ], [ "sayHello(\"a\",\"b\",'c','d')", "_____no_output_____" ], [ "from sklearn.neural_network import BernoulliRBM\nprint(two.shape)\n\nmodel = BernoulliRBM(n_components=30, n_iter=500,verbose = 0)\nmodel.fit(two)\n\n", "(20, 784)\n" ], [ "plotter.plot(np.where(model.gibbs(two),1,0))", "_____no_output_____" ], [ "import numpy as np\nimport rbm\nfrom sklearn.linear_model import Perceptron\n\nnum_items = 400\nbar = datasets.data_set_with_name(\"bar\", size = num_items)\nblob = datasets.data_set_with_name(\"blob\", size = num_items)\ntwo = datasets.data_set_with_name(2, size = num_items)\nthree = datasets.data_set_with_name(3, size = num_items)\n\ndef classify(hid_train, train_labels):\n classifier = Perceptron()\n classifier.fit(self.hid_train, self.train_labels)\n\nPartitionedSampler(two_model, bar_model, num_items= num_items)\ntraining = \ntrain_labels = \n\nc = classify(hidden_training_set(training, sampler), train_labels)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4e6f341f2430252430ca7d5778b3084e53e8e1
110,918
ipynb
Jupyter Notebook
notebooks/usecase03_clinical_and_acetylation.ipynb
PayneLab/cptac
531ec27a618270a2405bf876443fa58d0362b3c2
[ "Apache-2.0" ]
53
2019-05-30T02:05:04.000Z
2022-03-16T00:38:58.000Z
notebooks/usecase03_clinical_and_acetylation.ipynb
PayneLab/cptac
531ec27a618270a2405bf876443fa58d0362b3c2
[ "Apache-2.0" ]
20
2020-02-16T23:50:43.000Z
2021-09-26T10:07:59.000Z
notebooks/usecase03_clinical_and_acetylation.ipynb
PayneLab/cptac
531ec27a618270a2405bf876443fa58d0362b3c2
[ "Apache-2.0" ]
17
2019-09-27T20:55:09.000Z
2021-10-19T07:18:06.000Z
149.083333
42,264
0.837736
[ [ [ "# Use Case 3: Associating Clinical Variables with Acetylation", "_____no_output_____" ], [ "For this use case we will show how to analyze the acetylation data with a clinical attribute. We will use the clinical attribute \"Histologic_type\", but you can apply the processes shown here to many other clinical attributes. Our goal is to identify which acetylation sites differ significantly in frequency between non-tumor, serous and endometrial cells.", "_____no_output_____" ], [ "# Step 1: Import Packages and Load Data", "_____no_output_____" ], [ "We will start by importing the data analysis tools we need, importing the cptac package, and loading the Endometrial dataset.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport scipy.stats\nimport statsmodels.stats.multitest\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport math\nimport cptac\nimport cptac.utils as ut\n\ncptac.download(dataset=\"endometrial\", version=\"latest\")\nen = cptac.Endometrial()", " \r" ] ], [ [ "# Step 2: Choose Clinical Attribute and Join Dataframes", "_____no_output_____" ], [ "For this use case, we will use the 'Histologic_type' clinical attribute in order to find differences in acetylation sites between \"endometrioid\" and \"serous\" cancer cells. ", "_____no_output_____" ] ], [ [ "#Set desired attribute to variable 'clinical_attribute'\nclinical_attribute = \"Histologic_type\"", "_____no_output_____" ] ], [ [ "Here we will join our desired clinical attribute with our acetylation dataframe using the `en.join_metadata_to_omics` method.", "_____no_output_____" ] ], [ [ "#Join attribute with acetylation dataframe\nclinical_and_acetylation = en.join_metadata_to_omics(metadata_df_name=\"clinical\", omics_df_name=\"acetylproteomics\",\n metadata_cols=clinical_attribute)\n\n# Use the cptac.utils.reduce_multiindex function to combine the\n# multiple column levels, so it's easier to graph our data\nclinical_and_acetylation = ut.reduce_multiindex(df=clinical_and_acetylation, flatten=True)\n\nclinical_and_acetylation.head()", "_____no_output_____" ] ], [ [ "# Step 3: Format Dataframe to Compare Acetylproteomic Sites Between Histologic Types", "_____no_output_____" ] ], [ [ "clinical_attribute = \"Histologic_type\"\n#Show possible variations of Histologic_type\nclinical_and_acetylation[clinical_attribute].unique()", "_____no_output_____" ] ], [ [ "In this step, we will make two different dataframes for \"Endometrioid\" and \"Serous\" cancer types, as well as fill the NaN columns with \"Non-Tumor.\"", "_____no_output_____" ] ], [ [ "#Make dataframes with only endometrioid and only serous data in order to compare \nendom = clinical_and_acetylation.loc[clinical_and_acetylation[clinical_attribute] == \"Endometrioid\"]\nserous = clinical_and_acetylation.loc[clinical_and_acetylation[clinical_attribute] == \"Serous\"]\n#Here is where we set the NaN values to \"Non_Tumor\"\nclinical_and_acetylation[[clinical_attribute]] = clinical_and_acetylation[[clinical_attribute]].fillna(\n value=\"Non_Tumor\")", "_____no_output_____" ] ], [ [ "Now that we have our different dataframes, we want to make sure that the amount of data we are using for each site is significant. Since there are fewer patients with \"serous\" tumors than with \"endometrioid,\" we will check to make sure that we have at least five values for each acetylation site that we are comparing that have a measurement of intensity for serous patients. We will remove every acetylation site from our dataframe that doesn't have at least five values among the serous patients.", "_____no_output_____" ] ], [ [ "#Remove every column that doesn't have at least 5 values among the serous patients\nprint(\"Total Sites: \", len(serous.columns) - 1)\nsites_to_remove = []\nfor num in range(1, len(serous.columns)):\n serous_site = serous.columns[num]\n one_site = serous[serous_site]\n num_datapoints_ser = one_site.count()\n if num_datapoints_ser < 5:\n sites_to_remove.append(serous_site)\n\nclinical_and_acetylation = clinical_and_acetylation.drop(sites_to_remove, axis = 1)\n\n#Also remove non-tumor patients from our dataframe to use in comparison, as we want to compare only endometrioid and serous types\nclinical_and_acetylation_comparison = clinical_and_acetylation.loc[clinical_and_acetylation['Histologic_type'] != 'Non_Tumor']\n\nprint(\"Removed: \", len(sites_to_remove))\nprint(\"Remaining Sites: \", len(clinical_and_acetylation_comparison.columns) - 1)\nprint(\"Adjusted p-value cutoff will be: \", .05/(len(clinical_and_acetylation_comparison.columns)-1))\n", "Total Sites: 10862\nRemoved: 6926\nRemaining Sites: 3936\nAdjusted p-value cutoff will be: 1.2703252032520325e-05\n" ] ], [ [ "# Step 4: Compare Endometrioid and Serous Values", "_____no_output_____" ], [ "We will now call the wrap_ttest method, which will loop through the data and compare endometrioid versus serous data for each acetylation site. If we find a site that is significantly different, we will add it to a dataframe, with its p-value. The default alpha used is .05, which will be adjusted to account for multiple testing using a bonferroni correction, dividing alpha by the number of comparisons that will occur (the number of comparison columns).", "_____no_output_____" ] ], [ [ "#Make list of all remaining sites in dataframe to pass to wrap_ttest function\ncolumns_to_compare = list(clinical_and_acetylation_comparison.columns)\n\n#Remove the \"Histologic_type\" column (at index 0) from this list \ncolumns_to_compare = columns_to_compare[1:]\n\n#Perform ttest on each column in dataframe\nsignificant_sites_df = ut.wrap_ttest(df=clinical_and_acetylation_comparison, label_column=\"Histologic_type\", comparison_columns=columns_to_compare)\n\n#List significant results\nsignificant_sites_df", "_____no_output_____" ] ], [ [ "# Step 5: Graph Results", "_____no_output_____" ], [ "Now that we have eight acetylation sites that differ significantly between endometrioid and serous intensities, we will graph a couple of them using a boxplot and a stripplot in order to visually see the difference, as well as compare with normal cells.", "_____no_output_____" ] ], [ [ "graphingSite = 'FOXA2_acetylproteomics_K280'\nprint(scipy.stats.ttest_ind(endom[graphingSite], serous[graphingSite]))\nsns.boxplot(x=clinical_attribute, y=graphingSite, data=clinical_and_acetylation, showfliers=False, \n order=[\"Non_Tumor\", \"Endometrioid\", \"Serous\"])\nsns.stripplot(x=clinical_attribute, y=graphingSite, data=clinical_and_acetylation, color='.3', \n order=[\"Non_Tumor\", \"Endometrioid\", \"Serous\"])\nplt.show()", "Ttest_indResult(statistic=5.991702127182772, pvalue=3.89570439448459e-08)\n" ], [ "graphingSite = 'TBL1XR1_acetylproteomics_K102'\nprint(scipy.stats.ttest_ind(endom[graphingSite], serous[graphingSite]))\nsns.boxplot(x=clinical_attribute, y=graphingSite, data=clinical_and_acetylation, showfliers = False, \n order=[\"Non_Tumor\", \"Endometrioid\", \"Serous\"])\nsns.stripplot(x=clinical_attribute, y=graphingSite, data=clinical_and_acetylation, color='.3', \n order=[\"Non_Tumor\", \"Endometrioid\", \"Serous\"])\nplt.show()", "Ttest_indResult(statistic=-6.058405376720226, pvalue=2.8961545616585778e-08)\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
ec4e9c95b3856805784cebd57bf1b4fe4691c16b
757,349
ipynb
Jupyter Notebook
VGG19.ipynb
ankitdubey987/Enabling-CT-Scans-for-covid-detection-using-transfer-learning-based-neural-networks
58f0ea9c86f91001a726b5a2cb24626e0442deb7
[ "MIT" ]
null
null
null
VGG19.ipynb
ankitdubey987/Enabling-CT-Scans-for-covid-detection-using-transfer-learning-based-neural-networks
58f0ea9c86f91001a726b5a2cb24626e0442deb7
[ "MIT" ]
null
null
null
VGG19.ipynb
ankitdubey987/Enabling-CT-Scans-for-covid-detection-using-transfer-learning-based-neural-networks
58f0ea9c86f91001a726b5a2cb24626e0442deb7
[ "MIT" ]
null
null
null
468.946749
74,552
0.924401
[ [ [ "from builtins import range, input\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Input, Lambda, Dense, Flatten, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.applications.vgg19 import VGG19, preprocess_input, decode_predictions\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n \nfrom sklearn.metrics import confusion_matrix, roc_curve\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n \nfrom glob import glob\nimport pandas as pd\n \nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "import os\npath = list()\ntarget = list()\nfor root, _, filenames in os.walk('dataset'):\n for filename in filenames:\n if filename.endswith('jpg') or filename.endswith('png') or filename.endswith('jpeg'):\n full_path = os.path.join(root,filename)\n image_target_class = full_path.split('\\\\')[-2]\n# print(image_target_class)\n# print(os.path.join(root,filename))\n path.append(full_path)\n target.append(image_target_class)\nprint('Done!')", "Done!\n" ], [ "df = pd.DataFrame(data=zip(path,target),columns=['path','target'])\ndf.head()", "_____no_output_____" ], [ "df.groupby('target').count()", "_____no_output_____" ], [ "train_df, valid_df = train_test_split(\n df,\n stratify = df['target'],\n test_size = 0.2,\n random_state=42\n)\n", "_____no_output_____" ], [ "print(train_df.shape)\nprint(valid_df.shape)\nprint(train_df.target.value_counts())\nprint(valid_df.target.value_counts())", "(596, 2)\n(150, 2)\nCT_NonCOVID 317\nCT_COVID 279\nName: target, dtype: int64\nCT_NonCOVID 80\nCT_COVID 70\nName: target, dtype: int64\n" ], [ "target_size = (124,124)\ninput_image_size = (124,124,3)\nbatch_size = 10\n\ndatagen = ImageDataGenerator(\n rescale=1.0/255.0,\n horizontal_flip = True,\n)\n\ntrain_iterator = datagen.flow_from_dataframe(\n train_df,\n target_size = target_size,\n x_col='path',\n y_col='target',\n seed=42,\n batch_size=batch_size,\n class_mode='categorical',\n shuffle=True\n)\n\ntrain_datagen = ImageDataGenerator(\n rescale=1.0/255.0\n)\n\nvalidation_iterator = train_datagen.flow_from_dataframe(\n valid_df,\n target_size = target_size,\n x_col='path',\n y_col='target',\n seed=42,\n batch_size=batch_size,\n class_mode='categorical',\n shuffle=True\n)\n\nprint(train_iterator)\nprint(validation_iterator)", "Found 596 validated image filenames belonging to 2 classes.\nFound 150 validated image filenames belonging to 2 classes.\n<tensorflow.python.keras.preprocessing.image.DataFrameIterator object at 0x000001DD5596DD30>\n<tensorflow.python.keras.preprocessing.image.DataFrameIterator object at 0x000001DD2162F190>\n" ], [ "# confirm the scaling works\nbatchX, batchY = train_iterator.next()\nprint('Batch shape=%s, min=%.3f, max=%.3f' % (batchX.shape, batchX.min(), batchX.max()))", "Batch shape=(10, 124, 124, 3), min=0.000, max=1.000\n" ], [ "base_model = VGG19(\n input_shape = (124,124,3),\n include_top = False,\n weights = 'imagenet'\n)\nfor layer in base_model.layers:\n layer.trainable = False\n\nx = base_model.output\nx = Flatten()(x)\n# x = Dense(1024, activation = 'relu')(x)\n# x = Dense(512,activation='relu')(x)\n# x = Dense(64,activation='relu')(x)\nx = Dropout(0.3)(x)\n# x = Dense(32,activation='relu')(x)\n# x = Dense(16,activation='relu')(x)\n# x = Dense(8,activation='relu')(x)\npredictions = Dense(2, activation='softmax')(x)\nmodel_final = Model(base_model.input,predictions)\n\nmodel_final.compile(\n 'adam',\n loss='categorical_crossentropy',\n metrics=['accuracy']\n)", "_____no_output_____" ], [ "model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath='./VGG19ModelCheckPoints/',\n monitor='val_loss',\n verbose=0,\n save_best_only=True,\n save_weights_only=False,\n mode='min',\n save_freq='epoch'\n)", "_____no_output_____" ], [ "hist = model_final.fit(\n train_iterator,\n validation_data = validation_iterator,\n steps_per_epoch = train_iterator.samples//train_iterator.batch_size,\n validation_steps = validation_iterator.samples//validation_iterator.batch_size,\n epochs = 200,\n callbacks=[model_checkpoint_callback]\n)", "Epoch 1/200\n59/59 [==============================] - 31s 517ms/step - loss: 0.7166 - accuracy: 0.5717 - val_loss: 0.6469 - val_accuracy: 0.6267\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 2/200\n59/59 [==============================] - 30s 502ms/step - loss: 0.5391 - accuracy: 0.7389 - val_loss: 0.6036 - val_accuracy: 0.6600\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 3/200\n59/59 [==============================] - 30s 505ms/step - loss: 0.5101 - accuracy: 0.7423 - val_loss: 0.5797 - val_accuracy: 0.7333\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 4/200\n59/59 [==============================] - 29s 500ms/step - loss: 0.4228 - accuracy: 0.8072 - val_loss: 0.5948 - val_accuracy: 0.6800\nEpoch 5/200\n59/59 [==============================] - 30s 503ms/step - loss: 0.4045 - accuracy: 0.8242 - val_loss: 0.5629 - val_accuracy: 0.7467\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 6/200\n59/59 [==============================] - 30s 501ms/step - loss: 0.3972 - accuracy: 0.8123 - val_loss: 0.5804 - val_accuracy: 0.7267\nEpoch 7/200\n59/59 [==============================] - 30s 505ms/step - loss: 0.4036 - accuracy: 0.8157 - val_loss: 0.5548 - val_accuracy: 0.7467\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 8/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.3467 - accuracy: 0.8458 - val_loss: 0.5519 - val_accuracy: 0.7200\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 9/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.3489 - accuracy: 0.8362 - val_loss: 0.5437 - val_accuracy: 0.7533\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 10/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.3616 - accuracy: 0.8379 - val_loss: 0.5429 - val_accuracy: 0.7467\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 11/200\n59/59 [==============================] - 30s 506ms/step - loss: 0.3234 - accuracy: 0.8686 - val_loss: 0.5951 - val_accuracy: 0.7200\nEpoch 12/200\n59/59 [==============================] - 30s 503ms/step - loss: 0.3250 - accuracy: 0.8584 - val_loss: 0.6790 - val_accuracy: 0.6800\nEpoch 13/200\n59/59 [==============================] - 30s 505ms/step - loss: 0.3302 - accuracy: 0.8584 - val_loss: 0.5728 - val_accuracy: 0.7267\nEpoch 14/200\n59/59 [==============================] - 31s 519ms/step - loss: 0.2896 - accuracy: 0.8925 - val_loss: 0.5457 - val_accuracy: 0.7400\nEpoch 15/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.2958 - accuracy: 0.8737 - val_loss: 0.5360 - val_accuracy: 0.7200\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 16/200\n59/59 [==============================] - 30s 517ms/step - loss: 0.2799 - accuracy: 0.8959 - val_loss: 0.5455 - val_accuracy: 0.7467\nEpoch 17/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.2823 - accuracy: 0.8840 - val_loss: 0.5698 - val_accuracy: 0.7400\nEpoch 18/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.2522 - accuracy: 0.8823 - val_loss: 0.5913 - val_accuracy: 0.7267\nEpoch 19/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.2716 - accuracy: 0.8959 - val_loss: 0.5771 - val_accuracy: 0.7333\nEpoch 20/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.2781 - accuracy: 0.8686 - val_loss: 0.5929 - val_accuracy: 0.7400\nEpoch 21/200\n59/59 [==============================] - 30s 506ms/step - loss: 0.2495 - accuracy: 0.8959 - val_loss: 0.5784 - val_accuracy: 0.7533\nEpoch 22/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.2600 - accuracy: 0.8891 - val_loss: 0.5324 - val_accuracy: 0.7400\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 23/200\n59/59 [==============================] - 32s 538ms/step - loss: 0.2463 - accuracy: 0.8942 - val_loss: 0.5609 - val_accuracy: 0.7400\nEpoch 24/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.2507 - accuracy: 0.9096 - val_loss: 0.5568 - val_accuracy: 0.7333\nEpoch 25/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.2272 - accuracy: 0.9147 - val_loss: 0.5405 - val_accuracy: 0.7533\nEpoch 26/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.2449 - accuracy: 0.9078 - val_loss: 0.5493 - val_accuracy: 0.7533\nEpoch 27/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.2320 - accuracy: 0.9061 - val_loss: 0.5499 - val_accuracy: 0.7533\nEpoch 28/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.2108 - accuracy: 0.9096 - val_loss: 0.5551 - val_accuracy: 0.7467\nEpoch 29/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.2101 - accuracy: 0.9164 - val_loss: 0.5507 - val_accuracy: 0.7533\nEpoch 30/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.2082 - accuracy: 0.9266 - val_loss: 0.5262 - val_accuracy: 0.7467\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 31/200\n59/59 [==============================] - 31s 525ms/step - loss: 0.1945 - accuracy: 0.9249 - val_loss: 0.5505 - val_accuracy: 0.7400\nEpoch 32/200\n59/59 [==============================] - 30s 518ms/step - loss: 0.2098 - accuracy: 0.9198 - val_loss: 0.5339 - val_accuracy: 0.7667\nEpoch 33/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1914 - accuracy: 0.9334 - val_loss: 0.5413 - val_accuracy: 0.7600\nEpoch 34/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.2059 - accuracy: 0.9130 - val_loss: 0.5581 - val_accuracy: 0.7400\nEpoch 35/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.2289 - accuracy: 0.9010 - val_loss: 0.5335 - val_accuracy: 0.7400\nEpoch 36/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1934 - accuracy: 0.9215 - val_loss: 0.5611 - val_accuracy: 0.7400\nEpoch 37/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1826 - accuracy: 0.9369 - val_loss: 0.5726 - val_accuracy: 0.7467\nEpoch 38/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.1834 - accuracy: 0.9283 - val_loss: 0.5124 - val_accuracy: 0.7733\nINFO:tensorflow:Assets written to: ./VGG19ModelCheckPoints\\assets\nEpoch 39/200\n59/59 [==============================] - 31s 529ms/step - loss: 0.1960 - accuracy: 0.9198 - val_loss: 0.5270 - val_accuracy: 0.7600\nEpoch 40/200\n59/59 [==============================] - 30s 517ms/step - loss: 0.1888 - accuracy: 0.9300 - val_loss: 0.5634 - val_accuracy: 0.7667\nEpoch 41/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.2168 - accuracy: 0.8976 - val_loss: 0.6523 - val_accuracy: 0.7067\nEpoch 42/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.1833 - accuracy: 0.9283 - val_loss: 0.5589 - val_accuracy: 0.7467\nEpoch 43/200\n59/59 [==============================] - 30s 517ms/step - loss: 0.1777 - accuracy: 0.9386 - val_loss: 0.5604 - val_accuracy: 0.7600\nEpoch 44/200\n59/59 [==============================] - 30s 517ms/step - loss: 0.1679 - accuracy: 0.9420 - val_loss: 0.5571 - val_accuracy: 0.7333\nEpoch 45/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1957 - accuracy: 0.9215 - val_loss: 0.6092 - val_accuracy: 0.7267\nEpoch 46/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1662 - accuracy: 0.9317 - val_loss: 0.5415 - val_accuracy: 0.7600\nEpoch 47/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1767 - accuracy: 0.9300 - val_loss: 0.5495 - val_accuracy: 0.7467\nEpoch 48/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.1830 - accuracy: 0.9215 - val_loss: 0.5388 - val_accuracy: 0.7467\nEpoch 49/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1468 - accuracy: 0.9488 - val_loss: 0.5564 - val_accuracy: 0.7400\nEpoch 50/200\n59/59 [==============================] - 30s 517ms/step - loss: 0.1917 - accuracy: 0.9254 - val_loss: 0.5634 - val_accuracy: 0.7667\nEpoch 51/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1562 - accuracy: 0.9420 - val_loss: 0.5513 - val_accuracy: 0.7533\nEpoch 52/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1650 - accuracy: 0.9437 - val_loss: 0.5525 - val_accuracy: 0.7467\nEpoch 53/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1549 - accuracy: 0.9437 - val_loss: 0.5942 - val_accuracy: 0.7400\nEpoch 54/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1562 - accuracy: 0.9403 - val_loss: 0.5583 - val_accuracy: 0.7467\nEpoch 55/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.1512 - accuracy: 0.9471 - val_loss: 0.5428 - val_accuracy: 0.7533\nEpoch 56/200\n59/59 [==============================] - 30s 514ms/step - loss: 0.1532 - accuracy: 0.9522 - val_loss: 0.6024 - val_accuracy: 0.7533\nEpoch 57/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.2005 - accuracy: 0.9130 - val_loss: 0.5570 - val_accuracy: 0.7467\nEpoch 58/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1510 - accuracy: 0.9334 - val_loss: 0.5776 - val_accuracy: 0.7333\nEpoch 59/200\n59/59 [==============================] - 31s 529ms/step - loss: 0.1600 - accuracy: 0.9437 - val_loss: 0.5375 - val_accuracy: 0.7800\nEpoch 60/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1516 - accuracy: 0.9471 - val_loss: 0.5461 - val_accuracy: 0.7600\nEpoch 61/200\n59/59 [==============================] - 30s 514ms/step - loss: 0.1431 - accuracy: 0.9317 - val_loss: 0.5411 - val_accuracy: 0.7667\nEpoch 62/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1445 - accuracy: 0.9471 - val_loss: 0.6080 - val_accuracy: 0.7600\nEpoch 63/200\n59/59 [==============================] - 30s 517ms/step - loss: 0.1505 - accuracy: 0.9525 - val_loss: 0.5874 - val_accuracy: 0.7667\nEpoch 64/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1402 - accuracy: 0.9471 - val_loss: 0.5790 - val_accuracy: 0.7400\nEpoch 65/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.1203 - accuracy: 0.9693 - val_loss: 0.6068 - val_accuracy: 0.7400\nEpoch 66/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.1367 - accuracy: 0.9471 - val_loss: 0.5745 - val_accuracy: 0.7733\nEpoch 67/200\n59/59 [==============================] - 30s 516ms/step - loss: 0.1169 - accuracy: 0.9573 - val_loss: 0.5450 - val_accuracy: 0.7667\nEpoch 68/200\n59/59 [==============================] - 30s 518ms/step - loss: 0.1524 - accuracy: 0.9437 - val_loss: 0.5707 - val_accuracy: 0.7467\nEpoch 69/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.1298 - accuracy: 0.9539 - val_loss: 0.5813 - val_accuracy: 0.7467\nEpoch 70/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1382 - accuracy: 0.9454 - val_loss: 0.5783 - val_accuracy: 0.7533\nEpoch 71/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1401 - accuracy: 0.9471 - val_loss: 0.5483 - val_accuracy: 0.7667\nEpoch 72/200\n59/59 [==============================] - 31s 521ms/step - loss: 0.1624 - accuracy: 0.9403 - val_loss: 0.6734 - val_accuracy: 0.7533\nEpoch 73/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.1680 - accuracy: 0.9386 - val_loss: 0.6435 - val_accuracy: 0.7400\nEpoch 74/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1318 - accuracy: 0.9505 - val_loss: 0.5770 - val_accuracy: 0.7533\nEpoch 75/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.1070 - accuracy: 0.9642 - val_loss: 0.6367 - val_accuracy: 0.7467\nEpoch 76/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1483 - accuracy: 0.9420 - val_loss: 0.5678 - val_accuracy: 0.7533\nEpoch 77/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.1327 - accuracy: 0.9454 - val_loss: 0.6050 - val_accuracy: 0.7533\nEpoch 78/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1313 - accuracy: 0.9573 - val_loss: 0.5932 - val_accuracy: 0.7800\nEpoch 79/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1256 - accuracy: 0.9539 - val_loss: 0.6388 - val_accuracy: 0.7400\nEpoch 80/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1481 - accuracy: 0.9454 - val_loss: 0.6496 - val_accuracy: 0.7533\nEpoch 81/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1516 - accuracy: 0.9420 - val_loss: 0.5789 - val_accuracy: 0.7533\nEpoch 82/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1176 - accuracy: 0.9590 - val_loss: 0.6084 - val_accuracy: 0.7600\nEpoch 83/200\n59/59 [==============================] - 31s 521ms/step - loss: 0.1266 - accuracy: 0.9556 - val_loss: 0.5818 - val_accuracy: 0.7667\nEpoch 84/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.1469 - accuracy: 0.9471 - val_loss: 0.5676 - val_accuracy: 0.7667\nEpoch 85/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1161 - accuracy: 0.9642 - val_loss: 0.6273 - val_accuracy: 0.7400\nEpoch 86/200\n59/59 [==============================] - 31s 518ms/step - loss: 0.1286 - accuracy: 0.9539 - val_loss: 0.6441 - val_accuracy: 0.7267\nEpoch 87/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1237 - accuracy: 0.9573 - val_loss: 0.6015 - val_accuracy: 0.7267\nEpoch 88/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.1414 - accuracy: 0.9505 - val_loss: 0.5982 - val_accuracy: 0.7600\nEpoch 89/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1201 - accuracy: 0.9556 - val_loss: 0.6144 - val_accuracy: 0.7733\nEpoch 90/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1031 - accuracy: 0.9693 - val_loss: 0.5663 - val_accuracy: 0.7667\nEpoch 91/200\n59/59 [==============================] - 31s 524ms/step - loss: 0.1056 - accuracy: 0.9659 - val_loss: 0.6171 - val_accuracy: 0.7533\nEpoch 92/200\n59/59 [==============================] - 30s 506ms/step - loss: 0.1412 - accuracy: 0.9403 - val_loss: 0.6565 - val_accuracy: 0.7333\nEpoch 93/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1265 - accuracy: 0.9488 - val_loss: 0.6029 - val_accuracy: 0.7667\nEpoch 94/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.1202 - accuracy: 0.9573 - val_loss: 0.6041 - val_accuracy: 0.7600\nEpoch 95/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.1243 - accuracy: 0.9556 - val_loss: 0.6105 - val_accuracy: 0.7533\nEpoch 96/200\n59/59 [==============================] - 30s 514ms/step - loss: 0.1275 - accuracy: 0.9488 - val_loss: 0.6312 - val_accuracy: 0.7600\nEpoch 97/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1214 - accuracy: 0.9642 - val_loss: 0.6018 - val_accuracy: 0.7600\nEpoch 98/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.1196 - accuracy: 0.9539 - val_loss: 0.6083 - val_accuracy: 0.7733\nEpoch 99/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.1306 - accuracy: 0.9556 - val_loss: 0.6750 - val_accuracy: 0.7267\nEpoch 100/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1324 - accuracy: 0.9437 - val_loss: 0.5848 - val_accuracy: 0.7667\nEpoch 101/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.1096 - accuracy: 0.9608 - val_loss: 0.6260 - val_accuracy: 0.7733\nEpoch 102/200\n59/59 [==============================] - 30s 516ms/step - loss: 0.1111 - accuracy: 0.9542 - val_loss: 0.6243 - val_accuracy: 0.7800\nEpoch 103/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0920 - accuracy: 0.9727 - val_loss: 0.6246 - val_accuracy: 0.7667\nEpoch 104/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.1305 - accuracy: 0.9488 - val_loss: 0.6384 - val_accuracy: 0.7600\nEpoch 105/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.0968 - accuracy: 0.9676 - val_loss: 0.6286 - val_accuracy: 0.7533\nEpoch 106/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1123 - accuracy: 0.9676 - val_loss: 0.6733 - val_accuracy: 0.7467\nEpoch 107/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1492 - accuracy: 0.9437 - val_loss: 0.8519 - val_accuracy: 0.7333\nEpoch 108/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.1302 - accuracy: 0.9539 - val_loss: 0.8686 - val_accuracy: 0.6867\nEpoch 109/200\n59/59 [==============================] - 30s 514ms/step - loss: 0.1018 - accuracy: 0.9625 - val_loss: 0.6249 - val_accuracy: 0.7533\nEpoch 110/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1325 - accuracy: 0.9437 - val_loss: 0.6625 - val_accuracy: 0.7600\nEpoch 111/200\n59/59 [==============================] - 30s 516ms/step - loss: 0.1148 - accuracy: 0.9471 - val_loss: 0.6525 - val_accuracy: 0.7600\nEpoch 112/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1042 - accuracy: 0.9659 - val_loss: 0.6375 - val_accuracy: 0.7667\nEpoch 113/200\n59/59 [==============================] - 30s 516ms/step - loss: 0.1298 - accuracy: 0.9454 - val_loss: 0.6333 - val_accuracy: 0.7667\nEpoch 114/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1123 - accuracy: 0.9556 - val_loss: 0.6529 - val_accuracy: 0.7600\nEpoch 115/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.1151 - accuracy: 0.9556 - val_loss: 0.6317 - val_accuracy: 0.7600\nEpoch 116/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1214 - accuracy: 0.9386 - val_loss: 0.6607 - val_accuracy: 0.7867\nEpoch 117/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.0986 - accuracy: 0.9676 - val_loss: 0.6656 - val_accuracy: 0.7533\nEpoch 118/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.0929 - accuracy: 0.9710 - val_loss: 0.6593 - val_accuracy: 0.7600\nEpoch 119/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0927 - accuracy: 0.9676 - val_loss: 0.6813 - val_accuracy: 0.7600\nEpoch 120/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.1196 - accuracy: 0.9539 - val_loss: 0.6664 - val_accuracy: 0.7533\nEpoch 121/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0951 - accuracy: 0.9693 - val_loss: 0.6799 - val_accuracy: 0.7400\nEpoch 122/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.0790 - accuracy: 0.9761 - val_loss: 0.6519 - val_accuracy: 0.7467\nEpoch 123/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1044 - accuracy: 0.9590 - val_loss: 0.6180 - val_accuracy: 0.7533\nEpoch 124/200\n59/59 [==============================] - 31s 518ms/step - loss: 0.1266 - accuracy: 0.9608 - val_loss: 0.6033 - val_accuracy: 0.7400\nEpoch 125/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.0875 - accuracy: 0.9676 - val_loss: 0.7168 - val_accuracy: 0.7533\nEpoch 126/200\n59/59 [==============================] - 30s 517ms/step - loss: 0.1218 - accuracy: 0.9505 - val_loss: 0.6495 - val_accuracy: 0.7533\nEpoch 127/200\n59/59 [==============================] - 31s 527ms/step - loss: 0.1388 - accuracy: 0.9471 - val_loss: 0.6588 - val_accuracy: 0.7533\nEpoch 128/200\n59/59 [==============================] - 31s 530ms/step - loss: 0.0844 - accuracy: 0.9676 - val_loss: 0.6912 - val_accuracy: 0.7600\nEpoch 129/200\n59/59 [==============================] - 30s 514ms/step - loss: 0.1198 - accuracy: 0.9542 - val_loss: 0.7112 - val_accuracy: 0.7733\nEpoch 130/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.0922 - accuracy: 0.9642 - val_loss: 0.6491 - val_accuracy: 0.7600\nEpoch 131/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1054 - accuracy: 0.9642 - val_loss: 0.7015 - val_accuracy: 0.7533\nEpoch 132/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0944 - accuracy: 0.9625 - val_loss: 0.6511 - val_accuracy: 0.7533\nEpoch 133/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1121 - accuracy: 0.9539 - val_loss: 0.6378 - val_accuracy: 0.7467\nEpoch 134/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.1203 - accuracy: 0.9471 - val_loss: 0.6253 - val_accuracy: 0.7600\nEpoch 135/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.0929 - accuracy: 0.9659 - val_loss: 0.6282 - val_accuracy: 0.7667\nEpoch 136/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0783 - accuracy: 0.9761 - val_loss: 0.6516 - val_accuracy: 0.7733\nEpoch 137/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1032 - accuracy: 0.9505 - val_loss: 0.6392 - val_accuracy: 0.7800\nEpoch 138/200\n59/59 [==============================] - 31s 534ms/step - loss: 0.0947 - accuracy: 0.9659 - val_loss: 0.6542 - val_accuracy: 0.7667\nEpoch 139/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.0871 - accuracy: 0.9676 - val_loss: 0.6845 - val_accuracy: 0.7667\nEpoch 140/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0922 - accuracy: 0.9676 - val_loss: 0.6595 - val_accuracy: 0.7733\nEpoch 141/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.1060 - accuracy: 0.9590 - val_loss: 0.7698 - val_accuracy: 0.7400\nEpoch 142/200\n59/59 [==============================] - 30s 510ms/step - loss: 0.0981 - accuracy: 0.9659 - val_loss: 0.6829 - val_accuracy: 0.7600\nEpoch 143/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0925 - accuracy: 0.9625 - val_loss: 0.6855 - val_accuracy: 0.7333\nEpoch 144/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.0910 - accuracy: 0.9695 - val_loss: 0.7015 - val_accuracy: 0.7400\nEpoch 145/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.0906 - accuracy: 0.9727 - val_loss: 0.6716 - val_accuracy: 0.7600\nEpoch 146/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.0856 - accuracy: 0.9744 - val_loss: 0.7209 - val_accuracy: 0.7600\nEpoch 147/200\n59/59 [==============================] - 31s 519ms/step - loss: 0.0819 - accuracy: 0.9693 - val_loss: 0.6850 - val_accuracy: 0.7533\nEpoch 148/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.0950 - accuracy: 0.9659 - val_loss: 0.6659 - val_accuracy: 0.7533\nEpoch 149/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.0951 - accuracy: 0.9676 - val_loss: 0.7353 - val_accuracy: 0.7333\nEpoch 150/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.1135 - accuracy: 0.9625 - val_loss: 0.6912 - val_accuracy: 0.7600\nEpoch 151/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.0971 - accuracy: 0.9642 - val_loss: 0.8442 - val_accuracy: 0.7133\nEpoch 152/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1054 - accuracy: 0.9505 - val_loss: 0.7071 - val_accuracy: 0.7667\nEpoch 153/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.0829 - accuracy: 0.9744 - val_loss: 0.7420 - val_accuracy: 0.7667\nEpoch 154/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.0777 - accuracy: 0.9761 - val_loss: 0.6793 - val_accuracy: 0.7667\nEpoch 155/200\n59/59 [==============================] - 30s 516ms/step - loss: 0.1011 - accuracy: 0.9573 - val_loss: 0.6634 - val_accuracy: 0.7733\nEpoch 156/200\n59/59 [==============================] - 30s 506ms/step - loss: 0.0777 - accuracy: 0.9778 - val_loss: 0.6811 - val_accuracy: 0.7600\nEpoch 157/200\n59/59 [==============================] - 30s 518ms/step - loss: 0.0748 - accuracy: 0.9795 - val_loss: 0.7211 - val_accuracy: 0.7533\nEpoch 158/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.1062 - accuracy: 0.9608 - val_loss: 0.6910 - val_accuracy: 0.7733\nEpoch 159/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.0956 - accuracy: 0.9625 - val_loss: 0.6631 - val_accuracy: 0.7800\nEpoch 160/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.0934 - accuracy: 0.9676 - val_loss: 0.6876 - val_accuracy: 0.7533\nEpoch 161/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.0910 - accuracy: 0.9590 - val_loss: 0.7133 - val_accuracy: 0.7400\nEpoch 162/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.0960 - accuracy: 0.9642 - val_loss: 0.6864 - val_accuracy: 0.7600\nEpoch 163/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.0895 - accuracy: 0.9625 - val_loss: 0.7050 - val_accuracy: 0.7600\nEpoch 164/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.0917 - accuracy: 0.9695 - val_loss: 0.7582 - val_accuracy: 0.7333\nEpoch 165/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.0847 - accuracy: 0.9676 - val_loss: 0.6935 - val_accuracy: 0.7533\nEpoch 166/200\n59/59 [==============================] - 30s 508ms/step - loss: 0.0879 - accuracy: 0.9744 - val_loss: 0.7020 - val_accuracy: 0.7733\nEpoch 167/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0912 - accuracy: 0.9676 - val_loss: 0.6711 - val_accuracy: 0.7733\nEpoch 168/200\n59/59 [==============================] - 30s 514ms/step - loss: 0.0783 - accuracy: 0.9761 - val_loss: 0.6794 - val_accuracy: 0.7600\nEpoch 169/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.0804 - accuracy: 0.9710 - val_loss: 0.7083 - val_accuracy: 0.7533\nEpoch 170/200\n59/59 [==============================] - 30s 516ms/step - loss: 0.1098 - accuracy: 0.9539 - val_loss: 0.6777 - val_accuracy: 0.7600\nEpoch 171/200\n59/59 [==============================] - 30s 512ms/step - loss: 0.0780 - accuracy: 0.9710 - val_loss: 0.7113 - val_accuracy: 0.7333\nEpoch 172/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.0993 - accuracy: 0.9573 - val_loss: 0.7065 - val_accuracy: 0.7667\nEpoch 173/200\n59/59 [==============================] - 32s 538ms/step - loss: 0.1069 - accuracy: 0.9608 - val_loss: 0.7297 - val_accuracy: 0.7600\nEpoch 174/200\n59/59 [==============================] - 30s 516ms/step - loss: 0.0803 - accuracy: 0.9761 - val_loss: 0.6863 - val_accuracy: 0.7600\nEpoch 175/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.0874 - accuracy: 0.9778 - val_loss: 0.7687 - val_accuracy: 0.7467\nEpoch 176/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.1427 - accuracy: 0.9352 - val_loss: 0.6896 - val_accuracy: 0.7533\nEpoch 177/200\n59/59 [==============================] - 30s 509ms/step - loss: 0.0872 - accuracy: 0.9710 - val_loss: 0.7697 - val_accuracy: 0.7600\nEpoch 178/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.0882 - accuracy: 0.9710 - val_loss: 0.7484 - val_accuracy: 0.7600\nEpoch 179/200\n59/59 [==============================] - 31s 520ms/step - loss: 0.0806 - accuracy: 0.9727 - val_loss: 0.8300 - val_accuracy: 0.7533\nEpoch 180/200\n59/59 [==============================] - 32s 536ms/step - loss: 0.1037 - accuracy: 0.9573 - val_loss: 0.7455 - val_accuracy: 0.7467\nEpoch 181/200\n59/59 [==============================] - 31s 530ms/step - loss: 0.0777 - accuracy: 0.9778 - val_loss: 0.7112 - val_accuracy: 0.7533\nEpoch 182/200\n59/59 [==============================] - 32s 543ms/step - loss: 0.0757 - accuracy: 0.9761 - val_loss: 0.7899 - val_accuracy: 0.7667\nEpoch 183/200\n59/59 [==============================] - 31s 531ms/step - loss: 0.0800 - accuracy: 0.9744 - val_loss: 0.7657 - val_accuracy: 0.7667\nEpoch 184/200\n59/59 [==============================] - 31s 524ms/step - loss: 0.0978 - accuracy: 0.9590 - val_loss: 0.7756 - val_accuracy: 0.7533\nEpoch 185/200\n59/59 [==============================] - 31s 523ms/step - loss: 0.0869 - accuracy: 0.9727 - val_loss: 0.7607 - val_accuracy: 0.7533\nEpoch 186/200\n59/59 [==============================] - 30s 511ms/step - loss: 0.0792 - accuracy: 0.9693 - val_loss: 0.7320 - val_accuracy: 0.7533\nEpoch 187/200\n59/59 [==============================] - 31s 520ms/step - loss: 0.0883 - accuracy: 0.9659 - val_loss: 0.8564 - val_accuracy: 0.7533\nEpoch 188/200\n59/59 [==============================] - 30s 513ms/step - loss: 0.0987 - accuracy: 0.9573 - val_loss: 0.7657 - val_accuracy: 0.7667\nEpoch 189/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0967 - accuracy: 0.9676 - val_loss: 0.7329 - val_accuracy: 0.7600\nEpoch 190/200\n59/59 [==============================] - 30s 505ms/step - loss: 0.1030 - accuracy: 0.9642 - val_loss: 0.7409 - val_accuracy: 0.7667\nEpoch 191/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.1182 - accuracy: 0.9505 - val_loss: 0.8309 - val_accuracy: 0.7200\nEpoch 192/200\n59/59 [==============================] - 30s 503ms/step - loss: 0.0942 - accuracy: 0.9676 - val_loss: 0.7150 - val_accuracy: 0.7600\nEpoch 193/200\n59/59 [==============================] - 30s 504ms/step - loss: 0.0944 - accuracy: 0.9676 - val_loss: 0.6977 - val_accuracy: 0.7600\nEpoch 194/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.0669 - accuracy: 0.9778 - val_loss: 0.7505 - val_accuracy: 0.7667\nEpoch 195/200\n59/59 [==============================] - 30s 507ms/step - loss: 0.0986 - accuracy: 0.9659 - val_loss: 0.8469 - val_accuracy: 0.7333\nEpoch 196/200\n59/59 [==============================] - 30s 515ms/step - loss: 0.0795 - accuracy: 0.9744 - val_loss: 0.7306 - val_accuracy: 0.7400\nEpoch 197/200\n59/59 [==============================] - 29s 499ms/step - loss: 0.0652 - accuracy: 0.9761 - val_loss: 0.7452 - val_accuracy: 0.7533\nEpoch 198/200\n59/59 [==============================] - 30s 504ms/step - loss: 0.1092 - accuracy: 0.9590 - val_loss: 0.8018 - val_accuracy: 0.7333\nEpoch 199/200\n59/59 [==============================] - 29s 496ms/step - loss: 0.0849 - accuracy: 0.9659 - val_loss: 0.7517 - val_accuracy: 0.7533\nEpoch 200/200\n59/59 [==============================] - 29s 499ms/step - loss: 0.0807 - accuracy: 0.9710 - val_loss: 0.7512 - val_accuracy: 0.7533\n" ], [ "model_final.save('myvgg19.h5')", "_____no_output_____" ], [ "model_final.save('vgg19Model')", "INFO:tensorflow:Assets written to: vgg19Model\\assets\n" ], [ "# evaluating validation data on the model\nmodel_final.evaluate_generator(\n generator=validation_iterator,\n steps=validation_iterator.samples//validation_iterator.batch_size,\n verbose=1\n)", "C:\\Users\\ankit.dubey\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\keras\\engine\\training.py:1973: UserWarning: `Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators.\n warnings.warn('`Model.evaluate_generator` is deprecated and '\n" ] ], [ [ "# Plotting Model Loss & Accuracy ", "_____no_output_____" ] ], [ [ "plt.subplot(211)\nplt.title('Loss')\nplt.plot(hist.history['loss'],label='train')\nplt.plot(hist.history['val_loss'], label='test')\nplt.legend()\n# plot accuracy during training\nplt.subplot(212)\nplt.title('Accuracy')\nplt.plot(hist.history['accuracy'], label='train')\nplt.plot(hist.history['val_accuracy'], label='test')\nplt.legend()\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "# Model Performance Analysis", "_____no_output_____" ] ], [ [ "# predicting on the validation images\npreds_on_validation_data = model_final.predict(validation_iterator)\nlen(preds_on_validation_data)\n# getting the maximum probabilites among the predicted one\nmax_pred_on_validation_data = np.argmax(preds_on_validation_data,axis=1)\nmax_pred_on_validation_data[:10]", "_____no_output_____" ], [ "from sklearn.metrics import classification_report, confusion_matrix\nprint('Confusion Matrix')\nprint(confusion_matrix(validation_iterator.classes, max_pred_on_validation_data))\nmat = confusion_matrix(validation_iterator.classes, max_pred_on_validation_data)\nprint('Classification Report')\ntarget_names = ['Negative', 'Positive']\nprint(classification_report(validation_iterator.classes, max_pred_on_validation_data, target_names=target_names))", "Confusion Matrix\n[[28 42]\n [35 45]]\nClassification Report\n precision recall f1-score support\n\n Negative 0.44 0.40 0.42 70\n Positive 0.52 0.56 0.54 80\n\n accuracy 0.49 150\n macro avg 0.48 0.48 0.48 150\nweighted avg 0.48 0.49 0.48 150\n\n" ], [ "ax= plt.subplot()\nsns.heatmap(mat, annot=True, fmt='g', ax=ax); \n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Negative', 'Positive']); ax.yaxis.set_ticklabels(['Negative', 'Positive']);", "_____no_output_____" ] ], [ [ "# Testing on whole dataset", "_____no_output_____" ] ], [ [ "test_datagen = ImageDataGenerator(rescale=1./255.)\ntest_generator = test_datagen.flow_from_dataframe(\n dataframe=df,\n x_col='path',\n y_col='target',\n batch_size=10,\n seed=42,\n shuffle=False,\n class_mode='categorical',\n target_size=(124,124)\n)", "Found 746 validated image filenames belonging to 2 classes.\n" ], [ "model_final.evaluate_generator(\n generator=test_generator,\n steps=test_generator.samples//test_generator.batch_size\n)", "C:\\Users\\ankit.dubey\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\keras\\engine\\training.py:1973: UserWarning: `Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators.\n warnings.warn('`Model.evaluate_generator` is deprecated and '\n" ], [ "preds = model_final.predict(test_generator)\nlen(preds)\n# predictions for test data\npred = np.argmax(preds,axis=1)\npred[:10]", "_____no_output_____" ], [ "print('Confusion Matrix')\nprint(confusion_matrix(test_generator.classes, pred))\nmat = confusion_matrix(test_generator.classes, pred)\nprint('Classification Report')\ntarget_names = ['Negative', 'Positive']\nprint(classification_report(test_generator.classes, pred, target_names=target_names))", "Confusion Matrix\n[[326 23]\n [ 15 382]]\nClassification Report\n precision recall f1-score support\n\n Negative 0.96 0.93 0.94 349\n Positive 0.94 0.96 0.95 397\n\n accuracy 0.95 746\n macro avg 0.95 0.95 0.95 746\nweighted avg 0.95 0.95 0.95 746\n\n" ], [ "ax= plt.subplot()\nsns.heatmap(mat, annot=True, fmt='g', ax=ax); \n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Negative', 'Positive']); ax.yaxis.set_ticklabels(['Negative', 'Positive']);", "_____no_output_____" ], [ "for i in range(10):\n img,label = test_generator.next()\n plt.imshow(img[0])\n plt.show()", "_____no_output_____" ], [ "final_outcomes = zip(df['target'],pred,test_generator.classes)", "_____no_output_____" ], [ "final_df = pd.DataFrame(final_outcomes,columns=['actual target','Predicted target','classes'])\nfinal_df.head(10)", "_____no_output_____" ], [ "final_df.tail(10)", "_____no_output_____" ], [ "test_generator.class_indices", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4e9e9c744e6501fc2578ef54b547f7b0c64f09
651,666
ipynb
Jupyter Notebook
experiments/misclassifications.ipynb
oscarpimentel/astro-lightcurves-classifier
f697b43e22bd8c92c1b9df514be8565c736dd7cc
[ "MIT" ]
1
2021-12-31T18:00:08.000Z
2021-12-31T18:00:08.000Z
experiments/misclassifications.ipynb
oscarpimentel/astro-lightcurves-classifier
f697b43e22bd8c92c1b9df514be8565c736dd7cc
[ "MIT" ]
null
null
null
experiments/misclassifications.ipynb
oscarpimentel/astro-lightcurves-classifier
f697b43e22bd8c92c1b9df514be8565c736dd7cc
[ "MIT" ]
null
null
null
2,036.45625
635,588
0.958353
[ [ [ "import sys\nsys.path.append('../') # or just install the module\nsys.path.append('../../fuzzy-tools') # or just install the module\nsys.path.append('../../astro-lightcurves-handler') # or just install the module", "_____no_output_____" ], [ "%load_ext autoreload\n%autoreload 2\nfrom lcclassifier.results.utils import get_model_names\n\nlcset_name = 'test'\nrootdir = '../save'\nmethod = 'spm-mcmc-estw'\ncfilename = f'survey=alerceZTFv7.1~bands=gr~mode=onlySNe~method={method}'\nkf = '2'\n\nmodel_names = get_model_names(rootdir, cfilename, kf, lcset_name)\nmodel_names", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ], [ "%load_ext autoreload\n%autoreload 2\nimport numpy as np\nimport fuzzytools.files as ftfiles\nfrom fuzzytools.datascience import misclassifications\nimport matplotlib.pyplot as plt\n\nmodel_name = 'mdl=ParallelTimeModAttn~input_dims=1~dummy_seft=1~m=24~kernel_size=1~heads=4~time_noise_window=6*24**-1~enc_emb=g64-g64.r64-r64~dec_emb=g1-g128.r1-r128~b=200~pb=.~hr=0~bypass_synth=0~bypass_prob=0.0~ds_prob=0.1'\nrootdir = '../save'\ntrain_mode = 'fine-tuning'\nload_roodir = f'{rootdir}/{model_name}/{train_mode}/performance/{cfilename}'\nfiles, files_ids, kfs = ftfiles.gather_files_by_kfold(load_roodir, kf, lcset_name,\n fext='d',\n imbalanced_kf_mode='ignore', # error oversampling\n )\nprint(f'{files_ids}({len(files_ids)}#); {model_name}')\n\nfile_idx = 0\nfile = files[file_idx]\nthdays = file()['thdays']\nthday = thdays[-1]\nthdays_predictions = file()['thdays_predictions'][thday]\ny_pred_p = thdays_predictions['y_pred_p']\ny_true = thdays_predictions['y_true']\nclass_names = file()['class_names']\nobj_ids = file()['lcobj_names']\n\nfig, axs, miss_objs_df = misclassifications.plot_misclassification_map(y_pred_p, y_true, class_names,\n obj_ids=obj_ids,\n #pred_prob_th=.8, # None .5\n fontsize=12,\n figsize=(20,18),\n legend_loc='upper right',\n #verbose=1,\n also_show_correct_objs_txt=True,\n )\ndisplay(miss_objs_df)\nplt.show()", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n['id=1000c0', 'id=1000c1', 'id=1001c0', 'id=1001c1', 'id=1002c0', 'id=1002c1', 'id=1003c0', 'id=1003c1', 'id=1004c0', 'id=1004c1', 'id=1005c0', 'id=1005c1'](12#); mdl=ParallelTimeModAttn~input_dims=1~dummy_seft=1~m=24~kernel_size=1~heads=4~time_noise_window=6*24**-1~enc_emb=g64-g64.r64-r64~dec_emb=g1-g128.r1-r128~b=200~pb=.~hr=0~bypass_synth=0~bypass_prob=0.0~ds_prob=0.1\n" ], [ "txt = ''\nfor miss_obj_id in miss_objs_df.index:\n txt += f\"'{miss_obj_id}', \"\nprint(f'deep_miss_obj_ids = [{txt}]')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
ec4eaf77f4b0e73b84dee0dd98766342ec348468
14,443
ipynb
Jupyter Notebook
notebooks/01.b_Recaps.ipynb
zyzllik/advanced_python_2021-22_HD
8562fc2a3fe11ef40829072a493bc090606c2a8f
[ "CC0-1.0" ]
null
null
null
notebooks/01.b_Recaps.ipynb
zyzllik/advanced_python_2021-22_HD
8562fc2a3fe11ef40829072a493bc090606c2a8f
[ "CC0-1.0" ]
1
2021-11-15T13:55:23.000Z
2021-11-15T13:55:23.000Z
notebooks/01.b_Recaps.ipynb
zyzllik/advanced_python_2021-22_HD
8562fc2a3fe11ef40829072a493bc090606c2a8f
[ "CC0-1.0" ]
9
2021-11-08T12:53:30.000Z
2021-11-10T13:08:45.000Z
24.562925
428
0.530568
[ [ [ "import course;course.header()", "_____no_output_____" ] ], [ [ "# Mission statement\n\nI'd like to teach you \n* What I think is advanced Python\n* Give you my view on how to code (and how not to code)\n* Introduce you to \n * code structure\n * code testing\n * code documentation\n* Show case some useful python modules (that you might know of or not)\n* \\[ What you want to learn \\]\n", "_____no_output_____" ], [ "# Project show cases", "_____no_output_____" ], [ "\n### pymzML\n\npymzML is an extension to Python that offers\n* easy access to mass spectrometry (MS) data that allows the rapid development of tools\n* a very fast parser for mzML data, the standard mass spectrometry data format\n* a set of functions to compare and/or handle spectra\n* random access in compressed files\n* interactive data visualization\n\nM Kösters, J Leufken, S Schulze, K Sugimoto, J Klein, R P Zahedi, M Hippler, S A Leidel, C Fufezan; pymzML v2.0: introducing a highly compressed and seekable gzip format, Bioinformatics, doi: https://doi.org/10.1093/bioinformatics/bty046\n\nT Bald, J Barth, A Niehues, M Specht, M Hippler, C Fufezan; pymzML - Python module for high-throughput bioinformatics on mass spectrometry data, Bioinformatics, doi: https://doi.org/10.1093/bioinformatics/bts066 \n\n|![](https://travis-ci.org/pymzml/pymzML.svg?branch=master)|![](https://ci.appveyor.com/api/projects/status/4nlw52a9qn22921d?svg=true)|![](https://readthedocs.org/projects/pymzml/badge/?version=latest)|![](https://codecov.io/gh/pymzml/pymzml/branch/master/graph/badge.svg)|![](https://img.shields.io/pypi/v/pymzML.svg)|![](https://pepy.tech/badge/pymzml)|![](https://img.shields.io/badge/code%20style-black-000000.svg)|\n|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n|[travis](https://travis-ci.org/pymzml/pymzML)|[appveyor](https://ci.appveyor.com/project/fufezan-lab/pymzml)|[rtd](http://pymzml.readthedocs.io/en/latest/?badge=latest)|[codecov](https://codecov.io/gh/pymzml/pymzml)|[pypi](https://pypi.org/project/pymzML/)|[pepy](https://pepy.tech/project/pymzml)|[black](https://github.com/psf/black)|\n", "_____no_output_____" ], [ "### pyQms\n\npyQms is an extension to Python that offers amongst other things\n* fast and accurate quantification of all high-res LC-MS data\n* full labeling and modification flexibility\n* full platform independence\n\n\nLeufken, J., Niehues, A., Hippler, M., Sarin, L. P., Hippler, M., Leidel, S. A., and Fufezan, C. (2017) pyQms enables universal and accurate quantification of mass spectrometry data. MCP, https://doi.org/10.1074/mcp.M117.068007\n\n|![](https://travis-ci.org/pyQms/pyqms.svg?branch=master)|![](https://ci.appveyor.com/api/projects/status/n4x2ug7h3ce4d49y?svg=true)|![](https://readthedocs.org/projects/pyqms/badge/?version=latest)|![](https://img.shields.io/pypi/v/pyqms.svg)|![](https://img.shields.io/badge/code%20style-black-000000.svg)|\n|:---:|:---:|:---:|:---:|:---:|\n|[travis](https://travis-ci.org/pyQms/pyqms)|[appveyor](https://ci.appveyor.com/project/fufezan-lab/pyqms)|[rtd](http://pyqms.readthedocs.io/en/latest/?badge=latest)|[pypi](https://pypi.org/project/pyqms/)|[black](https://github.com/psf/black)|\n", "_____no_output_____" ], [ "### ursgal\n\nursgal - Universal Python Module Combining Common Bottom-Up Proteomics Tools for Large-Scale Analysis\n* Peptide spectrum matching with up to eight different search engines (some available in multiple versions), including three open modification search engines\n* Evaluation and post processing of search results with up to two different engines\n* Integration of search results from different search engines\n* De novo sequencing with up to two different search engines\n* Miscellaneous tools including the creation of a target decoy database as well as filtering, sanitizing and visualizing of results\n\n\nKremer, L. P. M., Leufken, J., Oyunchimeg, P., Schulze, S. and Fufezan, C.\n(2015) Ursgal, Universal Python Module Combining Common Bottom-Up Proteomics Tools for Large-Scale Analysis, Journal of Proteome research, 15, 788-.\nDOI:10.1021/acs.jproteome.5b00860*\n\n|![](https://travis-ci.org/ursgal/ursgal.svg?branch=master)|![](https://ci.appveyor.com/api/projects/status/hel9rowah1u3rfe1?svg=true)|![](http://readthedocs.org/projects/ursgal/badge/?version=latest)|![](https://badge.fury.io/py/ursgal.svg)|\n|:---:|:---:|:---:|:---:|\n|[travis](https://travis-ci.org/ursgal/ursgal)|[appveyor](https://ci.appveyor.com/project/fufezan-lab/ursgal)|[rtd](http://ursgal.readthedocs.io/en/latest/?badge=latest)|[pypi](https://badge.fury.io/py/ursgal/)|\n", "_____no_output_____" ], [ "## a lasting name \nhttp://proteomicsnews.blogspot.com/2017/02/ursgal-combine-all-python-proteomics.html\n\n<img style=\"right\" src=\"./images/proteomics-blog.png\">", "_____no_output_____" ], [ "# Python beginner recap", "_____no_output_____" ], [ "## Python basic type", "_____no_output_____" ], [ "* int\n* float\n* str\n* list\n* tuple\n* set\n* dict\n\nHave been covered else where. Quick recap, what's the outcome of these lines ...", "_____no_output_____" ] ], [ [ "a = 34 + 3.2\ntype(a)", "_____no_output_____" ], [ "a = \"Never odd\" + \" or even\"\na[::-1]", "_____no_output_____" ], [ "a[:-4]", "_____no_output_____" ], [ "a[0] = 'n'", "_____no_output_____" ], [ "a.split()", "_____no_output_____" ], [ "b = { (12,32): \"Well done ... \"}", "_____no_output_____" ], [ "b", "_____no_output_____" ], [ "set([12, 13, 14]) - set([13, 14, 15])", "_____no_output_____" ] ], [ [ "## Python comparisons", "_____no_output_____" ], [ "* \\>\n* \\>=\n* ==\n* <=\n* <\n* is\n\nHave been covered elsewhere. Quick recap, what's the outpcome of these lines ...", "_____no_output_____" ] ], [ [ "a = 42\n39.9 < a <= 42", "_____no_output_____" ], [ "a = \"Nature is lethal but it doesn't hold a candle to man.\"\nb = \"Nature is lethal but it doesn't hold a candle to man.\"\nprint(\"a is b?\", a is b)\nprint(\"a == b\", a == b)", "_____no_output_____" ], [ "\ndef release_password(authentication=False):\n answer = \"Not authenticated\"\n if authentication:\n answer = \"Here is your password\"\n return answer", "_____no_output_____" ], [ "release_password(authentication=True)", "_____no_output_____" ], [ "release_password(authentication=[1])", "_____no_output_____" ], [ "release_password(authentication=[])", "_____no_output_____" ] ], [ [ "## Fix it", "_____no_output_____" ] ], [ [ "# thinking that objectes eval to the same ensures equality is one major source of errors\ndef release_password(authentication=False):\n answer = \"Not authenticated\"\n if authentication == True:\n answer = \"Here is your pasword\"\n return answer", "_____no_output_____" ] ], [ [ "## Evaluating objects", "_____no_output_____" ] ], [ [ "print(\"[] is True?\", [] is True)\nprint(\"[1] is True?\", [1] is True) ", "_____no_output_____" ], [ "print(\"[] == True?\", [] == True)\nprint(\"[1] == True?\", [1] == True) ", "_____no_output_____" ], [ "print(\"bool([]) == True?\", bool([]) == True)\nprint(\"bool([1]) == True?\", bool([1]) == True) ", "_____no_output_____" ] ], [ [ "Fix the code!", "_____no_output_____" ], [ "## Other operators", "_____no_output_____" ], [ "### membership operators", "_____no_output_____" ] ], [ [ "'dog' in 'Not sure I went out with the dOg'", "_____no_output_____" ], [ "'dog' in ('d0g', 'dOg', 'dog', 'dot')", "_____no_output_____" ] ], [ [ "### logical operators", "_____no_output_____" ] ], [ [ "(1 is True)", "_____no_output_____" ], [ "(1 is True) or (1 == True) ", "_____no_output_____" ], [ "# Does not have to be boolean operations ... though imho less readable\n4 or 3", "_____no_output_____" ] ], [ [ "## Object references", "_____no_output_____" ] ], [ [ "a = \"Test!\"\nid(a)", "_____no_output_____" ], [ "a = 0\nb = a\nprint(\"a = {0} id:{1}\".format(a, id(a)))\nprint(\"b = {0} id:{1}\".format(b, id(b)))\nprint(\"a is b?\", a is b) # True\nprint(\"Adding 1 to a..\")\na += 1\nprint(\"a = {0} id:{1}\".format(a, id(a)))\nprint(\"b = {0} id:{1}\".format(b, id(b)))\nprint(\"a is b?\", a is b)", "_____no_output_____" ], [ "a = {}\nb = a\nprint(\"a = {0} id:{1}\".format(a, id(a)))\nprint(\"b = {0} id:{1}\".format(b, id(b)))\nprint(\"a is b?\", a is b)\nprint(\"Adding 1 to a..\")\na[12] = 12\nprint(\"a = {0} id:{1}\".format(a, id(a)))\nprint(\"b = {0} id:{1}\".format(b, id(b)))\nprint(\"a is b?\", a is b)", "_____no_output_____" ] ], [ [ "## immutable vs mutable", "_____no_output_____" ] ] ]
[ "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", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
ec4eb3921b5ef2b88fb6568b5a742a72c6bca9e7
100,543
ipynb
Jupyter Notebook
15. Astrophysics Data/02. Archivos DAT+ReadMe/DATFiles.ipynb
ashcat2005/AstrofisicaComputacional2022
67463ec4041eb08c0f326792fed0dcf9e970e9b7
[ "MIT" ]
3
2022-03-08T06:18:56.000Z
2022-03-10T04:55:53.000Z
15. Astrophysics Data/02. Archivos DAT+ReadMe/DATFiles.ipynb
ashcat2005/AstrofisicaComputacional2022
67463ec4041eb08c0f326792fed0dcf9e970e9b7
[ "MIT" ]
null
null
null
15. Astrophysics Data/02. Archivos DAT+ReadMe/DATFiles.ipynb
ashcat2005/AstrofisicaComputacional2022
67463ec4041eb08c0f326792fed0dcf9e970e9b7
[ "MIT" ]
4
2022-03-09T17:47:43.000Z
2022-03-21T02:29:36.000Z
141.014025
28,180
0.861472
[ [ [ "![Astrofisica Computacional](../../logo.png)", "_____no_output_____" ], [ "---\n## Archivos `.dat` + `ReadMe` \n\n\nEduard Larrañaga ([email protected])\n\n---", "_____no_output_____" ], [ "### Resumen\n\nEn este cuaderno se utiliza la librería `astropy.io` para leer una arcivo de datos de texto plano con extensión .dat (formato ascii) junto con un archivo adicional ReadMe que contiene los metadatos. \n\n---", "_____no_output_____" ], [ "## 1. Obtención y Lectura de los Datos\n\nConsideraremos el conjunto de datos reportado Greene and Ho [2006], el cual contiene información de 88 galaxias cercanas. \n\nGreene, J. E. and Ho, L. C. *The MBH − σ∗ Relation in Local Active Galaxies*. ApJ 641 L21 (2006)\nhttps://ui.adsabs.harvard.edu/abs/2006ApJ...641L..21G/abstract\n\nEl conjunto de datos está disponibele, en varios formatos en\n\nhttp://vizier.cfa.harvard.edu/viz-bin/VizieR?-source=J/ApJ/641/L21.\n\nAl hacer click en el link ReadMe+ftp link se puede acceder a los datos via FTP.\n\n---\n\n### Abrir los archivos .dat+ReadMe.\n\nPara acceder a la información del archivo plano .dat file (en formato ascii) y los metadatos en el archivo ReadMe se utilizará el comando [astropy.io.ascii](https://docs.astropy.org/en/stable/io/ascii/)\n ", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom astropy.io import ascii\nimport matplotlib.pyplot as plt\n\n\n\ndata = ascii.read('table1.dat', readme='ReadMe')\ndata", "WARNING: UnitsWarning: '[10-7W]' did not parse as cds unit: Syntax error If this is meant to be a custom unit, define it with 'u.def_unit'. To have it recognized inside a file reader or other code, enable it with 'u.add_enabled_units'. For details, see https://docs.astropy.org/en/latest/units/combining_and_defining.html [astropy.units.core]\n" ] ], [ [ "La longitud de la tabla es de 88 muestras y 12 características, incluyendo 'Name', 'z', 'sigma*', etc.", "_____no_output_____" ], [ "---\nEs posible acceder a cada una de las características,", "_____no_output_____" ] ], [ [ "data['z']", "_____no_output_____" ], [ "data['logL']", "_____no_output_____" ] ], [ [ "También se puede acceder a los datos completos de una muestra particular o un conjunto de muestras,", "_____no_output_____" ] ], [ [ "data[1]", "_____no_output_____" ], [ "data[[0,1,3,4]]", "_____no_output_____" ] ], [ [ "Distribuiremos la información en un conjunto de arreglos de numpy,", "_____no_output_____" ] ], [ [ "z = np.array(data[\"z\"])\nsigma_star = np.array(data[\"sigma*\"])\ne_sigma_star = np.array(data[\"e_sigma*\"])\nlogL = np.array(data[\"logL\"])\ne_logL = np.array(data[\"e_logL\"])\nlogM = np.array(data[\"logM\"])\ne_logM = np.array(data[\"e_logM\"])", "_____no_output_____" ] ], [ [ "## 2. Visualizar la información\n\nVeamos diferentes combinaciones de características, buscando alguna clase de patrón de interés,", "_____no_output_____" ] ], [ [ "plt.scatter(z, logM, color='red')\nplt.xlabel(r'$z$')\nplt.ylabel(r'$\\log M$')\nplt.show()", "_____no_output_____" ], [ "plt.figure(figsize=(10, 10))\n\nplt.subplot(221)\nplt.plot(z, logM, 'b.')\nplt.xlabel(r'$z$')\nplt.ylabel(r'$\\log M$')\n\nplt.subplot(222)\nplt.plot(logL, logM, 'r.')\nplt.xlabel(r'$\\log L$')\nplt.ylabel(r'$\\log M$')\n\nplt.subplot(223)\nplt.plot(z, logL, 'g.')\nplt.xlabel(r'$z$')\nplt.ylabel(r'$\\log L$')\n\nplt.subplot(224)\nplt.plot(sigma_star, logM, 'k.')\nplt.xlabel(r'$\\sigma_{*}$')\nplt.ylabel(r'$\\log M$')\n\nplt.show()", "_____no_output_____" ] ], [ [ "Aparecen alguna información o patrones intersantes. Por ejemplo,\n\n- Se obsrevan dos puntos separados (outcaast) en el gráfico de $\\log M$ vs $z$.\n- Parece que existen dos cúmulos separados en el gráfico de $\\log M$ vs $\\log L$\n- Parece que existen tres cúmulos separados (o dos cumulos y dos puntos separados) en el gráfico de $\\log L$ vs $z$\n- Existe una tendencia de correlación en el gráfico de $\\log M$ vs $\\sigma_{*}$\n\nA pesar de que estos comportamientos parecen existir, algunos de ellos deben revisarse con cuidado. Por ejemplo, los aparentes cúmulos en las figuras 2 y 3 corresponden a una ausencia de datos, mal interpreata al convertir la información a arreglos. Al revisar la información en $\\log L$ se tiene", "_____no_output_____" ] ], [ [ "logL", "_____no_output_____" ] ], [ [ "donde se observa una gran cantidad de valores $0.$ que en realidad correspondian a datos ausentes en el conjunto inicial. Estos valores de cero fueron incorporados al utilizar el comando `logL = np.array(data[\"logL\"])`. \n\nNOTA: Es importante manjear adecuadamente la ausencia de datos!", "_____no_output_____" ], [ "---\nPor otra parte, podemos analizar con mayor detalle la aparente correlación entre $\\log M$ y $\\sigma_{*}$", "_____no_output_____" ] ], [ [ "plt.plot(sigma_star, logM, 'k.')\nplt.xlabel(r'$\\sigma_{*}$')\nplt.ylabel(r'$\\log M$')\nplt.show()", "_____no_output_____" ] ], [ [ "Puede parecer una dependencia lineal entre las dos variables. Sin embargo, para tener una mejor apreciación, incluiremos las barras de error. Para ello utilizamos la función [matplotlib.pyplot.errorbar](https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.errorbar.html)", "_____no_output_____" ] ], [ [ "plt.errorbar(sigma_star, logM, e_logM, e_sigma_star, fmt='k.')\nplt.xlabel(r'$\\sigma_{*}$')\nplt.ylabel(r'$\\log M$')\nplt.show()", "_____no_output_____" ] ], [ [ "Esta visualización miestra una correlación no-lineal. Para comprobarlo, podemos modificar la gráfica incluyendo el logaritmo de la dispersion de velocidades, $\\log M$ vs $\\log \\sigma_{*}$,con lo cual la tendencia lineal es evidente,", "_____no_output_____" ] ], [ [ "plt.plot(np.log10(sigma_star), logM, 'k.')\nplt.xlabel(r'$\\log \\sigma_{*}$')\nplt.ylabel(r'$\\log M$')\nplt.show()", "_____no_output_____" ] ], [ [ "Para confirmar esta apreciación, incluimos nuevamente las incertidumbres asociadas. Para ello es necesario recordar la propagación de errores,\n\n\\begin{align}\nf(x) =& \\log_{10} x = \\frac{\\ln x}{\\ln 10}\\\\\n\\Delta f = &\\frac{1}{\\ln 10} \\frac{\\Delta x}{x}\n\\end{align}", "_____no_output_____" ] ], [ [ "\ne_log_sigma = e_sigma_star/(np.log(10.)*sigma_star)\n\n\nplt.errorbar(np.log10(sigma_star), logM, e_logM, e_log_sigma, fmt='k.')\nplt.xlabel(r'$\\log \\sigma_{*}$')\nplt.ylabel(r'$\\log M$')\nplt.show()", "_____no_output_____" ] ], [ [ "Luego volveremos sobre este conjunto de datos para analizar mejor esta relación.", "_____no_output_____" ] ] ]
[ "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", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec4ec47787a11f33be7f9b33cdd5982e2033c3be
422,921
ipynb
Jupyter Notebook
demo_MSMK.ipynb
PabloAlvarado/MSMK
9976429cf0a7f38e52d890e1cf6e6fc982fe2882
[ "Apache-2.0" ]
3
2018-02-20T20:38:40.000Z
2021-12-12T14:26:12.000Z
demo_MSMK.ipynb
PabloAlvarado/MSMK
9976429cf0a7f38e52d890e1cf6e6fc982fe2882
[ "Apache-2.0" ]
1
2018-11-16T15:00:03.000Z
2019-04-08T08:27:10.000Z
demo_MSMK.ipynb
PabloAlvarado/MSMK
9976429cf0a7f38e52d890e1cf6e6fc982fe2882
[ "Apache-2.0" ]
1
2020-06-01T07:21:59.000Z
2020-06-01T07:21:59.000Z
624.698671
79,588
0.942817
[ [ [ "# Matérn Spectral Mixture (MSM) kernel \n## Gaussian process priors for pitch detection in polyphonic music\n### Learning kernels in frequency domain\n#### Written by Pablo A. Alvarado, Centre for Digital Music, Queen Mary University of London.\n\n\n*Last updated Friday, 12 May 2017.*\n\n", "_____no_output_____" ], [ "The aim of this notebook is to ilustrate the approach proposed in (link) for pitch detection in polyphonic signals, applying Gaussian processes (GPs) models in Python using [GPflow](https://github.com/GPflow/GPflow). We first outline the mathematical formulation of the proposed model. Then we introduce how to learn hyperparameters in frequency domain. Finally we present an example for detecting two pitches in a polyphonic music signal.\n\nThe dataset used in this tutorial corresponds to the electric guitar mixture signal in http://winnie.kuis.kyoto-u.ac.jp/~yoshii/psdtf/. The first 4 seconds of the data were used for training, this segment corresponds to 2 isolated sound events, with pitch C4 and E4 respectively. The test data was made of three sound events with pitches C4, E4, C4+E4, i.e. the training data in addition to an event with both pitches. ", "_____no_output_____" ], [ "## GP additive model for pitch detection", "_____no_output_____" ], [ "Automatic music transcription aims to infer a symbolic representation, such as piano-roll or score, given an observed audio recording. From a Bayesian latent variable perspective, transcription consists in updating our beliefs about the symbolic description for a certain piece of music, after observing a corresponding audio recording. \n\nWe approach the transcription problem from a time-domain source separation perspective. That is, given an audio recording $\\mathcal{D}=\\left\\lbrace y_n, t_n \\right\\rbrace_{n=1}^{N}$, we seek to formulate a generative probabilistic model that describes how the observed polyphonic signal (mixture of sources) was generated and, moreover, that allows us to infer the latent variables associated with the piano-roll representation. To do so, we use the regression model \n\n\\begin{align}\ny_n = f(t_n) + \\epsilon,\n\\end{align}\n\t\nwhere $y_n$ is the value of the analysed polyphonic signal at time $t_n$, the noise follows a normal distribution $\\epsilon \\sim \\mathcal{N}(0,\\sigma^2)$, and the function $f(t)$ is a random process composed by a linear combination of $M$ sources $\\left\\lbrace f_m(t) \\right\\rbrace _{m=1}^{M} $, that is\n\n\\begin{align}\nf(t) = \\sum_{m=1}^{M} f_{m}(t).\n\\end{align}\n\t\nEach source is decomposed into the product of two factors, an amplitude-envelope or activation function $\\phi_m(t)$, and a quasi-periodic or component function $w_{m}(t)$. The overall model is then \n\n\\begin{align}\ny(t) = \\sum_{m=1}^{M} \\phi_{m}(t) w_{m}(t) + \\epsilon.\n\\end{align}\n\t\t\nWe can interpret the set $\\left\\lbrace w_{m}(t)\\right\\rbrace_{m=1}^{M}$ as a dictionary where each component $ w_{m}(t)$ is a quasi-periodic stochastic function with a defined pitch. Likewise, each stochastic function in $\\left\\lbrace \\phi_{m}(t)\\right\\rbrace_{m=1}^{M}$ represents a row of the piano roll-matrix, i.e the time dependent non-negative activation of a specific pitch throughout the analysed piece of music.\n\n\n\nComponents $\\left\\lbrace w_{m}(t)\\right\\rbrace_{m=1}^{M}$ follow \n\n\\begin{align}\nw_m(t) \\sim \\mathcal{GP}(0,k_m(t,t')),\n\\end{align}\n\n\nwhere the covariance $k_m(t,t')$ reflect the frequency content of the $m^{\\text{th}}$ component, and has the form of a Matérn spectral mixture (MSM) kernel.\n\nTo guarantee the activations to be non-negative we apply non-linear transformations to GPs. To do so, we use the sigmoid function \n\\begin{align}\n\\sigma(x) = \\left[ 1 + \\exp(-x) \\right]^{-1},\n\\end{align}\nThen, activations are defined as \n\\begin{align*}\n\\phi_m(t) = \\sigma( {g_{m}(t)} ),\n\\end{align*}\n\nwhere $ \\left\\lbrace g_{m}(t)\\right\\rbrace_{m=1}^{M} $ are GPs. The sigmoid model follows\n\n\\begin{align}\ny(t)=\n\\sum_{m = 1}^{M}\n\\sigma( {g_{m}(t)} )\n\\\nw_{m}(t) \n+ \\epsilon.\n\\end{align}\n", "_____no_output_____" ], [ "## Learning hyperparameters in frequency domain", "_____no_output_____" ], [ "In this section we describe how to learn the hyperparameters for the components $\\left\\lbrace w_{m}(t)\\right\\rbrace_{m=1}^{M}$, and the activations $\\left\\lbrace g_{m}(t)\\right\\rbrace_{m=1}^{M}$. ", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nplt.style.use('ggplot')\nplt.rcParams['figure.figsize'] = (16, 4)\nimport numpy as np\nimport scipy as sp\nimport scipy.io as sio\nimport scipy.io.wavfile as wav\nfrom scipy import signal \nfrom scipy.fftpack import fft\nimport gpflow\nimport GPitch", "_____no_output_____" ], [ "sf, y = wav.read('guitar.wav') #loading dataset\ny = y.astype(np.float64)\nyaudio = y / np.max(np.abs(y))\nN = np.size(yaudio)\nXaudio = np.linspace(0, (N-1.)/sf, N)\n\nX1, y1 = Xaudio[0:2*sf], yaudio[0:2*sf] # define training data for component 1 and 2\nX2, y2 = Xaudio[2*sf:4*sf], yaudio[2*sf:4*sf]\n\ny1f, y2f = sp.fftpack.fft(y1), sp.fftpack.fft(y2) # get spectral density for each isolated sound event \nN1 = y1.size # Number of sample points\nT = 1.0 / sf # sample period\nF = np.linspace(0.0, 1.0/(2.0*T), N1/2)\nS1 = 2.0/N1 * np.abs(y1f[0:N1/2])\nS2 = 2.0/N1 * np.abs(y2f[0:N1/2])", "_____no_output_____" ], [ "plt.figure()\nplt.subplot(1,2,1), plt.title('Waveform sound event with pitch C4'), plt.xlabel('Time (s)'),\nplt.plot(X1, y1), \n\nplt.subplot(1,2,2), plt.title('Waveform sound event with pitch E4'), plt.xlabel('Time (s)'),\nplt.plot(X2, y2)\n\nplt.figure()\nplt.subplot(1,2,1), plt.title('Spectral density sound event with pitch C4'), plt.xlabel('Frequency (Hz)'),\nplt.plot(F, S1, lw=2), plt.xlim([0, 5000])\n\nplt.subplot(1,2,2), plt.title('Spectral density sound event with pitch E4'), plt.xlabel('Frequency (Hz)'),\nplt.plot(F, S2, lw=2), plt.xlim([0, 5000]);", "_____no_output_____" ] ], [ [ "### Learning frequency content of each component process $\\left\\lbrace w_{m}(t)\\right\\rbrace_{m=1}^{M}$\n", "_____no_output_____" ], [ "#### Example fitting one frequency component", "_____no_output_____" ] ], [ [ "# example fitting one harmonic\nidx = np.argmax(S1)\na, b = idx - 50, idx + 50\nX, y = F[a: b,].reshape(-1,), S1[a: b,].reshape(-1,)\np0 = np.array([1., 1., 2*np.pi*F[idx]])\nphat = sp.optimize.minimize(GPitch.Lloss, p0, method='L-BFGS-B', args=(X, y), tol = 1e-10, options={'disp': True})\npstar = phat.x\nXaux = np.linspace(X.min(), X.max(), 1000)\nL = GPitch.Lorentzian(pstar,Xaux)\nplt.figure(), plt.xlim([X.min(), X.max()])\nplt.plot(Xaux, L, lw=2)\nplt.plot(X, y, '.', ms=8);", "_____no_output_____" ], [ "Nh = 15 # maximun number of harmonics\ns_1, l_1, f_1 = GPitch.learnparams(F, S1, Nh)\nNh1 = s_1.size\ns_2, l_2, f_2 = GPitch.learnparams(F, S2, Nh)\nNh2 = s_2.size", "_____no_output_____" ], [ "plt.figure()\nfor i in range(0, Nh1):\n idx = np.argmin(np.abs(F - f_1[i]))\n a = idx - 50\n b = idx + 50\n pstar = np.array([s_1[i], 1./l_1[i], 2.*np.pi*f_1[i]])\n learntfun = GPitch.Lorentzian(pstar, F)\n plt.subplot(1,Nh,i+1)\n plt.plot(F[a:b],learntfun[a:b],'', lw = 2)\n plt.plot(F[a:b],S1[a:b],'.', ms = 3)\n plt.axis('off')\n plt.ylim([S1.min(), S1.max()])\n \nplt.figure()\nfor i in range(0, Nh2):\n idx = np.argmin(np.abs(F - f_2[i]))\n a = idx - 50\n b = idx + 50\n pstar = np.array([s_2[i], 1./l_2[i], 2.*np.pi*f_2[i]])\n learntfun = GPitch.Lorentzian(pstar, F)\n plt.subplot(1,Nh,i+1)\n plt.plot(F[a:b],learntfun[a:b],'', lw = 2)\n plt.plot(F[a:b],S2[a:b],'.', ms = 3)\n plt.axis('off')\n plt.ylim([S2.min(), S2.max()])", "_____no_output_____" ], [ "S1k = GPitch.LorM(F, s=s_1, l=1./l_1, f=2*np.pi*f_1)\nS2k = GPitch.LorM(F, s=s_2, l=1./l_2, f=2*np.pi*f_2)\n\nplt.figure(), plt.title('Approximate spectrum using Lorentzian mixture')\nplt.subplot(1,2,1), plt.plot(F, S1, lw=2), plt.plot(F, S1k, lw=2)\nplt.legend(['FT source 1', 'S kernel 1']), plt.xlabel('Frequency (Hz)')\nplt.subplot(1,2,2), plt.plot(F, S2, lw=2), plt.plot(F, S2k, lw=2)\nplt.legend(['FT source 2', 'S kernel 2']), plt.xlabel('Frequency (Hz)');", "_____no_output_____" ], [ "Xk = np.linspace(-1.,1.,2*16000).reshape(-1,1)\nIFT_y1 = np.fft.ifft(np.abs(y1f))\nIFT_y2 = np.fft.ifft(np.abs(y2f))\nk1 = GPitch.MaternSM(Xk, s=s_1, l=1./l_1, f=2*np.pi*f_1)\nk2 = GPitch.MaternSM(Xk, s=s_2, l=1./l_2, f=2*np.pi*f_2)\n\nplt.figure()\nplt.subplot(1,2,1), plt.plot(Xk, k1, lw=2), plt.xlim([-0.005, 0.005])\nplt.subplot(1,2,2), plt.plot(Xk, k2, lw=2), plt.xlim([-0.005, 0.005])\n\nplt.figure()\nplt.subplot(1,2,1), plt.plot(Xk, k1)\nplt.subplot(1,2,2), plt.plot(Xk, k2)\n\nplt.figure(),\nplt.subplot(1,2,1), plt.plot(X1[0:16000],IFT_y1[0:16000], lw=1), plt.plot(X1[0:16000],k1[16000:32000], lw=1)\nplt.xlim([0, 0.03])\nplt.subplot(1,2,2), plt.plot(X1[0:16000],IFT_y2[0:16000], lw=1), plt.plot(X1[0:16000],k2[16000:32000], lw=1)\nplt.xlim([0, 0.03]);", "/home/pa/anaconda2/lib/python2.7/site-packages/numpy/core/numeric.py:501: ComplexWarning: Casting complex values to real discards the imaginary part\n return array(a, dtype, copy=False, order=order)\n" ] ], [ [ "### Learning hyperparameters of activation processes $\\left\\lbrace \\phi_{m}(t)\\right\\rbrace_{m=1}^{M}$", "_____no_output_____" ], [ "So far we have learnt the harmoninc content of the isolated events. Now we try to learn the parameters of the GP that describes the amplitude envelope. ", "_____no_output_____" ] ], [ [ "win = signal.hann(200)\nenv1 = signal.convolve(np.abs(y1), win, mode='same') / sum(win)\nenv1 = np.max(np.abs(y1))*(env1 / np.max(env1))\nenv1 = env1.reshape(-1,)\nenv2 = signal.convolve(np.abs(y2), win, mode='same') / sum(win)\nenv2 = np.max(np.abs(y2))*(env2 / np.max(env2))\nenv2 = env2.reshape(-1,)\n\nplt.figure()\nplt.subplot(1,2,1), plt.plot(X1, y1, ''), plt.plot(X1, env1, '', lw = 2)\nplt.subplot(1,2,2), plt.plot(X2, y2, ''), plt.plot(X2, env2, '', lw = 2);", "_____no_output_____" ], [ "yf = fft(env1)\nxf = np.linspace(-1.0/(2.0*T), 1.0/(2.0*T), N1)\nS = 1.0/N1 * np.abs(yf)\nsht = np.fft.fftshift(S)\n\na = np.argmin(np.abs(xf - (-10.)))\nb = np.argmin(np.abs(xf - ( 10.)))\nX, y = xf[a:b].reshape(-1,), sht[a:b].reshape(-1,)\np0 = np.array([1., 1., 0.])\nphat = sp.optimize.minimize(GPitch.Lloss, p0, method='L-BFGS-B', args=(X, y), tol = 1e-10, options={'disp': True})\nX2 = np.linspace(X.min(), X.max(), 1000)\nL = GPitch.Lorentzian(phat.x, X2)\nplt.figure()\nplt.subplot(1,2,1), plt.plot(X2, L), plt.plot(X, y, '.', ms=8)\nplt.subplot(1,2,2), plt.plot(X2, L), plt.plot(X, y, '.', ms=8)\ns_env, l_env, f_env = np.hsplit(phat.x, 3)", "_____no_output_____" ] ], [ [ "# Using the learnt MSM kernel for pitch detection", "_____no_output_____" ], [ "We keep the same form for the learnt variances $\\sigma^{2}$, but we modify the lengthscale because we learnt the inverse, i.e. $l = \\lambda^{-1}$. Also, we learnt the frequency vector in radians, that is why we convert it to Hz.", "_____no_output_____" ] ], [ [ "# To run the pitch detection change: RunExperiment = True\nRunExperiment = False\nif RunExperiment == True:\n GPitch.pitch('guitar.wav', windowsize=16000)\nelse:\n results = np.load('SIG_FL_results.npz')\n X = results['X']\n g1 = results['mu_g1']\n g2 = results['mu_g2']\n phi1 = GPitch.logistic(g1)\n phi2 = GPitch.logistic(g2)\n w1 = results['mu_f1']\n w2 = results['mu_f2']\n f1 = phi1*w1\n f2 = phi2*w2\n\nXtest1, ytest1 = Xaudio[0:4*sf], yaudio[0:4*sf]\nXtest2, ytest2 = Xaudio[6*sf:8*sf], yaudio[6*sf:8*sf]\nXtest = np.hstack((Xtest1, Xtest2)).reshape(-1,1)\nytest = np.hstack((ytest1, ytest2)).reshape(-1,1)\nsf, sourceC = wav.read('source_C.wav')\nsourceC = sourceC.astype(np.float64)\nsourceC = sourceC / np.max(np.abs(sourceC))\nsf, sourceE = wav.read('source_E.wav')\nsourceE = sourceE.astype(np.float64)\nsourceE = sourceE / np.max(np.abs(sourceE))\n\nplt.figure()\nplt.plot(Xtest, ytest)", "_____no_output_____" ], [ "plt.figure()\nplt.subplot(1,2,1), plt.plot(Xaudio, sourceC)\nplt.xlim([X.min(), X.max()])\nplt.subplot(1,2,2), plt.plot(Xaudio, sourceE)\nplt.xlim([X.min(), X.max()]) \n \nplt.figure()\nplt.subplot(1,2,1), plt.plot(X, f1)\nplt.subplot(1,2,2), plt.plot(X, f2)\n \nplt.figure()\nplt.subplot(1,2,1), plt.plot(X, phi1)\nplt.subplot(1,2,2), plt.plot(X, phi2)\n\nplt.figure()\nplt.subplot(1,2,1), plt.plot(X, w1)\nplt.subplot(1,2,2), plt.plot(X, w2)", "_____no_output_____" ] ], [ [ "## Piano-roll", "_____no_output_____" ] ], [ [ "#%% genetare piano-roll ground truth\njump = 100 #downsample\nXsubset = X[::jump]\noct1 = 24\noct2 = 84\nY = np.arange(oct1,oct2).reshape(-1,1)\nNs = Xsubset.size\nPhi = np.zeros((Y.size, Ns))\n#Phi[47-oct1, (Xsubset> 0.050 and Xsubset< 1.973)] = 1.\nC4_a1 = np.argmin(np.abs(Xsubset-0.050))\nC4_b1 = np.argmin(np.abs(Xsubset-1.973))\nC4_a2 = np.argmin(np.abs(Xsubset-6.050))\nC4_b2 = np.argmin(np.abs(Xsubset-7.979))\n\nPhi[47-oct1, C4_a1:C4_b1 ] = 1.\nPhi[47-oct1, C4_a2:C4_b2 ] = 1.\nPhi[47-oct1, C4_a3:C4_b3 ] = 1.\nPhi[47-oct1, C4_a4:C4_b4 ] = 1.\n\nE4_a1 = np.argmin(np.abs(Xsubset-2.050))\nE4_b1 = np.argmin(np.abs(Xsubset-3.979))\nE4_a2 = np.argmin(np.abs(Xsubset-6.050))\nE4_b2 = np.argmin(np.abs(Xsubset-7.979))\n\nPhi[51-oct1, E4_a1:E4_b1 ] = 1.\nPhi[51-oct1, E4_a2:E4_b2 ] = 1.\nPhi[51-oct1, E4_a3:E4_b3 ] = 1.\nPhi[51-oct1, E4_a4:E4_b4 ] = 1.\n\n\nPhi = np.abs(Phi-1)\n[Xm, Ym] = np.meshgrid(Xsubset,Y)\n\n#infered piano roll\nPhi_i = np.zeros((Y.size, Ns))\nPhi_i[47-oct1, :] = phi1[::jump].reshape(-1,)\nPhi_i[51-oct1, :] = phi2[::jump].reshape(-1,)\nPhi_i = np.abs(Phi_i-1)\n", "_____no_output_____" ], [ "plt.figure()\nplt.ylabel('')\nplt.xlabel('Time (s)')\nplt.pcolormesh(Xm, Ym, Phi, cmap='gray')\nplt.ylim([oct1, oct2])\nplt.xlim([0, 8])\nplt.xlabel('Time (seconds)')\n\nplt.figure()\nplt.ylabel('')\nplt.xlabel('Time (s)')\nplt.pcolormesh(Xm, Ym, Phi_i, cmap='gray')\nplt.ylim([oct1, oct2])\nplt.xlim([0, 8])\nplt.xlabel('Time (seconds)')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ec4ec71f1fa497bd6ce7eb7b03c07d3d874d84d5
95,157
ipynb
Jupyter Notebook
NN_Numpy/Neural_Network_Assignment.ipynb
keensam04/ml-ai
ff4e4b1bc6130dd9010d13a21c15c84bb33fea4c
[ "MIT" ]
10
2020-05-29T12:14:37.000Z
2022-02-10T07:55:52.000Z
NN_Numpy/Neural_Network_Assignment.ipynb
keensam04/ml-ai
ff4e4b1bc6130dd9010d13a21c15c84bb33fea4c
[ "MIT" ]
null
null
null
NN_Numpy/Neural_Network_Assignment.ipynb
keensam04/ml-ai
ff4e4b1bc6130dd9010d13a21c15c84bb33fea4c
[ "MIT" ]
8
2020-07-19T03:56:01.000Z
2022-02-27T14:43:07.000Z
49.304145
17,312
0.633469
[ [ [ "In this assignment, you'll implement an L-layered deep neural network and train it on the MNIST dataset. The MNIST dataset contains scanned images of handwritten digits, along with their correct classification labels (between 0-9). MNIST's name comes from the fact that it is a modified subset of two data sets collected by NIST, the United States' National Institute of Standards and Technology.<br>", "_____no_output_____" ], [ "## Data Preparation", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pickle\nimport gzip\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nimport sklearn\nimport sklearn.datasets\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\n\n\n%matplotlib inline", "/Users/saman.tamkeen/.local/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n" ] ], [ [ "The MNIST dataset we use here is 'mnist.pkl.gz' which is divided into training, validation and test data. The following function <i> load_data() </i> unpacks the file and extracts the training, validation and test data.", "_____no_output_____" ] ], [ [ "def load_data():\n f = gzip.open('mnist.pkl.gz', 'rb')\n f.seek(0)\n training_data, validation_data, test_data = pickle.load(f, encoding='latin1')\n f.close()\n return (training_data, validation_data, test_data)", "_____no_output_____" ] ], [ [ "Let's see how the data looks:", "_____no_output_____" ] ], [ [ "training_data, validation_data, test_data = load_data()", "_____no_output_____" ], [ "training_data", "_____no_output_____" ], [ "# shape of data\nprint(training_data[0].shape)\nprint(training_data[1].shape)", "(50000, 784)\n(50000,)\n" ], [ "print(\"The feature dataset is:\" + str(training_data[0]))\nprint(\"The target dataset is:\" + str(training_data[1]))\nprint(\"The number of examples in the training dataset is:\" + str(len(training_data[0])))\nprint(\"The number of points in a single input is:\" + str(len(training_data[0][1])))", "The feature dataset is:[[0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n ...\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]]\nThe target dataset is:[5 0 4 ... 8 4 8]\nThe number of examples in the training dataset is:50000\nThe number of points in a single input is:784\n" ] ], [ [ "Now, as discussed earlier in the lectures, the target variable is converted to a one hot matrix. We use the function <i> one_hot </i> to convert the target dataset to one hot encoding.", "_____no_output_____" ] ], [ [ "def one_hot(j):\n # input is the target dataset of shape (m,) where m is the number of data points\n # returns a 2 dimensional array of shape (10, m) where each target value is converted to a one hot encoding\n # Look at the next block of code for a better understanding of one hot encoding\n n = j.shape[0]\n new_array = np.zeros((10, n))\n index = 0\n for res in j:\n new_array[res][index] = 1.0\n index = index + 1\n return new_array", "_____no_output_____" ], [ "data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\nprint(data.shape)\none_hot(data)", "(10,)\n" ] ], [ [ "The following function data_wrapper() will convert the dataset into the desired shape and also convert the ground truth labels to one_hot matrix.", "_____no_output_____" ] ], [ [ "def data_wrapper():\n tr_d, va_d, te_d = load_data()\n \n training_inputs = np.array(tr_d[0][:]).T\n training_results = np.array(tr_d[1][:])\n train_set_y = one_hot(training_results)\n \n validation_inputs = np.array(va_d[0][:]).T\n validation_results = np.array(va_d[1][:])\n validation_set_y = one_hot(validation_results)\n \n test_inputs = np.array(te_d[0][:]).T\n test_results = np.array(te_d[1][:])\n test_set_y = one_hot(test_results)\n \n return (training_inputs, train_set_y, test_inputs, test_set_y)", "_____no_output_____" ], [ "train_set_x, train_set_y, test_set_x, test_set_y = data_wrapper()", "_____no_output_____" ], [ "print (\"train_set_x shape: \" + str(train_set_x.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x shape: \" + str(test_set_x.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))", "train_set_x shape: (784, 50000)\ntrain_set_y shape: (10, 50000)\ntest_set_x shape: (784, 10000)\ntest_set_y shape: (10, 10000)\n" ] ], [ [ "We can see that the data_wrapper has converted the training and validation data into numpy array of desired shapes. Let's convert the actual labels into a dataframe to see if the one hot conversions are correct.", "_____no_output_____" ] ], [ [ "y = pd.DataFrame(train_set_y)", "_____no_output_____" ], [ "print(\"The target dataset is:\" + str(training_data[1]))\nprint(\"The one hot encoding dataset is:\")\ny", "The target dataset is:[5 0 4 ... 8 4 8]\nThe one hot encoding dataset is:\n" ] ], [ [ "Now let us visualise the dataset. Feel free to change the index to see if the training data has been correctly tagged.", "_____no_output_____" ] ], [ [ "index = 1000\nk = train_set_x[:,index]\nk = k.reshape((28, 28))\nplt.title('Label is {label}'.format(label= training_data[1][index]))\nplt.imshow(k, cmap='gray')", "_____no_output_____" ] ], [ [ "# Feedforward", "_____no_output_____" ], [ "### sigmoid\nThis is one of the activation functions. It takes the cumulative input to the layer, the matrix **Z**, as the input. Upon application of the **`sigmoid`** function, the output matrix **H** is calculated. Also, **Z** is stored as the variable **sigmoid_memory** since it will be later used in backpropagation.You use _[np.exp()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html)_ here in the following way. The exponential gets applied to all the elements of Z.", "_____no_output_____" ] ], [ [ "def sigmoid(Z):\n \n # Z is numpy array of shape (n, m) where n is number of neurons in the layer and m is the number of samples \n # sigmoid_memory is stored as it is used later on in backpropagation\n \n H = 1/(1+np.exp(-Z))\n sigmoid_memory = Z\n \n return H, sigmoid_memory", "_____no_output_____" ], [ "Z = np.arange(8).reshape(4,2)\nprint (\"sigmoid(Z) = \" + str(sigmoid(Z)))", "sigmoid(Z) = (array([[0.5 , 0.73105858],\n [0.88079708, 0.95257413],\n [0.98201379, 0.99330715],\n [0.99752738, 0.99908895]]), array([[0, 1],\n [2, 3],\n [4, 5],\n [6, 7]]))\n" ] ], [ [ "### relu\nThis is one of the activation functions. It takes the cumulative input to the layer, matrix **Z** as the input. Upon application of the **`relu`** function, matrix **H** which is the output matrix is calculated. Also, **Z** is stored as **relu_memory** which will be later used in backpropagation. You use _[np.maximum()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.maximum.html)_ here in the following way.", "_____no_output_____" ] ], [ [ "def relu(Z):\n # Z is numpy array of shape (n, m) where n is number of neurons in the layer and m is the number of samples \n # relu_memory is stored as it is used later on in backpropagation\n \n H = np.maximum(0,Z)\n \n assert(H.shape == Z.shape)\n \n relu_memory = Z \n return H, relu_memory", "_____no_output_____" ], [ "Z = np.array([1, 3, -1, -4, -5, 7, 9, 18]).reshape(4,2)\nprint (\"relu(Z) = \" + str(relu(Z)))", "relu(Z) = (array([[ 1, 3],\n [ 0, 0],\n [ 0, 7],\n [ 9, 18]]), array([[ 1, 3],\n [-1, -4],\n [-5, 7],\n [ 9, 18]]))\n" ] ], [ [ "### softmax\nThis is the activation of the last layer. It takes the cumulative input to the layer, matrix **Z** as the input. Upon application of the **`softmax`** function, the output matrix **H** is calculated. Also, **Z** is stored as **softmax_memory** which will be later used in backpropagation. You use _[np.exp()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html)_ and _[np.sum()](https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.sum.html)_ here in the following way. The exponential gets applied to all the elements of Z.", "_____no_output_____" ] ], [ [ "def softmax(Z):\n # Z is numpy array of shape (n, m) where n is number of neurons in the layer and m is the number of samples \n # softmax_memory is stored as it is used later on in backpropagation\n \n Z_exp = np.exp(Z)\n\n Z_sum = np.sum(Z_exp,axis = 0, keepdims = True)\n \n H = Z_exp/Z_sum #normalising step\n softmax_memory = Z\n \n return H, softmax_memory", "_____no_output_____" ], [ "Z = np.array([[11,19,10], [12, 21, 23]])", "_____no_output_____" ], [ "#Z = np.array(np.arange(30)).reshape(10,3)\nH, softmax_memory = softmax(Z)\nprint(H)\nprint(softmax_memory)", "[[2.68941421e-01 1.19202922e-01 2.26032430e-06]\n [7.31058579e-01 8.80797078e-01 9.99997740e-01]]\n[[11 19 10]\n [12 21 23]]\n" ] ], [ [ "### initialize_parameters\nLet's now create a function **`initialize_parameters`** which initializes the weights and biases of the various layers. One way to initialise is to set all the parameters to 0. This is not a considered a good strategy as all the neurons will behave the same way and it'll defeat the purpose of deep networks. Hence, we initialize the weights randomly to very small values but not zeros. The biases are initialized to 0. Note that the **`initialize_parameters`** function initializes the parameters for all the layers in one `for` loop. \n\nThe inputs to this function is a list named `dimensions`. The length of the list is the number layers in the network + 1 (the plus one is for the input layer, rest are hidden + output). The first element of this list is the dimensionality or length of the input (784 for the MNIST dataset). The rest of the list contains the number of neurons in the corresponding (hidden and output) layers.\n\nFor example `dimensions = [784, 3, 7, 10]` specifies a network for the MNIST dataset with two hidden layers and a 10-dimensional softmax output.\n\nAlso, notice that the parameters are returned in a dictionary. This will help you in implementing the feedforward through the layer and the backprop throught the layer at once.", "_____no_output_____" ] ], [ [ "def initialize_parameters(dimensions):\n\n # dimensions is a list containing the number of neuron in each layer in the network\n # It returns parameters which is a python dictionary containing the parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n\n np.random.seed(2)\n parameters = {}\n L = len(dimensions) # number of layers in the network + 1\n\n for l in range(1, L): \n parameters['W' + str(l)] = np.random.randn(dimensions[l], dimensions[l-1]) * 0.1\n parameters['b' + str(l)] = np.zeros((dimensions[l], 1)) \n \n assert(parameters['W' + str(l)].shape == (dimensions[l], dimensions[l-1]))\n assert(parameters['b' + str(l)].shape == (dimensions[l], 1))\n\n \n return parameters", "_____no_output_____" ], [ "dimensions = [784, 3,7,10]\nparameters = initialize_parameters(dimensions)\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))\n# print(\"W3 = \" + str(parameters[\"W3\"]))\n# print(\"b3 = \" + str(parameters[\"b3\"]))", "W1 = [[-0.04167578 -0.00562668 -0.21361961 ... -0.06168445 0.03213358\n -0.09464469]\n [-0.05301394 -0.1259207 0.16775441 ... -0.03284246 -0.05623108\n 0.01179136]\n [ 0.07386378 -0.15872956 0.01532001 ... -0.08428557 0.10040469\n 0.00545832]]\nb1 = [[0.]\n [0.]\n [0.]]\nW2 = [[ 0.06650944 -0.19626047 0.2112715 ]\n [-0.28074571 -0.13967752 0.02641189]\n [ 0.10925169 0.06646016 0.08565535]\n [-0.11058228 0.03715795 0.13440124]\n [-0.16421272 -0.1153127 0.02013163]\n [ 0.13985659 0.07228733 -0.10717236]\n [-0.05673344 -0.03663499 -0.15460347]]\nb2 = [[0.]\n [0.]\n [0.]\n [0.]\n [0.]\n [0.]\n [0.]]\n" ] ], [ [ "### layer_forward\n\nThe function **`layer_forward`** implements the forward propagation for a certain layer 'l'. It calculates the cumulative input into the layer **Z** and uses it to calculate the output of the layer **H**. It takes **H_prev, W, b and the activation function** as inputs and stores the **linear_memory, activation_memory** in the variable **memory** which will be used later in backpropagation. \n\n<br> You have to first calculate the **Z**(using the forward propagation equation), **linear_memory**(H_prev, W, b) and then calculate **H, activation_memory**(Z) by applying activation functions - **`sigmoid`**, **`relu`** and **`softmax`** on **Z**.\n\n<br> Note that $$H^{L-1}$$ is referred here as H_prev. You might want to use _[np.dot()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html)_ to carry out the matrix multiplication.", "_____no_output_____" ] ], [ [ "#Graded\n\ndef layer_forward(H_prev, W, b, activation = 'relu'):\n\n # H_prev is of shape (size of previous layer, number of examples)\n # W is weights matrix of shape (size of current layer, size of previous layer)\n # b is bias vector of shape (size of the current layer, 1)\n # activation is the activation to be used for forward propagation : \"softmax\", \"relu\", \"sigmoid\"\n\n # H is the output of the activation function \n # memory is a python dictionary containing \"linear_memory\" and \"activation_memory\"\n \n _Z_without_bias = np.dot(W, H_prev)\n _Z_with_bias = np.add(_Z_without_bias, b)\n \n if activation == \"sigmoid\":\n Z = _Z_with_bias\n linear_memory = (H_prev, W, b)\n H, activation_memory = sigmoid(Z)\n \n elif activation == \"softmax\":\n Z = _Z_with_bias\n linear_memory = (H_prev, W, b)\n H, activation_memory = softmax(Z)\n \n elif activation == \"relu\":\n Z = _Z_with_bias\n linear_memory = (H_prev, W, b)\n H, activation_memory = relu(Z)\n \n assert (H.shape == (W.shape[0], H_prev.shape[1]))\n memory = (linear_memory, activation_memory)\n\n return H, memory", "_____no_output_____" ], [ "# verify\n# l-1 has two neurons, l has three, m = 5\n# H_prev is (l-1, m)\n# W is (l, l-1)\n# b is (l, 1)\n# H should be (l, m)\nH_prev = np.array([[1,0, 5, 10, 2], [2, 5, 3, 10, 2]])\nW_sample = np.array([[10, 5], [2, 0], [1, 0]])\nb_sample = np.array([10, 5, 0]).reshape((3, 1))\n\nH = layer_forward(H_prev, W_sample, b_sample, activation=\"sigmoid\")[0]\nH", "_____no_output_____" ] ], [ [ "You should get:<br>\n array([[1. , 1. , 1. , 1. , 1. ],<br>\n [0.99908895, 0.99330715, 0.99999969, 1. , 0.99987661],<br>\n [0.73105858, 0.5 , 0.99330715, 0.9999546 , 0.88079708]])\n ", "_____no_output_____" ], [ "### L_layer_forward\n**`L_layer_forward`** performs one forward pass through the whole network for all the training samples (note that we are feeding all training examples in one single batch). Use the **`layer_forward`** you have created above here to perform the feedforward for layers 1 to 'L-1' in the for loop with the activation **`relu`**. The last layer having a different activation **`softmax`** is calculated outside the loop. Notice that the **memory** is appended to **memories** for all the layers. These will be used in the backward order during backpropagation.", "_____no_output_____" ] ], [ [ "#Graded\n\ndef L_layer_forward(X, parameters):\n\n # X is input data of shape (input size, number of examples)\n # parameters is output of initialize_parameters()\n \n # HL is the last layer's post-activation value\n # memories is the list of memory containing (for a relu activation, for example):\n # - every memory of relu forward (there are L-1 of them, indexed from 1 to L-1), \n # - the memory of softmax forward (there is one, indexed L) \n\n memories = []\n H = X\n L = len(parameters) // 2 # number of layers in the neural network\n \n # Implement relu layer (L-1) times as the Lth layer is the softmax layer\n for l in range(1, L):\n H_prev = H\n \n H, memory = layer_forward(H_prev, parameters['W' + str(l)], parameters['b' + str(l)])\n \n memories.append(memory)\n \n # Implement the final softmax layer\n # HL here is the final prediction P as specified in the lectures\n HL, memory = layer_forward(H, parameters['W' + str(L)], parameters['b' + str(L)], activation='softmax')\n \n memories.append(memory)\n\n assert(HL.shape == (10, X.shape[1]))\n \n return HL, memories", "_____no_output_____" ], [ "# verify\n# X is (784, 10)\n# parameters is a dict\n# HL should be (10, 10)\nx_sample = train_set_x[:, 10:20]\nprint(x_sample.shape)\nHL = L_layer_forward(x_sample, parameters=parameters)[0]\nprint(HL[:, :5])", "(784, 10)\n[[0.10106734 0.10045152 0.09927757 0.10216656 0.1 ]\n [0.10567625 0.10230873 0.10170271 0.11250099 0.1 ]\n [0.09824287 0.0992886 0.09967128 0.09609693 0.1 ]\n [0.10028288 0.10013048 0.09998149 0.10046076 0.1 ]\n [0.09883601 0.09953443 0.09931419 0.097355 0.1 ]\n [0.10668575 0.10270912 0.10180736 0.11483609 0.1 ]\n [0.09832513 0.09932275 0.09954792 0.09627089 0.1 ]\n [0.09747092 0.09896735 0.0995387 0.09447277 0.1 ]\n [0.09489069 0.09788255 0.09929998 0.08915178 0.1 ]\n [0.09852217 0.09940447 0.09985881 0.09668824 0.1 ]]\n" ] ], [ [ "You should get:\n\n(784, 10)<br>\n[[0.10106734 0.10045152 0.09927757 0.10216656 0.1 ]<br>\n [0.10567625 0.10230873 0.10170271 0.11250099 0.1 ]<br>\n [0.09824287 0.0992886 0.09967128 0.09609693 0.1 ]<br>\n [0.10028288 0.10013048 0.09998149 0.10046076 0.1 ]<br>\n [0.09883601 0.09953443 0.09931419 0.097355 0.1 ]<br>\n [0.10668575 0.10270912 0.10180736 0.11483609 0.1 ]<br>\n [0.09832513 0.09932275 0.09954792 0.09627089 0.1 ]<br>\n [0.09747092 0.09896735 0.0995387 0.09447277 0.1 ]<br>\n [0.09489069 0.09788255 0.09929998 0.08915178 0.1 ]<br>\n [0.09852217 0.09940447 0.09985881 0.09668824 0.1 ]]", "_____no_output_____" ], [ "# Loss\n\n### compute_loss\nThe next step is to compute the loss function after every forward pass to keep checking whether it is decreasing with training.<br> **`compute_loss`** here calculates the cross-entropy loss. You may want to use _[np.log()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html)_, _[np.sum()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html)_, _[np.multiply()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html)_ here. Do not forget that it is the average loss across all the data points in the batch. It takes the output of the last layer **HL** and the ground truth label **Y** as input and returns the **loss**.", "_____no_output_____" ] ], [ [ "#Graded\n\ndef compute_loss(HL, Y):\n\n\n # HL is probability matrix of shape (10, number of examples)\n # Y is true \"label\" vector shape (10, number of examples)\n\n # loss is the cross-entropy loss\n\n m = Y.shape[1]\n\n log_p = np.log(HL)\n y_log_p = np.multiply(Y, log_p)\n total_loss = -1 * np.sum(y_log_p)\n loss = (1./m) * total_loss\n \n loss = np.squeeze(loss) # To make sure that the loss's shape is what we expect (e.g. this turns [[17]] into 17).\n assert(loss.shape == ())\n \n return loss", "_____no_output_____" ], [ "# sample\n# HL is (10, 5), Y is (10, 5)\nnp.random.seed(2)\nHL_sample = np.random.rand(10,5)\nY_sample = train_set_y[:, 10:15]\nprint(HL_sample)\nprint(Y_sample)\n\nprint(compute_loss(HL_sample, Y_sample))", "[[0.4359949 0.02592623 0.54966248 0.43532239 0.4203678 ]\n [0.33033482 0.20464863 0.61927097 0.29965467 0.26682728]\n [0.62113383 0.52914209 0.13457995 0.51357812 0.18443987]\n [0.78533515 0.85397529 0.49423684 0.84656149 0.07964548]\n [0.50524609 0.0652865 0.42812233 0.09653092 0.12715997]\n [0.59674531 0.226012 0.10694568 0.22030621 0.34982629]\n [0.46778748 0.20174323 0.64040673 0.48306984 0.50523672]\n [0.38689265 0.79363745 0.58000418 0.1622986 0.70075235]\n [0.96455108 0.50000836 0.88952006 0.34161365 0.56714413]\n [0.42754596 0.43674726 0.77655918 0.53560417 0.95374223]]\n[[0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 1.]\n [0. 0. 0. 0. 0.]\n [1. 0. 1. 0. 0.]\n [0. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0.]\n [0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]]\n0.8964600261334037\n" ] ], [ [ "You should get:<br>\n \n[[0.4359949 0.02592623 0.54966248 0.43532239 0.4203678 ]<br>\n [0.33033482 0.20464863 0.61927097 0.29965467 0.26682728]<br>\n [0.62113383 0.52914209 0.13457995 0.51357812 0.18443987]<br>\n [0.78533515 0.85397529 0.49423684 0.84656149 0.07964548]<br>\n [0.50524609 0.0652865 0.42812233 0.09653092 0.12715997]<br>\n [0.59674531 0.226012 0.10694568 0.22030621 0.34982629]<br>\n [0.46778748 0.20174323 0.64040673 0.48306984 0.50523672]<br>\n [0.38689265 0.79363745 0.58000418 0.1622986 0.70075235]<br>\n [0.96455108 0.50000836 0.88952006 0.34161365 0.56714413]<br>\n [0.42754596 0.43674726 0.77655918 0.53560417 0.95374223]]<br>\n[[0. 0. 0. 0. 0.]<br>\n [0. 0. 0. 0. 1.]<br>\n [0. 0. 0. 0. 0.]<br>\n [1. 0. 1. 0. 0.]<br>\n [0. 0. 0. 0. 0.]<br>\n [0. 1. 0. 0. 0.]<br>\n [0. 0. 0. 1. 0.]<br>\n [0. 0. 0. 0. 0.]<br>\n [0. 0. 0. 0. 0.]<br>\n [0. 0. 0. 0. 0.]]<br>\n0.8964600261334037", "_____no_output_____" ], [ "# Backpropagation\nLet's now get to the next step - backpropagation. Let's start with sigmoid_backward.\n\n### sigmoid-backward\nYou might remember that we had created **`sigmoid`** function that calculated the activation for forward propagation. Now, we need the activation backward, which helps in calculating **dZ** from **dH**. Notice that it takes input **dH** and **sigmoid_memory** as input. **sigmoid_memory** is the **Z** which we had calculated during forward propagation. You use _[np.exp()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html)_ here the following way.", "_____no_output_____" ] ], [ [ "def sigmoid_backward(dH, sigmoid_memory):\n \n # Implement the backpropagation of a sigmoid function\n # dH is gradient of the sigmoid activated activation of shape same as H or Z in the same layer \n # sigmoid_memory is the memory stored in the sigmoid(Z) calculation\n \n Z = sigmoid_memory\n \n H = 1/(1+np.exp(-Z))\n dZ = dH * H * (1-H)\n \n assert (dZ.shape == Z.shape)\n \n return dZ", "_____no_output_____" ] ], [ [ "### relu-backward\nYou might remember that we had created **`relu`** function that calculated the activation for forward propagation. Now, we need the activation backward, which helps in calculating **dZ** from **dH**. Notice that it takes input **dH** and **relu_memory** as input. **relu_memory** is the **Z** which we calculated uring forward propagation. ", "_____no_output_____" ] ], [ [ "def relu_backward(dH, relu_memory):\n \n # Implement the backpropagation of a relu function\n # dH is gradient of the relu activated activation of shape same as H or Z in the same layer \n # relu_memory is the memory stored in the sigmoid(Z) calculation\n \n Z = relu_memory\n dZ = np.array(dH, copy=True) # dZ will be the same as dA wherever the elements of A weren't 0\n \n dZ[Z <= 0] = 0\n \n assert (dZ.shape == Z.shape)\n \n return dZ", "_____no_output_____" ] ], [ [ "### layer_backward\n\n**`layer_backward`** is a complimentary function of **`layer_forward`**. Like **`layer_forward`** calculates **H** using **W**, **H_prev** and **b**, **`layer_backward`** uses **dH** to calculate **dW**, **dH_prev** and **db**. You have already studied the formulae in backpropogation. To calculate **dZ**, use the **`sigmoid_backward`** and **`relu_backward`** function. You might need to use _[np.dot()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html)_, _[np.sum()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html)_ for the rest. Remember to choose the axis correctly in db. ", "_____no_output_____" ] ], [ [ "#Graded\n\ndef layer_backward(dH, memory, activation = 'relu'):\n \n # takes dH and the memory calculated in layer_forward and activation as input to calculate the dH_prev, dW, db\n # performs the backprop depending upon the activation function\n \n\n linear_memory, activation_memory = memory\n \n if activation == \"relu\":\n dZ = relu_backward(dH, activation_memory)\n H_prev, W, b = linear_memory\n m = H_prev.shape[1]\n dW = (1./m) * np.dot(dZ, H_prev.transpose())\n db = (1./m) * np.sum(dZ, axis=1)\n dH_prev = np.dot(W.transpose(), dZ)\n \n elif activation == \"sigmoid\":\n dZ = sigmoid_backward(dH, activation_memory)\n H_prev, W, b = linear_memory\n m = H_prev.shape[1]\n dW = (1./m) * np.dot(dZ, H_prev.transpose())\n db = (1./m) * np.sum(dZ,axis=1)\n dH_prev = np.dot(W.transpose(), dZ)\n \n return dH_prev, dW, db", "_____no_output_____" ], [ "# verify\n# l-1 has two neurons, l has three, m = 5\n# H_prev is (l-1, m)\n# W is (l, l-1)\n# b is (l, 1)\n# H should be (l, m)\nH_prev = np.array([[1,0, 5, 10, 2], [2, 5, 3, 10, 2]])\nW_sample = np.array([[10, 5], [2, 0], [1, 0]])\nb_sample = np.array([10, 5, 0]).reshape((3, 1))\n\nH, memory = layer_forward(H_prev, W_sample, b_sample, activation=\"relu\")\nnp.random.seed(2)\ndH = np.random.rand(3,5)\ndH_prev, dW, db = layer_backward(dH, memory, activation = 'relu')\nprint('dH_prev is \\n' , dH_prev)\nprint('dW is \\n' ,dW)\nprint('db is \\n', db)", "dH_prev is \n [[5.6417525 0.66855959 6.86974666 5.46611139 4.92177244]\n [2.17997451 0.12963116 2.74831239 2.17661196 2.10183901]]\ndW is \n [[1.67565336 1.56891359]\n [1.39137819 1.4143854 ]\n [1.3597389 1.43013369]]\ndb is \n [0.37345476 0.34414727 0.29074635]\n" ] ], [ [ "You should get:<br>\ndH_prev is <br>\n [[5.6417525 0.66855959 6.86974666 5.46611139 4.92177244]<br>\n [2.17997451 0.12963116 2.74831239 2.17661196 2.10183901]]<br>\ndW is <br>\n [[1.67565336 1.56891359]<br>\n [1.39137819 1.4143854 ]<br>\n [1.3597389 1.43013369]]<br>\ndb is <br>\n [[0.37345476]<br>\n [0.34414727]<br>\n [0.29074635]]<br>\n", "_____no_output_____" ], [ "### L_layer_backward\n\n**`L_layer_backward`** performs backpropagation for the whole network. Recall that the backpropagation for the last layer, i.e. the softmax layer, is different from the rest, hence it is outside the reversed `for` loop. You need to use the function **`layer_backward`** here in the loop with the activation function as **`relu`**. ", "_____no_output_____" ] ], [ [ "#Graded\n\ndef L_layer_backward(HL, Y, memories):\n \n # Takes the predicted value HL and the true target value Y and the \n # memories calculated by L_layer_forward as input\n \n # returns the gradients calulated for all the layers as a dict\n\n gradients = {}\n L = len(memories) # the number of layers\n m = HL.shape[1]\n Y = Y.reshape(HL.shape) # after this line, Y is the same shape as AL\n \n # Perform the backprop for the last layer that is the softmax layer\n current_memory = memories[-1]\n linear_memory, activation_memory = current_memory\n dZ = HL - Y\n H_prev, W, b = linear_memory\n # Use the expressions you have used in 'layer_backward'\n gradients[\"dH\" + str(L-1)] = np.dot(W.transpose(), dZ)\n gradients[\"dW\" + str(L)] = (1./m) * np.dot(dZ, H_prev.transpose())\n gradients[\"db\" + str(L)] = (1./m) * np.sum(dZ,axis=1)\n \n # Perform the backpropagation l-1 times\n for l in reversed(range(L-1)):\n # Lth layer gradients: \"gradients[\"dH\" + str(l + 1)] \", gradients[\"dW\" + str(l + 2)] , gradients[\"db\" + str(l + 2)]\n current_memory = memories[l]\n \n dH_prev_temp, dW_temp, db_temp = layer_backward(gradients[\"dH\" + str(l + 1)], current_memory)\n gradients[\"dH\" + str(l)] = dH_prev_temp\n gradients[\"dW\" + str(l + 1)] = dW_temp\n gradients[\"db\" + str(l + 1)] = db_temp\n\n\n return gradients", "_____no_output_____" ], [ "# verify\n# X is (784, 10)\n# parameters is a dict\n# HL should be (10, 10)\nx_sample = train_set_x[:, 10:20]\ny_sample = train_set_y[:, 10:20]\n\nHL, memories = L_layer_forward(x_sample, parameters=parameters)\ngradients = L_layer_backward(HL, y_sample, memories)\nprint('dW3 is \\n', gradients['dW3'])\nprint('db3 is \\n', gradients['db3'])\nprint('dW2 is \\n', gradients['dW2'])\nprint('db2 is \\n', gradients['db2'])", "dW3 is \n [[ 0.02003701 0.0019043 0.01011729 0.0145757 0.00146444 0.00059863\n 0. ]\n [ 0.02154547 0.00203519 0.01085648 0.01567075 0.00156469 0.00060533\n 0. ]\n [-0.01718407 -0.00273711 -0.00499101 -0.00912135 -0.00207365 0.00059996\n 0. ]\n [-0.01141498 -0.00158622 -0.00607049 -0.00924709 -0.00119619 0.00060381\n 0. ]\n [ 0.01943173 0.0018421 0.00984543 0.01416368 0.00141676 0.00059682\n 0. ]\n [ 0.01045447 0.00063974 0.00637621 0.00863306 0.00050118 0.00060441\n 0. ]\n [-0.06338911 -0.00747251 -0.0242169 -0.03835708 -0.00581131 0.0006034\n 0. ]\n [ 0.01911373 0.001805 0.00703101 0.0120636 0.00138836 -0.00140535\n 0. ]\n [-0.01801603 0.0017357 -0.01489228 -0.02026076 0.00133528 0.00060264\n 0. ]\n [ 0.0194218 0.00183381 0.00594427 0.01187949 0.00141043 -0.00340965\n 0. ]]\ndb3 is \n [ 0.10031756 0.00460183 -0.00142942 -0.0997827 0.09872663 0.00536378\n -0.10124784 -0.00191121 -0.00359044 -0.00104818]\ndW2 is \n [[ 4.94428956e-05 1.13215514e-02 5.44180380e-02]\n [-4.81267081e-05 -2.96999448e-05 -1.81899582e-02]\n [ 5.63424333e-05 4.77190073e-03 4.04810232e-02]\n [ 1.49767478e-04 -1.89780927e-03 -7.91231369e-03]\n [ 1.97866094e-04 1.22107085e-04 2.64140566e-02]\n [ 0.00000000e+00 -3.75805770e-04 1.63906102e-05]\n [ 0.00000000e+00 0.00000000e+00 0.00000000e+00]]\ndb2 is \n [ 0.013979 -0.01329383 0.01275707 -0.01052957 0.03179224 -0.00039877\n 0. ]\n" ] ], [ [ "You should get:<br>\n\ndW3 is <br>\n [[ 0.02003701 0.0019043 0.01011729 0.0145757 0.00146444 0.00059863 0. ]<br>\n [ 0.02154547 0.00203519 0.01085648 0.01567075 0.00156469 0.00060533 0. ]<br>\n [-0.01718407 -0.00273711 -0.00499101 -0.00912135 -0.00207365 0.00059996 0. ]<br>\n [-0.01141498 -0.00158622 -0.00607049 -0.00924709 -0.00119619 0.00060381 0. ]<br>\n [ 0.01943173 0.0018421 0.00984543 0.01416368 0.00141676 0.00059682 0. ]<br>\n [ 0.01045447 0.00063974 0.00637621 0.00863306 0.00050118 0.00060441 0. ]<br>\n [-0.06338911 -0.00747251 -0.0242169 -0.03835708 -0.00581131 0.0006034 0. ]<br>\n [ 0.01911373 0.001805 0.00703101 0.0120636 0.00138836 -0.00140535 0. ]<br>\n [-0.01801603 0.0017357 -0.01489228 -0.02026076 0.00133528 0.00060264 0. ]<br>\n [ 0.0194218 0.00183381 0.00594427 0.01187949 0.00141043 -0.00340965 0. ]]<br>\ndb3 is <br>\n [[ 0.10031756]<br>\n [ 0.00460183]<br>\n [-0.00142942]<br>\n [-0.0997827 ]<br>\n [ 0.09872663]<br>\n [ 0.00536378]<br>\n [-0.10124784]<br>\n [-0.00191121]<br>\n [-0.00359044]<br>\n [-0.00104818]]<br>\ndW2 is <br>\n [[ 4.94428956e-05 1.13215514e-02 5.44180380e-02]<br>\n [-4.81267081e-05 -2.96999448e-05 -1.81899582e-02]<br>\n [ 5.63424333e-05 4.77190073e-03 4.04810232e-02]<br>\n [ 1.49767478e-04 -1.89780927e-03 -7.91231369e-03]<br>\n [ 1.97866094e-04 1.22107085e-04 2.64140566e-02]<br>\n [ 0.00000000e+00 -3.75805770e-04 1.63906102e-05]<br>\n [ 0.00000000e+00 0.00000000e+00 0.00000000e+00]]<br>\ndb2 is <br>\n [[ 0.013979 ]<br>\n [-0.01329383]<br>\n [ 0.01275707]<br>\n [-0.01052957]<br>\n [ 0.03179224]<br>\n [-0.00039877]<br>\n [ 0. ]]<br>", "_____no_output_____" ], [ "# Parameter Updates\n\nNow that we have calculated the gradients. let's do the last step which is updating the weights and biases.", "_____no_output_____" ] ], [ [ "#Graded\n\ndef update_parameters(parameters, gradients, learning_rate):\n\n # parameters is the python dictionary containing the parameters W and b for all the layers\n # gradients is the python dictionary containing your gradients, output of L_model_backward\n \n # returns updated weights after applying the gradient descent update\n\n \n L = len(parameters) // 2 # number of layers in the neural network\n\n for l in range(L):\n W_old = parameters[\"W\" + str(l+1)]\n dW = gradients['dW' + str(l+1)]\n W_delta = np.dot(-learning_rate, dW)\n W_new = np.add(W_old, W_delta)\n parameters[\"W\" + str(l+1)] = W_new\n\n b_old = parameters[\"b\" + str(l+1)]\n db = gradients['db' + str(l+1)]\n b_delta = np.dot(-learning_rate, db).reshape((len(db),1))\n b_new = np.add(b_old, b_delta)\n parameters[\"b\" + str(l+1)] = b_new\n \n return parameters", "_____no_output_____" ] ], [ [ "Having defined the bits and pieces of the feedforward and the backpropagation, let's now combine all that to form a model. The list `dimensions` has the number of neurons in each layer specified in it. For a neural network with 1 hidden layer with 45 neurons, you would specify the dimensions as follows:", "_____no_output_____" ] ], [ [ "dimensions = [784, 45, 10] # three-layer model", "_____no_output_____" ] ], [ [ "# Model\n\n### L_layer_model\n\nThis is a composite function which takes the training data as input **X**, ground truth label **Y**, the **dimensions** as stated above, **learning_rate**, the number of iterations **num_iterations** and if you want to print the loss, **print_loss**. You need to use the final functions we have written for feedforward, computing the loss, backpropagation and updating the parameters.", "_____no_output_____" ] ], [ [ "#Graded\n\ndef L_layer_model(X, Y, dimensions, learning_rate = 0.0075, num_iterations = 3000, print_loss=False):\n \n # X and Y are the input training datasets\n # learning_rate, num_iterations are gradient descent optimization parameters\n # returns updated parameters\n\n np.random.seed(2)\n losses = [] # keep track of loss\n \n # Parameters initialization\n parameters = initialize_parameters(dimensions)\n \n for i in range(0, num_iterations):\n\n # Forward propagation\n HL, memories = L_layer_forward(X, parameters)\n \n # Compute loss\n loss = compute_loss(HL, Y)\n \n # Backward propagation\n gradients = L_layer_backward(HL, Y, memories)\n \n # Update parameters.\n parameters = update_parameters(parameters, gradients, learning_rate)\n \n # Printing the loss every 100 training example\n if print_loss and i % 100 == 0:\n print (\"Loss after iteration %i: %f\" %(i, loss))\n losses.append(loss)\n \n # plotting the loss\n plt.plot(np.squeeze(losses))\n plt.ylabel('loss')\n plt.xlabel('iterations (per tens)')\n plt.title(\"Learning rate =\" + str(learning_rate))\n plt.show()\n \n return parameters", "_____no_output_____" ] ], [ [ "Since, it'll take a lot of time to train the model on 50,000 data points, we take a subset of 5,000 images.", "_____no_output_____" ] ], [ [ "train_set_x_new = train_set_x[:,0:5000]\ntrain_set_y_new = train_set_y[:,0:5000]\ntrain_set_x_new.shape", "_____no_output_____" ] ], [ [ "Now, let's call the function L_layer_model on the dataset we have created.This will take 10-20 mins to run.", "_____no_output_____" ] ], [ [ "parameters = L_layer_model(train_set_x_new, train_set_y_new, dimensions, num_iterations = 2000, print_loss = True)", "Loss after iteration 0: 2.422624\nLoss after iteration 100: 2.129232\nLoss after iteration 200: 1.876095\nLoss after iteration 300: 1.604213\nLoss after iteration 400: 1.350205\nLoss after iteration 500: 1.144823\nLoss after iteration 600: 0.990554\nLoss after iteration 700: 0.876603\nLoss after iteration 800: 0.791154\nLoss after iteration 900: 0.725441\nLoss after iteration 1000: 0.673485\nLoss after iteration 1100: 0.631386\nLoss after iteration 1200: 0.596598\nLoss after iteration 1300: 0.567342\nLoss after iteration 1400: 0.542346\nLoss after iteration 1500: 0.520746\nLoss after iteration 1600: 0.501865\nLoss after iteration 1700: 0.485205\nLoss after iteration 1800: 0.470368\nLoss after iteration 1900: 0.457054\n" ], [ "def predict(X, y, parameters):\n \n # Performs forward propogation using the trained parameters and calculates the accuracy\n \n m = X.shape[1]\n n = len(parameters) // 2 # number of layers in the neural network\n \n # Forward propagation\n probas, caches = L_layer_forward(X, parameters)\n \n p = np.argmax(probas, axis = 0)\n act = np.argmax(y, axis = 0)\n\n print(\"Accuracy: \" + str(np.sum((p == act)/m)))\n \n return p", "_____no_output_____" ] ], [ [ "Let's see the accuray we get on the training data.", "_____no_output_____" ] ], [ [ "pred_train = predict(train_set_x_new, train_set_y_new, parameters)", "Accuracy: 0.8774000000000002\n" ] ], [ [ "We get ~ 88% accuracy on the training data. Let's see the accuray on the test data.", "_____no_output_____" ] ], [ [ "pred_test = predict(test_set_x, test_set_y, parameters)", "Accuracy: 0.8674000000000002\n" ] ], [ [ "It is ~87%. You can train the model even longer and get better result. You can also try to change the network structure. \n<br>Below, you can see which all numbers are incorrectly identified by the neural network by changing the index.", "_____no_output_____" ] ], [ [ "index = 3474\nk = test_set_x[:,index]\nk = k.reshape((28, 28))\nplt.title('Label is {label}'.format(label=(pred_test[index], np.argmax(test_set_y, axis = 0)[index])))\nplt.imshow(k, cmap='gray')", "_____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" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec4ece84a1a3f011222459541a1ee3658682c665
95,454
ipynb
Jupyter Notebook
Hypothesis_Testing_And_Bayesian_Inference.ipynb
jzmnd/hypothesis-testing
d93f81640e414629072b694901e1c0158f877cd2
[ "MIT" ]
null
null
null
Hypothesis_Testing_And_Bayesian_Inference.ipynb
jzmnd/hypothesis-testing
d93f81640e414629072b694901e1c0158f877cd2
[ "MIT" ]
null
null
null
Hypothesis_Testing_And_Bayesian_Inference.ipynb
jzmnd/hypothesis-testing
d93f81640e414629072b694901e1c0158f877cd2
[ "MIT" ]
null
null
null
101.763326
24,790
0.809709
[ [ [ "%matplotlib inline", "_____no_output_____" ], [ "import matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nmatplotlib.rcParams['savefig.dpi'] = 144", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport itertools as it", "_____no_output_____" ] ], [ [ "# A Comparison of Classical Hypothesis Testing and Bayesian Inference", "_____no_output_____" ], [ "## Probability and Inference\n\nThere is an important distinction between the study of probability theory and statistical inference, although both rely on the same fundamental principles.\n\n**Probability Theory:**\n1. Given a known random process with a particular distribution, what are the outcomes from that process?\n1. Model $\\rightarrow$ Data\n\n**Statistical Inference:**\n1. Given a known dataset, what is the underlying process and its distribution?\n1. Data $\\rightarrow$ Model\n\nStatistical questions are generally what we will need to answer as data scientists. Although they can be thought of as the inverse of probability questions, they are in general ill-defined (i.e. our data will not always allow us to determine a unique model). However, we can make assumptions about the underlying probability model based on our knowledge of the problem and then use statistical tests to determine the \"correctness\" of our model.\n\nStatistical inference is characterized by the fact that:\n- Our dataset will typically be a *sample* taken from the *population* and we are trying to infer something about the population.\n- Data will have errors or noise associated with how it was collected\n\n*Frequentist (or Classical) Hypothesis testing* and *Bayesian Inference* are two examples of methods for statistical inference.", "_____no_output_____" ], [ "## Classical Hypothesis Testing\n\nA statistical hypothesis is one which is testable based on data from a process than is modeled by a set of random variables. \n\nWe are typically comparing two datasets, either:\n\n1. Two observed datasets (and testing their similarity)\n1. An observed dataset and a dataset generated from our proposed model (and again testing their similarity)\n\nThen the standard approach is to generate two hypotheses:\n\n1. **Alternative Hypothesis $H$:** The proposed relationship that we are investigating\n1. **Null Hypothesis $H_0$:** That there is no relationship of the form of our proposition between the two datasets", "_____no_output_____" ], [ "### $p$-values and determining significance\n\nWe want to determine whether we can reject the null hypotheses. To do this in the case of significance testing we follow these steps. *Note* that this is not the only way to do hypothesis testing and we can also use a Bayesian approach to testing.\n\n1. We then choose our *statistical test* and a suitable *significance level*, $\\alpha$.\n\n1. The *$p$-value* is defined as the probability, given that the null hypothesis is true, that the result of our statistical test is equal to or greater than the actual observed result.\n\n1. The relationship is then called *statistically significant* if the $p$-value is less than the significance level $(p \\leq \\alpha)$.\n\nMathematically we can write this in terms of the null hypothesis, $H_0$, a function of the observed data, the so-called test statistics, $X$, and a particular value $x$,\n\n$$p = P(X \\geq x \\mid H_0) \\:\\:\\text{(right tailed event)}$$\n$$p = P(X \\leq x \\mid H_0) \\:\\:\\text{(left tailed event)}$$", "_____no_output_____" ], [ "### Interpreting $p$-values\n\nWe must take care when assessing $p$-values and choosing our significance level. The probability of rejecting the null hypothesis given that the null hypothesis is in fact true is given by:\n\n$$P(\\text{reject } H_0 \\mid H_0) = P(p \\leq \\alpha \\mid H_0) = \\alpha$$\n\nThis would be a Type I Error or a False Positive.\n\nWe could also have a Type II Error or a False Negative, which would be the case of not rejecting the null hypothesis even though the alternative hypothesis is true. This would be given by:\n\n$$P(\\text{accept } H_0 \\mid H) = P(p \\geq \\alpha \\mid H) = \\beta$$\n\nThe **precision** and **recall** metrics that we defined before are also applicable in the case of hypothesis testing. Or we can use **sensitivity** and **specificity**, the difference being that precision and recall are independent of True Negative results and are therefore better suited to many machine learning problems with large datasets.\n\nUsing the definitions of True Positive (TP), True Negative (TN), False Positive (FP) and False Negative (FN) we can define the relationships between these metrics:\n\n$$\\text{precision} = \\frac{\\text{TP}}{\\text{TP} + \\text{FP}}$$\n\n$$\\text{recall} = \\frac{\\text{TP}}{\\text{TP} + \\text{FN}} = 1 - \\beta$$\n\n$$\\alpha = \\frac{\\text{FP}}{\\text{TN} + \\text{FP}} = 1 - \\text{specificity}$$\n\n$$\\beta = \\frac{\\text{FN}}{\\text{TP} + \\text{FN}} = 1 - \\text{sensitivity}$$", "_____no_output_____" ], [ "### Student's $t$-test\n\nThe $t$-test is a very common method for hypothesis testing. It is based on the $t$-distribution which arises from the sample estimate of the mean of a normally distributed population when the variance of the population is not known.\n\nThe $t$-test calculates a $t$ score, which in the case of comparing two means is given by:\n\n$$t = \\frac{\\bar{X_1} - \\bar{X_2}}{SE_{\\bar{X_1} - \\bar{X_2}}}$$\n\nWhere $SE$ is the standard error of the particular estimator we are using (the difference of the means in this case).\n\nFor equal sample size, $n$, and sample variances, $s^2$, this is:\n\n$$SE_{\\bar{X_1} - \\bar{X_2}} = \\sqrt{\\frac{s_{X_1}^2 + s_{X_2}^2}{n}}$$\n\nOur $t$ score follows the $t$-distribution, however, usually we want to convert this to a probability ($p$-value) by calculating the critical area under the probability density function.\n\n*Note:* the same method can be applied to other statistical tests e.g. $\\chi^2$-score, $F$-score, $z$-score etc.", "_____no_output_____" ] ], [ [ "from scipy.stats import t\n\ntscore = 2\ndegrees_freedom = 10\npval = t.sf(np.abs(tscore), degrees_freedom)*2\n\nx = np.linspace(-4, 4)\nxf = np.linspace(tscore, 4)\nplt.plot(x, t.pdf(x, degrees_freedom))\nplt.axvline(x=tscore, ls='--')\nplt.axvline(x=-tscore, ls='--')\nplt.fill_between(xf, t.pdf(xf, degrees_freedom), color='orange', alpha=0.5)\nplt.fill_between(-xf, t.pdf(xf, degrees_freedom), color='orange', alpha=0.5)\nplt.axis([-4, 4, 0, 0.4])\nplt.title(\"Student's t-distributionn\\n(p-value = {:.4f} for t = {}, two-tailed, df = {})\" \\\n .format(pval, tscore, degrees_freedom));", "_____no_output_____" ] ], [ [ "We can go through a simple example here using the Iris Plants Dataset and determining whether there is a statistically significant difference between the sepal widths of the different species. `scipy.stats` provides functions for various statistical tests including a $t$-test and calculates both $t$ scores and $p$-values for us.", "_____no_output_____" ] ], [ [ "from scipy.stats import ttest_ind\n\n# Load data\niris = sns.load_dataset('iris')\nspecies = ['setosa', 'versicolor', 'virginica']\nfeature = 'sepal_width'\n\n# Select only N samples from each species\nN = 20\nslist = []\nfor s in species:\n slist.append(iris[iris['species'] == s].sample(N, random_state=42))\niris_sample = pd.concat(slist)\n\n# Plot histograms of the petal lengths\niris_sample.hist(column=feature, by='species', bins=6,\n sharex=True, figsize=(6, 9), layout=(3, 1), alpha=0.5);", "_____no_output_____" ], [ "# Group by species and show stats\nstats = iris_sample.groupby('species')[feature].describe()\nstats", "_____no_output_____" ], [ "# Calculate t scores between different species\nsig_level = 0.05\n\ns_dict = {}\nfor s in species:\n s_dict[s] = iris_sample[iris_sample['species'] == s][feature]\n\nstat_df = []\nfor i in it.combinations(species, 2):\n t, p = ttest_ind(s_dict[i[0]], s_dict[i[1]], equal_var=False)\n stat_df.append([i[0], i[1], t, p, p < sig_level])\n\npd.DataFrame(stat_df, columns=['species A',\n 'species B',\n 't-score', 'p-value', 'p < 0.05'.format(sig_level)])", "_____no_output_____" ] ], [ [ "We can reject the null hypothesis in the first two cases but not for the last pair.\n\nWhat happens if we adjust the number of samples $N$ or our significance level?", "_____no_output_____" ], [ "### Assumptions for $t$-tests\n\n- Our samples are randomly generated from the population\n- Samples are normally distributed\n- Sample size is of reasonably large\n- Means are independent of variance (homoscedastic)", "_____no_output_____" ], [ "## Bayesian Inference", "_____no_output_____" ], [ "### Bayesian statistics vs Frequentist statistics\n\nThere are two philosophical approaches to how we think about probability and statistics.\n\nExample: roll a 6-sided die, what is the probability it will be a 6? And is the die fair?\n\n**Frequentist:** \"I will roll the die many times and find the frequency of 6 occurring, this gives my probability\"\n\n**Bayesian:** \"I will make an prior assumption that it is likely to be 1/6, I will then update my assumption as I collect more data, my probability is a measure of belief in a proposition\"\n\n\n| | Frequentist | Bayesian |\n|--------------------|:----------------------------------------------|:------------------------------------------|\n| *Probability* | Arises from the limiting frequency of event | Plausibility of a proposition |\n| *Model Parameters* | Fixed based on the model | Unknown and described probabilistically |\n| *Data* | Taken from repeatable random sampling | Fixed and observed from realized sample |\n| *Prior* | No prior information on parameters | Include prior parameter information |\n| *Inference* | Deduction from $P(X \\mid H_0)$ | Induction from $P(\\theta \\mid X)$ using $P(\\theta)$ |", "_____no_output_____" ], [ "### Why Bayes in data science?\n\n*Bayesian inference* therefore uses probabilities for both hypotheses and data whereas *Frequentist inference* does not allows us to calculate the probability of a hypothesis being correct.\n\nFrequentist inference, and classical hypothesis testing using $p$-values as described above, has been the predominant method in the sciences during the 20th century. However, with the ability to deal with large datasets, machine learning, and more powerful computational methods, Bayesian methods are becoming more popular.\n\n\nBayesian inference is very useful in data science for the following reasons:\n\n1. Even if our dataset is (relatively) small we can use prior information related to our problem e.g. evaluating a new advertising strategy with information about old strategies.\n1. If we have a very high variance model, we can use priors as a way to regularize the model e.g. in NLP and sentiment analysis.\n1. We may need an estimate of the likelihood of a particular model parameter especially when dealing with a large number of features.", "_____no_output_____" ], [ "### Bayes' theorem\n\nBayes' theorem describes the probability of an event based on prior knowledge of conditions that might be related to the event. Given two events $A$ and $B$, we can write that:\n\n$$P(A \\mid B) = \\frac{P(B \\mid A)\\; P(A)}{P(B)}$$\n\nIn the general case where $A$ is separable into parts, $\\{A_i\\}$, we can write:\n\n$$P(A_i \\mid B) = \\frac{P(B \\mid A_i)\\; P(A_i)}{P(B)} = \\frac{P(B \\mid A_i)\\; P(A_i)}{\\sum_{j}{P(B \\mid A_j)\\; P(A_j)}}$$\n\nAnd therefore we can also write a version for continuous random variables and probability distribution functions, $p$. \n\nAs applied to inference, we are interested in testing a model with parameters, $\\theta$, given a set of observed data points, $X$, and hyperparameters, $\\alpha$.\n\n$$p(\\theta \\mid X,\\alpha) = \\frac{p(X \\mid \\theta)\\; p(\\theta \\mid \\alpha)}{\\int{p(X \\mid \\theta^\\prime)\\; p(\\theta^\\prime \\mid \\alpha)\\; \\text{d}\\theta^\\prime}}$$", "_____no_output_____" ], [ "### Definitions\n\n- **Prior Distribution:** The probability of particular parameters without considering any data, $p(\\theta \\mid \\alpha)$\n- **Posterior Distribution:** The probability of particular parameters given the data, $p(\\theta \\mid X,\\alpha)$\n- **Likelihood:** The distribution of data conditional on its parameters, $p(X \\mid \\theta)$\n- **Marginal Likelihood:** The distribution of the observed data marginalized over the parameters, also called the evidence, $p(X \\mid \\alpha)$, and is the denominator in the above expression\n\nIn other words the posterior distribution is the likelihood multiplied by the prior and correctly normalized.", "_____no_output_____" ], [ "### Conjugate priors\n\nGenerally our likelihood distribution will be well-defined by how we collected our data. However, we can then choose any prior distribution that we want depending on our knowledge of the situation.\n\nThis means that the integral of $p(X \\mid \\theta^\\prime) p(\\theta^\\prime \\mid \\alpha)$ can very easily become impossible to compute analytically and would require numerical methods. This is one of the major reasons that Bayesian inference was not widely adopted before the advent of the computer.\n\nHowever, for certain choices of prior, called **conjugate priors**, and associated likelihood functions there exist closed-form solutions for the posterior distribution, thus simplifying the algebra that we need to do.\n\nHere are some common families of distributions and their conjugate priors:\n\n| Likelihood function | Conjugate Prior (and therefore Posterior) |\n|-----------------------------|:----------------------------------------------|\n| Normal (known $\\sigma^2$) | Normal |\n| Normal (known $\\mu$) | Gamma |\n| Exponential | Gamma |\n| Bernoulli | Beta |\n| Binomial | Beta |\n| Poisson | Gamma |", "_____no_output_____" ], [ "Here is a simple example using data that is a count of the number of successes, $x$, from 6 attempts at a particular event. We expect this to follow a binomial distribution with $n = 6$ therefore we can use:\n\n- **Likelihood:** $\\text{binomial}(n,p) \\propto p^x (1-p)^{n-x}$\n- **Conjugate prior:** $\\text{beta}(\\alpha, \\beta) \\propto p^{\\alpha-1} (1-p)^{\\beta-1}$\n\nSince we can just obtain the form of the posterior by multiplying these terms we get:\n\n$$\\text{posterior} \\propto p^x (1-p)^{n-x} p^{\\alpha-1} (1-p)^{\\beta-1} \\\\ = p^{x+\\alpha-1} (1-p)^{n-x+\\beta-1}$$\n", "_____no_output_____" ] ], [ [ "from scipy.stats import binom\nfrom scipy.stats import beta\n\ndata = np.array([2, 4, 3, 3, 1, 4, 1, 4, 3, 3, 0, 5, 4, 1, 1, 1, 2, 2, 2, 2,\n 2, 2, 3, 1, 2, 3, 0, 3, 1, 1, 4, 5, 3, 2, 1, 3, 2, 1, 2, 0])\n\nn = 6\ntrials = len(data) * n\nxm = data.mean()\nxsuccess = data.sum()\nsns.distplot(data, bins=6, kde=False, label='Data')\nplt.axvline(x=xm, ls='--')\nplt.title(\"Probability of success (uniform prior) = {:.4f}\".format(xm / n))\nplt.xlabel(\"Number of successes \");", "_____no_output_____" ] ], [ [ "But what if we want to include a prior?\n\nWe can choose our beta function depending on information we already have about our problem, for example, let's say that we had performed this experiment several times before and typically obtained a success rate of 5/6. Is our current batch abnormally low? Can we update our prior to give a more realistic estimate of the posterior?", "_____no_output_____" ] ], [ [ "from ipywidgets import *\n\n# Previous success rate\np = 5. / n\n\ndef update(prev_trials=100):\n\n # Conjugate Prior\n a = p * prev_trials\n b = (1 - p) * prev_trials\n prior = beta(a, b)\n\n # Calculate Posterior\n posterior = beta(xsuccess + a, trials - xsuccess + b)\n\n x = np.arange(0, 1.0, 0.001)\n sns.distplot(data / float(n), bins=6, kde=False, label='Data')\n plt.axvline(x=xm / n, ls='--')\n plt.plot(x, prior.pdf(x), label='Prior')\n plt.plot(x, posterior.pdf(x), label='Posterior')\n plt.axvline(x=posterior.mean(), c='g', ls='--')\n plt.legend()\n plt.xlabel(\"Probability of success\")\n plt.axis([0, 1, 0, 15])\n plt.show()\n return", "_____no_output_____" ], [ "widgets.interact(update, prev_trials=[0, 5, 10, 100, 1000]);", "_____no_output_____" ] ], [ [ "### Posterior sampling\n\nIf it is the case that we *cannot* find a suitable conjugate prior then we can instead use *posterior sampling*. Often we do not need the full form of the posterior distribution but only summary statistics about it, for example its mean and variance. Therefore, if we can *exactly sample* from the posterior distribution we can estimate these quantities without resorting to complex numerical integration.\n\nA common way to perform this sampling is by using *Monte Carlo Markov Chain* (MCMC) methods such as *Gibbs Sampling*. In MCMC we generate a Markov chain in such as way that the stationary state of the system produces samples with a distribution equal to the distribution we are interested in.\n\nWe can use the `pymc3` package to do MCMC sampling. Let's apply it to the previous dataset assuming that we do not know about conjugate priors and therefore cannot calculate the posterior directly.", "_____no_output_____" ] ], [ [ "import pymc3 as pm\n\n# Previous success rate and trials\np = 5. / n\nprev_trials = 100\n\n# Conjugate Prior\na = p * prev_trials\nb = (1 - p) * prev_trials\nprior = beta(a, b)\n\n# Create a statistical model\nwith pm.Model() as model:\n\n # Generate prior as before\n pr = pm.Beta('p', alpha=a, beta=b)\n\n # Likelihood function with our observed dataset with the correct prior\n y = pm.Binomial('y', n=n, p=pr, observed=data)\n\n # Use MAP estimate (optimization) as the initial state for the MCMC\n start = pm.find_MAP()\n\n # Choose sampler (Metropolis) and run\n step = pm.Metropolis()\n trace = pm.sample(5000, step, start=start,\n random_seed=42, progressbar=True)", "Optimization terminated successfully.\n Current function value: 98.398943\n Iterations: 5\n Function evaluations: 6\n Gradient evaluations: 6\n" ], [ "x = np.arange(0, 1.0, 0.001)\nsns.distplot(data / float(n), bins=6, kde=False, label='Data')\nplt.axvline(x=xm / n, ls='--')\n\nplt.plot(x, prior.pdf(x), label='Prior')\nsns.distplot(trace['p'], bins=20, norm_hist=True, kde=False, label='Posterior')\nplt.axvline(x=np.mean(trace['p']), c='g', ls='--')\nplt.legend()\nplt.xlabel(\"Probability of success\")\nplt.axis([0, 1, 0, 15]);", "_____no_output_____" ], [ "# Summary\nprint \"Success rate based only on our data (MLE) : {:.1f} %\".format(100 * xm / n)\nprint \"Prior sucess rate : {:.1f} %\".format(100 * p)\nprint \"Maximum a posteriori (MAP) success rate : {:.1f} %\".format(100 * np.mean(trace['p']))", "Success rate based only on our data (MLE) : 37.1 %\nPrior sucess rate : 83.3 %\nMaximum a posteriori (MAP) success rate : 50.7 %\n" ] ], [ [ "As expected we get the same result but now our posterior distribution is a sample of 5000 rather than the analytic form derived above, but this approach allows us to use any prior we want (not just conjugate priors). ", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
ec4ee4597581d65e139f5ec8c669dc13c624307f
20,591
ipynb
Jupyter Notebook
baxter/notebooks/Lab1Part2.ipynb
woudie/undergrad-labs
acee18f09190f45c6a6433ecf9de8e3eb167ffd7
[ "Apache-2.0" ]
null
null
null
baxter/notebooks/Lab1Part2.ipynb
woudie/undergrad-labs
acee18f09190f45c6a6433ecf9de8e3eb167ffd7
[ "Apache-2.0" ]
null
null
null
baxter/notebooks/Lab1Part2.ipynb
woudie/undergrad-labs
acee18f09190f45c6a6433ecf9de8e3eb167ffd7
[ "Apache-2.0" ]
null
null
null
39.44636
1,610
0.477053
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec4f026ae1b4ee1b017390ac4d63b9a9a191be10
80,988
ipynb
Jupyter Notebook
speech processing/4 - Lowpass and Highpass Filters.ipynb
livinNector/image-and-speech-processing-lab
0e03a232ee05261a346f92e89b54c9678d7e0e83
[ "MIT" ]
null
null
null
speech processing/4 - Lowpass and Highpass Filters.ipynb
livinNector/image-and-speech-processing-lab
0e03a232ee05261a346f92e89b54c9678d7e0e83
[ "MIT" ]
null
null
null
speech processing/4 - Lowpass and Highpass Filters.ipynb
livinNector/image-and-speech-processing-lab
0e03a232ee05261a346f92e89b54c9678d7e0e83
[ "MIT" ]
null
null
null
653.129032
46,436
0.949042
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nimport librosa", "_____no_output_____" ], [ "sr = 8000\nfiles = [\"auds/set2.wav\",\"auds/speech.wav\"]\nd = [librosa.load(file,sr)[0] for file in files]", "_____no_output_____" ], [ "fig,ax = plt.subplots(1,2,figsize=(15,2))\nfor i,di in enumerate(d):\n t=np.linspace(0,len(di)/sr,len(di))\n ax[i].plot(t,di, lw=1)\n ax[i].set_xlabel('Time(s)')\n ax[i].set_ylabel('Amplitude')\n ax[i].set_title('Original speech file')\n ax[i].grid(True)\nplt.show()", "_____no_output_____" ], [ "b, a = signal.butter(4, 2000. / (sr / 2.), 'high')\nd_high = signal.filtfilt(b, a, d[0])\n\nb, a = signal.butter(4, 500. / (sr / 2.), 'low')\nd_low = signal.filtfilt(b, a, d[1])\n\nfig, ax = plt.subplots(1, 2, figsize=(10, 3),tight_layout=True)\nfor i, (original,filtered) in enumerate(zip(d,[d_high,d_low])):\n t = np.linspace(0., len(original) / sr, len(original))\n ax[i].plot(t, original, lw=1,label=\"Original Signal\")\n ax[i].plot(t, filtered, lw=1,label=\"Filtered Signal\")\n ax[i].set_xlabel('Time(s)')\n ax[i].set_ylabel('Amplitude')\n ax[i].grid(True)\n ax[i].legend(loc=1)\n\nax[0].set_title('High pass filter')\nax[1].set_title('Low pass filter')\n\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
ec4f02ac11b3129492a0ac0e64e75cdfb51f9196
21,529
ipynb
Jupyter Notebook
25_insights.ipynb
puzzler10/travis_attack
14f9d4c467ee160f829c46ca568eade90a528d8a
[ "Apache-2.0" ]
1
2022-02-18T05:13:00.000Z
2022-02-18T05:13:00.000Z
25_insights.ipynb
puzzler10/travis_attack
14f9d4c467ee160f829c46ca568eade90a528d8a
[ "Apache-2.0" ]
null
null
null
25_insights.ipynb
puzzler10/travis_attack
14f9d4c467ee160f829c46ca568eade90a528d8a
[ "Apache-2.0" ]
null
null
null
40.091248
153
0.558317
[ [ [ "# default_exp insights", "_____no_output_____" ] ], [ [ "# Post-experiment insights ", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2\n%load_ext line_profiler", "_____no_output_____" ], [ "#export\nimport torch, wandb, spacy, textstat, psutil, pandas as pd, numpy as np, matplotlib.pyplot as plt, editdistance, plotly.express as px\nimport functools, operator, string, seaborn as sns\nfrom datasets import Dataset, load_dataset, load_metric\nfrom difflib import ndiff\nfrom IPython.display import Markdown, display\nfrom lexicalrichness import LexicalRichness\nfrom spacy_wordnet.wordnet_annotator import WordnetAnnotator\nfrom collections import defaultdict\nfrom itertools import groupby\nfrom IPython.core.debugger import set_trace\nfrom travis_attack.utils import display_all, resume_wandb_run, merge_dicts\nfrom fastcore.basics import patch_to\n\nimport logging \nlogger = logging.getLogger(\"travis_attack.insights\")", "_____no_output_____" ], [ "#hide \n", "_____no_output_____" ], [ "#export\nnlp = spacy.load(\"en_core_web_sm\")\n#run = resume_wandb_run(cfg)", "_____no_output_____" ] ], [ [ "## Compute and add metrics to dataframe", "_____no_output_____" ] ], [ [ "#export\ndef get_training_dfs(path_run, postprocessed=False): \n \"\"\"Return a dict of dataframes with all training and eval data\"\"\"\n df_d = dict()\n for key in ['training_step', 'train', 'valid', 'test']:\n try: \n if postprocessed: \n fname = f\"{path_run}{key}_postprocessed.pkl\" \n df_d[key] = pd.read_pickle(fname)\n else:\n fname = f\"{path_run}{key}.csv\"\n df_d[key] = pd.read_csv(fname)\n except FileNotFoundError: \n pass\n logger.info(f'Dataframes have shapes {[f\"{k}: {df.shape}\" for (k, df) in df_d.items()]}')\n return df_d \n\ndef postprocess_df(df, filter_idx=None, num_proc=min(8, psutil.cpu_count())): \n \"\"\"set df to one of training_step, train, valid, test\n filter_idx - for testing (remove later) \"\"\"\n # num_proc=8 seems pretty good - diminishing returns and we may as well leave some CPU for others \n df = df.sort_values(by=['idx', \"epoch\"], axis=0)\n if filter_idx is not None: df = df.query(\"idx <= @filter_idx\") # for testing purposes\n # Getting weird behaviour with group_by's so binning some of the numeric values\n for col in ['sts_score','vm_score','reward', 'pp_truelabel_probs']: df.loc[:, col] = df.loc[:, col].round(5)\n # Add metrics\n df = _add_number_of_unique_pps_per_idx(df)\n df = _add_number_of_pp_changes_per_idx(df)\n df = _add_epoch_of_first_label_flip( df)\n df = _add_text_metrics(df, num_proc=num_proc)\n return df\n\ndef _add_number_of_unique_pps_per_idx(df): \n df_grp = df.groupby(\"idx\").agg({\"pp_l\":\"nunique\"})\n df_grp= df_grp.rename(columns = {\"pp_l\":\"idx_n_unique_pp\"})\n df = df.merge(df_grp, left_on='idx', right_index=True, how='left')\n return df\n\ndef _add_number_of_pp_changes_per_idx(df): \n df['pp_changed'] = df.sort_values([\"idx\",\"epoch\"]).groupby('idx')['pp_l'].shift().ne(df['pp_l']).astype(int)\n df_grp = df.groupby('idx').agg({'pp_changed': 'sum'})\n df_grp= df_grp.rename(columns = {\"pp_changed\":\"idx_n_pp_changes\"})\n df_grp['idx_n_pp_changes'] -= 1 # The first paraphrase isn't a change\n df = df.drop('pp_changed', 1) # don't need this anymore\n df = df.merge(df_grp, left_on='idx', right_index=True, how='left')\n return df \n\ndef _add_epoch_of_first_label_flip(df): \n rownum_of_first_flip = df.groupby('idx')[['epoch','label_flip']].idxmax()['label_flip'] ## works since idxmax returns first max\n df_grp = df[['idx','epoch']].loc[rownum_of_first_flip]\n df_grp= df_grp.rename(columns = {\"epoch\":\"epoch_of_first_label_flip\"})\n df = df.merge(df_grp, left_on='idx', right_on='idx', how='left')\n return df\n\ndef _add_text_metrics(df, num_proc=min(8, psutil.cpu_count())):\n df = _add_text_metrics_for_column(df, \"orig_l\", suffix=\"orig\", num_proc=num_proc)\n df = _add_text_metrics_for_column(df, \"pp_l\", suffix=\"pp\", num_proc=num_proc)\n logger.info(\"Calculating metric differences between orig and pp\")\n for k in _get_text_metrics(\"some arbritary text here\").keys(): df[f\"{k}_diff\"] = df[f\"{k}_orig\"] - df[f\"{k}_pp\"]\n df = _add_text_pair_metrics(df, num_proc=num_proc) \n return df ", "_____no_output_____" ] ], [ [ "### Individual column metrics ", "_____no_output_____" ] ], [ [ "#export\ndef _add_text_metrics_for_column(df, cname, suffix, num_proc): \n logger.info(f\"Adding text metrics for column {cname}\")\n ds_cname = Dataset.from_pandas(df[cname].drop_duplicates().to_frame())\n ds_cname = _get_text_metrics_for_ds(ds_cname, cname=cname, suffix=suffix, num_proc=num_proc) \n df = pd.merge(df, pd.DataFrame(ds_cname), how='left', on=[cname])\n return df\n\ndef _get_text_metrics_for_ds(ds, cname, suffix, num_proc):\n x = ds.map(_get_text_metrics, input_columns = [cname], batched=False, num_proc=num_proc)\n colnames_mapping = dict()\n for k in x.column_names: colnames_mapping[k] = k + f\"_{suffix}\" if k != cname else k # rename columns\n return x.rename_columns(colnames_mapping)\n\ndef _get_text_metrics(text): \n d = defaultdict(lambda: 0)\n d['n_words'] = LexicalRichness(text).words\n d['n_sentences'] = textstat.sentence_count(text)\n def get_chartype_count(text, strset): return len(list(filter(functools.partial(operator.contains, strset), text))) \n d['n_punctuation'] = get_chartype_count(text, strset=string.punctuation)\n d['n_digits'] = get_chartype_count(text, strset=string.digits)\n d['n_letters'] = get_chartype_count(text, strset=string.ascii_letters)\n return d", "_____no_output_____" ] ], [ [ "### Text pair metrics ", "_____no_output_____" ] ], [ [ "#export\ndef _add_text_pair_metrics(df, num_proc): \n logger.info(\"Calculating text pair statistics for (orig, pp) unique pairs\")\n ds_pairs = Dataset.from_pandas(df[['orig_l','pp_l']].drop_duplicates())\n ds_pairs = _get_text_pair_metrics_for_ds(ds_pairs, num_proc=num_proc)\n df = pd.merge(df, pd.DataFrame(ds_pairs), how='left', on=['orig_l', 'pp_l'])\n return df\n\ndef _get_text_pair_metrics_for_ds(ds, num_proc): \n return ds.map(_get_text_pair_metrics, input_columns = [\"orig_l\", \"pp_l\"], batched=False, num_proc=num_proc)\n\ndef _get_text_pair_metrics(orig, pp):\n d = _get_removals_insertions_unchanged_phrases(orig, pp)\n d['edit_distance_token_level'] = _get_token_level_edit_distance(orig, pp)\n return d\n\ndef _get_removals_insertions_unchanged_phrases(orig, pp): \n orig_t,pp_t = [tkn.text for tkn in nlp(orig)],[tkn.text for tkn in nlp(pp)]\n diff = [x for x in ndiff(orig_t, pp_t)]\n ins_idx,ins_tkns,ins_tkn_grps,ins_phrases = _get_subsequences(diff, \"insertions\")\n rem_idx,rem_tkns,rem_tkn_grps,rem_phrases = _get_subsequences(diff, \"removals\")\n unc_idx,unc_tkns,unc_tkn_grps,unc_phrases = _get_subsequences(diff, \"unchanged\")\n return {'removals_idx': rem_idx, \n 'removals': rem_phrases,\n 'insertions_idx': ins_idx,\n 'insertions': ins_phrases, \n 'unchanged_idx': unc_idx,\n 'unchanged': unc_phrases, \n 'n_segments_inserted': len(ins_tkn_grps),\n 'n_segments_removed': len(rem_tkn_grps),\n 'n_tokens_inserted': len(ins_tkns), \n 'n_tokens_removed': len(rem_tkns),\n 'is_truncation': _is_truncation(rem_idx, unc_idx),\n 'any_phrase_capitalised': _any_phrase_capitalised(rem_phrases, ins_phrases),\n 'any_phrase_decapitalised': _any_phrase_capitalised(ins_phrases, rem_phrases)}\n \n \ndef _join_punctuation(seq, characters=set(string.punctuation)):\n \"Generator to join tokens respecting punctuation, but doesn't work that well.\"\n seq = iter(seq)\n current = next(seq)\n for nxt in seq:\n if nxt in characters:\n current += nxt\n else:\n yield current\n current = nxt\n yield current\n\ndef _get_subsequences(diff, sign): \n op = {\"insertions\": \"+\", \"removals\": \"-\", \"unchanged\": \" \"}[sign]\n idx,tokens = [],[]\n for i, o in enumerate(diff): \n if o[0] == op: idx.append(i); tokens.append(o[2:]) \n ## Group tokens that go together \n token_groups = []\n # bit of a mystery this bit but seems to work. just need 1-1 mapping between data and tokens \n for k, g in groupby(zip(enumerate(idx), tokens), lambda ix: ix[0][0] - ix[0][1]):\n token_groups.append(list(map(operator.itemgetter(1), g)))\n phrases = [' '.join(_join_punctuation(l)) for l in token_groups]\n return idx, tokens, token_groups, phrases\n\ndef _is_truncation(rem_idx, unc_idx):\n \"\"\"determines if a given phrase is trunctated or not. unc_idx = unchanged_idx, rem_idx = removals_idx \"\"\"\n if len(rem_idx) == 0 or len(unc_idx) == 0: return False \n if max(unc_idx) < max(rem_idx): return True \n else: return False\n\ndef _any_phrase_capitalised(lower_case_phrases, upper_case_phrases): \n \"\"\"tests if any of the phrases in lower_case_phrases, when capitalised, are present in upper_case_phrases\"\"\"\n for lc_p in lower_case_phrases: \n for uc_p in upper_case_phrases: \n if lc_p.capitalize() == uc_p: return True \n return False \n\ndef _get_token_level_edit_distance(s1, s2): \n l1,l2 = [o.text for o in nlp(s1)],[o.text for o in nlp(s2)]\n return editdistance.eval(l1,l2)", "_____no_output_____" ] ], [ [ "We can test some of these functions", "_____no_output_____" ] ], [ [ "def test_any_phrase_capitalised():\n ins1 = ['A']\n rem1 = ['a']\n ins2 = ['a', \"the duck is nice\"]\n rem2= ['A']\n ins3 = ['a']\n rem3 = ['look at that', 'A']\n for ins, rem in zip([ins1,ins2,ins3], [rem1,rem2,rem3]):\n print(\"Insertions\", ins)\n print(\"Removals\", rem)\n print(\"Any phrase decapitalised:\", _any_phrase_capitalised(ins, rem))\n print(\"Any phrase capitalised:\", _any_phrase_capitalised(rem, ins))\n print(\"\")\ntest_any_phrase_capitalised() \n ", "Insertions ['A']\nRemovals ['a']\nAny phrase decapitalised: False\nAny phrase capitalised: True\n\nInsertions ['a', 'the duck is nice']\nRemovals ['A']\nAny phrase decapitalised: True\nAny phrase capitalised: False\n\nInsertions ['a']\nRemovals ['look at that', 'A']\nAny phrase decapitalised: True\nAny phrase capitalised: False\n\n" ], [ "def test_get_token_level_edit_distance(): \n s1 = \"hello i am tom\"\n s2 = \"hello i am mike\"\n s3 = \"hello i'm tom \"\n s4 = \"hello my name is tom\"\n s5 = \"hello, i am tom\"\n s6 = \"hello i tom\"\n s7 = \"I am tom, don't forget it\"\n print(\"######\", s1, \"######\")\n for s in [s2,s3,s4,s5,s6,s7]:\n print(s)\n print (\"Edit distance:\", _get_token_level_edit_distance(s1, s)) \ntest_get_token_level_edit_distance() ", "###### hello i am tom ######\nhello i am mike\nEdit distance: 1\nhello i'm tom \nEdit distance: 1\nhello my name is tom\nEdit distance: 3\nhello, i am tom\nEdit distance: 1\nhello i tom\nEdit distance: 1\nI am tom, don't forget it\nEdit distance: 7\n" ] ], [ [ "## Wandb plots", "_____no_output_____" ] ], [ [ "#export \ndef create_and_log_wandb_postrun_plots(df_d): \n df_concat = _prepare_df_concat(df_d)\n wandb_plot_d = _prepare_wandb_postrun_plots(df_concat)\n wandb.log(wandb_plot_d)\n\ndef _prepare_df_concat(df_d):\n for k,df in df_d.items(): \n if k == \"training_step\": df_d[k]['data_split'] = k \n else: df_d[k]['data_split'] = f\"eval_{k}\" \n df_concat = pd.concat(df_d.values()).reset_index(drop=True)\n df_concat.loc[df_concat.epoch_of_first_label_flip == 0, 'epoch_of_first_label_flip'] = None # stop wrong spike at 0\n return df_concat\n\ndef _prepare_wandb_postrun_plots(df_concat):\n fig_l = []\n hist_config_dicts = [\n {\n 'cname': 'epoch_of_first_label_flip', \n 'xlabel': \"Epoch of first label flip\", \n 'desc': \"Cumulative prob epoch of first label flip for each original example\",\n 'cumulative': True,\n },\n {\n 'cname': 'idx_n_unique_pp', \n 'xlabel': \"Unique paraphrases per original example\", \n \"desc\": \"Number of generated unique paraphrases per original example during training\", \n 'cumulative': False,\n },\n {\n 'cname': 'idx_n_pp_changes', \n 'xlabel': \"Paraphrase changes per original example\", \n \"desc\": \"Number of paraphrase changes per original example during training\", \n 'cumulative': False,\n }]\n for d in hist_config_dicts: fig_l.append({f\"pp_metrics/{d['cname']}\": _plot_idx_hist(df_concat, d['cname'],d['xlabel'],d['cumulative'])})\n line_cnames = [o for o in df_concat.columns if \"_diff\" in o] + \\\n [\"is_truncation\", 'any_phrase_capitalised', 'any_phrase_decapitalised', 'n_segments_inserted', \n 'n_segments_removed', 'n_tokens_inserted', 'n_tokens_removed','edit_distance_token_level']\n for cname in line_cnames: fig_l.append({f\"pp_metrics/{cname}\": _plot_epoch_line_charts(df_concat, cname)})\n return {k:v for d in fig_l for k,v in d.items()}\n\ndef _plot_idx_hist(df_concat, cname, xlabel, cumulative=False): \n df1 = df_concat[['data_split','idx', cname]].drop_duplicates()\n fig = px.histogram(df1, x=cname, color='data_split', marginal=\"box\",\n labels={cname: xlabel},cumulative=cumulative, barmode='group', \n histnorm='probability', color_discrete_sequence=px.colors.qualitative.Dark24)\n fig.update_layout(showlegend=False)\n fig.update_layout(font_size=8)\n fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))\n fig.update_layout(autosize=True)\n return fig \n\ndef _plot_epoch_line_charts(df_concat, cname): \n df1 = df_concat[['data_split','epoch', cname]]\n df_grp = df1.groupby(['data_split', 'epoch']).agg('mean').reset_index()\n fig = px.line(df_grp, x=\"epoch\", y=cname, color='data_split', labels={cname: cname + \"_avg\"},\n color_discrete_sequence=px.colors.qualitative.Dark24)\n fig.update_layout(showlegend=False)\n fig.update_layout(font_size=8)\n fig.update_layout(autosize=True)\n fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))\n return fig", "_____no_output_____" ], [ "#hide\n### NOT USED \ndef pretty_print_pp_batch_and_next_token_probabilities(pp_output, tkn_kmaxidx, tkn_kmaxprob, generated_length): \n \"\"\"Goes through each paraphrase and shows at each timestep the next likely tokens. \n Only will work for greedy search. \n e.g. [\n \"<pad> ['▁My, 0.289', '▁I, 0.261', '▁Hello, 0.07'] | Entropy: 4.23 \",\n \"<pad> My ['▁name, 0.935', '▁Name, 0.005', 'name, 0.002'] | Entropy: 0.80 \"\n ]\n \"\"\"\n from pprint import pprint\n str_d = defaultdict(list)\n for i_tkn in range(0, generated_length-1): \n ids = pp_output.sequences[:, :(i_tkn+1)]\n partial_pp = pp_tokenizer.batch_decode(ids)\n kth_ids,kth_probs = tkn_kmaxidx[:, i_tkn, :], tkn_kmaxprob[:, i_tkn, :]\n kth_tkns = get_tokens_from_token_ids_batch(pp_tokenizer, kth_ids)\n\n # enumerates examples in batch\n z = zip(partial_pp, kth_tkns, kth_probs, ent.detach())\n for i_ex, (ex_sen, ex_next_tkns, ex_next_probs, ex_e) in enumerate(z): \n # Form nice formatted string mixing together tokens and probabilities\n tkn_tuples_l = [(tkn, round_t(prob,3)) for tkn, prob in zip(ex_next_tkns, ex_next_probs)]\n tkn_str = ['%s, %s' % t for t in tkn_tuples_l]\n # Add to dict of lists and add on entropy term. \n str_d[i_ex].append(f\"{ex_sen} {tkn_str} | Entropy: {ex_e[i_tkn]:.2f} \")\n\n for v in str_d.values(): pprint(v)", "_____no_output_____" ], [ "#hide\nfrom nbdev.export import notebook2script\nnotebook2script()", "Converted 00_utils.ipynb.\nConverted 02_tests.ipynb.\nConverted 03_config.ipynb.\nConverted 07_models.ipynb.\nConverted 10_data.ipynb.\nConverted 20_trainer.ipynb.\nConverted 25_insights.ipynb.\nConverted Untitled.ipynb.\nConverted baselines.ipynb.\nConverted baselines_analysis.ipynb.\nConverted index.ipynb.\nConverted run.ipynb.\nConverted show_examples.ipynb.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ec4f114f5f2176fcecf4187654f66af121264c39
17,160
ipynb
Jupyter Notebook
decomposition/latent-dirichlet-allocation/summary.ipynb
SeptumCapital/Machine-Learning-Numpy
ae8f9266a87ffd3f67471a97bf183b82740b7deb
[ "MIT" ]
89
2018-11-22T02:57:40.000Z
2022-03-10T09:17:19.000Z
decomposition/latent-dirichlet-allocation/summary.ipynb
IronOnet/Machine-Learning-Numpy
ae8f9266a87ffd3f67471a97bf183b82740b7deb
[ "MIT" ]
1
2019-02-25T15:23:42.000Z
2019-06-24T00:46:18.000Z
decomposition/latent-dirichlet-allocation/summary.ipynb
IronOnet/Machine-Learning-Numpy
ae8f9266a87ffd3f67471a97bf183b82740b7deb
[ "MIT" ]
57
2018-11-22T02:57:35.000Z
2022-03-29T00:14:36.000Z
75.929204
9,655
0.649942
[ [ [ "import numpy as np\nimport scipy as sp\nfrom scipy.special import gammaln\nimport re, random\nfrom operator import itemgetter", "_____no_output_____" ], [ "article = ['Martin Luther King Jr. is celebrated today, Jan. 17, 2011, just two days after he would have turned 82 years old.', 'It\\'s a great day to revisit the \"I Have A Dream\" speech he delivered in 1963 in Washington, D.C. Scroll down to read the text in full below.', 'Want to see MLK Jr. himself deliver the \"I Have A Dream\" speech? You can watch it here.', 'Full text to the \"I Have A Dream\" speech:', 'I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.', 'Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity.', 'But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languishing in the corners of American society and finds himself an exile in his own land. So we have come here today to dramatize a shameful condition.', \"In a sense we have come to our nation's capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.\", 'It is obvious today that America has defaulted on this promissory note insofar as her citizens of color are concerned. Instead of honoring this sacred obligation, America has given the Negro people a bad check, a check which has come back marked \"insufficient funds.\" But we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. So we have come to cash this check -- a check that will give us upon demand the riches of freedom and the security of justice. We have also come to this hallowed spot to remind America of the fierce urgency of now. This is no time to engage in the luxury of cooling off or to take the tranquilizing drug of gradualism. Now is the time to make real the promises of democracy. Now is the time to rise from the dark and desolate valley of segregation to the sunlit path of racial justice. Now is the time to lift our nation from the quick sands of racial injustice to the solid rock of brotherhood. Now is the time to make justice a reality for all of God\\'s children.', \"It would be fatal for the nation to overlook the urgency of the moment. This sweltering summer of the Negro's legitimate discontent will not pass until there is an invigorating autumn of freedom and equality. Nineteen sixty-three is not an end, but a beginning. Those who hope that the Negro needed to blow off steam and will now be content will have a rude awakening if the nation returns to business as usual. There will be neither rest nor tranquility in America until the Negro is granted his citizenship rights. The whirlwinds of revolt will continue to shake the foundations of our nation until the bright day of justice emerges.\", 'But there is something that I must say to my people who stand on the warm threshold which leads into the palace of justice. In the process of gaining our rightful place we must not be guilty of wrongful deeds. Let us not seek to satisfy our thirst for freedom by drinking from the cup of bitterness and hatred.', 'We must forever conduct our struggle on the high plane of dignity and discipline. We must not allow our creative protest to degenerate into physical violence. Again and again we must rise to the majestic heights of meeting physical force with soul force. The marvelous new militancy which has engulfed the Negro community must not lead us to a distrust of all white people, for many of our white brothers, as evidenced by their presence here today, have come to realize that their destiny is tied up with our destiny. They have come to realize that their freedom is inextricably bound to our freedom. We cannot walk alone.', 'As we walk, we must make the pledge that we shall always march ahead. We cannot turn back. There are those who are asking the devotees of civil rights, \"When will you be satisfied?\" We can never be satisfied as long as the Negro is the victim of the unspeakable horrors of police brutality. We can never be satisfied, as long as our bodies, heavy with the fatigue of travel, cannot gain lodging in the motels of the highways and the hotels of the cities. We cannot be satisfied as long as the Negro\\'s basic mobility is from a smaller ghetto to a larger one. We can never be satisfied as long as our children are stripped of their selfhood and robbed of their dignity by signs stating \"For Whites Only\". We cannot be satisfied as long as a Negro in Mississippi cannot vote and a Negro in New York believes he has nothing for which to vote. No, no, we are not satisfied, and we will not be satisfied until justice rolls down like waters and righteousness like a mighty stream.', 'I am not unmindful that some of you have come here out of great trials and tribulations. Some of you have come fresh from narrow jail cells. Some of you have come from areas where your quest for freedom left you battered by the storms of persecution and staggered by the winds of police brutality. You have been the veterans of creative suffering. Continue to work with the faith that unearned suffering is redemptive.', 'Go back to Mississippi, go back to Alabama, go back to South Carolina, go back to Georgia, go back to Louisiana, go back to the slums and ghettos of our northern cities, knowing that somehow this situation can and will be changed. Let us not wallow in the valley of despair.', 'I say to you today, my friends, so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream.', 'I have a dream that one day this nation will rise up and live out the true meaning of its creed: \"We hold these truths to be self-evident: that all men are created equal.\"', 'I have a dream that one day on the red hills of Georgia the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood.', 'I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice.', 'I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character.', 'I have a dream today.', 'I have a dream that one day, down in Alabama, with its vicious racists, with its governor having his lips dripping with the words of interposition and nullification; one day right there in Alabama, little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers.', 'I have a dream today.', 'I have a dream that one day every valley shall be exalted, every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight, and the glory of the Lord shall be revealed, and all flesh shall see it together.', 'This is our hope. This is the faith that I go back to the South with. With this faith we will be able to hew out of the mountain of despair a stone of hope. With this faith we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. With this faith we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day.', 'This will be the day when all of God\\'s children will be able to sing with a new meaning, \"My country, \\'tis of thee, sweet land of liberty, of thee I sing. Land where my fathers died, land of the pilgrim\\'s pride, from every mountainside, let freedom ring.\"', 'And if America is to be a great nation this must become true. So let freedom ring from the prodigious hilltops of New Hampshire. Let freedom ring from the mighty mountains of New York. Let freedom ring from the heightening Alleghenies of Pennsylvania!', 'Let freedom ring from the snowcapped Rockies of Colorado!', 'Let freedom ring from the curvaceous slopes of California!', 'But not only that; let freedom ring from Stone Mountain of Georgia!', 'Let freedom ring from Lookout Mountain of Tennessee!', 'Let freedom ring from every hill and molehill of Mississippi. From every mountainside, let freedom ring.', 'And when this happens, when we allow freedom to ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God\\'s children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual, \"Free at last! free at last! thank God Almighty, we are free at last!\"', 'Do you have information you want to share with HuffPost? Here\\xe2\\x80\\x99s how.']", "_____no_output_____" ], [ "def sample_index(p):\n return np.random.multinomial(1,p).argmax()\n\ndef word_indices(vec):\n for idx in vec.nonzero()[0]:\n for i in range(int(vec[idx])):\n yield idx\n\ndef log_multi_beta(alpha, K=None):\n if K is None:\n return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha))\n else:\n return K * gammaln(alpha) - gammaln(K*alpha)", "_____no_output_____" ], [ "class LDA:\n def __init__(self, corpus, n_topics, iteration=30, alpha=0.1, beta=0.1):\n self.corpus = corpus\n self.vocabulary = list(set(' '.join(self.corpus).split()))\n self.iteration = iteration\n self.alpha = alpha\n self.beta = beta\n self.n_topics = n_topics\n self._bow()\n n_docs, vocab_size = self.tfidf.shape\n self.nmz = np.zeros((n_docs, n_topics))\n self.nzw = np.zeros((n_topics, vocab_size))\n self.nm = np.zeros(n_docs)\n self.nz = np.zeros(self.n_topics)\n self.topics = {}\n \n for m in range(n_docs):\n for i, w in enumerate(word_indices(self.tfidf[m, :])):\n z = np.random.randint(n_topics)\n self.nmz[m,z] += 1\n self.nm[m] += 1\n self.nzw[z,w] += 1\n self.nz[z] += 1\n self.topics[(m,i)] = z\n \n def _bow(self):\n self.tfidf = np.zeros((len(self.corpus),len(self.vocabulary)))\n for no, i in enumerate(self.corpus):\n for text in i.split():\n self.tfidf[no, self.vocabulary.index(text)] += 1\n \n def _conditional_distribution(self, m, w):\n vocab_size = self.nzw.shape[1]\n left = (self.nzw[:,w] + self.beta) / (self.nz + self.beta * vocab_size)\n right = (self.nmz[m,:] + self.alpha) / (self.nm[m] + self.alpha * self.n_topics)\n p_z = left * right\n p_z /= np.sum(p_z)\n return p_z\n \n def loglikelihood(self):\n vocab_size = self.nzw.shape[1]\n n_docs = self.nmz.shape[0]\n lik = 0\n for z in range(self.n_topics):\n lik += log_multi_beta(self.nzw[z,:]+self.beta)\n lik -= log_multi_beta(self.beta, vocab_size)\n for m in range(n_docs):\n lik += log_multi_beta(self.nmz[m,:]+self.alpha)\n lik -= log_multi_beta(self.alpha, self.n_topics)\n return lik\n \n def run(self):\n for it in range(self.iteration):\n for m in range(self.tfidf.shape[0]):\n for i, w in enumerate(word_indices(self.tfidf[m, :])):\n z = self.topics[(m,i)]\n self.nmz[m,z] -= 1\n self.nm[m] -= 1\n self.nzw[z,w] -= 1\n self.nz[z] -= 1\n p_z = self._conditional_distribution(m, w)\n z = sample_index(p_z)\n self.nmz[m,z] += 1\n self.nm[m] += 1\n self.nzw[z,w] += 1\n self.nz[z] += 1\n self.topics[(m,i)] = z\n ", "_____no_output_____" ], [ "with open('kerajaan','r') as fopen:\n kerajaan = list(filter(None, fopen.read().split('\\n')))", "_____no_output_____" ], [ "def clearstring(string):\n string = re.sub('[^A-Za-z0-9 ]+', '', string)\n string = string.split(' ')\n string = filter(None, string)\n string = [y.strip() for y in string]\n string = ' '.join(string)\n return string.lower()\n\nkerajaan = [clearstring(i) for i in kerajaan]", "_____no_output_____" ], [ "def show_topics(corpus, count=10, k_words=10):\n lda = LDA(corpus,k_words)\n lda.run()\n vectors = lda.nmz[:count] \n top_words = lambda t: [lda.vocabulary[i] for i in np.argsort(t)[:-k_words-1:-1]]\n topic_words = ([top_words(t) for t in vectors])\n return [' '.join(t) for t in topic_words]", "_____no_output_____" ], [ "def summarize(article, k=3):\n article = [word for sentence in article for word in sentence.split() if re.match(\"^[a-zA-Z_-]*$\", word) or '.' in word or \"'\" in word or '\"' in word]\n article = ' '.join(article)\n sentences = article.split('.')\n sentences = [sentence for sentence in sentences if len(sentence)>1 and sentence != '']\n lda = LDA(sentences,len(sentences))\n lda.run()\n summary =[(sentences[i], np.linalg.norm(np.dot(lda.nmz,lda.nzw),2)) for i in range(len(sentences)) for b in range(len(lda.nmz))]\n summary = sorted(summary, key=itemgetter(1))\n summary = dict((v[0],v) for v in sorted(summary, key=lambda summary: summary[1])).values()\n return '.'.join([a for a, b in summary][len(summary)-(k):])", "_____no_output_____" ], [ "summarize(article, k=3)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4f13e06afb04d3d9e9ba552b50814319ff903f
25,510
ipynb
Jupyter Notebook
notebooks/Reinforcement_Learning_Demo_DockStream.ipynb
menggf/ReinventCommunity
9b6742b9e938cd3973ae8b5e7fbecfd26858b273
[ "MIT" ]
null
null
null
notebooks/Reinforcement_Learning_Demo_DockStream.ipynb
menggf/ReinventCommunity
9b6742b9e938cd3973ae8b5e7fbecfd26858b273
[ "MIT" ]
null
null
null
notebooks/Reinforcement_Learning_Demo_DockStream.ipynb
menggf/ReinventCommunity
9b6742b9e938cd3973ae8b5e7fbecfd26858b273
[ "MIT" ]
1
2021-12-15T08:32:34.000Z
2021-12-15T08:32:34.000Z
43.532423
689
0.540768
[ [ [ "> **How to run this notebook (command-line)?**\n1. Install the `ReinventCommunity` environment:\n`conda env create -f environment.yml`\n2. Activate the environment:\n`conda activate ReinventCommunity`\n3. Execute `jupyter`:\n`jupyter notebook`\n4. Copy the link to a browser\n\n\n# `REINVENT 3.0`: reinforcement learning with DockStream (docking)\n\n\nThis is a simple example of running `Reinvent` with only 1 score component (`DockStream`). To execute this notebook, make sure you have cloned the `DockStream` repository from GitHub and installed the conda environment.\n\n**NOTE: There is a detailed reasoning for each `REINVENT` code block provided in the `Reinforcement Learning Demo` notebook.**\n", "_____no_output_____" ], [ "## 1. Set up the paths\n_Please update the following code block such that it reflects your system's installation and execute it._", "_____no_output_____" ] ], [ [ "# load dependencies\nimport os\nimport re\nimport json\nimport tempfile\n\n# --------- change these path variables as required\nreinvent_dir = os.path.expanduser(\"~/Desktop/Reinvent\")\nreinvent_env = os.path.expanduser(\"~/miniconda3/envs/reinvent.v3.0\")\n\n# DockStream variables\ndockstream_dir = os.path.expanduser(\"~/Desktop/ProjectData/DockStream\")\ndockstream_env = os.path.expanduser(\"~/miniconda3/envs/DockStream/bin/python\")\n# generate the path to the DockStream entry points\ndocker_path = os.path.join(dockstream_dir, \"docker.py\")\n\noutput_dir = os.path.expanduser(\"~/Desktop/REINVENT_RL_DockStream_demo\")\n\n# --------- do not change\n# get the notebook's root path\ntry: ipynb_path\nexcept NameError: ipynb_path = os.getcwd()\n\n# if required, generate the folder to store the results\ntry:\n os.mkdir(output_dir)\nexcept FileExistsError:\n pass\n\n# Glide docking variables\ngrid_file_path = os.path.expanduser(\"~/Desktop/ReinventCommunity/notebooks/data/DockStream/1UYD_grid.zip\")\noutput_ligands_docked_poses_path = os.path.expanduser(\"~/Desktop/REINVENT_RL_DockStream_demo/docked_poses\")\noutput_ligands_docking_scores_path = os.path.expanduser(\"~/Desktop/REINVENT_RL_DockStream_demo/docking_scores\")\n\ntry:\n os.mkdir(output_ligands_docked_poses_path)\nexcept FileExistsError:\n pass\n\ntry:\n os.mkdir(output_ligands_docking_scores_path)\nexcept FileExistsError:\n pass\n\ndocking_configuration_path = os.path.join(output_dir, \"Glide_DockStream_Conf.json\")", "_____no_output_____" ] ], [ [ "## 2. Set up the `DockStream` Configuration\n_Please update the following code block such that it reflects your system's installation and execute it._\n\nIn this notebook, we will demonstrate how to use `DockStream` with `REINVENT`. `Glide` with `LigPrep` will be used as the molecular docking component. For more details regarding using `Glide` in `DockStream`, see the `demo_Glide` notebook in the `DockStreamCommunity` repository. There, all details and supported functionalities are presented. The `Glide` with `LigPrep` configuration used in this notebook is the simplest case.", "_____no_output_____" ] ], [ [ "# specify the embedding and docking JSON file as a dictionary and write it out\ned_dict = {\n \"docking\": {\n \"header\": { # general settings\n \"environment\": {\n }\n },\n \"ligand_preparation\": { # the ligand preparation part, defines how to build the pool\n \"embedding_pools\": [\n {\n \"pool_id\": \"Ligprep_pool\",\n \"type\": \"Ligprep\",\n \"parameters\": {\n \"prefix_execution\": \"module load schrodinger/2019-4\",\n \"parallelization\": {\n \"number_cores\": 2\n },\n \"use_epik\": {\n \"target_pH\": 7.0,\n \"pH_tolerance\": 2.0\n },\n \"force_field\": \"OPLS3e\"\n },\n \"input\": {\n \"standardize_smiles\": False,\n \"type\": \"console\" # input type \"console\" when using DockStream with REINVENT\n }\n }\n ]\n },\n \"docking_runs\": [\n {\n \"backend\": \"Glide\",\n \"run_id\": \"Glide_run\",\n \"input_pools\": [\"Ligprep_pool\"],\n \"parameters\": {\n \"prefix_execution\": \"module load schrodinger/2019-4\", # will be executed before a program call\n \"parallelization\": { # if present, the number of cores to be used\n # can be specified\n \"number_cores\": 2\n },\n \"glide_flags\": { # all all command-line flags for Glide here \n \"-HOST\": \"localhost\"\n },\n \"glide_keywords\": { # add all keywords for the \"input.in\" file here\n # this is the minimum keywords that needs to be \n # specified and represents a simple `Glide` \n # docking configuration\n \n \"GRIDFILE\": grid_file_path,\n \"POSE_OUTTYPE\": \"ligandlib_sd\",\n \"PRECISION\": \"HTVS\"\n }\n },\n \"output\": {\n \"poses\": { \"poses_path\": os.path.join(output_ligands_docked_poses_path, \"docked_poses.sdf\")},\n \"scores\": { \"scores_path\": os.path.join(output_ligands_docking_scores_path, \"docking_scores.csv\")}\n }\n }]}}\n\nwith open(docking_configuration_path, 'w') as f:\n json.dump(ed_dict, f, indent=2)", "_____no_output_____" ] ], [ [ "## 3. Set up the `REINVENT` configuration \nIn the cells below we will build a nested dictionary object that will be eventually converted to JSON file which in turn will be consumed by `REINVENT`. \nYou can find this file in your `output_dir` location.", "_____no_output_____" ], [ "### A) Declare the run type", "_____no_output_____" ] ], [ [ "# initialize the dictionary\nconfiguration = {\n \"version\": 3, # we are going to use REINVENT's newest release\n \"run_type\": \"reinforcement_learning\" # other run types: \"sampling\", \"validation\",\n # \"transfer_learning\",\n # \"scoring\" and \"create_model\"\n}", "_____no_output_____" ] ], [ [ "### B) Sort out the logging details\nThis includes `result_folder` path where the results will be produced.\n\nAlso: `REINVENT` can send custom log messages to a remote location. We have retained this capability in the code. if the `recipient` value differs from `\"local\"` `REINVENT` will attempt to POST the data to the specified `recipient`. ", "_____no_output_____" ] ], [ [ "# add block to specify whether to run locally or not and\n# where to store the results and logging\nconfiguration[\"logging\"] = {\n \"sender\": \"http://0.0.0.1\", # only relevant if \"recipient\" is set to \"remote\"\n \"recipient\": \"local\", # either to local logging or use a remote REST-interface\n \"logging_frequency\": 1, # log every x-th steps\n \"logging_path\": os.path.join(output_dir, \"progress.log\"), # load this folder in tensorboard\n \"result_folder\": os.path.join(output_dir, \"results\"), # will hold the compounds (SMILES) and summaries\n \"job_name\": \"Reinforcement learning DockStream demo\", # set an arbitrary job name for identification\n \"job_id\": \"demo\" # only relevant if \"recipient\" is set to a specific REST endpoint\n}", "_____no_output_____" ] ], [ [ "Create `parameters` field:", "_____no_output_____" ] ], [ [ "# add the \"parameters\" block\nconfiguration[\"parameters\"] = {}", "_____no_output_____" ] ], [ [ "### C) Set Diversity Filter\nDuring each step of Reinforcement Learning the compounds scored above `minscore` threshold are kept in memory. Those scored smiles are written out to a file in the results folder `scaffold_memory.csv`.", "_____no_output_____" ] ], [ [ "# add a \"diversity_filter\"\nconfiguration[\"parameters\"][\"diversity_filter\"] = {\n \"name\": \"IdenticalMurckoScaffold\", # other options are: \"IdenticalTopologicalScaffold\", \n # \"NoFilter\" and \"ScaffoldSimilarity\"\n # -> use \"NoFilter\" to disable this feature\n \"nbmax\": 25, # the bin size; penalization will start once this is exceeded\n \"minscore\": 0.4, # the minimum total score to be considered for binning\n \"minsimilarity\": 0.4 # the minimum similarity to be placed into the same bin\n}", "_____no_output_____" ] ], [ [ "### D) Set Inception\n* `smiles` provide here a list of smiles to be incepted \n* `memory_size` the number of smiles allowed in the inception memory\n* `sample_size` the number of smiles that can be sampled at each reinforcement learning step from inception memory", "_____no_output_____" ] ], [ [ "# prepare the inception (we do not use it in this example, so \"smiles\" is an empty list)\nconfiguration[\"parameters\"][\"inception\"] = {\n \"smiles\": [], # fill in a list of SMILES here that can be used (or leave empty)\n \"memory_size\": 100, # sets how many molecules are to be remembered\n \"sample_size\": 10 # how many are to be sampled each epoch from the memory\n}", "_____no_output_____" ] ], [ [ "### E) Set the general Reinforcement Learning parameters\n* `n_steps` is the amount of Reinforcement Learning steps to perform. Best start with 1000 steps and see if thats enough.\n* `agent` is the generative model that undergoes transformation during the Reinforcement Learning run.\n\nWe reccomend keeping the other parameters to their default values.", "_____no_output_____" ] ], [ [ "# set all \"reinforcement learning\"-specific run parameters\nconfiguration[\"parameters\"][\"reinforcement_learning\"] = {\n \"prior\": os.path.join(ipynb_path, \"models/random.prior.new\"), # path to the pre-trained model\n \"agent\": os.path.join(ipynb_path, \"models/random.prior.new\"), # path to the pre-trained model\n \"n_steps\": 2, # the number of epochs (steps) to be performed; often 1000\n # (set to 2 in this notebook to decrease docking computation time -\n # it is not expected that the agent will appreciably learn to\n # generate compounds with good docking scores in only 2 epochs.\n # The purpose of this notebook is to illustrate how DockStream \n # can be specified as a component to the `Scoring Function`)\n \n \"sigma\": 128, # used to calculate the \"augmented likelihood\", see publication\n \"learning_rate\": 0.0001, # sets how strongly the agent is influenced by each epoch\n \"batch_size\": 32, # specifies how many molecules are generated per epoch, often 128\n # docking becomes more computationally demanding the greater the\n # batch size, as each compound must be docked. Depending on the\n # docking configuration, embedding ligands may generate different \n # tautomers, ionization states, etc., which will increase the number\n # of compounds that need to be docked. Batch size is set to 32 in \n # this notebook to decrease docking computation time)\n \n \"reset\": 0, # if not '0', the reset the agent if threshold reached to get\n # more diverse solutions\n \"reset_score_cutoff\": 0.5, # if resetting is enabled, this is the threshold\n \"margin_threshold\": 50 # specify the (positive) margin between agent and prior\n}", "_____no_output_____" ] ], [ [ "### F) Define the scoring function\nThe scoring function will consist only of the `DockStream` component, in which `Glide` with `LigPrep` is used for molecular docking.", "_____no_output_____" ] ], [ [ "# prepare the scoring function definition and add at the end\nscoring_function = {\n \"name\": \"custom_product\", # this is our default one (alternative: \"custom_sum\")\n \"parallel\": False, # sets whether components are to be executed\n # in parallel; note, that python uses \"False\" / \"True\"\n # but the JSON \"false\" / \"true\"\n\n # the \"parameters\" list holds the individual components\n \"parameters\": [\n\n # add component: use \n {\n \"component_type\": \"dockstream\", # use DockStream as a Scoring Function component \n \"name\": \"Glide LigPrep Docking\", # arbitrary name\n \"weight\": 1,\n \"specific_parameters\": {\n \"transformation\": {\n \"transformation_type\": \"reverse_sigmoid\", # lower Glide scores are better - use reverse\n # sigmoid transformation\n \"low\": -11,\n \"high\": -5,\n \"k\": 0.25\n },\n \"configuration_path\": docking_configuration_path,\n \"docker_script_path\": docker_path,\n \"environment_path\": dockstream_env\n }\n }]\n}\nconfiguration[\"parameters\"][\"scoring_function\"] = scoring_function", "_____no_output_____" ] ], [ [ "## 4. Write out the `REINVENT` configuration", "_____no_output_____" ], [ "We now have successfully filled the dictionary and will write it out as a `JSON` file in the output directory. Please have a look at the file before proceeding in order to see how the paths have been inserted where required and the `dict` -> `JSON` translations (e.g. `True` to `true`) have taken place.", "_____no_output_____" ] ], [ [ "# write the configuration file to the disc\nconfiguration_JSON_path = os.path.join(output_dir, \"RL_DockStream_config.json\")\nwith open(configuration_JSON_path, 'w') as f:\n json.dump(configuration, f, indent=4, sort_keys=True)", "_____no_output_____" ] ], [ [ "## 5. Run `REINVENT`\nNow it is time to execute `REINVENT` locally. Note, that depending on the number of epochs (steps) and the execution time of the scoring function components, this might take a while. As we have only specified a low number of epochs (125) and all components should be fairly quick, this should not take too long in our case though.\n\nThe command-line execution looks like this:\n```\n# activate envionment\nconda activate reinvent.v3.0\n\n# execute REINVENT\npython <your_path>/input.py <config>.json\n```", "_____no_output_____" ] ], [ [ "%%capture captured_err_stream --no-stderr\n\n# execute REINVENT from the command-line\n!{reinvent_env}/bin/python {reinvent_dir}/input.py {configuration_JSON_path}", "_____no_output_____" ], [ "# print the output to a file, just to have it for documentation\nwith open(os.path.join(output_dir, \"run.err\"), 'w') as file:\n file.write(captured_err_stream.stdout)\n\n# prepare the output to be parsed\nlist_epochs = re.findall(r'INFO.*?local', captured_err_stream.stdout, re.DOTALL)\ndata = [epoch for idx, epoch in enumerate(list_epochs)]\ndata = [\"\\n\".join(element.splitlines()[:-1]) for element in data]", "_____no_output_____" ] ], [ [ "We have calculated a total of 2 epochs, let us quickly investigate how the agent fared in the first epoch. Below you see the print-out of the first epoch. Running `REINVENT` with `DockStream` for more epochs will show that the agent gradually improves over time, i.e, generates compounds that satisfy the docking component, thus generating compounds that dock well. Note, that the fraction of valid `SMILES` is high right from the start (because we use a pre-trained prior). You can see the partial scores for each component for the first couple of compounds, but the most important information is the average score. If run for more epochs, the average score will increase over time.", "_____no_output_____" ] ], [ [ "for element in data:\n print(element)", "INFO starting an RL run\nINFO \n Step 0 Fraction valid SMILES: 100.0 Score: 0.1702 Time elapsed: 229 Time left: 458.0\n Agent Prior Target Score SMILES\n-27.59 -27.59 2.99 0.24 C1(O)(c2cccc(Cl)c2)CC2N(Cc3c(C)noc3C)C(CC2)C1\n-23.84 -23.84 3.04 0.21 C1(C)N(S(c2cccc(Cl)c2C)(=O)=O)CCNC1=O\n-24.26 -24.26 -21.44 0.02 c1(C2C(C(OCC)=O)=C(C)N=C3CC(c4cc(OC)c(OC)cc4)CC(=O)C23)cscc1\n-37.08 -37.08 -30.63 0.05 C1CN(CCCN(C2CC3N(C(c4cnc(Cl)cc4)c4ccccc4Cl)C(CC3)C2)c2ccccc2)CCO1\n-24.37 -24.37 8.83 0.26 c1c2c(ccc1OC)-c1c(sc(=NCC3CCN(C(C)=O)CC3)[nH]1)CCC2\n-25.28 -25.28 -1.84 0.18 c1(C(N)=O)ccc(C(N(Cc2cccs2)C)=O)cc1\n-24.27 -24.27 34.28 0.46 c1(F)cc(C(c2cc(C(=O)N(CC)CC)[nH]c2)=O)cc(F)c1\n-27.77 -27.77 44.67 0.57 N1Cc2c(-c3ccc(C)cc3)cccc2C1CC=C\n-31.68 -31.68 -17.89 0.11 c1cnc(-c2cc3ncn(C4(C)CCN(C(C5CC5)=O)CC4)c3cn2)cc1\n-22.01 -22.01 20.28 0.33 n1ccncc1N1CCN(C(c2cccc(OC)c2)=O)CC1\nGlide LigPrep Docking raw_Glide LigPrep Docking\n0.23889151215553284 -6.792210102081299 \n0.20994886755943298 -6.61870002746582 \n0.022049779072403908 -4.047410011291504 \n0.05043281242251396 -4.940450191497803 \n0.25940054655075073 -6.906529903411865 \n0.18311482667922974 -6.441349983215332 \n0.45742636919021606 -7.822070121765137 \n0.5659542679786682 -8.276590347290039 \n0.10779209434986115 -5.79709005355835 \n0.3304086923599243 -7.263780117034912 \n\n" ] ], [ [ "## 6. Analyse the Results\nIn order to analyze the run in a more intuitive way, we can use `tensorboard`:\n\n```\n# go to the root folder of the output\ncd <your_path>/REINVENT_RL_demo\n\n# make sure, you have activated the proper environment\nconda activate reinvent.v3.0\n\n# start tensorboard\ntensorboard --logdir progress.log\n```\n\nThen copy the link provided to a browser window, e.g. \"http://workstation.url.com:6006/\".", "_____no_output_____" ], [ "The results folder will hold four different files: the agent (pickled), the input JSON (just for reference purposes), the memory (highest scoring compounds in `CSV` format) and the scaffold memory (in `CSV` format).", "_____no_output_____" ] ], [ [ "!head -n 15 {output_dir}/results/memory.csv", ",smiles,score,likelihood\r\n19,C(=NNC(N)=S)c1cc(OC2CCCC2)c(OC)cc1,0.6942421,-22.620014\r\n7,N1Cc2c(-c3ccc(C)cc3)cccc2C1CC=C,0.56595427,-27.769112\r\n28,c1c(Cn2c(=O)[nH]c3c(C)nc(C)n32)cccc1,0.5590625,-22.66359\r\n16,c1cc(Cn2c(CCCCN)cnc2)cc(Cl)c1,0.51199514,-27.736107\r\n3,C(C(N)=O)C(=O)N1CCN(c2ccc3c(c2)CN(C(=O)C)CC3)C=C1,0.4736048,-41.357193\r\n6,c1(F)cc(C(c2cc(C(=O)N(CC)CC)[nH]c2)=O)cc(F)c1,0.45742637,-24.27091\r\n18,c1(C2=NN(C(=O)C)C(c3ccccc3)C2)ccc(OC)cc1,0.43780145,-17.408478\r\n15,O1CCN(Cc2ccc(NC(=O)CC(C)=O)cc2)CC1,0.39261344,-24.114302\r\n17,c1(C=C2C(=O)N(C)C(=Nc3ccccc3)S2)ccc(N(CC)CC)c(Cl)c1,0.3528337,-28.79707\r\n18,Clc1ccccc1-c1[nH]c2c(n1)C(=O)CCC2,0.3498513,-22.323753\r\n24,Fc1c(C(C)=O)c(F)c(C(=O)c2ccc(=N)[nH]c2)c(Cl)c1,0.33398008,-24.691898\r\n9,n1ccncc1N1CCN(C(c2cccc(OC)c2)=O)CC1,0.3304087,-22.013836\r\n26,N(CC(=O)c1c(C(=O)c2ccccc2)ccc(C)c1)c1cc(Cc2ccccc2)ccc1,0.31439623,-43.123184\r\n23,O=S1(=O)CCC(n2c(=O)c3sc(-c4cccnc4)cc3[nH]c2=O)C1,0.29765692,-25.620085\r\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", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
ec4f33109b75275b9d67f0e373945c321678d5cc
585,885
ipynb
Jupyter Notebook
Machine Learning for Star Galaxy Separation.ipynb
nyLiao/SG-Separation
b32e899a6af07e47603d80aa722723e0bc435d22
[ "MIT" ]
1
2019-09-03T14:45:52.000Z
2019-09-03T14:45:52.000Z
Machine Learning for Star Galaxy Separation.ipynb
nyLiao/SG-Separation
b32e899a6af07e47603d80aa722723e0bc435d22
[ "MIT" ]
null
null
null
Machine Learning for Star Galaxy Separation.ipynb
nyLiao/SG-Separation
b32e899a6af07e47603d80aa722723e0bc435d22
[ "MIT" ]
null
null
null
512.137238
77,088
0.931917
[ [ [ "# Machine Learning for Star/Galaxy Separation: Performance Influence of Models and Magnitude \n\nnyLiao", "_____no_output_____" ], [ "# Introduction\n---", "_____no_output_____" ], [ "## Research Background\n\nDiscriminating between stars and galaxies is a classic topic that dates back to Charles Messier’s time. As astronomical observation technology develops, an unprecedentedly large number of objects have been discovered, exceeding the ability of any human to process manually. Hence, it is more essential than ever to develop automated methods on data analysis to perform the task efficiently and accurately. \n\nTelling stars and galaxies apart, or the Star/Galaxy Separation Problem (SGSP), is important, for being one of the first steps in processing observation data. It is only after correct separation that the following categorizing and analyzing technique would be effective. However, SGSP also remains as one of the most difficult tasks. For distant and dim objects, the difference between stars and galaxies becomes fuzzier, making it hard to discriminate simply with human eyes. In addition, many factors, including equipment resolution, imaging quality, and artifacts, will lead to even poorer separation results ([*Machado et al. (2016)*](https://ieeexplore.ieee.org/document/7727189)). \n\nIn the process of development, researchers apply different methods on SGSP. One of the main aspects is machine learning models, for their good performance as well as automated features. [*Odewahn et al. (1992)*](https://link.springer.com/chapter/10.1007/978-94-011-2472-0_28) first explored the possibility of automated algorithms using artificial neural networks, creating a fundamental precedent on this field. One of the example using neural networks is the popular astronomical image processing software SExtractor ([*Bertin & Arnouts 1996*](https://aas.aanda.org/articles/aas/ps/1996/08/ds1060.ps.gz)). Researchers also look into other machine learning approaches. [*Weir, Fayyad, & Djorgovski (1995)*](http://adsabs.harvard.edu/full/1995AJ....109.2401W) applied the decision trees method on large scale sky surveys data. In 2004, support vector machines is also implemented on SGSP ([*Zhang & Zhao*](https://www.aanda.org/articles/aa/abs/2004/30/aa3942/aa3942.html)). Recently, more advanced neural networks techniques are introduced thanks to the trend of deep learning ([*Kamdar, Turk, & Brunner 2015*](https://academic.oup.com/mnras/article-abstract/455/1/642/984981), [*Kim & Brunner 2016*](https://academic.oup.com/mnras/article-abstract/464/4/4463/2417400)). In 2016, [*Machado et al.*](https://ieeexplore.ieee.org/document/7727189) conducted a comparison study on different SGSP machine learning methods. \n\nOne of the common phenomenon is that, most SGSP solutions include, or mainly depend on the object attributes of spectroscopic data. This is effective for higher accuracy, as spectrum contains more information about the actual object. However it limits the scope of usage, that such algorithms would be inconvenient and impractical when there is no spectra available, due to either equipment or data limitations. This is especially a common case in amateur observation and photography. \n\nThere is also controversy on applying analytical methods in machine learning models according to some researchers ([*Kim & Brunner 2016*](https://academic.oup.com/mnras/article-abstract/464/4/4463/2417400)). They criticize that excessive intervention on the observation data not only requires abundant expert knowledge, but may also bring in bias. It is better and more general to enable the algorithm learning data features by itself. In the most straightforward form, it means to learn directly from the image pixels. \n\nIn this work, we focus on the context that using images only and directly as the input data. We search for the optimal hyper parameters of different supervised machine learning classifiers and train them on the data to solve the SGSP task. We then measure experiment performance of each models and look into the relationship between separation accuracy and object magnitude. ", "_____no_output_____" ], [ "## Data Processing\n\nIn this paper, we use a subset from the Sloan Digital Sky Survey Data Release 15, or the SDSS DR15 ([*Aguado et al. 2019*](https://iopscience.iop.org/article/10.3847/1538-4365/aaf651/meta)). Being one of the largest sky survey, the SDSS database contains five bands color information and other attributes of more than 300 million stars and galaxies ([*York et al. 2000*](https://iopscience.iop.org/article/10.1086/301513)). All the photometric and spectroscopic data is publicly [available online](https://www.sdss.org/dr15/data_access). \n\nTo acquire the data, we use the [SDSS SQL Search](http://skyserver.sdss.org/dr15/en/tools/search/sql.aspx) to query the object coordinates, magnitude, and type information. According to previous research ([*Machado et al. 2016*](https://ieeexplore.ieee.org/document/7727189)), the density of stars and galaxies in the dataset is correlated with their magnitude, which may bring additional information into classifiers and have influence on the separation. Hence we set the limit to $1,000$ of each star/galaxy visual magnitude ([*Jester et al. 2005*](http://www.sdss3.org/dr8/algorithms/sdssUBVRITransform.php#Jester2005)) range width $1.0$. The query magnitude range is from $15.0$ to $20.0$, forming a database subset of $10,000$ samples in total. As the query order is base on the attribute `id` of object, it can be seen as a random sampling subset. Other constraints include the `score` and `CLEAN` attributes mainly for the image quality. We also exclude QSOs, for the reason that identifying them should be a more specific problem base on their distinct characteristic. \n\nBase on the queries information, we then use the [SDSS Image Cutout API](http://skyserver.sdss.org/dr15/en/help/docs/api.aspx#imgcutout) to download $10,000$ images of corresponding objects. All the image data in our study are images of RGB color and in JPG format. This is one of the most common image formats, offering our models a wide applicability on the model data source, especially in the situation where RGB images are the only available input for a SGSP task. The images are cutouts of a single galaxy or star at the center base on their celestial coordinates. The resolution is $32 \\times 32$ pixels, at the scale of $0.4''/\\mathrm{px}$. We use the relatively low resolution for two reasons. First, dim objects are often small on images, which is the difficult case for most SGSP classifiers. Also, a smaller data size provides an efficient model training process, and may also maintain generality on higher resolution data. \n\nTo use the images as input data, we flatten the three channel image array to one-dimension feature vectors. Thus each pixel is calculated as one feature to the model input. We use the labeling data of `STAR` or `GALAXY` as target classes. \n\nThe data processing procedure is executed and can be deeper reviewed in the IPython Notebook [`data.ipynb`](data.ipynb). In this notebook, the data are provided by following functions. ", "_____no_output_____" ] ], [ [ "import warnings;\nwarnings.filterwarnings('ignore');\n\nimport numpy as np\nimport pandas as pd\nimport sklearn.model_selection, sklearn.metrics", "_____no_output_____" ], [ "def load_data(fname):\n '''Load label and image data of one given magnitude range.'''\n path_qry, path_arr = \"../data/query/\", \"../data/array/\"\n fname = str(fname)\n\n f_g, f_s = pd.read_csv(path_qry + \"g\" + fname + \".csv\"), pd.read_csv(path_qry + \"s\" + fname + \".csv\")\n d_g, d_s = np.load(path_arr+ \"g\" + fname + \".npy\"), np.load(path_arr+ \"s\" + fname + \".npy\")\n# print(d_s.shape, d_s[0, 0, 0, :])\n\n f = f_g.append(f_s)\n d = np.vstack((d_g, d_s))\n\n # shuffle order\n np.random.seed(42)\n pm = np.random.permutation(d.shape[0])\n f, d = f.iloc[pm, :], d[pm]\n# print(len(d), d[0, 0, 0, :])\n return f, d\n \ndef load_data_all(left=15, righ=20):\n '''Load the dataset of given magnitude range.'''\n path_qry, path_arr = \"../data/query/\", \"../data/array/\"\n for fname in range(left, righ):\n fname = str(fname)\n\n f_g, f_s = pd.read_csv(path_qry + \"g\" + fname + \".csv\"), pd.read_csv(path_qry + \"s\" + fname + \".csv\")\n d_g, d_s = np.load(path_arr + \"g\" + fname + \".npy\"), np.load(path_arr + \"s\" + fname + \".npy\")\n\n if fname == str(left):\n f = f_g.append(f_s)\n d = np.vstack((d_g, d_s))\n else:\n f = f.append(f_g)\n f = f.append(f_s)\n d = np.vstack((d, d_g, d_s))\n \n # shuffle order\n np.random.seed(42)\n pm = np.random.permutation(d.shape[0])\n f, d = f.iloc[pm, :], d[pm]\n# print('shape:', len(d), d[0, 0, 0, :])\n return f, d\n\ndef load_sample(f, d, random_state=None, test_size=0.25):\n '''Generate random training and testing samples from labels and images.'''\n x = d.reshape((len(d), -1))\n y = (f['type'] == 3).values # GALAXY for True, STAR for False\n\n x_tr, x_ts, y_tr, y_ts = sklearn.model_selection.train_test_split(x, y, \n test_size=test_size, \n random_state=random_state)\n\n# print('shape:', x.shape, y.shape, x_tr.shape, y_ts.shape)\n return x_tr, x_ts, y_tr, y_ts", "_____no_output_____" ] ], [ [ "Here are examples of the input data images. ", "_____no_output_____" ] ], [ [ "%pylab inline\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom matplotlib import rc\n\nrc('text', usetex=True)\nrc('font', family='Times New Roman')", "Populating the interactive namespace from numpy and matplotlib\n" ], [ "# prepare figure\nfig, axs = plt.subplots(2, 5, figsize=(18, 8))\nfig.subplots_adjust(hspace = 0.1, wspace = 0.15)\nfig.suptitle('Examples of Input Images', y=0.95)\n\nfor m in range(15, 20):\n # load a random sample\n path_qry, path_arr = \"../data/query/\", \"../data/array/\"\n fname = str(m)\n d_g, d_s = np.load(path_arr + \"g\" + fname + \".npy\"), np.load(path_arr + \"s\" + fname + \".npy\")\n img_g, img_s = d_g[42, :].astype(uint8), d_s[42, :].astype(uint8)\n \n axs[0, m-15].imshow(img_g)\n axs[0, m-15].set_title('Galaxy, $mag$=[%d, %d]' % (m, m+1))\n \n axs[1, m-15].imshow(img_s)\n axs[1, m-15].set_title('Star, $mag$=[%d, %d]' % (m, m+1))", "_____no_output_____" ] ], [ [ "# Classifiers and Parameter Exploration\n---\n\nIn this work, we apply five mainstream machine learning classification methods using the Python package scikit-learn ([`sklearn`](https://scikit-learn.org/stable/index.html)). We utilize the [`sklearn.model_selection.GridSearchCV`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) method to optimize hyper-parameters of each model with cross-validation. Note that we keep the random state parameter to `None` in order to explore a wider range of models states. \n\nAll exploratory trainings run on a $2,000$-image random sample from the full dataset. ", "_____no_output_____" ] ], [ [ "path_qry, path_arr, fname = \"../data/query/\", \"../data/array/\", \"sample\"\nf = pd.read_csv(path_qry + fname + \".csv\")\nd = np.load(path_arr + fname + \".npy\")\nx_tr, x_ts, y_tr, y_ts = load_sample(f, d)", "_____no_output_____" ] ], [ [ "To measure the training performance, we use the accuracy $A$ of each classifier defined as: \n$$\nA = \\frac{T_g + T_s}{T_g + T_s + F_g + F_s}\n$$\nwhere, $T_g$ and $T_s$ are the number of successfully classified galaxies and stars respectively, $F_g$ is the number of true galaxies classified as stars, and $F_s$ is number of true stars classified as galaxies. \n\nTo evaluate the models, we also introduce another common metrics in classification problems ([*Machado et al. 2016*](https://ieeexplore.ieee.org/document/7727189)), the completeness $C$ and purity $P$, which are expressed on the galaxy side by: \n$$\nC = \\frac{T_g}{T_g + F_g}\n$$\n\n$$\nP = \\frac{T_g}{T_g + F_s}\n$$\n\nThe higher $C$ represents more galaxies samples are successfully identified, and the higher $P$ value indicates more confidence that the classified galaxies objects are true galaxies. ", "_____no_output_____" ] ], [ [ "def metric(confusion_matrix):\n '''The metrics from a given confusion matrix.'''\n Tg, Ts = confusion_matrix[1, 1], confusion_matrix[0, 0]\n Fg, Fs = confusion_matrix[1, 0], confusion_matrix[0, 1]\n A = (Tg + Ts) / (Tg + Ts + Fg + Fs) * 100\n C = Tg / (Tg + Fg) * 100\n P = Tg / (Tg + Fs) * 100\n return A, C, P\n\ndef search_param(classifier, param_grid):\n '''Simplified grid search and cross-validate optimal paragrams process for presentation.'''\n # in real search the `cv` round should be at least 5 for better accuracy (but slower search)\n clf = sklearn.model_selection.GridSearchCV(classifier, param_grid, cv=2, iid=False, n_jobs=2)\n clf = clf.fit(x_tr, y_tr)\n clf_best = clf.best_estimator_\n \n # calculate metrics on testing data fold\n y_pred = clf_best.predict(x_ts)\n A, C, P = metric(sklearn.metrics.confusion_matrix(y_ts, y_pred, labels=range(2)))\n \n print('Best estimator =', clf.best_estimator_)\n print('A = %0.2f%%, C = %0.2f%%, P = %0.2f%%' % (A, C, P))", "_____no_output_____" ] ], [ [ "## Support Vector Machines\n\nSupport Vector Machines (SVM) are machine learning models that use kernels to classify samples in a high dimensional feature space with supporting vectors. SVM has been successfully applied in many astronomical problems ([*Zhang & Zhao 2004*](https://www.aanda.org/articles/aa/abs/2004/30/aa3942/aa3942.html), [*Fadely, Hogg, & Willman 2012*](https://iopscience.iop.org/article/10.1088/0004-637X/760/1/15/meta)). SVM requires careful parameters adjustment base on different input data, but often presents good results if suitable. \n\nOur SVM is based on the package [`sklearn.svm.SVC`](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC). Here we implement SVM with the $rbf$ kernel. We mainly look into two major SVM parameters, $C$ and $\\mathrm{gamma}$ within the range $0.1 \\le C \\le 1000$ and $10^{-7} \\le \\mathrm{gamma} \\le 0.1$. We conduct careful search and decide the best value of $C = 5$, $\\mathrm{gamma} = 2\\times10^{-6}$. Here is a simplified search procedure which intends to show the process but does not guarantee optimal parameters.", "_____no_output_____" ] ], [ [ "import sklearn.svm\n\nclassifier = sklearn.svm.SVC(kernel='rbf', class_weight='balanced')\nparam_grid = {'C': [0.1, 5, 100, 1000], \n 'gamma': [1e-6, 2e-6, 1e-4, 0.1]}\n\nsearch_param(classifier, param_grid)", "Best estimator = SVC(C=100, cache_size=200, class_weight='balanced', coef0=0.0,\n decision_function_shape='ovr', degree=3, gamma=1e-06, kernel='rbf',\n max_iter=-1, probability=False, random_state=None, shrinking=True,\n tol=0.001, verbose=False)\nA = 98.20%, C = 97.97%, P = 98.37%\n" ] ], [ [ "## k-Nearest Neighbors\n\nk-Nearest Neighbors (kNN) classifier implements the k-Nearest Neighbors algorithm to decide border and vote each input into one of the neighbors. kNN is suitable for complex input distribution and shares generality on different problem settings ([*Goldberger et al. 2005*](https://cs.nyu.edu/~roweis/papers/ncanips.pdf)). \n\nWe take the [`sklearn.neighbors.KNeighborsClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier) as our kNN method. The most important parameter in the model is the number of neighbors $k$, that a large $k$ classifier is lack of variance between classes, while few neighbors ignore some data detail information. We explore the range of $1 \\le k \\le 500$ to find the best value $k = 10$. ", "_____no_output_____" ] ], [ [ "import sklearn.neighbors\n\nclassifier = sklearn.neighbors.KNeighborsClassifier()\nparam_grid = {'n_neighbors': [1, 10, 100, 500]}\n\nsearch_param(classifier, param_grid)", "Best estimator = KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n metric_params=None, n_jobs=None, n_neighbors=10, p=2,\n weights='uniform')\nA = 97.00%, C = 97.56%, P = 96.39%\n" ] ], [ [ "## Decision Tree Classifier\n\nThe Decision Tree Classifier (DTC) builds a binary tree to look into data features and categorize input. It is easy to establish, but still remains useful on complex or large dataset. It is also a basic supervised machine learning method that gives interpretable results ([*Breiman et al. 1984*](https://content.taylorfrancis.com/books/download?dac=C2009-0-07054-X&isbn=9781351460491&format=googlePreviewPdf)). Decision Trees has been introduced to SGSP due to its robust performance ([*Ball et al. 2006*](https://iopscience.iop.org/article/10.1086/507440)). \n\nThe method [`sklearn.tree.DecisionTreeClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier) provides a well-prepared DTC. We continue from Ball's work, use the criterion of `entropy`, and mainly explore attributes of $\\mathrm{maximum\\ tree\\ depth}$ and $\\mathrm{minimum\\ leaf\\ samples}$ in order to balance efficiency and accuracy. The optimization range is $4 \\le \\mathrm{maximum\\ tree\\ depth} \\le 20$ and $1 \\le \\mathrm{minimum\\ leaf\\ samples} \\le 16$. Search result is $\\mathrm{maximum\\ tree\\ depth} = 4$, $\\mathrm{minimum\\ leaf\\ samples} = 2$.", "_____no_output_____" ] ], [ [ "import sklearn.tree\n\nclassifier = sklearn.tree.DecisionTreeClassifier(criterion='entropy')\nparam_grid = {'max_depth': [4, 8, 16, 20], \n 'min_samples_leaf': [1, 2, 4, 8, 16] }\n\nsearch_param(classifier, param_grid)", "Best estimator = DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=20,\n max_features=None, max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, presort=False,\n random_state=None, splitter='best')\nA = 96.00%, C = 98.78%, P = 93.46%\n" ] ], [ [ "## Random Forest Classifier\n\nThe thought of Random Forest is to build a series of Decision Trees, hence forms the Random Forest Classifier (RFC), which uses a subset data to train a number of trees and calculate ensemble average for classes. Comparing with Decision Trees, the RFC tries to overcome the problems such as over-fitting, and provides a wider transferability. [*Gao, Zhang, & Zhao (2009)*](https://iopscience.iop.org/article/10.1088/1674-4527/9/2/011) also study the usage of RFC in astronomical context. \n\nIn this paper we use the [`sklearn.ensemble.RandomForestClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier). We search for the key hyper-parameter of Decision Trees number $n$ with the range $100 \\le n \\le 500$. We reach the result of $n = 350$. ", "_____no_output_____" ] ], [ [ "import sklearn.ensemble\n\nclassifier = sklearn.ensemble.RandomForestClassifier()\nparam_grid = {'n_estimators': [100, 200, 350, 500]}\n\nsearch_param(classifier, param_grid)", "Best estimator = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=350,\n n_jobs=None, oob_score=False, random_state=None,\n verbose=0, warm_start=False)\nA = 97.00%, C = 97.15%, P = 96.76%\n" ] ], [ [ "## Gaussian Naive Bayes\n\nThe Gaussian Naive Bayes (GNB) is an extension of naive Bayes classifying method. It assumes a Gaussian distribution of the input data to carry Naive Bayes, that calculate the label category base on conditional probabilities from the dataset. The Naive Bayes and GNB are basic and simple solutions to categorical data with a wide range of usage ([*Chan, Golub, & LeVeque 1979*](http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf)). \n\nWe directly use the [`sklearn.naive_bayes.GaussianNB`](https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB). There is no parameter to set. ", "_____no_output_____" ] ], [ [ "import sklearn.naive_bayes\n\nclassifier = sklearn.naive_bayes.GaussianNB()\nparam_grid = {}\n\nsearch_param(classifier, param_grid)", "Best estimator = GaussianNB(priors=None, var_smoothing=1e-09)\nA = 69.00%, C = 47.15%, P = 82.27%\n" ] ], [ [ "The parameter optimization results are displayed in the following table:\n\n| Model | Parameters | Parameters Range | Optimal Result |\n|:-------:|:---------------------------------:|:------------------:|:---------------------:|\n| **SVM** | $C$ | $[0.1, 1000]$ | $5$ |\n| **SVM** | $\\mathrm{gamma}$ | $[10^{-7}, 0.1]$ | $2\\times 10^{-6}$ |\n| **kNN** | $k$ | $[1, 500]$ | $10$ |\n| **DTC** | $\\mathrm{maximum\\ tree\\ depth}$ | $[4, 20]$ | $4$ |\n| **DTC** | $\\mathrm{minimum\\ leaf\\ samples}$ | $[1, 16]$ | $2$ |\n| **RFC** | $n$ | $[100, 500]$ | $350$ |\n| **GNB** | - | - | - |", "_____no_output_____" ], [ "# Results\n---\n\nWe then use each classifiers with optimal parameters to fit the full dataset and evaluate their performances. We also fit the classifiers on each dataset of magnitude groups, then use the trained models to predict labels on every magnitude groups, to look into the training transferability and model generality. To maintain the experiment comparabilit, we use the same data folds of $1,500$ training samples and $500$ testing oneach magnitude group. ", "_____no_output_____" ] ], [ [ "import sklearn.svm, sklearn.neighbors, sklearn.tree, sklearn.ensemble, sklearn.naive_bayes\n\nclf_lst = [sklearn.svm.SVC(\n kernel='rbf', C=5, gamma=2e-6, \n class_weight='balanced', degree=3, verbose=False), \n sklearn.neighbors.KNeighborsClassifier(\n n_neighbors=10), \n sklearn.tree.DecisionTreeClassifier(\n criterion='entropy', \n max_depth=4, min_samples_leaf=2),\n sklearn.ensemble.RandomForestClassifier(\n n_estimators=350, verbose=False),\n sklearn.naive_bayes.GaussianNB()]\nname_lst = ['SVM', 'kNN', 'DTC', 'RFC', 'GNB']", "_____no_output_____" ] ], [ [ "## Performance on Different Magnitude Groups\n\nWe study the model performance between different datasets using a method called cross-prediction. For each model with optimal parameters, we first train it on one of the magnitude groups, then use the metrics $A$, $C$, and $P$ to evaluate prediction on all six groups to examine the model training transferability. Testing results on all six training groups forms a matrix for each metric, that demonstrate the model separation performance when the dataset is altered. \n\nThe overall experiments results show that models usually perform best when training and testing magnitude ranges are matched. As magnitude decreases, the models accuracy usually decrease correspondingly, and this is mainly due to the decrease of completeness, which indicated that more dim galaxies are recognized as stars. This result is understandable from the data. It is also consistent with the following phenomenon. When trained on a brighter magnitude dataset and tested on a dimmer one, all models experience the issue of low completeness, but the degrees differ. On the opposite, when trained on a low magnitude range and tested on a brighter one, most models share the issue of low purity. It can lead to the conclusion that when training classifiers on a specific magnitude group, it is common that the models would over-fit to the dataset and have weak transferability to other magnitude range. \n\nTHe performance of whole dataset training is the first row of each matrix. Such training provides models a better transferability among magnitude ranges. There is still some loss when the object is too dim. It is foreseeable that to prevent models fail on distance and dim objects, one practical solution is to include low-magnitude objects in training data. \n\nFrom the aspect of classifiers, whole-data trained SVM and RFC achieve accuracy over 99% on ll testing groups, followed by kNN and DTC with suboptimal results. The SVM suffers greatest performance decrease when training and testing groups are not matched. ", "_____no_output_____" ] ], [ [ "def cross_predict(clf):\n '''Train and test classifier on each dataset combination.'''\n mat_metric = np.empty((6, 6, 3))\n\n for data_train in range(6):\n if data_train == 0:\n f, d = load_data_all()\n else:\n f, d = load_data(14 + data_train)\n x_tr, _, y_tr, _ = load_sample(f, d, random_state=42)\n\n# print('data_train =', data_train)\n clf.fit(x_tr, y_tr)\n\n for data_test in range(6):\n if data_test == 0:\n f, d = load_data_all()\n else:\n f, d = load_data(14 + data_test)\n _, x_ts, _, y_ts = load_sample(f, d, random_state=42)\n\n y_pred = clf.predict(x_ts)\n mat_metric[data_train, data_test, :] = \\\n metric(sklearn.metrics.confusion_matrix(y_ts, y_pred, labels=range(2)))\n return mat_metric", "_____no_output_____" ], [ "mat_metric_lst = np.empty([5, 6, 6, 3])\n\nfor i in range(5):\n mat_metric = cross_predict(clf_lst[i])\n mat_metric_lst[i, :] = mat_metric", "_____no_output_____" ] ], [ [ "We then plot the generated matrixs. ", "_____no_output_____" ] ], [ [ "cmap = plt.cm.coolwarm_r\nctext = lambda x: 'w' if (x > 85 or x < 15) else (72/256,72/256,72/256)\nlabel = ['[15, 20]'] + [('[%d, %d]' % (mag, mag+1)) for mag in range(15, 20)]\n\ndef plot_metrics(mat_metric, name):\n '''Plot three metric matrixes of a given classifier.'''\n mat_a, mat_c, mat_p = mat_metric[:,:,0], mat_metric[:,:,1], mat_metric[:,:,2]\n fig, (ax_a, ax_c, ax_p) = plt.subplots(1, 3, figsize=(14.5, 4))\n fig.subplots_adjust(wspace = 0.2, hspace = 0.4)\n fig.suptitle('Cross-Prediction Results of ' + name, \n x=0.52, y=0.99995, fontweight='bold')\n\n # plot accuracy\n img_a = ax_a.imshow(mat_a, interpolation='nearest', \n cmap=cmap, vmin=0, vmax=100)\n # set labels\n ax_a.set(xticks=np.arange(6), yticks=np.arange(6),\n xticklabels=label, yticklabels=label,\n title='Cross-Prediction Accuracy',\n ylabel='Train Magnitude', xlabel='Test Magnitude')\n # set annotations \n for i in range(6):\n for j in range(6):\n ax_a.text(j, i, format(mat_a[i, j], '0.1f'),\n ha='center', va='center',\n color=ctext(mat_a[i, j]))\n\n # plot completeness\n img_c = ax_c.imshow(mat_c, interpolation='nearest', \n cmap=cmap, vmin=0, vmax=100)\n # set labels\n ax_c.set(xticks=np.arange(6), yticks=np.arange(6),\n xticklabels=label, yticklabels=label,\n title='Cross-Prediction Completeness',\n ylabel='Train Magnitude', xlabel='Test Magnitude')\n # set annotations \n for i in range(6):\n for j in range(6):\n ax_c.text(j, i, format(mat_c[i, j], '0.1f'),\n ha='center', va='center',\n color=ctext(mat_c[i, j]))\n\n # plot purity\n img_p = ax_p.imshow(mat_p, interpolation='nearest', \n cmap=cmap, vmin=0, vmax=100)\n ax_p.figure.colorbar(img_p, ax=ax_p)\n # set labels\n ax_p.set(xticks=np.arange(6), yticks=np.arange(6),\n xticklabels=label, yticklabels=label,\n title='Cross-Prediction Purity',\n ylabel='Train Magnitude', xlabel='Test Magnitude')\n # set annotations \n for i in range(6):\n for j in range(6):\n ax_p.text(j, i, format(mat_p[i, j], '0.1f'),\n ha='center', va='center',\n color=ctext(mat_p[i, j]))\n\n fig.tight_layout()\n plt.show()", "_____no_output_____" ], [ "for i in range(5):\n mat_metric = mat_metric_lst[i, :]\n plot_metrics(mat_metric, name_lst[i])", "_____no_output_____" ] ], [ [ "## Performance on Different Models\n\nFrom the cross-prediction results above, we can compare performance between models. Here we plot the performance verses magnitude for every models training and testing individually on the same dataset, which is the diagonal of each cross-prediction matrix above. \n\nOverall, the RFC achieves best accuracy and completeness and remains robust when magnitude decreases. The DTC also has notable performances on low magnitude groups, possibly due to its ability to extract data features. SVM and kNN give good results if fitted well, but produce less generality. ", "_____no_output_____" ] ], [ [ "cmap = plt.cm.Set3(np.arange(3, 8))\n\nfig, (ax_a, ax_c, ax_p) = plt.subplots(1, 3, figsize=(18, 4))\nfig.subplots_adjust(wspace = 0.2, hspace = 0.4)\nfig.suptitle('Individual Training Results of Models', y=0.9999, fontweight='bold')\n\nfor i in range(5):\n # get the diagonals\n p_a, p_c, p_p = mat_metric_lst[i, :, :, 0].diagonal(), mat_metric_lst[i, :, :, 1].diagonal(), mat_metric_lst[i, :, :, 2].diagonal()\n ax_a.plot(np.arange(6), p_a, 'o-', alpha=0.6,\n c=cmap[i], label=name_lst[i])\n ax_c.plot(np.arange(6), p_c, 'o-', alpha=0.6,\n c=cmap[i], label=name_lst[i])\n ax_p.plot(np.arange(6), p_p, 'o-', alpha=0.6,\n c=cmap[i], label=name_lst[i])\n \nax_a.set(xticks=np.arange(6), xticklabels=label, \n ylim=[89.5, 100.5],\n title='Cross-Prediction Accuracy',\n ylabel='Test Accuracy', xlabel='Train Magnitude')\nax_a.legend(loc=3, ncol=2)\nax_c.set(xticks=np.arange(6), xticklabels=label, \n ylim=[89.5, 100.5],\n title='Cross-Prediction Completeness',\n ylabel='Test Completeness', xlabel='Train Magnitude')\nax_c.legend(loc=3, ncol=2)\nax_p.set(xticks=np.arange(6), xticklabels=label, \n ylim=[89.5, 100.5],\n title='Cross-Prediction Purity',\n ylabel='Test Purity', xlabel='Train Magnitude')\nax_p.legend(loc=3, ncol=2)", "_____no_output_____" ] ], [ [ "The testing results metrics of each models on the whole dataset are displayed in the following table:\n\n| Model | Accuracy | Completeness | Purity |\n|:-------:|:------------:|:------------:|:------------:|\n| **SVM** | 98.7% | 98.2% | **99.2%** |\n| **kNN** | 96.9% | 96.7% | 97.1% |\n| **DTC** | 95.9% | 96.3% | 95.5% |\n| **RFC** | **98.8%** | **98.6%** | 99.1% |\n| **GNB** | 69.7% | 52.0% | 80.8% |", "_____no_output_____" ], [ "We also print the performance of models trained on the whole dataset and tested on different groups, i.e. the first rows in former cross-prediction matrix. \n\nIt can be inferred that SVM and RFC are suitable for train on one representative dataset and conduct separation on given input. DTC and kNN are second choices showing less stableness. ", "_____no_output_____" ] ], [ [ "cmap = plt.cm.Set3(np.arange(3, 8))\n\nfig, (ax_a, ax_c, ax_p) = plt.subplots(1, 3, figsize=(18, 4))\nfig.subplots_adjust(wspace = 0.2, hspace = 0.4)\nfig.suptitle('Whole dataset Training Results of Models', y=0.9999, fontweight='bold')\n\nfor i in range(5):\n # get first row\n p_a, p_c, p_p = mat_metric_lst[i, 0, :, 0], mat_metric_lst[i, 0, :, 1], mat_metric_lst[i, 0, :, 2]\n ax_a.plot(np.arange(6), p_a, 'o-', alpha=0.6,\n c=cmap[i], label=name_lst[i])\n ax_c.plot(np.arange(6), p_c, 'o-', alpha=0.6,\n c=cmap[i], label=name_lst[i])\n ax_p.plot(np.arange(6), p_p, 'o-', alpha=0.6,\n c=cmap[i], label=name_lst[i])\n \nax_a.set(xticks=np.arange(6), xticklabels=label, \n ylim=[89.5, 100.5],\n title='Cross-Prediction Accuracy',\n ylabel='Test Accuracy', xlabel='Train Magnitude')\nax_a.legend(loc=3, ncol=2)\nax_c.set(xticks=np.arange(6), xticklabels=label, \n ylim=[89.5, 100.5],\n title='Cross-Prediction Completeness',\n ylabel='Test Completeness', xlabel='Train Magnitude')\nax_c.legend(loc=3, ncol=2)\nax_p.set(xticks=np.arange(6), xticklabels=label, \n ylim=[89.5, 100.5],\n title='Cross-Prediction Purity',\n ylabel='Test Purity', xlabel='Train Magnitude')\nax_p.legend(loc=3, ncol=2)", "_____no_output_____" ] ], [ [ "## Performance on Single Dataset\n\nWe look specifically into the model performance on each single datasets. We use one model to conduct individual training and testing processes on six magnitude groups, i.e., the whole dataset and five subsets of magnitude range with $1.0$ magnitude step. We evaluate the predicting performance by confusion matrix. We adopt the matrix in the form without normalization for a more direct view. To illustrate below, we use Random Forest Classifier, which is the most accurate classifier overall, as an example. \n\nAs magnitude decrease, the accuracy is affected by the increased appearance of $F_g$ and $F_s$, which is consistent with former results. ", "_____no_output_____" ] ], [ [ "label = lambda y: 'Galaxy' if y else 'Star'\n\nclf = clf_lst[3]\nmat_conf_lst = np.empty((6, 2, 2))\nx_wr_lst, y_wr_lst, y_pred_wr_lst = [], [], []\n\nfor data_i in range(6):\n if data_i == 0:\n f, d = load_data_all()\n else:\n f, d = load_data(14 + data_i)\n x_tr, x_ts, y_tr, y_ts = load_sample(f, d, random_state=42)\n\n# print('data_i =', data_i)\n clf.fit(x_tr, y_tr)\n y_pred = clf.predict(x_ts)\n \n # save confusion matrix\n mat_conf_lst[data_i, :] = sklearn.metrics.confusion_matrix(y_ts, y_pred, labels=range(2))\n \n # save one example for printing below\n idx_lst = (y_pred != y_ts)\n assert len(np.nonzero(idx_lst)) > 0, 'Perfect Model!'\n idx = np.nonzero(idx_lst)[0][0]\n # reconstruct sample data\n x_wr_lst.append(x_ts[idx].reshape((32, 32, 3)).astype(uint8))\n y_wr_lst.append(label(y_ts[idx]))\n y_pred_wr_lst.append(label(y_pred[idx]))", "_____no_output_____" ] ], [ [ "We visualize the matrixs by following codes. ", "_____no_output_____" ] ], [ [ "cmap = plt.cm.Blues\nctext = lambda x: 'w' if (x > 50) else (72/256,72/256,72/256)\nmname = ['[15, 20]'] + [('[%d, %d]' % (mag, mag+1)) for mag in range(15, 20)]\nlabel = ['Star', 'Galaxy']\npre = [['$T_s$', '$F_s$'], \n ['$F_g$', '$T_g$']]\n\ndef plot_confusion(mat_conf, ax, mag):\n '''Plot confusion matrix on given axis.'''\n img = ax.imshow(mat_conf, interpolation='nearest', cmap=cmap)\n A, C, P = metric(mat_conf)\n \n # set labels\n ax.set(xticks=np.arange(2), yticks=np.arange(2),\n xticklabels=label, yticklabels=label,\n title='$mag$=%s \\n $A$=%0.1f, $C$=%0.1f, $P$=%0.1f' % (mag, A, C, P),\n ylabel='True Label', xlabel='Predicted Label')\n # set annotations \n for i in range(2):\n for j in range(2):\n ax.text(j, i, pre[i][j] + '=' + format(mat_conf[i, j], '0.0f'),\n ha='center', va='center',\n color=ctext(mat_conf[i, j]))\n \n return img", "_____no_output_____" ], [ "fig, ax = plt.subplots(1, 6, figsize=(18, 4))\nfig.subplots_adjust(wspace = 0.2, hspace = 0.4)\nfig.suptitle('Confusion Matrixs of Individual Training RFC', fontweight='bold')\n\nfor data_i in range(6):\n mat_conf = mat_conf_lst[data_i, :]\n img = plot_confusion(mat_conf, ax[data_i], mname[data_i])\n \nfig.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "Here are examples of images and wrongly-predicted labels in each group, which gives some possible explanation on the errors. It can be see that low magnitude objects can hardly classified by eyes. ", "_____no_output_____" ] ], [ [ "# prepare figure\nfig, axs = plt.subplots(1, 5, figsize=(18, 5))\nfig.subplots_adjust(hspace = 0.1, wspace = 0.15)\nfig.suptitle('Examples of Images and Labels', y=0.92)\n\nfor data_i in range(5):\n axs[data_i].imshow(x_wr_lst[data_i])\n axs[data_i].set_title('$mag$=[%d, %d] \\n True: %s, Predict: %s' % (data_i+15, data_i+16, y_wr_lst[data_i], y_pred_wr_lst[data_i]))", "_____no_output_____" ] ], [ [ "# Conclusion and Discussion\n---\n\nIn this work, we apply supervised machine learning models to solve the Star/Galaxy Separation Problem. We explore the optimal parameters settings of each model to achieve the best classification accuracy on visual magnitude range $[15, 20]$. We then evaluate the models performance by three metrics accuracy $A$, completeness $C$, and purity $P$. We study the relationship between results and training/testing magnitude range and discuss the issue and causes of metrics decrease. We also compare different models in the given context. \n\nWhen image data are the only and direct input to models, it exists a problem that the classification accuracy will decrease when separating objects of lower magnitude. This is mainly due to the decline of galaxy completeness, that is, dim galaxies are identified as stars. This issue is severer for some models in particular, such as SVM, which calls for a more representative dataset and proper training. Our experiments show that training on the dataset includes different magnitude range will alleviate such problem, which would be a possible solution leading to better SGSP classifiers. By this study we offer a practical way and several models to conduct SGSP tasks directly and solely on images. Our work may also contribute to the research and application of SGSP approaches with the results on model performance and magnitude relation. \n\nDue to the time and requirement limitations, neural networks, which is a superior and important branch of SGSP machine learning models, are not able to be included in experiments. Similar studies can be carried on neural networks, especially CNN, to explore their unique characteristic and generality. Also, recent development of theories and observation technologies have raised the interest on deep space objects. A wider study magnitude range is another meaningful extension. ", "_____no_output_____" ], [ "# Acknowledgement\n---\n\nThis work is the final project of ASTRO 9, summer, 2019. Special thanks to Professor Ben Horowitz. \n\nCitations and references links are given in the text. ", "_____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" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "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" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec4f3c8db67065e12245ea721efa9579b2c49ea4
18,826
ipynb
Jupyter Notebook
notebooks/105-language-quantize-bert/105-language-quantize-bert.ipynb
AlexKoff88/openvino_notebooks
0946f78a7869cc94030033294c8cc6be024c40de
[ "Apache-2.0" ]
null
null
null
notebooks/105-language-quantize-bert/105-language-quantize-bert.ipynb
AlexKoff88/openvino_notebooks
0946f78a7869cc94030033294c8cc6be024c40de
[ "Apache-2.0" ]
null
null
null
notebooks/105-language-quantize-bert/105-language-quantize-bert.ipynb
AlexKoff88/openvino_notebooks
0946f78a7869cc94030033294c8cc6be024c40de
[ "Apache-2.0" ]
null
null
null
35.188785
690
0.57495
[ [ [ "# Accelerate Inference of NLP models with OpenVINO Post-Training Optimization Tool ​\nThis tutorial demostrates how to apply INT8 quantization to the Natural Language Processing model BERT, using the [Post-Training Optimization Tool API](https://docs.openvinotoolkit.org/latest/pot_compression_api_README.html) (part of the [OpenVINO Toolkit](https://docs.openvinotoolkit.org/)). We will use a fine-tuned [HuggingFace BERT](https://huggingface.co/transformers/model_doc/bert.html) [PyTorch](https://pytorch.org/) model trained for [Microsoft Research Paraphrase Corpus (MRPC)](https://www.microsoft.com/en-us/download/details.aspx?id=52398) task. The code of the tutorial is designed to be extendable to custom models and datasets. It consists of the following steps:\n\n- Download and prepare the MRPC model and dataset\n- Define data loading and accuracy validation functionality\n- Prepare the model for quantization\n- Run optimization pipeline\n- Compare performance of the original and quantized models", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport time\nimport warnings\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom addict import Dict\nfrom compression.api import DataLoader as POTDataLoader\nfrom compression.api import Metric\nfrom compression.engines.ie_engine import IEEngine\nfrom compression.graph import load_model, save_model\nfrom compression.graph.model_utils import compress_model_weights\nfrom compression.pipeline.initializer import create_pipeline\nfrom compression.utils.logger import get_logger, init_logger\nfrom torch.utils.data import TensorDataset\nfrom transformers import BertForSequenceClassification, BertTokenizer\nfrom transformers import glue_convert_examples_to_features as convert_examples_to_features\nfrom transformers import glue_output_modes as output_modes\nfrom transformers import glue_processors as processors", "_____no_output_____" ], [ "DATA_DIR = \"data\"\nMODEL_DIR = \"model\"\n\nos.makedirs(DATA_DIR, exist_ok=True)\nos.makedirs(MODEL_DIR, exist_ok=True)", "_____no_output_____" ] ], [ [ "## Prepare the Model\nNext steps include:\n- Download and unpack pre-trained BERT model for MRPC by PyTorch\n- Convert model to ONNX\n- Run OpenVINO Model Optimizer tool to convert the model from the ONNX representation to the OpenVINO Intermediate Representation (IR)", "_____no_output_____" ] ], [ [ "!curl https://download.pytorch.org/tutorial/MRPC.zip --output $MODEL_DIR/MRPC.zip\n!unzip -n $MODEL_DIR/MRPC.zip -d $MODEL_DIR", "_____no_output_____" ] ], [ [ "Import all dependencies to load the original PyTorch model and convert it to the ONNX representation.", "_____no_output_____" ] ], [ [ "BATCH_SIZE = 1\nMAX_SEQ_LENGTH = 128\n\n\ndef export_model_to_onnx(model, path):\n with torch.no_grad():\n default_input = torch.ones(1, MAX_SEQ_LENGTH, dtype=torch.int64)\n inputs = {\n \"input_ids\": default_input,\n \"attention_mask\": default_input,\n \"token_type_ids\": default_input,\n }\n outputs = model(**inputs)\n symbolic_names = {0: \"batch_size\", 1: \"max_seq_len\"}\n torch.onnx.export(\n model,\n (inputs[\"input_ids\"], inputs[\"attention_mask\"], inputs[\"token_type_ids\"]),\n path,\n opset_version=11,\n do_constant_folding=True,\n input_names=[\"input_ids\", \"input_mask\", \"segment_ids\"],\n output_names=[\"output\"],\n dynamic_axes={\n \"input_ids\": symbolic_names,\n \"input_mask\": symbolic_names,\n \"segment_ids\": symbolic_names,\n },\n )\n print(\"ONNX model saved to {}\".format(path))\n\n\ntorch_model = BertForSequenceClassification.from_pretrained(os.path.join(MODEL_DIR, \"MRPC\"))\nonnx_model_path = Path(MODEL_DIR) / \"bert_mrpc.onnx\"\nif not onnx_model_path.exists():\n export_model_to_onnx(torch_model, onnx_model_path)", "_____no_output_____" ] ], [ [ "Then convert the ONNX model using OpenVINO Model Optimizer with the required parameters.", "_____no_output_____" ] ], [ [ "ir_model_xml = onnx_model_path.with_suffix(\".xml\")\nir_model_bin = onnx_model_path.with_suffix(\".bin\")\n\nif not ir_model_xml.exists():\n !mo --input_model $onnx_model_path --output_dir $MODEL_DIR --model_name bert_mrpc --input input_ids,input_mask,segment_ids --input_shape [1,128],[1,128],[1,128] --output output --data_type FP16", "_____no_output_____" ] ], [ [ "## Prepare MRPC Task Dataset\n\nTo run this tutorial, you will need to download the GLUE data part for MRPC task from HuggingFace.\nThe following cells will download a script with functions to download data, and run the function to download and unpack GLUE data.", "_____no_output_____" ] ], [ [ "!curl https://raw.githubusercontent.com/huggingface/transformers/f98ef14d161d7bcdc9808b5ec399981481411cc1/utils/download_glue_data.py --output download_glue_data.py", "_____no_output_____" ], [ "from download_glue_data import format_mrpc\n\nos.makedirs(DATA_DIR, exist_ok=True)\nformat_mrpc(DATA_DIR, \"\")", "_____no_output_____" ] ], [ [ "## Define DataLoader for POT\nIn this step, we need to define `DataLoader` based on POT API. This loader will be used to collect statistics for quantization and run model evaluation.", "_____no_output_____" ] ], [ [ "class MRPCDataLoader(POTDataLoader):\n # Required methods\n def __init__(self, config):\n \"\"\"Constructor\n :param config: data loader specific config\n \"\"\"\n if not isinstance(config, Dict):\n config = Dict(config)\n super().__init__(config)\n self._task = config[\"task\"].lower()\n self._model_dir = config[\"model_dir\"]\n self._data_dir = config[\"data_source\"]\n self._batch_size = config[\"batch_size\"]\n self._max_length = config[\"max_length\"]\n self._prepare_dataset()\n\n def __len__(self):\n \"\"\"Returns size of the dataset\"\"\"\n return len(self.dataset)\n\n def __getitem__(self, index):\n \"\"\"\n Returns annotation, data and metadata at the specified index.\n Possible formats:\n (index, annotation), data\n (index, annotation), data, metadata\n \"\"\"\n if index >= len(self):\n raise IndexError\n\n batch = self.dataset[index]\n batch = tuple(t.detach().cpu().numpy() for t in batch)\n inputs = {\"input_ids\": batch[0], \"input_mask\": batch[1], \"segment_ids\": batch[2]}\n labels = batch[3]\n return (index, labels), inputs\n\n # Methods specific to the current implementation\n def _prepare_dataset(self):\n \"\"\"Prepare dataset\"\"\"\n tokenizer = BertTokenizer.from_pretrained(self._model_dir, do_lower_case=True)\n processor = processors[self._task]()\n output_mode = output_modes[self._task]\n label_list = processor.get_labels()\n examples = processor.get_dev_examples(self._data_dir)\n features = convert_examples_to_features(\n examples,\n tokenizer,\n label_list=label_list,\n max_length=self._max_length,\n output_mode=output_mode,\n )\n all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)\n all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)\n all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)\n all_labels = torch.tensor([f.label for f in features], dtype=torch.long)\n self.dataset = TensorDataset(\n all_input_ids, all_attention_mask, all_token_type_ids, all_labels\n )", "_____no_output_____" ] ], [ [ "## Define Accuracy Metric Calculation\nAt this step the `Metric` interface for MRPC task metrics is implemented. It is used for validating accuracy of models.", "_____no_output_____" ] ], [ [ "class Accuracy(Metric):\n\n # Required methods\n def __init__(self):\n super().__init__()\n self._name = \"Accuracy\"\n self._matches = []\n\n @property\n def value(self):\n \"\"\"Returns accuracy metric value for the last model output.\"\"\"\n return {self._name: self._matches[-1]}\n\n @property\n def avg_value(self):\n \"\"\"Returns accuracy metric value for all model outputs.\"\"\"\n return {self._name: np.ravel(self._matches).mean()}\n\n def update(self, output, target):\n \"\"\"Updates prediction matches.\n :param output: model output\n :param target: annotations\n \"\"\"\n if len(output) > 1:\n raise Exception(\n \"The accuracy metric cannot be calculated \" \"for a model with multiple outputs\"\n )\n output = np.argmax(output)\n match = output == target[0]\n self._matches.append(match)\n\n def reset(self):\n \"\"\"Resets collected matches\"\"\"\n self._matches = []\n\n def get_attributes(self):\n \"\"\"\n Returns a dictionary of metric attributes {metric_name: {attribute_name: value}}.\n Required attributes: 'direction': 'higher-better' or 'higher-worse'\n 'type': metric type\n \"\"\"\n return {self._name: {\"direction\": \"higher-better\", \"type\": \"accuracy\"}}", "_____no_output_____" ] ], [ [ "## Run Quantization Pipeline\nHere we define a configuration for our quantization pipeline and run it. Please note that we use built-in `IEEngine` implementation of `Engine` interface from the POT API for model inference.", "_____no_output_____" ] ], [ [ "warnings.filterwarnings(\"ignore\") # Suppress accuracychecker warnings\n\nmodel_config = Dict({\"model_name\": \"bert_mrpc\", \"model\": ir_model_xml, \"weights\": ir_model_bin})\nengine_config = Dict({\"device\": \"CPU\"})\ndataset_config = {\n \"task\": \"mrpc\",\n \"data_source\": os.path.join(DATA_DIR, \"MRPC\"),\n \"model_dir\": os.path.join(MODEL_DIR, \"MRPC\"),\n \"batch_size\": BATCH_SIZE,\n \"max_length\": MAX_SEQ_LENGTH,\n}\nalgorithms = [\n {\n \"name\": \"DefaultQuantization\",\n \"params\": {\n \"target_device\": \"ANY\",\n \"model_type\": \"transformer\",\n \"preset\": \"performance\",\n \"stat_subset_size\": 250,\n },\n }\n]\n\n\n# Step 1: Load the model.\nmodel = load_model(model_config)\n\n# Step 2: Initialize the data loader.\ndata_loader = MRPCDataLoader(dataset_config)\n\n# Step 3 (Optional. Required for AccuracyAwareQuantization): Initialize the metric.\nmetric = Accuracy()\n\n# Step 4: Initialize the engine for metric calculation and statistics collection.\nengine = IEEngine(config=engine_config, data_loader=data_loader, metric=metric)\n\n# Step 5: Create a pipeline of compression algorithms.\npipeline = create_pipeline(algorithms, engine)\n\n# Step 6 (Optional): Evaluate the original model. Print the results.\nfp_results = pipeline.evaluate(model)\nif fp_results:\n print(\"FP16 model results:\")\n for name, value in fp_results.items():\n print(f\"{name}: {value:.5f}\")", "_____no_output_____" ], [ "# Step 7: Execute the pipeline.\nwarnings.filterwarnings(\"ignore\") # Suppress accuracychecker warnings\nprint(\n f\"Quantizing model with {algorithms[0]['params']['preset']} preset and {algorithms[0]['name']}\"\n)\nstart_time = time.perf_counter()\ncompressed_model = pipeline.run(model)\nend_time = time.perf_counter()\nprint(f\"Quantization finished in {end_time - start_time:.2f} seconds\")\n\n# Step 8 (Optional): Compress model weights to quantized precision\n# in order to reduce the size of final .bin file.\ncompress_model_weights(compressed_model)\n\n# Step 9: Save the compressed model to the desired path.\ncompressed_model_paths = save_model(\n compressed_model, save_path=MODEL_DIR, model_name=\"quantized_bert_mrpc\"\n)\ncompressed_model_xml = compressed_model_paths[0][\"model\"]", "_____no_output_____" ], [ "# Step 10 (Optional): Evaluate the compressed model. Print the results.\nint_results = pipeline.evaluate(compressed_model)\n\nif int_results:\n print(\"INT8 model results:\")\n for name, value in int_results.items():\n print(f\"{name}: {value:.5f}\")", "_____no_output_____" ] ], [ [ "## Compare Performance of the Original and Quantized Models\nFinally, we will measure the inference performance of the FP32 and INT8 models. To do this, we use [Benchmark Tool](https://docs.openvinotoolkit.org/latest/openvino_inference_engine_tools_benchmark_tool_README.html) - OpenVINO's inference performance measurement tool.\n\n> NOTE: For more accurate performance, we recommended running `benchmark_app` in a terminal/command prompt after closing other applications. Run `benchmark_app -m model.xml -d CPU` to benchmark async inference on CPU for one minute. Change `CPU` to `GPU` to benchmark on GPU. Run `benchmark_app --help` to see an overview of all command line options.", "_____no_output_____" ] ], [ [ "## compressed_model_xml is defined after quantizing the model.\n## Uncomment the lines below to set default values for the model file locations.\n# ir_model_xml = \"model/bert_mrpc.xml\"\n# compressed_model_xml = \"model/quantized_bert_mrpc.xml\"", "_____no_output_____" ], [ "# Inference FP16 model (IR)\n! benchmark_app -m $ir_model_xml -d CPU -api async", "_____no_output_____" ], [ "# Inference INT8 model (IR)\n! benchmark_app -m $compressed_model_xml -d CPU -api async", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ec4f3e88309a77ac19ab269b80a4ebf8c7e17fb8
7,339
ipynb
Jupyter Notebook
Untitled.ipynb
shujalraj/DefaultWeb
bdfa3d84066a636d1b3061b3f8cffa3bf9b61135
[ "MIT" ]
null
null
null
Untitled.ipynb
shujalraj/DefaultWeb
bdfa3d84066a636d1b3061b3f8cffa3bf9b61135
[ "MIT" ]
null
null
null
Untitled.ipynb
shujalraj/DefaultWeb
bdfa3d84066a636d1b3061b3f8cffa3bf9b61135
[ "MIT" ]
null
null
null
90.604938
5,673
0.643821
[ [ [ "opened_file = open('D:\\\\Study Material\\\\Python\\\\food-price-index-april-2019-csv\\\\File3.csv')\nfrom csv import reader\nread_file = reader(opened_file)\napps_data = list(read_file)\n\n# INITIAL FUNCTION\ndef freq_table(index):\n frequency_table = {}\n \n for row in apps_data[1:]:\n value = row[index]\n if value in frequency_table:\n frequency_table[value] += 1\n else:\n frequency_table[value] = 1\n return frequency_table\nratings_ft = freq_table(7)\nprint (ratings_ft)", "{'Oranges, 1kg': 155, 'Bananas, 1kg': 155, 'Apples, 1kg': 155, 'Kiwifruit, 1kg': 155, 'Sultanas (supermarket only), 375g': 155, 'Peaches - canned (supermarket only), 410g': 155, 'Lettuce, 1kg': 155, 'Broccoli, 1kg': 155, 'Cabbage, 1kg': 155, 'Tomatoes, 1kg': 155, 'Carrots, 1kg': 155, 'Mushrooms, 1kg': 155, 'Potatoes, 1kg': 155, 'Peas - frozen (supermarket only), 1kg': 155, 'Beef steak - blade, 1kg': 155, 'Beef steak - porterhouse/sirloin, 1kg': 155, 'Beef - mince, 1kg': 155, 'Pork - loin chops, 1kg': 155, 'Lamb - chops, 1kg': 155, 'Sausages, 1kg': 155, 'Tuna - canned (supermarket only), 185g': 155, 'Biscuits - chocolate, 200g': 155, 'Breakfast biscuits, 1kg': 155, 'Flour - white (supermarket only), 1.5kg': 155, 'Rice - long grain, white (supermarket only), 1kg': 155, 'Milk - standard homogenised, 2 litres': 155, 'Yoghurt - flavoured, 150g pottle (supermarket only), pk of 6': 155, 'Cheese - mild cheddar (supermarket only), 1kg': 155, 'Eggs, dozen': 155, 'Butter - salted, 500g': 155, 'Sugar - white, 1.5kg': 155, 'Chocolate - block (supermarket only), 250g': 155, 'Spaghetti - canned, 420g': 155, 'Coffee - instant, 100g': 155, 'Tea bags (supermarket only), box of 100': 155, 'Soft drink, 1.5 litres': 155, 'Bottled water, 750ml': 155, 'Fish and chips, One fish/chips': 155, 'Meat pie - hot, each': 155, 'Fruit juice - apple based (supermarket only), 3 litre': 95, 'Potato crisps, 150g': 95, 'Tomato sauce - canned, 560g': 95, 'Bacon - middle rashers (supermarket only), 700g': 59, 'Chicken breast, 1kg': 59, 'Bread - white sliced loaf, 600g': 155, 'Apricots, dried, 100g': 94, 'Avocado, 1kg': 147, 'Baby food, 110g': 147, 'Beans, 1kg': 147, 'Bread rolls, filled, hot, each': 147, 'Bread rolls, hamburger buns, 6 pack': 147, 'Breakfast drink, 250ml, 6 pack': 58, 'Burger, with or without accompaniments, each': 147, 'Soup, canned, 500g': 147, 'Capsicums, green, else red, 1kg': 147, 'Cauliflower, 1kg': 147, 'Celery, 1kg': 147, 'Cheese, camembert, 125g': 147, 'Cheese, processed slices, 250g': 147, 'Chicken, cooked, whole, No. 15 - Cheapest Available': 130, 'Chicken pieces (excluding breast), boneless or bone in, 1kg': 58, 'Chicken, whole, frozen, No. 15 - Cheapest Available': 147, 'Chicken nuggets, frozen, 1kg': 94, 'Chilled fruit juice or smoothies, 1 to 1.5 litre': 130, 'Chocolate, boxed, loose, 250g': 147, 'Chocolate blocks, convenience stores, 100g to 250g': 147, 'Chocolate novelty bars, 50g': 147, 'Corn flakes, 500g': 147, 'Corned beef, fresh, chilled or frozen, 1kg': 147, 'Courgettes, 1kg': 147, 'Biscuits, savoury, crackers 250g': 147, 'Cream, 300ml - Cheapest Available': 147, 'Cucumber, 1kg': 147, 'Dessert, frozen, 500g': 130, 'Fruit flavoured drink powder, multipack of 3 to 5': 147, 'Dried pasta, spaghetti or other type, 500g': 130, 'Drinking chocolate, 300g': 147, 'Milk, calcium enriched, 2 litres': 147, 'Fish fillets, frozen, multipack, 500g': 147, 'Flat bread - pita, tortilla, or other type': 94, 'Eggs, free range, 6 pack': 130, 'Fresh fish, 1kg': 147, 'Fresh pasta, tortellini or other filled type, 300g': 130, 'Fried and other takeaway chicken, 5 pieces': 147, 'Berries, frozen, 500g': 94, 'Grapes, green or red': 147, 'Coffee, ground, 200g': 147, 'Honey, clover, creamed, 500g': 147, 'Hot chips, hot wedges': 147, 'Hummus dip, 200g': 130, 'Ice block, water based, each': 147, 'Ice cream bought in bulk, 2 litres': 147, 'Ice cream novelty, chocolate coated, each': 147, 'Infant formula, 900g': 147, 'Jam, 375g': 147, 'Kumara, 1kg': 147, 'Mandarins, 1kg': 147, 'Mussels, marinated, 375g': 147, 'Meat pies, chilled, 6 or 8 pack - Cheapest Available': 147, 'Mixed vegetables, frozen, 1kg': 147, 'Muesli, natural or toasted, 750g': 147, 'Muesli/cereal bars, 200g': 130, 'Mussels, live, 1kg': 147, 'Sandwich, fresh or toasted': 155, 'Olive oil, pure, not extra virgin or light, 1 litre': 147, 'Onions, 1kg': 147, 'Orange juice, not apple based, 1 litre - Cheapest Available': 94, 'Packaged cake slice, 300g': 147, 'Parsnips, 1kg': 147, 'Packaged meal, pasta and sauce, 130g': 147, 'Pasta sauces, tomato based, 500g': 147, 'Pastry, frozen sheets, puff or flaky, 800g': 147, 'Pears, 1kg': 147, 'Pineapple, pieces, in juice or syrup, canned, 425g': 147, 'Pineapple, 1kg': 130, 'Biscuits, plain (eg arrowroot, ginger, malt, wine), 250g': 147, 'Potato fries, frozen, 1kg': 147, 'Prawns, frozen, 700g': 58, 'Prepared meals, frozen, 340g': 147, 'Pumpkin, 1kg': 147, 'Roasting lamb and hogget, fresh, chilled or frozen, 1kg': 147, 'Roasting pork, fresh, chilled or frozen, 1kg': 147, 'Salad, leaf, packaged, 150g': 58, 'Salami, 100g': 147, 'Salmon, imported, pink, canned, unflavoured, 210g': 147, 'Soft drinks, poured': 147, 'Soft drinks, 600ml': 147, 'Soy milk, unflavoured, 1 litre': 130, 'Soy sauce, 300ml': 147, 'Sports energy drinks, 350ml': 58, 'Sports energy drinks, 250ml': 58, 'Two minute noodles, multipack,5': 147, 'Peanut butter, not salt free, 375g': 155, 'Sweets, 200g': 147, 'Cakes and biscuits, takeaway': 147, 'Coffee, takeway, each': 147, 'Cookie, takeaway, each': 147, 'Takeaway muffins and buns, each': 147, 'Pizza, takeaway': 147, 'Salad, takeaway, vegetable, 1kg': 147, 'Tea, takeaway': 147, 'Tomatoes, canned, 400g': 147, 'Vinegar, 750ml': 147, 'Wheatmeal bread, sliced, 700g': 147, 'Wholegrain bread, sliced, 700g': 147, 'Fresh herbs, packaged, chilled': 19, 'Olives, jar, 400g': 19, 'Tea bags, flavoured or herbal, box of 25': 19, 'Pizza, fresh or frozen, with any standard topping, each': 155, 'Margarine/table spread, 500g': 155, 'Mayonnaise, 380ml': 155, 'Dried mixed herbs, 10g to 15g': 155, 'Peanuts, blanched, salted, 250g': 155, 'Ham, sliced or shaved, 1kg': 155, 'Chewing gum, packet, each': 131}\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
ec4f4cb26a706c996c07b9f794c81a69a4695004
246,409
ipynb
Jupyter Notebook
Compare Activation Functions/Compare Activation Functions.ipynb
snoor-projects/Case-Studies
7eaec53eac861e9c869059e7ef6f33521ca3b5ce
[ "MIT" ]
null
null
null
Compare Activation Functions/Compare Activation Functions.ipynb
snoor-projects/Case-Studies
7eaec53eac861e9c869059e7ef6f33521ca3b5ce
[ "MIT" ]
null
null
null
Compare Activation Functions/Compare Activation Functions.ipynb
snoor-projects/Case-Studies
7eaec53eac861e9c869059e7ef6f33521ca3b5ce
[ "MIT" ]
null
null
null
270.779121
57,724
0.907524
[ [ [ "# Created by:\n## Shubhnoor Gill\n## 18BCS6061\n## B.E. CSE(AIML)-1\n## Group-B", "_____no_output_____" ], [ "# Comparison of Activation Functions using MNIST Dataset\n\nFor this purpose, a simple ANN model was used for the MNIST dataset.\n- Rectified Linear Unit(ReLU) Function\n- Sigmoid Function\n- Hyperbolic Tangent Function\n- Swish Function\n- Scaled Exponential Linear Unit (SELU) Function\n\nThe loss, validation, training accuracy for the different activation function with the respective plots is shown in this notebook.", "_____no_output_____" ] ], [ [ "# Importing the required libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom keras.datasets import mnist\nfrom keras.utils import plot_model\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils import np_utils # used for categorisation\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam", "Using TensorFlow backend.\n" ], [ "# Unpacking dataset into train and test\n(X_train, y_train), (X_test, y_test) = mnist.load_data()", "_____no_output_____" ], [ "X_train.shape", "_____no_output_____" ], [ "# Data Pre-processing\n\nn = X_train.shape[1] * X_train.shape[2] # flatten this array into a vector of 28×28=784\nX_train = X_train.reshape(X_train.shape[0], n).astype('float32') #type to cast one or more of the DataFrame's columns to column-specific types.\nX_test = X_test.reshape(X_test.shape[0], n).astype('float32')\nX_train = X_train / 255 # convert into fully black and fully white\nX_test = X_test / 255\ny_train = np_utils.to_categorical(y_train) # digits are 0-9, so we have 10 classes, one hot encoding\ny_test = np_utils.to_categorical(y_test) #Converts a class vector (integers) to binary class matrix.\nnum_classes = y_test.shape[1]", "_____no_output_____" ], [ "X_train.shape ", "_____no_output_____" ], [ "X_test.shape", "_____no_output_____" ] ], [ [ "## Rectified Linear Unit (ReLU) Activation Function", "_____no_output_____" ] ], [ [ "RELU_model = Sequential()\n\nRELU_model.add(Dense(500, input_dim=n, activation='relu'))\n\nRELU_model.add(Dense(100, activation='relu'))\n\nRELU_model.add(Dense(num_classes, activation='softmax'))\n\n# Compile model\n\nRELU_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nRELU_model.summary()", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_1 (Dense) (None, 500) 392500 \n_________________________________________________________________\ndense_2 (Dense) (None, 100) 50100 \n_________________________________________________________________\ndense_3 (Dense) (None, 10) 1010 \n=================================================================\nTotal params: 443,610\nTrainable params: 443,610\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### Result of Train and Test", "_____no_output_____" ] ], [ [ "hist_relu=RELU_model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)\nscores_relu = RELU_model.evaluate(X_test, y_test)\nprint('Test loss:', scores_relu[0])\nprint('Test accuracy:', scores_relu[1])", "Train on 60000 samples, validate on 10000 samples\nEpoch 1/10\n60000/60000 [==============================] - 2s 35us/step - loss: 0.2723 - accuracy: 0.9215 - val_loss: 0.1248 - val_accuracy: 0.9632\nEpoch 2/10\n60000/60000 [==============================] - 2s 28us/step - loss: 0.0990 - accuracy: 0.9715 - val_loss: 0.0997 - val_accuracy: 0.9685\nEpoch 3/10\n60000/60000 [==============================] - 2s 32us/step - loss: 0.0638 - accuracy: 0.9808 - val_loss: 0.0719 - val_accuracy: 0.9765\nEpoch 4/10\n60000/60000 [==============================] - 2s 31us/step - loss: 0.0442 - accuracy: 0.9869 - val_loss: 0.0623 - val_accuracy: 0.9797\nEpoch 5/10\n60000/60000 [==============================] - 2s 28us/step - loss: 0.0310 - accuracy: 0.9904 - val_loss: 0.0613 - val_accuracy: 0.9811\nEpoch 6/10\n60000/60000 [==============================] - 2s 28us/step - loss: 0.0237 - accuracy: 0.9929 - val_loss: 0.0711 - val_accuracy: 0.9786\nEpoch 7/10\n60000/60000 [==============================] - 2s 32us/step - loss: 0.0176 - accuracy: 0.9943 - val_loss: 0.0657 - val_accuracy: 0.9817\nEpoch 8/10\n60000/60000 [==============================] - 2s 37us/step - loss: 0.0135 - accuracy: 0.9959 - val_loss: 0.0679 - val_accuracy: 0.9798\nEpoch 9/10\n60000/60000 [==============================] - 2s 33us/step - loss: 0.0122 - accuracy: 0.9964 - val_loss: 0.0720 - val_accuracy: 0.9805\nEpoch 10/10\n60000/60000 [==============================] - 2s 36us/step - loss: 0.0104 - accuracy: 0.9968 - val_loss: 0.0692 - val_accuracy: 0.9792\n10000/10000 [==============================] - 1s 84us/step\nTest loss: 0.06924099981761683\nTest accuracy: 0.979200005531311\n" ] ], [ [ "## Sigmoid Activation Function", "_____no_output_____" ] ], [ [ "SIG_model = Sequential()\n\nSIG_model.add(Dense(500, input_dim=n, activation='sigmoid'))\n\nSIG_model.add(Dense(100, activation='sigmoid'))\n\nSIG_model.add(Dense(num_classes, activation='softmax'))\n\n# Compile model\n\nSIG_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nSIG_model.summary()", "Model: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_4 (Dense) (None, 500) 392500 \n_________________________________________________________________\ndense_5 (Dense) (None, 100) 50100 \n_________________________________________________________________\ndense_6 (Dense) (None, 10) 1010 \n=================================================================\nTotal params: 443,610\nTrainable params: 443,610\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### Result of Train and Test", "_____no_output_____" ] ], [ [ "hist_sig=SIG_model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)\nscores_sig = SIG_model.evaluate(X_test, y_test)\nprint('Test loss:', scores_sig[0])\nprint('Test accuracy:', scores_sig[1])", "Train on 60000 samples, validate on 10000 samples\nEpoch 1/10\n60000/60000 [==============================] - 2s 38us/step - loss: 0.7180 - accuracy: 0.8184 - val_loss: 0.3013 - val_accuracy: 0.9162\nEpoch 2/10\n60000/60000 [==============================] - 2s 38us/step - loss: 0.2614 - accuracy: 0.9248 - val_loss: 0.2189 - val_accuracy: 0.9362\nEpoch 3/10\n60000/60000 [==============================] - 3s 44us/step - loss: 0.1986 - accuracy: 0.9421 - val_loss: 0.1752 - val_accuracy: 0.9481\nEpoch 4/10\n60000/60000 [==============================] - 2s 36us/step - loss: 0.1582 - accuracy: 0.9535 - val_loss: 0.1463 - val_accuracy: 0.9555\nEpoch 5/10\n60000/60000 [==============================] - 2s 37us/step - loss: 0.1291 - accuracy: 0.9626 - val_loss: 0.1267 - val_accuracy: 0.9619\nEpoch 6/10\n60000/60000 [==============================] - 2s 29us/step - loss: 0.1059 - accuracy: 0.9690 - val_loss: 0.1075 - val_accuracy: 0.9669\nEpoch 7/10\n60000/60000 [==============================] - 2s 29us/step - loss: 0.0875 - accuracy: 0.9744 - val_loss: 0.0945 - val_accuracy: 0.9704\nEpoch 8/10\n60000/60000 [==============================] - 2s 33us/step - loss: 0.0735 - accuracy: 0.9790 - val_loss: 0.0905 - val_accuracy: 0.9727\nEpoch 9/10\n60000/60000 [==============================] - 2s 26us/step - loss: 0.0611 - accuracy: 0.9825 - val_loss: 0.0805 - val_accuracy: 0.9735\nEpoch 10/10\n60000/60000 [==============================] - 2s 32us/step - loss: 0.0522 - accuracy: 0.9848 - val_loss: 0.0764 - val_accuracy: 0.9764\n10000/10000 [==============================] - 1s 77us/step\nTest loss: 0.07643256488069892\nTest accuracy: 0.9764000177383423\n" ] ], [ [ "## Hyperbolic Tangent Activation Function", "_____no_output_____" ] ], [ [ "HTan_model = Sequential()\n\nHTan_model.add(Dense(500, input_dim=n, activation='tanh'))\n\nHTan_model.add(Dense(100, activation='tanh'))\n\nHTan_model.add(Dense(num_classes, activation='softmax'))\n\n# Compile model\n\nHTan_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nHTan_model.summary()", "Model: \"sequential_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_7 (Dense) (None, 500) 392500 \n_________________________________________________________________\ndense_8 (Dense) (None, 100) 50100 \n_________________________________________________________________\ndense_9 (Dense) (None, 10) 1010 \n=================================================================\nTotal params: 443,610\nTrainable params: 443,610\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### Result of Train and Test", "_____no_output_____" ] ], [ [ "hist_htan=HTan_model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)\nscores_htan =HTan_model.evaluate(X_test, y_test)\nprint('Test loss:', scores_htan[0])\nprint('Test accuracy:', scores_htan[1])", "Train on 60000 samples, validate on 10000 samples\nEpoch 1/10\n60000/60000 [==============================] - 2s 37us/step - loss: 0.3003 - accuracy: 0.9115 - val_loss: 0.1729 - val_accuracy: 0.9491\nEpoch 2/10\n60000/60000 [==============================] - 2s 29us/step - loss: 0.1475 - accuracy: 0.9576 - val_loss: 0.1285 - val_accuracy: 0.9631\nEpoch 3/10\n60000/60000 [==============================] - 2s 34us/step - loss: 0.1041 - accuracy: 0.9700 - val_loss: 0.1025 - val_accuracy: 0.9705\nEpoch 4/10\n60000/60000 [==============================] - 2s 32us/step - loss: 0.0806 - accuracy: 0.9764 - val_loss: 0.0925 - val_accuracy: 0.9730\nEpoch 5/10\n60000/60000 [==============================] - 2s 29us/step - loss: 0.0616 - accuracy: 0.9821 - val_loss: 0.0827 - val_accuracy: 0.9749\nEpoch 6/10\n60000/60000 [==============================] - 2s 30us/step - loss: 0.0487 - accuracy: 0.9861 - val_loss: 0.0696 - val_accuracy: 0.9777\nEpoch 7/10\n60000/60000 [==============================] - 2s 30us/step - loss: 0.0374 - accuracy: 0.9897 - val_loss: 0.0783 - val_accuracy: 0.9760\nEpoch 8/10\n60000/60000 [==============================] - 2s 28us/step - loss: 0.0307 - accuracy: 0.9915 - val_loss: 0.0748 - val_accuracy: 0.9777\nEpoch 9/10\n60000/60000 [==============================] - 2s 28us/step - loss: 0.0235 - accuracy: 0.9943 - val_loss: 0.0685 - val_accuracy: 0.9792\nEpoch 10/10\n60000/60000 [==============================] - 2s 28us/step - loss: 0.0189 - accuracy: 0.9958 - val_loss: 0.0713 - val_accuracy: 0.9792\n10000/10000 [==============================] - 1s 77us/step\nTest loss: 0.07125129706889857\nTest accuracy: 0.979200005531311\n" ] ], [ [ "## Swish Activation Function", "_____no_output_____" ] ], [ [ "def swish(x):\n return x * keras.backend.sigmoid(x)", "_____no_output_____" ], [ "SWISH_model = Sequential()\n\nSWISH_model.add(Dense(500, input_dim=n, activation=swish))\n\nSWISH_model.add(Dense(100, activation=swish))\n\nSWISH_model.add(Dense(num_classes, activation='softmax'))\n\n# Compile model\n\nSWISH_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nSWISH_model.summary()", "_____no_output_____" ] ], [ [ "### Result of Train and Test", "_____no_output_____" ] ], [ [ "hist_swish=SWISH_model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)\nscores_swish =SWISH_model.evaluate(X_test, y_test)\nprint('Test loss:', scores_swish[0])\nprint('Test accuracy:', scores_swish[1])", "Train on 60000 samples, validate on 10000 samples\nEpoch 1/10\n60000/60000 [==============================] - 2s 32us/step - loss: 0.2995 - accuracy: 0.9163 - val_loss: 0.1398 - val_accuracy: 0.9584\nEpoch 2/10\n60000/60000 [==============================] - 2s 29us/step - loss: 0.1199 - accuracy: 0.9638 - val_loss: 0.1013 - val_accuracy: 0.9681\nEpoch 3/10\n60000/60000 [==============================] - 2s 30us/step - loss: 0.0765 - accuracy: 0.9767 - val_loss: 0.0775 - val_accuracy: 0.9752\nEpoch 4/10\n60000/60000 [==============================] - 2s 30us/step - loss: 0.0539 - accuracy: 0.9835 - val_loss: 0.0686 - val_accuracy: 0.9780\nEpoch 5/10\n60000/60000 [==============================] - 3s 43us/step - loss: 0.0395 - accuracy: 0.9879 - val_loss: 0.0629 - val_accuracy: 0.9789\nEpoch 6/10\n60000/60000 [==============================] - 2s 38us/step - loss: 0.0294 - accuracy: 0.9909 - val_loss: 0.0578 - val_accuracy: 0.9824\nEpoch 7/10\n60000/60000 [==============================] - 3s 47us/step - loss: 0.0219 - accuracy: 0.9935 - val_loss: 0.0592 - val_accuracy: 0.9816\nEpoch 8/10\n60000/60000 [==============================] - 2s 33us/step - loss: 0.0179 - accuracy: 0.9944 - val_loss: 0.0635 - val_accuracy: 0.9813\nEpoch 9/10\n60000/60000 [==============================] - 2s 32us/step - loss: 0.0121 - accuracy: 0.9964 - val_loss: 0.0614 - val_accuracy: 0.9825\nEpoch 10/10\n60000/60000 [==============================] - 2s 39us/step - loss: 0.0128 - accuracy: 0.9958 - val_loss: 0.0654 - val_accuracy: 0.9811\n10000/10000 [==============================] - 1s 120us/step\nTest loss: 0.06543042148059466\nTest accuracy: 0.9811000227928162\n" ] ], [ [ "## Scaled Exponential Linear Unit (SELU) Activation Function", "_____no_output_____" ] ], [ [ "SELU_model = Sequential()\n\nSELU_model.add(Dense(500, input_dim=n, activation='selu'))\n\nSELU_model.add(Dense(100, activation='selu'))\n\nSELU_model.add(Dense(num_classes, activation='softmax'))\n\n# Compile model\n\nSELU_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nSELU_model.summary()", "Model: \"sequential_5\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_13 (Dense) (None, 500) 392500 \n_________________________________________________________________\ndense_14 (Dense) (None, 100) 50100 \n_________________________________________________________________\ndense_15 (Dense) (None, 10) 1010 \n=================================================================\nTotal params: 443,610\nTrainable params: 443,610\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### Result of Train and Test", "_____no_output_____" ] ], [ [ "hist_selu=SELU_model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)\nscores_selu =SELU_model.evaluate(X_test, y_test)\nprint('Test loss:', scores_selu[0])\nprint('Test accuracy:', scores_selu[1])", "Train on 60000 samples, validate on 10000 samples\nEpoch 1/10\n60000/60000 [==============================] - 2s 41us/step - loss: 0.3116 - accuracy: 0.9072 - val_loss: 0.1997 - val_accuracy: 0.9390\nEpoch 2/10\n60000/60000 [==============================] - 3s 42us/step - loss: 0.1502 - accuracy: 0.9554 - val_loss: 0.1314 - val_accuracy: 0.9586\nEpoch 3/10\n60000/60000 [==============================] - 2s 37us/step - loss: 0.1066 - accuracy: 0.9678 - val_loss: 0.1071 - val_accuracy: 0.9667\nEpoch 4/10\n60000/60000 [==============================] - 2s 32us/step - loss: 0.0819 - accuracy: 0.9745 - val_loss: 0.1000 - val_accuracy: 0.9688\nEpoch 5/10\n60000/60000 [==============================] - 2s 33us/step - loss: 0.0653 - accuracy: 0.9799 - val_loss: 0.0986 - val_accuracy: 0.9703\nEpoch 6/10\n60000/60000 [==============================] - 2s 36us/step - loss: 0.0535 - accuracy: 0.9834 - val_loss: 0.0893 - val_accuracy: 0.9736\nEpoch 7/10\n60000/60000 [==============================] - 2s 30us/step - loss: 0.0447 - accuracy: 0.9855 - val_loss: 0.0862 - val_accuracy: 0.9739\nEpoch 8/10\n60000/60000 [==============================] - 2s 29us/step - loss: 0.0374 - accuracy: 0.9876 - val_loss: 0.0783 - val_accuracy: 0.9775\nEpoch 9/10\n60000/60000 [==============================] - 2s 35us/step - loss: 0.0331 - accuracy: 0.9890 - val_loss: 0.0914 - val_accuracy: 0.9755\nEpoch 10/10\n60000/60000 [==============================] - 2s 36us/step - loss: 0.0277 - accuracy: 0.9907 - val_loss: 0.0961 - val_accuracy: 0.9728\n10000/10000 [==============================] - 1s 83us/step\nTest loss: 0.09614768207155866\nTest accuracy: 0.9728000164031982\n" ] ], [ [ "# Comparision of all 5 Activation Functions", "_____no_output_____" ] ], [ [ "test_loss=[scores_relu[0],scores_sig[0],scores_htan[0],scores_swish[0],scores_selu[0]]\ntest_acc=[scores_relu[1],scores_sig[1],scores_htan[1],scores_swish[1],scores_selu[1]]\n\ndf_scores=pd.DataFrame({'Test Loss':test_loss,'Test Accuracy':test_acc},index=['RELU','Sigmoid','TanH','Swish','SELU'])\ndf_scores", "_____no_output_____" ], [ "hists = [hist_htan, hist_sig, hist_relu, hist_swish, hist_selu]", "_____no_output_____" ], [ "def plot_history(hists, attribute, axis=(-1,10,0.85,0.94), loc='lower right'):\n title={'val_loss': 'Validation loss', 'loss': 'Training loss', 'val_accuracy': 'Validation accuracy', 'accuracy': 'Training accuracy'}\n num_hists=len(hists)\n \n plt.figure(figsize=(12, 8)) \n plt.axis(axis)\n for i in range(num_hists):\n plt.plot(hists[i].history[attribute])\n plt.title(title[attribute], fontsize=25) \n plt.ylabel(title[attribute]) \n plt.xlabel('Epochs') \n plt.legend(['TanH', 'Sigmoid', 'ReLU', 'Swish', 'SELU'], loc=loc) \n plt.show()", "_____no_output_____" ], [ "plot_history(hists, attribute='val_accuracy',axis=(-1,10,0.91,0.99), loc='lower right')", "_____no_output_____" ], [ "plot_history(hists, attribute='accuracy', axis=(-1,10,0.825,1), loc='lower right')", "_____no_output_____" ], [ "plot_history(hists, attribute='val_loss', axis=(-1,10,0.05,0.30), loc='upper right')", "_____no_output_____" ], [ "plot_history(hists, attribute='loss', axis=(-1,10,0.000,0.4), loc='upper right')", "_____no_output_____" ] ], [ [ "# Thank You", "_____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", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
ec4f5468a31d2d92261079e316d9e4045c91f1f6
13,745
ipynb
Jupyter Notebook
2_aging_signature/archive_initial_submission/.ipynb_checkpoints/DE_tissue_bulk-checkpoint.ipynb
gmstanle/msc_aging
3ea74dcfc48bc530ee47581ffe60e42f15b9178d
[ "MIT" ]
57
2019-06-09T20:44:02.000Z
2022-02-07T05:22:44.000Z
2_aging_signature/archive_initial_submission/.ipynb_checkpoints/DE_tissue_bulk-checkpoint.ipynb
gmstanle/msc_aging
3ea74dcfc48bc530ee47581ffe60e42f15b9178d
[ "MIT" ]
33
2019-07-02T13:54:45.000Z
2022-03-04T07:07:25.000Z
2_aging_signature/archive_initial_submission/.ipynb_checkpoints/DE_tissue_bulk-checkpoint.ipynb
gmstanle/msc_aging
3ea74dcfc48bc530ee47581ffe60e42f15b9178d
[ "MIT" ]
20
2019-09-15T02:50:17.000Z
2022-03-23T17:19:09.000Z
24.241623
424
0.515606
[ [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"whitegrid\")\nimport numpy as np\nimport scanpy.api as sc\nfrom anndata import read_h5ad\nfrom anndata import AnnData\nimport scipy as sp\nimport scipy.stats\nfrom gprofiler import GProfiler\nimport pickle\n# Other specific functions \nfrom itertools import product\nfrom statsmodels.stats.multitest import multipletests\nimport util\n# R related packages \nimport rpy2.rinterface_lib.callbacks\nimport logging\nfrom rpy2.robjects import pandas2ri\nimport anndata2ri", "/home/martin/anaconda3/lib/python3.6/site-packages/sklearn/externals/joblib/__init__.py:15: DeprecationWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.\n warnings.warn(msg, category=DeprecationWarning)\n" ], [ "# Ignore R warning messages\n#Note: this can be commented out to get more verbose R output\nrpy2.rinterface_lib.callbacks.logger.setLevel(logging.ERROR)\n# Automatically convert rpy2 outputs to pandas dataframes\npandas2ri.activate()\nanndata2ri.activate()\n%load_ext rpy2.ipython\n# autoreload\n%load_ext autoreload\n%autoreload 2\n# logging\nsc.logging.print_versions()", "scanpy==1.4.3 anndata==0.6.20 umap==0.3.8 numpy==1.16.4 scipy==1.2.1 pandas==0.25.0 scikit-learn==0.21.1 statsmodels==0.9.0 python-igraph==0.7.1 louvain==0.6.1 \n" ], [ "%%R\nlibrary(MAST)", "_____no_output_____" ] ], [ [ "## Load data", "_____no_output_____" ] ], [ [ "# Data path\ndata_path = '/data3/martin/tms_gene_data'\noutput_folder = data_path + '/DE_result'", "_____no_output_____" ], [ "# Load the data \nadata_bulk = util.load_normalized_data_bulk(data_path)", "Trying to set attribute `.obs` of view, making a copy.\n" ], [ "temp_bulk = adata_bulk.copy()", "_____no_output_____" ] ], [ [ "## DE, age, tissue, bulk", "_____no_output_____" ] ], [ [ "# cell_type_list = list(set(temp_facs.obs['cell_ontology_class']))\ntissue_list = list(set(temp_bulk.obs['tissue']))\nmin_cell_number = 1\nanalysis_list = []\nanalysis_info = {}\n# for cell_type in cell_type_list:\nfor tissue in tissue_list:\n analyte = tissue\n ind_select = (temp_bulk.obs['tissue'] == tissue)\n n_young = (temp_bulk.obs['age_num'][ind_select]<10).sum()\n n_old = (temp_bulk.obs['age_num'][ind_select]>10).sum()\n analysis_info[analyte] = {}\n analysis_info[analyte]['n_young'] = n_young\n analysis_info[analyte]['n_old'] = n_old\n if (n_young>min_cell_number) & (n_old>min_cell_number):\n print('%s, n_young=%d, n_old=%d'%(analyte, n_young, n_old))\n analysis_list.append(analyte)", "Gonadal_Fat, n_young=24, n_old=31\nBrown_Fat, n_young=23, n_old=31\nKidney, n_young=23, n_old=32\nBrain, n_young=24, n_old=32\nHeart, n_young=21, n_old=31\nSubcutaneous_Fat, n_young=23, n_old=32\nMarrow, n_young=23, n_old=30\nLung, n_young=23, n_old=32\nWhite_Blood_Cells, n_young=24, n_old=31\nLiver, n_young=24, n_old=30\nSpleen, n_young=24, n_old=32\nSmall_Intestine, n_young=24, n_old=31\nPancreas, n_young=24, n_old=32\nLimb_Muscle, n_young=23, n_old=31\nMesenteric_Fat, n_young=24, n_old=32\nBone, n_young=23, n_old=32\nSkin, n_young=23, n_old=28\n" ] ], [ [ "### DE using R package MAST ", "_____no_output_____" ] ], [ [ "## DE testing\ngene_name_list = np.array(temp_bulk.var_names)\nDE_result_MAST = {}\nfor i_analyte,analyte in enumerate(analysis_list):\n print(analyte, '%d/%d'%(i_analyte, len(analysis_list)))\n tissue = analyte\n# tissue,cell_type = analyte.split('.')\n ind_select = (temp_bulk.obs['tissue'] == tissue)\n adata_temp = temp_bulk[ind_select,]\n # reformatting\n# adata_temp.X = np.array(adata_temp.X.todense())\n adata_temp.X = np.array(adata_temp.X)\n adata_temp.obs['condition'] = [int(x[:-1]) for x in adata_temp.obs['age']] \n adata_temp.obs = adata_temp.obs[['condition', 'sex']]\n if len(set(adata_temp.obs['sex'])) <2:\n covariate = ''\n else:\n covariate = '+sex'\n# # toy example\n# covariate = ''\n# np.random.seed(0)\n# ind_select = np.random.permutation(adata_temp.shape[0])[0:100]\n# ind_select = np.sort(ind_select)\n# adata_temp = adata_temp[:, 0:3]\n# adata_temp.X[:,0] = (adata_temp.obs['sex'] == 'male')*3\n# adata_temp.X[:,1] = (adata_temp.obs['condition'])*3\n # DE using MAST \n R_cmd = util.call_MAST_age()\n get_ipython().run_cell_magic(u'R', u'-i adata_temp -i covariate -o de_res', R_cmd)\n de_res.columns = ['gene', 'raw-p', 'coef', 'bh-p']\n de_res.index = de_res['gene']\n DE_result_MAST[analyte] = pd.DataFrame(index = gene_name_list)\n DE_result_MAST[analyte] = DE_result_MAST[analyte].join(de_res)\n # fc between yound and old\n X = adata_temp.X\n y = (adata_temp.obs['condition']>10)\n DE_result_MAST[analyte]['fc'] = X[y,:].mean(axis=0) - X[~y,:].mean(axis=0)\n# break", "Trying to set attribute `.obs` of view, making a copy.\n" ] ], [ [ "### Save DE results", "_____no_output_____" ] ], [ [ "with open(output_folder+'/DE_bulk.pickle', 'wb') as handle:\n pickle.dump(DE_result_MAST, handle)\n pickle.dump(analysis_list, handle)\n pickle.dump(analysis_info, handle)", "_____no_output_____" ] ], [ [ "### Validation", "_____no_output_____" ] ], [ [ "for analyte in DE_result_MAST.keys():\n print(analyte, np.sum(DE_result_MAST[analyte]['bh-p']<0.00001))\n", "Fat 12428\nLiver 8147\nLimb_Muscle 8066\nTrachea 9606\nPancreas 10145\nMarrow 10720\nTongue 8795\nLung 5588\nSpleen 2500\nHeart 8132\nSkin 8647\nBladder 11658\nKidney 1001\nThymus 4762\nBrain_Myeloid 9601\nMammary_Gland 5029\nBrain_Non-Myeloid 12855\nLarge_Intestine 10159\n" ] ] ]
[ "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" ] ]
ec4f578666bfec9d5a0e6563f64b5f24d6527c40
15,187
ipynb
Jupyter Notebook
notebooks/06_sklearn/06_solucion_ejercicios_Knn.ipynb
PyDataMallorca/PyConES2018_Introduccion_a_data_science_en_Python
71d0c6f86afdc992e3b2ba1d6862eb34dead5698
[ "MIT" ]
15
2018-09-03T16:45:42.000Z
2020-02-16T13:50:06.000Z
notebooks/06_sklearn/06_solucion_ejercicios_Knn.ipynb
NachoAG76/PyConES2018_Introduccion_a_data_science_en_Python
71d0c6f86afdc992e3b2ba1d6862eb34dead5698
[ "MIT" ]
null
null
null
notebooks/06_sklearn/06_solucion_ejercicios_Knn.ipynb
NachoAG76/PyConES2018_Introduccion_a_data_science_en_Python
71d0c6f86afdc992e3b2ba1d6862eb34dead5698
[ "MIT" ]
9
2018-09-08T10:06:00.000Z
2020-05-09T05:09:38.000Z
32.244161
325
0.58076
[ [ [ "import warnings\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import classification_report, accuracy_score, confusion_matrix\n\n\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "# Cancer Data Set \n\n### Breast Cancer Wisconsin (Diagnostic) Data Set\n\n**Abstract:** Diagnostic Wisconsin Breast Cancer Database\nSource:\n\nCreators:\n\n1. Dr. William H. Wolberg, General Surgery Dept.\nUniversity of Wisconsin, Clinical Sciences Center\nMadison, WI 53792\nwolberg '@' eagle.surgery.wisc.edu\n\n2. W. Nick Street, Computer Sciences Dept.\nUniversity of Wisconsin, 1210 West Dayton St., Madison, WI 53706\nstreet '@' cs.wisc.edu 608-262-6619\n\n3. Olvi L. Mangasarian, Computer Sciences Dept.\nUniversity of Wisconsin, 1210 West Dayton St., Madison, WI 53706\nolvi '@' cs.wisc.edu\n\n### Información del conjunto de datos:\n\nLas características se calculan a partir de una imagen digitalizada de aspiración con aguja fina (PAAF) de una masas mamarias. Describen las características de los núcleos celulares presentes en la imagen (más detalles http://pages.cs.wisc.edu/~street/images/)\n\nAttribute Information:\n\n1. ID number\n2. Diagnosis (M = malignant, B = benign) \n\n**Ten real-valued features are computed for each cell nucleus:**\n\na) radius (mean of distances from center to points on the perimeter)\n\nb) texture (standard deviation of gray-scale values)\n\nc) perimeter\n\nd) area\n\ne) smoothness (local variation in radius lengths)\n\nf) compactness (perimeter^2 / area - 1.0)\n\ng) concavity (severity of concave portions of the contour)\n\nh) concave points (number of concave portions of the contour)\n\ni) symmetry\n\nj) fractal dimension (\"coastline approximation\" - 1)", "_____no_output_____" ] ], [ [ "# Cargamos los datos del fichero CSV\ncancer_df = pd.read_csv('../../data/06_breast-cancer-wisconsin-data.csv')\n\n# Imprimimos los datos cargados con pandas\n#df.describe()\n#df = df.set_index('id')\ncancer_df.info()", "_____no_output_____" ] ], [ [ "## Preparamos Datos", "_____no_output_____" ] ], [ [ "le = preprocessing.LabelEncoder()\nle.fit(cancer_df['diagnosis'])\ncancer_df['diagnosis_cod'] = le.transform(cancer_df['diagnosis'])\ncancer_df = cancer_df.drop(['Unnamed: 32','id','diagnosis'], axis=1)\ncancer_df\n#le.inverse_transform(iris_df.species_cod)", "_____no_output_____" ], [ "# separamos datos en data y target\ncancer_data = cancer_df.drop(['diagnosis_cod'], axis=1)\ncancer_target = cancer_df.diagnosis_cod", "_____no_output_____" ], [ "# Separamos los Datos.... Entrenamiento y test\n#? train_test_split()\n\n\nX_train, X_test, y_train, y_test = train_test_split(cancer_data, cancer_target,\n test_size=0.33,\n random_state=None,\n shuffle =None)\n\nprint('Set de datos para Entrenamiento =',len(X_train))\nprint('Set de datos para Test',len(X_test))\nprint('Total',len(X_test)+len(X_train))\nprint('Data Shape=',X_test.shape)\nprint('Target Shape =',y_test.shape)\n\nX_train.head()\n#X_train.columns", "_____no_output_____" ] ], [ [ "# ======== Knn Cancer Data Set =========", "_____no_output_____" ] ], [ [ "# Create two lists for training and test accuracies\ntraining_accuracy = []\ntest_accuracy = []\n\n# Define a range of 1 to 10 (included) neighbors to be tested\nneighbors_settings = range(1,20)\n\n# Loop with the KNN through the different number of neighbors to determine the most appropriate (best)\nfor n_neighbors in neighbors_settings:\n clf = KNeighborsClassifier(n_neighbors=n_neighbors,\n algorithm='auto',\n weights='uniform')\n clf.fit(X_train, y_train)\n training_accuracy.append(clf.score(X_train, y_train))\n test_accuracy.append(clf.score(X_test, y_test))\n\n# Visualize results - to help with deciding which n_neigbors yields the best results (n_neighbors=6, in this case)\nplt.plot(neighbors_settings, training_accuracy, label='Accuracy of the training set', marker='o')\nplt.plot(neighbors_settings, test_accuracy, label='Accuracy of the test set', marker='o')\nplt.ylabel('Accuracy')\nplt.xlabel('Number of Neighbors')\nplt.legend()\n", "_____no_output_____" ], [ "clf = KNeighborsClassifier(n_neighbors=5,weights='uniform', algorithm='auto')\nclf.fit(X_train, y_train)\nprint (\"Score with data Tes\",clf.score(X_test,y_test))\nprint (\"Score with data Train\",clf.score(X_train,y_train))", "_____no_output_____" ] ], [ [ "# Alguna Predicción ", "_____no_output_____" ] ], [ [ "warnings.filterwarnings('ignore')\nind = 78\nprint(cancer_data.iloc[ind])\nprint('specie',cancer_target.iloc[ind], le.inverse_transform(cancer_target.iloc[[ind]]))\nx_new = cancer_data.iloc[ind]\n\nprint('\\n======== PREDICTION ========')\nprediction = clf.predict([x_new.values])\nprediction_pb = clf.predict_proba([x_new.values])\nprint('Specie prediction',prediction, le.inverse_transform(prediction))\nprint('Probability Specie prediction',prediction_pb)", "_____no_output_____" ] ], [ [ "# Clasification Report", "_____no_output_____" ] ], [ [ "p = clf.predict(X_test)\n\nprint ('Accuracy:', accuracy_score(y_test, p))\nprint ('\\nConfusion Matrix:\\n', confusion_matrix(y_test, p))\nprint ('\\nClassification Report:', classification_report(y_test, p))\n", "_____no_output_____" ] ], [ [ "Diabetes Data Set\n\nMichael Kahn, MD, PhD, Universidad de Washington, St. Louis, MO\nInformación del conjunto de datos:\n\nLos registros de pacientes con diabetes se obtuvieron de dos fuentes: a) un dispositivo de registro electrónico automático y b) registros en papel.\n\nEl dispositivo automático tenía un reloj interno para los eventos de marca de tiempo, mientras que los registros en papel solo proporcionaban espacios de \"tiempo lógico\" (desayuno, almuerzo, cena, hora de acostarse).\n\nPara los registros en papel, se asignaron horarios fijos para el desayuno (08:00), el almuerzo (12:00), la cena (18:00) y la hora de acostarse (22:00). Por lo tanto, los registros en papel tienen tiempos de grabación uniformes ficticios, mientras que los registros electrónicos tienen marcas de tiempo más realistas.\n\nLos archivos de diabetes constan de cuatro campos por registro. Cada campo está separado por una pestaña y cada registro está separado por una nueva línea.\n\nNombres de archivos y formato\n\n(1) Fecha en formato MM-DD-YYYY (2) Tiempo en formato XX: YY (3) Código (4) Valor\n\nEl campo Código se descifra de la siguiente manera:\n\n33 = Dosis de insulina regular\n\n34 = dosis de insulina NPH\n\n35 = dosis de insulina UltraLente\n\n48 = medición de glucosa en sangre no especificada\n\n57 = medición de glucosa en sangre no especificada\n\n58 = medición de glucosa en sangre antes del desayuno\n\n59 = medición de glucosa en sangre después del desayuno\n\n60 = medición de glucosa en sangre antes del almuerzo\n\n61 = medición de glucosa en sangre después del almuerzo\n\n62 = medición de glucosa en sangre antes de la cena\n\n63 = medición de glucosa en sangre después de la cena\n\n64 = Medición de glucosa en sangre antes del aperitivo\n\n65 = Síntomas de hipoglucemia\n\n66 = Ingestión típica de comida\n\n67 = Ingestión de comida más de lo habitual\n\n68 = ingesta de comida menos de lo usual\n\n69 = actividad típica de ejercicio\n\n70 = Actividad de ejercicio más de lo habitual\n\n71 = actividad de ejercicio menos de lo\n", "_____no_output_____" ] ], [ [ "# Cargamos los datos del fichero CSV\ndiabetes_df = pd.read_csv('../../data/06_diabetes.csv')\n\n# Imprimimos los datos cargados con pandas\n#diabetes_df.info()\ndiabetes_df", "_____no_output_____" ], [ "# separamos datos en data y target\ndiabetes_data = diabetes_df.drop(['diagnosis'], axis=1)\ndiabetes_target = diabetes_df.diagnosis", "_____no_output_____" ], [ "# Separamos los Datos.... Entrenamiento y test\n#? train_test_split()\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(diabetes_data, diabetes_target,\n test_size=0.33,\n random_state=None,\n shuffle =None)\n\nprint('Set de datos para Entrenamiento =',len(X_train))\nprint('Set de datos para Test',len(X_test))\nprint('Total',len(X_test)+len(X_train))\nprint('Data Shape=',X_test.shape)\nprint('Target Shape =',y_test.shape)\n\nX_train.head()\n#X_train.columns", "_____no_output_____" ], [ "# Create two lists for training and test accuracies\ntraining_accuracy = []\ntest_accuracy = []\n\n# Define a range of 1 to 10 (included) neighbors to be tested\nneighbors_settings = range(1,20)\n\n# Loop with the KNN through the different number of neighbors to determine the most appropriate (best)\nfor n_neighbors in neighbors_settings:\n clf = KNeighborsClassifier(n_neighbors=n_neighbors,\n algorithm='auto',\n weights='uniform')\n clf.fit(X_train, y_train)\n training_accuracy.append(clf.score(X_train, y_train))\n test_accuracy.append(clf.score(X_test, y_test))\n\n# Visualize results - to help with deciding which n_neigbors yields the best results (n_neighbors=6, in this case)\nplt.plot(neighbors_settings, training_accuracy, label='Accuracy of the training set', marker='o')\nplt.plot(neighbors_settings, test_accuracy, label='Accuracy of the test set', marker='o')\nplt.ylabel('Accuracy')\nplt.xlabel('Number of Neighbors')\nplt.legend()", "_____no_output_____" ], [ "clf = KNeighborsClassifier(n_neighbors=15,weights='uniform', algorithm='auto')\nclf.fit(X_train, y_train)\nprint (\"Score with data Tes\",clf.score(X_test,y_test))\nprint (\"Score with data Train\",clf.score(X_train,y_train))", "_____no_output_____" ] ], [ [ "# ========= Alguna Predicción ========", "_____no_output_____" ] ], [ [ "ind = 78\nprint(diabetes_data.iloc[ind])\nprint('specie',diabetes_target.iloc[ind], le.inverse_transform(diabetes_target.iloc[[ind]]))\nx_new = diabetes_data.ix[ind]\n\nprint('\\n======== PREDICTION ========')\nprediction = clf.predict([x_new.values])\nprediction_pb = clf.predict_proba([x_new.values])\nprint('Specie prediction',prediction, le.inverse_transform(prediction))\nprint('Probability Specie prediction',prediction_pb)", "_____no_output_____" ] ], [ [ "# ============ Classification Report============", "_____no_output_____" ] ], [ [ "p = clf.predict(X_test)\n\nprint ('Accuracy:', accuracy_score(y_test, p))\nprint ('\\nConfusion Matrix:\\n', confusion_matrix(y_test, p))\nprint ('\\nClassification Report:', classification_report(y_test, p))\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ec4f5adfb3705154c843bee53105eac4542ef214
13,401
ipynb
Jupyter Notebook
examples/cta_backtesting/trade_by_trade.ipynb
Bombenchris/vnpy
1993e583807acc95aaf76ffa1a60244a2f2fba05
[ "MIT" ]
21
2020-07-15T07:06:25.000Z
2021-12-19T07:33:02.000Z
examples/cta_backtesting/trade_by_trade.ipynb
Bombenchris/vnpy
1993e583807acc95aaf76ffa1a60244a2f2fba05
[ "MIT" ]
2
2019-08-04T01:45:37.000Z
2019-08-04T01:48:18.000Z
examples/cta_backtesting/trade_by_trade.ipynb
Bombenchris/vnpy
1993e583807acc95aaf76ffa1a60244a2f2fba05
[ "MIT" ]
10
2021-03-14T13:28:18.000Z
2022-02-18T13:38:17.000Z
33.418953
97
0.503918
[ [ [ "#%%\nfrom vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting\nfrom vnpy.app.cta_strategy.strategies.turtle_signal_strategy import TurtleSignalStrategy\nfrom datetime import datetime", "_____no_output_____" ], [ "#%%\nengine = BacktestingEngine()\nengine.set_parameters(\n vt_symbol=\"XBTUSD.BITMEX\",\n interval=\"1h\",\n start=datetime(2017, 1, 1),\n end=datetime(2019, 11, 30),\n rate=1/10000,\n slippage=0.5,\n size=1,\n pricetick=0.5,\n capital=1_000_000,\n)\nengine.add_strategy(TurtleSignalStrategy, {})", "_____no_output_____" ], [ "#%%\nengine.load_data()\nengine.run_backtesting()\ndf = engine.calculate_result()\nengine.calculate_statistics()\nengine.show_chart()", "_____no_output_____" ], [ "import pandas as pd\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\npd.set_option('mode.chained_assignment', None)\n\n\ndef calculate_trades_result(trades):\n \"\"\"\n Deal with trade data\n \"\"\"\n dt, direction, offset, price, volume = [], [], [], [], []\n for i in trades.values():\n dt.append(i.datetime)\n direction.append(i.direction.value)\n offset.append(i.offset.value)\n price.append(i.price)\n volume.append(i.volume)\n\n # Generate DataFrame with datetime, direction, offset, price, volume\n df = pd.DataFrame()\n df[\"direction\"] = direction\n df[\"offset\"] = offset\n df[\"price\"] = price\n df[\"volume\"] = volume\n\n df[\"current_time\"] = dt\n df[\"last_time\"] = df[\"current_time\"].shift(1)\n\n # Calculate trade amount\n df[\"amount\"] = df[\"price\"] * df[\"volume\"]\n df[\"acum_amount\"] = df[\"amount\"].cumsum()\n\n # Calculate pos, net pos(with direction), acumluation pos(with direction)\n def calculate_pos(df):\n if df[\"direction\"] == \"多\":\n result = df[\"volume\"]\n else:\n result = - df[\"volume\"]\n\n return result\n df[\"pos\"] = df.apply(calculate_pos, axis=1)\n\n df[\"net_pos\"] = df[\"pos\"].cumsum()\n df[\"acum_pos\"] = df[\"volume\"].cumsum()\n\n # Calculate trade result, acumulation result\n # ej: trade result(buy->sell) means (new price - old price) * volume\n df[\"result\"] = -1 * df[\"pos\"] * df[\"price\"]\n df[\"acum_result\"] = df[\"result\"].cumsum()\n\n # Filter column data when net pos comes to zero\n def get_acum_trade_result(df):\n if df[\"net_pos\"] == 0:\n return df[\"acum_result\"]\n df[\"acum_trade_result\"] = df.apply(get_acum_trade_result, axis=1)\n\n def get_acum_trade_volume(df):\n if df[\"net_pos\"] == 0:\n return df[\"acum_pos\"]\n df[\"acum_trade_volume\"] = df.apply(get_acum_trade_volume, axis=1) \n\n def get_acum_trade_duration(df):\n if df[\"net_pos\"] == 0:\n return df[\"current_time\"] - df[\"last_time\"]\n df[\"acum_trade_duration\"] = df.apply(get_acum_trade_duration, axis=1) \n\n def get_acum_trade_amount(df):\n if df[\"net_pos\"] == 0:\n return df[\"acum_amount\"]\n df[\"acum_trade_amount\"] = df.apply(get_acum_trade_amount, axis=1) \n\n # Select row data with net pos equil to zero \n df = df.dropna()\n\n return df\n\n\ndef generate_trade_df(trades, size, rate, slippage, capital):\n \"\"\"\n Calculate trade result from increment\n \"\"\"\n df = calculate_trades_result(trades)\n\n trade_df = pd.DataFrame()\n trade_df[\"close_direction\"] = df[\"direction\"]\n trade_df[\"close_time\"] = df[\"current_time\"]\n trade_df[\"close_price\"] = df[\"price\"]\n trade_df[\"pnl\"] = df[\"acum_trade_result\"] - \\\n df[\"acum_trade_result\"].shift(1).fillna(0)\n \n trade_df[\"volume\"] = df[\"acum_trade_volume\"] - \\\n df[\"acum_trade_volume\"].shift(1).fillna(0)\n trade_df[\"duration\"] = df[\"current_time\"] - \\\n df[\"last_time\"]\n trade_df[\"turnover\"] = df[\"acum_trade_amount\"] - \\\n df[\"acum_trade_amount\"].shift(1).fillna(0)\n \n trade_df[\"commission\"] = trade_df[\"turnover\"] * rate\n trade_df[\"slipping\"] = trade_df[\"volume\"] * size * slippage\n\n trade_df[\"net_pnl\"] = trade_df[\"pnl\"] - \\\n trade_df[\"commission\"] - trade_df[\"slipping\"]\n\n result = calculate_base_net_pnl(trade_df, capital)\n return result\n\n\ndef calculate_base_net_pnl(df, capital):\n \"\"\"\n Calculate statistic base on net pnl\n \"\"\"\n df[\"acum_pnl\"] = df[\"net_pnl\"].cumsum()\n df[\"balance\"] = df[\"acum_pnl\"] + capital\n df[\"return\"] = np.log(\n df[\"balance\"] / df[\"balance\"].shift(1)\n ).fillna(0)\n df[\"highlevel\"] = (\n df[\"balance\"].rolling(\n min_periods=1, window=len(df), center=False).max()\n )\n df[\"drawdown\"] = df[\"balance\"] - df[\"highlevel\"]\n df[\"ddpercent\"] = df[\"drawdown\"] / df[\"highlevel\"] * 100\n\n df.reset_index(drop=True, inplace=True)\n \n return df\n\n\ndef buy2sell(df, capital):\n \"\"\"\n Generate DataFrame with only trade from buy to sell\n \"\"\"\n buy2sell = df[df[\"close_direction\"] == \"空\"]\n result = calculate_base_net_pnl(buy2sell, capital)\n return result\n\n\ndef short2cover(df, capital):\n \"\"\"\n Generate DataFrame with only trade from short to cover\n \"\"\"\n short2cover = df[df[\"close_direction\"] == \"多\"]\n result = calculate_base_net_pnl(short2cover, capital)\n return result\n\n\ndef statistics_trade_result(df, capital, show_chart=True):\n \"\"\"\"\"\"\n end_balance = df[\"balance\"].iloc[-1]\n max_drawdown = df[\"drawdown\"].min()\n max_ddpercent = df[\"ddpercent\"].min()\n\n pnl_medio = df[\"net_pnl\"].mean()\n trade_count = len(df)\n duration_medio = df[\"duration\"].mean().total_seconds()/3600\n commission_medio = df[\"commission\"].mean()\n slipping_medio = df[\"slipping\"].mean()\n\n win = df[df[\"net_pnl\"] > 0]\n win_amount = win[\"net_pnl\"].sum()\n win_pnl_medio = win[\"net_pnl\"].mean()\n win_duration_medio = win[\"duration\"].mean().total_seconds()/3600\n win_count = len(win)\n\n loss = df[df[\"net_pnl\"] < 0]\n loss_amount = loss[\"net_pnl\"].sum()\n loss_pnl_medio = loss[\"net_pnl\"].mean()\n loss_duration_medio = loss[\"duration\"].mean().total_seconds()/3600\n loss_count = len(loss)\n\n winning_rate = win_count / trade_count\n win_loss_pnl_ratio = - win_pnl_medio / loss_pnl_medio\n\n total_return = (end_balance / capital - 1) * 100\n return_drawdown_ratio = -total_return / max_ddpercent\n\n output(f\"起始资金:\\t{capital:,.2f}\")\n output(f\"结束资金:\\t{end_balance:,.2f}\")\n output(f\"总收益率:\\t{total_return:,.2f}%\")\n output(f\"最大回撤: \\t{max_drawdown:,.2f}\")\n output(f\"百分比最大回撤: {max_ddpercent:,.2f}%\")\n output(f\"收益回撤比:\\t{return_drawdown_ratio:,.2f}\")\n\n output(f\"总成交次数:\\t{trade_count}\")\n output(f\"盈利成交次数:\\t{win_count}\")\n output(f\"亏损成交次数:\\t{loss_count}\")\n output(f\"胜率:\\t\\t{winning_rate:,.2f}\")\n output(f\"盈亏比:\\t\\t{win_loss_pnl_ratio:,.2f}\")\n\n output(f\"平均每笔盈亏:\\t{pnl_medio:,.2f}\")\n output(f\"平均持仓小时:\\t{duration_medio:,.2f}\")\n output(f\"平均每笔手续费:\\t{commission_medio:,.2f}\")\n output(f\"平均每笔滑点:\\t{slipping_medio:,.2f}\")\n\n output(f\"总盈利金额:\\t{win_amount:,.2f}\")\n output(f\"盈利交易均值:\\t{win_pnl_medio:,.2f}\")\n output(f\"盈利持仓小时:\\t{win_duration_medio:,.2f}\")\n\n output(f\"总亏损金额:\\t{loss_amount:,.2f}\")\n output(f\"亏损交易均值:\\t{loss_pnl_medio:,.2f}\")\n output(f\"亏损持仓小时:\\t{loss_duration_medio:,.2f}\")\n\n if not show_chart:\n return\n\n plt.figure(figsize=(10, 12))\n\n acum_pnl_plot = plt.subplot(3, 1, 1)\n acum_pnl_plot.set_title(\"Balance Plot\")\n df[\"balance\"].plot(legend=True)\n\n pnl_plot = plt.subplot(3, 1, 2)\n pnl_plot.set_title(\"Pnl Per Trade\")\n df[\"net_pnl\"].plot(legend=True)\n\n distribution_plot = plt.subplot(3, 1, 3)\n distribution_plot.set_title(\"Trade Pnl Distribution\")\n df[\"net_pnl\"].hist(bins=100)\n\n plt.show()\n\n\ndef output(msg):\n \"\"\"\n Output message with datetime.\n \"\"\"\n print(f\"{datetime.now()}\\t{msg}\")\n\n\ndef exhaust_trade_result(\n trades, \n size: int = 10, \n rate: float = 0.0, \n slippage: float = 0.0, \n capital: int = 1000000,\n show_long_short_condition=True\n ):\n \"\"\"\n Exhaust all trade result.\n \"\"\"\n\n total_trades = generate_trade_df(trades, size, rate, slippage, capital)\n statistics_trade_result(total_trades, capital)\n\n if not show_long_short_condition:\n return\n long_trades = buy2sell(total_trades, capital)\n short_trades = short2cover(total_trades, capital)\n\n output(\"-----------------------\")\n output(\"纯多头交易\")\n statistics_trade_result(long_trades, capital)\n\n output(\"-----------------------\")\n output(\"纯空头交易\")\n statistics_trade_result(short_trades, capital)", "_____no_output_____" ], [ "exhaust_trade_result(engine.trades,size=1, rate=8/10000, slippage=0.5)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
ec4f5cd5540b21842a65306d682c8bef09c487b8
295,019
ipynb
Jupyter Notebook
experiments/Conditional_Neural_Processes.ipynb
fredchettouh/neural-processes
3259cea7d1608392906f95dcba6899f6ec7911ee
[ "Apache-2.0" ]
null
null
null
experiments/Conditional_Neural_Processes.ipynb
fredchettouh/neural-processes
3259cea7d1608392906f95dcba6899f6ec7911ee
[ "Apache-2.0" ]
null
null
null
experiments/Conditional_Neural_Processes.ipynb
fredchettouh/neural-processes
3259cea7d1608392906f95dcba6899f6ec7911ee
[ "Apache-2.0" ]
null
null
null
195.506296
28,748
0.890353
[ [ [ "Copyright 2018 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n [https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n", "_____no_output_____" ] ], [ [ "!nvidia-smi", "Wed Apr 29 10:19:44 2020 \n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 440.64.00 Driver Version: 418.67 CUDA Version: 10.1 |\n|-------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n|===============================+======================+======================|\n| 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 |\n| N/A 55C P8 10W / 70W | 0MiB / 15079MiB | 0% Default |\n+-------------------------------+----------------------+----------------------+\n \n+-----------------------------------------------------------------------------+\n| Processes: GPU Memory |\n| GPU PID Type Process name Usage |\n|=============================================================================|\n| No running processes found |\n+-----------------------------------------------------------------------------+\n" ] ], [ [ "# Conditional Neural Processes (CNP) for 1D regression.\n\n[Conditional Neural Processes](https://arxiv.org/pdf/1807.01613.pdf) (CNPs) were\nintroduced as a continuation of\n[Generative Query Networks](https://deepmind.com/blog/neural-scene-representation-and-rendering/)\n(GQN) to extend its training regime to tasks beyond scene rendering, e.g. to\nregression and classification.\n\nIn contrast to most standard neural networks, CNPs learn to approximate a\ndistribution over functions rather than approximating just a single function. As a result, at\ntest time CNPs are flexible and can approximate any function from this\ndistribution when provided with a handful of observations. In addition, they\nlearn to estimate the uncertainty of their prediction from the dataset and as\nthe number of observations is increased this uncertainty reduces and the\naccuracy of their prediction increases.\n\nIn this notebook we describe the different parts of a CNP and apply the\nresulting model to a 1D regression task where a CNP is trained on a dataset of\nrandom functions.\n\nAny thoughts or questions? We'd love any feedback (about this notebook or CNPs\nin general) so just contact us at [email protected].", "_____no_output_____" ], [ "## Implementing CNPs\n\nWe start by importing the necessary dependencies. We will make use of numpy,\ntensorflow, and matplotlib.", "_____no_output_____" ] ], [ [ "!pip install tensorflow==1.12.0\nimport tensorflow as tf\nprint(tf.__version__)\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport collections", "Collecting tensorflow==1.12.0\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/22/cc/ca70b78087015d21c5f3f93694107f34ebccb3be9624385a911d4b52ecef/tensorflow-1.12.0-cp36-cp36m-manylinux1_x86_64.whl (83.1MB)\n\u001b[K |████████████████████████████████| 83.1MB 38kB/s \n\u001b[?25hRequirement already satisfied: absl-py>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (0.9.0)\nRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (1.12.0)\nCollecting tensorboard<1.13.0,>=1.12.0\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/07/53/8d32ce9471c18f8d99028b7cef2e5b39ea8765bd7ef250ca05b490880971/tensorboard-1.12.2-py3-none-any.whl (3.0MB)\n\u001b[K |████████████████████████████████| 3.1MB 47.2MB/s \n\u001b[?25hRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (0.34.2)\nRequirement already satisfied: gast>=0.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (0.3.3)\nRequirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (1.18.3)\nRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (1.1.0)\nRequirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (1.28.1)\nRequirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (1.1.0)\nRequirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (0.8.1)\nRequirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (3.10.0)\nRequirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.12.0) (1.0.8)\nRequirement already satisfied: werkzeug>=0.11.10 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.13.0,>=1.12.0->tensorflow==1.12.0) (1.0.1)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.13.0,>=1.12.0->tensorflow==1.12.0) (3.2.1)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tensorflow==1.12.0) (46.1.3)\nRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras-applications>=1.0.6->tensorflow==1.12.0) (2.10.0)\nInstalling collected packages: tensorboard, tensorflow\n Found existing installation: tensorboard 2.2.1\n Uninstalling tensorboard-2.2.1:\n Successfully uninstalled tensorboard-2.2.1\n Found existing installation: tensorflow 2.2.0rc3\n Uninstalling tensorflow-2.2.0rc3:\n Successfully uninstalled tensorflow-2.2.0rc3\nSuccessfully installed tensorboard-1.12.2 tensorflow-1.12.0\n" ] ], [ [ "## Training data\n\nA crucial property of CNPs is their flexibility at test time, as they can model\na whole range of functions and narrow down their prediction as we condition on\nan increasing number of context observations. This behaviour is a result of the\ntraining regime of CNPs which is reflected in our datasets.\n\n![](https://bit.ly/2O2Lq8c)\n\nRather than training using observations from a single function as it is often\nthe case in machine learning (for example value functions in reinforcement\nlearning) we will use a dataset that consists of many different functions that\nshare some underlying characteristics. This is visualized in the figure above.\nThe example on the left corresponds to a classic training regime: we have a\nsingle underlying ground truth function (eg. our value function for an agent) in\ngrey and at each learning iteration we are provided with a handful of examples from this\nfunction that we have visualized in different colours for batches of different\niterations. On the right we show an example of a dataset that could be used for\ntraining neural processes. Instead of a single function, it consists of a large number of functions of a function-class that we are interested in modeling. At each iteration we randomly choose one from the dataset and provide some observations from that function for training. For the next iteration we put that function back and\npick a new one from our dataset and use this new function to select the training\ndata. This type of dataset ensures that our model can't overfit to a single\nfunction but rather learns a distribution over functions. This idea of a\nhierarchical dataset also lies at the core of current meta-learning methods.\nExamples of such datasets could be:\n\n* Functions describing the evolution of temperature over time in different cities \nof the world.\n* A dataset of functions generated by a motion capture sensor of different humans\n walking.\n* As in this particular example differents functions generated by a Gaussian process (GP)\n with a specific kernel.\n\nWe have chosen GPs for the data generation of this example because they\nconstitute an easy way of sampling smooth curves that share some underlying\ncharacteristic (in this case the kernel). Other than for data generation of this\nparticular example neural processes do not make use of kernels or GPs as they\nare implemented as neural networks.", "_____no_output_____" ], [ "## Data generator\n\nIn the following section we provide the code for generating our training and\ntesting sets using a GP to generate a dataset of functions. As we will explain\nlater, CNPs use two subset of points at every iteration: one to serve as the\ncontext, and the other as targets. In practise we found that including the\ncontext points as targets together with some additional new points helped during\ntraining. Our data generator divides the generated data into these two groups\nand provides it in the correct format.", "_____no_output_____" ] ], [ [ "# The CNP takes as input a `CNPRegressionDescription` namedtuple with fields:\n# `query`: a tuple containing ((context_x, context_y), target_x)\n# `target_y`: a tesor containing the ground truth for the targets to be\n# predicted\n# `num_total_points`: A vector containing a scalar that describes the total\n# number of datapoints used (context + target)\n# `num_context_points`: A vector containing a scalar that describes the number\n# of datapoints used as context\n# The GPCurvesReader returns the newly sampled data in this format at each\n# iteration\n\nCNPRegressionDescription = collections.namedtuple(\n \"CNPRegressionDescription\",\n (\"query\", \"target_y\", \"num_total_points\", \"num_context_points\"))\n\n\nclass GPCurvesReader(object):\n \"\"\"Generates curves using a Gaussian Process (GP).\n\n Supports vector inputs (x) and vector outputs (y). Kernel is\n mean-squared exponential, using the x-value l2 coordinate distance scaled by\n some factor chosen randomly in a range. Outputs are independent gaussian\n processes.\n \"\"\"\n\n def __init__(self,\n batch_size,\n max_num_context,\n x_size=1,\n y_size=1,\n l1_scale=0.4,\n sigma_scale=1.0,\n testing=False):\n \"\"\"Creates a regression dataset of functions sampled from a GP.\n\n Args:\n batch_size: An integer.\n max_num_context: The max number of observations in the context.\n x_size: Integer >= 1 for length of \"x values\" vector.\n y_size: Integer >= 1 for length of \"y values\" vector.\n l1_scale: Float; typical scale for kernel distance function.\n sigma_scale: Float; typical scale for variance.\n testing: Boolean that indicates whether we are testing. If so there are\n more targets for visualization.\n \"\"\"\n self._batch_size = batch_size\n self._max_num_context = max_num_context\n self._x_size = x_size\n self._y_size = y_size\n self._l1_scale = l1_scale\n self._sigma_scale = sigma_scale\n self._testing = testing\n\n def _gaussian_kernel(self, xdata, l1, sigma_f, sigma_noise=2e-2):\n \"\"\"Applies the Gaussian kernel to generate curve data.\n\n Args:\n xdata: Tensor with shape `[batch_size, num_total_points, x_size]` with\n the values of the x-axis data.\n l1: Tensor with shape `[batch_size, y_size, x_size]`, the scale\n parameter of the Gaussian kernel.\n sigma_f: Float tensor with shape `[batch_size, y_size]`; the magnitude\n of the std.\n sigma_noise: Float, std of the noise that we add for stability.\n\n Returns:\n The kernel, a float tensor with shape\n `[batch_size, y_size, num_total_points, num_total_points]`.\n \"\"\"\n num_total_points = tf.shape(xdata)[1]\n\n # Expand and take the difference\n xdata1 = tf.expand_dims(xdata, axis=1) # [B, 1, num_total_points, x_size]\n xdata2 = tf.expand_dims(xdata, axis=2) # [B, num_total_points, 1, x_size]\n diff = xdata1 - xdata2 # [B, num_total_points, num_total_points, x_size]\n\n # [B, y_size, num_total_points, num_total_points, x_size]\n norm = tf.square(diff[:, None, :, :, :] / l1[:, :, None, None, :])\n\n norm = tf.reduce_sum(\n norm, -1) # [B, data_size, num_total_points, num_total_points]\n\n # [B, y_size, num_total_points, num_total_points]\n kernel = tf.square(sigma_f)[:, :, None, None] * tf.exp(-0.5 * norm)\n\n # Add some noise to the diagonal to make the cholesky work.\n kernel += (sigma_noise**2) * tf.eye(num_total_points)\n\n return kernel\n\n def generate_curves(self):\n \"\"\"Builds the op delivering the data.\n\n Generated functions are `float32` with x values between -2 and 2.\n \n Returns:\n A `CNPRegressionDescription` namedtuple.\n \"\"\"\n num_context = tf.random_uniform(\n shape=[], minval=3, maxval=self._max_num_context, dtype=tf.int32)\n\n # If we are testing we want to have more targets and have them evenly\n # distributed in order to plot the function. t\n if self._testing:\n num_target = 400\n num_total_points = num_target\n x_values = tf.tile(\n tf.expand_dims(tf.range(-2., 2., 1. / 100, dtype=tf.float32), axis=0),\n [self._batch_size, 1])\n x_values = tf.expand_dims(x_values, axis=-1)\n # During training the number of target points and their x-positions are\n # selected at random\n else:\n num_target = tf.random_uniform(\n shape=(), minval=2, maxval=self._max_num_context, dtype=tf.int32)\n num_total_points = num_context + num_target\n x_values = tf.random_uniform(\n [self._batch_size, num_total_points, self._x_size], -2, 2)\n\n # Set kernel parameters\n l1 = (\n tf.ones(shape=[self._batch_size, self._y_size, self._x_size]) *\n self._l1_scale)\n sigma_f = tf.ones(\n shape=[self._batch_size, self._y_size]) * self._sigma_scale\n\n # Pass the x_values through the Gaussian kernel\n # [batch_size, y_size, num_total_points, num_total_points]\n kernel = self._gaussian_kernel(x_values, l1, sigma_f)\n\n # Calculate Cholesky, using double precision for better stability:\n cholesky = tf.cast(tf.cholesky(tf.cast(kernel, tf.float64)), tf.float32)\n\n # Sample a curve\n # [batch_size, y_size, num_total_points, 1]\n y_values = tf.matmul(\n cholesky,\n tf.random_normal([self._batch_size, self._y_size, num_total_points, 1]))\n\n # [batch_size, num_total_points, y_size]\n y_values = tf.transpose(tf.squeeze(y_values, 3), [0, 2, 1])\n\n if self._testing:\n # Select the targets\n target_x = x_values\n target_y = y_values\n\n # Select the observations\n idx = tf.random_shuffle(tf.range(num_target))\n context_x = tf.gather(x_values, idx[:num_context], axis=1)\n context_y = tf.gather(y_values, idx[:num_context], axis=1)\n\n else:\n # Select the targets which will consist of the context points as well as\n # some new target points\n target_x = x_values[:, :num_target + num_context, :]\n target_y = y_values[:, :num_target + num_context, :]\n\n # Select the observations\n context_x = x_values[:, :num_context, :]\n context_y = y_values[:, :num_context, :]\n\n query = ((context_x, context_y), target_x)\n\n return CNPRegressionDescription(\n query=query,\n target_y=target_y,\n num_total_points=tf.shape(target_x)[1],\n num_context_points=num_context)", "_____no_output_____" ] ], [ [ "## Conditional Neural Processes\n\nWe can visualise a forward pass in a CNP as follows:\n\n<img src=\"https://bit.ly/2OFb6ZK\" alt=\"drawing\" width=\"400\"/>\n\nAs shown in the diagram, CNPs take in pairs **(x, y)<sub>i</sub>** of context\npoints, pass them through an **encoder** to obtain\nindividual representations **r<sub>i</sub>** which are combined using an **aggregator**. The resulting representation **r**\nis then combined with the locations of the targets **x<sub>T</sub>** and passed\nthrough a **decoder** that returns a mean estimate\nof the **y** value at that target location together with a measure of the\nuncertainty over said prediction. Implementing CNPs therefore involves coding up\nthe three main building blocks:\n\n* Encoder\n* Aggregator\n* Decoder\n\nA more detailed description of these three parts is presented in the following\nsections alongside the code.", "_____no_output_____" ], [ "## Encoder\n\nThe encoder **e** is shared between all the context points and consists of an\nMLP with a handful of layers. For this experiment four layers are enough, but we\ncan still change the number and size of the layers when we build the graph later\non via the variable **`encoder_output_sizes`**. Each of the context pairs **(x,\ny)<sub>i</sub>** results in an individual representation **r<sub>i</sub>** after\nencoding. These representations are then combined across context points to form\na single representation **r** using the aggregator **a**.\n\nIn this implementation we have included the aggregator **a** in the encoder as\nwe are only taking the mean across all points. The representation **r** produced\nby the aggregator contains the information about the underlying unknown function\n**f** that is provided by all the context points.", "_____no_output_____" ] ], [ [ "class DeterministicEncoder(object):\n \"\"\"The Encoder.\"\"\"\n\n def __init__(self, output_sizes):\n \"\"\"CNP encoder.\n\n Args:\n output_sizes: An iterable containing the output sizes of the encoding MLP.\n \"\"\"\n self._output_sizes = output_sizes\n\n def __call__(self, context_x, context_y, num_context_points):\n \"\"\"Encodes the inputs into one representation.\n\n Args:\n context_x: Tensor of size bs x observations x m_ch. For this 1D regression\n task this corresponds to the x-values.\n context_y: Tensor of size bs x observations x d_ch. For this 1D regression\n task this corresponds to the y-values.\n num_context_points: A tensor containing a single scalar that indicates the\n number of context_points provided in this iteration.\n\n Returns:\n representation: The encoded representation averaged over all context \n points.\n \"\"\"\n\n # Concatenate x and y along the filter axes\n encoder_input = tf.concat([context_x, context_y], axis=-1)\n\n # Get the shapes of the input and reshape to parallelise across observations\n batch_size, _, filter_size = encoder_input.shape.as_list()\n hidden = tf.reshape(encoder_input, (batch_size * num_context_points, -1))\n hidden.set_shape((None, filter_size))\n\n # Pass through MLP\n with tf.variable_scope(\"encoder\", reuse=tf.AUTO_REUSE):\n for i, size in enumerate(self._output_sizes[:-1]):\n print(i)\n hidden = tf.nn.relu(\n tf.layers.dense(hidden, size, name=\"Encoder_layer_{}\".format(i)))\n\n # Last layer without a ReLu\n hidden = tf.layers.dense(\n hidden, self._output_sizes[-1], name=\"Encoder_layer_{}\".format(i + 1))\n print(hidden)\n # Bring back into original shape\n hidden = tf.reshape(hidden, (batch_size, num_context_points, size))\n # Aggregator: take the mean over all points\n representation = tf.reduce_mean(hidden, axis=1)\n\n return representation", "_____no_output_____" ] ], [ [ "## Decoder\n\nOnce we have obtained our representation **r** we concatenate it with each of\nthe targets **x<sub>t</sub>** and pass it through the decoder **d**. As with the\nencoder **e**, the decoder **d** is shared between all the target points and\nconsists of a small MLP with layer sizes defined in **`decoder_output_sizes`**.\nThe decoder outputs a mean **&mu;<sub>t</sub>** and a variance\n**&sigma;<sub>t</sub>** for each of the targets **x<sub>t</sub>**. To train our\nCNP we use the log likelihood of the ground truth value **y<sub>t</sub>** under\na Gaussian parametrized by these predicted **&mu;<sub>t</sub>** and\n**&sigma;<sub>t</sub>**.\n\nIn this implementation we clip the variance **&sigma;<sub>t</sub>** at 0.1 to\navoid collapsing.", "_____no_output_____" ] ], [ [ "class DeterministicDecoder(object):\n \"\"\"The Decoder.\"\"\"\n\n def __init__(self, output_sizes):\n \"\"\"CNP decoder.\n\n Args:\n output_sizes: An iterable containing the output sizes of the decoder MLP \n as defined in `basic.Linear`.\n \"\"\"\n self._output_sizes = output_sizes\n\n def __call__(self, representation, target_x, num_total_points):\n \"\"\"Decodes the individual targets.\n\n Args:\n representation: The encoded representation of the context\n target_x: The x locations for the target query\n num_total_points: The number of target points.\n\n Returns:\n dist: A multivariate Gaussian over the target points.\n mu: The mean of the multivariate Gaussian.\n sigma: The standard deviation of the multivariate Gaussian.\n \"\"\"\n\n # Concatenate the representation and the target_x\n representation = tf.tile(\n tf.expand_dims(representation, axis=1), [1, num_total_points, 1])\n input = tf.concat([representation, target_x], axis=-1)\n\n # Get the shapes of the input and reshape to parallelise across observations\n batch_size, _, filter_size = input.shape.as_list()\n hidden = tf.reshape(input, (batch_size * num_total_points, -1))\n hidden.set_shape((None, filter_size))\n\n # Pass through MLP\n with tf.variable_scope(\"decoder\", reuse=tf.AUTO_REUSE):\n for i, size in enumerate(self._output_sizes[:-1]):\n print(i)\n hidden = tf.nn.relu(\n tf.layers.dense(hidden, size, name=\"Decoder_layer_{}\".format(i)))\n\n # Last layer without a ReLu\n hidden = tf.layers.dense(\n hidden, self._output_sizes[-1], name=\"Decoder_layer_{}\".format(i + 1))\n\n # Bring back into original shape\n print(hidden)\n hidden = tf.reshape(hidden, (batch_size, num_total_points, -1))\n\n # Get the mean an the variance\n mu, log_sigma = tf.split(hidden, 2, axis=-1)\n\n # Bound the variance\n sigma = 0.1 + 0.9 * tf.nn.softplus(log_sigma)\n print(f' this is the covariance matrix{sigma.shape}')\n # Get the distribution\n dist = tf.contrib.distributions.MultivariateNormalDiag(\n loc=mu, scale_diag=sigma)\n\n return dist, mu, sigma", "_____no_output_____" ] ], [ [ "## Model\n\nNow that the main building blocks (encoder, aggregator and decoder) of the CNP\nare defined we can put everything together into one model. Fundamentally this\nmodel only needs to include two main methods: 1. A method that returns the log\nlikelihood of the targets' ground truth values under the predicted\ndistribution.This method will be called during training as our loss function. 2.\nAnother method that returns the predicted mean and variance at the target\nlocations in order to evaluate or query the CNP at test time. This second method\nneeds to be defined separately as, unlike the method above, it should not depend\non the ground truth target values.", "_____no_output_____" ] ], [ [ "class DeterministicModel(object):\n \"\"\"The CNP model.\"\"\"\n\n def __init__(self, encoder_output_sizes, decoder_output_sizes):\n \"\"\"Initialises the model.\n\n Args:\n encoder_output_sizes: An iterable containing the sizes of hidden layers of\n the encoder. The last one is the size of the representation r.\n decoder_output_sizes: An iterable containing the sizes of hidden layers of\n the decoder. The last element should correspond to the dimension of\n the y * 2 (it encodes both mean and variance concatenated)\n \"\"\"\n self._encoder = DeterministicEncoder(encoder_output_sizes)\n self._decoder = DeterministicDecoder(decoder_output_sizes)\n\n def __call__(self, query, num_total_points, num_contexts, target_y=None):\n \"\"\"Returns the predicted mean and variance at the target points.\n\n Args:\n query: Array containing ((context_x, context_y), target_x) where:\n context_x: Array of shape batch_size x num_context x 1 contains the \n x values of the context points.\n context_y: Array of shape batch_size x num_context x 1 contains the \n y values of the context points.\n target_x: Array of shape batch_size x num_target x 1 contains the\n x values of the target points.\n target_y: The ground truth y values of the target y. An array of \n shape batchsize x num_targets x 1.\n num_total_points: Number of target points.\n\n Returns:\n log_p: The log_probability of the target_y given the predicted\n distribution.\n mu: The mean of the predicted distribution.\n sigma: The variance of the predicted distribution.\n \"\"\"\n\n (context_x, context_y), target_x = query\n\n # Pass query through the encoder and the decoder\n representation = self._encoder(context_x, context_y, num_contexts)\n dist, mu, sigma = self._decoder(representation, target_x, num_total_points)\n\n # If we want to calculate the log_prob for training we will make use of the\n # target_y. At test time the target_y is not available so we return None\n if target_y is not None:\n log_p = dist.log_prob(target_y)\n \n else:\n log_p = None\n\n return log_p, mu, sigma", "_____no_output_____" ] ], [ [ "## Plotting function\nWe define a helper function for plotting the intermediate predictions\nevery `PLOT_AFTER` iterations. The ground truth curve will be shown as a black\ndotted line and the context points from this curve that are fed into the model\nas black dots. The model's predicted mean and variance is shown in blue for a\nrange of target points in the interval [-2, 2].", "_____no_output_____" ] ], [ [ "def plot_functions(target_x, target_y, context_x, context_y, pred_y, var):\n \"\"\"Plots the predicted mean and variance and the context points.\n \n Args: \n target_x: An array of shape batchsize x number_targets x 1 that contains the\n x values of the target points.\n target_y: An array of shape batchsize x number_targets x 1 that contains the\n y values of the target points.\n context_x: An array of shape batchsize x number_context x 1 that contains \n the x values of the context points.\n context_y: An array of shape batchsize x number_context x 1 that contains \n the y values of the context points.\n pred_y: An array of shape batchsize x number_targets x 1 that contains the\n predicted means of the y values at the target points in target_x.\n pred_y: An array of shape batchsize x number_targets x 1 that contains the\n predicted variance of the y values at the target points in target_x.\n \"\"\"\n # Plot everything\n print(f'this is the variance in the plotting function{var.shape}')\n plt.plot(target_x[0], pred_y[0], 'b', linewidth=2)\n plt.plot(target_x[0], target_y[0], 'k:', linewidth=2)\n plt.plot(context_x[0], context_y[0], 'ko', markersize=10)\n plt.fill_between(\n target_x[0, :, 0],\n pred_y[0, :, 0] - var[0, :, 0],\n pred_y[0, :, 0] + var[0, :, 0],\n alpha=0.2,\n facecolor='#65c9f7',\n interpolate=True)\n\n # Make the plot pretty\n plt.yticks([-2, 0, 2], fontsize=16)\n plt.xticks([-2, 0, 2], fontsize=16)\n plt.ylim([-2, 2])\n plt.grid('off')\n ax = plt.gca()\n plt.show()", "_____no_output_____" ] ], [ [ "## Running Conditional Neural Processes\n\nNow that we have defined the dataset as well as our model and its components we\ncan start building everything into the graph. Before we get started we need to\nset some variables:\n\n* **`TRAINING_ITERATIONS`** - a scalar that describes the number of iterations\n for training. At each iteration we will sample a new batch of functions from\n the GP, pick some of the points on the curves as our context points **(x,\n y)<sub>C</sub>** and some points as our target points **(x,\n y)<sub>T</sub>**. We will predict the mean and variance at the target points\n given the context and use the log likelihood of the ground truth targets as\n our loss to update the model.\n* **`MAX_CONTEXT_POINTS`** - a scalar that sets the maximum number of contest\n points used during training. The number of context points will then be a\n value between 3 and `MAX_CONTEXT_POINTS` that is sampled at random for every\n iteration.\n* **`PLOT_AFTER`** - a scalar that regulates how often we plot the\n intermediate results.", "_____no_output_____" ] ], [ [ "TRAINING_ITERATIONS = int(2e5)\nMAX_CONTEXT_POINTS = 10\nPLOT_AFTER = int(2e4)\ntf.reset_default_graph()", "_____no_output_____" ] ], [ [ "We add the dataset reader to the graph for both the training and the testing\nset. As mentioned above for this experiment the dataset consists of functions\nthat are sampled anew from a GP at each iteration. The main difference between\ntrain and test in this case is that the test set contains more targets so that\nwe can plot the entire curve, whereas the training set only contains a few\ntarget points to predict.", "_____no_output_____" ] ], [ [ "# Train dataset\ndataset_train = GPCurvesReader(\n batch_size=64, max_num_context=MAX_CONTEXT_POINTS)\ndata_train = dataset_train.generate_curves()\n# Test dataset\ndataset_test = GPCurvesReader(\n batch_size=1, max_num_context=MAX_CONTEXT_POINTS, testing=True)\ndata_test = dataset_test.generate_curves()", "_____no_output_____" ] ], [ [ "We can now add the model to the graph and finalise it by defining the train step\nand the initializer.", "_____no_output_____" ] ], [ [ "# Sizes of the layers of the MLPs for the encoder and decoder\n# The final output layer of the decoder outputs two values, one for the mean and\n# one for the variance of the prediction at the target location\nencoder_output_sizes = [128, 128, 128, 128]\ndecoder_output_sizes = [128, 128, 2]\n\n# Define the model\nmodel = DeterministicModel(encoder_output_sizes, decoder_output_sizes)\n\n# Define the loss\nlog_prob, _, _ = model(data_train.query, data_train.num_total_points,\n data_train.num_context_points, data_train.target_y)\nloss = -tf.reduce_mean(log_prob)\n\n# Get the predicted mean and variance at the target points for the testing set\n_, mu, sigma = model(data_test.query, data_test.num_total_points,\n data_test.num_context_points)\n\n# Set up the optimizer and train step\noptimizer = tf.train.AdamOptimizer(1e-4)\ntrain_step = optimizer.minimize(loss)\ninit = tf.initialize_all_variables()", "0\n1\n2\nTensor(\"encoder/Encoder_layer_3/BiasAdd:0\", shape=(?, 128), dtype=float32)\n0\n1\nTensor(\"decoder/Decoder_layer_2/BiasAdd:0\", shape=(?, 2), dtype=float32)\n this is the covariance matrix(64, ?, ?)\n0\n1\n2\nTensor(\"encoder_1/Encoder_layer_3/BiasAdd:0\", shape=(?, 128), dtype=float32)\n0\n1\nTensor(\"decoder_1/Decoder_layer_2/BiasAdd:0\", shape=(400, 2), dtype=float32)\n this is the covariance matrix(1, 400, 1)\n" ], [ "model._decoder._output_sizes", "_____no_output_____" ], [ "model.__sizeof__()", "_____no_output_____" ] ], [ [ "We are ready to train the model! During training we will plot some intermediate\npredictions to visualize how the model evolves.\n\nEvery `PLOT_AFTER` iterations we print out the loss, which corresponds to the\nnegative log probability of the ground truth targets under the predicted\ndistribution. As the model is trained this value should decrease.\n\nIn addition we are going to plot the predictions of our model alongside the\nground truth curve and the context points that the CNP is provided at that\niteration.", "_____no_output_____" ] ], [ [ "with tf.Session() as sess:\n sess.run(init)\n\n for it in range(TRAINING_ITERATIONS):\n sess.run([train_step])\n \n\n # Plot the predictions in `PLOT_AFTER` intervals\n if it % PLOT_AFTER == 0:\n loss_value, pred_y, var, target_y, whole_query = sess.run(\n [loss, mu, sigma, data_test.target_y, data_test.query])\n\n (context_x, context_y), target_x = whole_query\n print('Iteration: {}, loss: {}'.format(it, loss_value))\n\n # Plot the prediction and the context\n plot_functions(target_x, target_y, context_x, context_y, pred_y, var)", "Iteration: 0, loss: 1.3950097560882568\nthis is the variance in the plotting function(1, 400, 1)\n" ], [ "import torch\n", "_____no_output_____" ], [ "from datasets import SineData\n", "_____no_output_____" ], [ "Hola, me llamo Fred soy de alemania y estoy buscando una habitación por 2-4 semanas a partir del 1 de julio para terminar mi trabajo de fin de master\nVivía en Madrid pero preferiría passar el verano en Donosti. Estaba pensando que quizás tengas dificuldades en encontrar\ncompañeros con la situación actual (Corona) y por eso te escribo. ", "_____no_output_____" ], [ "1e-4", "_____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" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
ec4f61eea3071abf72a578871bde527469c3a6e9
57,057
ipynb
Jupyter Notebook
notebooks/alt_ref_pairs_in_network.ipynb
Seb-Leb/altProts_in_communities
ee5f39f0058275909527625f6d196460afbcd464
[ "MIT" ]
null
null
null
notebooks/alt_ref_pairs_in_network.ipynb
Seb-Leb/altProts_in_communities
ee5f39f0058275909527625f6d196460afbcd464
[ "MIT" ]
null
null
null
notebooks/alt_ref_pairs_in_network.ipynb
Seb-Leb/altProts_in_communities
ee5f39f0058275909527625f6d196460afbcd464
[ "MIT" ]
1
2021-02-10T11:50:54.000Z
2021-02-10T11:50:54.000Z
56.380435
13,852
0.668244
[ [ [ "import pickle\nfrom collections import Counter\nfrom altProts_in_communities.network_assembly import *\nfrom altProts_in_communities.utils import *", "_____no_output_____" ], [ "ev1 = pickle.load(open('ev1.pkl', 'rb'))\nG_o = pickle.load(open('G_o.pkl', 'rb'))\nBG = pickle.load(open('biogrid_networkx.pkl', 'rb'))", "_____no_output_____" ], [ "detection_summary = pickle.load(open('detection_summary.pkl', 'rb'))\ndetected_alts = set([x[0] for x in detection_summary if x[-1]])\nlen(detected_alts)", "_____no_output_____" ], [ "alt_pseudos = set([x['altProt accession'] for x in ev1 if 'pseudo' in x['gene biotype']])\nlen(alt_pseudos)", "_____no_output_____" ], [ "# http://www.pseudogene.org/psicube/data/gencode.v10.pgene.parents.txt\npseudo_parent_dict = pickle.load(open('pseudo_parent_dict.pkl', 'rb'))", "_____no_output_____" ], [ "pseudo_parent_refProt_acc = dict([\n ('AK2', 'ENSP00000346921.6'), \n ('ANXA2', 'ENSP00000346032.3'), \n ('ASS1', 'ENSP00000253004.6'), \n ('CCT6A', 'ENSP00000275603.4'), \n ('CCT8', 'ENSP00000286788.4'), \n ('DNAJA1', 'ENSP00000369127.3'),\n ('GAPDH', 'ENSP00000229239.5'),\n ('GLUL', 'ENSP00000307900.5'),\n ('HMGB3', 'ENSP00000359393.3'),\n ('HNRNPA1', 'ENSP00000341826.6'),\n ('HSP90AA1', 'ENSP00000335153.7'),\n ('HSPD1', 'ENSP00000340019.2'),\n ('RPS2', 'ENSP00000341885.4'),\n ('ST13', 'ENSP00000216218.3')\n])", "_____no_output_____" ], [ "ensmbl_gene_prot = {}\nwith open('mart_export.txt', 'r') as f:\n reader = csv.reader(f, delimiter='\\t')\n for n,row in enumerate(reader):\n if n==0:\n keys = row\n continue\n line = dict(zip(keys, row))\n ensmbl_gene_prot[line['Gene name']] = line['Protein stable ID']", "_____no_output_____" ], [ "psicube_dict = {}\nwith open('gencode.v10.pgene.parents.txt', 'r') as f:\n for n,l in enumerate(f):\n ls = l.strip().split('\\t')\n if n==0:\n keys = ls\n continue\n line = dict(zip(keys, ls))\n if 'Parent name' in line:\n psicube_dict[line['Name']] = line['Parent name']\n elif 'Parent gene' in line:\n psicube_dict[line['Name']] = line['Parent gene']", "_____no_output_____" ], [ "pseudo_parent_prot_pairs = {}\nmissing_parent_genes = []\nfor alt_acc in alt_pseudos:\n pseudogene = prot_gene_dict[alt_acc]\n pseudo_parent_prot_pairs[(alt_acc, pseudogene)] = {}\n \n if pseudogene in pseudo_parent_dict:\n pseudo_parent_prot_pairs[(alt_acc, pseudogene)].update(pseudo_parent_dict[pseudogene])\n \n elif pseudogene in psicube_dict:\n parent = psicube_dict[pseudogene]\n if parent not in pseudo_parent_refProt_acc:\n print(\"pseudo_parent_dict['{}'] = 'parent':'{}', 'prot_acc':'', 'alt_acc':'{}'\".format(pseudogene, parent, alt_acc))\n continue\n pseudo_parent_prot_pairs[(alt_acc, pseudogene)] = {'parent': psicube_dict[pseudogene], 'prot_acc':pseudo_parent_refProt_acc[parent], 'alt_acc':alt_acc}\n\n else:\n missing_parent_genes.append(pseudogene)\n print(\"No parent found: {}|{}\".format(pseudogene, alt_acc))", "No parent found: LOC646938|IP_734554\nNo parent found: SULT1C2P2|IP_638493\nNo parent found: AC008758.4|IP_691643\nNo parent found: AL096701.1|IP_651189\nNo parent found: EEF1GP5|IP_558531\nNo parent found: KRT89P|IP_762764\nNo parent found: HLA-V|IP_597081\nNo parent found: AC010677.1|IP_584259\nNo parent found: AL391419.1|IP_556791\nNo parent found: KRT87P|IP_3404123\nNo parent found: AC008481.1|IP_691723\nNo parent found: AC008567.1|IP_689722\nNo parent found: AL355994.2|IP_671823\nNo parent found: FMO5|IP_669446\nNo parent found: AC025470.1|IP_603113\nNo parent found: AL021407.2|IP_595437\nNo parent found: AC110994.1|IP_622877\nNo parent found: AL139100.1|IP_592636\npseudo_parent_dict['BRD7P6'] = 'parent':'BRD7', 'prot_acc':'', 'alt_acc':'IP_638355'\nNo parent found: TUBB8P11|IP_673226\nNo parent found: AL355365.1|IP_589156\nNo parent found: KRT89P|IP_3435724\nNo parent found: HSPA8P7|IP_557401\nNo parent found: KLRA1P|IP_763043\nNo parent found: AC010395.2|IP_602155\nNo parent found: AC008481.2|IP_691726\nNo parent found: PSAT1P1|IP_571913\nNo parent found: SORD2P|IP_737297\nNo parent found: AC098590.1|IP_614318\nNo parent found: AL121916.1|IP_665467\n" ], [ "#http://scikit-bio.org/docs/0.4.2/generated/skbio.alignment.global_pairwise_align_protein.html#skbio.alignment.global_pairwise_align_protein\nfrom skbio.alignment import global_pairwise_align_protein\nfrom skbio.sequence import Protein", "/home/sleblanc/anaconda3/lib/python3.7/site-packages/skbio/util/_testing.py:15: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as pdt\n" ], [ "blosum62 = {\n ('W', 'F'): 1, ('L', 'R'): -2, ('S', 'P'): -1, ('V', 'T'): 0,\n ('Q', 'Q'): 5, ('N', 'A'): -2, ('Z', 'Y'): -2, ('W', 'R'): -3,\n ('Q', 'A'): -1, ('S', 'D'): 0, ('H', 'H'): 8, ('S', 'H'): -1,\n ('H', 'D'): -1, ('L', 'N'): -3, ('W', 'A'): -3, ('Y', 'M'): -1,\n ('G', 'R'): -2, ('Y', 'I'): -1, ('Y', 'E'): -2, ('B', 'Y'): -3,\n ('Y', 'A'): -2, ('V', 'D'): -3, ('B', 'S'): 0, ('Y', 'Y'): 7,\n ('G', 'N'): 0, ('E', 'C'): -4, ('Y', 'Q'): -1, ('Z', 'Z'): 4,\n ('V', 'A'): 0, ('C', 'C'): 9, ('M', 'R'): -1, ('V', 'E'): -2,\n ('T', 'N'): 0, ('P', 'P'): 7, ('V', 'I'): 3, ('V', 'S'): -2,\n ('Z', 'P'): -1, ('V', 'M'): 1, ('T', 'F'): -2, ('V', 'Q'): -2,\n ('K', 'K'): 5, ('P', 'D'): -1, ('I', 'H'): -3, ('I', 'D'): -3,\n ('T', 'R'): -1, ('P', 'L'): -3, ('K', 'G'): -2, ('M', 'N'): -2,\n ('P', 'H'): -2, ('F', 'Q'): -3, ('Z', 'G'): -2, ('X', 'L'): -1,\n ('T', 'M'): -1, ('Z', 'C'): -3, ('X', 'H'): -1, ('D', 'R'): -2,\n ('B', 'W'): -4, ('X', 'D'): -1, ('Z', 'K'): 1, ('F', 'A'): -2,\n ('Z', 'W'): -3, ('F', 'E'): -3, ('D', 'N'): 1, ('B', 'K'): 0,\n ('X', 'X'): -1, ('F', 'I'): 0, ('B', 'G'): -1, ('X', 'T'): 0,\n ('F', 'M'): 0, ('B', 'C'): -3, ('Z', 'I'): -3, ('Z', 'V'): -2,\n ('S', 'S'): 4, ('L', 'Q'): -2, ('W', 'E'): -3, ('Q', 'R'): 1,\n ('N', 'N'): 6, ('W', 'M'): -1, ('Q', 'C'): -3, ('W', 'I'): -3,\n ('S', 'C'): -1, ('L', 'A'): -1, ('S', 'G'): 0, ('L', 'E'): -3,\n ('W', 'Q'): -2, ('H', 'G'): -2, ('S', 'K'): 0, ('Q', 'N'): 0,\n ('N', 'R'): 0, ('H', 'C'): -3, ('Y', 'N'): -2, ('G', 'Q'): -2,\n ('Y', 'F'): 3, ('C', 'A'): 0, ('V', 'L'): 1, ('G', 'E'): -2,\n ('G', 'A'): 0, ('K', 'R'): 2, ('E', 'D'): 2, ('Y', 'R'): -2,\n ('M', 'Q'): 0, ('T', 'I'): -1, ('C', 'D'): -3, ('V', 'F'): -1,\n ('T', 'A'): 0, ('T', 'P'): -1, ('B', 'P'): -2, ('T', 'E'): -1,\n ('V', 'N'): -3, ('P', 'G'): -2, ('M', 'A'): -1, ('K', 'H'): -1,\n ('V', 'R'): -3, ('P', 'C'): -3, ('M', 'E'): -2, ('K', 'L'): -2,\n ('V', 'V'): 4, ('M', 'I'): 1, ('T', 'Q'): -1, ('I', 'G'): -4,\n ('P', 'K'): -1, ('M', 'M'): 5, ('K', 'D'): -1, ('I', 'C'): -1,\n ('Z', 'D'): 1, ('F', 'R'): -3, ('X', 'K'): -1, ('Q', 'D'): 0,\n ('X', 'G'): -1, ('Z', 'L'): -3, ('X', 'C'): -2, ('Z', 'H'): 0,\n ('B', 'L'): -4, ('B', 'H'): 0, ('F', 'F'): 6, ('X', 'W'): -2,\n ('B', 'D'): 4, ('D', 'A'): -2, ('S', 'L'): -2, ('X', 'S'): 0,\n ('F', 'N'): -3, ('S', 'R'): -1, ('W', 'D'): -4, ('V', 'Y'): -1,\n ('W', 'L'): -2, ('H', 'R'): 0, ('W', 'H'): -2, ('H', 'N'): 1,\n ('W', 'T'): -2, ('T', 'T'): 5, ('S', 'F'): -2, ('W', 'P'): -4,\n ('L', 'D'): -4, ('B', 'I'): -3, ('L', 'H'): -3, ('S', 'N'): 1,\n ('B', 'T'): -1, ('L', 'L'): 4, ('Y', 'K'): -2, ('E', 'Q'): 2,\n ('Y', 'G'): -3, ('Z', 'S'): 0, ('Y', 'C'): -2, ('G', 'D'): -1,\n ('B', 'V'): -3, ('E', 'A'): -1, ('Y', 'W'): 2, ('E', 'E'): 5,\n ('Y', 'S'): -2, ('C', 'N'): -3, ('V', 'C'): -1, ('T', 'H'): -2,\n ('P', 'R'): -2, ('V', 'G'): -3, ('T', 'L'): -1, ('V', 'K'): -2,\n ('K', 'Q'): 1, ('R', 'A'): -1, ('I', 'R'): -3, ('T', 'D'): -1,\n ('P', 'F'): -4, ('I', 'N'): -3, ('K', 'I'): -3, ('M', 'D'): -3,\n ('V', 'W'): -3, ('W', 'W'): 11, ('M', 'H'): -2, ('P', 'N'): -2,\n ('K', 'A'): -1, ('M', 'L'): 2, ('K', 'E'): 1, ('Z', 'E'): 4,\n ('X', 'N'): -1, ('Z', 'A'): -1, ('Z', 'M'): -1, ('X', 'F'): -1,\n ('K', 'C'): -3, ('B', 'Q'): 0, ('X', 'B'): -1, ('B', 'M'): -3,\n ('F', 'C'): -2, ('Z', 'Q'): 3, ('X', 'Z'): -1, ('F', 'G'): -3,\n ('B', 'E'): 1, ('X', 'V'): -1, ('F', 'K'): -3, ('B', 'A'): -2,\n ('X', 'R'): -1, ('D', 'D'): 6, ('W', 'G'): -2, ('Z', 'F'): -3,\n ('S', 'Q'): 0, ('W', 'C'): -2, ('W', 'K'): -3, ('H', 'Q'): 0,\n ('L', 'C'): -1, ('W', 'N'): -4, ('S', 'A'): 1, ('L', 'G'): -4,\n ('W', 'S'): -3, ('S', 'E'): 0, ('H', 'E'): 0, ('S', 'I'): -2,\n ('H', 'A'): -2, ('S', 'M'): -1, ('Y', 'L'): -1, ('Y', 'H'): 2,\n ('Y', 'D'): -3, ('E', 'R'): 0, ('X', 'P'): -2, ('G', 'G'): 6,\n ('G', 'C'): -3, ('E', 'N'): 0, ('Y', 'T'): -2, ('Y', 'P'): -3,\n ('T', 'K'): -1, ('A', 'A'): 4, ('P', 'Q'): -1, ('T', 'C'): -1,\n ('V', 'H'): -3, ('T', 'G'): -2, ('I', 'Q'): -3, ('Z', 'T'): -1,\n ('C', 'R'): -3, ('V', 'P'): -2, ('P', 'E'): -1, ('M', 'C'): -1,\n ('K', 'N'): 0, ('I', 'I'): 4, ('P', 'A'): -1, ('M', 'G'): -3,\n ('T', 'S'): 1, ('I', 'E'): -3, ('P', 'M'): -2, ('M', 'K'): -1,\n ('I', 'A'): -1, ('P', 'I'): -3, ('R', 'R'): 5, ('X', 'M'): -1,\n ('L', 'I'): 2, ('X', 'I'): -1, ('Z', 'B'): 1, ('X', 'E'): -1,\n ('Z', 'N'): 0, ('X', 'A'): 0, ('B', 'R'): -1, ('B', 'N'): 3,\n ('F', 'D'): -3, ('X', 'Y'): -1, ('Z', 'R'): 0, ('F', 'H'): -1,\n ('B', 'F'): -3, ('F', 'L'): 0, ('X', 'Q'): -1, ('B', 'B'): 4\n}\n\nBLOSUM62 = {}\nfor aas, s in blosum62.items():\n aa1, aa2 = aas\n if aa1 not in BLOSUM62:\n BLOSUM62[aa1] = {}\n if aa2 not in BLOSUM62:\n BLOSUM62[aa2] = {}\n BLOSUM62[aa1].update({aa2:s})\n BLOSUM62[aa2].update({aa1:s})", "_____no_output_____" ], [ "fasta_fields = ['OS', 'GN', 'TA', 'PA']\ndef parse_fasta_header(h):\n h = h.split()\n acc = h[0].split('|')[0]\n res = {}\n for f in h[1:]:\n for field in fasta_fields:\n if f[:2] == field:\n res[field] = f[3:]\n if 'GN' not in res:\n res['GN'] = 'unknown'\n if 'PA' in res and ',' in res['PA']:\n res['PA'] = res['PA'].split(',')\n return res ", "_____no_output_____" ], [ "prot_seq_dict = {}\nfor rec in SeqIO.parse('human-openprot-r1_6-refprots+altprots+isoforms-+uniprot2019_03_01.fasta', 'fasta'):\n tt_acc = rec.name.split('|')[0]\n prot_seq_dict[tt_acc] = rec.seq\n if '.' in tt_acc:\n prot_seq_dict[tt_acc.split('.')[0]] = rec.seq\n header = parse_fasta_header(rec.description)\n \n if 'PA' in header:\n for pa in header['PA']:\n prot_seq_dict[pa.split('.')[0]] = rec.seq", "_____no_output_____" ], [ "G_paths = G_o.copy()\nsps, alignments = [], []\nmissing_parent_genes = []\nfor pseudo_alt, parent_prot in pseudo_parent_prot_pairs.items():\n alt_acc, pseudogene = pseudo_alt\n alt_acc_gene = '|'.join([pseudogene, alt_acc])\n if 'parent' not in parent_prot:\n missing_parent_genes.append(pseudo_alt)\n print('missing parent gene:', pseudo_alt)\n continue\n parent_gene = parent_prot['parent']\n sp = 0\n seq1 = Protein(altprotseq_dict[alt_acc])\n if parent_prot['prot_acc'].split('.')[0] not in prot_seq_dict:\n print('not in seq dict:', parent_prot['prot_acc'].split('.')[0])\n break\n seq2 = str(prot_seq_dict[parent_prot['prot_acc'].split('.')[0]])\n if seq2:\n seq2 = Protein(seq2)\n else:\n print('No seq from OP:', parent_prot['prot_acc'])\n continue\n \n NW_score = global_pairwise_align_protein(seq1, seq2, gap_open_penalty=10, gap_extend_penalty=0.5, substitution_matrix=BLOSUM62, penalize_terminal_gaps=False)\n pseudo_parent_prot_pairs[pseudo_alt].update({'sortest_path_len':sp, 'NW_score':NW_score[1]})\n \n if parent_gene in G_paths:\n try:\n sp = nx.shortest_path_length(G_paths, alt_acc_gene, parent_gene)\n except:\n print('issue calculating path - ', alt_acc_gene, parent_gene)\n continue\n \n elif parent_gene in G_b:\n for n in G_b.neighbors(parent_gene):\n if n in G_paths:\n G_paths.add_edge(parent_gene, n)\n try:\n sp = nx.shortest_path_length(G_paths, alt_acc_gene, parent_gene)\n except:\n print('{} - {} no path'.format(parent_gene, alt_acc_gene))\n print(parent_gene, 'in BP2', )\n \n elif parent_gene in BG:\n if sum(n in G_paths for n in BG.neighbors(parent_gene)) == 0: continue# no BioGrid 2nd deg neighbors in G_o\n for n in BG.neighbors(parent_gene):\n if n in G_paths:\n G_paths.add_edge(parent_gene, n)\n try:\n sp = nx.shortest_path_length(G_paths, alt_acc_gene, parent_gene)\n except:\n print('{} - {} no path'.format(parent_gene, alt_acc_gene))\n print(parent_gene, 'in BIOGRID', sp)\n \n if sp<1: continue\n pseudo_parent_prot_pairs[pseudo_alt].update({'sortest_path_len':sp, 'NW_score':NW_score[1]})\n sps.append(sp)\n alignments.append(NW_score[1])\n print(alt_acc, pseudogene, parent_gene, sp)", "/home/sleblanc/anaconda3/lib/python3.7/site-packages/skbio/alignment/_pairwise.py:599: EfficiencyWarning: You're using skbio's python implementation of Needleman-Wunsch alignment. This is known to be very slow (e.g., thousands of times slower than a native C implementation). We'll be adding a faster version soon (see https://github.com/biocore/scikit-bio/issues/254 to track progress on this).\n \"to track progress on this).\", EfficiencyWarning)\n" ], [ "sps_plot = []\nfor sp in sps:\n sps_plot.append(sp+np.random.normal(0, 0.1))\nprint('count alt-pseugogene pairs:', len(sps_plot))\nfig, ax = plt.subplots()\nax.bar(range(1, 8), [max(alignments)+100,]*7, width=1, color=['#dfdfdf','w'], )\nax.scatter(sps_plot, alignments, s=12, color='#8F2D56', zorder=10)\n#ax.set_ylim(0,100)\nax.set_xlabel('shortest path length')\nax.set_xticks(range(1,8))\nax.set_ylabel('NW alignment score')\nplt.savefig('bioplex_figures/pseudo_alt_sp.svg')\nplt.show()", "count alt-pseugogene pairs: 80\n" ], [ "interpro = pickle.load(open('interpro.pkl', 'rb'))", "_____no_output_____" ], [ "prent_prots = [p['prot_acc'] for p in pseudo_parent_prot_pairs.values() if 'prot_acc' in p and p['prot_acc']]", "_____no_output_____" ], [ "altpseudo_parent_interpro = []\nfor alt_pseudogene, parent in pseudo_parent_prot_pairs.items():\n if 'prot_acc' not in parent or not parent['prot_acc']: continue\n alt_acc, pseudogene = alt_pseudogene\n alt_interpro, parent_interpro, alt_interpro_id, alt_interpro_desc, parent_interpro_id, parent_interpro_desc = ['NA']*6\n if alt_acc in interpro:\n alt_interpro_id = '|'.join(interpro[alt_acc]['ipr_ids'])\n alt_interpro_desc = '|'.join(interpro[alt_acc]['ipr_desc'])\n \n if parent['prot_acc'] in interpro:\n parent_interpro_id = '|'.join(interpro[parent['prot_acc']]['ipr_ids'])\n parent_interpro_desc = '|'.join(interpro[parent['prot_acc']]['ipr_desc'])\n \n count_shared_interpro = len(set(alt_interpro_id.split('|')).intersection(set(parent_interpro_id.split('|'))))\n\n sp = parent['sortest_path_len'] if 'sortest_path_len' in parent and parent['sortest_path_len']>0 else 'no path'\n NW = parent['NW_score']\n altpseudo_parent_interpro.append((alt_acc, pseudogene, parent['parent'], parent['prot_acc'], sp, NW, count_shared_interpro, alt_interpro_desc, parent_interpro_desc, alt_interpro_id, parent_interpro_id))", "_____no_output_____" ], [ "cols = ('altProt accession', 'pseudogene', 'parent gene', 'parent refProt', 'shortest path length', 'NW alignment score', \n 'count shared interproscan', 'altProt interproscan descriptions', 'refProt interproscan descriptions', \n 'altProt interproscan ids', 'refProt interproscan ids')\n\nwith open('bioplex_tables/Table_S4.tsv', 'w') as f:\n writer = csv.writer(f, delimiter='\\t')\n writer.writerow(cols)\n for l in sorted(altpseudo_parent_interpro, key=lambda x: x[4] if type(x[4])==int else 100):\n writer.writerow(l)", "_____no_output_____" ], [ "alt_coding = set([x['altProt accession'] for x in ev1 if 'protein_coding' in x['gene biotype']])\nlen(alt_coding)", "_____no_output_____" ], [ "G_paths = G_o.copy()\nalt_coding_shortest_paths = []\nprocessed_pepgrps = []\nfor alt in alt_coding:\n gene = prot_gene_dict[alt]\n gene_alt = '|'.join([gene, alt])\n if gene in G_paths:\n try:\n alt_coding_shortest_paths.append(\n (gene, gene_alt, nx.shortest_path_length(G_paths, gene_alt, gene))\n )\n except:\n print('{} - {} no path'.format(gene, alt))\n \n elif gene in G_b:\n for n in G_b.neighbors(gene):\n if n in G_paths:\n G_paths.add_edge(gene, n)\n try:\n sp = nx.shortest_path_length(G_paths, gene_alt, gene)\n alt_coding_shortest_paths.append(\n (gene, gene_alt, nx.shortest_path_length(G_paths, gene_alt, gene))\n )\n except:\n sp = '{} - {} no path'.format(gene, alt)\n print(gene, 'in BP2', sp)\n \n elif gene in BG:\n if sum(n in G_paths for n in BG.neighbors(gene)) == 0: continue# no BioGrid 2nd deg neighbors in G_o\n for n in BG.neighbors(gene):\n if n in G_paths:\n G_paths.add_edge(gene, n)\n\n try:\n sp = nx.shortest_path_length(G_paths, gene_alt, gene)\n alt_coding_shortest_paths.append(\n (gene, gene_alt, nx.shortest_path_length(G_paths, gene_alt, gene))\n )\n except:\n \n sp = '{} - {} no path'.format(gene, alt)\n print(gene, 'in BIOGRID', sp)\nprint(len(alt_coding_shortest_paths), alt_coding_shortest_paths[:5])", "SLC25A13 in BP2 6\nXCR1 in BIOGRID XCR1 - IP_2372737 no path\nNPAS1 in BP2 6\nCEPT1 in BP2 CEPT1 - IP_679545 no path\nLRRC4C in BP2 5\nNAPSA - IP_695602 no path\nPDSS1 in BP2 5\nC11orf65 in BP2 7\nCDK8 - IP_218971 no path\nRSPO3 in BP2 10\nECHDC1 in BP2 ECHDC1 - IP_145280 no path\nPTPN20 - IP_2320285 no path\nPIGP in BP2 PIGP - IP_661114 no path\nFAM91A1 in BP2 6\nRAB3C in BIOGRID 7\nRYR2 in BIOGRID RYR2 - IP_079402 no path\nRUSC1 in BIOGRID 4\nCOL7A1 in BIOGRID 8\nCD200 in BIOGRID 7\nNCOA4 - IP_182923 no path\nSULT4A1 - IP_295454 no path\nUBE3D in BIOGRID 7\nKCNC4 in BP2 3\nC2orf71 in BIOGRID 4\nFUS in BP2 FUS - IP_243680 no path\nGIMAP1 in BP2 7\nFUS - IP_3408961 no path\nSNCAIP in BP2 7\nPTPRQ in BIOGRID 5\nLMCD1 in BIOGRID 6\nFMO5 in BP2 6\nRASAL2 - IP_074307 no path\nKRT13 in BIOGRID KRT13 - IP_255333 no path\nBEND4 in BIOGRID 5\nNBPF3 in BP2 NBPF3 - IP_060186 no path\nRETREG1 - IP_2360322 no path\nITGB8 in BP2 7\nNR3C2 in BP2 NR3C2 - IP_122416 no path\nAP4S1 in BP2 AP4S1 - IP_224381 no path\nHMBOX1 in BP2 6\nCASR in BIOGRID 5\nARF3 in BIOGRID ARF3 - IP_209309 no path\nCRLF1 in BP2 CRLF1 - IP_272387 no path\nPSD3 in BIOGRID 8\nZNF84 in BP2 ZNF84 - IP_767719 no path\nRPL14 - IP_630937 no path\nRNF215 in BP2 6\nCOL4A5 in BP2 COL4A5 - IP_302474 no path\nSVOP in BIOGRID 7\nPOM121 - IP_153108 no path\nSMPX in BP2 5\n75 [('KLHDC2', 'KLHDC2|IP_751763', 4), ('SLC25A13', 'SLC25A13|IP_154569', 6), ('PRRC2A', 'PRRC2A|IP_138993', 5), ('NPAS1', 'NPAS1|IP_276857', 6), ('CBR1', 'CBR1|IP_289338', 1)]\n" ], [ "ev1 = pickle.load(open('ev1.pkl', 'rb'))", "_____no_output_____" ], [ "coding_types = dict()\nfor trxp in ev1:\n gene = trxp['gene']\n if gene in coding_types:\n coding_types[gene].append(trxp['multi-coding type'])\n else:\n coding_types[gene] = [trxp['multi-coding type']]\n\nmulti_codeing_types = dict()\nfor gene, types in coding_types.items():\n majority_type = sorted(Counter(types).items(), key=lambda x: -x[1])[0][0]\n multi_codeing_types[gene] = majority_type", "_____no_output_____" ], [ "sp, cnt = list(zip(*list(Counter([x[-1] for x in alt_coding_shortest_paths]).items())))\nplt.bar(sp, cnt, color='#8F2D56')\nplt.xticks(sp)\nplt.savefig('bioplex_figures/alt_coding_sp_bar.svg')\nplt.show()", "_____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" ] ]
ec4f6798123604b0f00819c4e3dfca8e0bd0162d
483,053
ipynb
Jupyter Notebook
Bag_of_words_on_raw_data.ipynb
reeha-parkar/natural-language-processing
2b0047fdbdc3445c40faedfa6ae9809a0a98b14d
[ "MIT" ]
null
null
null
Bag_of_words_on_raw_data.ipynb
reeha-parkar/natural-language-processing
2b0047fdbdc3445c40faedfa6ae9809a0a98b14d
[ "MIT" ]
null
null
null
Bag_of_words_on_raw_data.ipynb
reeha-parkar/natural-language-processing
2b0047fdbdc3445c40faedfa6ae9809a0a98b14d
[ "MIT" ]
null
null
null
438.740236
202,014
0.688332
[ [ [ "### Practical 2\n\n### Creating a bag of words model by processing raw wikipedia text", "_____no_output_____" ] ], [ [ "# Implementing bag of words model\nimport nltk\nimport numpy as np # matrix is required to vectorize the words\nimport bs4 as bs\nimport urllib.request\nimport re", "_____no_output_____" ], [ "# Scrape the web data\nraw_html = urllib.request.urlopen('https://en.wikipedia.org/wiki/Natural_language_processing')\nraw_html = raw_html.read()\nprint(raw_html)", "b'<!DOCTYPE html>\\n<html class=\"client-nojs\" lang=\"en\" dir=\"ltr\">\\n<head>\\n<meta charset=\"UTF-8\"/>\\n<title>Natural language processing - Wikipedia</title>\\n<script>document.documentElement.className=\"client-js\";RLCONF={\"wgBreakFrames\":!1,\"wgSeparatorTransformTable\":[\"\",\"\"],\"wgDigitTransformTable\":[\"\",\"\"],\"wgDefaultDateFormat\":\"dmy\",\"wgMonthNames\":[\"\",\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"],\"wgRequestId\":\"1d520229-7b57-47f3-9817-5e3f5cb41783\",\"wgCSPNonce\":!1,\"wgCanonicalNamespace\":\"\",\"wgCanonicalSpecialPageName\":!1,\"wgNamespaceNumber\":0,\"wgPageName\":\"Natural_language_processing\",\"wgTitle\":\"Natural language processing\",\"wgCurRevisionId\":1016426461,\"wgRevisionId\":1016426461,\"wgArticleId\":21652,\"wgIsArticle\":!0,\"wgIsRedirect\":!1,\"wgAction\":\"view\",\"wgUserName\":null,\"wgUserGroups\":[\"*\"],\"wgCategories\":[\"CS1 maint: location\",\"Articles with short description\",\"Short description matches Wikidata\",\"Commons link from Wikidata\",\"Wikipedia articles with LCCN identifiers\",\"Wikipedia articles with NDL identifiers\",\"Natural language processing\",\"Computational linguistics\",\\n\"Speech recognition\",\"Computational fields of study\",\"Artificial intelligence\"],\"wgPageContentLanguage\":\"en\",\"wgPageContentModel\":\"wikitext\",\"wgRelevantPageName\":\"Natural_language_processing\",\"wgRelevantArticleId\":21652,\"wgIsProbablyEditable\":!0,\"wgRelevantPageIsProbablyEditable\":!0,\"wgRestrictionEdit\":[],\"wgRestrictionMove\":[],\"wgMediaViewerOnClick\":!0,\"wgMediaViewerEnabledByDefault\":!0,\"wgPopupsFlags\":10,\"wgVisualEditor\":{\"pageLanguageCode\":\"en\",\"pageLanguageDir\":\"ltr\",\"pageVariantFallbacks\":\"en\"},\"wgMFDisplayWikibaseDescriptions\":{\"search\":!0,\"nearby\":!0,\"watchlist\":!0,\"tagline\":!1},\"wgWMESchemaEditAttemptStepOversample\":!1,\"wgULSCurrentAutonym\":\"English\",\"wgNoticeProject\":\"wikipedia\",\"wgCentralAuthMobileDomain\":!1,\"wgEditSubmitButtonLabelPublish\":!0,\"wgULSPosition\":\"interlanguage\",\"wgWikibaseItemId\":\"Q30642\"};RLSTATE={\"ext.globalCssJs.user.styles\":\"ready\",\"site.styles\":\"ready\",\"noscript\":\"ready\",\"user.styles\":\"ready\",\"ext.globalCssJs.user\":\"ready\",\"user\":\\n\"ready\",\"user.options\":\"loading\",\"ext.cite.styles\":\"ready\",\"ext.math.styles\":\"ready\",\"skins.vector.styles.legacy\":\"ready\",\"jquery.makeCollapsible.styles\":\"ready\",\"ext.visualEditor.desktopArticleTarget.noscript\":\"ready\",\"ext.uls.interlanguage\":\"ready\",\"ext.wikimediaBadges\":\"ready\",\"wikibase.client.init\":\"ready\"};RLPAGEMODULES=[\"ext.cite.ux-enhancements\",\"ext.math.scripts\",\"site\",\"mediawiki.page.ready\",\"jquery.makeCollapsible\",\"mediawiki.toc\",\"skins.vector.legacy.js\",\"ext.gadget.ReferenceTooltips\",\"ext.gadget.charinsert\",\"ext.gadget.extra-toolbar-buttons\",\"ext.gadget.refToolbar\",\"ext.gadget.switcher\",\"ext.centralauth.centralautologin\",\"mmv.head\",\"mmv.bootstrap.autostart\",\"ext.popups\",\"ext.visualEditor.desktopArticleTarget.init\",\"ext.visualEditor.targetLoader\",\"ext.eventLogging\",\"ext.wikimediaEvents\",\"ext.navigationTiming\",\"ext.uls.compactlinks\",\"ext.uls.interface\",\"ext.cx.eventlogging.campaigns\",\"ext.centralNotice.geoIP\",\"ext.centralNotice.startUp\"];</script>\\n<script>(RLQ=window.RLQ||[]).push(function(){mw.loader.implement(\"user.options@1hzgi\",function($,jQuery,require,module){/*@nomin*/mw.user.tokens.set({\"patrolToken\":\"+\\\\\\\\\",\"watchToken\":\"+\\\\\\\\\",\"csrfToken\":\"+\\\\\\\\\"});\\n});});</script>\\n<link rel=\"stylesheet\" href=\"/w/load.php?lang=en&amp;modules=ext.cite.styles%7Cext.math.styles%7Cext.uls.interlanguage%7Cext.visualEditor.desktopArticleTarget.noscript%7Cext.wikimediaBadges%7Cjquery.makeCollapsible.styles%7Cskins.vector.styles.legacy%7Cwikibase.client.init&amp;only=styles&amp;skin=vector\"/>\\n<script async=\"\" src=\"/w/load.php?lang=en&amp;modules=startup&amp;only=scripts&amp;raw=1&amp;skin=vector\"></script>\\n<meta name=\"ResourceLoaderDynamicStyles\" content=\"\"/>\\n<link rel=\"stylesheet\" href=\"/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=vector\"/>\\n<meta name=\"generator\" content=\"MediaWiki 1.36.0-wmf.38\"/>\\n<meta name=\"referrer\" content=\"origin\"/>\\n<meta name=\"referrer\" content=\"origin-when-crossorigin\"/>\\n<meta name=\"referrer\" content=\"origin-when-cross-origin\"/>\\n<meta property=\"og:image\" content=\"https://upload.wikimedia.org/wikipedia/commons/8/8b/Automated_online_assistant.png\"/>\\n<meta property=\"og:title\" content=\"Natural language processing - Wikipedia\"/>\\n<meta property=\"og:type\" content=\"website\"/>\\n<link rel=\"preconnect\" href=\"//upload.wikimedia.org\"/>\\n<link rel=\"alternate\" media=\"only screen and (max-width: 720px)\" href=\"//en.m.wikipedia.org/wiki/Natural_language_processing\"/>\\n<link rel=\"alternate\" type=\"application/x-wiki\" title=\"Edit this page\" href=\"/w/index.php?title=Natural_language_processing&amp;action=edit\"/>\\n<link rel=\"edit\" title=\"Edit this page\" href=\"/w/index.php?title=Natural_language_processing&amp;action=edit\"/>\\n<link rel=\"apple-touch-icon\" href=\"/static/apple-touch/wikipedia.png\"/>\\n<link rel=\"shortcut icon\" href=\"/static/favicon/wikipedia.ico\"/>\\n<link rel=\"search\" type=\"application/opensearchdescription+xml\" href=\"/w/opensearch_desc.php\" title=\"Wikipedia (en)\"/>\\n<link rel=\"EditURI\" type=\"application/rsd+xml\" href=\"//en.wikipedia.org/w/api.php?action=rsd\"/>\\n<link rel=\"license\" href=\"//creativecommons.org/licenses/by-sa/3.0/\"/>\\n<link rel=\"canonical\" href=\"https://en.wikipedia.org/wiki/Natural_language_processing\"/>\\n<link rel=\"dns-prefetch\" href=\"//login.wikimedia.org\"/>\\n<link rel=\"dns-prefetch\" href=\"//meta.wikimedia.org\" />\\n</head>\\n<body class=\"mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject mw-editable page-Natural_language_processing rootpage-Natural_language_processing skin-vector action-view skin-vector-legacy\"><div id=\"mw-page-base\" class=\"noprint\"></div>\\n<div id=\"mw-head-base\" class=\"noprint\"></div>\\n<div id=\"content\" class=\"mw-body\" role=\"main\">\\n\\t<a id=\"top\"></a>\\n\\t<div id=\"siteNotice\" class=\"mw-body-content\"><!-- CentralNotice --></div>\\n\\t<div class=\"mw-indicators mw-body-content\">\\n\\t</div>\\n\\t<h1 id=\"firstHeading\" class=\"firstHeading\" >Natural language processing</h1>\\n\\t<div id=\"bodyContent\" class=\"mw-body-content\">\\n\\t\\t<div id=\"siteSub\" class=\"noprint\">From Wikipedia, the free encyclopedia</div>\\n\\t\\t<div id=\"contentSub\"></div>\\n\\t\\t<div id=\"contentSub2\"></div>\\n\\t\\t\\n\\t\\t<div id=\"jump-to-nav\"></div>\\n\\t\\t<a class=\"mw-jump-link\" href=\"#mw-head\">Jump to navigation</a>\\n\\t\\t<a class=\"mw-jump-link\" href=\"#searchInput\">Jump to search</a>\\n\\t\\t<div id=\"mw-content-text\" lang=\"en\" dir=\"ltr\" class=\"mw-content-ltr\"><div class=\"mw-parser-output\"><div class=\"shortdescription nomobile noexcerpt noprint searchaux\" style=\"display:none\">Field of computer science and linguistics</div>\\n<div class=\"thumb tright\"><div class=\"thumbinner\" style=\"width:202px;\"><a href=\"/wiki/File:Automated_online_assistant.png\" class=\"image\"><img alt=\"\" src=\"//upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Automated_online_assistant.png/200px-Automated_online_assistant.png\" decoding=\"async\" width=\"200\" height=\"251\" class=\"thumbimage\" srcset=\"//upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Automated_online_assistant.png/300px-Automated_online_assistant.png 1.5x, //upload.wikimedia.org/wikipedia/commons/8/8b/Automated_online_assistant.png 2x\" data-file-width=\"400\" data-file-height=\"501\" /></a> <div class=\"thumbcaption\"><div class=\"magnify\"><a href=\"/wiki/File:Automated_online_assistant.png\" class=\"internal\" title=\"Enlarge\"></a></div>An <a href=\"/wiki/Automated_online_assistant\" class=\"mw-redirect\" title=\"Automated online assistant\">automated online assistant</a> providing <a href=\"/wiki/Customer_service\" title=\"Customer service\">customer service</a> on a web page, an example of an application where natural language processing is a major component.<sup id=\"cite_ref-Kongthon_1-0\" class=\"reference\"><a href=\"#cite_note-Kongthon-1\">&#91;1&#93;</a></sup></div></div></div>\\n<p><b>Natural language processing</b> (<b>NLP</b>) is a subfield of <a href=\"/wiki/Linguistics\" title=\"Linguistics\">linguistics</a>, <a href=\"/wiki/Computer_science\" title=\"Computer science\">computer science</a>, and <a href=\"/wiki/Artificial_intelligence\" title=\"Artificial intelligence\">artificial intelligence</a> concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of <a href=\"/wiki/Natural_language\" title=\"Natural language\">natural language</a> data. The result is a computer capable of \"understanding\" the contents of documents, including the contextual nuances of the language within them. The technology can then accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves. \\n</p><p>Challenges in natural language processing frequently involve <a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">speech recognition</a>, <a href=\"/wiki/Natural_language_understanding\" class=\"mw-redirect\" title=\"Natural language understanding\">natural language understanding</a>, and <a href=\"/wiki/Natural-language_generation\" title=\"Natural-language generation\">natural-language generation</a>.\\n</p>\\n<div id=\"toc\" class=\"toc\" role=\"navigation\" aria-labelledby=\"mw-toc-heading\"><input type=\"checkbox\" role=\"button\" id=\"toctogglecheckbox\" class=\"toctogglecheckbox\" style=\"display:none\" /><div class=\"toctitle\" lang=\"en\" dir=\"ltr\"><h2 id=\"mw-toc-heading\">Contents</h2><span class=\"toctogglespan\"><label class=\"toctogglelabel\" for=\"toctogglecheckbox\"></label></span></div>\\n<ul>\\n<li class=\"toclevel-1 tocsection-1\"><a href=\"#History\"><span class=\"tocnumber\">1</span> <span class=\"toctext\">History</span></a>\\n<ul>\\n<li class=\"toclevel-2 tocsection-2\"><a href=\"#Symbolic_NLP_(1950s_-_early_1990s)\"><span class=\"tocnumber\">1.1</span> <span class=\"toctext\">Symbolic NLP (1950s - early 1990s)</span></a></li>\\n<li class=\"toclevel-2 tocsection-3\"><a href=\"#Statistical_NLP_(1990s_-_2010s)\"><span class=\"tocnumber\">1.2</span> <span class=\"toctext\">Statistical NLP (1990s - 2010s)</span></a></li>\\n<li class=\"toclevel-2 tocsection-4\"><a href=\"#Neural_NLP_(present)\"><span class=\"tocnumber\">1.3</span> <span class=\"toctext\">Neural NLP (present)</span></a></li>\\n</ul>\\n</li>\\n<li class=\"toclevel-1 tocsection-5\"><a href=\"#Methods:_Rules,_statistics,_neural_networks\"><span class=\"tocnumber\">2</span> <span class=\"toctext\">Methods: Rules, statistics, neural networks</span></a>\\n<ul>\\n<li class=\"toclevel-2 tocsection-6\"><a href=\"#Statistical_methods\"><span class=\"tocnumber\">2.1</span> <span class=\"toctext\">Statistical methods</span></a></li>\\n<li class=\"toclevel-2 tocsection-7\"><a href=\"#Neural_networks\"><span class=\"tocnumber\">2.2</span> <span class=\"toctext\">Neural networks</span></a></li>\\n</ul>\\n</li>\\n<li class=\"toclevel-1 tocsection-8\"><a href=\"#Common_NLP_tasks\"><span class=\"tocnumber\">3</span> <span class=\"toctext\">Common NLP tasks</span></a>\\n<ul>\\n<li class=\"toclevel-2 tocsection-9\"><a href=\"#Text_and_speech_processing\"><span class=\"tocnumber\">3.1</span> <span class=\"toctext\">Text and speech processing</span></a></li>\\n<li class=\"toclevel-2 tocsection-10\"><a href=\"#Morphological_analysis\"><span class=\"tocnumber\">3.2</span> <span class=\"toctext\">Morphological analysis</span></a></li>\\n<li class=\"toclevel-2 tocsection-11\"><a href=\"#Syntactic_analysis\"><span class=\"tocnumber\">3.3</span> <span class=\"toctext\">Syntactic analysis</span></a></li>\\n<li class=\"toclevel-2 tocsection-12\"><a href=\"#Lexical_semantics_(of_individual_words_in_context)\"><span class=\"tocnumber\">3.4</span> <span class=\"toctext\">Lexical semantics (of individual words in context)</span></a></li>\\n<li class=\"toclevel-2 tocsection-13\"><a href=\"#Relational_semantics_(semantics_of_individual_sentences)\"><span class=\"tocnumber\">3.5</span> <span class=\"toctext\">Relational semantics (semantics of individual sentences)</span></a></li>\\n<li class=\"toclevel-2 tocsection-14\"><a href=\"#Discourse_(semantics_beyond_individual_sentences)\"><span class=\"tocnumber\">3.6</span> <span class=\"toctext\">Discourse (semantics beyond individual sentences)</span></a></li>\\n<li class=\"toclevel-2 tocsection-15\"><a href=\"#Higher-level_NLP_applications\"><span class=\"tocnumber\">3.7</span> <span class=\"toctext\">Higher-level NLP applications</span></a></li>\\n</ul>\\n</li>\\n<li class=\"toclevel-1 tocsection-16\"><a href=\"#General_tendencies_and_(possible)_future_directions\"><span class=\"tocnumber\">4</span> <span class=\"toctext\">General tendencies and (possible) future directions</span></a>\\n<ul>\\n<li class=\"toclevel-2 tocsection-17\"><a href=\"#Cognition_and_NLP\"><span class=\"tocnumber\">4.1</span> <span class=\"toctext\">Cognition and NLP</span></a></li>\\n</ul>\\n</li>\\n<li class=\"toclevel-1 tocsection-18\"><a href=\"#See_also\"><span class=\"tocnumber\">5</span> <span class=\"toctext\">See also</span></a></li>\\n<li class=\"toclevel-1 tocsection-19\"><a href=\"#References\"><span class=\"tocnumber\">6</span> <span class=\"toctext\">References</span></a></li>\\n<li class=\"toclevel-1 tocsection-20\"><a href=\"#Further_reading\"><span class=\"tocnumber\">7</span> <span class=\"toctext\">Further reading</span></a></li>\\n</ul>\\n</div>\\n\\n<h2><span class=\"mw-headline\" id=\"History\">History</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=1\" title=\"Edit section: History\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\\n<div role=\"note\" class=\"hatnote navigation-not-searchable\">Further information: <a href=\"/wiki/History_of_natural_language_processing\" title=\"History of natural language processing\">History of natural language processing</a></div>\\n<p>Natural language processing has its roots in the 1950s. Already in 1950, <a href=\"/wiki/Alan_Turing\" title=\"Alan Turing\">Alan Turing</a> published an article titled \"<a href=\"/wiki/Computing_Machinery_and_Intelligence\" title=\"Computing Machinery and Intelligence\">Computing Machinery and Intelligence</a>\" which proposed what is now called the <a href=\"/wiki/Turing_test\" title=\"Turing test\">Turing test</a> as a criterion of intelligence, a task that involves the automated interpretation and generation of natural language, but at the time not articulated as a problem separate from artificial intelligence.\\n</p>\\n<h3><span id=\"Symbolic_NLP_.281950s_-_early_1990s.29\"></span><span class=\"mw-headline\" id=\"Symbolic_NLP_(1950s_-_early_1990s)\">Symbolic NLP (1950s - early 1990s)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=2\" title=\"Edit section: Symbolic NLP (1950s - early 1990s)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<p>The premise of symbolic NLP is well-summarized by <a href=\"/wiki/John_Searle\" title=\"John Searle\">John Searle</a>\\'s <a href=\"/wiki/Chinese_room\" title=\"Chinese room\">Chinese room</a> experiment: Given a collection of rules (e.g., a Chinese phrasebook, with questions and matching answers), the computer emulates natural language understanding (or other NLP tasks) by applying those rules to the data it is confronted with.\\n</p>\\n<ul><li><b>1950s</b>: The <a href=\"/wiki/Georgetown-IBM_experiment\" class=\"mw-redirect\" title=\"Georgetown-IBM experiment\">Georgetown experiment</a> in 1954 involved fully <a href=\"/wiki/Automatic_translation\" class=\"mw-redirect\" title=\"Automatic translation\">automatic translation</a> of more than sixty Russian sentences into English. The authors claimed that within three or five years, machine translation would be a solved problem.<sup id=\"cite_ref-2\" class=\"reference\"><a href=\"#cite_note-2\">&#91;2&#93;</a></sup> However, real progress was much slower, and after the <a href=\"/wiki/ALPAC\" title=\"ALPAC\">ALPAC report</a> in 1966, which found that ten-year-long research had failed to fulfill the expectations, funding for machine translation was dramatically reduced. Little further research in machine translation was conducted until the late 1980s when the first <a href=\"/wiki/Statistical_machine_translation\" title=\"Statistical machine translation\">statistical machine translation</a> systems were developed.</li>\\n<li><b>1960s</b>: Some notably successful natural language processing systems developed in the 1960s were <a href=\"/wiki/SHRDLU\" title=\"SHRDLU\">SHRDLU</a>, a natural language system working in restricted \"<a href=\"/wiki/Blocks_world\" title=\"Blocks world\">blocks worlds</a>\" with restricted vocabularies, and <a href=\"/wiki/ELIZA\" title=\"ELIZA\">ELIZA</a>, a simulation of a <a href=\"/wiki/Rogerian_psychotherapy\" class=\"mw-redirect\" title=\"Rogerian psychotherapy\">Rogerian psychotherapist</a>, written by <a href=\"/wiki/Joseph_Weizenbaum\" title=\"Joseph Weizenbaum\">Joseph Weizenbaum</a> between 1964 and 1966. Using almost no information about human thought or emotion, ELIZA sometimes provided a startlingly human-like interaction. When the \"patient\" exceeded the very small knowledge base, ELIZA might provide a generic response, for example, responding to \"My head hurts\" with \"Why do you say your head hurts?\".</li>\\n<li><b>1970s</b>: During the 1970s, many programmers began to write \"conceptual <a href=\"/wiki/Ontology_(information_science)\" title=\"Ontology (information science)\">ontologies</a>\", which structured real-world information into computer-understandable data. Examples are MARGIE (Schank, 1975), SAM (Cullingford, 1978), PAM (Wilensky, 1978), TaleSpin (Meehan, 1976), QUALM (Lehnert, 1977), Politics (Carbonell, 1979), and Plot Units (Lehnert 1981). During this time, the first many <a href=\"/wiki/Chatterbots\" class=\"mw-redirect\" title=\"Chatterbots\">chatterbots</a> were written (e.g., <a href=\"/wiki/PARRY\" title=\"PARRY\">PARRY</a>).</li>\\n<li><b>1980s</b>: The 1980s and early 1990s mark the hey-day of symbolic methods in NLP. Focus areas of the time included research on rule-based parsing (e.g., the development of <a href=\"/wiki/Head-driven_phrase_structure_grammar\" title=\"Head-driven phrase structure grammar\">HPSG</a> as a computational operationalization of <a href=\"/wiki/Generative_grammar\" title=\"Generative grammar\">generative grammar</a>), morphology (e.g., two-level morphology<sup id=\"cite_ref-3\" class=\"reference\"><a href=\"#cite_note-3\">&#91;3&#93;</a></sup>), semantics (e.g., <a href=\"/wiki/Lesk_algorithm\" title=\"Lesk algorithm\">Lesk algorithm</a>), reference (e.g., within Centering Theory<sup id=\"cite_ref-4\" class=\"reference\"><a href=\"#cite_note-4\">&#91;4&#93;</a></sup>) and other areas of natural language understanding (e.g., in the <a href=\"/wiki/Rhetorical_structure_theory\" title=\"Rhetorical structure theory\">Rhetorical Structure Theory</a>). Other lines of research were continued, e.g., the development of chatterbots with <a href=\"/wiki/Racter\" title=\"Racter\">Racter</a> and <a href=\"/wiki/Jabberwacky\" title=\"Jabberwacky\">Jabberwacky</a>. An important development (that eventually led to the statistical turn in the 1990s) was the rising importance of quantitative evaluation in this period.<sup id=\"cite_ref-5\" class=\"reference\"><a href=\"#cite_note-5\">&#91;5&#93;</a></sup></li></ul>\\n<h3><span id=\"Statistical_NLP_.281990s_-_2010s.29\"></span><span class=\"mw-headline\" id=\"Statistical_NLP_(1990s_-_2010s)\">Statistical NLP (1990s - 2010s)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=3\" title=\"Edit section: Statistical NLP (1990s - 2010s)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<p>Up to the 1980s, most natural language processing systems were based on complex sets of hand-written rules. Starting in the late 1980s, however, there was a revolution in natural language processing with the introduction of <a href=\"/wiki/Machine_learning\" title=\"Machine learning\">machine learning</a> algorithms for language processing. This was due to both the steady increase in computational power (see <a href=\"/wiki/Moore%27s_law\" title=\"Moore&#39;s law\">Moore\\'s law</a>) and the gradual lessening of the dominance of <a href=\"/wiki/Noam_Chomsky\" title=\"Noam Chomsky\">Chomskyan</a> theories of linguistics (e.g. <a href=\"/wiki/Transformational_grammar\" title=\"Transformational grammar\">transformational grammar</a>), whose theoretical underpinnings discouraged the sort of <a href=\"/wiki/Corpus_linguistics\" title=\"Corpus linguistics\">corpus linguistics</a> that underlies the machine-learning approach to language processing.<sup id=\"cite_ref-6\" class=\"reference\"><a href=\"#cite_note-6\">&#91;6&#93;</a></sup> \\n</p>\\n<ul><li><b>1990s</b>: Many of the notable early successes on statistical methods in NLP occurred in the field of <a href=\"/wiki/Machine_translation\" title=\"Machine translation\">machine translation</a>, due especially to work at IBM Research. These systems were able to take advantage of existing multilingual <a href=\"/wiki/Text_corpus\" title=\"Text corpus\">textual corpora</a> that had been produced by the <a href=\"/wiki/Parliament_of_Canada\" title=\"Parliament of Canada\">Parliament of Canada</a> and the <a href=\"/wiki/European_Union\" title=\"European Union\">European Union</a> as a result of laws calling for the translation of all governmental proceedings into all official languages of the corresponding systems of government. However, most other systems depended on corpora specifically developed for the tasks implemented by these systems, which was (and often continues to be) a major limitation in the success of these systems. As a result, a great deal of research has gone into methods of more effectively learning from limited amounts of data.</li>\\n<li><b>2000s</b>: With the growth of the web, increasing amounts of raw (unannotated) language data has become available since the mid-1990s. Research has thus increasingly focused on <a href=\"/wiki/Unsupervised_learning\" title=\"Unsupervised learning\">unsupervised</a> and <a href=\"/wiki/Semi-supervised_learning\" title=\"Semi-supervised learning\">semi-supervised learning</a> algorithms. Such algorithms can learn from data that has not been hand-annotated with the desired answers or using a combination of annotated and non-annotated data. Generally, this task is much more difficult than <a href=\"/wiki/Supervised_learning\" title=\"Supervised learning\">supervised learning</a>, and typically produces less accurate results for a given amount of input data. However, there is an enormous amount of non-annotated data available (including, among other things, the entire content of the <a href=\"/wiki/World_Wide_Web\" title=\"World Wide Web\">World Wide Web</a>), which can often make up for the inferior results if the algorithm used has a low enough <a href=\"/wiki/Time_complexity\" title=\"Time complexity\">time complexity</a> to be practical.</li></ul>\\n<h3><span id=\"Neural_NLP_.28present.29\"></span><span class=\"mw-headline\" id=\"Neural_NLP_(present)\">Neural NLP (present)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=4\" title=\"Edit section: Neural NLP (present)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<p>In the 2010s, <a href=\"/wiki/Representation_learning\" class=\"mw-redirect\" title=\"Representation learning\">representation learning</a> and <a href=\"/wiki/Deep_learning\" title=\"Deep learning\">deep neural network</a>-style machine learning methods became widespread in natural language processing, due in part to a flurry of results showing that such techniques<sup id=\"cite_ref-goldberg:nnlp17_7-0\" class=\"reference\"><a href=\"#cite_note-goldberg:nnlp17-7\">&#91;7&#93;</a></sup><sup id=\"cite_ref-goodfellow:book16_8-0\" class=\"reference\"><a href=\"#cite_note-goodfellow:book16-8\">&#91;8&#93;</a></sup> can achieve state-of-the-art results in many natural language tasks, for example in language modeling,<sup id=\"cite_ref-jozefowicz:lm16_9-0\" class=\"reference\"><a href=\"#cite_note-jozefowicz:lm16-9\">&#91;9&#93;</a></sup> parsing,<sup id=\"cite_ref-choe:emnlp16_10-0\" class=\"reference\"><a href=\"#cite_note-choe:emnlp16-10\">&#91;10&#93;</a></sup><sup id=\"cite_ref-vinyals:nips15_11-0\" class=\"reference\"><a href=\"#cite_note-vinyals:nips15-11\">&#91;11&#93;</a></sup> and many others.\\n</p>\\n<h2><span id=\"Methods:_Rules.2C_statistics.2C_neural_networks\"></span><span class=\"mw-headline\" id=\"Methods:_Rules,_statistics,_neural_networks\">Methods: Rules, statistics, neural networks<span class=\"anchor\" id=\"Statistical_natural_language_processing_(SNLP)\"></span></span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=5\" title=\"Edit section: Methods: Rules, statistics, neural networks\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\\n<p>In the early days, many language-processing systems were designed by symbolic methods, i.e., the hand-coding of a set of rules, coupled with a dictionary lookup:<sup id=\"cite_ref-winograd:shrdlu71_12-0\" class=\"reference\"><a href=\"#cite_note-winograd:shrdlu71-12\">&#91;12&#93;</a></sup><sup id=\"cite_ref-schank77_13-0\" class=\"reference\"><a href=\"#cite_note-schank77-13\">&#91;13&#93;</a></sup> such as by writing grammars or devising heuristic rules for <a href=\"/wiki/Stemming\" title=\"Stemming\">stemming</a>.\\n</p><p>More recent systems based on <a href=\"/wiki/Machine_learning\" title=\"Machine learning\">machine-learning</a> algorithms have many advantages over hand-produced rules: \\n</p>\\n<ul><li>The learning procedures used during machine learning automatically focus on the most common cases, whereas when writing rules by hand it is often not at all obvious where the effort should be directed.</li>\\n<li>Automatic learning procedures can make use of statistical inference algorithms to produce models that are robust to unfamiliar input (e.g. containing words or structures that have not been seen before) and to erroneous input (e.g. with misspelled words or words accidentally omitted). Generally, handling such input gracefully with handwritten rules, or, more generally, creating systems of handwritten rules that make soft decisions, is extremely difficult, error-prone and time-consuming.</li>\\n<li>Systems based on automatically learning the rules can be made more accurate simply by supplying more input data. However, systems based on handwritten rules can only be made more accurate by increasing the complexity of the rules, which is a much more difficult task. In particular, there is a limit to the complexity of systems based on handwritten rules, beyond which the systems become more and more unmanageable. However, creating more data to input to machine-learning systems simply requires a corresponding increase in the number of man-hours worked, generally without significant increases in the complexity of the annotation process.</li></ul>\\n<p>Despite the popularity of machine learning in NLP research, symbolic methods are still (2020) commonly used\\n</p>\\n<ul><li>when the amount of training data is insufficient to successfully apply machine learning methods, e.g., for the machine translation of low-resource languages such as provided by the <a href=\"/wiki/Apertium\" title=\"Apertium\">Apertium</a> system,</li>\\n<li>for preprocessing in NLP pipelines, e.g., <a href=\"/wiki/Tokenization_(lexical_analysis)\" class=\"mw-redirect\" title=\"Tokenization (lexical analysis)\">tokenization</a>, or</li>\\n<li>for postprocessing and transforming the output of NLP pipelines, e.g., for <a href=\"/wiki/Knowledge_extraction\" title=\"Knowledge extraction\">knowledge extraction</a> from syntactic parses.</li></ul>\\n<h3><span class=\"mw-headline\" id=\"Statistical_methods\">Statistical methods</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=6\" title=\"Edit section: Statistical methods\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<p>Since the so-called \"statistical revolution\"<sup id=\"cite_ref-johnson:eacl:ilcl09_14-0\" class=\"reference\"><a href=\"#cite_note-johnson:eacl:ilcl09-14\">&#91;14&#93;</a></sup><sup id=\"cite_ref-resnik:langlog11_15-0\" class=\"reference\"><a href=\"#cite_note-resnik:langlog11-15\">&#91;15&#93;</a></sup> in the late 1980s and mid-1990s, much natural language processing research has relied heavily on machine learning. The machine-learning paradigm calls instead for using <a href=\"/wiki/Statistical_inference\" title=\"Statistical inference\">statistical inference</a> to automatically learn such rules through the analysis of large <i><a href=\"/wiki/Text_corpus\" title=\"Text corpus\">corpora</a></i> (the plural form of <i>corpus</i>, is a set of documents, possibly with human or computer annotations) of typical real-world examples.\\n</p><p>Many different classes of machine-learning algorithms have been applied to natural-language-processing tasks. These algorithms take as input a large set of \"features\" that are generated from the input data. Increasingly, however, research has focused on <a href=\"/wiki/Statistical_models\" class=\"mw-redirect\" title=\"Statistical models\">statistical models</a>, which make soft, <a href=\"/wiki/Probabilistic\" class=\"mw-redirect\" title=\"Probabilistic\">probabilistic</a> decisions based on attaching <a href=\"/wiki/Real-valued\" class=\"mw-redirect\" title=\"Real-valued\">real-valued</a> weights to each input feature. Such models have the advantage that they can express the relative certainty of many different possible answers rather than only one, producing more reliable results when such a model is included as a component of a larger system.\\n</p><p>Some of the earliest-used machine learning algorithms, such as <a href=\"/wiki/Decision_tree\" title=\"Decision tree\">decision trees</a>, produced systems of hard if-then rules similar to existing hand-written rules. However, <a href=\"/wiki/Part_of_speech_tagging\" class=\"mw-redirect\" title=\"Part of speech tagging\">part-of-speech tagging</a> introduced the use of <a href=\"/wiki/Hidden_Markov_models\" class=\"mw-redirect\" title=\"Hidden Markov models\">hidden Markov models</a> to natural language processing, and increasingly, research has focused on <a href=\"/wiki/Statistical_models\" class=\"mw-redirect\" title=\"Statistical models\">statistical models</a>, which make soft, <a href=\"/wiki/Probabilistic\" class=\"mw-redirect\" title=\"Probabilistic\">probabilistic</a> decisions based on attaching <a href=\"/wiki/Real-valued\" class=\"mw-redirect\" title=\"Real-valued\">real-valued</a> weights to the features making up the input data. The <a href=\"/wiki/Cache_language_model\" title=\"Cache language model\">cache language models</a> upon which many <a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">speech recognition</a> systems now rely are examples of such statistical models. Such models are generally more robust when given unfamiliar input, especially input that contains errors (as is very common for real-world data), and produce more reliable results when integrated into a larger system comprising multiple subtasks.\\n</p><p>Since the neural turn, statistical methods in NLP research have been largely replaced by neural networks. However, they continue to be relevant for contexts in which statistical interpretability and transparency is required.\\n</p>\\n<h3><span class=\"mw-headline\" id=\"Neural_networks\">Neural networks</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=7\" title=\"Edit section: Neural networks\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<div role=\"note\" class=\"hatnote navigation-not-searchable\">Further information: <a href=\"/wiki/Artificial_neural_network\" title=\"Artificial neural network\">Artificial neural network</a></div>\\n<p>A major drawback of statistical methods is that they require elaborate feature engineering. Since 2015,<sup id=\"cite_ref-16\" class=\"reference\"><a href=\"#cite_note-16\">&#91;16&#93;</a></sup> the field has thus largely abandoned statistical methods and shifted to <a href=\"/wiki/Neural_network\" title=\"Neural network\">neural networks</a> for machine learning. Popular techniques include the use of <a href=\"/wiki/Word_embedding\" title=\"Word embedding\">word embeddings</a> to capture semantic properties of words, and an increase in end-to-end learning of a higher-level task (e.g., question answering) instead of relying on a pipeline of separate intermediate tasks (e.g., part-of-speech tagging and dependency parsing). In some areas, this shift has entailed substantial changes in how NLP systems are designed, such that deep neural network-based approaches may be viewed as a new paradigm distinct from statistical natural language processing. For instance, the term <i><a href=\"/wiki/Neural_machine_translation\" title=\"Neural machine translation\">neural machine translation</a></i> (NMT) emphasizes the fact that deep learning-based approaches to machine translation directly learn <a href=\"/wiki/Seq2seq\" title=\"Seq2seq\">sequence-to-sequence</a> transformations, obviating the need for intermediate steps such as word alignment and language modeling that was used in <a href=\"/wiki/Statistical_machine_translation\" title=\"Statistical machine translation\">statistical machine translation</a> (SMT). Latest works tend to use non-technical structure of a given task to build proper neural network.<sup id=\"cite_ref-17\" class=\"reference\"><a href=\"#cite_note-17\">&#91;17&#93;</a></sup>\\n</p>\\n<h2><span class=\"mw-headline\" id=\"Common_NLP_tasks\">Common NLP tasks</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=8\" title=\"Edit section: Common NLP tasks\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\\n<p>The following is a list of some of the most commonly researched tasks in natural language processing. Some of these tasks have direct real-world applications, while others more commonly serve as subtasks that are used to aid in solving larger tasks.\\n</p><p>Though natural language processing tasks are closely intertwined, they can be subdivided into categories for convenience. A coarse division is given below.\\n</p>\\n<h3><span class=\"mw-headline\" id=\"Text_and_speech_processing\">Text and speech processing</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=9\" title=\"Edit section: Text and speech processing\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<dl><dt><a href=\"/wiki/Optical_character_recognition\" title=\"Optical character recognition\">Optical character recognition</a> (OCR)</dt>\\n<dd>Given an image representing printed text, determine the corresponding text.</dd></dl>\\n<dl><dt><a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">Speech recognition</a></dt>\\n<dd>Given a sound clip of a person or people speaking, determine the textual representation of the speech. This is the opposite of <a href=\"/wiki/Text_to_speech\" class=\"mw-redirect\" title=\"Text to speech\">text to speech</a> and is one of the extremely difficult problems colloquially termed \"<a href=\"/wiki/AI-complete\" title=\"AI-complete\">AI-complete</a>\" (see above). In <a href=\"/wiki/Natural_speech\" class=\"mw-redirect\" title=\"Natural speech\">natural speech</a> there are hardly any pauses between successive words, and thus <a href=\"/wiki/Speech_segmentation\" title=\"Speech segmentation\">speech segmentation</a> is a necessary subtask of speech recognition (see below). In most spoken languages, the sounds representing successive letters blend into each other in a process termed <a href=\"/wiki/Coarticulation\" title=\"Coarticulation\">coarticulation</a>, so the conversion of the <a href=\"/wiki/Analog_signal\" title=\"Analog signal\">analog signal</a> to discrete characters can be a very difficult process. Also, given that words in the same language are spoken by people with different accents, the speech recognition software must be able to recognize the wide variety of input as being identical to each other in terms of its textual equivalent.</dd>\\n<dt><a href=\"/wiki/Speech_segmentation\" title=\"Speech segmentation\">Speech segmentation</a></dt>\\n<dd>Given a sound clip of a person or people speaking, separate it into words. A subtask of <a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">speech recognition</a> and typically grouped with it.</dd></dl>\\n<dl><dt><a href=\"/wiki/Text-to-speech\" class=\"mw-redirect\" title=\"Text-to-speech\">Text-to-speech</a></dt>\\n<dd>Given a text, transform those units and produce a spoken representation. Text-to-speech can be used to aid the visually impaired.<sup id=\"cite_ref-18\" class=\"reference\"><a href=\"#cite_note-18\">&#91;18&#93;</a></sup></dd></dl>\\n<dl><dt><a href=\"/wiki/Word_segmentation\" class=\"mw-redirect\" title=\"Word segmentation\">Word segmentation</a> (<a href=\"/wiki/Tokenization_(lexical_analysis)\" class=\"mw-redirect\" title=\"Tokenization (lexical analysis)\">Tokenization</a>)</dt>\\n<dd>Separate a chunk of continuous text into separate words. For a language like <a href=\"/wiki/English_language\" title=\"English language\">English</a>, this is fairly trivial, since words are usually separated by spaces. However, some written languages like <a href=\"/wiki/Chinese_language\" title=\"Chinese language\">Chinese</a>, <a href=\"/wiki/Japanese_language\" title=\"Japanese language\">Japanese</a> and <a href=\"/wiki/Thai_language\" title=\"Thai language\">Thai</a> do not mark word boundaries in such a fashion, and in those languages text segmentation is a significant task requiring knowledge of the <a href=\"/wiki/Vocabulary\" title=\"Vocabulary\">vocabulary</a> and <a href=\"/wiki/Morphology_(linguistics)\" title=\"Morphology (linguistics)\">morphology</a> of words in the language. Sometimes this process is also used in cases like <a href=\"/wiki/Bag_of_words\" class=\"mw-redirect\" title=\"Bag of words\">bag of words</a> (BOW) creation in data mining.</dd></dl>\\n<h3><span class=\"mw-headline\" id=\"Morphological_analysis\">Morphological analysis</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=10\" title=\"Edit section: Morphological analysis\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<dl><dt><a href=\"/wiki/Lemmatisation\" title=\"Lemmatisation\">Lemmatization</a></dt>\\n<dd>The task of removing inflectional endings only and to return the base dictionary form of a word which is also known as a lemma. Lemmatization is another technique for reducing words to their normalized form. But in this case, the transformation actually uses a dictionary to map words to their actual form.<sup id=\"cite_ref-19\" class=\"reference\"><a href=\"#cite_note-19\">&#91;19&#93;</a></sup></dd>\\n<dt><a href=\"/wiki/Morphology_(linguistics)\" title=\"Morphology (linguistics)\">Morphological segmentation</a></dt>\\n<dd>Separate words into individual <a href=\"/wiki/Morpheme\" title=\"Morpheme\">morphemes</a> and identify the class of the morphemes. The difficulty of this task depends greatly on the complexity of the <a href=\"/wiki/Morphology_(linguistics)\" title=\"Morphology (linguistics)\">morphology</a> (<i>i.e.</i>, the structure of words) of the language being considered. <a href=\"/wiki/English_language\" title=\"English language\">English</a> has fairly simple morphology, especially <a href=\"/wiki/Inflectional_morphology\" class=\"mw-redirect\" title=\"Inflectional morphology\">inflectional morphology</a>, and thus it is often possible to ignore this task entirely and simply model all possible forms of a word (<i>e.g.</i>, \"open, opens, opened, opening\") as separate words. In languages such as <a href=\"/wiki/Turkish_language\" title=\"Turkish language\">Turkish</a> or <a href=\"/wiki/Meitei_language\" title=\"Meitei language\">Meitei</a>,<sup id=\"cite_ref-20\" class=\"reference\"><a href=\"#cite_note-20\">&#91;20&#93;</a></sup> a highly <a href=\"/wiki/Agglutination\" title=\"Agglutination\">agglutinated</a> Indian language, however, such an approach is not possible, as each dictionary entry has thousands of possible word forms.</dd>\\n<dt><a href=\"/wiki/Part-of-speech_tagging\" title=\"Part-of-speech tagging\">Part-of-speech tagging</a></dt>\\n<dd>Given a sentence, determine the <a href=\"/wiki/Part_of_speech\" title=\"Part of speech\">part of speech</a> (POS) for each word. Many words, especially common ones, can serve as multiple <a href=\"/wiki/Parts_of_speech\" class=\"mw-redirect\" title=\"Parts of speech\">parts of speech</a>. For example, \"book\" can be a <a href=\"/wiki/Noun\" title=\"Noun\">noun</a> (\"the book on the table\") or <a href=\"/wiki/Verb\" title=\"Verb\">verb</a> (\"to book a flight\"); \"set\" can be a <a href=\"/wiki/Noun\" title=\"Noun\">noun</a>, <a href=\"/wiki/Verb\" title=\"Verb\">verb</a> or <a href=\"/wiki/Adjective\" title=\"Adjective\">adjective</a>; and \"out\" can be any of at least five different parts of speech.</dd></dl>\\n<dl><dt><a href=\"/wiki/Stemming\" title=\"Stemming\">Stemming</a></dt>\\n<dd>The process of reducing inflected (or sometimes derived) words to a base form (<i>e.g.</i>, \"close\" will be the root for \"closed\", \"closing\", \"close\", \"closer\" etc.). Stemming yields similar results as lemmatization, but does so on grounds of rules, not a dictionary.</dd></dl>\\n<h3><span class=\"mw-headline\" id=\"Syntactic_analysis\">Syntactic analysis</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=11\" title=\"Edit section: Syntactic analysis\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<dl><dt><a href=\"/wiki/Grammar_induction\" title=\"Grammar induction\">Grammar induction</a><sup id=\"cite_ref-21\" class=\"reference\"><a href=\"#cite_note-21\">&#91;21&#93;</a></sup></dt>\\n<dd>Generate a <a href=\"/wiki/Formal_grammar\" title=\"Formal grammar\">formal grammar</a> that describes a language\\'s syntax.</dd>\\n<dt><a href=\"/wiki/Sentence_breaking\" class=\"mw-redirect\" title=\"Sentence breaking\">Sentence breaking</a> (also known as \"<a href=\"/wiki/Sentence_boundary_disambiguation\" title=\"Sentence boundary disambiguation\">sentence boundary disambiguation</a>\")</dt>\\n<dd>Given a chunk of text, find the sentence boundaries. Sentence boundaries are often marked by <a href=\"/wiki/Full_stop\" title=\"Full stop\">periods</a> or other <a href=\"/wiki/Punctuation_mark\" class=\"mw-redirect\" title=\"Punctuation mark\">punctuation marks</a>, but these same characters can serve other purposes (<i>e.g.</i>, marking <a href=\"/wiki/Abbreviation\" title=\"Abbreviation\">abbreviations</a>).</dd>\\n<dt><a href=\"/wiki/Parsing\" title=\"Parsing\">Parsing</a></dt>\\n<dd>Determine the <a href=\"/wiki/Parse_tree\" title=\"Parse tree\">parse tree</a> (grammatical analysis) of a given sentence. The <a href=\"/wiki/Grammar\" title=\"Grammar\">grammar</a> for <a href=\"/wiki/Natural_language\" title=\"Natural language\">natural languages</a> is <a href=\"/wiki/Ambiguous\" class=\"mw-redirect\" title=\"Ambiguous\">ambiguous</a> and typical sentences have multiple possible analyses: perhaps surprisingly, for a typical sentence there may be thousands of potential parses (most of which will seem completely nonsensical to a human). There are two primary types of parsing: <i>dependency parsing</i> and <i>constituency parsing</i>. Dependency parsing focuses on the relationships between words in a sentence (marking things like primary objects and predicates), whereas constituency parsing focuses on building out the parse tree using a <a href=\"/wiki/Probabilistic_context-free_grammar\" title=\"Probabilistic context-free grammar\">probabilistic context-free grammar</a> (PCFG) (see also <i><a href=\"/wiki/Stochastic_grammar\" title=\"Stochastic grammar\">stochastic grammar</a></i>).</dd></dl>\\n<h3><span id=\"Lexical_semantics_.28of_individual_words_in_context.29\"></span><span class=\"mw-headline\" id=\"Lexical_semantics_(of_individual_words_in_context)\">Lexical semantics (of individual words in context)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=12\" title=\"Edit section: Lexical semantics (of individual words in context)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<dl><dt><a href=\"/wiki/Lexical_semantics\" title=\"Lexical semantics\">Lexical semantics</a></dt>\\n<dd>What is the computational meaning of individual words in context?</dd>\\n<dt><a href=\"/wiki/Distributional_semantics\" title=\"Distributional semantics\">Distributional semantics</a></dt>\\n<dd>How can we learn semantic representations from data?</dd>\\n<dt><a href=\"/wiki/Named_entity_recognition\" class=\"mw-redirect\" title=\"Named entity recognition\">Named entity recognition</a> (NER)</dt>\\n<dd>Given a stream of text, determine which items in the text map to proper names, such as people or places, and what the type of each such name is (e.g. person, location, organization). Although <a href=\"/wiki/Capitalization\" title=\"Capitalization\">capitalization</a> can aid in recognizing named entities in languages such as English, this information cannot aid in determining the type of <a href=\"/wiki/Named_entity\" title=\"Named entity\">named entity</a>, and in any case, is often inaccurate or insufficient. For example, the first letter of a sentence is also capitalized, and named entities often span several words, only some of which are capitalized. Furthermore, many other languages in non-Western scripts (e.g. <a href=\"/wiki/Chinese_language\" title=\"Chinese language\">Chinese</a> or <a href=\"/wiki/Arabic_language\" class=\"mw-redirect\" title=\"Arabic language\">Arabic</a>) do not have any capitalization at all, and even languages with capitalization may not consistently use it to distinguish names. For example, <a href=\"/wiki/German_language\" title=\"German language\">German</a> capitalizes all <a href=\"/wiki/Noun\" title=\"Noun\">nouns</a>, regardless of whether they are names, and <a href=\"/wiki/French_language\" title=\"French language\">French</a> and <a href=\"/wiki/Spanish_language\" title=\"Spanish language\">Spanish</a> do not capitalize names that serve as <a href=\"/wiki/Adjective\" title=\"Adjective\">adjectives</a>.</dd></dl>\\n<dl><dt><a href=\"/wiki/Sentiment_analysis\" title=\"Sentiment analysis\">Sentiment analysis</a> (see also <a href=\"/wiki/Multimodal_sentiment_analysis\" title=\"Multimodal sentiment analysis\">Multimodal sentiment analysis</a>)</dt>\\n<dd>Extract subjective information usually from a set of documents, often using online reviews to determine \"polarity\" about specific objects. It is especially useful for identifying trends of public opinion in social media, for marketing.</dd></dl>\\n<dl><dt><dl><dt><a href=\"/wiki/Terminology_extraction\" title=\"Terminology extraction\">Terminology extraction</a></dt></dl>\\n</dt><dd>The goal of terminology extraction is to automatically extract relevant terms from a given corpus.</dd>\\n<dt><a href=\"/wiki/Word_sense_disambiguation\" class=\"mw-redirect\" title=\"Word sense disambiguation\">Word sense disambiguation</a></dt>\\n<dd>Many words have more than one <a href=\"/wiki/Meaning_(linguistics)\" class=\"mw-redirect\" title=\"Meaning (linguistics)\">meaning</a>; we have to select the meaning which makes the most sense in context. For this problem, we are typically given a list of words and associated word senses, e.g. from a dictionary or an online resource such as <a href=\"/wiki/WordNet\" title=\"WordNet\">WordNet</a>.</dd></dl>\\n<h3><span id=\"Relational_semantics_.28semantics_of_individual_sentences.29\"></span><span class=\"mw-headline\" id=\"Relational_semantics_(semantics_of_individual_sentences)\">Relational semantics (semantics of individual sentences)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=13\" title=\"Edit section: Relational semantics (semantics of individual sentences)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<dl><dt><a href=\"/wiki/Relationship_extraction\" title=\"Relationship extraction\">Relationship extraction</a></dt>\\n<dd>Given a chunk of text, identify the relationships among named entities (e.g. who is married to whom).</dd>\\n<dt><a href=\"/wiki/Semantic_parsing\" title=\"Semantic parsing\">Semantic parsing</a></dt>\\n<dd>Given a piece of text (typically a sentence), produce a formal representation of its semantics, either as a graph (e.g., in <a href=\"/wiki/Abstract_Meaning_Representation\" title=\"Abstract Meaning Representation\">AMR parsing</a>) or in accordance with a logical formalism (e.g., in <a href=\"/wiki/Discourse_representation_theory\" title=\"Discourse representation theory\">DRT parsing</a>). This challenge typically includes aspects of several more elementary NLP tasks from semantics (e.g., semantic role labelling, word sense disambiguation) and can be extended to include full-fledged discourse analysis (e.g., discourse analysis, coreference; see <a href=\"#Natural_language_understanding\">Natural language understanding</a> below).</dd>\\n<dt><a href=\"/wiki/Semantic_role_labeling\" title=\"Semantic role labeling\">Semantic role labelling</a> (see also implicit semantic role labelling below)</dt>\\n<dd>Given a single sentence, identify and disambiguate semantic predicates (e.g., verbal <a href=\"/wiki/Frame_semantics_(linguistics)\" title=\"Frame semantics (linguistics)\">frames</a>), then identify and classify the frame elements (<a href=\"/wiki/Semantic_roles\" class=\"mw-redirect\" title=\"Semantic roles\">semantic roles</a>).</dd></dl>\\n<h3><span id=\"Discourse_.28semantics_beyond_individual_sentences.29\"></span><span class=\"mw-headline\" id=\"Discourse_(semantics_beyond_individual_sentences)\">Discourse (semantics beyond individual sentences)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=14\" title=\"Edit section: Discourse (semantics beyond individual sentences)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<dl><dt><a href=\"/wiki/Coreference\" title=\"Coreference\">Coreference resolution</a></dt>\\n<dd>Given a sentence or larger chunk of text, determine which words (\"mentions\") refer to the same objects (\"entities\"). <a href=\"/wiki/Anaphora_resolution\" class=\"mw-redirect\" title=\"Anaphora resolution\">Anaphora resolution</a> is a specific example of this task, and is specifically concerned with matching up <a href=\"/wiki/Pronoun\" title=\"Pronoun\">pronouns</a> with the nouns or names to which they refer. The more general task of coreference resolution also includes identifying so-called \"bridging relationships\" involving <a href=\"/wiki/Referring_expression\" title=\"Referring expression\">referring expressions</a>. For example, in a sentence such as \"He entered John\\'s house through the front door\", \"the front door\" is a referring expression and the bridging relationship to be identified is the fact that the door being referred to is the front door of John\\'s house (rather than of some other structure that might also be referred to).</dd>\\n<dt><a href=\"/wiki/Discourse_analysis\" title=\"Discourse analysis\">Discourse analysis</a></dt>\\n<dd>This rubric includes several related tasks. One task is discourse parsing, i.e., identifying the <a href=\"/wiki/Discourse\" title=\"Discourse\">discourse</a> structure of a connected text, i.e. the nature of the discourse relationships between sentences (e.g. elaboration, explanation, contrast). Another possible task is recognizing and classifying the <a href=\"/wiki/Speech_act\" title=\"Speech act\">speech acts</a> in a chunk of text (e.g. yes-no question, content question, statement, assertion, etc.).</dd></dl>\\n<dl><dt>Implicit semantic role labelling</dt>\\n<dd>Given a single sentence, identify and disambiguate semantic predicates (e.g., verbal <a href=\"/wiki/Frame_semantics_(linguistics)\" title=\"Frame semantics (linguistics)\">frames</a>) and their explicit semantic roles in the current sentence (see <a href=\"#Semantic_role_labelling\">Semantic role labelling</a> above). Then, identify semantic roles that are not explicitly realized in the current sentence, classify them into arguments that are explicitly realized elsewhere in the text and those that are not specified, and resolve the former against the local text. A closely related task is zero anaphora resolution, i.e., the extension of coreference resolution to <a href=\"/wiki/Pro-drop_language\" title=\"Pro-drop language\">pro-drop languages</a>.</dd></dl>\\n<dl><dt><a href=\"/wiki/Textual_entailment\" title=\"Textual entailment\">Recognizing textual entailment</a></dt>\\n<dd>Given two text fragments, determine if one being true entails the other, entails the other\\'s negation, or allows the other to be either true or false.<sup id=\"cite_ref-rte:11_22-0\" class=\"reference\"><a href=\"#cite_note-rte:11-22\">&#91;22&#93;</a></sup></dd></dl>\\n<dl><dt><a href=\"/wiki/Topic_segmentation\" class=\"mw-redirect\" title=\"Topic segmentation\">Topic segmentation</a> and recognition</dt>\\n<dd>Given a chunk of text, separate it into segments each of which is devoted to a topic, and identify the topic of the segment.</dd></dl>\\n<dl><dt><a href=\"/wiki/Argument_mining\" title=\"Argument mining\">Argument mining</a></dt>\\n<dd>The goal of argument mining is the automatic extraction and identification of argumentative structures from <a href=\"/wiki/Natural_language\" title=\"Natural language\">natural language</a> text with the aid of computer programs. <sup id=\"cite_ref-23\" class=\"reference\"><a href=\"#cite_note-23\">&#91;23&#93;</a></sup> Such argumentative structures include the premise, conclusions, the <a href=\"/wiki/Argument_scheme\" class=\"mw-redirect\" title=\"Argument scheme\">argument scheme</a> and the relationship between the main and subsidiary argument, or the main and counter-argument within discourse. <sup id=\"cite_ref-24\" class=\"reference\"><a href=\"#cite_note-24\">&#91;24&#93;</a></sup><sup id=\"cite_ref-25\" class=\"reference\"><a href=\"#cite_note-25\">&#91;25&#93;</a></sup></dd></dl>\\n<h3><span class=\"mw-headline\" id=\"Higher-level_NLP_applications\">Higher-level NLP applications</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=15\" title=\"Edit section: Higher-level NLP applications\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<dl><dt><a href=\"/wiki/Automatic_summarization\" title=\"Automatic summarization\">Automatic summarization</a> (text summarization)</dt>\\n<dd>Produce a readable summary of a chunk of text. Often used to provide summaries of the text of a known type, such as research papers, articles in the financial section of a newspaper.</dd>\\n<dt>Book generation</dt>\\n<dd>Not an NLP task proper but an extension of natural language generation and other NLP tasks is the creation of full-fledged books. The first machine-generated book was created by a rule-based system in 1984 (Racter, <i>The policeman\\'s beard is half-constructed</i>).<sup id=\"cite_ref-26\" class=\"reference\"><a href=\"#cite_note-26\">&#91;26&#93;</a></sup> The first published work by a neural network was published in 2018, <i><a href=\"/wiki/1_the_Road\" title=\"1 the Road\">1 the Road</a></i>, marketed as a novel, contains sixty million words. Both these systems are basically elaborate but non-sensical (semantics-free) <a href=\"/wiki/Language_model\" title=\"Language model\">language models</a>. The first machine-generated science book was published in 2019 (Beta Writer, <i>Lithium-Ion Batteries</i>, Springer, Cham).<sup id=\"cite_ref-27\" class=\"reference\"><a href=\"#cite_note-27\">&#91;27&#93;</a></sup> Unlike <i>Racter</i> and <i>1 the Road</i>, this is grounded on factual knowledge and based on text summarization.</dd>\\n<dt><a href=\"/wiki/Dialogue_system\" title=\"Dialogue system\">Dialogue management</a></dt>\\n<dd>Computer systems intended to converse with a human.</dd>\\n<dt><a href=\"/wiki/Document_AI\" title=\"Document AI\">Document AI</a></dt>\\n<dd>A Document AI platform sits on top of the NLP technology enabling users with no prior experience of artificial intelligence, machine learning or NLP to quickly train a computer to extract the specific data they need from different document types. NLP-powered Document AI enables non-technical teams to quickly access information hidden in documents, for example, lawyers, business analysts and accountants.<sup id=\"cite_ref-28\" class=\"reference\"><a href=\"#cite_note-28\">&#91;28&#93;</a></sup></dd>\\n<dt><span id=\"Grammatical_error_correction\">Grammatical error correction</span></dt>\\n<dd>Grammatical error detection and correction involves a great band-width of problems on all levels of linguistic analysis (phonology/orthography, morphology, syntax, semantics, pragmatics). Grammatical error correction is impactful since it affects hundreds of millions of people that use or acquire English as a second language. It has thus been subject to a number of shared tasks since 2011.<sup id=\"cite_ref-29\" class=\"reference\"><a href=\"#cite_note-29\">&#91;29&#93;</a></sup><sup id=\"cite_ref-30\" class=\"reference\"><a href=\"#cite_note-30\">&#91;30&#93;</a></sup><sup id=\"cite_ref-31\" class=\"reference\"><a href=\"#cite_note-31\">&#91;31&#93;</a></sup> As far as orthography, morphology, syntax and certain aspects of semantics are concerned, and due to the development of powerful neural language models such as <a href=\"/wiki/GPT-2\" title=\"GPT-2\">GPT-2</a>, this can now (2019) be considered a largely solved problem and is being marketed in various commercial applications.<sup id=\"cite_ref-32\" class=\"reference\"><a href=\"#cite_note-32\">&#91;32&#93;</a></sup></dd>\\n<dt><a href=\"/wiki/Machine_translation\" title=\"Machine translation\">Machine translation</a></dt>\\n<dd>Automatically translate text from one human language to another. This is one of the most difficult problems, and is a member of a class of problems colloquially termed \"<a href=\"/wiki/AI-complete\" title=\"AI-complete\">AI-complete</a>\", i.e. requiring all of the different types of knowledge that humans possess (grammar, semantics, facts about the real world, etc.) to solve properly.</dd>\\n<dt><a href=\"/wiki/Natural_language_generation\" class=\"mw-redirect\" title=\"Natural language generation\">Natural language generation</a> (NLG):</dt>\\n<dd>Convert information from computer databases or semantic intents into readable human language.</dd>\\n<dt><a href=\"/wiki/Natural_language_understanding\" class=\"mw-redirect\" title=\"Natural language understanding\">Natural language understanding</a> (NLU)</dt>\\n<dd>Convert chunks of text into more formal representations such as <a href=\"/wiki/First-order_logic\" title=\"First-order logic\">first-order logic</a> structures that are easier for <a href=\"/wiki/Computer\" title=\"Computer\">computer</a> programs to manipulate. Natural language understanding involves the identification of the intended semantic from the multiple possible semantics which can be derived from a natural language expression which usually takes the form of organized notations of natural language concepts. Introduction and creation of language metamodel and ontology are efficient however empirical solutions. An explicit formalization of natural language semantics without confusions with implicit assumptions such as <a href=\"/wiki/Closed-world_assumption\" title=\"Closed-world assumption\">closed-world assumption</a> (CWA) vs. <a href=\"/wiki/Open-world_assumption\" title=\"Open-world assumption\">open-world assumption</a>, or subjective Yes/No vs. objective True/False is expected for the construction of a basis of semantics formalization.<sup id=\"cite_ref-33\" class=\"reference\"><a href=\"#cite_note-33\">&#91;33&#93;</a></sup></dd>\\n<dt><a href=\"/wiki/Question_answering\" title=\"Question answering\">Question answering</a></dt>\\n<dd>Given a human-language question, determine its answer. Typical questions have a specific right answer (such as \"What is the capital of Canada?\"), but sometimes open-ended questions are also considered (such as \"What is the meaning of life?\"). Recent works have looked at even more complex questions.<sup id=\"cite_ref-34\" class=\"reference\"><a href=\"#cite_note-34\">&#91;34&#93;</a></sup></dd></dl>\\n<h2><span id=\"General_tendencies_and_.28possible.29_future_directions\"></span><span class=\"mw-headline\" id=\"General_tendencies_and_(possible)_future_directions\">General tendencies and (possible) future directions</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=16\" title=\"Edit section: General tendencies and (possible) future directions\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\\n<p>Based on long-standing trends in the field, it is possible to extrapolate future directions of NLP. As of 2020, three trends among the topics of the long-standing series of CoNLL Shared Tasks can be observed:<sup id=\"cite_ref-35\" class=\"reference\"><a href=\"#cite_note-35\">&#91;35&#93;</a></sup>\\n</p>\\n<ul><li>Interest on increasingly abstract, \"cognitive\" aspects of natural language (1999-2001: shallow parsing, 2002-03: named entity recognition, 2006-09/2017-18: dependency syntax, 2004-05/2008-09 semantic role labelling, 2011-12 coreference, 2015-16: discourse parsing, 2019: semantic parsing).</li>\\n<li>Increasing interest in multilinguality, and, potentially, multimodality (English since 1999; Spanish, Dutch since 2002; German since 2003; Bulgarian, Danish, Japanese, Portuguese, Slovenian, Swedish, Turkish since 2006; Basque, Catalan, Chinese, Greek, Hungarian, Italian, Turkish since 2007; Czech since 2009; Arabic since 2012; 2017: 40+ languages; 2018: 60+/100+ languages)</li>\\n<li>Elimination of symbolic representations (rule-based over supervised towards weakly supervised methods, representation learning and end-to-end systems)</li></ul>\\n<h3><span class=\"mw-headline\" id=\"Cognition_and_NLP\">Cognition and NLP</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=17\" title=\"Edit section: Cognition and NLP\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\\n<p>Most more higher-level NLP applications involve aspects that emulate intelligent behaviour and apparent comprehension of natural language. More broadly speaking, the technical operationalization of increasingly advanced aspects of cognitive behaviour represents one of the developmental trajectories of NLP (see trends among CoNLL shared tasks above).\\n</p><p><a href=\"/wiki/Cognition\" title=\"Cognition\">Cognition</a> refers to \"the mental action or process of acquiring knowledge and understanding through thought, experience, and the senses.\"<sup id=\"cite_ref-36\" class=\"reference\"><a href=\"#cite_note-36\">&#91;36&#93;</a></sup> <a href=\"/wiki/Cognitive_science\" title=\"Cognitive science\">Cognitive science</a> is the interdisciplinary, scientific study of the mind and its processes.<sup id=\"cite_ref-37\" class=\"reference\"><a href=\"#cite_note-37\">&#91;37&#93;</a></sup> <a href=\"/wiki/Cognitive_linguistics\" title=\"Cognitive linguistics\">Cognitive linguistics</a> is an interdisciplinary branch of linguistics, combining knowledge and research from both psychology and linguistics.<sup id=\"cite_ref-38\" class=\"reference\"><a href=\"#cite_note-38\">&#91;38&#93;</a></sup> Especially during the age of <a href=\"#Symbolic_NLP_(1950s_-_early_1990s)\">symbolic NLP</a>, the area of computational linguistics maintained strong ties with cognitive studies. \\n</p><p>As an example, <a href=\"/wiki/George_Lakoff\" title=\"George Lakoff\">George Lakoff</a> offers a methodology to build natural language processing (NLP) algorithms through the perspective of <a href=\"/wiki/Cognitive_science\" title=\"Cognitive science\">cognitive science</a>, along with the findings of <a href=\"/wiki/Cognitive_linguistics\" title=\"Cognitive linguistics\">cognitive linguistics</a>,<sup id=\"cite_ref-39\" class=\"reference\"><a href=\"#cite_note-39\">&#91;39&#93;</a></sup> with two defining aspects: \\n</p>\\n<ol><li>Apply the theory of <a href=\"/wiki/Conceptual_metaphor\" title=\"Conceptual metaphor\">conceptual metaphor</a>, explained by Lakoff as \\xe2\\x80\\x9cthe understanding of one idea, in terms of another\\xe2\\x80\\x9d which provides an idea of the intent of the author.<sup id=\"cite_ref-40\" class=\"reference\"><a href=\"#cite_note-40\">&#91;40&#93;</a></sup> For example, consider the English word <i>\\xe2\\x80\\x9cbig\\xe2\\x80\\x9d</i>. When used in a comparison (<i>\\xe2\\x80\\x9cThat is a big tree\\xe2\\x80\\x9d</i>), the author\\'s intent is to imply that the tree is <i>\\xe2\\x80\\x9dphysically large\\xe2\\x80\\x9d</i> relative to other trees or the authors experience. When used metaphorically (<i>\\xe2\\x80\\x9dTomorrow is a big day\\xe2\\x80\\x9d</i>), the author\\xe2\\x80\\x99s intent to imply <i>\\xe2\\x80\\x9dimportance\\xe2\\x80\\x9d</i>. The intent behind other usages, like in <i>\\xe2\\x80\\x9dShe is a big person\\xe2\\x80\\x9d</i> will remain somewhat ambiguous to a person and a cognitive NLP algorithm alike without additional information.</li>\\n<li>Assign relative measures of meaning to a word, phrase, sentence or piece of text based on the information presented before and after the piece of text being analyzed, e.g., by means of a <a href=\"/wiki/Probabilistic_context-free_grammar\" title=\"Probabilistic context-free grammar\">probabilistic context-free grammar</a> (PCFG). The mathematical equation for such algorithms is presented in <span class=\"citation patent\"><a rel=\"nofollow\" class=\"external text\" href=\"https://worldwide.espacenet.com/textdoc?DB=EPODOC&amp;IDX=US9269353\">US&#32;patent 9269353</a></span><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Apatent&amp;rft.number=9269353&amp;rft.cc=US&amp;rft.title=\"><span style=\"display: none;\">&#160;</span></span>:</li></ol>\\n<dl><dd><dl><dd><span class=\"mwe-math-element\"><span class=\"mwe-math-mathml-inline mwe-math-mathml-a11y\" style=\"display: none;\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\" alttext=\"{\\\\displaystyle {RMM(token_{N})}={PMM(token_{N})}\\\\times {\\\\frac {1}{2d}}\\\\left(\\\\sum _{i=-d}^{d}{((PMM(token_{N-1})}\\\\times {PF(token_{N},token_{N-1}))_{i}}\\\\right)}\">\\n <semantics>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mstyle displaystyle=\"true\" scriptlevel=\"0\">\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>R</mi>\\n <mi>M</mi>\\n <mi>M</mi>\\n <mo stretchy=\"false\">(</mo>\\n <mi>t</mi>\\n <mi>o</mi>\\n <mi>k</mi>\\n <mi>e</mi>\\n <msub>\\n <mi>n</mi>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>N</mi>\\n </mrow>\\n </msub>\\n <mo stretchy=\"false\">)</mo>\\n </mrow>\\n <mo>=</mo>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>P</mi>\\n <mi>M</mi>\\n <mi>M</mi>\\n <mo stretchy=\"false\">(</mo>\\n <mi>t</mi>\\n <mi>o</mi>\\n <mi>k</mi>\\n <mi>e</mi>\\n <msub>\\n <mi>n</mi>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>N</mi>\\n </mrow>\\n </msub>\\n <mo stretchy=\"false\">)</mo>\\n </mrow>\\n <mo>&#x00D7;<!-- \\xc3\\x97 --></mo>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mfrac>\\n <mn>1</mn>\\n <mrow>\\n <mn>2</mn>\\n <mi>d</mi>\\n </mrow>\\n </mfrac>\\n </mrow>\\n <mrow>\\n <mo>(</mo>\\n <mrow>\\n <munderover>\\n <mo>&#x2211;<!-- \\xe2\\x88\\x91 --></mo>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>i</mi>\\n <mo>=</mo>\\n <mo>&#x2212;<!-- \\xe2\\x88\\x92 --></mo>\\n <mi>d</mi>\\n </mrow>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>d</mi>\\n </mrow>\\n </munderover>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mo stretchy=\"false\">(</mo>\\n <mo stretchy=\"false\">(</mo>\\n <mi>P</mi>\\n <mi>M</mi>\\n <mi>M</mi>\\n <mo stretchy=\"false\">(</mo>\\n <mi>t</mi>\\n <mi>o</mi>\\n <mi>k</mi>\\n <mi>e</mi>\\n <msub>\\n <mi>n</mi>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>N</mi>\\n <mo>&#x2212;<!-- \\xe2\\x88\\x92 --></mo>\\n <mn>1</mn>\\n </mrow>\\n </msub>\\n <mo stretchy=\"false\">)</mo>\\n </mrow>\\n <mo>&#x00D7;<!-- \\xc3\\x97 --></mo>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>P</mi>\\n <mi>F</mi>\\n <mo stretchy=\"false\">(</mo>\\n <mi>t</mi>\\n <mi>o</mi>\\n <mi>k</mi>\\n <mi>e</mi>\\n <msub>\\n <mi>n</mi>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>N</mi>\\n </mrow>\\n </msub>\\n <mo>,</mo>\\n <mi>t</mi>\\n <mi>o</mi>\\n <mi>k</mi>\\n <mi>e</mi>\\n <msub>\\n <mi>n</mi>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>N</mi>\\n <mo>&#x2212;<!-- \\xe2\\x88\\x92 --></mo>\\n <mn>1</mn>\\n </mrow>\\n </msub>\\n <mo stretchy=\"false\">)</mo>\\n <msub>\\n <mo stretchy=\"false\">)</mo>\\n <mrow class=\"MJX-TeXAtom-ORD\">\\n <mi>i</mi>\\n </mrow>\\n </msub>\\n </mrow>\\n </mrow>\\n <mo>)</mo>\\n </mrow>\\n </mstyle>\\n </mrow>\\n <annotation encoding=\"application/x-tex\">{\\\\displaystyle {RMM(token_{N})}={PMM(token_{N})}\\\\times {\\\\frac {1}{2d}}\\\\left(\\\\sum _{i=-d}^{d}{((PMM(token_{N-1})}\\\\times {PF(token_{N},token_{N-1}))_{i}}\\\\right)}</annotation>\\n </semantics>\\n</math></span><img src=\"https://wikimedia.org/api/rest_v1/media/math/render/svg/145bdbd62e463df3e65c94db2e17224ecbcb2c40\" class=\"mwe-math-fallback-image-inline\" aria-hidden=\"true\" style=\"vertical-align: -3.171ex; width:96.554ex; height:7.509ex;\" alt=\"{\\\\displaystyle {RMM(token_{N})}={PMM(token_{N})}\\\\times {\\\\frac {1}{2d}}\\\\left(\\\\sum _{i=-d}^{d}{((PMM(token_{N-1})}\\\\times {PF(token_{N},token_{N-1}))_{i}}\\\\right)}\"/></span></dd></dl></dd></dl>\\n<dl><dd><dl><dd><i>Where,</i>\\n<dl><dd><b>RMM</b>, is the Relative Measure of Meaning</dd>\\n<dd><b>token</b>, is any block of text, sentence, phrase or word</dd>\\n<dd><b>N</b>, is the number of tokens being analyzed</dd>\\n<dd><b>PMM</b>, is the Probable Measure of Meaning based on a corpora</dd>\\n<dd><b>d</b>, is the location of the token along the sequence of <b>N-1</b> tokens</dd>\\n<dd><b>PF</b>, is the Probability Function specific to a language</dd></dl></dd></dl></dd></dl>\\n<p>Ties with cognitive linguistics are part of the historical heritage of NLP, but they have been less frequently addressed since the statistical turn during the 1990s. Nevertheless, approaches to develop cognitive models towards technically operationalizable frameworks have been pursued in the context of various frameworks, e.g., of cognitive grammar,<sup id=\"cite_ref-41\" class=\"reference\"><a href=\"#cite_note-41\">&#91;41&#93;</a></sup> functional grammar,<sup id=\"cite_ref-42\" class=\"reference\"><a href=\"#cite_note-42\">&#91;42&#93;</a></sup> construction grammar,<sup id=\"cite_ref-43\" class=\"reference\"><a href=\"#cite_note-43\">&#91;43&#93;</a></sup> computational psycholinguistics and cognitive neuroscience (e.g., <a href=\"/wiki/ACT-R\" title=\"ACT-R\">ACT-R</a>), however, with limited uptake in mainstream NLP (as measured by presence on major conferences<sup id=\"cite_ref-44\" class=\"reference\"><a href=\"#cite_note-44\">&#91;44&#93;</a></sup> of the <a href=\"/wiki/Association_for_Computational_Linguistics\" title=\"Association for Computational Linguistics\">ACL</a>). More recently, ideas of cognitive NLP have been revived as an approach to achieve <a href=\"/wiki/Explainable_artificial_intelligence\" title=\"Explainable artificial intelligence\">explainability</a>, e.g., under the notion of \"cognitive AI\".<sup id=\"cite_ref-45\" class=\"reference\"><a href=\"#cite_note-45\">&#91;45&#93;</a></sup> Likewise, ideas of cognitive NLP are inherent to neural models multimodal NLP (although rarely made explicit).<sup id=\"cite_ref-46\" class=\"reference\"><a href=\"#cite_note-46\">&#91;46&#93;</a></sup>\\n</p>\\n<h2><span class=\"mw-headline\" id=\"See_also\">See also</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=18\" title=\"Edit section: See also\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\\n<style data-mw-deduplicate=\"TemplateStyles:r998391716\">.mw-parser-output .div-col{margin-top:0.3em;column-width:30em}.mw-parser-output .div-col-small{font-size:90%}.mw-parser-output .div-col-rules{column-rule:1px solid #aaa}.mw-parser-output .div-col dl,.mw-parser-output .div-col ol,.mw-parser-output .div-col ul{margin-top:0}.mw-parser-output .div-col li,.mw-parser-output .div-col dd{page-break-inside:avoid;break-inside:avoid-column}</style><div class=\"div-col\" style=\"column-width: 22em;\">\\n<ul><li><i><a href=\"/wiki/1_the_Road\" title=\"1 the Road\">1 the Road</a></i></li>\\n<li><a href=\"/wiki/Automated_essay_scoring\" title=\"Automated essay scoring\">Automated essay scoring</a></li>\\n<li><a href=\"/wiki/Biomedical_text_mining\" title=\"Biomedical text mining\">Biomedical text mining</a></li>\\n<li><a href=\"/wiki/Compound_term_processing\" class=\"mw-redirect\" title=\"Compound term processing\">Compound term processing</a></li>\\n<li><a href=\"/wiki/Computational_linguistics\" title=\"Computational linguistics\">Computational linguistics</a></li>\\n<li><a href=\"/wiki/Computer-assisted_reviewing\" title=\"Computer-assisted reviewing\">Computer-assisted reviewing</a></li>\\n<li><a href=\"/wiki/Controlled_natural_language\" title=\"Controlled natural language\">Controlled natural language</a></li>\\n<li><a href=\"/wiki/Deep_learning\" title=\"Deep learning\">Deep learning</a></li>\\n<li><a href=\"/wiki/Deep_linguistic_processing\" title=\"Deep linguistic processing\">Deep linguistic processing</a></li>\\n<li><a href=\"/wiki/Distributional_semantics\" title=\"Distributional semantics\">Distributional semantics</a></li>\\n<li><a href=\"/wiki/Foreign_language_reading_aid\" class=\"mw-redirect\" title=\"Foreign language reading aid\">Foreign language reading aid</a></li>\\n<li><a href=\"/wiki/Foreign_language_writing_aid\" title=\"Foreign language writing aid\">Foreign language writing aid</a></li>\\n<li><a href=\"/wiki/Information_extraction\" title=\"Information extraction\">Information extraction</a></li>\\n<li><a href=\"/wiki/Information_retrieval\" title=\"Information retrieval\">Information retrieval</a></li>\\n<li><a href=\"/wiki/Language_and_Communication_Technologies\" title=\"Language and Communication Technologies\">Language and Communication Technologies</a></li>\\n<li><a href=\"/wiki/Language_technology\" title=\"Language technology\">Language technology</a></li>\\n<li><a href=\"/wiki/Latent_semantic_indexing\" class=\"mw-redirect\" title=\"Latent semantic indexing\">Latent semantic indexing</a></li>\\n<li><a href=\"/wiki/Native-language_identification\" title=\"Native-language identification\">Native-language identification</a></li>\\n<li><a href=\"/wiki/Natural_language_programming\" class=\"mw-redirect\" title=\"Natural language programming\">Natural language programming</a></li>\\n<li><a href=\"/wiki/Natural_language_user_interface\" class=\"mw-redirect\" title=\"Natural language user interface\">Natural language search</a></li>\\n<li><a href=\"/wiki/Outline_of_natural_language_processing\" title=\"Outline of natural language processing\">Outline of natural language processing</a></li>\\n<li><a href=\"/wiki/Query_expansion\" title=\"Query expansion\">Query expansion</a></li>\\n<li><a href=\"/wiki/Query_understanding\" title=\"Query understanding\">Query understanding</a></li>\\n<li><a href=\"/wiki/Reification_(linguistics)\" title=\"Reification (linguistics)\">Reification (linguistics)</a></li>\\n<li><a href=\"/wiki/Speech_processing\" title=\"Speech processing\">Speech processing</a></li>\\n<li><a href=\"/wiki/Spoken_dialogue_system\" class=\"mw-redirect\" title=\"Spoken dialogue system\">Spoken dialogue system</a></li>\\n<li><a href=\"/wiki/Text-proofing\" class=\"mw-redirect\" title=\"Text-proofing\">Text-proofing</a></li>\\n<li><a href=\"/wiki/Text_simplification\" title=\"Text simplification\">Text simplification</a></li>\\n<li><a href=\"/wiki/Transformer_(machine_learning_model)\" title=\"Transformer (machine learning model)\">Transformer (machine learning model)</a></li>\\n<li><a href=\"/wiki/Truecasing\" title=\"Truecasing\">Truecasing</a></li>\\n<li><a href=\"/wiki/Question_answering\" title=\"Question answering\">Question answering</a></li>\\n<li><a href=\"/wiki/Word2vec\" title=\"Word2vec\">Word2vec</a></li></ul>\\n</div>\\n<h2><span class=\"mw-headline\" id=\"References\">References</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=19\" title=\"Edit section: References\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\\n<style data-mw-deduplicate=\"TemplateStyles:r1011085734\">.mw-parser-output .reflist{font-size:90%;margin-bottom:0.5em;list-style-type:decimal}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}</style><div class=\"reflist reflist-columns references-column-width\" style=\"column-width: 30em;\">\\n<ol class=\"references\">\\n<li id=\"cite_note-Kongthon-1\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-Kongthon_1-0\">^</a></b></span> <span class=\"reference-text\"><style data-mw-deduplicate=\"TemplateStyles:r999302996\">.mw-parser-output cite.citation{font-style:inherit}.mw-parser-output .citation q{quotes:\"\\\\\"\"\"\\\\\"\"\"\\'\"\"\\'\"}.mw-parser-output .id-lock-free a,.mw-parser-output .citation .cs1-lock-free a{background:linear-gradient(transparent,transparent),url(\"//upload.wikimedia.org/wikipedia/commons/6/65/Lock-green.svg\")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited a,.mw-parser-output .id-lock-registration a,.mw-parser-output .citation .cs1-lock-limited a,.mw-parser-output .citation .cs1-lock-registration a{background:linear-gradient(transparent,transparent),url(\"//upload.wikimedia.org/wikipedia/commons/d/d6/Lock-gray-alt-2.svg\")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription a,.mw-parser-output .citation .cs1-lock-subscription a{background:linear-gradient(transparent,transparent),url(\"//upload.wikimedia.org/wikipedia/commons/a/aa/Lock-red-alt-2.svg\")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-subscription,.mw-parser-output .cs1-registration{color:#555}.mw-parser-output .cs1-subscription span,.mw-parser-output .cs1-registration span{border-bottom:1px dotted;cursor:help}.mw-parser-output .cs1-ws-icon a{background:linear-gradient(transparent,transparent),url(\"//upload.wikimedia.org/wikipedia/commons/4/4c/Wikisource-logo.svg\")right 0.1em center/12px no-repeat}.mw-parser-output code.cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;font-size:100%}.mw-parser-output .cs1-visible-error{font-size:100%}.mw-parser-output .cs1-maint{display:none;color:#33aa33;margin-left:0.3em}.mw-parser-output .cs1-format{font-size:95%}.mw-parser-output .cs1-kern-left,.mw-parser-output .cs1-kern-wl-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right,.mw-parser-output .cs1-kern-wl-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}</style><cite id=\"CITEREFKongthonSangkeettrakarnKongyoungHaruechaiyasak2009\" class=\"citation conference cs1\">Kongthon, Alisa; Sangkeettrakarn, Chatchawal; Kongyoung, Sarawoot; Haruechaiyasak, Choochart (October 27\\xe2\\x80\\x9330, 2009). <i>Implementing an online help desk system based on conversational agent</i>. MEDES \\'09: The International Conference on Management of Emergent Digital EcoSystems. France: ACM. <a href=\"/wiki/Doi_(identifier)\" class=\"mw-redirect\" title=\"Doi (identifier)\">doi</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://doi.org/10.1145%2F1643823.1643908\">10.1145/1643823.1643908</a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=conference&amp;rft.btitle=Implementing+an+online+help+desk+system+based+on+conversational+agent&amp;rft.place=France&amp;rft.pub=ACM&amp;rft.date=2009-10-27%2F2009-10-30&amp;rft_id=info%3Adoi%2F10.1145%2F1643823.1643908&amp;rft.aulast=Kongthon&amp;rft.aufirst=Alisa&amp;rft.au=Sangkeettrakarn%2C+Chatchawal&amp;rft.au=Kongyoung%2C+Sarawoot&amp;rft.au=Haruechaiyasak%2C+Choochart&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-2\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-2\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFHutchins,_J.2005\" class=\"citation web cs1\">Hutchins, J. (2005). <a rel=\"nofollow\" class=\"external text\" href=\"http://www.hutchinsweb.me.uk/Nutshell-2005.pdf\">\"The history of machine translation in a nutshell\"</a> <span class=\"cs1-format\">(PDF)</span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=The+history+of+machine+translation+in+a+nutshell&amp;rft.date=2005&amp;rft.au=Hutchins%2C+J.&amp;rft_id=http%3A%2F%2Fwww.hutchinsweb.me.uk%2FNutshell-2005.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span><sup class=\"noprint Inline-Template\" style=\"white-space:nowrap;\">&#91;<i><a href=\"/wiki/Wikipedia:Verifiability#Self-published_sources\" title=\"Wikipedia:Verifiability\"><span title=\"This reference citation appears to be to a self-published source. (December 2013)\">self-published source</span></a></i>&#93;</sup></span>\\n</li>\\n<li id=\"cite_note-3\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-3\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFKoskenniemi1983\" class=\"citation cs2\"><a href=\"/wiki/Kimmo_Koskenniemi\" title=\"Kimmo Koskenniemi\">Koskenniemi, Kimmo</a> (1983), <a rel=\"nofollow\" class=\"external text\" href=\"http://www.ling.helsinki.fi/~koskenni/doc/Two-LevelMorphology.pdf\"><i>Two-level morphology: A general computational model of word-form recognition and production</i></a> <span class=\"cs1-format\">(PDF)</span>, Department of General Linguistics, <a href=\"/wiki/University_of_Helsinki\" title=\"University of Helsinki\">University of Helsinki</a></cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Two-level+morphology%3A+A+general+computational+model+of+word-form+recognition+and+production&amp;rft.pub=Department+of+General+Linguistics%2C+University+of+Helsinki&amp;rft.date=1983&amp;rft.aulast=Koskenniemi&amp;rft.aufirst=Kimmo&amp;rft_id=http%3A%2F%2Fwww.ling.helsinki.fi%2F~koskenni%2Fdoc%2FTwo-LevelMorphology.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-4\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-4\">^</a></b></span> <span class=\"reference-text\">Joshi, A. K., &amp; Weinstein, S. (1981, August). <a rel=\"nofollow\" class=\"external text\" href=\"https://www.ijcai.org/Proceedings/81-1/Papers/071.pdf\">Control of Inference: Role of Some Aspects of Discourse Structure-Centering</a>. In <i>IJCAI</i> (pp. 385-387).</span>\\n</li>\\n<li id=\"cite_note-5\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-5\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFGuidaMauri1986\" class=\"citation journal cs1\">Guida, G.; Mauri, G. (July 1986). \"Evaluation of natural language processing systems: Issues and approaches\". <i>Proceedings of the IEEE</i>. <b>74</b> (7): 1026\\xe2\\x80\\x931035. <a href=\"/wiki/Doi_(identifier)\" class=\"mw-redirect\" title=\"Doi (identifier)\">doi</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://doi.org/10.1109%2FPROC.1986.13580\">10.1109/PROC.1986.13580</a>. <a href=\"/wiki/ISSN_(identifier)\" class=\"mw-redirect\" title=\"ISSN (identifier)\">ISSN</a>&#160;<a rel=\"nofollow\" class=\"external text\" href=\"//www.worldcat.org/issn/1558-2256\">1558-2256</a>. <a href=\"/wiki/S2CID_(identifier)\" class=\"mw-redirect\" title=\"S2CID (identifier)\">S2CID</a>&#160;<a rel=\"nofollow\" class=\"external text\" href=\"https://api.semanticscholar.org/CorpusID:30688575\">30688575</a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Proceedings+of+the+IEEE&amp;rft.atitle=Evaluation+of+natural+language+processing+systems%3A+Issues+and+approaches&amp;rft.volume=74&amp;rft.issue=7&amp;rft.pages=1026-1035&amp;rft.date=1986-07&amp;rft_id=https%3A%2F%2Fapi.semanticscholar.org%2FCorpusID%3A30688575%23id-name%3DS2CID&amp;rft.issn=1558-2256&amp;rft_id=info%3Adoi%2F10.1109%2FPROC.1986.13580&amp;rft.aulast=Guida&amp;rft.aufirst=G.&amp;rft.au=Mauri%2C+G.&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-6\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-6\">^</a></b></span> <span class=\"reference-text\">Chomskyan linguistics encourages the investigation of \"<a href=\"/wiki/Corner_case\" title=\"Corner case\">corner cases</a>\" that stress the limits of its theoretical models (comparable to <a href=\"/wiki/Pathological_(mathematics)\" title=\"Pathological (mathematics)\">pathological</a> phenomena in mathematics), typically created using <a href=\"/wiki/Thought_experiment\" title=\"Thought experiment\">thought experiments</a>, rather than the systematic investigation of typical phenomena that occur in real-world data, as is the case in <a href=\"/wiki/Corpus_linguistics\" title=\"Corpus linguistics\">corpus linguistics</a>. The creation and use of such <a href=\"/wiki/Text_corpus\" title=\"Text corpus\">corpora</a> of real-world data is a fundamental part of machine-learning algorithms for natural language processing. In addition, theoretical underpinnings of Chomskyan linguistics such as the so-called \"<a href=\"/wiki/Poverty_of_the_stimulus\" title=\"Poverty of the stimulus\">poverty of the stimulus</a>\" argument entail that general learning algorithms, as are typically used in machine learning, cannot be successful in language processing. As a result, the Chomskyan paradigm discouraged the application of such models to language processing.</span>\\n</li>\\n<li id=\"cite_note-goldberg:nnlp17-7\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-goldberg:nnlp17_7-0\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFGoldberg2016\" class=\"citation journal cs1\">Goldberg, Yoav (2016). \"A Primer on Neural Network Models for Natural Language Processing\". <i>Journal of Artificial Intelligence Research</i>. <b>57</b>: 345\\xe2\\x80\\x93420. <a href=\"/wiki/ArXiv_(identifier)\" class=\"mw-redirect\" title=\"ArXiv (identifier)\">arXiv</a>:<span class=\"cs1-lock-free\" title=\"Freely accessible\"><a rel=\"nofollow\" class=\"external text\" href=\"//arxiv.org/abs/1807.10854\">1807.10854</a></span>. <a href=\"/wiki/Doi_(identifier)\" class=\"mw-redirect\" title=\"Doi (identifier)\">doi</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://doi.org/10.1613%2Fjair.4992\">10.1613/jair.4992</a>. <a href=\"/wiki/S2CID_(identifier)\" class=\"mw-redirect\" title=\"S2CID (identifier)\">S2CID</a>&#160;<a rel=\"nofollow\" class=\"external text\" href=\"https://api.semanticscholar.org/CorpusID:8273530\">8273530</a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Journal+of+Artificial+Intelligence+Research&amp;rft.atitle=A+Primer+on+Neural+Network+Models+for+Natural+Language+Processing&amp;rft.volume=57&amp;rft.pages=345-420&amp;rft.date=2016&amp;rft_id=info%3Aarxiv%2F1807.10854&amp;rft_id=https%3A%2F%2Fapi.semanticscholar.org%2FCorpusID%3A8273530%23id-name%3DS2CID&amp;rft_id=info%3Adoi%2F10.1613%2Fjair.4992&amp;rft.aulast=Goldberg&amp;rft.aufirst=Yoav&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-goodfellow:book16-8\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-goodfellow:book16_8-0\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFGoodfellowBengioCourville2016\" class=\"citation book cs1\">Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron (2016). <a rel=\"nofollow\" class=\"external text\" href=\"http://www.deeplearningbook.org/\"><i>Deep Learning</i></a>. MIT Press.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Deep+Learning&amp;rft.pub=MIT+Press&amp;rft.date=2016&amp;rft.aulast=Goodfellow&amp;rft.aufirst=Ian&amp;rft.au=Bengio%2C+Yoshua&amp;rft.au=Courville%2C+Aaron&amp;rft_id=http%3A%2F%2Fwww.deeplearningbook.org%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-jozefowicz:lm16-9\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-jozefowicz:lm16_9-0\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFJozefowiczVinyalsSchusterShazeer2016\" class=\"citation book cs1\">Jozefowicz, Rafal; Vinyals, Oriol; Schuster, Mike; Shazeer, Noam; Wu, Yonghui (2016). <i>Exploring the Limits of Language Modeling</i>. <a href=\"/wiki/ArXiv_(identifier)\" class=\"mw-redirect\" title=\"ArXiv (identifier)\">arXiv</a>:<span class=\"cs1-lock-free\" title=\"Freely accessible\"><a rel=\"nofollow\" class=\"external text\" href=\"//arxiv.org/abs/1602.02410\">1602.02410</a></span>. <a href=\"/wiki/Bibcode_(identifier)\" class=\"mw-redirect\" title=\"Bibcode (identifier)\">Bibcode</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://ui.adsabs.harvard.edu/abs/2016arXiv160202410J\">2016arXiv160202410J</a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Exploring+the+Limits+of+Language+Modeling&amp;rft.date=2016&amp;rft_id=info%3Aarxiv%2F1602.02410&amp;rft_id=info%3Abibcode%2F2016arXiv160202410J&amp;rft.aulast=Jozefowicz&amp;rft.aufirst=Rafal&amp;rft.au=Vinyals%2C+Oriol&amp;rft.au=Schuster%2C+Mike&amp;rft.au=Shazeer%2C+Noam&amp;rft.au=Wu%2C+Yonghui&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-choe:emnlp16-10\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-choe:emnlp16_10-0\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFChoeCharniak\" class=\"citation journal cs1\">Choe, Do Kook; Charniak, Eugene. <a rel=\"nofollow\" class=\"external text\" href=\"https://aclanthology.coli.uni-saarland.de/papers/D16-1257/d16-1257\">\"Parsing as Language Modeling\"</a>. <i>Emnlp 2016</i>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Emnlp+2016&amp;rft.atitle=Parsing+as+Language+Modeling&amp;rft.aulast=Choe&amp;rft.aufirst=Do+Kook&amp;rft.au=Charniak%2C+Eugene&amp;rft_id=https%3A%2F%2Faclanthology.coli.uni-saarland.de%2Fpapers%2FD16-1257%2Fd16-1257&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-vinyals:nips15-11\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-vinyals:nips15_11-0\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFVinyalsKaiser2014\" class=\"citation journal cs1\">Vinyals, Oriol; et&#160;al. (2014). <a rel=\"nofollow\" class=\"external text\" href=\"https://papers.nips.cc/paper/5635-grammar-as-a-foreign-language.pdf\">\"Grammar as a Foreign Language\"</a> <span class=\"cs1-format\">(PDF)</span>. <i>Nips2015</i>. <a href=\"/wiki/ArXiv_(identifier)\" class=\"mw-redirect\" title=\"ArXiv (identifier)\">arXiv</a>:<span class=\"cs1-lock-free\" title=\"Freely accessible\"><a rel=\"nofollow\" class=\"external text\" href=\"//arxiv.org/abs/1412.7449\">1412.7449</a></span>. <a href=\"/wiki/Bibcode_(identifier)\" class=\"mw-redirect\" title=\"Bibcode (identifier)\">Bibcode</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://ui.adsabs.harvard.edu/abs/2014arXiv1412.7449V\">2014arXiv1412.7449V</a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Nips2015&amp;rft.atitle=Grammar+as+a+Foreign+Language&amp;rft.date=2014&amp;rft_id=info%3Aarxiv%2F1412.7449&amp;rft_id=info%3Abibcode%2F2014arXiv1412.7449V&amp;rft.aulast=Vinyals&amp;rft.aufirst=Oriol&amp;rft.au=Kaiser%2C+Lukasz&amp;rft_id=https%3A%2F%2Fpapers.nips.cc%2Fpaper%2F5635-grammar-as-a-foreign-language.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-winograd:shrdlu71-12\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-winograd:shrdlu71_12-0\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFWinograd1971\" class=\"citation thesis cs1\">Winograd, Terry (1971). <a rel=\"nofollow\" class=\"external text\" href=\"http://hci.stanford.edu/winograd/shrdlu/\"><i>Procedures as a Representation for Data in a Computer Program for Understanding Natural Language</i></a> (Thesis).</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adissertation&amp;rft.title=Procedures+as+a+Representation+for+Data+in+a+Computer+Program+for+Understanding+Natural+Language&amp;rft.date=1971&amp;rft.aulast=Winograd&amp;rft.aufirst=Terry&amp;rft_id=http%3A%2F%2Fhci.stanford.edu%2Fwinograd%2Fshrdlu%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-schank77-13\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-schank77_13-0\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFSchankAbelson1977\" class=\"citation book cs1\">Schank, Roger C.; Abelson, Robert P. (1977). <i>Scripts, Plans, Goals, and Understanding: An Inquiry Into Human Knowledge Structures</i>. Hillsdale: Erlbaum. <a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/0-470-99033-3\" title=\"Special:BookSources/0-470-99033-3\"><bdi>0-470-99033-3</bdi></a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Scripts%2C+Plans%2C+Goals%2C+and+Understanding%3A+An+Inquiry+Into+Human+Knowledge+Structures&amp;rft.place=Hillsdale&amp;rft.pub=Erlbaum&amp;rft.date=1977&amp;rft.isbn=0-470-99033-3&amp;rft.aulast=Schank&amp;rft.aufirst=Roger+C.&amp;rft.au=Abelson%2C+Robert+P.&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-johnson:eacl:ilcl09-14\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-johnson:eacl:ilcl09_14-0\">^</a></b></span> <span class=\"reference-text\"><a rel=\"nofollow\" class=\"external text\" href=\"http://www.aclweb.org/anthology/W09-0103\">Mark Johnson. How the statistical revolution changes (computational) linguistics.</a> Proceedings of the EACL 2009 Workshop on the Interaction between Linguistics and Computational Linguistics.</span>\\n</li>\\n<li id=\"cite_note-resnik:langlog11-15\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-resnik:langlog11_15-0\">^</a></b></span> <span class=\"reference-text\"><a rel=\"nofollow\" class=\"external text\" href=\"http://languagelog.ldc.upenn.edu/nll/?p=2946\">Philip Resnik. Four revolutions.</a> Language Log, February 5, 2011.</span>\\n</li>\\n<li id=\"cite_note-16\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-16\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFSocher\" class=\"citation web cs1\">Socher, Richard. <a rel=\"nofollow\" class=\"external text\" href=\"https://www.socher.org/index.php/Main/DeepLearningForNLP-ACL2012Tutorial\">\"Deep Learning For NLP-ACL 2012 Tutorial\"</a>. <i>www.socher.org</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2020-08-17</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.socher.org&amp;rft.atitle=Deep+Learning+For+NLP-ACL+2012+Tutorial&amp;rft.aulast=Socher&amp;rft.aufirst=Richard&amp;rft_id=https%3A%2F%2Fwww.socher.org%2Findex.php%2FMain%2FDeepLearningForNLP-ACL2012Tutorial&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span> This was an early Deep Learning tutorial at the ACL 2012 and met with both interest and (at the time) skepticism by most participants. Until then, neural learning was basically rejected because of its lack of statistical interpretability. Until 2015, deep learning had evolved into the major framework of NLP.</span>\\n</li>\\n<li id=\"cite_note-17\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-17\">^</a></b></span> <span class=\"reference-text\">Annamoradnejad, I. (2020). <a rel=\"nofollow\" class=\"external text\" href=\"https://arxiv.org/abs/2004.12765\">Colbert: Using bert sentence embedding for humor detection</a>. arXiv preprint arXiv:2004.12765.</span>\\n</li>\\n<li id=\"cite_note-18\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-18\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFYiTian2012\" class=\"citation cs2\">Yi, Chucai; Tian, Yingli (2012), \"Assistive Text Reading from Complex Background for Blind Persons\", <i>Camera-Based Document Analysis and Recognition</i>, Springer Berlin Heidelberg, pp.&#160;15\\xe2\\x80\\x9328, <a href=\"/wiki/CiteSeerX_(identifier)\" class=\"mw-redirect\" title=\"CiteSeerX (identifier)\">CiteSeerX</a>&#160;<span class=\"cs1-lock-free\" title=\"Freely accessible\"><a rel=\"nofollow\" class=\"external text\" href=\"//citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.668.869\">10.1.1.668.869</a></span>, <a href=\"/wiki/Doi_(identifier)\" class=\"mw-redirect\" title=\"Doi (identifier)\">doi</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://doi.org/10.1007%2F978-3-642-29364-1_2\">10.1007/978-3-642-29364-1_2</a>, <a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/9783642293634\" title=\"Special:BookSources/9783642293634\"><bdi>9783642293634</bdi></a></cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Camera-Based+Document+Analysis+and+Recognition&amp;rft.atitle=Assistive+Text+Reading+from+Complex+Background+for+Blind+Persons&amp;rft.pages=15-28&amp;rft.date=2012&amp;rft_id=%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fsummary%3Fdoi%3D10.1.1.668.869%23id-name%3DCiteSeerX&amp;rft_id=info%3Adoi%2F10.1007%2F978-3-642-29364-1_2&amp;rft.isbn=9783642293634&amp;rft.aulast=Yi&amp;rft.aufirst=Chucai&amp;rft.au=Tian%2C+Yingli&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-19\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-19\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.gyansetu.in/what-is-natural-language-processing/\">\"What is Natural Language Processing? Intro to NLP in Machine Learning\"</a>. <i>GyanSetu!</i>. 2020-12-06<span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-09</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=GyanSetu%21&amp;rft.atitle=What+is+Natural+Language+Processing%3F+Intro+to+NLP+in+Machine+Learning&amp;rft.date=2020-12-06&amp;rft_id=https%3A%2F%2Fwww.gyansetu.in%2Fwhat-is-natural-language-processing%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-20\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-20\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFKishorjitVidyaNirmalSivaji2012\" class=\"citation journal cs1\">Kishorjit, N.; Vidya, Raj RK.; Nirmal, Y.; Sivaji, B. (2012). <a rel=\"nofollow\" class=\"external text\" href=\"http://aclweb.org/anthology//W/W12/W12-5008.pdf\">\"Manipuri Morpheme Identification\"</a> <span class=\"cs1-format\">(PDF)</span>. <i>Proceedings of the 3rd Workshop on South and Southeast Asian Natural Language Processing (SANLP)</i>. COLING 2012, Mumbai, December 2012: 95\\xe2\\x80\\x93108.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Proceedings+of+the+3rd+Workshop+on+South+and+Southeast+Asian+Natural+Language+Processing+%28SANLP%29&amp;rft.atitle=Manipuri+Morpheme+Identification&amp;rft.pages=95-108&amp;rft.date=2012&amp;rft.aulast=Kishorjit&amp;rft.aufirst=N.&amp;rft.au=Vidya%2C+Raj+RK.&amp;rft.au=Nirmal%2C+Y.&amp;rft.au=Sivaji%2C+B.&amp;rft_id=http%3A%2F%2Faclweb.org%2Fanthology%2F%2FW%2FW12%2FW12-5008.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span><span class=\"cs1-maint citation-comment\">CS1 maint: location (<a href=\"/wiki/Category:CS1_maint:_location\" title=\"Category:CS1 maint: location\">link</a>)</span></span>\\n</li>\\n<li id=\"cite_note-21\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-21\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFKleinManning2002\" class=\"citation journal cs1\">Klein, Dan; Manning, Christopher D. (2002). <a rel=\"nofollow\" class=\"external text\" href=\"http://papers.nips.cc/paper/1945-natural-language-grammar-induction-using-a-constituent-context-model.pdf\">\"Natural language grammar induction using a constituent-context model\"</a> <span class=\"cs1-format\">(PDF)</span>. <i>Advances in Neural Information Processing Systems</i>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Advances+in+Neural+Information+Processing+Systems&amp;rft.atitle=Natural+language+grammar+induction+using+a+constituent-context+model&amp;rft.date=2002&amp;rft.aulast=Klein&amp;rft.aufirst=Dan&amp;rft.au=Manning%2C+Christopher+D.&amp;rft_id=http%3A%2F%2Fpapers.nips.cc%2Fpaper%2F1945-natural-language-grammar-induction-using-a-constituent-context-model.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-rte:11-22\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-rte:11_22-0\">^</a></b></span> <span class=\"reference-text\">PASCAL Recognizing Textual Entailment Challenge (RTE-7) <a rel=\"nofollow\" class=\"external free\" href=\"https://tac.nist.gov//2011/RTE/\">https://tac.nist.gov//2011/RTE/</a></span>\\n</li>\\n<li id=\"cite_note-23\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-23\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFLippiTorroni2016\" class=\"citation journal cs1\">Lippi, Marco; Torroni, Paolo (2016-04-20). <a rel=\"nofollow\" class=\"external text\" href=\"https://dl.acm.org/doi/10.1145/2850417\">\"Argumentation Mining: State of the Art and Emerging Trends\"</a>. <i>ACM Transactions on Internet Technology</i>. <b>16</b> (2): 1\\xe2\\x80\\x9325. <a href=\"/wiki/Doi_(identifier)\" class=\"mw-redirect\" title=\"Doi (identifier)\">doi</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://doi.org/10.1145%2F2850417\">10.1145/2850417</a>. <a href=\"/wiki/ISSN_(identifier)\" class=\"mw-redirect\" title=\"ISSN (identifier)\">ISSN</a>&#160;<a rel=\"nofollow\" class=\"external text\" href=\"//www.worldcat.org/issn/1533-5399\">1533-5399</a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=ACM+Transactions+on+Internet+Technology&amp;rft.atitle=Argumentation+Mining%3A+State+of+the+Art+and+Emerging+Trends&amp;rft.volume=16&amp;rft.issue=2&amp;rft.pages=1-25&amp;rft.date=2016-04-20&amp;rft_id=info%3Adoi%2F10.1145%2F2850417&amp;rft.issn=1533-5399&amp;rft.aulast=Lippi&amp;rft.aufirst=Marco&amp;rft.au=Torroni%2C+Paolo&amp;rft_id=https%3A%2F%2Fdl.acm.org%2Fdoi%2F10.1145%2F2850417&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-24\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-24\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.i3s.unice.fr/~villata/tutorialIJCAI2016.html\">\"Argument Mining - IJCAI2016 Tutorial\"</a>. <i>www.i3s.unice.fr</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-03-09</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.i3s.unice.fr&amp;rft.atitle=Argument+Mining+-+IJCAI2016+Tutorial&amp;rft_id=https%3A%2F%2Fwww.i3s.unice.fr%2F~villata%2FtutorialIJCAI2016.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-25\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-25\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"http://acl2016tutorial.arg.tech/\">\"NLP Approaches to Computational Argumentation \\xe2\\x80\\x93 ACL 2016, Berlin\"</a><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-03-09</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=NLP+Approaches+to+Computational+Argumentation+%E2%80%93+ACL+2016%2C+Berlin&amp;rft_id=http%3A%2F%2Facl2016tutorial.arg.tech%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-26\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-26\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"http://www.ubu.com/historical/racter/index.html\">\"U B U W E B&#160;:: Racter\"</a>. <i>www.ubu.com</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2020-08-17</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.ubu.com&amp;rft.atitle=U+B+U+W+E+B+%3A%3A+Racter&amp;rft_id=http%3A%2F%2Fwww.ubu.com%2Fhistorical%2Fracter%2Findex.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-27\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-27\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFWriter2019\" class=\"citation book cs1\">Writer, Beta (2019). <i>Lithium-Ion Batteries</i>. <a href=\"/wiki/Doi_(identifier)\" class=\"mw-redirect\" title=\"Doi (identifier)\">doi</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://doi.org/10.1007%2F978-3-030-16800-1\">10.1007/978-3-030-16800-1</a>. <a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-3-030-16799-8\" title=\"Special:BookSources/978-3-030-16799-8\"><bdi>978-3-030-16799-8</bdi></a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Lithium-Ion+Batteries&amp;rft.date=2019&amp;rft_id=info%3Adoi%2F10.1007%2F978-3-030-16800-1&amp;rft.isbn=978-3-030-16799-8&amp;rft.aulast=Writer&amp;rft.aufirst=Beta&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-28\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-28\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.youtube.com/watch?v=7dtl650D0y0\">\"Document Understanding AI on Google Cloud (Cloud Next \\'19) - YouTube\"</a>. <i>www.youtube.com</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.youtube.com&amp;rft.atitle=Document+Understanding+AI+on+Google+Cloud+%28Cloud+Next+%2719%29+-+YouTube&amp;rft_id=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7dtl650D0y0&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-29\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-29\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFAdministration\" class=\"citation web cs1\">Administration. <a rel=\"nofollow\" class=\"external text\" href=\"https://www.mq.edu.au/research/research-centres-groups-and-facilities/innovative-technologies/centres/centre-for-language-technology-clt\">\"Centre for Language Technology (CLT)\"</a>. <i>Macquarie University</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Macquarie+University&amp;rft.atitle=Centre+for+Language+Technology+%28CLT%29&amp;rft.au=Administration&amp;rft_id=https%3A%2F%2Fwww.mq.edu.au%2Fresearch%2Fresearch-centres-groups-and-facilities%2Finnovative-technologies%2Fcentres%2Fcentre-for-language-technology-clt&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-30\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-30\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.comp.nus.edu.sg/~nlp/conll13st.html\">\"Shared Task: Grammatical Error Correction\"</a>. <i>www.comp.nus.edu.sg</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.comp.nus.edu.sg&amp;rft.atitle=Shared+Task%3A+Grammatical+Error+Correction&amp;rft_id=https%3A%2F%2Fwww.comp.nus.edu.sg%2F~nlp%2Fconll13st.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-31\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-31\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.comp.nus.edu.sg/~nlp/conll14st.html\">\"Shared Task: Grammatical Error Correction\"</a>. <i>www.comp.nus.edu.sg</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.comp.nus.edu.sg&amp;rft.atitle=Shared+Task%3A+Grammatical+Error+Correction&amp;rft_id=https%3A%2F%2Fwww.comp.nus.edu.sg%2F~nlp%2Fconll14st.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-32\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-32\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.grammarly.com/about\">\"About Us | Grammarly\"</a>. <i>www.grammarly.com</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.grammarly.com&amp;rft.atitle=About+Us+%7C+Grammarly&amp;rft_id=https%3A%2F%2Fwww.grammarly.com%2Fabout&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-33\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-33\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFDuanCruz2011\" class=\"citation journal cs1\">Duan, Yucong; Cruz, Christophe (2011). <a rel=\"nofollow\" class=\"external text\" href=\"https://web.archive.org/web/20111009135952/http://www.ijimt.org/abstract/100-E00187.htm\">\"Formalizing Semantic of Natural Language through Conceptualization from Existence\"</a>. <i>International Journal of Innovation, Management and Technology</i>. <b>2</b> (1): 37\\xe2\\x80\\x9342. Archived from <a rel=\"nofollow\" class=\"external text\" href=\"http://www.ijimt.org/abstract/100-E00187.htm\">the original</a> on 2011-10-09.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=International+Journal+of+Innovation%2C+Management+and+Technology&amp;rft.atitle=Formalizing+Semantic+of+Natural+Language+through+Conceptualization+from+Existence&amp;rft.volume=2&amp;rft.issue=1&amp;rft.pages=37-42&amp;rft.date=2011&amp;rft.aulast=Duan&amp;rft.aufirst=Yucong&amp;rft.au=Cruz%2C+Christophe&amp;rft_id=http%3A%2F%2Fwww.ijimt.org%2Fabstract%2F100-E00187.htm&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-34\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-34\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFMittal2011\" class=\"citation journal cs1\">Mittal (2011). <a rel=\"nofollow\" class=\"external text\" href=\"https://hal.archives-ouvertes.fr/hal-01104648/file/Mittal_VersatileQA_IJIIDS.pdf\">\"Versatile question answering systems: seeing in synthesis\"</a> <span class=\"cs1-format\">(PDF)</span>. <i>International Journal of Intelligent Information and Database Systems</i>. <b>5</b> (2): 119\\xe2\\x80\\x93142. <a href=\"/wiki/Doi_(identifier)\" class=\"mw-redirect\" title=\"Doi (identifier)\">doi</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://doi.org/10.1504%2FIJIIDS.2011.038968\">10.1504/IJIIDS.2011.038968</a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=International+Journal+of+Intelligent+Information+and+Database+Systems&amp;rft.atitle=Versatile+question+answering+systems%3A+seeing+in+synthesis&amp;rft.volume=5&amp;rft.issue=2&amp;rft.pages=119-142&amp;rft.date=2011&amp;rft_id=info%3Adoi%2F10.1504%2FIJIIDS.2011.038968&amp;rft.au=Mittal&amp;rft_id=https%3A%2F%2Fhal.archives-ouvertes.fr%2Fhal-01104648%2Ffile%2FMittal_VersatileQA_IJIIDS.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-35\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-35\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.conll.org/previous-tasks\">\"Previous shared tasks | CoNLL\"</a>. <i>www.conll.org</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.conll.org&amp;rft.atitle=Previous+shared+tasks+%7C+CoNLL&amp;rft_id=https%3A%2F%2Fwww.conll.org%2Fprevious-tasks&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-36\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-36\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.lexico.com/definition/cognition\">\"Cognition\"</a>. <i>Lexico</i>. <a href=\"/wiki/Oxford_University_Press\" title=\"Oxford University Press\">Oxford University Press</a> and <a href=\"/wiki/Dictionary.com\" title=\"Dictionary.com\">Dictionary.com</a><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">6 May</span> 2020</span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Lexico&amp;rft.atitle=Cognition&amp;rft_id=https%3A%2F%2Fwww.lexico.com%2Fdefinition%2Fcognition&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-37\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-37\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"http://www.aft.org/newspubs/periodicals/ae/summer2002/willingham.cfm\">\"Ask the Cognitive Scientist\"</a>. <i>American Federation of Teachers</i>. 8 August 2014. <q>Cognitive science is an interdisciplinary field of researchers from Linguistics, psychology, neuroscience, philosophy, computer science, and anthropology that seek to understand the mind.</q></cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=American+Federation+of+Teachers&amp;rft.atitle=Ask+the+Cognitive+Scientist&amp;rft.date=2014-08-08&amp;rft_id=http%3A%2F%2Fwww.aft.org%2Fnewspubs%2Fperiodicals%2Fae%2Fsummer2002%2Fwillingham.cfm&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-38\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-38\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFRobinson2008\" class=\"citation book cs1\">Robinson, Peter (2008). <i>Handbook of Cognitive Linguistics and Second Language Acquisition</i>. Routledge. pp.&#160;3\\xe2\\x80\\x938. <a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-0-805-85352-0\" title=\"Special:BookSources/978-0-805-85352-0\"><bdi>978-0-805-85352-0</bdi></a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Handbook+of+Cognitive+Linguistics+and+Second+Language+Acquisition&amp;rft.pages=3-8&amp;rft.pub=Routledge&amp;rft.date=2008&amp;rft.isbn=978-0-805-85352-0&amp;rft.aulast=Robinson&amp;rft.aufirst=Peter&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-39\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-39\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFLakoff1999\" class=\"citation book cs1\">Lakoff, George (1999). <i>Philosophy in the Flesh: The Embodied Mind and Its Challenge to Western Philosophy; Appendix: The Neural Theory of Language Paradigm</i>. New York Basic Books. pp.&#160;569\\xe2\\x80\\x93583. <a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-0-465-05674-3\" title=\"Special:BookSources/978-0-465-05674-3\"><bdi>978-0-465-05674-3</bdi></a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Philosophy+in+the+Flesh%3A+The+Embodied+Mind+and+Its+Challenge+to+Western+Philosophy%3B+Appendix%3A+The+Neural+Theory+of+Language+Paradigm&amp;rft.pages=569-583&amp;rft.pub=New+York+Basic+Books&amp;rft.date=1999&amp;rft.isbn=978-0-465-05674-3&amp;rft.aulast=Lakoff&amp;rft.aufirst=George&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-40\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-40\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFStrauss1999\" class=\"citation book cs1\">Strauss, Claudia (1999). <i>A Cognitive Theory of Cultural Meaning</i>. Cambridge University Press. pp.&#160;156\\xe2\\x80\\x93164. <a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-0-521-59541-4\" title=\"Special:BookSources/978-0-521-59541-4\"><bdi>978-0-521-59541-4</bdi></a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=A+Cognitive+Theory+of+Cultural+Meaning&amp;rft.pages=156-164&amp;rft.pub=Cambridge+University+Press&amp;rft.date=1999&amp;rft.isbn=978-0-521-59541-4&amp;rft.aulast=Strauss&amp;rft.aufirst=Claudia&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-41\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-41\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://universalconceptualcognitiveannotation.github.io/\">\"Universal Conceptual Cognitive Annotation (UCCA)\"</a>. <i>Universal Conceptual Cognitive Annotation (UCCA)</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Universal+Conceptual+Cognitive+Annotation+%28UCCA%29&amp;rft.atitle=Universal+Conceptual+Cognitive+Annotation+%28UCCA%29&amp;rft_id=https%3A%2F%2Funiversalconceptualcognitiveannotation.github.io%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-42\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-42\">^</a></b></span> <span class=\"reference-text\">Rodr\\xc3\\xadguez, F. C., &amp; Mairal-Us\\xc3\\xb3n, R. (2016). <a rel=\"nofollow\" class=\"external text\" href=\"https://www.redalyc.org/pdf/1345/134549291020.pdf\">Building an RRG computational grammar</a>. <i>Onomazein</i>, (34), 86-117.</span>\\n</li>\\n<li id=\"cite_note-43\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-43\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.fcg-net.org/\">\"Fluid Construction Grammar \\xe2\\x80\\x93 A fully operational processing system for construction grammars\"</a><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=Fluid+Construction+Grammar+%E2%80%93+A+fully+operational+processing+system+for+construction+grammars&amp;rft_id=https%3A%2F%2Fwww.fcg-net.org%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-44\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-44\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.aclweb.org/portal/\">\"ACL Member Portal | The Association for Computational Linguistics Member Portal\"</a>. <i>www.aclweb.org</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.aclweb.org&amp;rft.atitle=ACL+Member+Portal+%7C+The+Association+for+Computational+Linguistics+Member+Portal&amp;rft_id=https%3A%2F%2Fwww.aclweb.org%2Fportal%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-45\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-45\">^</a></b></span> <span class=\"reference-text\"><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite class=\"citation web cs1\"><a rel=\"nofollow\" class=\"external text\" href=\"https://www.w3.org/Data/demos/chunks/chunks.html\">\"Chunks and Rules\"</a>. <i>www.w3.org</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.w3.org&amp;rft.atitle=Chunks+and+Rules&amp;rft_id=https%3A%2F%2Fwww.w3.org%2FData%2Fdemos%2Fchunks%2Fchunks.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></span>\\n</li>\\n<li id=\"cite_note-46\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-46\">^</a></b></span> <span class=\"reference-text\">Socher, R., Karpathy, A., Le, Q. V., Manning, C. D., &amp; Ng, A. Y. (2014). <a rel=\"nofollow\" class=\"external text\" href=\"https://www.mitpressjournals.org/doi/pdfplus/10.1162/tacl_a_00177\">Grounded compositional semantics for finding and describing images with sentences.</a> <i>Transactions of the Association for Computational Linguistics</i>, <i>2</i>, 207-218.</span>\\n</li>\\n</ol></div>\\n<h2><span class=\"mw-headline\" id=\"Further_reading\">Further reading</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=20\" title=\"Edit section: Further reading\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\\n<style data-mw-deduplicate=\"TemplateStyles:r1011217839\">.mw-parser-output .refbegin{font-size:90%;margin-bottom:0.5em}.mw-parser-output .refbegin-hanging-indents>ul{margin-left:0}.mw-parser-output .refbegin-hanging-indents>ul>li{margin-left:0;padding-left:3.2em;text-indent:-3.2em}.mw-parser-output .refbegin-hanging-indents ul,.mw-parser-output .refbegin-hanging-indents ul li{list-style:none}@media(max-width:720px){.mw-parser-output .refbegin-hanging-indents>ul>li{padding-left:1.6em;text-indent:-1.6em}}.mw-parser-output .refbegin-100{font-size:100%}.mw-parser-output .refbegin-columns{margin-top:0.3em}.mw-parser-output .refbegin-columns ul{margin-top:0}.mw-parser-output .refbegin-columns li{page-break-inside:avoid;break-inside:avoid-column}</style><div class=\"refbegin\" style=\"\">\\n<ul><li><link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><cite id=\"CITEREFBates1995\" class=\"citation journal cs1\">Bates, M (1995). <a rel=\"nofollow\" class=\"external text\" href=\"//www.ncbi.nlm.nih.gov/pmc/articles/PMC40721\">\"Models of natural language understanding\"</a>. <i>Proceedings of the National Academy of Sciences of the United States of America</i>. <b>92</b> (22): 9977\\xe2\\x80\\x939982. <a href=\"/wiki/Bibcode_(identifier)\" class=\"mw-redirect\" title=\"Bibcode (identifier)\">Bibcode</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://ui.adsabs.harvard.edu/abs/1995PNAS...92.9977B\">1995PNAS...92.9977B</a>. <a href=\"/wiki/Doi_(identifier)\" class=\"mw-redirect\" title=\"Doi (identifier)\">doi</a>:<a rel=\"nofollow\" class=\"external text\" href=\"https://doi.org/10.1073%2Fpnas.92.22.9977\">10.1073/pnas.92.22.9977</a>. <a href=\"/wiki/PMC_(identifier)\" class=\"mw-redirect\" title=\"PMC (identifier)\">PMC</a>&#160;<span class=\"cs1-lock-free\" title=\"Freely accessible\"><a rel=\"nofollow\" class=\"external text\" href=\"//www.ncbi.nlm.nih.gov/pmc/articles/PMC40721\">40721</a></span>. <a href=\"/wiki/PMID_(identifier)\" class=\"mw-redirect\" title=\"PMID (identifier)\">PMID</a>&#160;<a rel=\"nofollow\" class=\"external text\" href=\"//pubmed.ncbi.nlm.nih.gov/7479812\">7479812</a>.</cite><span title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Proceedings+of+the+National+Academy+of+Sciences+of+the+United+States+of+America&amp;rft.atitle=Models+of+natural+language+understanding&amp;rft.volume=92&amp;rft.issue=22&amp;rft.pages=9977-9982&amp;rft.date=1995&amp;rft_id=%2F%2Fwww.ncbi.nlm.nih.gov%2Fpmc%2Farticles%2FPMC40721%23id-name%3DPMC&amp;rft_id=info%3Apmid%2F7479812&amp;rft_id=info%3Adoi%2F10.1073%2Fpnas.92.22.9977&amp;rft_id=info%3Abibcode%2F1995PNAS...92.9977B&amp;rft.aulast=Bates&amp;rft.aufirst=M&amp;rft_id=%2F%2Fwww.ncbi.nlm.nih.gov%2Fpmc%2Farticles%2FPMC40721&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\" class=\"Z3988\"></span></li>\\n<li>Steven Bird, Ewan Klein, and Edward Loper (2009). <i>Natural Language Processing with Python</i>. O\\'Reilly Media. <link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-0-596-51649-9\" title=\"Special:BookSources/978-0-596-51649-9\">978-0-596-51649-9</a>.</li>\\n<li>Daniel Jurafsky and James H. Martin (2008). <i>Speech and Language Processing</i>, 2nd edition. Pearson Prentice Hall. <link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-0-13-187321-6\" title=\"Special:BookSources/978-0-13-187321-6\">978-0-13-187321-6</a>.</li>\\n<li>Mohamed Zakaria Kurdi (2016). <i>Natural Language Processing and Computational Linguistics: speech, morphology, and syntax</i>, Volume 1. ISTE-Wiley. <link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-1848218482\" title=\"Special:BookSources/978-1848218482\">978-1848218482</a>.</li>\\n<li>Mohamed Zakaria Kurdi (2017). <i>Natural Language Processing and Computational Linguistics: semantics, discourse, and applications</i>, Volume 2. ISTE-Wiley. <link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-1848219212\" title=\"Special:BookSources/978-1848219212\">978-1848219212</a>.</li>\\n<li>Christopher D. Manning, Prabhakar Raghavan, and Hinrich Sch\\xc3\\xbctze (2008). <i>Introduction to Information Retrieval</i>. Cambridge University Press. <link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-0-521-86571-5\" title=\"Special:BookSources/978-0-521-86571-5\">978-0-521-86571-5</a>. <a rel=\"nofollow\" class=\"external text\" href=\"http://nlp.stanford.edu/IR-book/\">Official html and pdf versions available without charge.</a></li>\\n<li>Christopher D. Manning and Hinrich Sch\\xc3\\xbctze (1999). <i>Foundations of Statistical Natural Language Processing</i>. The MIT Press. <link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-0-262-13360-9\" title=\"Special:BookSources/978-0-262-13360-9\">978-0-262-13360-9</a>.</li>\\n<li>David M. W. Powers and Christopher C. R. Turk (1989). <i>Machine Learning of Natural Language</i>. Springer-Verlag. <link rel=\"mw-deduplicated-inline-style\" href=\"mw-data:TemplateStyles:r999302996\"/><a href=\"/wiki/ISBN_(identifier)\" class=\"mw-redirect\" title=\"ISBN (identifier)\">ISBN</a>&#160;<a href=\"/wiki/Special:BookSources/978-0-387-19557-5\" title=\"Special:BookSources/978-0-387-19557-5\">978-0-387-19557-5</a>.</li></ul>\\n</div>\\n<table role=\"presentation\" class=\"mbox-small plainlinks sistersitebox\" style=\"background-color:#f9f9f9;border:1px solid #aaa;color:#000\">\\n<tbody><tr>\\n<td class=\"mbox-image\"><img alt=\"\" src=\"//upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/30px-Commons-logo.svg.png\" decoding=\"async\" width=\"30\" height=\"40\" class=\"noviewer\" srcset=\"//upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/45px-Commons-logo.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/59px-Commons-logo.svg.png 2x\" data-file-width=\"1024\" data-file-height=\"1376\" /></td>\\n<td class=\"mbox-text plainlist\">Wikimedia Commons has media related to <i><b><a href=\"https://commons.wikimedia.org/wiki/Category:Natural_language_processing\" class=\"extiw\" title=\"commons:Category:Natural language processing\">Natural language processing</a></b></i>.</td></tr>\\n</tbody></table>\\n<div role=\"navigation\" class=\"navbox\" aria-labelledby=\"Natural_language_processing\" style=\"padding:3px\"><table class=\"nowraplinks hlist mw-collapsible mw-collapsed navbox-inner\" style=\"border-spacing:0;background:transparent;color:inherit\"><tbody><tr><th scope=\"col\" class=\"navbox-title\" colspan=\"2\"><style data-mw-deduplicate=\"TemplateStyles:r992953826\">.mw-parser-output .navbar{display:inline;font-size:88%;font-weight:normal}.mw-parser-output .navbar-collapse{float:left;text-align:left}.mw-parser-output .navbar-boxtext{word-spacing:0}.mw-parser-output .navbar ul{display:inline-block;white-space:nowrap;line-height:inherit}.mw-parser-output .navbar-brackets::before{margin-right:-0.125em;content:\"[ \"}.mw-parser-output .navbar-brackets::after{margin-left:-0.125em;content:\" ]\"}.mw-parser-output .navbar li{word-spacing:-0.125em}.mw-parser-output .navbar-mini abbr{font-variant:small-caps;border-bottom:none;text-decoration:none;cursor:inherit}.mw-parser-output .navbar-ct-full{font-size:114%;margin:0 7em}.mw-parser-output .navbar-ct-mini{font-size:114%;margin:0 4em}.mw-parser-output .infobox .navbar{font-size:100%}.mw-parser-output .navbox .navbar{display:block;font-size:100%}.mw-parser-output .navbox-title .navbar{float:left;text-align:left;margin-right:0.5em}</style><div class=\"navbar plainlinks hlist navbar-mini\"><ul><li class=\"nv-view\"><a href=\"/wiki/Template:Natural_language_processing\" title=\"Template:Natural language processing\"><abbr title=\"View this template\" style=\";;background:none transparent;border:none;box-shadow:none;padding:0;\">v</abbr></a></li><li class=\"nv-talk\"><a href=\"/wiki/Template_talk:Natural_language_processing\" title=\"Template talk:Natural language processing\"><abbr title=\"Discuss this template\" style=\";;background:none transparent;border:none;box-shadow:none;padding:0;\">t</abbr></a></li><li class=\"nv-edit\"><a class=\"external text\" href=\"https://en.wikipedia.org/w/index.php?title=Template:Natural_language_processing&amp;action=edit\"><abbr title=\"Edit this template\" style=\";;background:none transparent;border:none;box-shadow:none;padding:0;\">e</abbr></a></li></ul></div><div id=\"Natural_language_processing\" style=\"font-size:114%;margin:0 4em\"><a class=\"mw-selflink selflink\">Natural language processing</a></div></th></tr><tr><th scope=\"row\" class=\"navbox-group\" style=\"width:1%\">General terms</th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><a href=\"/wiki/AI-complete\" title=\"AI-complete\">AI-complete</a></li>\\n<li><a href=\"/wiki/Bag-of-words_model\" title=\"Bag-of-words model\">Bag-of-words</a></li>\\n<li><a href=\"/wiki/N-gram\" title=\"N-gram\">n-gram</a>\\n<ul><li><a href=\"/wiki/Bigram\" title=\"Bigram\">Bigram</a></li>\\n<li><a href=\"/wiki/Trigram\" title=\"Trigram\">Trigram</a></li></ul></li>\\n<li><a href=\"/wiki/Natural_language_understanding\" class=\"mw-redirect\" title=\"Natural language understanding\">Natural language understanding</a></li>\\n<li><a href=\"/wiki/Speech_corpus\" title=\"Speech corpus\">Speech corpus</a></li>\\n<li><a href=\"/wiki/Stop_words\" class=\"mw-redirect\" title=\"Stop words\">Stopwords</a></li>\\n<li><a href=\"/wiki/Text_corpus\" title=\"Text corpus\">Text corpus</a></li></ul>\\n</div></td></tr><tr><th scope=\"row\" class=\"navbox-group\" style=\"width:1%\"><a href=\"/wiki/Text_mining\" title=\"Text mining\">Text analysis</a></th><td class=\"navbox-list navbox-even\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><a href=\"/wiki/Collocation_extraction\" title=\"Collocation extraction\">Collocation extraction</a></li>\\n<li><a href=\"/wiki/Concept_mining\" title=\"Concept mining\">Concept mining</a></li>\\n<li><a href=\"/wiki/Compound_term_processing\" class=\"mw-redirect\" title=\"Compound term processing\">Compound term processing</a></li>\\n<li><a href=\"/wiki/Coreference#Coreference_resolution\" title=\"Coreference\">Coreference resolution</a></li>\\n<li><a href=\"/wiki/Lemmatisation\" title=\"Lemmatisation\">Lemmatisation</a></li>\\n<li><a href=\"/wiki/Named-entity_recognition\" title=\"Named-entity recognition\">Named-entity recognition</a></li>\\n<li><a href=\"/wiki/Ontology_learning\" title=\"Ontology learning\">Ontology learning</a></li>\\n<li><a href=\"/wiki/Parsing\" title=\"Parsing\">Parsing</a></li>\\n<li><a href=\"/wiki/Part-of-speech_tagging\" title=\"Part-of-speech tagging\">Part-of-speech tagging</a></li>\\n<li><a href=\"/wiki/Semantic_similarity\" title=\"Semantic similarity\">Semantic similarity</a></li>\\n<li><a href=\"/wiki/Sentiment_analysis\" title=\"Sentiment analysis\">Sentiment analysis</a></li>\\n<li><a href=\"/wiki/Stemming\" title=\"Stemming\">Stemming</a></li>\\n<li><a href=\"/wiki/Terminology_extraction\" title=\"Terminology extraction\">Terminology extraction</a></li>\\n<li><a href=\"/wiki/Shallow_parsing\" title=\"Shallow parsing\">Text chunking</a></li>\\n<li><a href=\"/wiki/Text_segmentation\" title=\"Text segmentation\">Text segmentation</a>\\n<ul><li><a href=\"/wiki/Sentence_boundary_disambiguation\" title=\"Sentence boundary disambiguation\">Sentence segmentation</a></li>\\n<li><a href=\"/wiki/Word#Word_boundaries\" title=\"Word\">Word segmentation</a></li></ul></li>\\n<li><a href=\"/wiki/Textual_entailment\" title=\"Textual entailment\">Textual entailment</a></li>\\n<li><a href=\"/wiki/Truecasing\" title=\"Truecasing\">Truecasing</a></li>\\n<li><a href=\"/wiki/Word-sense_disambiguation\" title=\"Word-sense disambiguation\">Word-sense disambiguation</a></li></ul>\\n</div></td></tr><tr><th scope=\"row\" class=\"navbox-group\" style=\"width:1%\"><a href=\"/wiki/Automatic_summarization\" title=\"Automatic summarization\">Automatic summarization</a></th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><a href=\"/wiki/Multi-document_summarization\" title=\"Multi-document summarization\">Multi-document summarization</a></li>\\n<li><a href=\"/wiki/Sentence_extraction\" title=\"Sentence extraction\">Sentence extraction</a></li>\\n<li><a href=\"/wiki/Text_simplification\" title=\"Text simplification\">Text simplification</a></li></ul>\\n</div></td></tr><tr><th scope=\"row\" class=\"navbox-group\" style=\"width:1%\"><a href=\"/wiki/Machine_translation\" title=\"Machine translation\">Machine translation</a></th><td class=\"navbox-list navbox-even\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><a href=\"/wiki/Computer-assisted_translation\" title=\"Computer-assisted translation\">Computer-assisted</a></li>\\n<li><a href=\"/wiki/Example-based_machine_translation\" title=\"Example-based machine translation\">Example-based</a></li>\\n<li><a href=\"/wiki/Rule-based_machine_translation\" title=\"Rule-based machine translation\">Rule-based</a></li>\\n<li><a href=\"/wiki/Neural_machine_translation\" title=\"Neural machine translation\">Neural</a></li></ul>\\n</div></td></tr><tr><th scope=\"row\" class=\"navbox-group\" style=\"width:1%\"><a href=\"/wiki/Automatic_identification_and_data_capture\" title=\"Automatic identification and data capture\">Automatic identification<br />and data capture</a></th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">Speech recognition</a></li>\\n<li><a href=\"/wiki/Speech_segmentation\" title=\"Speech segmentation\">Speech segmentation</a></li>\\n<li><a href=\"/wiki/Speech_synthesis\" title=\"Speech synthesis\">Speech synthesis</a></li>\\n<li><a href=\"/wiki/Natural_language_generation\" class=\"mw-redirect\" title=\"Natural language generation\">Natural language generation</a></li>\\n<li><a href=\"/wiki/Optical_character_recognition\" title=\"Optical character recognition\">Optical character recognition</a></li></ul>\\n</div></td></tr><tr><th scope=\"row\" class=\"navbox-group\" style=\"width:1%\"><a href=\"/wiki/Topic_model\" title=\"Topic model\">Topic model</a></th><td class=\"navbox-list navbox-even\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><a href=\"/wiki/Latent_Dirichlet_allocation\" title=\"Latent Dirichlet allocation\">Latent Dirichlet allocation</a></li>\\n<li><a href=\"/wiki/Latent_semantic_analysis\" title=\"Latent semantic analysis\">Latent semantic analysis</a></li>\\n<li><a href=\"/wiki/Pachinko_allocation\" title=\"Pachinko allocation\">Pachinko allocation</a></li></ul>\\n</div></td></tr><tr><th scope=\"row\" class=\"navbox-group\" style=\"width:1%\"><a href=\"/wiki/Computer-assisted_reviewing\" title=\"Computer-assisted reviewing\">Computer-assisted<br />reviewing</a></th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><a href=\"/wiki/Automated_essay_scoring\" title=\"Automated essay scoring\">Automated essay scoring</a></li>\\n<li><a href=\"/wiki/Concordancer\" title=\"Concordancer\">Concordancer</a></li>\\n<li><a href=\"/wiki/Grammar_checker\" title=\"Grammar checker\">Grammar checker</a></li>\\n<li><a href=\"/wiki/Predictive_text\" title=\"Predictive text\">Predictive text</a></li>\\n<li><a href=\"/wiki/Spell_checker\" title=\"Spell checker\">Spell checker</a></li>\\n<li><a href=\"/wiki/Syntax_guessing\" title=\"Syntax guessing\">Syntax guessing</a></li></ul>\\n</div></td></tr><tr><th scope=\"row\" class=\"navbox-group\" style=\"width:1%\"><a href=\"/wiki/Natural_language_user_interface\" class=\"mw-redirect\" title=\"Natural language user interface\">Natural language<br />user interface</a></th><td class=\"navbox-list navbox-even\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><a href=\"/wiki/Chatbot\" title=\"Chatbot\">Chatbot</a></li>\\n<li><a href=\"/wiki/Interactive_fiction\" title=\"Interactive fiction\">Interactive fiction</a></li>\\n<li><a href=\"/wiki/Question_answering\" title=\"Question answering\">Question answering</a></li>\\n<li><a href=\"/wiki/Virtual_assistant\" title=\"Virtual assistant\">Virtual assistant</a></li>\\n<li><a href=\"/wiki/Voice_user_interface\" title=\"Voice user interface\">Voice user interface</a></li></ul>\\n</div></td></tr></tbody></table></div>\\n<div role=\"navigation\" class=\"navbox authority-control\" aria-labelledby=\"Authority_control_frameless_&amp;#124;text-top_&amp;#124;10px_&amp;#124;alt=Edit_this_at_Wikidata_&amp;#124;link=https&amp;#58;//www.wikidata.org/wiki/Q30642#identifiers&amp;#124;Edit_this_at_Wikidata\" style=\"padding:3px\"><table class=\"nowraplinks hlist navbox-inner\" style=\"border-spacing:0;background:transparent;color:inherit\"><tbody><tr><th id=\"Authority_control_frameless_&amp;#124;text-top_&amp;#124;10px_&amp;#124;alt=Edit_this_at_Wikidata_&amp;#124;link=https&amp;#58;//www.wikidata.org/wiki/Q30642#identifiers&amp;#124;Edit_this_at_Wikidata\" scope=\"row\" class=\"navbox-group\" style=\"width:1%\"><a href=\"/wiki/Help:Authority_control\" title=\"Help:Authority control\">Authority control</a> <a href=\"https://www.wikidata.org/wiki/Q30642#identifiers\" title=\"Edit this at Wikidata\"><img alt=\"Edit this at Wikidata\" src=\"//upload.wikimedia.org/wikipedia/en/thumb/8/8a/OOjs_UI_icon_edit-ltr-progressive.svg/10px-OOjs_UI_icon_edit-ltr-progressive.svg.png\" decoding=\"async\" width=\"10\" height=\"10\" style=\"vertical-align: text-top\" srcset=\"//upload.wikimedia.org/wikipedia/en/thumb/8/8a/OOjs_UI_icon_edit-ltr-progressive.svg/15px-OOjs_UI_icon_edit-ltr-progressive.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/8/8a/OOjs_UI_icon_edit-ltr-progressive.svg/20px-OOjs_UI_icon_edit-ltr-progressive.svg.png 2x\" data-file-width=\"20\" data-file-height=\"20\" /></a></th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\\n<ul><li><span class=\"nowrap\"><a href=\"/wiki/LCCN_(identifier)\" class=\"mw-redirect\" title=\"LCCN (identifier)\">LCCN</a>: <span class=\"uid\"><a rel=\"nofollow\" class=\"external text\" href=\"https://id.loc.gov/authorities/subjects/sh88002425\">sh88002425</a></span></span></li>\\n<li><span class=\"nowrap\"><a href=\"/wiki/NDL_(identifier)\" class=\"mw-redirect\" title=\"NDL (identifier)\">NDL</a>: <span class=\"uid\"><a rel=\"nofollow\" class=\"external text\" href=\"https://id.ndl.go.jp/auth/ndlna/00562347\">00562347</a></span></span></li></ul>\\n</div></td></tr></tbody></table></div>\\n<div class=\"noprint metadata navbox\" role=\"navigation\" aria-label=\"Portals\" style=\"font-weight:bold;padding:0.4em 2em\"><ul style=\"margin:0.1em 0 0\"><li style=\"display:inline\"><span style=\"display:inline-block;white-space:nowrap\"><span style=\"margin:0 0.5em\"><a href=\"/wiki/File:Globe_of_letters.svg\" class=\"image\"><img alt=\"Globe of letters.svg\" src=\"//upload.wikimedia.org/wikipedia/commons/thumb/d/de/Globe_of_letters.svg/21px-Globe_of_letters.svg.png\" decoding=\"async\" width=\"21\" height=\"21\" srcset=\"//upload.wikimedia.org/wikipedia/commons/thumb/d/de/Globe_of_letters.svg/32px-Globe_of_letters.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/d/de/Globe_of_letters.svg/42px-Globe_of_letters.svg.png 2x\" data-file-width=\"512\" data-file-height=\"512\" /></a></span><a href=\"/wiki/Portal:Language\" title=\"Portal:Language\">Language portal</a></span></li></ul></div>\\n<!-- \\nNewPP limit report\\nParsed by mw1267\\nCached time: 20210414012917\\nCache expiry: 2592000\\nDynamic content: false\\nComplications: [vary\\xe2\\x80\\x90revision\\xe2\\x80\\x90sha1]\\nCPU time usage: 1.005 seconds\\nReal time usage: 1.382 seconds\\nPreprocessor visited node count: 4406/1000000\\nPost\\xe2\\x80\\x90expand include size: 98406/2097152 bytes\\nTemplate argument size: 5151/2097152 bytes\\nHighest expansion depth: 14/40\\nExpensive parser function count: 3/500\\nUnstrip recursion depth: 1/20\\nUnstrip post\\xe2\\x80\\x90expand size: 142685/5000000 bytes\\nLua time usage: 0.495/10.000 seconds\\nLua memory usage: 6443714/52428800 bytes\\nNumber of Wikibase entities loaded: 1/400\\n-->\\n<!--\\nTransclusion expansion time report (%,ms,calls,template)\\n100.00% 1144.153 1 -total\\n 44.83% 512.908 1 Template:Reflist\\n 11.76% 134.511 7 Template:ISBN\\n 11.63% 133.094 1 Template:Cite_conference\\n 10.19% 116.587 18 Template:Cite_web\\n 8.53% 97.569 1 Template:Short_description\\n 7.23% 82.697 10 Template:Cite_journal\\n 5.15% 58.934 1 Template:Natural_Language_Processing\\n 5.01% 57.293 1 Template:Self-published_source\\n 4.76% 54.473 1 Template:Authority_control\\n-->\\n\\n<!-- Saved in parser cache with key enwiki:pcache:idhash:21652-0!canonical!math=5 and timestamp 20210414012916 and revision id 1016426461. Serialized with JSON.\\n -->\\n</div><noscript><img src=\"//en.wikipedia.org/wiki/Special:CentralAutoLogin/start?type=1x1\" alt=\"\" title=\"\" width=\"1\" height=\"1\" style=\"border: none; position: absolute;\" /></noscript>\\n<div class=\"printfooter\">Retrieved from \"<a dir=\"ltr\" href=\"https://en.wikipedia.org/w/index.php?title=Natural_language_processing&amp;oldid=1016426461\">https://en.wikipedia.org/w/index.php?title=Natural_language_processing&amp;oldid=1016426461</a>\"</div></div>\\n\\t\\t<div id=\"catlinks\" class=\"catlinks\" data-mw=\"interface\"><div id=\"mw-normal-catlinks\" class=\"mw-normal-catlinks\"><a href=\"/wiki/Help:Category\" title=\"Help:Category\">Categories</a>: <ul><li><a href=\"/wiki/Category:Natural_language_processing\" title=\"Category:Natural language processing\">Natural language processing</a></li><li><a href=\"/wiki/Category:Computational_linguistics\" title=\"Category:Computational linguistics\">Computational linguistics</a></li><li><a href=\"/wiki/Category:Speech_recognition\" title=\"Category:Speech recognition\">Speech recognition</a></li><li><a href=\"/wiki/Category:Computational_fields_of_study\" title=\"Category:Computational fields of study\">Computational fields of study</a></li><li><a href=\"/wiki/Category:Artificial_intelligence\" title=\"Category:Artificial intelligence\">Artificial intelligence</a></li></ul></div><div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks mw-hidden-cats-hidden\">Hidden categories: <ul><li><a href=\"/wiki/Category:CS1_maint:_location\" title=\"Category:CS1 maint: location\">CS1 maint: location</a></li><li><a href=\"/wiki/Category:Articles_with_short_description\" title=\"Category:Articles with short description\">Articles with short description</a></li><li><a href=\"/wiki/Category:Short_description_matches_Wikidata\" title=\"Category:Short description matches Wikidata\">Short description matches Wikidata</a></li><li><a href=\"/wiki/Category:Commons_link_from_Wikidata\" title=\"Category:Commons link from Wikidata\">Commons link from Wikidata</a></li><li><a href=\"/wiki/Category:Wikipedia_articles_with_LCCN_identifiers\" title=\"Category:Wikipedia articles with LCCN identifiers\">Wikipedia articles with LCCN identifiers</a></li><li><a href=\"/wiki/Category:Wikipedia_articles_with_NDL_identifiers\" title=\"Category:Wikipedia articles with NDL identifiers\">Wikipedia articles with NDL identifiers</a></li></ul></div></div>\\n\\t</div>\\n</div>\\n<div id=\\'mw-data-after-content\\'>\\n\\t<div class=\"read-more-container\"></div>\\n</div>\\n\\n<div id=\"mw-navigation\">\\n\\t<h2>Navigation menu</h2>\\n\\t<div id=\"mw-head\">\\n\\t\\t<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-personal\" class=\"mw-portlet mw-portlet-personal vector-menu\" aria-labelledby=\"p-personal-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-personal-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Personal tools</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li id=\"pt-anonuserpage\">Not logged in</li><li id=\"pt-anontalk\"><a href=\"/wiki/Special:MyTalk\" title=\"Discussion about edits from this IP address [n]\" accesskey=\"n\">Talk</a></li><li id=\"pt-anoncontribs\"><a href=\"/wiki/Special:MyContributions\" title=\"A list of edits made from this IP address [y]\" accesskey=\"y\">Contributions</a></li><li id=\"pt-createaccount\"><a href=\"/w/index.php?title=Special:CreateAccount&amp;returnto=Natural+language+processing\" title=\"You are encouraged to create an account and log in; however, it is not mandatory\">Create account</a></li><li id=\"pt-login\"><a href=\"/w/index.php?title=Special:UserLogin&amp;returnto=Natural+language+processing\" title=\"You&#039;re encouraged to log in; however, it&#039;s not mandatory. [o]\" accesskey=\"o\">Log in</a></li></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n\\n\\t\\t<div id=\"left-navigation\">\\n\\t\\t\\t<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-namespaces\" class=\"mw-portlet mw-portlet-namespaces vector-menu vector-menu-tabs\" aria-labelledby=\"p-namespaces-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-namespaces-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Namespaces</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li id=\"ca-nstab-main\" class=\"selected\"><a href=\"/wiki/Natural_language_processing\" title=\"View the content page [c]\" accesskey=\"c\">Article</a></li><li id=\"ca-talk\"><a href=\"/wiki/Talk:Natural_language_processing\" rel=\"discussion\" title=\"Discuss improvements to the content page [t]\" accesskey=\"t\">Talk</a></li></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n\\n\\t\\t\\t<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-variants\" class=\"mw-portlet mw-portlet-variants emptyPortlet vector-menu vector-menu-dropdown\" aria-labelledby=\"p-variants-label\" role=\"navigation\" \\n\\t >\\n\\t<input type=\"checkbox\" class=\"vector-menu-checkbox\" aria-labelledby=\"p-variants-label\" />\\n\\t<h3 id=\"p-variants-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Variants</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n\\n\\t\\t</div>\\n\\t\\t<div id=\"right-navigation\">\\n\\t\\t\\t<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-views\" class=\"mw-portlet mw-portlet-views vector-menu vector-menu-tabs\" aria-labelledby=\"p-views-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-views-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Views</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li id=\"ca-view\" class=\"selected\"><a href=\"/wiki/Natural_language_processing\">Read</a></li><li id=\"ca-edit\"><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit\" title=\"Edit this page [e]\" accesskey=\"e\">Edit</a></li><li id=\"ca-history\"><a href=\"/w/index.php?title=Natural_language_processing&amp;action=history\" title=\"Past revisions of this page [h]\" accesskey=\"h\">View history</a></li></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n\\n\\t\\t\\t<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-cactions\" class=\"mw-portlet mw-portlet-cactions emptyPortlet vector-menu vector-menu-dropdown\" aria-labelledby=\"p-cactions-label\" role=\"navigation\" \\n\\t >\\n\\t<input type=\"checkbox\" class=\"vector-menu-checkbox\" aria-labelledby=\"p-cactions-label\" />\\n\\t<h3 id=\"p-cactions-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>More</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n\\n\\t\\t\\t<div id=\"p-search\" role=\"search\" >\\n\\t<h3 >\\n\\t\\t<label for=\"searchInput\">Search</label>\\n\\t</h3>\\n\\t<form action=\"/w/index.php\" id=\"searchform\">\\n\\t\\t<div id=\"simpleSearch\" data-search-loc=\"header-navigation\">\\n\\t\\t\\t<input type=\"search\" name=\"search\" placeholder=\"Search Wikipedia\" autocapitalize=\"sentences\" title=\"Search Wikipedia [f]\" accesskey=\"f\" id=\"searchInput\"/>\\n\\t\\t\\t<input type=\"hidden\" name=\"title\" value=\"Special:Search\"/>\\n\\t\\t\\t<input type=\"submit\" name=\"fulltext\" value=\"Search\" title=\"Search Wikipedia for this text\" id=\"mw-searchButton\" class=\"searchButton mw-fallbackSearchButton\"/>\\n\\t\\t\\t<input type=\"submit\" name=\"go\" value=\"Go\" title=\"Go to a page with this exact name if it exists\" id=\"searchButton\" class=\"searchButton\"/>\\n\\t\\t</div>\\n\\t</form>\\n</div>\\n\\n\\t\\t</div>\\n\\t</div>\\n\\t\\n<div id=\"mw-panel\">\\n\\t<div id=\"p-logo\" role=\"banner\">\\n\\t\\t<a class=\"mw-wiki-logo\" href=\"/wiki/Main_Page\"\\n\\t\\t\\ttitle=\"Visit the main page\"></a>\\n\\t</div>\\n\\t<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-navigation\" class=\"mw-portlet mw-portlet-navigation vector-menu vector-menu-portal portal\" aria-labelledby=\"p-navigation-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-navigation-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Navigation</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li id=\"n-mainpage-description\"><a href=\"/wiki/Main_Page\" title=\"Visit the main page [z]\" accesskey=\"z\">Main page</a></li><li id=\"n-contents\"><a href=\"/wiki/Wikipedia:Contents\" title=\"Guides to browsing Wikipedia\">Contents</a></li><li id=\"n-currentevents\"><a href=\"/wiki/Portal:Current_events\" title=\"Articles related to current events\">Current events</a></li><li id=\"n-randompage\"><a href=\"/wiki/Special:Random\" title=\"Visit a randomly selected article [x]\" accesskey=\"x\">Random article</a></li><li id=\"n-aboutsite\"><a href=\"/wiki/Wikipedia:About\" title=\"Learn about Wikipedia and how it works\">About Wikipedia</a></li><li id=\"n-contactpage\"><a href=\"//en.wikipedia.org/wiki/Wikipedia:Contact_us\" title=\"How to contact Wikipedia\">Contact us</a></li><li id=\"n-sitesupport\"><a href=\"https://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&amp;utm_medium=sidebar&amp;utm_campaign=C13_en.wikipedia.org&amp;uselang=en\" title=\"Support us by donating to the Wikimedia Foundation\">Donate</a></li></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n\\n\\t<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-interaction\" class=\"mw-portlet mw-portlet-interaction vector-menu vector-menu-portal portal\" aria-labelledby=\"p-interaction-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-interaction-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Contribute</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li id=\"n-help\"><a href=\"/wiki/Help:Contents\" title=\"Guidance on how to use and edit Wikipedia\">Help</a></li><li id=\"n-introduction\"><a href=\"/wiki/Help:Introduction\" title=\"Learn how to edit Wikipedia\">Learn to edit</a></li><li id=\"n-portal\"><a href=\"/wiki/Wikipedia:Community_portal\" title=\"The hub for editors\">Community portal</a></li><li id=\"n-recentchanges\"><a href=\"/wiki/Special:RecentChanges\" title=\"A list of recent changes to Wikipedia [r]\" accesskey=\"r\">Recent changes</a></li><li id=\"n-upload\"><a href=\"/wiki/Wikipedia:File_Upload_Wizard\" title=\"Add images or other media for use on Wikipedia\">Upload file</a></li></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-tb\" class=\"mw-portlet mw-portlet-tb vector-menu vector-menu-portal portal\" aria-labelledby=\"p-tb-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-tb-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Tools</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li id=\"t-whatlinkshere\"><a href=\"/wiki/Special:WhatLinksHere/Natural_language_processing\" title=\"List of all English Wikipedia pages containing links to this page [j]\" accesskey=\"j\">What links here</a></li><li id=\"t-recentchangeslinked\"><a href=\"/wiki/Special:RecentChangesLinked/Natural_language_processing\" rel=\"nofollow\" title=\"Recent changes in pages linked from this page [k]\" accesskey=\"k\">Related changes</a></li><li id=\"t-upload\"><a href=\"/wiki/Wikipedia:File_Upload_Wizard\" title=\"Upload files [u]\" accesskey=\"u\">Upload file</a></li><li id=\"t-specialpages\"><a href=\"/wiki/Special:SpecialPages\" title=\"A list of all special pages [q]\" accesskey=\"q\">Special pages</a></li><li id=\"t-permalink\"><a href=\"/w/index.php?title=Natural_language_processing&amp;oldid=1016426461\" title=\"Permanent link to this revision of this page\">Permanent link</a></li><li id=\"t-info\"><a href=\"/w/index.php?title=Natural_language_processing&amp;action=info\" title=\"More information about this page\">Page information</a></li><li id=\"t-cite\"><a href=\"/w/index.php?title=Special:CiteThisPage&amp;page=Natural_language_processing&amp;id=1016426461&amp;wpFormIdentifier=titleform\" title=\"Information on how to cite this page\">Cite this page</a></li><li id=\"t-wikibase\"><a href=\"https://www.wikidata.org/wiki/Special:EntityPage/Q30642\" title=\"Structured data on this page hosted by Wikidata [g]\" accesskey=\"g\">Wikidata item</a></li></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-coll-print_export\" class=\"mw-portlet mw-portlet-coll-print_export vector-menu vector-menu-portal portal\" aria-labelledby=\"p-coll-print_export-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-coll-print_export-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Print/export</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li id=\"coll-download-as-rl\"><a href=\"/w/index.php?title=Special:DownloadAsPdf&amp;page=Natural_language_processing&amp;action=show-download-screen\" title=\"Download this page as a PDF file\">Download as PDF</a></li><li id=\"t-print\"><a href=\"/w/index.php?title=Natural_language_processing&amp;printable=yes\" title=\"Printable version of this page [p]\" accesskey=\"p\">Printable version</a></li></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-wikibase-otherprojects\" class=\"mw-portlet mw-portlet-wikibase-otherprojects vector-menu vector-menu-portal portal\" aria-labelledby=\"p-wikibase-otherprojects-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-wikibase-otherprojects-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>In other projects</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li class=\"wb-otherproject-link wb-otherproject-commons\"><a href=\"https://commons.wikimedia.org/wiki/Category:Natural_language_processing\" hreflang=\"en\">Wikimedia Commons</a></li></ul>\\n\\t\\t\\n\\t</div>\\n</nav>\\n\\n\\t<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\\n<nav id=\"p-lang\" class=\"mw-portlet mw-portlet-lang vector-menu vector-menu-portal portal\" aria-labelledby=\"p-lang-label\" role=\"navigation\" \\n\\t >\\n\\t<h3 id=\"p-lang-label\" class=\"vector-menu-heading\">\\n\\t\\t<span>Languages</span>\\n\\t</h3>\\n\\t<div class=\"vector-menu-content\">\\n\\t\\t<ul class=\"vector-menu-content-list\"><li class=\"interlanguage-link interwiki-af\"><a href=\"https://af.wikipedia.org/wiki/Natuurliketaalverwerking\" title=\"Natuurliketaalverwerking \\xe2\\x80\\x93 Afrikaans\" lang=\"af\" hreflang=\"af\" class=\"interlanguage-link-target\">Afrikaans</a></li><li class=\"interlanguage-link interwiki-ar\"><a href=\"https://ar.wikipedia.org/wiki/%D9%85%D8%B9%D8%A7%D9%84%D8%AC%D8%A9_%D8%A7%D9%84%D9%84%D8%BA%D8%A7%D8%AA_%D8%A7%D9%84%D8%B7%D8%A8%D9%8A%D8%B9%D9%8A%D8%A9\" title=\"\\xd9\\x85\\xd8\\xb9\\xd8\\xa7\\xd9\\x84\\xd8\\xac\\xd8\\xa9 \\xd8\\xa7\\xd9\\x84\\xd9\\x84\\xd8\\xba\\xd8\\xa7\\xd8\\xaa \\xd8\\xa7\\xd9\\x84\\xd8\\xb7\\xd8\\xa8\\xd9\\x8a\\xd8\\xb9\\xd9\\x8a\\xd8\\xa9 \\xe2\\x80\\x93 Arabic\" lang=\"ar\" hreflang=\"ar\" class=\"interlanguage-link-target\">\\xd8\\xa7\\xd9\\x84\\xd8\\xb9\\xd8\\xb1\\xd8\\xa8\\xd9\\x8a\\xd8\\xa9</a></li><li class=\"interlanguage-link interwiki-az\"><a href=\"https://az.wikipedia.org/wiki/T%C9%99bii_dilin_emal%C4%B1\" title=\"T\\xc9\\x99bii dilin emal\\xc4\\xb1 \\xe2\\x80\\x93 Azerbaijani\" lang=\"az\" hreflang=\"az\" class=\"interlanguage-link-target\">Az\\xc9\\x99rbaycanca</a></li><li class=\"interlanguage-link interwiki-bn\"><a href=\"https://bn.wikipedia.org/wiki/%E0%A6%B8%E0%A7%8D%E0%A6%AC%E0%A6%BE%E0%A6%AD%E0%A6%BE%E0%A6%AC%E0%A6%BF%E0%A6%95_%E0%A6%AD%E0%A6%BE%E0%A6%B7%E0%A6%BE_%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A6%95%E0%A7%8D%E0%A6%B0%E0%A6%BF%E0%A6%AF%E0%A6%BC%E0%A6%BE%E0%A6%9C%E0%A6%BE%E0%A6%A4%E0%A6%95%E0%A6%B0%E0%A6%A3\" title=\"\\xe0\\xa6\\xb8\\xe0\\xa7\\x8d\\xe0\\xa6\\xac\\xe0\\xa6\\xbe\\xe0\\xa6\\xad\\xe0\\xa6\\xbe\\xe0\\xa6\\xac\\xe0\\xa6\\xbf\\xe0\\xa6\\x95 \\xe0\\xa6\\xad\\xe0\\xa6\\xbe\\xe0\\xa6\\xb7\\xe0\\xa6\\xbe \\xe0\\xa6\\xaa\\xe0\\xa7\\x8d\\xe0\\xa6\\xb0\\xe0\\xa6\\x95\\xe0\\xa7\\x8d\\xe0\\xa6\\xb0\\xe0\\xa6\\xbf\\xe0\\xa6\\xaf\\xe0\\xa6\\xbc\\xe0\\xa6\\xbe\\xe0\\xa6\\x9c\\xe0\\xa6\\xbe\\xe0\\xa6\\xa4\\xe0\\xa6\\x95\\xe0\\xa6\\xb0\\xe0\\xa6\\xa3 \\xe2\\x80\\x93 Bangla\" lang=\"bn\" hreflang=\"bn\" class=\"interlanguage-link-target\">\\xe0\\xa6\\xac\\xe0\\xa6\\xbe\\xe0\\xa6\\x82\\xe0\\xa6\\xb2\\xe0\\xa6\\xbe</a></li><li class=\"interlanguage-link interwiki-zh-min-nan\"><a href=\"https://zh-min-nan.wikipedia.org/wiki/Ch%C5%AB-ji%C3%A2n_gi%C3%A2n-g%C3%BA_chh%C3%BA-l%C3%AD\" title=\"Ch\\xc5\\xab-ji\\xc3\\xa2n gi\\xc3\\xa2n-g\\xc3\\xba chh\\xc3\\xba-l\\xc3\\xad \\xe2\\x80\\x93 Chinese (Min Nan)\" lang=\"nan\" hreflang=\"nan\" class=\"interlanguage-link-target\">B\\xc3\\xa2n-l\\xc3\\xa2m-g\\xc3\\xba</a></li><li class=\"interlanguage-link interwiki-be\"><a href=\"https://be.wikipedia.org/wiki/%D0%90%D0%BF%D1%80%D0%B0%D1%86%D0%BE%D1%9E%D0%BA%D0%B0_%D0%BD%D0%B0%D1%82%D1%83%D1%80%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D0%B9_%D0%BC%D0%BE%D0%B2%D1%8B\" title=\"\\xd0\\x90\\xd0\\xbf\\xd1\\x80\\xd0\\xb0\\xd1\\x86\\xd0\\xbe\\xd1\\x9e\\xd0\\xba\\xd0\\xb0 \\xd0\\xbd\\xd0\\xb0\\xd1\\x82\\xd1\\x83\\xd1\\x80\\xd0\\xb0\\xd0\\xbb\\xd1\\x8c\\xd0\\xbd\\xd0\\xb0\\xd0\\xb9 \\xd0\\xbc\\xd0\\xbe\\xd0\\xb2\\xd1\\x8b \\xe2\\x80\\x93 Belarusian\" lang=\"be\" hreflang=\"be\" class=\"interlanguage-link-target\">\\xd0\\x91\\xd0\\xb5\\xd0\\xbb\\xd0\\xb0\\xd1\\x80\\xd1\\x83\\xd1\\x81\\xd0\\xba\\xd0\\xb0\\xd1\\x8f</a></li><li class=\"interlanguage-link interwiki-be-x-old\"><a href=\"https://be-tarask.wikipedia.org/wiki/%D0%90%D0%BF%D1%80%D0%B0%D1%86%D0%BE%D1%9E%D0%BA%D0%B0_%D0%BD%D0%B0%D1%82%D1%83%D1%80%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D0%B9_%D0%BC%D0%BE%D0%B2%D1%8B\" title=\"\\xd0\\x90\\xd0\\xbf\\xd1\\x80\\xd0\\xb0\\xd1\\x86\\xd0\\xbe\\xd1\\x9e\\xd0\\xba\\xd0\\xb0 \\xd0\\xbd\\xd0\\xb0\\xd1\\x82\\xd1\\x83\\xd1\\x80\\xd0\\xb0\\xd0\\xbb\\xd1\\x8c\\xd0\\xbd\\xd0\\xb0\\xd0\\xb9 \\xd0\\xbc\\xd0\\xbe\\xd0\\xb2\\xd1\\x8b \\xe2\\x80\\x93 Belarusian (Tara\\xc5\\xa1kievica orthography)\" lang=\"be-tarask\" hreflang=\"be-tarask\" class=\"interlanguage-link-target\">\\xd0\\x91\\xd0\\xb5\\xd0\\xbb\\xd0\\xb0\\xd1\\x80\\xd1\\x83\\xd1\\x81\\xd0\\xba\\xd0\\xb0\\xd1\\x8f (\\xd1\\x82\\xd0\\xb0\\xd1\\x80\\xd0\\xb0\\xd1\\x88\\xd0\\xba\\xd0\\xb5\\xd0\\xb2\\xd1\\x96\\xd1\\x86\\xd0\\xb0)\\xe2\\x80\\x8e</a></li><li class=\"interlanguage-link interwiki-bg\"><a href=\"https://bg.wikipedia.org/wiki/%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B0_%D0%BD%D0%B0_%D0%B5%D1%81%D1%82%D0%B5%D1%81%D1%82%D0%B2%D0%B5%D0%BD_%D0%B5%D0%B7%D0%B8%D0%BA\" title=\"\\xd0\\x9e\\xd0\\xb1\\xd1\\x80\\xd0\\xb0\\xd0\\xb1\\xd0\\xbe\\xd1\\x82\\xd0\\xba\\xd0\\xb0 \\xd0\\xbd\\xd0\\xb0 \\xd0\\xb5\\xd1\\x81\\xd1\\x82\\xd0\\xb5\\xd1\\x81\\xd1\\x82\\xd0\\xb2\\xd0\\xb5\\xd0\\xbd \\xd0\\xb5\\xd0\\xb7\\xd0\\xb8\\xd0\\xba \\xe2\\x80\\x93 Bulgarian\" lang=\"bg\" hreflang=\"bg\" class=\"interlanguage-link-target\">\\xd0\\x91\\xd1\\x8a\\xd0\\xbb\\xd0\\xb3\\xd0\\xb0\\xd1\\x80\\xd1\\x81\\xd0\\xba\\xd0\\xb8</a></li><li class=\"interlanguage-link interwiki-ca\"><a href=\"https://ca.wikipedia.org/wiki/Processament_de_llenguatge_natural\" title=\"Processament de llenguatge natural \\xe2\\x80\\x93 Catalan\" lang=\"ca\" hreflang=\"ca\" class=\"interlanguage-link-target\">Catal\\xc3\\xa0</a></li><li class=\"interlanguage-link interwiki-cs\"><a href=\"https://cs.wikipedia.org/wiki/Zpracov%C3%A1n%C3%AD_p%C5%99irozen%C3%A9ho_jazyka\" title=\"Zpracov\\xc3\\xa1n\\xc3\\xad p\\xc5\\x99irozen\\xc3\\xa9ho jazyka \\xe2\\x80\\x93 Czech\" lang=\"cs\" hreflang=\"cs\" class=\"interlanguage-link-target\">\\xc4\\x8ce\\xc5\\xa1tina</a></li><li class=\"interlanguage-link interwiki-da\"><a href=\"https://da.wikipedia.org/wiki/Sprogteknologi\" title=\"Sprogteknologi \\xe2\\x80\\x93 Danish\" lang=\"da\" hreflang=\"da\" class=\"interlanguage-link-target\">Dansk</a></li><li class=\"interlanguage-link interwiki-de\"><a href=\"https://de.wikipedia.org/wiki/Verarbeitung_nat%C3%BCrlicher_Sprache\" title=\"Verarbeitung nat\\xc3\\xbcrlicher Sprache \\xe2\\x80\\x93 German\" lang=\"de\" hreflang=\"de\" class=\"interlanguage-link-target\">Deutsch</a></li><li class=\"interlanguage-link interwiki-et\"><a href=\"https://et.wikipedia.org/wiki/Loomuliku_keele_t%C3%B6%C3%B6tlus\" title=\"Loomuliku keele t\\xc3\\xb6\\xc3\\xb6tlus \\xe2\\x80\\x93 Estonian\" lang=\"et\" hreflang=\"et\" class=\"interlanguage-link-target\">Eesti</a></li><li class=\"interlanguage-link interwiki-el\"><a href=\"https://el.wikipedia.org/wiki/%CE%95%CF%80%CE%B5%CE%BE%CE%B5%CF%81%CE%B3%CE%B1%CF%83%CE%AF%CE%B1_%CF%86%CF%85%CF%83%CE%B9%CE%BA%CE%AE%CF%82_%CE%B3%CE%BB%CF%8E%CF%83%CF%83%CE%B1%CF%82\" title=\"\\xce\\x95\\xcf\\x80\\xce\\xb5\\xce\\xbe\\xce\\xb5\\xcf\\x81\\xce\\xb3\\xce\\xb1\\xcf\\x83\\xce\\xaf\\xce\\xb1 \\xcf\\x86\\xcf\\x85\\xcf\\x83\\xce\\xb9\\xce\\xba\\xce\\xae\\xcf\\x82 \\xce\\xb3\\xce\\xbb\\xcf\\x8e\\xcf\\x83\\xcf\\x83\\xce\\xb1\\xcf\\x82 \\xe2\\x80\\x93 Greek\" lang=\"el\" hreflang=\"el\" class=\"interlanguage-link-target\">\\xce\\x95\\xce\\xbb\\xce\\xbb\\xce\\xb7\\xce\\xbd\\xce\\xb9\\xce\\xba\\xce\\xac</a></li><li class=\"interlanguage-link interwiki-es\"><a href=\"https://es.wikipedia.org/wiki/Procesamiento_de_lenguajes_naturales\" title=\"Procesamiento de lenguajes naturales \\xe2\\x80\\x93 Spanish\" lang=\"es\" hreflang=\"es\" class=\"interlanguage-link-target\">Espa\\xc3\\xb1ol</a></li><li class=\"interlanguage-link interwiki-eu\"><a href=\"https://eu.wikipedia.org/wiki/Hizkuntzaren_prozesamendu\" title=\"Hizkuntzaren prozesamendu \\xe2\\x80\\x93 Basque\" lang=\"eu\" hreflang=\"eu\" class=\"interlanguage-link-target\">Euskara</a></li><li class=\"interlanguage-link interwiki-fa\"><a href=\"https://fa.wikipedia.org/wiki/%D9%BE%D8%B1%D8%AF%D8%A7%D8%B2%D8%B4_%D8%B2%D8%A8%D8%A7%D9%86%E2%80%8C%D9%87%D8%A7%DB%8C_%D8%B7%D8%A8%DB%8C%D8%B9%DB%8C\" title=\"\\xd9\\xbe\\xd8\\xb1\\xd8\\xaf\\xd8\\xa7\\xd8\\xb2\\xd8\\xb4 \\xd8\\xb2\\xd8\\xa8\\xd8\\xa7\\xd9\\x86\\xe2\\x80\\x8c\\xd9\\x87\\xd8\\xa7\\xdb\\x8c \\xd8\\xb7\\xd8\\xa8\\xdb\\x8c\\xd8\\xb9\\xdb\\x8c \\xe2\\x80\\x93 Persian\" lang=\"fa\" hreflang=\"fa\" class=\"interlanguage-link-target\">\\xd9\\x81\\xd8\\xa7\\xd8\\xb1\\xd8\\xb3\\xdb\\x8c</a></li><li class=\"interlanguage-link interwiki-fr\"><a href=\"https://fr.wikipedia.org/wiki/Traitement_automatique_des_langues\" title=\"Traitement automatique des langues \\xe2\\x80\\x93 French\" lang=\"fr\" hreflang=\"fr\" class=\"interlanguage-link-target\">Fran\\xc3\\xa7ais</a></li><li class=\"interlanguage-link interwiki-gl\"><a href=\"https://gl.wikipedia.org/wiki/Procesamento_da_linguaxe_natural\" title=\"Procesamento da linguaxe natural \\xe2\\x80\\x93 Galician\" lang=\"gl\" hreflang=\"gl\" class=\"interlanguage-link-target\">Galego</a></li><li class=\"interlanguage-link interwiki-ko\"><a href=\"https://ko.wikipedia.org/wiki/%EC%9E%90%EC%97%B0%EC%96%B4_%EC%B2%98%EB%A6%AC\" title=\"\\xec\\x9e\\x90\\xec\\x97\\xb0\\xec\\x96\\xb4 \\xec\\xb2\\x98\\xeb\\xa6\\xac \\xe2\\x80\\x93 Korean\" lang=\"ko\" hreflang=\"ko\" class=\"interlanguage-link-target\">\\xed\\x95\\x9c\\xea\\xb5\\xad\\xec\\x96\\xb4</a></li><li class=\"interlanguage-link interwiki-hy\"><a href=\"https://hy.wikipedia.org/wiki/%D4%B2%D5%B6%D5%A1%D5%AF%D5%A1%D5%B6_%D5%AC%D5%A5%D5%A6%D5%BE%D5%AB_%D5%B4%D5%B7%D5%A1%D5%AF%D5%B8%D6%82%D5%B4\" title=\"\\xd4\\xb2\\xd5\\xb6\\xd5\\xa1\\xd5\\xaf\\xd5\\xa1\\xd5\\xb6 \\xd5\\xac\\xd5\\xa5\\xd5\\xa6\\xd5\\xbe\\xd5\\xab \\xd5\\xb4\\xd5\\xb7\\xd5\\xa1\\xd5\\xaf\\xd5\\xb8\\xd6\\x82\\xd5\\xb4 \\xe2\\x80\\x93 Armenian\" lang=\"hy\" hreflang=\"hy\" class=\"interlanguage-link-target\">\\xd5\\x80\\xd5\\xa1\\xd5\\xb5\\xd5\\xa5\\xd6\\x80\\xd5\\xa5\\xd5\\xb6</a></li><li class=\"interlanguage-link interwiki-hi\"><a href=\"https://hi.wikipedia.org/wiki/%E0%A4%AA%E0%A5%8D%E0%A4%B0%E0%A4%BE%E0%A4%95%E0%A5%83%E0%A4%A4%E0%A4%BF%E0%A4%95_%E0%A4%AD%E0%A4%BE%E0%A4%B7%E0%A4%BE_%E0%A4%B8%E0%A4%82%E0%A4%B8%E0%A4%BE%E0%A4%A7%E0%A4%A8\" title=\"\\xe0\\xa4\\xaa\\xe0\\xa5\\x8d\\xe0\\xa4\\xb0\\xe0\\xa4\\xbe\\xe0\\xa4\\x95\\xe0\\xa5\\x83\\xe0\\xa4\\xa4\\xe0\\xa4\\xbf\\xe0\\xa4\\x95 \\xe0\\xa4\\xad\\xe0\\xa4\\xbe\\xe0\\xa4\\xb7\\xe0\\xa4\\xbe \\xe0\\xa4\\xb8\\xe0\\xa4\\x82\\xe0\\xa4\\xb8\\xe0\\xa4\\xbe\\xe0\\xa4\\xa7\\xe0\\xa4\\xa8 \\xe2\\x80\\x93 Hindi\" lang=\"hi\" hreflang=\"hi\" class=\"interlanguage-link-target\">\\xe0\\xa4\\xb9\\xe0\\xa4\\xbf\\xe0\\xa4\\xa8\\xe0\\xa5\\x8d\\xe0\\xa4\\xa6\\xe0\\xa5\\x80</a></li><li class=\"interlanguage-link interwiki-hr\"><a href=\"https://hr.wikipedia.org/wiki/Obrada_prirodnog_jezika\" title=\"Obrada prirodnog jezika \\xe2\\x80\\x93 Croatian\" lang=\"hr\" hreflang=\"hr\" class=\"interlanguage-link-target\">Hrvatski</a></li><li class=\"interlanguage-link interwiki-id\"><a href=\"https://id.wikipedia.org/wiki/Pemrosesan_bahasa_alami\" title=\"Pemrosesan bahasa alami \\xe2\\x80\\x93 Indonesian\" lang=\"id\" hreflang=\"id\" class=\"interlanguage-link-target\">Bahasa Indonesia</a></li><li class=\"interlanguage-link interwiki-is\"><a href=\"https://is.wikipedia.org/wiki/M%C3%A1lgreining\" title=\"M\\xc3\\xa1lgreining \\xe2\\x80\\x93 Icelandic\" lang=\"is\" hreflang=\"is\" class=\"interlanguage-link-target\">\\xc3\\x8dslenska</a></li><li class=\"interlanguage-link interwiki-it\"><a href=\"https://it.wikipedia.org/wiki/Elaborazione_del_linguaggio_naturale\" title=\"Elaborazione del linguaggio naturale \\xe2\\x80\\x93 Italian\" lang=\"it\" hreflang=\"it\" class=\"interlanguage-link-target\">Italiano</a></li><li class=\"interlanguage-link interwiki-he\"><a href=\"https://he.wikipedia.org/wiki/%D7%A2%D7%99%D7%91%D7%95%D7%93_%D7%A9%D7%A4%D7%94_%D7%98%D7%91%D7%A2%D7%99%D7%AA\" title=\"\\xd7\\xa2\\xd7\\x99\\xd7\\x91\\xd7\\x95\\xd7\\x93 \\xd7\\xa9\\xd7\\xa4\\xd7\\x94 \\xd7\\x98\\xd7\\x91\\xd7\\xa2\\xd7\\x99\\xd7\\xaa \\xe2\\x80\\x93 Hebrew\" lang=\"he\" hreflang=\"he\" class=\"interlanguage-link-target\">\\xd7\\xa2\\xd7\\x91\\xd7\\xa8\\xd7\\x99\\xd7\\xaa</a></li><li class=\"interlanguage-link interwiki-kn\"><a href=\"https://kn.wikipedia.org/wiki/%E0%B2%AA%E0%B3%8D%E0%B2%B0%E0%B2%BE%E0%B2%95%E0%B3%83%E0%B2%A4%E0%B2%BF%E0%B2%95_%E0%B2%AD%E0%B2%BE%E0%B2%B7%E0%B3%86%E0%B2%AF_%E0%B2%AA%E0%B2%B0%E0%B2%BF%E0%B2%B7%E0%B3%8D%E0%B2%95%E0%B2%B0%E0%B2%A3%E0%B3%86\" title=\"\\xe0\\xb2\\xaa\\xe0\\xb3\\x8d\\xe0\\xb2\\xb0\\xe0\\xb2\\xbe\\xe0\\xb2\\x95\\xe0\\xb3\\x83\\xe0\\xb2\\xa4\\xe0\\xb2\\xbf\\xe0\\xb2\\x95 \\xe0\\xb2\\xad\\xe0\\xb2\\xbe\\xe0\\xb2\\xb7\\xe0\\xb3\\x86\\xe0\\xb2\\xaf \\xe0\\xb2\\xaa\\xe0\\xb2\\xb0\\xe0\\xb2\\xbf\\xe0\\xb2\\xb7\\xe0\\xb3\\x8d\\xe0\\xb2\\x95\\xe0\\xb2\\xb0\\xe0\\xb2\\xa3\\xe0\\xb3\\x86 \\xe2\\x80\\x93 Kannada\" lang=\"kn\" hreflang=\"kn\" class=\"interlanguage-link-target\">\\xe0\\xb2\\x95\\xe0\\xb2\\xa8\\xe0\\xb3\\x8d\\xe0\\xb2\\xa8\\xe0\\xb2\\xa1</a></li><li class=\"interlanguage-link interwiki-ka\"><a href=\"https://ka.wikipedia.org/wiki/%E1%83%91%E1%83%A3%E1%83%9C%E1%83%94%E1%83%91%E1%83%A0%E1%83%98%E1%83%95%E1%83%98_%E1%83%94%E1%83%9C%E1%83%98%E1%83%A1_%E1%83%93%E1%83%90%E1%83%9B%E1%83%A3%E1%83%A8%E1%83%90%E1%83%95%E1%83%94%E1%83%91%E1%83%90\" title=\"\\xe1\\x83\\x91\\xe1\\x83\\xa3\\xe1\\x83\\x9c\\xe1\\x83\\x94\\xe1\\x83\\x91\\xe1\\x83\\xa0\\xe1\\x83\\x98\\xe1\\x83\\x95\\xe1\\x83\\x98 \\xe1\\x83\\x94\\xe1\\x83\\x9c\\xe1\\x83\\x98\\xe1\\x83\\xa1 \\xe1\\x83\\x93\\xe1\\x83\\x90\\xe1\\x83\\x9b\\xe1\\x83\\xa3\\xe1\\x83\\xa8\\xe1\\x83\\x90\\xe1\\x83\\x95\\xe1\\x83\\x94\\xe1\\x83\\x91\\xe1\\x83\\x90 \\xe2\\x80\\x93 Georgian\" lang=\"ka\" hreflang=\"ka\" class=\"interlanguage-link-target\">\\xe1\\x83\\xa5\\xe1\\x83\\x90\\xe1\\x83\\xa0\\xe1\\x83\\x97\\xe1\\x83\\xa3\\xe1\\x83\\x9a\\xe1\\x83\\x98</a></li><li class=\"interlanguage-link interwiki-lt\"><a href=\"https://lt.wikipedia.org/wiki/Nat%C5%ABralios_kalbos_apdorojimas\" title=\"Nat\\xc5\\xabralios kalbos apdorojimas \\xe2\\x80\\x93 Lithuanian\" lang=\"lt\" hreflang=\"lt\" class=\"interlanguage-link-target\">Lietuvi\\xc5\\xb3</a></li><li class=\"interlanguage-link interwiki-mk\"><a href=\"https://mk.wikipedia.org/wiki/%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B0_%D0%BD%D0%B0_%D0%BF%D1%80%D0%B8%D1%80%D0%BE%D0%B4%D0%BD%D0%B8_%D1%98%D0%B0%D0%B7%D0%B8%D1%86%D0%B8\" title=\"\\xd0\\x9e\\xd0\\xb1\\xd1\\x80\\xd0\\xb0\\xd0\\xb1\\xd0\\xbe\\xd1\\x82\\xd0\\xba\\xd0\\xb0 \\xd0\\xbd\\xd0\\xb0 \\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd1\\x80\\xd0\\xbe\\xd0\\xb4\\xd0\\xbd\\xd0\\xb8 \\xd1\\x98\\xd0\\xb0\\xd0\\xb7\\xd0\\xb8\\xd1\\x86\\xd0\\xb8 \\xe2\\x80\\x93 Macedonian\" lang=\"mk\" hreflang=\"mk\" class=\"interlanguage-link-target\">\\xd0\\x9c\\xd0\\xb0\\xd0\\xba\\xd0\\xb5\\xd0\\xb4\\xd0\\xbe\\xd0\\xbd\\xd1\\x81\\xd0\\xba\\xd0\\xb8</a></li><li class=\"interlanguage-link interwiki-mr\"><a href=\"https://mr.wikipedia.org/wiki/%E0%A4%A8%E0%A5%88%E0%A4%B8%E0%A4%B0%E0%A5%8D%E0%A4%97%E0%A4%BF%E0%A4%95_%E0%A4%AD%E0%A4%BE%E0%A4%B7%E0%A4%BE_%E0%A4%AA%E0%A5%8D%E0%A4%B0%E0%A4%95%E0%A5%8D%E0%A4%B0%E0%A4%BF%E0%A4%AF%E0%A4%BE\" title=\"\\xe0\\xa4\\xa8\\xe0\\xa5\\x88\\xe0\\xa4\\xb8\\xe0\\xa4\\xb0\\xe0\\xa5\\x8d\\xe0\\xa4\\x97\\xe0\\xa4\\xbf\\xe0\\xa4\\x95 \\xe0\\xa4\\xad\\xe0\\xa4\\xbe\\xe0\\xa4\\xb7\\xe0\\xa4\\xbe \\xe0\\xa4\\xaa\\xe0\\xa5\\x8d\\xe0\\xa4\\xb0\\xe0\\xa4\\x95\\xe0\\xa5\\x8d\\xe0\\xa4\\xb0\\xe0\\xa4\\xbf\\xe0\\xa4\\xaf\\xe0\\xa4\\xbe \\xe2\\x80\\x93 Marathi\" lang=\"mr\" hreflang=\"mr\" class=\"interlanguage-link-target\">\\xe0\\xa4\\xae\\xe0\\xa4\\xb0\\xe0\\xa4\\xbe\\xe0\\xa4\\xa0\\xe0\\xa5\\x80</a></li><li class=\"interlanguage-link interwiki-mn\"><a href=\"https://mn.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BC%D0%BF%D1%8C%D1%8E%D1%82%D0%B5%D1%80%D1%8B%D0%BD_%D1%85%D1%8D%D0%BB_%D1%88%D0%B8%D0%BD%D0%B6%D0%BB%D1%8D%D0%BB\" title=\"\\xd0\\x9a\\xd0\\xbe\\xd0\\xbc\\xd0\\xbf\\xd1\\x8c\\xd1\\x8e\\xd1\\x82\\xd0\\xb5\\xd1\\x80\\xd1\\x8b\\xd0\\xbd \\xd1\\x85\\xd1\\x8d\\xd0\\xbb \\xd1\\x88\\xd0\\xb8\\xd0\\xbd\\xd0\\xb6\\xd0\\xbb\\xd1\\x8d\\xd0\\xbb \\xe2\\x80\\x93 Mongolian\" lang=\"mn\" hreflang=\"mn\" class=\"interlanguage-link-target\">\\xd0\\x9c\\xd0\\xbe\\xd0\\xbd\\xd0\\xb3\\xd0\\xbe\\xd0\\xbb</a></li><li class=\"interlanguage-link interwiki-my\"><a href=\"https://my.wikipedia.org/wiki/%E1%80%99%E1%80%AD%E1%80%81%E1%80%84%E1%80%BA%E1%80%98%E1%80%AC%E1%80%9E%E1%80%AC%E1%80%85%E1%80%80%E1%80%AC%E1%80%B8%E1%80%9E%E1%80%AF%E1%80%B6%E1%80%B8_%E1%80%80%E1%80%BD%E1%80%94%E1%80%BA%E1%80%95%E1%80%BB%E1%80%B0%E1%80%90%E1%80%AC%E1%80%85%E1%80%94%E1%80%85%E1%80%BA\" title=\"\\xe1\\x80\\x99\\xe1\\x80\\xad\\xe1\\x80\\x81\\xe1\\x80\\x84\\xe1\\x80\\xba\\xe1\\x80\\x98\\xe1\\x80\\xac\\xe1\\x80\\x9e\\xe1\\x80\\xac\\xe1\\x80\\x85\\xe1\\x80\\x80\\xe1\\x80\\xac\\xe1\\x80\\xb8\\xe1\\x80\\x9e\\xe1\\x80\\xaf\\xe1\\x80\\xb6\\xe1\\x80\\xb8 \\xe1\\x80\\x80\\xe1\\x80\\xbd\\xe1\\x80\\x94\\xe1\\x80\\xba\\xe1\\x80\\x95\\xe1\\x80\\xbb\\xe1\\x80\\xb0\\xe1\\x80\\x90\\xe1\\x80\\xac\\xe1\\x80\\x85\\xe1\\x80\\x94\\xe1\\x80\\x85\\xe1\\x80\\xba \\xe2\\x80\\x93 Burmese\" lang=\"my\" hreflang=\"my\" class=\"interlanguage-link-target\">\\xe1\\x80\\x99\\xe1\\x80\\xbc\\xe1\\x80\\x94\\xe1\\x80\\xba\\xe1\\x80\\x99\\xe1\\x80\\xac\\xe1\\x80\\x98\\xe1\\x80\\xac\\xe1\\x80\\x9e\\xe1\\x80\\xac</a></li><li class=\"interlanguage-link interwiki-ja\"><a href=\"https://ja.wikipedia.org/wiki/%E8%87%AA%E7%84%B6%E8%A8%80%E8%AA%9E%E5%87%A6%E7%90%86\" title=\"\\xe8\\x87\\xaa\\xe7\\x84\\xb6\\xe8\\xa8\\x80\\xe8\\xaa\\x9e\\xe5\\x87\\xa6\\xe7\\x90\\x86 \\xe2\\x80\\x93 Japanese\" lang=\"ja\" hreflang=\"ja\" class=\"interlanguage-link-target\">\\xe6\\x97\\xa5\\xe6\\x9c\\xac\\xe8\\xaa\\x9e</a></li><li class=\"interlanguage-link interwiki-or\"><a href=\"https://or.wikipedia.org/wiki/%E0%AC%A8%E0%AD%8D%E0%AD%9F%E0%AC%BE%E0%AC%9A%E0%AD%81%E0%AC%B0%E0%AC%BE%E0%AC%B2_%E0%AC%B2%E0%AC%BE%E0%AC%99%E0%AD%8D%E0%AC%97%E0%AD%81%E0%AC%8F%E0%AC%9C_%E0%AC%AA%E0%AD%8D%E0%AC%B0%E0%AD%8B%E0%AC%B8%E0%AD%87%E0%AC%B8%E0%AC%BF%E0%AC%82\" title=\"\\xe0\\xac\\xa8\\xe0\\xad\\x8d\\xe0\\xad\\x9f\\xe0\\xac\\xbe\\xe0\\xac\\x9a\\xe0\\xad\\x81\\xe0\\xac\\xb0\\xe0\\xac\\xbe\\xe0\\xac\\xb2 \\xe0\\xac\\xb2\\xe0\\xac\\xbe\\xe0\\xac\\x99\\xe0\\xad\\x8d\\xe0\\xac\\x97\\xe0\\xad\\x81\\xe0\\xac\\x8f\\xe0\\xac\\x9c \\xe0\\xac\\xaa\\xe0\\xad\\x8d\\xe0\\xac\\xb0\\xe0\\xad\\x8b\\xe0\\xac\\xb8\\xe0\\xad\\x87\\xe0\\xac\\xb8\\xe0\\xac\\xbf\\xe0\\xac\\x82 \\xe2\\x80\\x93 Odia\" lang=\"or\" hreflang=\"or\" class=\"interlanguage-link-target\">\\xe0\\xac\\x93\\xe0\\xac\\xa1\\xe0\\xac\\xbc\\xe0\\xac\\xbf\\xe0\\xac\\x86</a></li><li class=\"interlanguage-link interwiki-pms\"><a href=\"https://pms.wikipedia.org/wiki/NLP\" title=\"NLP \\xe2\\x80\\x93 Piedmontese\" lang=\"pms\" hreflang=\"pms\" class=\"interlanguage-link-target\">Piemont\\xc3\\xa8is</a></li><li class=\"interlanguage-link interwiki-pl\"><a href=\"https://pl.wikipedia.org/wiki/Przetwarzanie_j%C4%99zyka_naturalnego\" title=\"Przetwarzanie j\\xc4\\x99zyka naturalnego \\xe2\\x80\\x93 Polish\" lang=\"pl\" hreflang=\"pl\" class=\"interlanguage-link-target\">Polski</a></li><li class=\"interlanguage-link interwiki-pt\"><a href=\"https://pt.wikipedia.org/wiki/Processamento_de_linguagem_natural\" title=\"Processamento de linguagem natural \\xe2\\x80\\x93 Portuguese\" lang=\"pt\" hreflang=\"pt\" class=\"interlanguage-link-target\">Portugu\\xc3\\xaas</a></li><li class=\"interlanguage-link interwiki-ro\"><a href=\"https://ro.wikipedia.org/wiki/Prelucrarea_limbajului_natural\" title=\"Prelucrarea limbajului natural \\xe2\\x80\\x93 Romanian\" lang=\"ro\" hreflang=\"ro\" class=\"interlanguage-link-target\">Rom\\xc3\\xa2n\\xc4\\x83</a></li><li class=\"interlanguage-link interwiki-ru\"><a href=\"https://ru.wikipedia.org/wiki/%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B0_%D0%B5%D1%81%D1%82%D0%B5%D1%81%D1%82%D0%B2%D0%B5%D0%BD%D0%BD%D0%BE%D0%B3%D0%BE_%D1%8F%D0%B7%D1%8B%D0%BA%D0%B0\" title=\"\\xd0\\x9e\\xd0\\xb1\\xd1\\x80\\xd0\\xb0\\xd0\\xb1\\xd0\\xbe\\xd1\\x82\\xd0\\xba\\xd0\\xb0 \\xd0\\xb5\\xd1\\x81\\xd1\\x82\\xd0\\xb5\\xd1\\x81\\xd1\\x82\\xd0\\xb2\\xd0\\xb5\\xd0\\xbd\\xd0\\xbd\\xd0\\xbe\\xd0\\xb3\\xd0\\xbe \\xd1\\x8f\\xd0\\xb7\\xd1\\x8b\\xd0\\xba\\xd0\\xb0 \\xe2\\x80\\x93 Russian\" lang=\"ru\" hreflang=\"ru\" class=\"interlanguage-link-target\">\\xd0\\xa0\\xd1\\x83\\xd1\\x81\\xd1\\x81\\xd0\\xba\\xd0\\xb8\\xd0\\xb9</a></li><li class=\"interlanguage-link interwiki-simple\"><a href=\"https://simple.wikipedia.org/wiki/Natural_language_processing\" title=\"Natural language processing \\xe2\\x80\\x93 Simple English\" lang=\"en-simple\" hreflang=\"en-simple\" class=\"interlanguage-link-target\">Simple English</a></li><li class=\"interlanguage-link interwiki-ckb\"><a href=\"https://ckb.wikipedia.org/wiki/%D9%BE%DB%8E%D9%88%D8%A7%DA%98%DB%86%DA%A9%D8%B1%D8%AF%D9%86%DB%8C_%D8%B2%D9%85%D8%A7%D9%86%DB%8C_%D8%B3%D8%B1%D9%88%D8%B4%D8%AA%DB%8C\" title=\"\\xd9\\xbe\\xdb\\x8e\\xd9\\x88\\xd8\\xa7\\xda\\x98\\xdb\\x86\\xda\\xa9\\xd8\\xb1\\xd8\\xaf\\xd9\\x86\\xdb\\x8c \\xd8\\xb2\\xd9\\x85\\xd8\\xa7\\xd9\\x86\\xdb\\x8c \\xd8\\xb3\\xd8\\xb1\\xd9\\x88\\xd8\\xb4\\xd8\\xaa\\xdb\\x8c \\xe2\\x80\\x93 Central Kurdish\" lang=\"ckb\" hreflang=\"ckb\" class=\"interlanguage-link-target\">\\xda\\xa9\\xd9\\x88\\xd8\\xb1\\xd8\\xaf\\xdb\\x8c</a></li><li class=\"interlanguage-link interwiki-sr\"><a href=\"https://sr.wikipedia.org/wiki/Obrada_prirodnih_jezika\" title=\"Obrada prirodnih jezika \\xe2\\x80\\x93 Serbian\" lang=\"sr\" hreflang=\"sr\" class=\"interlanguage-link-target\">\\xd0\\xa1\\xd1\\x80\\xd0\\xbf\\xd1\\x81\\xd0\\xba\\xd0\\xb8 / srpski</a></li><li class=\"interlanguage-link interwiki-sh\"><a href=\"https://sh.wikipedia.org/wiki/Obrada_prirodnih_jezika\" title=\"Obrada prirodnih jezika \\xe2\\x80\\x93 Serbo-Croatian\" lang=\"sh\" hreflang=\"sh\" class=\"interlanguage-link-target\">Srpskohrvatski / \\xd1\\x81\\xd1\\x80\\xd0\\xbf\\xd1\\x81\\xd0\\xba\\xd0\\xbe\\xd1\\x85\\xd1\\x80\\xd0\\xb2\\xd0\\xb0\\xd1\\x82\\xd1\\x81\\xd0\\xba\\xd0\\xb8</a></li><li class=\"interlanguage-link interwiki-ta\"><a href=\"https://ta.wikipedia.org/wiki/%E0%AE%87%E0%AE%AF%E0%AE%B1%E0%AF%8D%E0%AE%95%E0%AF%88_%E0%AE%AE%E0%AF%8A%E0%AE%B4%E0%AE%BF_%E0%AE%AE%E0%AF%81%E0%AE%B1%E0%AF%88%E0%AE%AF%E0%AE%BE%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%AE%E0%AF%8D\" title=\"\\xe0\\xae\\x87\\xe0\\xae\\xaf\\xe0\\xae\\xb1\\xe0\\xaf\\x8d\\xe0\\xae\\x95\\xe0\\xaf\\x88 \\xe0\\xae\\xae\\xe0\\xaf\\x8a\\xe0\\xae\\xb4\\xe0\\xae\\xbf \\xe0\\xae\\xae\\xe0\\xaf\\x81\\xe0\\xae\\xb1\\xe0\\xaf\\x88\\xe0\\xae\\xaf\\xe0\\xae\\xbe\\xe0\\xae\\x95\\xe0\\xaf\\x8d\\xe0\\xae\\x95\\xe0\\xae\\xae\\xe0\\xaf\\x8d \\xe2\\x80\\x93 Tamil\" lang=\"ta\" hreflang=\"ta\" class=\"interlanguage-link-target\">\\xe0\\xae\\xa4\\xe0\\xae\\xae\\xe0\\xae\\xbf\\xe0\\xae\\xb4\\xe0\\xaf\\x8d</a></li><li class=\"interlanguage-link interwiki-th\"><a href=\"https://th.wikipedia.org/wiki/%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%A1%E0%B8%A7%E0%B8%A5%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B8%98%E0%B8%A3%E0%B8%A3%E0%B8%A1%E0%B8%8A%E0%B8%B2%E0%B8%95%E0%B8%B4\" title=\"\\xe0\\xb8\\x81\\xe0\\xb8\\xb2\\xe0\\xb8\\xa3\\xe0\\xb8\\x9b\\xe0\\xb8\\xa3\\xe0\\xb8\\xb0\\xe0\\xb8\\xa1\\xe0\\xb8\\xa7\\xe0\\xb8\\xa5\\xe0\\xb8\\xa0\\xe0\\xb8\\xb2\\xe0\\xb8\\xa9\\xe0\\xb8\\xb2\\xe0\\xb8\\x98\\xe0\\xb8\\xa3\\xe0\\xb8\\xa3\\xe0\\xb8\\xa1\\xe0\\xb8\\x8a\\xe0\\xb8\\xb2\\xe0\\xb8\\x95\\xe0\\xb8\\xb4 \\xe2\\x80\\x93 Thai\" lang=\"th\" hreflang=\"th\" class=\"interlanguage-link-target\">\\xe0\\xb9\\x84\\xe0\\xb8\\x97\\xe0\\xb8\\xa2</a></li><li class=\"interlanguage-link interwiki-tr\"><a href=\"https://tr.wikipedia.org/wiki/Do%C4%9Fal_dil_i%C5%9Fleme\" title=\"Do\\xc4\\x9fal dil i\\xc5\\x9fleme \\xe2\\x80\\x93 Turkish\" lang=\"tr\" hreflang=\"tr\" class=\"interlanguage-link-target\">T\\xc3\\xbcrk\\xc3\\xa7e</a></li><li class=\"interlanguage-link interwiki-uk\"><a href=\"https://uk.wikipedia.org/wiki/%D0%9E%D0%B1%D1%80%D0%BE%D0%B1%D0%BA%D0%B0_%D0%BF%D1%80%D0%B8%D1%80%D0%BE%D0%B4%D0%BD%D0%BE%D1%97_%D0%BC%D0%BE%D0%B2%D0%B8\" title=\"\\xd0\\x9e\\xd0\\xb1\\xd1\\x80\\xd0\\xbe\\xd0\\xb1\\xd0\\xba\\xd0\\xb0 \\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd1\\x80\\xd0\\xbe\\xd0\\xb4\\xd0\\xbd\\xd0\\xbe\\xd1\\x97 \\xd0\\xbc\\xd0\\xbe\\xd0\\xb2\\xd0\\xb8 \\xe2\\x80\\x93 Ukrainian\" lang=\"uk\" hreflang=\"uk\" class=\"interlanguage-link-target\">\\xd0\\xa3\\xd0\\xba\\xd1\\x80\\xd0\\xb0\\xd1\\x97\\xd0\\xbd\\xd1\\x81\\xd1\\x8c\\xd0\\xba\\xd0\\xb0</a></li><li class=\"interlanguage-link interwiki-vi\"><a href=\"https://vi.wikipedia.org/wiki/X%E1%BB%AD_l%C3%BD_ng%C3%B4n_ng%E1%BB%AF_t%E1%BB%B1_nhi%C3%AAn\" title=\"X\\xe1\\xbb\\xad l\\xc3\\xbd ng\\xc3\\xb4n ng\\xe1\\xbb\\xaf t\\xe1\\xbb\\xb1 nhi\\xc3\\xaan \\xe2\\x80\\x93 Vietnamese\" lang=\"vi\" hreflang=\"vi\" class=\"interlanguage-link-target\">Ti\\xe1\\xba\\xbfng Vi\\xe1\\xbb\\x87t</a></li><li class=\"interlanguage-link interwiki-zh-yue\"><a href=\"https://zh-yue.wikipedia.org/wiki/%E8%87%AA%E7%84%B6%E8%AA%9E%E8%A8%80%E8%99%95%E7%90%86\" title=\"\\xe8\\x87\\xaa\\xe7\\x84\\xb6\\xe8\\xaa\\x9e\\xe8\\xa8\\x80\\xe8\\x99\\x95\\xe7\\x90\\x86 \\xe2\\x80\\x93 Cantonese\" lang=\"yue\" hreflang=\"yue\" class=\"interlanguage-link-target\">\\xe7\\xb2\\xb5\\xe8\\xaa\\x9e</a></li><li class=\"interlanguage-link interwiki-zh\"><a href=\"https://zh.wikipedia.org/wiki/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7%90%86\" title=\"\\xe8\\x87\\xaa\\xe7\\x84\\xb6\\xe8\\xaf\\xad\\xe8\\xa8\\x80\\xe5\\xa4\\x84\\xe7\\x90\\x86 \\xe2\\x80\\x93 Chinese\" lang=\"zh\" hreflang=\"zh\" class=\"interlanguage-link-target\">\\xe4\\xb8\\xad\\xe6\\x96\\x87</a></li></ul>\\n\\t\\t<div class=\"after-portlet after-portlet-lang\"><span class=\"wb-langlinks-edit wb-langlinks-link\"><a href=\"https://www.wikidata.org/wiki/Special:EntityPage/Q30642#sitelinks-wikipedia\" title=\"Edit interlanguage links\" class=\"wbc-editpage\">Edit links</a></span></div>\\n\\t</div>\\n</nav>\\n\\n</div>\\n\\n</div>\\n<footer id=\"footer\" class=\"mw-footer\" role=\"contentinfo\" >\\n\\t<ul id=\"footer-info\" >\\n\\t<li id=\"footer-info-lastmod\"> This page was last edited on 7 April 2021, at 03:07<span class=\"anonymous-show\">&#160;(UTC)</span>.</li>\\n\\t<li id=\"footer-info-copyright\">Text is available under the <a rel=\"license\" href=\"//en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\">Creative Commons Attribution-ShareAlike License</a><a rel=\"license\" href=\"//creativecommons.org/licenses/by-sa/3.0/\" style=\"display:none;\"></a>;\\nadditional terms may apply. By using this site, you agree to the <a href=\"//foundation.wikimedia.org/wiki/Terms_of_Use\">Terms of Use</a> and <a href=\"//foundation.wikimedia.org/wiki/Privacy_policy\">Privacy Policy</a>. Wikipedia\\xc2\\xae is a registered trademark of the <a href=\"//www.wikimediafoundation.org/\">Wikimedia Foundation, Inc.</a>, a non-profit organization.</li>\\n</ul>\\n\\n\\t<ul id=\"footer-places\" >\\n\\t<li id=\"footer-places-privacy\"><a href=\"https://foundation.wikimedia.org/wiki/Privacy_policy\" class=\"extiw\" title=\"wmf:Privacy policy\">Privacy policy</a></li>\\n\\t<li id=\"footer-places-about\"><a href=\"/wiki/Wikipedia:About\" title=\"Wikipedia:About\">About Wikipedia</a></li>\\n\\t<li id=\"footer-places-disclaimer\"><a href=\"/wiki/Wikipedia:General_disclaimer\" title=\"Wikipedia:General disclaimer\">Disclaimers</a></li>\\n\\t<li id=\"footer-places-contact\"><a href=\"//en.wikipedia.org/wiki/Wikipedia:Contact_us\">Contact Wikipedia</a></li>\\n\\t<li id=\"footer-places-mobileview\"><a href=\"//en.m.wikipedia.org/w/index.php?title=Natural_language_processing&amp;mobileaction=toggle_view_mobile\" class=\"noprint stopMobileRedirectToggle\">Mobile view</a></li>\\n\\t<li id=\"footer-places-developers\"><a href=\"https://www.mediawiki.org/wiki/Special:MyLanguage/How_to_contribute\">Developers</a></li>\\n\\t<li id=\"footer-places-statslink\"><a href=\"https://stats.wikimedia.org/#/en.wikipedia.org\">Statistics</a></li>\\n\\t<li id=\"footer-places-cookiestatement\"><a href=\"https://foundation.wikimedia.org/wiki/Cookie_statement\">Cookie statement</a></li>\\n</ul>\\n\\n\\t<ul id=\"footer-icons\" class=\"noprint\">\\n\\t<li id=\"footer-copyrightico\"><a href=\"https://wikimediafoundation.org/\"><img src=\"/static/images/footer/wikimedia-button.png\" srcset=\"/static/images/footer/wikimedia-button-1.5x.png 1.5x, /static/images/footer/wikimedia-button-2x.png 2x\" width=\"88\" height=\"31\" alt=\"Wikimedia Foundation\" loading=\"lazy\" /></a></li>\\n\\t<li id=\"footer-poweredbyico\"><a href=\"https://www.mediawiki.org/\"><img src=\"/static/images/footer/poweredby_mediawiki_88x31.png\" alt=\"Powered by MediaWiki\" srcset=\"/static/images/footer/poweredby_mediawiki_132x47.png 1.5x, /static/images/footer/poweredby_mediawiki_176x62.png 2x\" width=\"88\" height=\"31\" loading=\"lazy\"/></a></li>\\n</ul>\\n\\n</footer>\\n\\n\\n<script>(RLQ=window.RLQ||[]).push(function(){mw.config.set({\"wgPageParseReport\":{\"limitreport\":{\"cputime\":\"1.005\",\"walltime\":\"1.382\",\"ppvisitednodes\":{\"value\":4406,\"limit\":1000000},\"postexpandincludesize\":{\"value\":98406,\"limit\":2097152},\"templateargumentsize\":{\"value\":5151,\"limit\":2097152},\"expansiondepth\":{\"value\":14,\"limit\":40},\"expensivefunctioncount\":{\"value\":3,\"limit\":500},\"unstrip-depth\":{\"value\":1,\"limit\":20},\"unstrip-size\":{\"value\":142685,\"limit\":5000000},\"entityaccesscount\":{\"value\":1,\"limit\":400},\"timingprofile\":[\"100.00% 1144.153 1 -total\",\" 44.83% 512.908 1 Template:Reflist\",\" 11.76% 134.511 7 Template:ISBN\",\" 11.63% 133.094 1 Template:Cite_conference\",\" 10.19% 116.587 18 Template:Cite_web\",\" 8.53% 97.569 1 Template:Short_description\",\" 7.23% 82.697 10 Template:Cite_journal\",\" 5.15% 58.934 1 Template:Natural_Language_Processing\",\" 5.01% 57.293 1 Template:Self-published_source\",\" 4.76% 54.473 1 Template:Authority_control\"]},\"scribunto\":{\"limitreport-timeusage\":{\"value\":\"0.495\",\"limit\":\"10.000\"},\"limitreport-memusage\":{\"value\":6443714,\"limit\":52428800}},\"cachereport\":{\"origin\":\"mw1267\",\"timestamp\":\"20210414012917\",\"ttl\":2592000,\"transientcontent\":false}}});});</script>\\n<script type=\"application/ld+json\">{\"@context\":\"https:\\\\/\\\\/schema.org\",\"@type\":\"Article\",\"name\":\"Natural language processing\",\"url\":\"https:\\\\/\\\\/en.wikipedia.org\\\\/wiki\\\\/Natural_language_processing\",\"sameAs\":\"http:\\\\/\\\\/www.wikidata.org\\\\/entity\\\\/Q30642\",\"mainEntity\":\"http:\\\\/\\\\/www.wikidata.org\\\\/entity\\\\/Q30642\",\"author\":{\"@type\":\"Organization\",\"name\":\"Contributors to Wikimedia projects\"},\"publisher\":{\"@type\":\"Organization\",\"name\":\"Wikimedia Foundation, Inc.\",\"logo\":{\"@type\":\"ImageObject\",\"url\":\"https:\\\\/\\\\/www.wikimedia.org\\\\/static\\\\/images\\\\/wmf-hor-googpub.png\"}},\"datePublished\":\"2001-09-22T05:47:41Z\",\"dateModified\":\"2021-04-07T03:07:39Z\",\"image\":\"https:\\\\/\\\\/upload.wikimedia.org\\\\/wikipedia\\\\/commons\\\\/8\\\\/8b\\\\/Automated_online_assistant.png\",\"headline\":\"field of computer science and linguistics\"}</script>\\n<script>(RLQ=window.RLQ||[]).push(function(){mw.config.set({\"wgBackendResponseTime\":173,\"wgHostname\":\"mw1385\"});});</script>\\n</body></html>'\n" ], [ "article_html = bs.BeautifulSoup(raw_html, 'lxml')\nprint(article_html)", "<!DOCTYPE html>\n<html class=\"client-nojs\" dir=\"ltr\" lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<title>Natural language processing - Wikipedia</title>\n<script>document.documentElement.className=\"client-js\";RLCONF={\"wgBreakFrames\":!1,\"wgSeparatorTransformTable\":[\"\",\"\"],\"wgDigitTransformTable\":[\"\",\"\"],\"wgDefaultDateFormat\":\"dmy\",\"wgMonthNames\":[\"\",\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"],\"wgRequestId\":\"1d520229-7b57-47f3-9817-5e3f5cb41783\",\"wgCSPNonce\":!1,\"wgCanonicalNamespace\":\"\",\"wgCanonicalSpecialPageName\":!1,\"wgNamespaceNumber\":0,\"wgPageName\":\"Natural_language_processing\",\"wgTitle\":\"Natural language processing\",\"wgCurRevisionId\":1016426461,\"wgRevisionId\":1016426461,\"wgArticleId\":21652,\"wgIsArticle\":!0,\"wgIsRedirect\":!1,\"wgAction\":\"view\",\"wgUserName\":null,\"wgUserGroups\":[\"*\"],\"wgCategories\":[\"CS1 maint: location\",\"Articles with short description\",\"Short description matches Wikidata\",\"Commons link from Wikidata\",\"Wikipedia articles with LCCN identifiers\",\"Wikipedia articles with NDL identifiers\",\"Natural language processing\",\"Computational linguistics\",\n\"Speech recognition\",\"Computational fields of study\",\"Artificial intelligence\"],\"wgPageContentLanguage\":\"en\",\"wgPageContentModel\":\"wikitext\",\"wgRelevantPageName\":\"Natural_language_processing\",\"wgRelevantArticleId\":21652,\"wgIsProbablyEditable\":!0,\"wgRelevantPageIsProbablyEditable\":!0,\"wgRestrictionEdit\":[],\"wgRestrictionMove\":[],\"wgMediaViewerOnClick\":!0,\"wgMediaViewerEnabledByDefault\":!0,\"wgPopupsFlags\":10,\"wgVisualEditor\":{\"pageLanguageCode\":\"en\",\"pageLanguageDir\":\"ltr\",\"pageVariantFallbacks\":\"en\"},\"wgMFDisplayWikibaseDescriptions\":{\"search\":!0,\"nearby\":!0,\"watchlist\":!0,\"tagline\":!1},\"wgWMESchemaEditAttemptStepOversample\":!1,\"wgULSCurrentAutonym\":\"English\",\"wgNoticeProject\":\"wikipedia\",\"wgCentralAuthMobileDomain\":!1,\"wgEditSubmitButtonLabelPublish\":!0,\"wgULSPosition\":\"interlanguage\",\"wgWikibaseItemId\":\"Q30642\"};RLSTATE={\"ext.globalCssJs.user.styles\":\"ready\",\"site.styles\":\"ready\",\"noscript\":\"ready\",\"user.styles\":\"ready\",\"ext.globalCssJs.user\":\"ready\",\"user\":\n\"ready\",\"user.options\":\"loading\",\"ext.cite.styles\":\"ready\",\"ext.math.styles\":\"ready\",\"skins.vector.styles.legacy\":\"ready\",\"jquery.makeCollapsible.styles\":\"ready\",\"ext.visualEditor.desktopArticleTarget.noscript\":\"ready\",\"ext.uls.interlanguage\":\"ready\",\"ext.wikimediaBadges\":\"ready\",\"wikibase.client.init\":\"ready\"};RLPAGEMODULES=[\"ext.cite.ux-enhancements\",\"ext.math.scripts\",\"site\",\"mediawiki.page.ready\",\"jquery.makeCollapsible\",\"mediawiki.toc\",\"skins.vector.legacy.js\",\"ext.gadget.ReferenceTooltips\",\"ext.gadget.charinsert\",\"ext.gadget.extra-toolbar-buttons\",\"ext.gadget.refToolbar\",\"ext.gadget.switcher\",\"ext.centralauth.centralautologin\",\"mmv.head\",\"mmv.bootstrap.autostart\",\"ext.popups\",\"ext.visualEditor.desktopArticleTarget.init\",\"ext.visualEditor.targetLoader\",\"ext.eventLogging\",\"ext.wikimediaEvents\",\"ext.navigationTiming\",\"ext.uls.compactlinks\",\"ext.uls.interface\",\"ext.cx.eventlogging.campaigns\",\"ext.centralNotice.geoIP\",\"ext.centralNotice.startUp\"];</script>\n<script>(RLQ=window.RLQ||[]).push(function(){mw.loader.implement(\"user.options@1hzgi\",function($,jQuery,require,module){/*@nomin*/mw.user.tokens.set({\"patrolToken\":\"+\\\\\",\"watchToken\":\"+\\\\\",\"csrfToken\":\"+\\\\\"});\n});});</script>\n<link href=\"/w/load.php?lang=en&amp;modules=ext.cite.styles%7Cext.math.styles%7Cext.uls.interlanguage%7Cext.visualEditor.desktopArticleTarget.noscript%7Cext.wikimediaBadges%7Cjquery.makeCollapsible.styles%7Cskins.vector.styles.legacy%7Cwikibase.client.init&amp;only=styles&amp;skin=vector\" rel=\"stylesheet\"/>\n<script async=\"\" src=\"/w/load.php?lang=en&amp;modules=startup&amp;only=scripts&amp;raw=1&amp;skin=vector\"></script>\n<meta content=\"\" name=\"ResourceLoaderDynamicStyles\"/>\n<link href=\"/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=vector\" rel=\"stylesheet\"/>\n<meta content=\"MediaWiki 1.36.0-wmf.38\" name=\"generator\"/>\n<meta content=\"origin\" name=\"referrer\"/>\n<meta content=\"origin-when-crossorigin\" name=\"referrer\"/>\n<meta content=\"origin-when-cross-origin\" name=\"referrer\"/>\n<meta content=\"https://upload.wikimedia.org/wikipedia/commons/8/8b/Automated_online_assistant.png\" property=\"og:image\"/>\n<meta content=\"Natural language processing - Wikipedia\" property=\"og:title\"/>\n<meta content=\"website\" property=\"og:type\"/>\n<link href=\"//upload.wikimedia.org\" rel=\"preconnect\"/>\n<link href=\"//en.m.wikipedia.org/wiki/Natural_language_processing\" media=\"only screen and (max-width: 720px)\" rel=\"alternate\"/>\n<link href=\"/w/index.php?title=Natural_language_processing&amp;action=edit\" rel=\"alternate\" title=\"Edit this page\" type=\"application/x-wiki\"/>\n<link href=\"/w/index.php?title=Natural_language_processing&amp;action=edit\" rel=\"edit\" title=\"Edit this page\"/>\n<link href=\"/static/apple-touch/wikipedia.png\" rel=\"apple-touch-icon\"/>\n<link href=\"/static/favicon/wikipedia.ico\" rel=\"shortcut icon\"/>\n<link href=\"/w/opensearch_desc.php\" rel=\"search\" title=\"Wikipedia (en)\" type=\"application/opensearchdescription+xml\"/>\n<link href=\"//en.wikipedia.org/w/api.php?action=rsd\" rel=\"EditURI\" type=\"application/rsd+xml\"/>\n<link href=\"//creativecommons.org/licenses/by-sa/3.0/\" rel=\"license\"/>\n<link href=\"https://en.wikipedia.org/wiki/Natural_language_processing\" rel=\"canonical\"/>\n<link href=\"//login.wikimedia.org\" rel=\"dns-prefetch\"/>\n<link href=\"//meta.wikimedia.org\" rel=\"dns-prefetch\"/>\n</head>\n<body class=\"mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject mw-editable page-Natural_language_processing rootpage-Natural_language_processing skin-vector action-view skin-vector-legacy\"><div class=\"noprint\" id=\"mw-page-base\"></div>\n<div class=\"noprint\" id=\"mw-head-base\"></div>\n<div class=\"mw-body\" id=\"content\" role=\"main\">\n<a id=\"top\"></a>\n<div class=\"mw-body-content\" id=\"siteNotice\"><!-- CentralNotice --></div>\n<div class=\"mw-indicators mw-body-content\">\n</div>\n<h1 class=\"firstHeading\" id=\"firstHeading\">Natural language processing</h1>\n<div class=\"mw-body-content\" id=\"bodyContent\">\n<div class=\"noprint\" id=\"siteSub\">From Wikipedia, the free encyclopedia</div>\n<div id=\"contentSub\"></div>\n<div id=\"contentSub2\"></div>\n<div id=\"jump-to-nav\"></div>\n<a class=\"mw-jump-link\" href=\"#mw-head\">Jump to navigation</a>\n<a class=\"mw-jump-link\" href=\"#searchInput\">Jump to search</a>\n<div class=\"mw-content-ltr\" dir=\"ltr\" id=\"mw-content-text\" lang=\"en\"><div class=\"mw-parser-output\"><div class=\"shortdescription nomobile noexcerpt noprint searchaux\" style=\"display:none\">Field of computer science and linguistics</div>\n<div class=\"thumb tright\"><div class=\"thumbinner\" style=\"width:202px;\"><a class=\"image\" href=\"/wiki/File:Automated_online_assistant.png\"><img alt=\"\" class=\"thumbimage\" data-file-height=\"501\" data-file-width=\"400\" decoding=\"async\" height=\"251\" src=\"//upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Automated_online_assistant.png/200px-Automated_online_assistant.png\" srcset=\"//upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Automated_online_assistant.png/300px-Automated_online_assistant.png 1.5x, //upload.wikimedia.org/wikipedia/commons/8/8b/Automated_online_assistant.png 2x\" width=\"200\"/></a> <div class=\"thumbcaption\"><div class=\"magnify\"><a class=\"internal\" href=\"/wiki/File:Automated_online_assistant.png\" title=\"Enlarge\"></a></div>An <a class=\"mw-redirect\" href=\"/wiki/Automated_online_assistant\" title=\"Automated online assistant\">automated online assistant</a> providing <a href=\"/wiki/Customer_service\" title=\"Customer service\">customer service</a> on a web page, an example of an application where natural language processing is a major component.<sup class=\"reference\" id=\"cite_ref-Kongthon_1-0\"><a href=\"#cite_note-Kongthon-1\">[1]</a></sup></div></div></div>\n<p><b>Natural language processing</b> (<b>NLP</b>) is a subfield of <a href=\"/wiki/Linguistics\" title=\"Linguistics\">linguistics</a>, <a href=\"/wiki/Computer_science\" title=\"Computer science\">computer science</a>, and <a href=\"/wiki/Artificial_intelligence\" title=\"Artificial intelligence\">artificial intelligence</a> concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of <a href=\"/wiki/Natural_language\" title=\"Natural language\">natural language</a> data. The result is a computer capable of \"understanding\" the contents of documents, including the contextual nuances of the language within them. The technology can then accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves. \n</p><p>Challenges in natural language processing frequently involve <a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">speech recognition</a>, <a class=\"mw-redirect\" href=\"/wiki/Natural_language_understanding\" title=\"Natural language understanding\">natural language understanding</a>, and <a href=\"/wiki/Natural-language_generation\" title=\"Natural-language generation\">natural-language generation</a>.\n</p>\n<div aria-labelledby=\"mw-toc-heading\" class=\"toc\" id=\"toc\" role=\"navigation\"><input class=\"toctogglecheckbox\" id=\"toctogglecheckbox\" role=\"button\" style=\"display:none\" type=\"checkbox\"/><div class=\"toctitle\" dir=\"ltr\" lang=\"en\"><h2 id=\"mw-toc-heading\">Contents</h2><span class=\"toctogglespan\"><label class=\"toctogglelabel\" for=\"toctogglecheckbox\"></label></span></div>\n<ul>\n<li class=\"toclevel-1 tocsection-1\"><a href=\"#History\"><span class=\"tocnumber\">1</span> <span class=\"toctext\">History</span></a>\n<ul>\n<li class=\"toclevel-2 tocsection-2\"><a href=\"#Symbolic_NLP_(1950s_-_early_1990s)\"><span class=\"tocnumber\">1.1</span> <span class=\"toctext\">Symbolic NLP (1950s - early 1990s)</span></a></li>\n<li class=\"toclevel-2 tocsection-3\"><a href=\"#Statistical_NLP_(1990s_-_2010s)\"><span class=\"tocnumber\">1.2</span> <span class=\"toctext\">Statistical NLP (1990s - 2010s)</span></a></li>\n<li class=\"toclevel-2 tocsection-4\"><a href=\"#Neural_NLP_(present)\"><span class=\"tocnumber\">1.3</span> <span class=\"toctext\">Neural NLP (present)</span></a></li>\n</ul>\n</li>\n<li class=\"toclevel-1 tocsection-5\"><a href=\"#Methods:_Rules,_statistics,_neural_networks\"><span class=\"tocnumber\">2</span> <span class=\"toctext\">Methods: Rules, statistics, neural networks</span></a>\n<ul>\n<li class=\"toclevel-2 tocsection-6\"><a href=\"#Statistical_methods\"><span class=\"tocnumber\">2.1</span> <span class=\"toctext\">Statistical methods</span></a></li>\n<li class=\"toclevel-2 tocsection-7\"><a href=\"#Neural_networks\"><span class=\"tocnumber\">2.2</span> <span class=\"toctext\">Neural networks</span></a></li>\n</ul>\n</li>\n<li class=\"toclevel-1 tocsection-8\"><a href=\"#Common_NLP_tasks\"><span class=\"tocnumber\">3</span> <span class=\"toctext\">Common NLP tasks</span></a>\n<ul>\n<li class=\"toclevel-2 tocsection-9\"><a href=\"#Text_and_speech_processing\"><span class=\"tocnumber\">3.1</span> <span class=\"toctext\">Text and speech processing</span></a></li>\n<li class=\"toclevel-2 tocsection-10\"><a href=\"#Morphological_analysis\"><span class=\"tocnumber\">3.2</span> <span class=\"toctext\">Morphological analysis</span></a></li>\n<li class=\"toclevel-2 tocsection-11\"><a href=\"#Syntactic_analysis\"><span class=\"tocnumber\">3.3</span> <span class=\"toctext\">Syntactic analysis</span></a></li>\n<li class=\"toclevel-2 tocsection-12\"><a href=\"#Lexical_semantics_(of_individual_words_in_context)\"><span class=\"tocnumber\">3.4</span> <span class=\"toctext\">Lexical semantics (of individual words in context)</span></a></li>\n<li class=\"toclevel-2 tocsection-13\"><a href=\"#Relational_semantics_(semantics_of_individual_sentences)\"><span class=\"tocnumber\">3.5</span> <span class=\"toctext\">Relational semantics (semantics of individual sentences)</span></a></li>\n<li class=\"toclevel-2 tocsection-14\"><a href=\"#Discourse_(semantics_beyond_individual_sentences)\"><span class=\"tocnumber\">3.6</span> <span class=\"toctext\">Discourse (semantics beyond individual sentences)</span></a></li>\n<li class=\"toclevel-2 tocsection-15\"><a href=\"#Higher-level_NLP_applications\"><span class=\"tocnumber\">3.7</span> <span class=\"toctext\">Higher-level NLP applications</span></a></li>\n</ul>\n</li>\n<li class=\"toclevel-1 tocsection-16\"><a href=\"#General_tendencies_and_(possible)_future_directions\"><span class=\"tocnumber\">4</span> <span class=\"toctext\">General tendencies and (possible) future directions</span></a>\n<ul>\n<li class=\"toclevel-2 tocsection-17\"><a href=\"#Cognition_and_NLP\"><span class=\"tocnumber\">4.1</span> <span class=\"toctext\">Cognition and NLP</span></a></li>\n</ul>\n</li>\n<li class=\"toclevel-1 tocsection-18\"><a href=\"#See_also\"><span class=\"tocnumber\">5</span> <span class=\"toctext\">See also</span></a></li>\n<li class=\"toclevel-1 tocsection-19\"><a href=\"#References\"><span class=\"tocnumber\">6</span> <span class=\"toctext\">References</span></a></li>\n<li class=\"toclevel-1 tocsection-20\"><a href=\"#Further_reading\"><span class=\"tocnumber\">7</span> <span class=\"toctext\">Further reading</span></a></li>\n</ul>\n</div>\n<h2><span class=\"mw-headline\" id=\"History\">History</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=1\" title=\"Edit section: History\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\n<div class=\"hatnote navigation-not-searchable\" role=\"note\">Further information: <a href=\"/wiki/History_of_natural_language_processing\" title=\"History of natural language processing\">History of natural language processing</a></div>\n<p>Natural language processing has its roots in the 1950s. Already in 1950, <a href=\"/wiki/Alan_Turing\" title=\"Alan Turing\">Alan Turing</a> published an article titled \"<a href=\"/wiki/Computing_Machinery_and_Intelligence\" title=\"Computing Machinery and Intelligence\">Computing Machinery and Intelligence</a>\" which proposed what is now called the <a href=\"/wiki/Turing_test\" title=\"Turing test\">Turing test</a> as a criterion of intelligence, a task that involves the automated interpretation and generation of natural language, but at the time not articulated as a problem separate from artificial intelligence.\n</p>\n<h3><span id=\"Symbolic_NLP_.281950s_-_early_1990s.29\"></span><span class=\"mw-headline\" id=\"Symbolic_NLP_(1950s_-_early_1990s)\">Symbolic NLP (1950s - early 1990s)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=2\" title=\"Edit section: Symbolic NLP (1950s - early 1990s)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<p>The premise of symbolic NLP is well-summarized by <a href=\"/wiki/John_Searle\" title=\"John Searle\">John Searle</a>'s <a href=\"/wiki/Chinese_room\" title=\"Chinese room\">Chinese room</a> experiment: Given a collection of rules (e.g., a Chinese phrasebook, with questions and matching answers), the computer emulates natural language understanding (or other NLP tasks) by applying those rules to the data it is confronted with.\n</p>\n<ul><li><b>1950s</b>: The <a class=\"mw-redirect\" href=\"/wiki/Georgetown-IBM_experiment\" title=\"Georgetown-IBM experiment\">Georgetown experiment</a> in 1954 involved fully <a class=\"mw-redirect\" href=\"/wiki/Automatic_translation\" title=\"Automatic translation\">automatic translation</a> of more than sixty Russian sentences into English. The authors claimed that within three or five years, machine translation would be a solved problem.<sup class=\"reference\" id=\"cite_ref-2\"><a href=\"#cite_note-2\">[2]</a></sup> However, real progress was much slower, and after the <a href=\"/wiki/ALPAC\" title=\"ALPAC\">ALPAC report</a> in 1966, which found that ten-year-long research had failed to fulfill the expectations, funding for machine translation was dramatically reduced. Little further research in machine translation was conducted until the late 1980s when the first <a href=\"/wiki/Statistical_machine_translation\" title=\"Statistical machine translation\">statistical machine translation</a> systems were developed.</li>\n<li><b>1960s</b>: Some notably successful natural language processing systems developed in the 1960s were <a href=\"/wiki/SHRDLU\" title=\"SHRDLU\">SHRDLU</a>, a natural language system working in restricted \"<a href=\"/wiki/Blocks_world\" title=\"Blocks world\">blocks worlds</a>\" with restricted vocabularies, and <a href=\"/wiki/ELIZA\" title=\"ELIZA\">ELIZA</a>, a simulation of a <a class=\"mw-redirect\" href=\"/wiki/Rogerian_psychotherapy\" title=\"Rogerian psychotherapy\">Rogerian psychotherapist</a>, written by <a href=\"/wiki/Joseph_Weizenbaum\" title=\"Joseph Weizenbaum\">Joseph Weizenbaum</a> between 1964 and 1966. Using almost no information about human thought or emotion, ELIZA sometimes provided a startlingly human-like interaction. When the \"patient\" exceeded the very small knowledge base, ELIZA might provide a generic response, for example, responding to \"My head hurts\" with \"Why do you say your head hurts?\".</li>\n<li><b>1970s</b>: During the 1970s, many programmers began to write \"conceptual <a href=\"/wiki/Ontology_(information_science)\" title=\"Ontology (information science)\">ontologies</a>\", which structured real-world information into computer-understandable data. Examples are MARGIE (Schank, 1975), SAM (Cullingford, 1978), PAM (Wilensky, 1978), TaleSpin (Meehan, 1976), QUALM (Lehnert, 1977), Politics (Carbonell, 1979), and Plot Units (Lehnert 1981). During this time, the first many <a class=\"mw-redirect\" href=\"/wiki/Chatterbots\" title=\"Chatterbots\">chatterbots</a> were written (e.g., <a href=\"/wiki/PARRY\" title=\"PARRY\">PARRY</a>).</li>\n<li><b>1980s</b>: The 1980s and early 1990s mark the hey-day of symbolic methods in NLP. Focus areas of the time included research on rule-based parsing (e.g., the development of <a href=\"/wiki/Head-driven_phrase_structure_grammar\" title=\"Head-driven phrase structure grammar\">HPSG</a> as a computational operationalization of <a href=\"/wiki/Generative_grammar\" title=\"Generative grammar\">generative grammar</a>), morphology (e.g., two-level morphology<sup class=\"reference\" id=\"cite_ref-3\"><a href=\"#cite_note-3\">[3]</a></sup>), semantics (e.g., <a href=\"/wiki/Lesk_algorithm\" title=\"Lesk algorithm\">Lesk algorithm</a>), reference (e.g., within Centering Theory<sup class=\"reference\" id=\"cite_ref-4\"><a href=\"#cite_note-4\">[4]</a></sup>) and other areas of natural language understanding (e.g., in the <a href=\"/wiki/Rhetorical_structure_theory\" title=\"Rhetorical structure theory\">Rhetorical Structure Theory</a>). Other lines of research were continued, e.g., the development of chatterbots with <a href=\"/wiki/Racter\" title=\"Racter\">Racter</a> and <a href=\"/wiki/Jabberwacky\" title=\"Jabberwacky\">Jabberwacky</a>. An important development (that eventually led to the statistical turn in the 1990s) was the rising importance of quantitative evaluation in this period.<sup class=\"reference\" id=\"cite_ref-5\"><a href=\"#cite_note-5\">[5]</a></sup></li></ul>\n<h3><span id=\"Statistical_NLP_.281990s_-_2010s.29\"></span><span class=\"mw-headline\" id=\"Statistical_NLP_(1990s_-_2010s)\">Statistical NLP (1990s - 2010s)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=3\" title=\"Edit section: Statistical NLP (1990s - 2010s)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<p>Up to the 1980s, most natural language processing systems were based on complex sets of hand-written rules. Starting in the late 1980s, however, there was a revolution in natural language processing with the introduction of <a href=\"/wiki/Machine_learning\" title=\"Machine learning\">machine learning</a> algorithms for language processing. This was due to both the steady increase in computational power (see <a href=\"/wiki/Moore%27s_law\" title=\"Moore's law\">Moore's law</a>) and the gradual lessening of the dominance of <a href=\"/wiki/Noam_Chomsky\" title=\"Noam Chomsky\">Chomskyan</a> theories of linguistics (e.g. <a href=\"/wiki/Transformational_grammar\" title=\"Transformational grammar\">transformational grammar</a>), whose theoretical underpinnings discouraged the sort of <a href=\"/wiki/Corpus_linguistics\" title=\"Corpus linguistics\">corpus linguistics</a> that underlies the machine-learning approach to language processing.<sup class=\"reference\" id=\"cite_ref-6\"><a href=\"#cite_note-6\">[6]</a></sup>\n</p>\n<ul><li><b>1990s</b>: Many of the notable early successes on statistical methods in NLP occurred in the field of <a href=\"/wiki/Machine_translation\" title=\"Machine translation\">machine translation</a>, due especially to work at IBM Research. These systems were able to take advantage of existing multilingual <a href=\"/wiki/Text_corpus\" title=\"Text corpus\">textual corpora</a> that had been produced by the <a href=\"/wiki/Parliament_of_Canada\" title=\"Parliament of Canada\">Parliament of Canada</a> and the <a href=\"/wiki/European_Union\" title=\"European Union\">European Union</a> as a result of laws calling for the translation of all governmental proceedings into all official languages of the corresponding systems of government. However, most other systems depended on corpora specifically developed for the tasks implemented by these systems, which was (and often continues to be) a major limitation in the success of these systems. As a result, a great deal of research has gone into methods of more effectively learning from limited amounts of data.</li>\n<li><b>2000s</b>: With the growth of the web, increasing amounts of raw (unannotated) language data has become available since the mid-1990s. Research has thus increasingly focused on <a href=\"/wiki/Unsupervised_learning\" title=\"Unsupervised learning\">unsupervised</a> and <a href=\"/wiki/Semi-supervised_learning\" title=\"Semi-supervised learning\">semi-supervised learning</a> algorithms. Such algorithms can learn from data that has not been hand-annotated with the desired answers or using a combination of annotated and non-annotated data. Generally, this task is much more difficult than <a href=\"/wiki/Supervised_learning\" title=\"Supervised learning\">supervised learning</a>, and typically produces less accurate results for a given amount of input data. However, there is an enormous amount of non-annotated data available (including, among other things, the entire content of the <a href=\"/wiki/World_Wide_Web\" title=\"World Wide Web\">World Wide Web</a>), which can often make up for the inferior results if the algorithm used has a low enough <a href=\"/wiki/Time_complexity\" title=\"Time complexity\">time complexity</a> to be practical.</li></ul>\n<h3><span id=\"Neural_NLP_.28present.29\"></span><span class=\"mw-headline\" id=\"Neural_NLP_(present)\">Neural NLP (present)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=4\" title=\"Edit section: Neural NLP (present)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<p>In the 2010s, <a class=\"mw-redirect\" href=\"/wiki/Representation_learning\" title=\"Representation learning\">representation learning</a> and <a href=\"/wiki/Deep_learning\" title=\"Deep learning\">deep neural network</a>-style machine learning methods became widespread in natural language processing, due in part to a flurry of results showing that such techniques<sup class=\"reference\" id=\"cite_ref-goldberg:nnlp17_7-0\"><a href=\"#cite_note-goldberg:nnlp17-7\">[7]</a></sup><sup class=\"reference\" id=\"cite_ref-goodfellow:book16_8-0\"><a href=\"#cite_note-goodfellow:book16-8\">[8]</a></sup> can achieve state-of-the-art results in many natural language tasks, for example in language modeling,<sup class=\"reference\" id=\"cite_ref-jozefowicz:lm16_9-0\"><a href=\"#cite_note-jozefowicz:lm16-9\">[9]</a></sup> parsing,<sup class=\"reference\" id=\"cite_ref-choe:emnlp16_10-0\"><a href=\"#cite_note-choe:emnlp16-10\">[10]</a></sup><sup class=\"reference\" id=\"cite_ref-vinyals:nips15_11-0\"><a href=\"#cite_note-vinyals:nips15-11\">[11]</a></sup> and many others.\n</p>\n<h2><span id=\"Methods:_Rules.2C_statistics.2C_neural_networks\"></span><span class=\"mw-headline\" id=\"Methods:_Rules,_statistics,_neural_networks\">Methods: Rules, statistics, neural networks<span class=\"anchor\" id=\"Statistical_natural_language_processing_(SNLP)\"></span></span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=5\" title=\"Edit section: Methods: Rules, statistics, neural networks\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\n<p>In the early days, many language-processing systems were designed by symbolic methods, i.e., the hand-coding of a set of rules, coupled with a dictionary lookup:<sup class=\"reference\" id=\"cite_ref-winograd:shrdlu71_12-0\"><a href=\"#cite_note-winograd:shrdlu71-12\">[12]</a></sup><sup class=\"reference\" id=\"cite_ref-schank77_13-0\"><a href=\"#cite_note-schank77-13\">[13]</a></sup> such as by writing grammars or devising heuristic rules for <a href=\"/wiki/Stemming\" title=\"Stemming\">stemming</a>.\n</p><p>More recent systems based on <a href=\"/wiki/Machine_learning\" title=\"Machine learning\">machine-learning</a> algorithms have many advantages over hand-produced rules: \n</p>\n<ul><li>The learning procedures used during machine learning automatically focus on the most common cases, whereas when writing rules by hand it is often not at all obvious where the effort should be directed.</li>\n<li>Automatic learning procedures can make use of statistical inference algorithms to produce models that are robust to unfamiliar input (e.g. containing words or structures that have not been seen before) and to erroneous input (e.g. with misspelled words or words accidentally omitted). Generally, handling such input gracefully with handwritten rules, or, more generally, creating systems of handwritten rules that make soft decisions, is extremely difficult, error-prone and time-consuming.</li>\n<li>Systems based on automatically learning the rules can be made more accurate simply by supplying more input data. However, systems based on handwritten rules can only be made more accurate by increasing the complexity of the rules, which is a much more difficult task. In particular, there is a limit to the complexity of systems based on handwritten rules, beyond which the systems become more and more unmanageable. However, creating more data to input to machine-learning systems simply requires a corresponding increase in the number of man-hours worked, generally without significant increases in the complexity of the annotation process.</li></ul>\n<p>Despite the popularity of machine learning in NLP research, symbolic methods are still (2020) commonly used\n</p>\n<ul><li>when the amount of training data is insufficient to successfully apply machine learning methods, e.g., for the machine translation of low-resource languages such as provided by the <a href=\"/wiki/Apertium\" title=\"Apertium\">Apertium</a> system,</li>\n<li>for preprocessing in NLP pipelines, e.g., <a class=\"mw-redirect\" href=\"/wiki/Tokenization_(lexical_analysis)\" title=\"Tokenization (lexical analysis)\">tokenization</a>, or</li>\n<li>for postprocessing and transforming the output of NLP pipelines, e.g., for <a href=\"/wiki/Knowledge_extraction\" title=\"Knowledge extraction\">knowledge extraction</a> from syntactic parses.</li></ul>\n<h3><span class=\"mw-headline\" id=\"Statistical_methods\">Statistical methods</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=6\" title=\"Edit section: Statistical methods\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<p>Since the so-called \"statistical revolution\"<sup class=\"reference\" id=\"cite_ref-johnson:eacl:ilcl09_14-0\"><a href=\"#cite_note-johnson:eacl:ilcl09-14\">[14]</a></sup><sup class=\"reference\" id=\"cite_ref-resnik:langlog11_15-0\"><a href=\"#cite_note-resnik:langlog11-15\">[15]</a></sup> in the late 1980s and mid-1990s, much natural language processing research has relied heavily on machine learning. The machine-learning paradigm calls instead for using <a href=\"/wiki/Statistical_inference\" title=\"Statistical inference\">statistical inference</a> to automatically learn such rules through the analysis of large <i><a href=\"/wiki/Text_corpus\" title=\"Text corpus\">corpora</a></i> (the plural form of <i>corpus</i>, is a set of documents, possibly with human or computer annotations) of typical real-world examples.\n</p><p>Many different classes of machine-learning algorithms have been applied to natural-language-processing tasks. These algorithms take as input a large set of \"features\" that are generated from the input data. Increasingly, however, research has focused on <a class=\"mw-redirect\" href=\"/wiki/Statistical_models\" title=\"Statistical models\">statistical models</a>, which make soft, <a class=\"mw-redirect\" href=\"/wiki/Probabilistic\" title=\"Probabilistic\">probabilistic</a> decisions based on attaching <a class=\"mw-redirect\" href=\"/wiki/Real-valued\" title=\"Real-valued\">real-valued</a> weights to each input feature. Such models have the advantage that they can express the relative certainty of many different possible answers rather than only one, producing more reliable results when such a model is included as a component of a larger system.\n</p><p>Some of the earliest-used machine learning algorithms, such as <a href=\"/wiki/Decision_tree\" title=\"Decision tree\">decision trees</a>, produced systems of hard if-then rules similar to existing hand-written rules. However, <a class=\"mw-redirect\" href=\"/wiki/Part_of_speech_tagging\" title=\"Part of speech tagging\">part-of-speech tagging</a> introduced the use of <a class=\"mw-redirect\" href=\"/wiki/Hidden_Markov_models\" title=\"Hidden Markov models\">hidden Markov models</a> to natural language processing, and increasingly, research has focused on <a class=\"mw-redirect\" href=\"/wiki/Statistical_models\" title=\"Statistical models\">statistical models</a>, which make soft, <a class=\"mw-redirect\" href=\"/wiki/Probabilistic\" title=\"Probabilistic\">probabilistic</a> decisions based on attaching <a class=\"mw-redirect\" href=\"/wiki/Real-valued\" title=\"Real-valued\">real-valued</a> weights to the features making up the input data. The <a href=\"/wiki/Cache_language_model\" title=\"Cache language model\">cache language models</a> upon which many <a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">speech recognition</a> systems now rely are examples of such statistical models. Such models are generally more robust when given unfamiliar input, especially input that contains errors (as is very common for real-world data), and produce more reliable results when integrated into a larger system comprising multiple subtasks.\n</p><p>Since the neural turn, statistical methods in NLP research have been largely replaced by neural networks. However, they continue to be relevant for contexts in which statistical interpretability and transparency is required.\n</p>\n<h3><span class=\"mw-headline\" id=\"Neural_networks\">Neural networks</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=7\" title=\"Edit section: Neural networks\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<div class=\"hatnote navigation-not-searchable\" role=\"note\">Further information: <a href=\"/wiki/Artificial_neural_network\" title=\"Artificial neural network\">Artificial neural network</a></div>\n<p>A major drawback of statistical methods is that they require elaborate feature engineering. Since 2015,<sup class=\"reference\" id=\"cite_ref-16\"><a href=\"#cite_note-16\">[16]</a></sup> the field has thus largely abandoned statistical methods and shifted to <a href=\"/wiki/Neural_network\" title=\"Neural network\">neural networks</a> for machine learning. Popular techniques include the use of <a href=\"/wiki/Word_embedding\" title=\"Word embedding\">word embeddings</a> to capture semantic properties of words, and an increase in end-to-end learning of a higher-level task (e.g., question answering) instead of relying on a pipeline of separate intermediate tasks (e.g., part-of-speech tagging and dependency parsing). In some areas, this shift has entailed substantial changes in how NLP systems are designed, such that deep neural network-based approaches may be viewed as a new paradigm distinct from statistical natural language processing. For instance, the term <i><a href=\"/wiki/Neural_machine_translation\" title=\"Neural machine translation\">neural machine translation</a></i> (NMT) emphasizes the fact that deep learning-based approaches to machine translation directly learn <a href=\"/wiki/Seq2seq\" title=\"Seq2seq\">sequence-to-sequence</a> transformations, obviating the need for intermediate steps such as word alignment and language modeling that was used in <a href=\"/wiki/Statistical_machine_translation\" title=\"Statistical machine translation\">statistical machine translation</a> (SMT). Latest works tend to use non-technical structure of a given task to build proper neural network.<sup class=\"reference\" id=\"cite_ref-17\"><a href=\"#cite_note-17\">[17]</a></sup>\n</p>\n<h2><span class=\"mw-headline\" id=\"Common_NLP_tasks\">Common NLP tasks</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=8\" title=\"Edit section: Common NLP tasks\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\n<p>The following is a list of some of the most commonly researched tasks in natural language processing. Some of these tasks have direct real-world applications, while others more commonly serve as subtasks that are used to aid in solving larger tasks.\n</p><p>Though natural language processing tasks are closely intertwined, they can be subdivided into categories for convenience. A coarse division is given below.\n</p>\n<h3><span class=\"mw-headline\" id=\"Text_and_speech_processing\">Text and speech processing</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=9\" title=\"Edit section: Text and speech processing\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<dl><dt><a href=\"/wiki/Optical_character_recognition\" title=\"Optical character recognition\">Optical character recognition</a> (OCR)</dt>\n<dd>Given an image representing printed text, determine the corresponding text.</dd></dl>\n<dl><dt><a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">Speech recognition</a></dt>\n<dd>Given a sound clip of a person or people speaking, determine the textual representation of the speech. This is the opposite of <a class=\"mw-redirect\" href=\"/wiki/Text_to_speech\" title=\"Text to speech\">text to speech</a> and is one of the extremely difficult problems colloquially termed \"<a href=\"/wiki/AI-complete\" title=\"AI-complete\">AI-complete</a>\" (see above). In <a class=\"mw-redirect\" href=\"/wiki/Natural_speech\" title=\"Natural speech\">natural speech</a> there are hardly any pauses between successive words, and thus <a href=\"/wiki/Speech_segmentation\" title=\"Speech segmentation\">speech segmentation</a> is a necessary subtask of speech recognition (see below). In most spoken languages, the sounds representing successive letters blend into each other in a process termed <a href=\"/wiki/Coarticulation\" title=\"Coarticulation\">coarticulation</a>, so the conversion of the <a href=\"/wiki/Analog_signal\" title=\"Analog signal\">analog signal</a> to discrete characters can be a very difficult process. Also, given that words in the same language are spoken by people with different accents, the speech recognition software must be able to recognize the wide variety of input as being identical to each other in terms of its textual equivalent.</dd>\n<dt><a href=\"/wiki/Speech_segmentation\" title=\"Speech segmentation\">Speech segmentation</a></dt>\n<dd>Given a sound clip of a person or people speaking, separate it into words. A subtask of <a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">speech recognition</a> and typically grouped with it.</dd></dl>\n<dl><dt><a class=\"mw-redirect\" href=\"/wiki/Text-to-speech\" title=\"Text-to-speech\">Text-to-speech</a></dt>\n<dd>Given a text, transform those units and produce a spoken representation. Text-to-speech can be used to aid the visually impaired.<sup class=\"reference\" id=\"cite_ref-18\"><a href=\"#cite_note-18\">[18]</a></sup></dd></dl>\n<dl><dt><a class=\"mw-redirect\" href=\"/wiki/Word_segmentation\" title=\"Word segmentation\">Word segmentation</a> (<a class=\"mw-redirect\" href=\"/wiki/Tokenization_(lexical_analysis)\" title=\"Tokenization (lexical analysis)\">Tokenization</a>)</dt>\n<dd>Separate a chunk of continuous text into separate words. For a language like <a href=\"/wiki/English_language\" title=\"English language\">English</a>, this is fairly trivial, since words are usually separated by spaces. However, some written languages like <a href=\"/wiki/Chinese_language\" title=\"Chinese language\">Chinese</a>, <a href=\"/wiki/Japanese_language\" title=\"Japanese language\">Japanese</a> and <a href=\"/wiki/Thai_language\" title=\"Thai language\">Thai</a> do not mark word boundaries in such a fashion, and in those languages text segmentation is a significant task requiring knowledge of the <a href=\"/wiki/Vocabulary\" title=\"Vocabulary\">vocabulary</a> and <a href=\"/wiki/Morphology_(linguistics)\" title=\"Morphology (linguistics)\">morphology</a> of words in the language. Sometimes this process is also used in cases like <a class=\"mw-redirect\" href=\"/wiki/Bag_of_words\" title=\"Bag of words\">bag of words</a> (BOW) creation in data mining.</dd></dl>\n<h3><span class=\"mw-headline\" id=\"Morphological_analysis\">Morphological analysis</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=10\" title=\"Edit section: Morphological analysis\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<dl><dt><a href=\"/wiki/Lemmatisation\" title=\"Lemmatisation\">Lemmatization</a></dt>\n<dd>The task of removing inflectional endings only and to return the base dictionary form of a word which is also known as a lemma. Lemmatization is another technique for reducing words to their normalized form. But in this case, the transformation actually uses a dictionary to map words to their actual form.<sup class=\"reference\" id=\"cite_ref-19\"><a href=\"#cite_note-19\">[19]</a></sup></dd>\n<dt><a href=\"/wiki/Morphology_(linguistics)\" title=\"Morphology (linguistics)\">Morphological segmentation</a></dt>\n<dd>Separate words into individual <a href=\"/wiki/Morpheme\" title=\"Morpheme\">morphemes</a> and identify the class of the morphemes. The difficulty of this task depends greatly on the complexity of the <a href=\"/wiki/Morphology_(linguistics)\" title=\"Morphology (linguistics)\">morphology</a> (<i>i.e.</i>, the structure of words) of the language being considered. <a href=\"/wiki/English_language\" title=\"English language\">English</a> has fairly simple morphology, especially <a class=\"mw-redirect\" href=\"/wiki/Inflectional_morphology\" title=\"Inflectional morphology\">inflectional morphology</a>, and thus it is often possible to ignore this task entirely and simply model all possible forms of a word (<i>e.g.</i>, \"open, opens, opened, opening\") as separate words. In languages such as <a href=\"/wiki/Turkish_language\" title=\"Turkish language\">Turkish</a> or <a href=\"/wiki/Meitei_language\" title=\"Meitei language\">Meitei</a>,<sup class=\"reference\" id=\"cite_ref-20\"><a href=\"#cite_note-20\">[20]</a></sup> a highly <a href=\"/wiki/Agglutination\" title=\"Agglutination\">agglutinated</a> Indian language, however, such an approach is not possible, as each dictionary entry has thousands of possible word forms.</dd>\n<dt><a href=\"/wiki/Part-of-speech_tagging\" title=\"Part-of-speech tagging\">Part-of-speech tagging</a></dt>\n<dd>Given a sentence, determine the <a href=\"/wiki/Part_of_speech\" title=\"Part of speech\">part of speech</a> (POS) for each word. Many words, especially common ones, can serve as multiple <a class=\"mw-redirect\" href=\"/wiki/Parts_of_speech\" title=\"Parts of speech\">parts of speech</a>. For example, \"book\" can be a <a href=\"/wiki/Noun\" title=\"Noun\">noun</a> (\"the book on the table\") or <a href=\"/wiki/Verb\" title=\"Verb\">verb</a> (\"to book a flight\"); \"set\" can be a <a href=\"/wiki/Noun\" title=\"Noun\">noun</a>, <a href=\"/wiki/Verb\" title=\"Verb\">verb</a> or <a href=\"/wiki/Adjective\" title=\"Adjective\">adjective</a>; and \"out\" can be any of at least five different parts of speech.</dd></dl>\n<dl><dt><a href=\"/wiki/Stemming\" title=\"Stemming\">Stemming</a></dt>\n<dd>The process of reducing inflected (or sometimes derived) words to a base form (<i>e.g.</i>, \"close\" will be the root for \"closed\", \"closing\", \"close\", \"closer\" etc.). Stemming yields similar results as lemmatization, but does so on grounds of rules, not a dictionary.</dd></dl>\n<h3><span class=\"mw-headline\" id=\"Syntactic_analysis\">Syntactic analysis</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=11\" title=\"Edit section: Syntactic analysis\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<dl><dt><a href=\"/wiki/Grammar_induction\" title=\"Grammar induction\">Grammar induction</a><sup class=\"reference\" id=\"cite_ref-21\"><a href=\"#cite_note-21\">[21]</a></sup></dt>\n<dd>Generate a <a href=\"/wiki/Formal_grammar\" title=\"Formal grammar\">formal grammar</a> that describes a language's syntax.</dd>\n<dt><a class=\"mw-redirect\" href=\"/wiki/Sentence_breaking\" title=\"Sentence breaking\">Sentence breaking</a> (also known as \"<a href=\"/wiki/Sentence_boundary_disambiguation\" title=\"Sentence boundary disambiguation\">sentence boundary disambiguation</a>\")</dt>\n<dd>Given a chunk of text, find the sentence boundaries. Sentence boundaries are often marked by <a href=\"/wiki/Full_stop\" title=\"Full stop\">periods</a> or other <a class=\"mw-redirect\" href=\"/wiki/Punctuation_mark\" title=\"Punctuation mark\">punctuation marks</a>, but these same characters can serve other purposes (<i>e.g.</i>, marking <a href=\"/wiki/Abbreviation\" title=\"Abbreviation\">abbreviations</a>).</dd>\n<dt><a href=\"/wiki/Parsing\" title=\"Parsing\">Parsing</a></dt>\n<dd>Determine the <a href=\"/wiki/Parse_tree\" title=\"Parse tree\">parse tree</a> (grammatical analysis) of a given sentence. The <a href=\"/wiki/Grammar\" title=\"Grammar\">grammar</a> for <a href=\"/wiki/Natural_language\" title=\"Natural language\">natural languages</a> is <a class=\"mw-redirect\" href=\"/wiki/Ambiguous\" title=\"Ambiguous\">ambiguous</a> and typical sentences have multiple possible analyses: perhaps surprisingly, for a typical sentence there may be thousands of potential parses (most of which will seem completely nonsensical to a human). There are two primary types of parsing: <i>dependency parsing</i> and <i>constituency parsing</i>. Dependency parsing focuses on the relationships between words in a sentence (marking things like primary objects and predicates), whereas constituency parsing focuses on building out the parse tree using a <a href=\"/wiki/Probabilistic_context-free_grammar\" title=\"Probabilistic context-free grammar\">probabilistic context-free grammar</a> (PCFG) (see also <i><a href=\"/wiki/Stochastic_grammar\" title=\"Stochastic grammar\">stochastic grammar</a></i>).</dd></dl>\n<h3><span id=\"Lexical_semantics_.28of_individual_words_in_context.29\"></span><span class=\"mw-headline\" id=\"Lexical_semantics_(of_individual_words_in_context)\">Lexical semantics (of individual words in context)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=12\" title=\"Edit section: Lexical semantics (of individual words in context)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<dl><dt><a href=\"/wiki/Lexical_semantics\" title=\"Lexical semantics\">Lexical semantics</a></dt>\n<dd>What is the computational meaning of individual words in context?</dd>\n<dt><a href=\"/wiki/Distributional_semantics\" title=\"Distributional semantics\">Distributional semantics</a></dt>\n<dd>How can we learn semantic representations from data?</dd>\n<dt><a class=\"mw-redirect\" href=\"/wiki/Named_entity_recognition\" title=\"Named entity recognition\">Named entity recognition</a> (NER)</dt>\n<dd>Given a stream of text, determine which items in the text map to proper names, such as people or places, and what the type of each such name is (e.g. person, location, organization). Although <a href=\"/wiki/Capitalization\" title=\"Capitalization\">capitalization</a> can aid in recognizing named entities in languages such as English, this information cannot aid in determining the type of <a href=\"/wiki/Named_entity\" title=\"Named entity\">named entity</a>, and in any case, is often inaccurate or insufficient. For example, the first letter of a sentence is also capitalized, and named entities often span several words, only some of which are capitalized. Furthermore, many other languages in non-Western scripts (e.g. <a href=\"/wiki/Chinese_language\" title=\"Chinese language\">Chinese</a> or <a class=\"mw-redirect\" href=\"/wiki/Arabic_language\" title=\"Arabic language\">Arabic</a>) do not have any capitalization at all, and even languages with capitalization may not consistently use it to distinguish names. For example, <a href=\"/wiki/German_language\" title=\"German language\">German</a> capitalizes all <a href=\"/wiki/Noun\" title=\"Noun\">nouns</a>, regardless of whether they are names, and <a href=\"/wiki/French_language\" title=\"French language\">French</a> and <a href=\"/wiki/Spanish_language\" title=\"Spanish language\">Spanish</a> do not capitalize names that serve as <a href=\"/wiki/Adjective\" title=\"Adjective\">adjectives</a>.</dd></dl>\n<dl><dt><a href=\"/wiki/Sentiment_analysis\" title=\"Sentiment analysis\">Sentiment analysis</a> (see also <a href=\"/wiki/Multimodal_sentiment_analysis\" title=\"Multimodal sentiment analysis\">Multimodal sentiment analysis</a>)</dt>\n<dd>Extract subjective information usually from a set of documents, often using online reviews to determine \"polarity\" about specific objects. It is especially useful for identifying trends of public opinion in social media, for marketing.</dd></dl>\n<dl><dt></dt><dl><dt><a href=\"/wiki/Terminology_extraction\" title=\"Terminology extraction\">Terminology extraction</a></dt></dl>\n<dd>The goal of terminology extraction is to automatically extract relevant terms from a given corpus.</dd>\n<dt><a class=\"mw-redirect\" href=\"/wiki/Word_sense_disambiguation\" title=\"Word sense disambiguation\">Word sense disambiguation</a></dt>\n<dd>Many words have more than one <a class=\"mw-redirect\" href=\"/wiki/Meaning_(linguistics)\" title=\"Meaning (linguistics)\">meaning</a>; we have to select the meaning which makes the most sense in context. For this problem, we are typically given a list of words and associated word senses, e.g. from a dictionary or an online resource such as <a href=\"/wiki/WordNet\" title=\"WordNet\">WordNet</a>.</dd></dl>\n<h3><span id=\"Relational_semantics_.28semantics_of_individual_sentences.29\"></span><span class=\"mw-headline\" id=\"Relational_semantics_(semantics_of_individual_sentences)\">Relational semantics (semantics of individual sentences)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=13\" title=\"Edit section: Relational semantics (semantics of individual sentences)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<dl><dt><a href=\"/wiki/Relationship_extraction\" title=\"Relationship extraction\">Relationship extraction</a></dt>\n<dd>Given a chunk of text, identify the relationships among named entities (e.g. who is married to whom).</dd>\n<dt><a href=\"/wiki/Semantic_parsing\" title=\"Semantic parsing\">Semantic parsing</a></dt>\n<dd>Given a piece of text (typically a sentence), produce a formal representation of its semantics, either as a graph (e.g., in <a href=\"/wiki/Abstract_Meaning_Representation\" title=\"Abstract Meaning Representation\">AMR parsing</a>) or in accordance with a logical formalism (e.g., in <a href=\"/wiki/Discourse_representation_theory\" title=\"Discourse representation theory\">DRT parsing</a>). This challenge typically includes aspects of several more elementary NLP tasks from semantics (e.g., semantic role labelling, word sense disambiguation) and can be extended to include full-fledged discourse analysis (e.g., discourse analysis, coreference; see <a href=\"#Natural_language_understanding\">Natural language understanding</a> below).</dd>\n<dt><a href=\"/wiki/Semantic_role_labeling\" title=\"Semantic role labeling\">Semantic role labelling</a> (see also implicit semantic role labelling below)</dt>\n<dd>Given a single sentence, identify and disambiguate semantic predicates (e.g., verbal <a href=\"/wiki/Frame_semantics_(linguistics)\" title=\"Frame semantics (linguistics)\">frames</a>), then identify and classify the frame elements (<a class=\"mw-redirect\" href=\"/wiki/Semantic_roles\" title=\"Semantic roles\">semantic roles</a>).</dd></dl>\n<h3><span id=\"Discourse_.28semantics_beyond_individual_sentences.29\"></span><span class=\"mw-headline\" id=\"Discourse_(semantics_beyond_individual_sentences)\">Discourse (semantics beyond individual sentences)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=14\" title=\"Edit section: Discourse (semantics beyond individual sentences)\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<dl><dt><a href=\"/wiki/Coreference\" title=\"Coreference\">Coreference resolution</a></dt>\n<dd>Given a sentence or larger chunk of text, determine which words (\"mentions\") refer to the same objects (\"entities\"). <a class=\"mw-redirect\" href=\"/wiki/Anaphora_resolution\" title=\"Anaphora resolution\">Anaphora resolution</a> is a specific example of this task, and is specifically concerned with matching up <a href=\"/wiki/Pronoun\" title=\"Pronoun\">pronouns</a> with the nouns or names to which they refer. The more general task of coreference resolution also includes identifying so-called \"bridging relationships\" involving <a href=\"/wiki/Referring_expression\" title=\"Referring expression\">referring expressions</a>. For example, in a sentence such as \"He entered John's house through the front door\", \"the front door\" is a referring expression and the bridging relationship to be identified is the fact that the door being referred to is the front door of John's house (rather than of some other structure that might also be referred to).</dd>\n<dt><a href=\"/wiki/Discourse_analysis\" title=\"Discourse analysis\">Discourse analysis</a></dt>\n<dd>This rubric includes several related tasks. One task is discourse parsing, i.e., identifying the <a href=\"/wiki/Discourse\" title=\"Discourse\">discourse</a> structure of a connected text, i.e. the nature of the discourse relationships between sentences (e.g. elaboration, explanation, contrast). Another possible task is recognizing and classifying the <a href=\"/wiki/Speech_act\" title=\"Speech act\">speech acts</a> in a chunk of text (e.g. yes-no question, content question, statement, assertion, etc.).</dd></dl>\n<dl><dt>Implicit semantic role labelling</dt>\n<dd>Given a single sentence, identify and disambiguate semantic predicates (e.g., verbal <a href=\"/wiki/Frame_semantics_(linguistics)\" title=\"Frame semantics (linguistics)\">frames</a>) and their explicit semantic roles in the current sentence (see <a href=\"#Semantic_role_labelling\">Semantic role labelling</a> above). Then, identify semantic roles that are not explicitly realized in the current sentence, classify them into arguments that are explicitly realized elsewhere in the text and those that are not specified, and resolve the former against the local text. A closely related task is zero anaphora resolution, i.e., the extension of coreference resolution to <a href=\"/wiki/Pro-drop_language\" title=\"Pro-drop language\">pro-drop languages</a>.</dd></dl>\n<dl><dt><a href=\"/wiki/Textual_entailment\" title=\"Textual entailment\">Recognizing textual entailment</a></dt>\n<dd>Given two text fragments, determine if one being true entails the other, entails the other's negation, or allows the other to be either true or false.<sup class=\"reference\" id=\"cite_ref-rte:11_22-0\"><a href=\"#cite_note-rte:11-22\">[22]</a></sup></dd></dl>\n<dl><dt><a class=\"mw-redirect\" href=\"/wiki/Topic_segmentation\" title=\"Topic segmentation\">Topic segmentation</a> and recognition</dt>\n<dd>Given a chunk of text, separate it into segments each of which is devoted to a topic, and identify the topic of the segment.</dd></dl>\n<dl><dt><a href=\"/wiki/Argument_mining\" title=\"Argument mining\">Argument mining</a></dt>\n<dd>The goal of argument mining is the automatic extraction and identification of argumentative structures from <a href=\"/wiki/Natural_language\" title=\"Natural language\">natural language</a> text with the aid of computer programs. <sup class=\"reference\" id=\"cite_ref-23\"><a href=\"#cite_note-23\">[23]</a></sup> Such argumentative structures include the premise, conclusions, the <a class=\"mw-redirect\" href=\"/wiki/Argument_scheme\" title=\"Argument scheme\">argument scheme</a> and the relationship between the main and subsidiary argument, or the main and counter-argument within discourse. <sup class=\"reference\" id=\"cite_ref-24\"><a href=\"#cite_note-24\">[24]</a></sup><sup class=\"reference\" id=\"cite_ref-25\"><a href=\"#cite_note-25\">[25]</a></sup></dd></dl>\n<h3><span class=\"mw-headline\" id=\"Higher-level_NLP_applications\">Higher-level NLP applications</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=15\" title=\"Edit section: Higher-level NLP applications\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<dl><dt><a href=\"/wiki/Automatic_summarization\" title=\"Automatic summarization\">Automatic summarization</a> (text summarization)</dt>\n<dd>Produce a readable summary of a chunk of text. Often used to provide summaries of the text of a known type, such as research papers, articles in the financial section of a newspaper.</dd>\n<dt>Book generation</dt>\n<dd>Not an NLP task proper but an extension of natural language generation and other NLP tasks is the creation of full-fledged books. The first machine-generated book was created by a rule-based system in 1984 (Racter, <i>The policeman's beard is half-constructed</i>).<sup class=\"reference\" id=\"cite_ref-26\"><a href=\"#cite_note-26\">[26]</a></sup> The first published work by a neural network was published in 2018, <i><a href=\"/wiki/1_the_Road\" title=\"1 the Road\">1 the Road</a></i>, marketed as a novel, contains sixty million words. Both these systems are basically elaborate but non-sensical (semantics-free) <a href=\"/wiki/Language_model\" title=\"Language model\">language models</a>. The first machine-generated science book was published in 2019 (Beta Writer, <i>Lithium-Ion Batteries</i>, Springer, Cham).<sup class=\"reference\" id=\"cite_ref-27\"><a href=\"#cite_note-27\">[27]</a></sup> Unlike <i>Racter</i> and <i>1 the Road</i>, this is grounded on factual knowledge and based on text summarization.</dd>\n<dt><a href=\"/wiki/Dialogue_system\" title=\"Dialogue system\">Dialogue management</a></dt>\n<dd>Computer systems intended to converse with a human.</dd>\n<dt><a href=\"/wiki/Document_AI\" title=\"Document AI\">Document AI</a></dt>\n<dd>A Document AI platform sits on top of the NLP technology enabling users with no prior experience of artificial intelligence, machine learning or NLP to quickly train a computer to extract the specific data they need from different document types. NLP-powered Document AI enables non-technical teams to quickly access information hidden in documents, for example, lawyers, business analysts and accountants.<sup class=\"reference\" id=\"cite_ref-28\"><a href=\"#cite_note-28\">[28]</a></sup></dd>\n<dt><span id=\"Grammatical_error_correction\">Grammatical error correction</span></dt>\n<dd>Grammatical error detection and correction involves a great band-width of problems on all levels of linguistic analysis (phonology/orthography, morphology, syntax, semantics, pragmatics). Grammatical error correction is impactful since it affects hundreds of millions of people that use or acquire English as a second language. It has thus been subject to a number of shared tasks since 2011.<sup class=\"reference\" id=\"cite_ref-29\"><a href=\"#cite_note-29\">[29]</a></sup><sup class=\"reference\" id=\"cite_ref-30\"><a href=\"#cite_note-30\">[30]</a></sup><sup class=\"reference\" id=\"cite_ref-31\"><a href=\"#cite_note-31\">[31]</a></sup> As far as orthography, morphology, syntax and certain aspects of semantics are concerned, and due to the development of powerful neural language models such as <a href=\"/wiki/GPT-2\" title=\"GPT-2\">GPT-2</a>, this can now (2019) be considered a largely solved problem and is being marketed in various commercial applications.<sup class=\"reference\" id=\"cite_ref-32\"><a href=\"#cite_note-32\">[32]</a></sup></dd>\n<dt><a href=\"/wiki/Machine_translation\" title=\"Machine translation\">Machine translation</a></dt>\n<dd>Automatically translate text from one human language to another. This is one of the most difficult problems, and is a member of a class of problems colloquially termed \"<a href=\"/wiki/AI-complete\" title=\"AI-complete\">AI-complete</a>\", i.e. requiring all of the different types of knowledge that humans possess (grammar, semantics, facts about the real world, etc.) to solve properly.</dd>\n<dt><a class=\"mw-redirect\" href=\"/wiki/Natural_language_generation\" title=\"Natural language generation\">Natural language generation</a> (NLG):</dt>\n<dd>Convert information from computer databases or semantic intents into readable human language.</dd>\n<dt><a class=\"mw-redirect\" href=\"/wiki/Natural_language_understanding\" title=\"Natural language understanding\">Natural language understanding</a> (NLU)</dt>\n<dd>Convert chunks of text into more formal representations such as <a href=\"/wiki/First-order_logic\" title=\"First-order logic\">first-order logic</a> structures that are easier for <a href=\"/wiki/Computer\" title=\"Computer\">computer</a> programs to manipulate. Natural language understanding involves the identification of the intended semantic from the multiple possible semantics which can be derived from a natural language expression which usually takes the form of organized notations of natural language concepts. Introduction and creation of language metamodel and ontology are efficient however empirical solutions. An explicit formalization of natural language semantics without confusions with implicit assumptions such as <a href=\"/wiki/Closed-world_assumption\" title=\"Closed-world assumption\">closed-world assumption</a> (CWA) vs. <a href=\"/wiki/Open-world_assumption\" title=\"Open-world assumption\">open-world assumption</a>, or subjective Yes/No vs. objective True/False is expected for the construction of a basis of semantics formalization.<sup class=\"reference\" id=\"cite_ref-33\"><a href=\"#cite_note-33\">[33]</a></sup></dd>\n<dt><a href=\"/wiki/Question_answering\" title=\"Question answering\">Question answering</a></dt>\n<dd>Given a human-language question, determine its answer. Typical questions have a specific right answer (such as \"What is the capital of Canada?\"), but sometimes open-ended questions are also considered (such as \"What is the meaning of life?\"). Recent works have looked at even more complex questions.<sup class=\"reference\" id=\"cite_ref-34\"><a href=\"#cite_note-34\">[34]</a></sup></dd></dl>\n<h2><span id=\"General_tendencies_and_.28possible.29_future_directions\"></span><span class=\"mw-headline\" id=\"General_tendencies_and_(possible)_future_directions\">General tendencies and (possible) future directions</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=16\" title=\"Edit section: General tendencies and (possible) future directions\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\n<p>Based on long-standing trends in the field, it is possible to extrapolate future directions of NLP. As of 2020, three trends among the topics of the long-standing series of CoNLL Shared Tasks can be observed:<sup class=\"reference\" id=\"cite_ref-35\"><a href=\"#cite_note-35\">[35]</a></sup>\n</p>\n<ul><li>Interest on increasingly abstract, \"cognitive\" aspects of natural language (1999-2001: shallow parsing, 2002-03: named entity recognition, 2006-09/2017-18: dependency syntax, 2004-05/2008-09 semantic role labelling, 2011-12 coreference, 2015-16: discourse parsing, 2019: semantic parsing).</li>\n<li>Increasing interest in multilinguality, and, potentially, multimodality (English since 1999; Spanish, Dutch since 2002; German since 2003; Bulgarian, Danish, Japanese, Portuguese, Slovenian, Swedish, Turkish since 2006; Basque, Catalan, Chinese, Greek, Hungarian, Italian, Turkish since 2007; Czech since 2009; Arabic since 2012; 2017: 40+ languages; 2018: 60+/100+ languages)</li>\n<li>Elimination of symbolic representations (rule-based over supervised towards weakly supervised methods, representation learning and end-to-end systems)</li></ul>\n<h3><span class=\"mw-headline\" id=\"Cognition_and_NLP\">Cognition and NLP</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=17\" title=\"Edit section: Cognition and NLP\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h3>\n<p>Most more higher-level NLP applications involve aspects that emulate intelligent behaviour and apparent comprehension of natural language. More broadly speaking, the technical operationalization of increasingly advanced aspects of cognitive behaviour represents one of the developmental trajectories of NLP (see trends among CoNLL shared tasks above).\n</p><p><a href=\"/wiki/Cognition\" title=\"Cognition\">Cognition</a> refers to \"the mental action or process of acquiring knowledge and understanding through thought, experience, and the senses.\"<sup class=\"reference\" id=\"cite_ref-36\"><a href=\"#cite_note-36\">[36]</a></sup> <a href=\"/wiki/Cognitive_science\" title=\"Cognitive science\">Cognitive science</a> is the interdisciplinary, scientific study of the mind and its processes.<sup class=\"reference\" id=\"cite_ref-37\"><a href=\"#cite_note-37\">[37]</a></sup> <a href=\"/wiki/Cognitive_linguistics\" title=\"Cognitive linguistics\">Cognitive linguistics</a> is an interdisciplinary branch of linguistics, combining knowledge and research from both psychology and linguistics.<sup class=\"reference\" id=\"cite_ref-38\"><a href=\"#cite_note-38\">[38]</a></sup> Especially during the age of <a href=\"#Symbolic_NLP_(1950s_-_early_1990s)\">symbolic NLP</a>, the area of computational linguistics maintained strong ties with cognitive studies. \n</p><p>As an example, <a href=\"/wiki/George_Lakoff\" title=\"George Lakoff\">George Lakoff</a> offers a methodology to build natural language processing (NLP) algorithms through the perspective of <a href=\"/wiki/Cognitive_science\" title=\"Cognitive science\">cognitive science</a>, along with the findings of <a href=\"/wiki/Cognitive_linguistics\" title=\"Cognitive linguistics\">cognitive linguistics</a>,<sup class=\"reference\" id=\"cite_ref-39\"><a href=\"#cite_note-39\">[39]</a></sup> with two defining aspects: \n</p>\n<ol><li>Apply the theory of <a href=\"/wiki/Conceptual_metaphor\" title=\"Conceptual metaphor\">conceptual metaphor</a>, explained by Lakoff as “the understanding of one idea, in terms of another” which provides an idea of the intent of the author.<sup class=\"reference\" id=\"cite_ref-40\"><a href=\"#cite_note-40\">[40]</a></sup> For example, consider the English word <i>“big”</i>. When used in a comparison (<i>“That is a big tree”</i>), the author's intent is to imply that the tree is <i>”physically large”</i> relative to other trees or the authors experience. When used metaphorically (<i>”Tomorrow is a big day”</i>), the author’s intent to imply <i>”importance”</i>. The intent behind other usages, like in <i>”She is a big person”</i> will remain somewhat ambiguous to a person and a cognitive NLP algorithm alike without additional information.</li>\n<li>Assign relative measures of meaning to a word, phrase, sentence or piece of text based on the information presented before and after the piece of text being analyzed, e.g., by means of a <a href=\"/wiki/Probabilistic_context-free_grammar\" title=\"Probabilistic context-free grammar\">probabilistic context-free grammar</a> (PCFG). The mathematical equation for such algorithms is presented in <span class=\"citation patent\"><a class=\"external text\" href=\"https://worldwide.espacenet.com/textdoc?DB=EPODOC&amp;IDX=US9269353\" rel=\"nofollow\">US patent 9269353</a></span><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Apatent&amp;rft.number=9269353&amp;rft.cc=US&amp;rft.title=\"><span style=\"display: none;\"> </span></span>:</li></ol>\n<dl><dd><dl><dd><span class=\"mwe-math-element\"><span class=\"mwe-math-mathml-inline mwe-math-mathml-a11y\" style=\"display: none;\"><math alttext=\"{\\displaystyle {RMM(token_{N})}={PMM(token_{N})}\\times {\\frac {1}{2d}}\\left(\\sum _{i=-d}^{d}{((PMM(token_{N-1})}\\times {PF(token_{N},token_{N-1}))_{i}}\\right)}\" xmlns=\"http://www.w3.org/1998/Math/MathML\">\n<semantics>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mstyle displaystyle=\"true\" scriptlevel=\"0\">\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>R</mi>\n<mi>M</mi>\n<mi>M</mi>\n<mo stretchy=\"false\">(</mo>\n<mi>t</mi>\n<mi>o</mi>\n<mi>k</mi>\n<mi>e</mi>\n<msub>\n<mi>n</mi>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>N</mi>\n</mrow>\n</msub>\n<mo stretchy=\"false\">)</mo>\n</mrow>\n<mo>=</mo>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>P</mi>\n<mi>M</mi>\n<mi>M</mi>\n<mo stretchy=\"false\">(</mo>\n<mi>t</mi>\n<mi>o</mi>\n<mi>k</mi>\n<mi>e</mi>\n<msub>\n<mi>n</mi>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>N</mi>\n</mrow>\n</msub>\n<mo stretchy=\"false\">)</mo>\n</mrow>\n<mo>×<!-- × --></mo>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mfrac>\n<mn>1</mn>\n<mrow>\n<mn>2</mn>\n<mi>d</mi>\n</mrow>\n</mfrac>\n</mrow>\n<mrow>\n<mo>(</mo>\n<mrow>\n<munderover>\n<mo>∑<!-- ∑ --></mo>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>i</mi>\n<mo>=</mo>\n<mo>−<!-- − --></mo>\n<mi>d</mi>\n</mrow>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>d</mi>\n</mrow>\n</munderover>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mo stretchy=\"false\">(</mo>\n<mo stretchy=\"false\">(</mo>\n<mi>P</mi>\n<mi>M</mi>\n<mi>M</mi>\n<mo stretchy=\"false\">(</mo>\n<mi>t</mi>\n<mi>o</mi>\n<mi>k</mi>\n<mi>e</mi>\n<msub>\n<mi>n</mi>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>N</mi>\n<mo>−<!-- − --></mo>\n<mn>1</mn>\n</mrow>\n</msub>\n<mo stretchy=\"false\">)</mo>\n</mrow>\n<mo>×<!-- × --></mo>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>P</mi>\n<mi>F</mi>\n<mo stretchy=\"false\">(</mo>\n<mi>t</mi>\n<mi>o</mi>\n<mi>k</mi>\n<mi>e</mi>\n<msub>\n<mi>n</mi>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>N</mi>\n</mrow>\n</msub>\n<mo>,</mo>\n<mi>t</mi>\n<mi>o</mi>\n<mi>k</mi>\n<mi>e</mi>\n<msub>\n<mi>n</mi>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>N</mi>\n<mo>−<!-- − --></mo>\n<mn>1</mn>\n</mrow>\n</msub>\n<mo stretchy=\"false\">)</mo>\n<msub>\n<mo stretchy=\"false\">)</mo>\n<mrow class=\"MJX-TeXAtom-ORD\">\n<mi>i</mi>\n</mrow>\n</msub>\n</mrow>\n</mrow>\n<mo>)</mo>\n</mrow>\n</mstyle>\n</mrow>\n<annotation encoding=\"application/x-tex\">{\\displaystyle {RMM(token_{N})}={PMM(token_{N})}\\times {\\frac {1}{2d}}\\left(\\sum _{i=-d}^{d}{((PMM(token_{N-1})}\\times {PF(token_{N},token_{N-1}))_{i}}\\right)}</annotation>\n</semantics>\n</math></span><img alt=\"{\\displaystyle {RMM(token_{N})}={PMM(token_{N})}\\times {\\frac {1}{2d}}\\left(\\sum _{i=-d}^{d}{((PMM(token_{N-1})}\\times {PF(token_{N},token_{N-1}))_{i}}\\right)}\" aria-hidden=\"true\" class=\"mwe-math-fallback-image-inline\" src=\"https://wikimedia.org/api/rest_v1/media/math/render/svg/145bdbd62e463df3e65c94db2e17224ecbcb2c40\" style=\"vertical-align: -3.171ex; width:96.554ex; height:7.509ex;\"/></span></dd></dl></dd></dl>\n<dl><dd><dl><dd><i>Where,</i>\n<dl><dd><b>RMM</b>, is the Relative Measure of Meaning</dd>\n<dd><b>token</b>, is any block of text, sentence, phrase or word</dd>\n<dd><b>N</b>, is the number of tokens being analyzed</dd>\n<dd><b>PMM</b>, is the Probable Measure of Meaning based on a corpora</dd>\n<dd><b>d</b>, is the location of the token along the sequence of <b>N-1</b> tokens</dd>\n<dd><b>PF</b>, is the Probability Function specific to a language</dd></dl></dd></dl></dd></dl>\n<p>Ties with cognitive linguistics are part of the historical heritage of NLP, but they have been less frequently addressed since the statistical turn during the 1990s. Nevertheless, approaches to develop cognitive models towards technically operationalizable frameworks have been pursued in the context of various frameworks, e.g., of cognitive grammar,<sup class=\"reference\" id=\"cite_ref-41\"><a href=\"#cite_note-41\">[41]</a></sup> functional grammar,<sup class=\"reference\" id=\"cite_ref-42\"><a href=\"#cite_note-42\">[42]</a></sup> construction grammar,<sup class=\"reference\" id=\"cite_ref-43\"><a href=\"#cite_note-43\">[43]</a></sup> computational psycholinguistics and cognitive neuroscience (e.g., <a href=\"/wiki/ACT-R\" title=\"ACT-R\">ACT-R</a>), however, with limited uptake in mainstream NLP (as measured by presence on major conferences<sup class=\"reference\" id=\"cite_ref-44\"><a href=\"#cite_note-44\">[44]</a></sup> of the <a href=\"/wiki/Association_for_Computational_Linguistics\" title=\"Association for Computational Linguistics\">ACL</a>). More recently, ideas of cognitive NLP have been revived as an approach to achieve <a href=\"/wiki/Explainable_artificial_intelligence\" title=\"Explainable artificial intelligence\">explainability</a>, e.g., under the notion of \"cognitive AI\".<sup class=\"reference\" id=\"cite_ref-45\"><a href=\"#cite_note-45\">[45]</a></sup> Likewise, ideas of cognitive NLP are inherent to neural models multimodal NLP (although rarely made explicit).<sup class=\"reference\" id=\"cite_ref-46\"><a href=\"#cite_note-46\">[46]</a></sup>\n</p>\n<h2><span class=\"mw-headline\" id=\"See_also\">See also</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=18\" title=\"Edit section: See also\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\n<style data-mw-deduplicate=\"TemplateStyles:r998391716\">.mw-parser-output .div-col{margin-top:0.3em;column-width:30em}.mw-parser-output .div-col-small{font-size:90%}.mw-parser-output .div-col-rules{column-rule:1px solid #aaa}.mw-parser-output .div-col dl,.mw-parser-output .div-col ol,.mw-parser-output .div-col ul{margin-top:0}.mw-parser-output .div-col li,.mw-parser-output .div-col dd{page-break-inside:avoid;break-inside:avoid-column}</style><div class=\"div-col\" style=\"column-width: 22em;\">\n<ul><li><i><a href=\"/wiki/1_the_Road\" title=\"1 the Road\">1 the Road</a></i></li>\n<li><a href=\"/wiki/Automated_essay_scoring\" title=\"Automated essay scoring\">Automated essay scoring</a></li>\n<li><a href=\"/wiki/Biomedical_text_mining\" title=\"Biomedical text mining\">Biomedical text mining</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Compound_term_processing\" title=\"Compound term processing\">Compound term processing</a></li>\n<li><a href=\"/wiki/Computational_linguistics\" title=\"Computational linguistics\">Computational linguistics</a></li>\n<li><a href=\"/wiki/Computer-assisted_reviewing\" title=\"Computer-assisted reviewing\">Computer-assisted reviewing</a></li>\n<li><a href=\"/wiki/Controlled_natural_language\" title=\"Controlled natural language\">Controlled natural language</a></li>\n<li><a href=\"/wiki/Deep_learning\" title=\"Deep learning\">Deep learning</a></li>\n<li><a href=\"/wiki/Deep_linguistic_processing\" title=\"Deep linguistic processing\">Deep linguistic processing</a></li>\n<li><a href=\"/wiki/Distributional_semantics\" title=\"Distributional semantics\">Distributional semantics</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Foreign_language_reading_aid\" title=\"Foreign language reading aid\">Foreign language reading aid</a></li>\n<li><a href=\"/wiki/Foreign_language_writing_aid\" title=\"Foreign language writing aid\">Foreign language writing aid</a></li>\n<li><a href=\"/wiki/Information_extraction\" title=\"Information extraction\">Information extraction</a></li>\n<li><a href=\"/wiki/Information_retrieval\" title=\"Information retrieval\">Information retrieval</a></li>\n<li><a href=\"/wiki/Language_and_Communication_Technologies\" title=\"Language and Communication Technologies\">Language and Communication Technologies</a></li>\n<li><a href=\"/wiki/Language_technology\" title=\"Language technology\">Language technology</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Latent_semantic_indexing\" title=\"Latent semantic indexing\">Latent semantic indexing</a></li>\n<li><a href=\"/wiki/Native-language_identification\" title=\"Native-language identification\">Native-language identification</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Natural_language_programming\" title=\"Natural language programming\">Natural language programming</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Natural_language_user_interface\" title=\"Natural language user interface\">Natural language search</a></li>\n<li><a href=\"/wiki/Outline_of_natural_language_processing\" title=\"Outline of natural language processing\">Outline of natural language processing</a></li>\n<li><a href=\"/wiki/Query_expansion\" title=\"Query expansion\">Query expansion</a></li>\n<li><a href=\"/wiki/Query_understanding\" title=\"Query understanding\">Query understanding</a></li>\n<li><a href=\"/wiki/Reification_(linguistics)\" title=\"Reification (linguistics)\">Reification (linguistics)</a></li>\n<li><a href=\"/wiki/Speech_processing\" title=\"Speech processing\">Speech processing</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Spoken_dialogue_system\" title=\"Spoken dialogue system\">Spoken dialogue system</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Text-proofing\" title=\"Text-proofing\">Text-proofing</a></li>\n<li><a href=\"/wiki/Text_simplification\" title=\"Text simplification\">Text simplification</a></li>\n<li><a href=\"/wiki/Transformer_(machine_learning_model)\" title=\"Transformer (machine learning model)\">Transformer (machine learning model)</a></li>\n<li><a href=\"/wiki/Truecasing\" title=\"Truecasing\">Truecasing</a></li>\n<li><a href=\"/wiki/Question_answering\" title=\"Question answering\">Question answering</a></li>\n<li><a href=\"/wiki/Word2vec\" title=\"Word2vec\">Word2vec</a></li></ul>\n</div>\n<h2><span class=\"mw-headline\" id=\"References\">References</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=19\" title=\"Edit section: References\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\n<style data-mw-deduplicate=\"TemplateStyles:r1011085734\">.mw-parser-output .reflist{font-size:90%;margin-bottom:0.5em;list-style-type:decimal}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}</style><div class=\"reflist reflist-columns references-column-width\" style=\"column-width: 30em;\">\n<ol class=\"references\">\n<li id=\"cite_note-Kongthon-1\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-Kongthon_1-0\">^</a></b></span> <span class=\"reference-text\"><style data-mw-deduplicate=\"TemplateStyles:r999302996\">.mw-parser-output cite.citation{font-style:inherit}.mw-parser-output .citation q{quotes:\"\\\"\"\"\\\"\"\"'\"\"'\"}.mw-parser-output .id-lock-free a,.mw-parser-output .citation .cs1-lock-free a{background:linear-gradient(transparent,transparent),url(\"//upload.wikimedia.org/wikipedia/commons/6/65/Lock-green.svg\")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited a,.mw-parser-output .id-lock-registration a,.mw-parser-output .citation .cs1-lock-limited a,.mw-parser-output .citation .cs1-lock-registration a{background:linear-gradient(transparent,transparent),url(\"//upload.wikimedia.org/wikipedia/commons/d/d6/Lock-gray-alt-2.svg\")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription a,.mw-parser-output .citation .cs1-lock-subscription a{background:linear-gradient(transparent,transparent),url(\"//upload.wikimedia.org/wikipedia/commons/a/aa/Lock-red-alt-2.svg\")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-subscription,.mw-parser-output .cs1-registration{color:#555}.mw-parser-output .cs1-subscription span,.mw-parser-output .cs1-registration span{border-bottom:1px dotted;cursor:help}.mw-parser-output .cs1-ws-icon a{background:linear-gradient(transparent,transparent),url(\"//upload.wikimedia.org/wikipedia/commons/4/4c/Wikisource-logo.svg\")right 0.1em center/12px no-repeat}.mw-parser-output code.cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;font-size:100%}.mw-parser-output .cs1-visible-error{font-size:100%}.mw-parser-output .cs1-maint{display:none;color:#33aa33;margin-left:0.3em}.mw-parser-output .cs1-format{font-size:95%}.mw-parser-output .cs1-kern-left,.mw-parser-output .cs1-kern-wl-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right,.mw-parser-output .cs1-kern-wl-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}</style><cite class=\"citation conference cs1\" id=\"CITEREFKongthonSangkeettrakarnKongyoungHaruechaiyasak2009\">Kongthon, Alisa; Sangkeettrakarn, Chatchawal; Kongyoung, Sarawoot; Haruechaiyasak, Choochart (October 27–30, 2009). <i>Implementing an online help desk system based on conversational agent</i>. MEDES '09: The International Conference on Management of Emergent Digital EcoSystems. France: ACM. <a class=\"mw-redirect\" href=\"/wiki/Doi_(identifier)\" title=\"Doi (identifier)\">doi</a>:<a class=\"external text\" href=\"https://doi.org/10.1145%2F1643823.1643908\" rel=\"nofollow\">10.1145/1643823.1643908</a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=conference&amp;rft.btitle=Implementing+an+online+help+desk+system+based+on+conversational+agent&amp;rft.place=France&amp;rft.pub=ACM&amp;rft.date=2009-10-27%2F2009-10-30&amp;rft_id=info%3Adoi%2F10.1145%2F1643823.1643908&amp;rft.aulast=Kongthon&amp;rft.aufirst=Alisa&amp;rft.au=Sangkeettrakarn%2C+Chatchawal&amp;rft.au=Kongyoung%2C+Sarawoot&amp;rft.au=Haruechaiyasak%2C+Choochart&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-2\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-2\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\" id=\"CITEREFHutchins,_J.2005\">Hutchins, J. (2005). <a class=\"external text\" href=\"http://www.hutchinsweb.me.uk/Nutshell-2005.pdf\" rel=\"nofollow\">\"The history of machine translation in a nutshell\"</a> <span class=\"cs1-format\">(PDF)</span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=The+history+of+machine+translation+in+a+nutshell&amp;rft.date=2005&amp;rft.au=Hutchins%2C+J.&amp;rft_id=http%3A%2F%2Fwww.hutchinsweb.me.uk%2FNutshell-2005.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span><sup class=\"noprint Inline-Template\" style=\"white-space:nowrap;\">[<i><a href=\"/wiki/Wikipedia:Verifiability#Self-published_sources\" title=\"Wikipedia:Verifiability\"><span title=\"This reference citation appears to be to a self-published source. (December 2013)\">self-published source</span></a></i>]</sup></span>\n</li>\n<li id=\"cite_note-3\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-3\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation cs2\" id=\"CITEREFKoskenniemi1983\"><a href=\"/wiki/Kimmo_Koskenniemi\" title=\"Kimmo Koskenniemi\">Koskenniemi, Kimmo</a> (1983), <a class=\"external text\" href=\"http://www.ling.helsinki.fi/~koskenni/doc/Two-LevelMorphology.pdf\" rel=\"nofollow\"><i>Two-level morphology: A general computational model of word-form recognition and production</i></a> <span class=\"cs1-format\">(PDF)</span>, Department of General Linguistics, <a href=\"/wiki/University_of_Helsinki\" title=\"University of Helsinki\">University of Helsinki</a></cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Two-level+morphology%3A+A+general+computational+model+of+word-form+recognition+and+production&amp;rft.pub=Department+of+General+Linguistics%2C+University+of+Helsinki&amp;rft.date=1983&amp;rft.aulast=Koskenniemi&amp;rft.aufirst=Kimmo&amp;rft_id=http%3A%2F%2Fwww.ling.helsinki.fi%2F~koskenni%2Fdoc%2FTwo-LevelMorphology.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-4\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-4\">^</a></b></span> <span class=\"reference-text\">Joshi, A. K., &amp; Weinstein, S. (1981, August). <a class=\"external text\" href=\"https://www.ijcai.org/Proceedings/81-1/Papers/071.pdf\" rel=\"nofollow\">Control of Inference: Role of Some Aspects of Discourse Structure-Centering</a>. In <i>IJCAI</i> (pp. 385-387).</span>\n</li>\n<li id=\"cite_note-5\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-5\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFGuidaMauri1986\">Guida, G.; Mauri, G. (July 1986). \"Evaluation of natural language processing systems: Issues and approaches\". <i>Proceedings of the IEEE</i>. <b>74</b> (7): 1026–1035. <a class=\"mw-redirect\" href=\"/wiki/Doi_(identifier)\" title=\"Doi (identifier)\">doi</a>:<a class=\"external text\" href=\"https://doi.org/10.1109%2FPROC.1986.13580\" rel=\"nofollow\">10.1109/PROC.1986.13580</a>. <a class=\"mw-redirect\" href=\"/wiki/ISSN_(identifier)\" title=\"ISSN (identifier)\">ISSN</a> <a class=\"external text\" href=\"//www.worldcat.org/issn/1558-2256\" rel=\"nofollow\">1558-2256</a>. <a class=\"mw-redirect\" href=\"/wiki/S2CID_(identifier)\" title=\"S2CID (identifier)\">S2CID</a> <a class=\"external text\" href=\"https://api.semanticscholar.org/CorpusID:30688575\" rel=\"nofollow\">30688575</a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Proceedings+of+the+IEEE&amp;rft.atitle=Evaluation+of+natural+language+processing+systems%3A+Issues+and+approaches&amp;rft.volume=74&amp;rft.issue=7&amp;rft.pages=1026-1035&amp;rft.date=1986-07&amp;rft_id=https%3A%2F%2Fapi.semanticscholar.org%2FCorpusID%3A30688575%23id-name%3DS2CID&amp;rft.issn=1558-2256&amp;rft_id=info%3Adoi%2F10.1109%2FPROC.1986.13580&amp;rft.aulast=Guida&amp;rft.aufirst=G.&amp;rft.au=Mauri%2C+G.&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-6\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-6\">^</a></b></span> <span class=\"reference-text\">Chomskyan linguistics encourages the investigation of \"<a href=\"/wiki/Corner_case\" title=\"Corner case\">corner cases</a>\" that stress the limits of its theoretical models (comparable to <a href=\"/wiki/Pathological_(mathematics)\" title=\"Pathological (mathematics)\">pathological</a> phenomena in mathematics), typically created using <a href=\"/wiki/Thought_experiment\" title=\"Thought experiment\">thought experiments</a>, rather than the systematic investigation of typical phenomena that occur in real-world data, as is the case in <a href=\"/wiki/Corpus_linguistics\" title=\"Corpus linguistics\">corpus linguistics</a>. The creation and use of such <a href=\"/wiki/Text_corpus\" title=\"Text corpus\">corpora</a> of real-world data is a fundamental part of machine-learning algorithms for natural language processing. In addition, theoretical underpinnings of Chomskyan linguistics such as the so-called \"<a href=\"/wiki/Poverty_of_the_stimulus\" title=\"Poverty of the stimulus\">poverty of the stimulus</a>\" argument entail that general learning algorithms, as are typically used in machine learning, cannot be successful in language processing. As a result, the Chomskyan paradigm discouraged the application of such models to language processing.</span>\n</li>\n<li id=\"cite_note-goldberg:nnlp17-7\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-goldberg:nnlp17_7-0\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFGoldberg2016\">Goldberg, Yoav (2016). \"A Primer on Neural Network Models for Natural Language Processing\". <i>Journal of Artificial Intelligence Research</i>. <b>57</b>: 345–420. <a class=\"mw-redirect\" href=\"/wiki/ArXiv_(identifier)\" title=\"ArXiv (identifier)\">arXiv</a>:<span class=\"cs1-lock-free\" title=\"Freely accessible\"><a class=\"external text\" href=\"//arxiv.org/abs/1807.10854\" rel=\"nofollow\">1807.10854</a></span>. <a class=\"mw-redirect\" href=\"/wiki/Doi_(identifier)\" title=\"Doi (identifier)\">doi</a>:<a class=\"external text\" href=\"https://doi.org/10.1613%2Fjair.4992\" rel=\"nofollow\">10.1613/jair.4992</a>. <a class=\"mw-redirect\" href=\"/wiki/S2CID_(identifier)\" title=\"S2CID (identifier)\">S2CID</a> <a class=\"external text\" href=\"https://api.semanticscholar.org/CorpusID:8273530\" rel=\"nofollow\">8273530</a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Journal+of+Artificial+Intelligence+Research&amp;rft.atitle=A+Primer+on+Neural+Network+Models+for+Natural+Language+Processing&amp;rft.volume=57&amp;rft.pages=345-420&amp;rft.date=2016&amp;rft_id=info%3Aarxiv%2F1807.10854&amp;rft_id=https%3A%2F%2Fapi.semanticscholar.org%2FCorpusID%3A8273530%23id-name%3DS2CID&amp;rft_id=info%3Adoi%2F10.1613%2Fjair.4992&amp;rft.aulast=Goldberg&amp;rft.aufirst=Yoav&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-goodfellow:book16-8\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-goodfellow:book16_8-0\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation book cs1\" id=\"CITEREFGoodfellowBengioCourville2016\">Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron (2016). <a class=\"external text\" href=\"http://www.deeplearningbook.org/\" rel=\"nofollow\"><i>Deep Learning</i></a>. MIT Press.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Deep+Learning&amp;rft.pub=MIT+Press&amp;rft.date=2016&amp;rft.aulast=Goodfellow&amp;rft.aufirst=Ian&amp;rft.au=Bengio%2C+Yoshua&amp;rft.au=Courville%2C+Aaron&amp;rft_id=http%3A%2F%2Fwww.deeplearningbook.org%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-jozefowicz:lm16-9\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-jozefowicz:lm16_9-0\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation book cs1\" id=\"CITEREFJozefowiczVinyalsSchusterShazeer2016\">Jozefowicz, Rafal; Vinyals, Oriol; Schuster, Mike; Shazeer, Noam; Wu, Yonghui (2016). <i>Exploring the Limits of Language Modeling</i>. <a class=\"mw-redirect\" href=\"/wiki/ArXiv_(identifier)\" title=\"ArXiv (identifier)\">arXiv</a>:<span class=\"cs1-lock-free\" title=\"Freely accessible\"><a class=\"external text\" href=\"//arxiv.org/abs/1602.02410\" rel=\"nofollow\">1602.02410</a></span>. <a class=\"mw-redirect\" href=\"/wiki/Bibcode_(identifier)\" title=\"Bibcode (identifier)\">Bibcode</a>:<a class=\"external text\" href=\"https://ui.adsabs.harvard.edu/abs/2016arXiv160202410J\" rel=\"nofollow\">2016arXiv160202410J</a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Exploring+the+Limits+of+Language+Modeling&amp;rft.date=2016&amp;rft_id=info%3Aarxiv%2F1602.02410&amp;rft_id=info%3Abibcode%2F2016arXiv160202410J&amp;rft.aulast=Jozefowicz&amp;rft.aufirst=Rafal&amp;rft.au=Vinyals%2C+Oriol&amp;rft.au=Schuster%2C+Mike&amp;rft.au=Shazeer%2C+Noam&amp;rft.au=Wu%2C+Yonghui&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-choe:emnlp16-10\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-choe:emnlp16_10-0\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFChoeCharniak\">Choe, Do Kook; Charniak, Eugene. <a class=\"external text\" href=\"https://aclanthology.coli.uni-saarland.de/papers/D16-1257/d16-1257\" rel=\"nofollow\">\"Parsing as Language Modeling\"</a>. <i>Emnlp 2016</i>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Emnlp+2016&amp;rft.atitle=Parsing+as+Language+Modeling&amp;rft.aulast=Choe&amp;rft.aufirst=Do+Kook&amp;rft.au=Charniak%2C+Eugene&amp;rft_id=https%3A%2F%2Faclanthology.coli.uni-saarland.de%2Fpapers%2FD16-1257%2Fd16-1257&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-vinyals:nips15-11\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-vinyals:nips15_11-0\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFVinyalsKaiser2014\">Vinyals, Oriol; et al. (2014). <a class=\"external text\" href=\"https://papers.nips.cc/paper/5635-grammar-as-a-foreign-language.pdf\" rel=\"nofollow\">\"Grammar as a Foreign Language\"</a> <span class=\"cs1-format\">(PDF)</span>. <i>Nips2015</i>. <a class=\"mw-redirect\" href=\"/wiki/ArXiv_(identifier)\" title=\"ArXiv (identifier)\">arXiv</a>:<span class=\"cs1-lock-free\" title=\"Freely accessible\"><a class=\"external text\" href=\"//arxiv.org/abs/1412.7449\" rel=\"nofollow\">1412.7449</a></span>. <a class=\"mw-redirect\" href=\"/wiki/Bibcode_(identifier)\" title=\"Bibcode (identifier)\">Bibcode</a>:<a class=\"external text\" href=\"https://ui.adsabs.harvard.edu/abs/2014arXiv1412.7449V\" rel=\"nofollow\">2014arXiv1412.7449V</a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Nips2015&amp;rft.atitle=Grammar+as+a+Foreign+Language&amp;rft.date=2014&amp;rft_id=info%3Aarxiv%2F1412.7449&amp;rft_id=info%3Abibcode%2F2014arXiv1412.7449V&amp;rft.aulast=Vinyals&amp;rft.aufirst=Oriol&amp;rft.au=Kaiser%2C+Lukasz&amp;rft_id=https%3A%2F%2Fpapers.nips.cc%2Fpaper%2F5635-grammar-as-a-foreign-language.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-winograd:shrdlu71-12\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-winograd:shrdlu71_12-0\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation thesis cs1\" id=\"CITEREFWinograd1971\">Winograd, Terry (1971). <a class=\"external text\" href=\"http://hci.stanford.edu/winograd/shrdlu/\" rel=\"nofollow\"><i>Procedures as a Representation for Data in a Computer Program for Understanding Natural Language</i></a> (Thesis).</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adissertation&amp;rft.title=Procedures+as+a+Representation+for+Data+in+a+Computer+Program+for+Understanding+Natural+Language&amp;rft.date=1971&amp;rft.aulast=Winograd&amp;rft.aufirst=Terry&amp;rft_id=http%3A%2F%2Fhci.stanford.edu%2Fwinograd%2Fshrdlu%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-schank77-13\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-schank77_13-0\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation book cs1\" id=\"CITEREFSchankAbelson1977\">Schank, Roger C.; Abelson, Robert P. (1977). <i>Scripts, Plans, Goals, and Understanding: An Inquiry Into Human Knowledge Structures</i>. Hillsdale: Erlbaum. <a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/0-470-99033-3\" title=\"Special:BookSources/0-470-99033-3\"><bdi>0-470-99033-3</bdi></a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Scripts%2C+Plans%2C+Goals%2C+and+Understanding%3A+An+Inquiry+Into+Human+Knowledge+Structures&amp;rft.place=Hillsdale&amp;rft.pub=Erlbaum&amp;rft.date=1977&amp;rft.isbn=0-470-99033-3&amp;rft.aulast=Schank&amp;rft.aufirst=Roger+C.&amp;rft.au=Abelson%2C+Robert+P.&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-johnson:eacl:ilcl09-14\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-johnson:eacl:ilcl09_14-0\">^</a></b></span> <span class=\"reference-text\"><a class=\"external text\" href=\"http://www.aclweb.org/anthology/W09-0103\" rel=\"nofollow\">Mark Johnson. How the statistical revolution changes (computational) linguistics.</a> Proceedings of the EACL 2009 Workshop on the Interaction between Linguistics and Computational Linguistics.</span>\n</li>\n<li id=\"cite_note-resnik:langlog11-15\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-resnik:langlog11_15-0\">^</a></b></span> <span class=\"reference-text\"><a class=\"external text\" href=\"http://languagelog.ldc.upenn.edu/nll/?p=2946\" rel=\"nofollow\">Philip Resnik. Four revolutions.</a> Language Log, February 5, 2011.</span>\n</li>\n<li id=\"cite_note-16\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-16\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\" id=\"CITEREFSocher\">Socher, Richard. <a class=\"external text\" href=\"https://www.socher.org/index.php/Main/DeepLearningForNLP-ACL2012Tutorial\" rel=\"nofollow\">\"Deep Learning For NLP-ACL 2012 Tutorial\"</a>. <i>www.socher.org</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2020-08-17</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.socher.org&amp;rft.atitle=Deep+Learning+For+NLP-ACL+2012+Tutorial&amp;rft.aulast=Socher&amp;rft.aufirst=Richard&amp;rft_id=https%3A%2F%2Fwww.socher.org%2Findex.php%2FMain%2FDeepLearningForNLP-ACL2012Tutorial&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span> This was an early Deep Learning tutorial at the ACL 2012 and met with both interest and (at the time) skepticism by most participants. Until then, neural learning was basically rejected because of its lack of statistical interpretability. Until 2015, deep learning had evolved into the major framework of NLP.</span>\n</li>\n<li id=\"cite_note-17\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-17\">^</a></b></span> <span class=\"reference-text\">Annamoradnejad, I. (2020). <a class=\"external text\" href=\"https://arxiv.org/abs/2004.12765\" rel=\"nofollow\">Colbert: Using bert sentence embedding for humor detection</a>. arXiv preprint arXiv:2004.12765.</span>\n</li>\n<li id=\"cite_note-18\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-18\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation cs2\" id=\"CITEREFYiTian2012\">Yi, Chucai; Tian, Yingli (2012), \"Assistive Text Reading from Complex Background for Blind Persons\", <i>Camera-Based Document Analysis and Recognition</i>, Springer Berlin Heidelberg, pp. 15–28, <a class=\"mw-redirect\" href=\"/wiki/CiteSeerX_(identifier)\" title=\"CiteSeerX (identifier)\">CiteSeerX</a> <span class=\"cs1-lock-free\" title=\"Freely accessible\"><a class=\"external text\" href=\"//citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.668.869\" rel=\"nofollow\">10.1.1.668.869</a></span>, <a class=\"mw-redirect\" href=\"/wiki/Doi_(identifier)\" title=\"Doi (identifier)\">doi</a>:<a class=\"external text\" href=\"https://doi.org/10.1007%2F978-3-642-29364-1_2\" rel=\"nofollow\">10.1007/978-3-642-29364-1_2</a>, <a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/9783642293634\" title=\"Special:BookSources/9783642293634\"><bdi>9783642293634</bdi></a></cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Camera-Based+Document+Analysis+and+Recognition&amp;rft.atitle=Assistive+Text+Reading+from+Complex+Background+for+Blind+Persons&amp;rft.pages=15-28&amp;rft.date=2012&amp;rft_id=%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fsummary%3Fdoi%3D10.1.1.668.869%23id-name%3DCiteSeerX&amp;rft_id=info%3Adoi%2F10.1007%2F978-3-642-29364-1_2&amp;rft.isbn=9783642293634&amp;rft.aulast=Yi&amp;rft.aufirst=Chucai&amp;rft.au=Tian%2C+Yingli&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-19\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-19\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.gyansetu.in/what-is-natural-language-processing/\" rel=\"nofollow\">\"What is Natural Language Processing? Intro to NLP in Machine Learning\"</a>. <i>GyanSetu!</i>. 2020-12-06<span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-09</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=GyanSetu%21&amp;rft.atitle=What+is+Natural+Language+Processing%3F+Intro+to+NLP+in+Machine+Learning&amp;rft.date=2020-12-06&amp;rft_id=https%3A%2F%2Fwww.gyansetu.in%2Fwhat-is-natural-language-processing%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-20\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-20\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFKishorjitVidyaNirmalSivaji2012\">Kishorjit, N.; Vidya, Raj RK.; Nirmal, Y.; Sivaji, B. (2012). <a class=\"external text\" href=\"http://aclweb.org/anthology//W/W12/W12-5008.pdf\" rel=\"nofollow\">\"Manipuri Morpheme Identification\"</a> <span class=\"cs1-format\">(PDF)</span>. <i>Proceedings of the 3rd Workshop on South and Southeast Asian Natural Language Processing (SANLP)</i>. COLING 2012, Mumbai, December 2012: 95–108.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Proceedings+of+the+3rd+Workshop+on+South+and+Southeast+Asian+Natural+Language+Processing+%28SANLP%29&amp;rft.atitle=Manipuri+Morpheme+Identification&amp;rft.pages=95-108&amp;rft.date=2012&amp;rft.aulast=Kishorjit&amp;rft.aufirst=N.&amp;rft.au=Vidya%2C+Raj+RK.&amp;rft.au=Nirmal%2C+Y.&amp;rft.au=Sivaji%2C+B.&amp;rft_id=http%3A%2F%2Faclweb.org%2Fanthology%2F%2FW%2FW12%2FW12-5008.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span><span class=\"cs1-maint citation-comment\">CS1 maint: location (<a href=\"/wiki/Category:CS1_maint:_location\" title=\"Category:CS1 maint: location\">link</a>)</span></span>\n</li>\n<li id=\"cite_note-21\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-21\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFKleinManning2002\">Klein, Dan; Manning, Christopher D. (2002). <a class=\"external text\" href=\"http://papers.nips.cc/paper/1945-natural-language-grammar-induction-using-a-constituent-context-model.pdf\" rel=\"nofollow\">\"Natural language grammar induction using a constituent-context model\"</a> <span class=\"cs1-format\">(PDF)</span>. <i>Advances in Neural Information Processing Systems</i>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Advances+in+Neural+Information+Processing+Systems&amp;rft.atitle=Natural+language+grammar+induction+using+a+constituent-context+model&amp;rft.date=2002&amp;rft.aulast=Klein&amp;rft.aufirst=Dan&amp;rft.au=Manning%2C+Christopher+D.&amp;rft_id=http%3A%2F%2Fpapers.nips.cc%2Fpaper%2F1945-natural-language-grammar-induction-using-a-constituent-context-model.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-rte:11-22\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-rte:11_22-0\">^</a></b></span> <span class=\"reference-text\">PASCAL Recognizing Textual Entailment Challenge (RTE-7) <a class=\"external free\" href=\"https://tac.nist.gov//2011/RTE/\" rel=\"nofollow\">https://tac.nist.gov//2011/RTE/</a></span>\n</li>\n<li id=\"cite_note-23\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-23\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFLippiTorroni2016\">Lippi, Marco; Torroni, Paolo (2016-04-20). <a class=\"external text\" href=\"https://dl.acm.org/doi/10.1145/2850417\" rel=\"nofollow\">\"Argumentation Mining: State of the Art and Emerging Trends\"</a>. <i>ACM Transactions on Internet Technology</i>. <b>16</b> (2): 1–25. <a class=\"mw-redirect\" href=\"/wiki/Doi_(identifier)\" title=\"Doi (identifier)\">doi</a>:<a class=\"external text\" href=\"https://doi.org/10.1145%2F2850417\" rel=\"nofollow\">10.1145/2850417</a>. <a class=\"mw-redirect\" href=\"/wiki/ISSN_(identifier)\" title=\"ISSN (identifier)\">ISSN</a> <a class=\"external text\" href=\"//www.worldcat.org/issn/1533-5399\" rel=\"nofollow\">1533-5399</a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=ACM+Transactions+on+Internet+Technology&amp;rft.atitle=Argumentation+Mining%3A+State+of+the+Art+and+Emerging+Trends&amp;rft.volume=16&amp;rft.issue=2&amp;rft.pages=1-25&amp;rft.date=2016-04-20&amp;rft_id=info%3Adoi%2F10.1145%2F2850417&amp;rft.issn=1533-5399&amp;rft.aulast=Lippi&amp;rft.aufirst=Marco&amp;rft.au=Torroni%2C+Paolo&amp;rft_id=https%3A%2F%2Fdl.acm.org%2Fdoi%2F10.1145%2F2850417&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-24\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-24\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.i3s.unice.fr/~villata/tutorialIJCAI2016.html\" rel=\"nofollow\">\"Argument Mining - IJCAI2016 Tutorial\"</a>. <i>www.i3s.unice.fr</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-03-09</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.i3s.unice.fr&amp;rft.atitle=Argument+Mining+-+IJCAI2016+Tutorial&amp;rft_id=https%3A%2F%2Fwww.i3s.unice.fr%2F~villata%2FtutorialIJCAI2016.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-25\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-25\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"http://acl2016tutorial.arg.tech/\" rel=\"nofollow\">\"NLP Approaches to Computational Argumentation – ACL 2016, Berlin\"</a><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-03-09</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=NLP+Approaches+to+Computational+Argumentation+%E2%80%93+ACL+2016%2C+Berlin&amp;rft_id=http%3A%2F%2Facl2016tutorial.arg.tech%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-26\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-26\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"http://www.ubu.com/historical/racter/index.html\" rel=\"nofollow\">\"U B U W E B :: Racter\"</a>. <i>www.ubu.com</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2020-08-17</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.ubu.com&amp;rft.atitle=U+B+U+W+E+B+%3A%3A+Racter&amp;rft_id=http%3A%2F%2Fwww.ubu.com%2Fhistorical%2Fracter%2Findex.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-27\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-27\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation book cs1\" id=\"CITEREFWriter2019\">Writer, Beta (2019). <i>Lithium-Ion Batteries</i>. <a class=\"mw-redirect\" href=\"/wiki/Doi_(identifier)\" title=\"Doi (identifier)\">doi</a>:<a class=\"external text\" href=\"https://doi.org/10.1007%2F978-3-030-16800-1\" rel=\"nofollow\">10.1007/978-3-030-16800-1</a>. <a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-3-030-16799-8\" title=\"Special:BookSources/978-3-030-16799-8\"><bdi>978-3-030-16799-8</bdi></a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Lithium-Ion+Batteries&amp;rft.date=2019&amp;rft_id=info%3Adoi%2F10.1007%2F978-3-030-16800-1&amp;rft.isbn=978-3-030-16799-8&amp;rft.aulast=Writer&amp;rft.aufirst=Beta&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-28\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-28\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.youtube.com/watch?v=7dtl650D0y0\" rel=\"nofollow\">\"Document Understanding AI on Google Cloud (Cloud Next '19) - YouTube\"</a>. <i>www.youtube.com</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.youtube.com&amp;rft.atitle=Document+Understanding+AI+on+Google+Cloud+%28Cloud+Next+%2719%29+-+YouTube&amp;rft_id=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7dtl650D0y0&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-29\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-29\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\" id=\"CITEREFAdministration\">Administration. <a class=\"external text\" href=\"https://www.mq.edu.au/research/research-centres-groups-and-facilities/innovative-technologies/centres/centre-for-language-technology-clt\" rel=\"nofollow\">\"Centre for Language Technology (CLT)\"</a>. <i>Macquarie University</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Macquarie+University&amp;rft.atitle=Centre+for+Language+Technology+%28CLT%29&amp;rft.au=Administration&amp;rft_id=https%3A%2F%2Fwww.mq.edu.au%2Fresearch%2Fresearch-centres-groups-and-facilities%2Finnovative-technologies%2Fcentres%2Fcentre-for-language-technology-clt&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-30\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-30\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.comp.nus.edu.sg/~nlp/conll13st.html\" rel=\"nofollow\">\"Shared Task: Grammatical Error Correction\"</a>. <i>www.comp.nus.edu.sg</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.comp.nus.edu.sg&amp;rft.atitle=Shared+Task%3A+Grammatical+Error+Correction&amp;rft_id=https%3A%2F%2Fwww.comp.nus.edu.sg%2F~nlp%2Fconll13st.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-31\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-31\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.comp.nus.edu.sg/~nlp/conll14st.html\" rel=\"nofollow\">\"Shared Task: Grammatical Error Correction\"</a>. <i>www.comp.nus.edu.sg</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.comp.nus.edu.sg&amp;rft.atitle=Shared+Task%3A+Grammatical+Error+Correction&amp;rft_id=https%3A%2F%2Fwww.comp.nus.edu.sg%2F~nlp%2Fconll14st.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-32\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-32\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.grammarly.com/about\" rel=\"nofollow\">\"About Us | Grammarly\"</a>. <i>www.grammarly.com</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.grammarly.com&amp;rft.atitle=About+Us+%7C+Grammarly&amp;rft_id=https%3A%2F%2Fwww.grammarly.com%2Fabout&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-33\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-33\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFDuanCruz2011\">Duan, Yucong; Cruz, Christophe (2011). <a class=\"external text\" href=\"https://web.archive.org/web/20111009135952/http://www.ijimt.org/abstract/100-E00187.htm\" rel=\"nofollow\">\"Formalizing Semantic of Natural Language through Conceptualization from Existence\"</a>. <i>International Journal of Innovation, Management and Technology</i>. <b>2</b> (1): 37–42. Archived from <a class=\"external text\" href=\"http://www.ijimt.org/abstract/100-E00187.htm\" rel=\"nofollow\">the original</a> on 2011-10-09.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=International+Journal+of+Innovation%2C+Management+and+Technology&amp;rft.atitle=Formalizing+Semantic+of+Natural+Language+through+Conceptualization+from+Existence&amp;rft.volume=2&amp;rft.issue=1&amp;rft.pages=37-42&amp;rft.date=2011&amp;rft.aulast=Duan&amp;rft.aufirst=Yucong&amp;rft.au=Cruz%2C+Christophe&amp;rft_id=http%3A%2F%2Fwww.ijimt.org%2Fabstract%2F100-E00187.htm&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-34\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-34\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFMittal2011\">Mittal (2011). <a class=\"external text\" href=\"https://hal.archives-ouvertes.fr/hal-01104648/file/Mittal_VersatileQA_IJIIDS.pdf\" rel=\"nofollow\">\"Versatile question answering systems: seeing in synthesis\"</a> <span class=\"cs1-format\">(PDF)</span>. <i>International Journal of Intelligent Information and Database Systems</i>. <b>5</b> (2): 119–142. <a class=\"mw-redirect\" href=\"/wiki/Doi_(identifier)\" title=\"Doi (identifier)\">doi</a>:<a class=\"external text\" href=\"https://doi.org/10.1504%2FIJIIDS.2011.038968\" rel=\"nofollow\">10.1504/IJIIDS.2011.038968</a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=International+Journal+of+Intelligent+Information+and+Database+Systems&amp;rft.atitle=Versatile+question+answering+systems%3A+seeing+in+synthesis&amp;rft.volume=5&amp;rft.issue=2&amp;rft.pages=119-142&amp;rft.date=2011&amp;rft_id=info%3Adoi%2F10.1504%2FIJIIDS.2011.038968&amp;rft.au=Mittal&amp;rft_id=https%3A%2F%2Fhal.archives-ouvertes.fr%2Fhal-01104648%2Ffile%2FMittal_VersatileQA_IJIIDS.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-35\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-35\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.conll.org/previous-tasks\" rel=\"nofollow\">\"Previous shared tasks | CoNLL\"</a>. <i>www.conll.org</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.conll.org&amp;rft.atitle=Previous+shared+tasks+%7C+CoNLL&amp;rft_id=https%3A%2F%2Fwww.conll.org%2Fprevious-tasks&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-36\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-36\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.lexico.com/definition/cognition\" rel=\"nofollow\">\"Cognition\"</a>. <i>Lexico</i>. <a href=\"/wiki/Oxford_University_Press\" title=\"Oxford University Press\">Oxford University Press</a> and <a href=\"/wiki/Dictionary.com\" title=\"Dictionary.com\">Dictionary.com</a><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">6 May</span> 2020</span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Lexico&amp;rft.atitle=Cognition&amp;rft_id=https%3A%2F%2Fwww.lexico.com%2Fdefinition%2Fcognition&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-37\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-37\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"http://www.aft.org/newspubs/periodicals/ae/summer2002/willingham.cfm\" rel=\"nofollow\">\"Ask the Cognitive Scientist\"</a>. <i>American Federation of Teachers</i>. 8 August 2014. <q>Cognitive science is an interdisciplinary field of researchers from Linguistics, psychology, neuroscience, philosophy, computer science, and anthropology that seek to understand the mind.</q></cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=American+Federation+of+Teachers&amp;rft.atitle=Ask+the+Cognitive+Scientist&amp;rft.date=2014-08-08&amp;rft_id=http%3A%2F%2Fwww.aft.org%2Fnewspubs%2Fperiodicals%2Fae%2Fsummer2002%2Fwillingham.cfm&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-38\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-38\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation book cs1\" id=\"CITEREFRobinson2008\">Robinson, Peter (2008). <i>Handbook of Cognitive Linguistics and Second Language Acquisition</i>. Routledge. pp. 3–8. <a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-0-805-85352-0\" title=\"Special:BookSources/978-0-805-85352-0\"><bdi>978-0-805-85352-0</bdi></a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Handbook+of+Cognitive+Linguistics+and+Second+Language+Acquisition&amp;rft.pages=3-8&amp;rft.pub=Routledge&amp;rft.date=2008&amp;rft.isbn=978-0-805-85352-0&amp;rft.aulast=Robinson&amp;rft.aufirst=Peter&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-39\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-39\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation book cs1\" id=\"CITEREFLakoff1999\">Lakoff, George (1999). <i>Philosophy in the Flesh: The Embodied Mind and Its Challenge to Western Philosophy; Appendix: The Neural Theory of Language Paradigm</i>. New York Basic Books. pp. 569–583. <a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-0-465-05674-3\" title=\"Special:BookSources/978-0-465-05674-3\"><bdi>978-0-465-05674-3</bdi></a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Philosophy+in+the+Flesh%3A+The+Embodied+Mind+and+Its+Challenge+to+Western+Philosophy%3B+Appendix%3A+The+Neural+Theory+of+Language+Paradigm&amp;rft.pages=569-583&amp;rft.pub=New+York+Basic+Books&amp;rft.date=1999&amp;rft.isbn=978-0-465-05674-3&amp;rft.aulast=Lakoff&amp;rft.aufirst=George&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-40\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-40\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation book cs1\" id=\"CITEREFStrauss1999\">Strauss, Claudia (1999). <i>A Cognitive Theory of Cultural Meaning</i>. Cambridge University Press. pp. 156–164. <a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-0-521-59541-4\" title=\"Special:BookSources/978-0-521-59541-4\"><bdi>978-0-521-59541-4</bdi></a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=A+Cognitive+Theory+of+Cultural+Meaning&amp;rft.pages=156-164&amp;rft.pub=Cambridge+University+Press&amp;rft.date=1999&amp;rft.isbn=978-0-521-59541-4&amp;rft.aulast=Strauss&amp;rft.aufirst=Claudia&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-41\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-41\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://universalconceptualcognitiveannotation.github.io/\" rel=\"nofollow\">\"Universal Conceptual Cognitive Annotation (UCCA)\"</a>. <i>Universal Conceptual Cognitive Annotation (UCCA)</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Universal+Conceptual+Cognitive+Annotation+%28UCCA%29&amp;rft.atitle=Universal+Conceptual+Cognitive+Annotation+%28UCCA%29&amp;rft_id=https%3A%2F%2Funiversalconceptualcognitiveannotation.github.io%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-42\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-42\">^</a></b></span> <span class=\"reference-text\">Rodríguez, F. C., &amp; Mairal-Usón, R. (2016). <a class=\"external text\" href=\"https://www.redalyc.org/pdf/1345/134549291020.pdf\" rel=\"nofollow\">Building an RRG computational grammar</a>. <i>Onomazein</i>, (34), 86-117.</span>\n</li>\n<li id=\"cite_note-43\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-43\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.fcg-net.org/\" rel=\"nofollow\">\"Fluid Construction Grammar – A fully operational processing system for construction grammars\"</a><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=Fluid+Construction+Grammar+%E2%80%93+A+fully+operational+processing+system+for+construction+grammars&amp;rft_id=https%3A%2F%2Fwww.fcg-net.org%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-44\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-44\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.aclweb.org/portal/\" rel=\"nofollow\">\"ACL Member Portal | The Association for Computational Linguistics Member Portal\"</a>. <i>www.aclweb.org</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.aclweb.org&amp;rft.atitle=ACL+Member+Portal+%7C+The+Association+for+Computational+Linguistics+Member+Portal&amp;rft_id=https%3A%2F%2Fwww.aclweb.org%2Fportal%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-45\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-45\">^</a></b></span> <span class=\"reference-text\"><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation web cs1\"><a class=\"external text\" href=\"https://www.w3.org/Data/demos/chunks/chunks.html\" rel=\"nofollow\">\"Chunks and Rules\"</a>. <i>www.w3.org</i><span class=\"reference-accessdate\">. Retrieved <span class=\"nowrap\">2021-01-11</span></span>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=www.w3.org&amp;rft.atitle=Chunks+and+Rules&amp;rft_id=https%3A%2F%2Fwww.w3.org%2FData%2Fdemos%2Fchunks%2Fchunks.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></span>\n</li>\n<li id=\"cite_note-46\"><span class=\"mw-cite-backlink\"><b><a href=\"#cite_ref-46\">^</a></b></span> <span class=\"reference-text\">Socher, R., Karpathy, A., Le, Q. V., Manning, C. D., &amp; Ng, A. Y. (2014). <a class=\"external text\" href=\"https://www.mitpressjournals.org/doi/pdfplus/10.1162/tacl_a_00177\" rel=\"nofollow\">Grounded compositional semantics for finding and describing images with sentences.</a> <i>Transactions of the Association for Computational Linguistics</i>, <i>2</i>, 207-218.</span>\n</li>\n</ol></div>\n<h2><span class=\"mw-headline\" id=\"Further_reading\">Further reading</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">[</span><a href=\"/w/index.php?title=Natural_language_processing&amp;action=edit&amp;section=20\" title=\"Edit section: Further reading\">edit</a><span class=\"mw-editsection-bracket\">]</span></span></h2>\n<style data-mw-deduplicate=\"TemplateStyles:r1011217839\">.mw-parser-output .refbegin{font-size:90%;margin-bottom:0.5em}.mw-parser-output .refbegin-hanging-indents>ul{margin-left:0}.mw-parser-output .refbegin-hanging-indents>ul>li{margin-left:0;padding-left:3.2em;text-indent:-3.2em}.mw-parser-output .refbegin-hanging-indents ul,.mw-parser-output .refbegin-hanging-indents ul li{list-style:none}@media(max-width:720px){.mw-parser-output .refbegin-hanging-indents>ul>li{padding-left:1.6em;text-indent:-1.6em}}.mw-parser-output .refbegin-100{font-size:100%}.mw-parser-output .refbegin-columns{margin-top:0.3em}.mw-parser-output .refbegin-columns ul{margin-top:0}.mw-parser-output .refbegin-columns li{page-break-inside:avoid;break-inside:avoid-column}</style><div class=\"refbegin\" style=\"\">\n<ul><li><link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><cite class=\"citation journal cs1\" id=\"CITEREFBates1995\">Bates, M (1995). <a class=\"external text\" href=\"//www.ncbi.nlm.nih.gov/pmc/articles/PMC40721\" rel=\"nofollow\">\"Models of natural language understanding\"</a>. <i>Proceedings of the National Academy of Sciences of the United States of America</i>. <b>92</b> (22): 9977–9982. <a class=\"mw-redirect\" href=\"/wiki/Bibcode_(identifier)\" title=\"Bibcode (identifier)\">Bibcode</a>:<a class=\"external text\" href=\"https://ui.adsabs.harvard.edu/abs/1995PNAS...92.9977B\" rel=\"nofollow\">1995PNAS...92.9977B</a>. <a class=\"mw-redirect\" href=\"/wiki/Doi_(identifier)\" title=\"Doi (identifier)\">doi</a>:<a class=\"external text\" href=\"https://doi.org/10.1073%2Fpnas.92.22.9977\" rel=\"nofollow\">10.1073/pnas.92.22.9977</a>. <a class=\"mw-redirect\" href=\"/wiki/PMC_(identifier)\" title=\"PMC (identifier)\">PMC</a> <span class=\"cs1-lock-free\" title=\"Freely accessible\"><a class=\"external text\" href=\"//www.ncbi.nlm.nih.gov/pmc/articles/PMC40721\" rel=\"nofollow\">40721</a></span>. <a class=\"mw-redirect\" href=\"/wiki/PMID_(identifier)\" title=\"PMID (identifier)\">PMID</a> <a class=\"external text\" href=\"//pubmed.ncbi.nlm.nih.gov/7479812\" rel=\"nofollow\">7479812</a>.</cite><span class=\"Z3988\" title=\"ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=Proceedings+of+the+National+Academy+of+Sciences+of+the+United+States+of+America&amp;rft.atitle=Models+of+natural+language+understanding&amp;rft.volume=92&amp;rft.issue=22&amp;rft.pages=9977-9982&amp;rft.date=1995&amp;rft_id=%2F%2Fwww.ncbi.nlm.nih.gov%2Fpmc%2Farticles%2FPMC40721%23id-name%3DPMC&amp;rft_id=info%3Apmid%2F7479812&amp;rft_id=info%3Adoi%2F10.1073%2Fpnas.92.22.9977&amp;rft_id=info%3Abibcode%2F1995PNAS...92.9977B&amp;rft.aulast=Bates&amp;rft.aufirst=M&amp;rft_id=%2F%2Fwww.ncbi.nlm.nih.gov%2Fpmc%2Farticles%2FPMC40721&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3ANatural+language+processing\"></span></li>\n<li>Steven Bird, Ewan Klein, and Edward Loper (2009). <i>Natural Language Processing with Python</i>. O'Reilly Media. <link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-0-596-51649-9\" title=\"Special:BookSources/978-0-596-51649-9\">978-0-596-51649-9</a>.</li>\n<li>Daniel Jurafsky and James H. Martin (2008). <i>Speech and Language Processing</i>, 2nd edition. Pearson Prentice Hall. <link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-0-13-187321-6\" title=\"Special:BookSources/978-0-13-187321-6\">978-0-13-187321-6</a>.</li>\n<li>Mohamed Zakaria Kurdi (2016). <i>Natural Language Processing and Computational Linguistics: speech, morphology, and syntax</i>, Volume 1. ISTE-Wiley. <link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-1848218482\" title=\"Special:BookSources/978-1848218482\">978-1848218482</a>.</li>\n<li>Mohamed Zakaria Kurdi (2017). <i>Natural Language Processing and Computational Linguistics: semantics, discourse, and applications</i>, Volume 2. ISTE-Wiley. <link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-1848219212\" title=\"Special:BookSources/978-1848219212\">978-1848219212</a>.</li>\n<li>Christopher D. Manning, Prabhakar Raghavan, and Hinrich Schütze (2008). <i>Introduction to Information Retrieval</i>. Cambridge University Press. <link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-0-521-86571-5\" title=\"Special:BookSources/978-0-521-86571-5\">978-0-521-86571-5</a>. <a class=\"external text\" href=\"http://nlp.stanford.edu/IR-book/\" rel=\"nofollow\">Official html and pdf versions available without charge.</a></li>\n<li>Christopher D. Manning and Hinrich Schütze (1999). <i>Foundations of Statistical Natural Language Processing</i>. The MIT Press. <link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-0-262-13360-9\" title=\"Special:BookSources/978-0-262-13360-9\">978-0-262-13360-9</a>.</li>\n<li>David M. W. Powers and Christopher C. R. Turk (1989). <i>Machine Learning of Natural Language</i>. Springer-Verlag. <link href=\"mw-data:TemplateStyles:r999302996\" rel=\"mw-deduplicated-inline-style\"/><a class=\"mw-redirect\" href=\"/wiki/ISBN_(identifier)\" title=\"ISBN (identifier)\">ISBN</a> <a href=\"/wiki/Special:BookSources/978-0-387-19557-5\" title=\"Special:BookSources/978-0-387-19557-5\">978-0-387-19557-5</a>.</li></ul>\n</div>\n<table class=\"mbox-small plainlinks sistersitebox\" role=\"presentation\" style=\"background-color:#f9f9f9;border:1px solid #aaa;color:#000\">\n<tbody><tr>\n<td class=\"mbox-image\"><img alt=\"\" class=\"noviewer\" data-file-height=\"1376\" data-file-width=\"1024\" decoding=\"async\" height=\"40\" src=\"//upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/30px-Commons-logo.svg.png\" srcset=\"//upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/45px-Commons-logo.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/59px-Commons-logo.svg.png 2x\" width=\"30\"/></td>\n<td class=\"mbox-text plainlist\">Wikimedia Commons has media related to <i><b><a class=\"extiw\" href=\"https://commons.wikimedia.org/wiki/Category:Natural_language_processing\" title=\"commons:Category:Natural language processing\">Natural language processing</a></b></i>.</td></tr>\n</tbody></table>\n<div aria-labelledby=\"Natural_language_processing\" class=\"navbox\" role=\"navigation\" style=\"padding:3px\"><table class=\"nowraplinks hlist mw-collapsible mw-collapsed navbox-inner\" style=\"border-spacing:0;background:transparent;color:inherit\"><tbody><tr><th class=\"navbox-title\" colspan=\"2\" scope=\"col\"><style data-mw-deduplicate=\"TemplateStyles:r992953826\">.mw-parser-output .navbar{display:inline;font-size:88%;font-weight:normal}.mw-parser-output .navbar-collapse{float:left;text-align:left}.mw-parser-output .navbar-boxtext{word-spacing:0}.mw-parser-output .navbar ul{display:inline-block;white-space:nowrap;line-height:inherit}.mw-parser-output .navbar-brackets::before{margin-right:-0.125em;content:\"[ \"}.mw-parser-output .navbar-brackets::after{margin-left:-0.125em;content:\" ]\"}.mw-parser-output .navbar li{word-spacing:-0.125em}.mw-parser-output .navbar-mini abbr{font-variant:small-caps;border-bottom:none;text-decoration:none;cursor:inherit}.mw-parser-output .navbar-ct-full{font-size:114%;margin:0 7em}.mw-parser-output .navbar-ct-mini{font-size:114%;margin:0 4em}.mw-parser-output .infobox .navbar{font-size:100%}.mw-parser-output .navbox .navbar{display:block;font-size:100%}.mw-parser-output .navbox-title .navbar{float:left;text-align:left;margin-right:0.5em}</style><div class=\"navbar plainlinks hlist navbar-mini\"><ul><li class=\"nv-view\"><a href=\"/wiki/Template:Natural_language_processing\" title=\"Template:Natural language processing\"><abbr style=\";;background:none transparent;border:none;box-shadow:none;padding:0;\" title=\"View this template\">v</abbr></a></li><li class=\"nv-talk\"><a href=\"/wiki/Template_talk:Natural_language_processing\" title=\"Template talk:Natural language processing\"><abbr style=\";;background:none transparent;border:none;box-shadow:none;padding:0;\" title=\"Discuss this template\">t</abbr></a></li><li class=\"nv-edit\"><a class=\"external text\" href=\"https://en.wikipedia.org/w/index.php?title=Template:Natural_language_processing&amp;action=edit\"><abbr style=\";;background:none transparent;border:none;box-shadow:none;padding:0;\" title=\"Edit this template\">e</abbr></a></li></ul></div><div id=\"Natural_language_processing\" style=\"font-size:114%;margin:0 4em\"><a class=\"mw-selflink selflink\">Natural language processing</a></div></th></tr><tr><th class=\"navbox-group\" scope=\"row\" style=\"width:1%\">General terms</th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><a href=\"/wiki/AI-complete\" title=\"AI-complete\">AI-complete</a></li>\n<li><a href=\"/wiki/Bag-of-words_model\" title=\"Bag-of-words model\">Bag-of-words</a></li>\n<li><a href=\"/wiki/N-gram\" title=\"N-gram\">n-gram</a>\n<ul><li><a href=\"/wiki/Bigram\" title=\"Bigram\">Bigram</a></li>\n<li><a href=\"/wiki/Trigram\" title=\"Trigram\">Trigram</a></li></ul></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Natural_language_understanding\" title=\"Natural language understanding\">Natural language understanding</a></li>\n<li><a href=\"/wiki/Speech_corpus\" title=\"Speech corpus\">Speech corpus</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Stop_words\" title=\"Stop words\">Stopwords</a></li>\n<li><a href=\"/wiki/Text_corpus\" title=\"Text corpus\">Text corpus</a></li></ul>\n</div></td></tr><tr><th class=\"navbox-group\" scope=\"row\" style=\"width:1%\"><a href=\"/wiki/Text_mining\" title=\"Text mining\">Text analysis</a></th><td class=\"navbox-list navbox-even\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><a href=\"/wiki/Collocation_extraction\" title=\"Collocation extraction\">Collocation extraction</a></li>\n<li><a href=\"/wiki/Concept_mining\" title=\"Concept mining\">Concept mining</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Compound_term_processing\" title=\"Compound term processing\">Compound term processing</a></li>\n<li><a href=\"/wiki/Coreference#Coreference_resolution\" title=\"Coreference\">Coreference resolution</a></li>\n<li><a href=\"/wiki/Lemmatisation\" title=\"Lemmatisation\">Lemmatisation</a></li>\n<li><a href=\"/wiki/Named-entity_recognition\" title=\"Named-entity recognition\">Named-entity recognition</a></li>\n<li><a href=\"/wiki/Ontology_learning\" title=\"Ontology learning\">Ontology learning</a></li>\n<li><a href=\"/wiki/Parsing\" title=\"Parsing\">Parsing</a></li>\n<li><a href=\"/wiki/Part-of-speech_tagging\" title=\"Part-of-speech tagging\">Part-of-speech tagging</a></li>\n<li><a href=\"/wiki/Semantic_similarity\" title=\"Semantic similarity\">Semantic similarity</a></li>\n<li><a href=\"/wiki/Sentiment_analysis\" title=\"Sentiment analysis\">Sentiment analysis</a></li>\n<li><a href=\"/wiki/Stemming\" title=\"Stemming\">Stemming</a></li>\n<li><a href=\"/wiki/Terminology_extraction\" title=\"Terminology extraction\">Terminology extraction</a></li>\n<li><a href=\"/wiki/Shallow_parsing\" title=\"Shallow parsing\">Text chunking</a></li>\n<li><a href=\"/wiki/Text_segmentation\" title=\"Text segmentation\">Text segmentation</a>\n<ul><li><a href=\"/wiki/Sentence_boundary_disambiguation\" title=\"Sentence boundary disambiguation\">Sentence segmentation</a></li>\n<li><a href=\"/wiki/Word#Word_boundaries\" title=\"Word\">Word segmentation</a></li></ul></li>\n<li><a href=\"/wiki/Textual_entailment\" title=\"Textual entailment\">Textual entailment</a></li>\n<li><a href=\"/wiki/Truecasing\" title=\"Truecasing\">Truecasing</a></li>\n<li><a href=\"/wiki/Word-sense_disambiguation\" title=\"Word-sense disambiguation\">Word-sense disambiguation</a></li></ul>\n</div></td></tr><tr><th class=\"navbox-group\" scope=\"row\" style=\"width:1%\"><a href=\"/wiki/Automatic_summarization\" title=\"Automatic summarization\">Automatic summarization</a></th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><a href=\"/wiki/Multi-document_summarization\" title=\"Multi-document summarization\">Multi-document summarization</a></li>\n<li><a href=\"/wiki/Sentence_extraction\" title=\"Sentence extraction\">Sentence extraction</a></li>\n<li><a href=\"/wiki/Text_simplification\" title=\"Text simplification\">Text simplification</a></li></ul>\n</div></td></tr><tr><th class=\"navbox-group\" scope=\"row\" style=\"width:1%\"><a href=\"/wiki/Machine_translation\" title=\"Machine translation\">Machine translation</a></th><td class=\"navbox-list navbox-even\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><a href=\"/wiki/Computer-assisted_translation\" title=\"Computer-assisted translation\">Computer-assisted</a></li>\n<li><a href=\"/wiki/Example-based_machine_translation\" title=\"Example-based machine translation\">Example-based</a></li>\n<li><a href=\"/wiki/Rule-based_machine_translation\" title=\"Rule-based machine translation\">Rule-based</a></li>\n<li><a href=\"/wiki/Neural_machine_translation\" title=\"Neural machine translation\">Neural</a></li></ul>\n</div></td></tr><tr><th class=\"navbox-group\" scope=\"row\" style=\"width:1%\"><a href=\"/wiki/Automatic_identification_and_data_capture\" title=\"Automatic identification and data capture\">Automatic identification<br/>and data capture</a></th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">Speech recognition</a></li>\n<li><a href=\"/wiki/Speech_segmentation\" title=\"Speech segmentation\">Speech segmentation</a></li>\n<li><a href=\"/wiki/Speech_synthesis\" title=\"Speech synthesis\">Speech synthesis</a></li>\n<li><a class=\"mw-redirect\" href=\"/wiki/Natural_language_generation\" title=\"Natural language generation\">Natural language generation</a></li>\n<li><a href=\"/wiki/Optical_character_recognition\" title=\"Optical character recognition\">Optical character recognition</a></li></ul>\n</div></td></tr><tr><th class=\"navbox-group\" scope=\"row\" style=\"width:1%\"><a href=\"/wiki/Topic_model\" title=\"Topic model\">Topic model</a></th><td class=\"navbox-list navbox-even\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><a href=\"/wiki/Latent_Dirichlet_allocation\" title=\"Latent Dirichlet allocation\">Latent Dirichlet allocation</a></li>\n<li><a href=\"/wiki/Latent_semantic_analysis\" title=\"Latent semantic analysis\">Latent semantic analysis</a></li>\n<li><a href=\"/wiki/Pachinko_allocation\" title=\"Pachinko allocation\">Pachinko allocation</a></li></ul>\n</div></td></tr><tr><th class=\"navbox-group\" scope=\"row\" style=\"width:1%\"><a href=\"/wiki/Computer-assisted_reviewing\" title=\"Computer-assisted reviewing\">Computer-assisted<br/>reviewing</a></th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><a href=\"/wiki/Automated_essay_scoring\" title=\"Automated essay scoring\">Automated essay scoring</a></li>\n<li><a href=\"/wiki/Concordancer\" title=\"Concordancer\">Concordancer</a></li>\n<li><a href=\"/wiki/Grammar_checker\" title=\"Grammar checker\">Grammar checker</a></li>\n<li><a href=\"/wiki/Predictive_text\" title=\"Predictive text\">Predictive text</a></li>\n<li><a href=\"/wiki/Spell_checker\" title=\"Spell checker\">Spell checker</a></li>\n<li><a href=\"/wiki/Syntax_guessing\" title=\"Syntax guessing\">Syntax guessing</a></li></ul>\n</div></td></tr><tr><th class=\"navbox-group\" scope=\"row\" style=\"width:1%\"><a class=\"mw-redirect\" href=\"/wiki/Natural_language_user_interface\" title=\"Natural language user interface\">Natural language<br/>user interface</a></th><td class=\"navbox-list navbox-even\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><a href=\"/wiki/Chatbot\" title=\"Chatbot\">Chatbot</a></li>\n<li><a href=\"/wiki/Interactive_fiction\" title=\"Interactive fiction\">Interactive fiction</a></li>\n<li><a href=\"/wiki/Question_answering\" title=\"Question answering\">Question answering</a></li>\n<li><a href=\"/wiki/Virtual_assistant\" title=\"Virtual assistant\">Virtual assistant</a></li>\n<li><a href=\"/wiki/Voice_user_interface\" title=\"Voice user interface\">Voice user interface</a></li></ul>\n</div></td></tr></tbody></table></div>\n<div aria-labelledby=\"Authority_control_frameless_&amp;#124;text-top_&amp;#124;10px_&amp;#124;alt=Edit_this_at_Wikidata_&amp;#124;link=https&amp;#58;//www.wikidata.org/wiki/Q30642#identifiers&amp;#124;Edit_this_at_Wikidata\" class=\"navbox authority-control\" role=\"navigation\" style=\"padding:3px\"><table class=\"nowraplinks hlist navbox-inner\" style=\"border-spacing:0;background:transparent;color:inherit\"><tbody><tr><th class=\"navbox-group\" id=\"Authority_control_frameless_&amp;#124;text-top_&amp;#124;10px_&amp;#124;alt=Edit_this_at_Wikidata_&amp;#124;link=https&amp;#58;//www.wikidata.org/wiki/Q30642#identifiers&amp;#124;Edit_this_at_Wikidata\" scope=\"row\" style=\"width:1%\"><a href=\"/wiki/Help:Authority_control\" title=\"Help:Authority control\">Authority control</a> <a href=\"https://www.wikidata.org/wiki/Q30642#identifiers\" title=\"Edit this at Wikidata\"><img alt=\"Edit this at Wikidata\" data-file-height=\"20\" data-file-width=\"20\" decoding=\"async\" height=\"10\" src=\"//upload.wikimedia.org/wikipedia/en/thumb/8/8a/OOjs_UI_icon_edit-ltr-progressive.svg/10px-OOjs_UI_icon_edit-ltr-progressive.svg.png\" srcset=\"//upload.wikimedia.org/wikipedia/en/thumb/8/8a/OOjs_UI_icon_edit-ltr-progressive.svg/15px-OOjs_UI_icon_edit-ltr-progressive.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/8/8a/OOjs_UI_icon_edit-ltr-progressive.svg/20px-OOjs_UI_icon_edit-ltr-progressive.svg.png 2x\" style=\"vertical-align: text-top\" width=\"10\"/></a></th><td class=\"navbox-list navbox-odd\" style=\"text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px\"><div style=\"padding:0em 0.25em\">\n<ul><li><span class=\"nowrap\"><a class=\"mw-redirect\" href=\"/wiki/LCCN_(identifier)\" title=\"LCCN (identifier)\">LCCN</a>: <span class=\"uid\"><a class=\"external text\" href=\"https://id.loc.gov/authorities/subjects/sh88002425\" rel=\"nofollow\">sh88002425</a></span></span></li>\n<li><span class=\"nowrap\"><a class=\"mw-redirect\" href=\"/wiki/NDL_(identifier)\" title=\"NDL (identifier)\">NDL</a>: <span class=\"uid\"><a class=\"external text\" href=\"https://id.ndl.go.jp/auth/ndlna/00562347\" rel=\"nofollow\">00562347</a></span></span></li></ul>\n</div></td></tr></tbody></table></div>\n<div aria-label=\"Portals\" class=\"noprint metadata navbox\" role=\"navigation\" style=\"font-weight:bold;padding:0.4em 2em\"><ul style=\"margin:0.1em 0 0\"><li style=\"display:inline\"><span style=\"display:inline-block;white-space:nowrap\"><span style=\"margin:0 0.5em\"><a class=\"image\" href=\"/wiki/File:Globe_of_letters.svg\"><img alt=\"Globe of letters.svg\" data-file-height=\"512\" data-file-width=\"512\" decoding=\"async\" height=\"21\" src=\"//upload.wikimedia.org/wikipedia/commons/thumb/d/de/Globe_of_letters.svg/21px-Globe_of_letters.svg.png\" srcset=\"//upload.wikimedia.org/wikipedia/commons/thumb/d/de/Globe_of_letters.svg/32px-Globe_of_letters.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/d/de/Globe_of_letters.svg/42px-Globe_of_letters.svg.png 2x\" width=\"21\"/></a></span><a href=\"/wiki/Portal:Language\" title=\"Portal:Language\">Language portal</a></span></li></ul></div>\n<!-- \nNewPP limit report\nParsed by mw1267\nCached time: 20210414012917\nCache expiry: 2592000\nDynamic content: false\nComplications: [vary‐revision‐sha1]\nCPU time usage: 1.005 seconds\nReal time usage: 1.382 seconds\nPreprocessor visited node count: 4406/1000000\nPost‐expand include size: 98406/2097152 bytes\nTemplate argument size: 5151/2097152 bytes\nHighest expansion depth: 14/40\nExpensive parser function count: 3/500\nUnstrip recursion depth: 1/20\nUnstrip post‐expand size: 142685/5000000 bytes\nLua time usage: 0.495/10.000 seconds\nLua memory usage: 6443714/52428800 bytes\nNumber of Wikibase entities loaded: 1/400\n-->\n<!--\nTransclusion expansion time report (%,ms,calls,template)\n100.00% 1144.153 1 -total\n 44.83% 512.908 1 Template:Reflist\n 11.76% 134.511 7 Template:ISBN\n 11.63% 133.094 1 Template:Cite_conference\n 10.19% 116.587 18 Template:Cite_web\n 8.53% 97.569 1 Template:Short_description\n 7.23% 82.697 10 Template:Cite_journal\n 5.15% 58.934 1 Template:Natural_Language_Processing\n 5.01% 57.293 1 Template:Self-published_source\n 4.76% 54.473 1 Template:Authority_control\n-->\n<!-- Saved in parser cache with key enwiki:pcache:idhash:21652-0!canonical!math=5 and timestamp 20210414012916 and revision id 1016426461. Serialized with JSON.\n -->\n</div><noscript><img alt=\"\" height=\"1\" src=\"//en.wikipedia.org/wiki/Special:CentralAutoLogin/start?type=1x1\" style=\"border: none; position: absolute;\" title=\"\" width=\"1\"/></noscript>\n<div class=\"printfooter\">Retrieved from \"<a dir=\"ltr\" href=\"https://en.wikipedia.org/w/index.php?title=Natural_language_processing&amp;oldid=1016426461\">https://en.wikipedia.org/w/index.php?title=Natural_language_processing&amp;oldid=1016426461</a>\"</div></div>\n<div class=\"catlinks\" data-mw=\"interface\" id=\"catlinks\"><div class=\"mw-normal-catlinks\" id=\"mw-normal-catlinks\"><a href=\"/wiki/Help:Category\" title=\"Help:Category\">Categories</a>: <ul><li><a href=\"/wiki/Category:Natural_language_processing\" title=\"Category:Natural language processing\">Natural language processing</a></li><li><a href=\"/wiki/Category:Computational_linguistics\" title=\"Category:Computational linguistics\">Computational linguistics</a></li><li><a href=\"/wiki/Category:Speech_recognition\" title=\"Category:Speech recognition\">Speech recognition</a></li><li><a href=\"/wiki/Category:Computational_fields_of_study\" title=\"Category:Computational fields of study\">Computational fields of study</a></li><li><a href=\"/wiki/Category:Artificial_intelligence\" title=\"Category:Artificial intelligence\">Artificial intelligence</a></li></ul></div><div class=\"mw-hidden-catlinks mw-hidden-cats-hidden\" id=\"mw-hidden-catlinks\">Hidden categories: <ul><li><a href=\"/wiki/Category:CS1_maint:_location\" title=\"Category:CS1 maint: location\">CS1 maint: location</a></li><li><a href=\"/wiki/Category:Articles_with_short_description\" title=\"Category:Articles with short description\">Articles with short description</a></li><li><a href=\"/wiki/Category:Short_description_matches_Wikidata\" title=\"Category:Short description matches Wikidata\">Short description matches Wikidata</a></li><li><a href=\"/wiki/Category:Commons_link_from_Wikidata\" title=\"Category:Commons link from Wikidata\">Commons link from Wikidata</a></li><li><a href=\"/wiki/Category:Wikipedia_articles_with_LCCN_identifiers\" title=\"Category:Wikipedia articles with LCCN identifiers\">Wikipedia articles with LCCN identifiers</a></li><li><a href=\"/wiki/Category:Wikipedia_articles_with_NDL_identifiers\" title=\"Category:Wikipedia articles with NDL identifiers\">Wikipedia articles with NDL identifiers</a></li></ul></div></div>\n</div>\n</div>\n<div id=\"mw-data-after-content\">\n<div class=\"read-more-container\"></div>\n</div>\n<div id=\"mw-navigation\">\n<h2>Navigation menu</h2>\n<div id=\"mw-head\">\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-personal-label\" class=\"mw-portlet mw-portlet-personal vector-menu\" id=\"p-personal\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-personal-label\">\n<span>Personal tools</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li id=\"pt-anonuserpage\">Not logged in</li><li id=\"pt-anontalk\"><a accesskey=\"n\" href=\"/wiki/Special:MyTalk\" title=\"Discussion about edits from this IP address [n]\">Talk</a></li><li id=\"pt-anoncontribs\"><a accesskey=\"y\" href=\"/wiki/Special:MyContributions\" title=\"A list of edits made from this IP address [y]\">Contributions</a></li><li id=\"pt-createaccount\"><a href=\"/w/index.php?title=Special:CreateAccount&amp;returnto=Natural+language+processing\" title=\"You are encouraged to create an account and log in; however, it is not mandatory\">Create account</a></li><li id=\"pt-login\"><a accesskey=\"o\" href=\"/w/index.php?title=Special:UserLogin&amp;returnto=Natural+language+processing\" title=\"You're encouraged to log in; however, it's not mandatory. [o]\">Log in</a></li></ul>\n</div>\n</nav>\n<div id=\"left-navigation\">\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-namespaces-label\" class=\"mw-portlet mw-portlet-namespaces vector-menu vector-menu-tabs\" id=\"p-namespaces\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-namespaces-label\">\n<span>Namespaces</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li class=\"selected\" id=\"ca-nstab-main\"><a accesskey=\"c\" href=\"/wiki/Natural_language_processing\" title=\"View the content page [c]\">Article</a></li><li id=\"ca-talk\"><a accesskey=\"t\" href=\"/wiki/Talk:Natural_language_processing\" rel=\"discussion\" title=\"Discuss improvements to the content page [t]\">Talk</a></li></ul>\n</div>\n</nav>\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-variants-label\" class=\"mw-portlet mw-portlet-variants emptyPortlet vector-menu vector-menu-dropdown\" id=\"p-variants\" role=\"navigation\">\n<input aria-labelledby=\"p-variants-label\" class=\"vector-menu-checkbox\" type=\"checkbox\"/>\n<h3 class=\"vector-menu-heading\" id=\"p-variants-label\">\n<span>Variants</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"></ul>\n</div>\n</nav>\n</div>\n<div id=\"right-navigation\">\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-views-label\" class=\"mw-portlet mw-portlet-views vector-menu vector-menu-tabs\" id=\"p-views\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-views-label\">\n<span>Views</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li class=\"selected\" id=\"ca-view\"><a href=\"/wiki/Natural_language_processing\">Read</a></li><li id=\"ca-edit\"><a accesskey=\"e\" href=\"/w/index.php?title=Natural_language_processing&amp;action=edit\" title=\"Edit this page [e]\">Edit</a></li><li id=\"ca-history\"><a accesskey=\"h\" href=\"/w/index.php?title=Natural_language_processing&amp;action=history\" title=\"Past revisions of this page [h]\">View history</a></li></ul>\n</div>\n</nav>\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-cactions-label\" class=\"mw-portlet mw-portlet-cactions emptyPortlet vector-menu vector-menu-dropdown\" id=\"p-cactions\" role=\"navigation\">\n<input aria-labelledby=\"p-cactions-label\" class=\"vector-menu-checkbox\" type=\"checkbox\"/>\n<h3 class=\"vector-menu-heading\" id=\"p-cactions-label\">\n<span>More</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"></ul>\n</div>\n</nav>\n<div id=\"p-search\" role=\"search\">\n<h3>\n<label for=\"searchInput\">Search</label>\n</h3>\n<form action=\"/w/index.php\" id=\"searchform\">\n<div data-search-loc=\"header-navigation\" id=\"simpleSearch\">\n<input accesskey=\"f\" autocapitalize=\"sentences\" id=\"searchInput\" name=\"search\" placeholder=\"Search Wikipedia\" title=\"Search Wikipedia [f]\" type=\"search\"/>\n<input name=\"title\" type=\"hidden\" value=\"Special:Search\"/>\n<input class=\"searchButton mw-fallbackSearchButton\" id=\"mw-searchButton\" name=\"fulltext\" title=\"Search Wikipedia for this text\" type=\"submit\" value=\"Search\"/>\n<input class=\"searchButton\" id=\"searchButton\" name=\"go\" title=\"Go to a page with this exact name if it exists\" type=\"submit\" value=\"Go\"/>\n</div>\n</form>\n</div>\n</div>\n</div>\n<div id=\"mw-panel\">\n<div id=\"p-logo\" role=\"banner\">\n<a class=\"mw-wiki-logo\" href=\"/wiki/Main_Page\" title=\"Visit the main page\"></a>\n</div>\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-navigation-label\" class=\"mw-portlet mw-portlet-navigation vector-menu vector-menu-portal portal\" id=\"p-navigation\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-navigation-label\">\n<span>Navigation</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li id=\"n-mainpage-description\"><a accesskey=\"z\" href=\"/wiki/Main_Page\" title=\"Visit the main page [z]\">Main page</a></li><li id=\"n-contents\"><a href=\"/wiki/Wikipedia:Contents\" title=\"Guides to browsing Wikipedia\">Contents</a></li><li id=\"n-currentevents\"><a href=\"/wiki/Portal:Current_events\" title=\"Articles related to current events\">Current events</a></li><li id=\"n-randompage\"><a accesskey=\"x\" href=\"/wiki/Special:Random\" title=\"Visit a randomly selected article [x]\">Random article</a></li><li id=\"n-aboutsite\"><a href=\"/wiki/Wikipedia:About\" title=\"Learn about Wikipedia and how it works\">About Wikipedia</a></li><li id=\"n-contactpage\"><a href=\"//en.wikipedia.org/wiki/Wikipedia:Contact_us\" title=\"How to contact Wikipedia\">Contact us</a></li><li id=\"n-sitesupport\"><a href=\"https://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&amp;utm_medium=sidebar&amp;utm_campaign=C13_en.wikipedia.org&amp;uselang=en\" title=\"Support us by donating to the Wikimedia Foundation\">Donate</a></li></ul>\n</div>\n</nav>\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-interaction-label\" class=\"mw-portlet mw-portlet-interaction vector-menu vector-menu-portal portal\" id=\"p-interaction\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-interaction-label\">\n<span>Contribute</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li id=\"n-help\"><a href=\"/wiki/Help:Contents\" title=\"Guidance on how to use and edit Wikipedia\">Help</a></li><li id=\"n-introduction\"><a href=\"/wiki/Help:Introduction\" title=\"Learn how to edit Wikipedia\">Learn to edit</a></li><li id=\"n-portal\"><a href=\"/wiki/Wikipedia:Community_portal\" title=\"The hub for editors\">Community portal</a></li><li id=\"n-recentchanges\"><a accesskey=\"r\" href=\"/wiki/Special:RecentChanges\" title=\"A list of recent changes to Wikipedia [r]\">Recent changes</a></li><li id=\"n-upload\"><a href=\"/wiki/Wikipedia:File_Upload_Wizard\" title=\"Add images or other media for use on Wikipedia\">Upload file</a></li></ul>\n</div>\n</nav>\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-tb-label\" class=\"mw-portlet mw-portlet-tb vector-menu vector-menu-portal portal\" id=\"p-tb\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-tb-label\">\n<span>Tools</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li id=\"t-whatlinkshere\"><a accesskey=\"j\" href=\"/wiki/Special:WhatLinksHere/Natural_language_processing\" title=\"List of all English Wikipedia pages containing links to this page [j]\">What links here</a></li><li id=\"t-recentchangeslinked\"><a accesskey=\"k\" href=\"/wiki/Special:RecentChangesLinked/Natural_language_processing\" rel=\"nofollow\" title=\"Recent changes in pages linked from this page [k]\">Related changes</a></li><li id=\"t-upload\"><a accesskey=\"u\" href=\"/wiki/Wikipedia:File_Upload_Wizard\" title=\"Upload files [u]\">Upload file</a></li><li id=\"t-specialpages\"><a accesskey=\"q\" href=\"/wiki/Special:SpecialPages\" title=\"A list of all special pages [q]\">Special pages</a></li><li id=\"t-permalink\"><a href=\"/w/index.php?title=Natural_language_processing&amp;oldid=1016426461\" title=\"Permanent link to this revision of this page\">Permanent link</a></li><li id=\"t-info\"><a href=\"/w/index.php?title=Natural_language_processing&amp;action=info\" title=\"More information about this page\">Page information</a></li><li id=\"t-cite\"><a href=\"/w/index.php?title=Special:CiteThisPage&amp;page=Natural_language_processing&amp;id=1016426461&amp;wpFormIdentifier=titleform\" title=\"Information on how to cite this page\">Cite this page</a></li><li id=\"t-wikibase\"><a accesskey=\"g\" href=\"https://www.wikidata.org/wiki/Special:EntityPage/Q30642\" title=\"Structured data on this page hosted by Wikidata [g]\">Wikidata item</a></li></ul>\n</div>\n</nav>\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-coll-print_export-label\" class=\"mw-portlet mw-portlet-coll-print_export vector-menu vector-menu-portal portal\" id=\"p-coll-print_export\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-coll-print_export-label\">\n<span>Print/export</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li id=\"coll-download-as-rl\"><a href=\"/w/index.php?title=Special:DownloadAsPdf&amp;page=Natural_language_processing&amp;action=show-download-screen\" title=\"Download this page as a PDF file\">Download as PDF</a></li><li id=\"t-print\"><a accesskey=\"p\" href=\"/w/index.php?title=Natural_language_processing&amp;printable=yes\" title=\"Printable version of this page [p]\">Printable version</a></li></ul>\n</div>\n</nav>\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-wikibase-otherprojects-label\" class=\"mw-portlet mw-portlet-wikibase-otherprojects vector-menu vector-menu-portal portal\" id=\"p-wikibase-otherprojects\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-wikibase-otherprojects-label\">\n<span>In other projects</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li class=\"wb-otherproject-link wb-otherproject-commons\"><a href=\"https://commons.wikimedia.org/wiki/Category:Natural_language_processing\" hreflang=\"en\">Wikimedia Commons</a></li></ul>\n</div>\n</nav>\n<!-- Please do not use role attribute as CSS selector, it is deprecated. -->\n<nav aria-labelledby=\"p-lang-label\" class=\"mw-portlet mw-portlet-lang vector-menu vector-menu-portal portal\" id=\"p-lang\" role=\"navigation\">\n<h3 class=\"vector-menu-heading\" id=\"p-lang-label\">\n<span>Languages</span>\n</h3>\n<div class=\"vector-menu-content\">\n<ul class=\"vector-menu-content-list\"><li class=\"interlanguage-link interwiki-af\"><a class=\"interlanguage-link-target\" href=\"https://af.wikipedia.org/wiki/Natuurliketaalverwerking\" hreflang=\"af\" lang=\"af\" title=\"Natuurliketaalverwerking – Afrikaans\">Afrikaans</a></li><li class=\"interlanguage-link interwiki-ar\"><a class=\"interlanguage-link-target\" href=\"https://ar.wikipedia.org/wiki/%D9%85%D8%B9%D8%A7%D9%84%D8%AC%D8%A9_%D8%A7%D9%84%D9%84%D8%BA%D8%A7%D8%AA_%D8%A7%D9%84%D8%B7%D8%A8%D9%8A%D8%B9%D9%8A%D8%A9\" hreflang=\"ar\" lang=\"ar\" title=\"معالجة اللغات الطبيعية – Arabic\">العربية</a></li><li class=\"interlanguage-link interwiki-az\"><a class=\"interlanguage-link-target\" href=\"https://az.wikipedia.org/wiki/T%C9%99bii_dilin_emal%C4%B1\" hreflang=\"az\" lang=\"az\" title=\"Təbii dilin emalı – Azerbaijani\">Azərbaycanca</a></li><li class=\"interlanguage-link interwiki-bn\"><a class=\"interlanguage-link-target\" href=\"https://bn.wikipedia.org/wiki/%E0%A6%B8%E0%A7%8D%E0%A6%AC%E0%A6%BE%E0%A6%AD%E0%A6%BE%E0%A6%AC%E0%A6%BF%E0%A6%95_%E0%A6%AD%E0%A6%BE%E0%A6%B7%E0%A6%BE_%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A6%95%E0%A7%8D%E0%A6%B0%E0%A6%BF%E0%A6%AF%E0%A6%BC%E0%A6%BE%E0%A6%9C%E0%A6%BE%E0%A6%A4%E0%A6%95%E0%A6%B0%E0%A6%A3\" hreflang=\"bn\" lang=\"bn\" title=\"স্বাভাবিক ভাষা প্রক্রিয়াজাতকরণ – Bangla\">বাংলা</a></li><li class=\"interlanguage-link interwiki-zh-min-nan\"><a class=\"interlanguage-link-target\" href=\"https://zh-min-nan.wikipedia.org/wiki/Ch%C5%AB-ji%C3%A2n_gi%C3%A2n-g%C3%BA_chh%C3%BA-l%C3%AD\" hreflang=\"nan\" lang=\"nan\" title=\"Chū-jiân giân-gú chhú-lí – Chinese (Min Nan)\">Bân-lâm-gú</a></li><li class=\"interlanguage-link interwiki-be\"><a class=\"interlanguage-link-target\" href=\"https://be.wikipedia.org/wiki/%D0%90%D0%BF%D1%80%D0%B0%D1%86%D0%BE%D1%9E%D0%BA%D0%B0_%D0%BD%D0%B0%D1%82%D1%83%D1%80%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D0%B9_%D0%BC%D0%BE%D0%B2%D1%8B\" hreflang=\"be\" lang=\"be\" title=\"Апрацоўка натуральнай мовы – Belarusian\">Беларуская</a></li><li class=\"interlanguage-link interwiki-be-x-old\"><a class=\"interlanguage-link-target\" href=\"https://be-tarask.wikipedia.org/wiki/%D0%90%D0%BF%D1%80%D0%B0%D1%86%D0%BE%D1%9E%D0%BA%D0%B0_%D0%BD%D0%B0%D1%82%D1%83%D1%80%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D0%B9_%D0%BC%D0%BE%D0%B2%D1%8B\" hreflang=\"be-tarask\" lang=\"be-tarask\" title=\"Апрацоўка натуральнай мовы – Belarusian (Taraškievica orthography)\">Беларуская (тарашкевіца)‎</a></li><li class=\"interlanguage-link interwiki-bg\"><a class=\"interlanguage-link-target\" href=\"https://bg.wikipedia.org/wiki/%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B0_%D0%BD%D0%B0_%D0%B5%D1%81%D1%82%D0%B5%D1%81%D1%82%D0%B2%D0%B5%D0%BD_%D0%B5%D0%B7%D0%B8%D0%BA\" hreflang=\"bg\" lang=\"bg\" title=\"Обработка на естествен език – Bulgarian\">Български</a></li><li class=\"interlanguage-link interwiki-ca\"><a class=\"interlanguage-link-target\" href=\"https://ca.wikipedia.org/wiki/Processament_de_llenguatge_natural\" hreflang=\"ca\" lang=\"ca\" title=\"Processament de llenguatge natural – Catalan\">Català</a></li><li class=\"interlanguage-link interwiki-cs\"><a class=\"interlanguage-link-target\" href=\"https://cs.wikipedia.org/wiki/Zpracov%C3%A1n%C3%AD_p%C5%99irozen%C3%A9ho_jazyka\" hreflang=\"cs\" lang=\"cs\" title=\"Zpracování přirozeného jazyka – Czech\">Čeština</a></li><li class=\"interlanguage-link interwiki-da\"><a class=\"interlanguage-link-target\" href=\"https://da.wikipedia.org/wiki/Sprogteknologi\" hreflang=\"da\" lang=\"da\" title=\"Sprogteknologi – Danish\">Dansk</a></li><li class=\"interlanguage-link interwiki-de\"><a class=\"interlanguage-link-target\" href=\"https://de.wikipedia.org/wiki/Verarbeitung_nat%C3%BCrlicher_Sprache\" hreflang=\"de\" lang=\"de\" title=\"Verarbeitung natürlicher Sprache – German\">Deutsch</a></li><li class=\"interlanguage-link interwiki-et\"><a class=\"interlanguage-link-target\" href=\"https://et.wikipedia.org/wiki/Loomuliku_keele_t%C3%B6%C3%B6tlus\" hreflang=\"et\" lang=\"et\" title=\"Loomuliku keele töötlus – Estonian\">Eesti</a></li><li class=\"interlanguage-link interwiki-el\"><a class=\"interlanguage-link-target\" href=\"https://el.wikipedia.org/wiki/%CE%95%CF%80%CE%B5%CE%BE%CE%B5%CF%81%CE%B3%CE%B1%CF%83%CE%AF%CE%B1_%CF%86%CF%85%CF%83%CE%B9%CE%BA%CE%AE%CF%82_%CE%B3%CE%BB%CF%8E%CF%83%CF%83%CE%B1%CF%82\" hreflang=\"el\" lang=\"el\" title=\"Επεξεργασία φυσικής γλώσσας – Greek\">Ελληνικά</a></li><li class=\"interlanguage-link interwiki-es\"><a class=\"interlanguage-link-target\" href=\"https://es.wikipedia.org/wiki/Procesamiento_de_lenguajes_naturales\" hreflang=\"es\" lang=\"es\" title=\"Procesamiento de lenguajes naturales – Spanish\">Español</a></li><li class=\"interlanguage-link interwiki-eu\"><a class=\"interlanguage-link-target\" href=\"https://eu.wikipedia.org/wiki/Hizkuntzaren_prozesamendu\" hreflang=\"eu\" lang=\"eu\" title=\"Hizkuntzaren prozesamendu – Basque\">Euskara</a></li><li class=\"interlanguage-link interwiki-fa\"><a class=\"interlanguage-link-target\" href=\"https://fa.wikipedia.org/wiki/%D9%BE%D8%B1%D8%AF%D8%A7%D8%B2%D8%B4_%D8%B2%D8%A8%D8%A7%D9%86%E2%80%8C%D9%87%D8%A7%DB%8C_%D8%B7%D8%A8%DB%8C%D8%B9%DB%8C\" hreflang=\"fa\" lang=\"fa\" title=\"پردازش زبان‌های طبیعی – Persian\">فارسی</a></li><li class=\"interlanguage-link interwiki-fr\"><a class=\"interlanguage-link-target\" href=\"https://fr.wikipedia.org/wiki/Traitement_automatique_des_langues\" hreflang=\"fr\" lang=\"fr\" title=\"Traitement automatique des langues – French\">Français</a></li><li class=\"interlanguage-link interwiki-gl\"><a class=\"interlanguage-link-target\" href=\"https://gl.wikipedia.org/wiki/Procesamento_da_linguaxe_natural\" hreflang=\"gl\" lang=\"gl\" title=\"Procesamento da linguaxe natural – Galician\">Galego</a></li><li class=\"interlanguage-link interwiki-ko\"><a class=\"interlanguage-link-target\" href=\"https://ko.wikipedia.org/wiki/%EC%9E%90%EC%97%B0%EC%96%B4_%EC%B2%98%EB%A6%AC\" hreflang=\"ko\" lang=\"ko\" title=\"자연어 처리 – Korean\">한국어</a></li><li class=\"interlanguage-link interwiki-hy\"><a class=\"interlanguage-link-target\" href=\"https://hy.wikipedia.org/wiki/%D4%B2%D5%B6%D5%A1%D5%AF%D5%A1%D5%B6_%D5%AC%D5%A5%D5%A6%D5%BE%D5%AB_%D5%B4%D5%B7%D5%A1%D5%AF%D5%B8%D6%82%D5%B4\" hreflang=\"hy\" lang=\"hy\" title=\"Բնական լեզվի մշակում – Armenian\">Հայերեն</a></li><li class=\"interlanguage-link interwiki-hi\"><a class=\"interlanguage-link-target\" href=\"https://hi.wikipedia.org/wiki/%E0%A4%AA%E0%A5%8D%E0%A4%B0%E0%A4%BE%E0%A4%95%E0%A5%83%E0%A4%A4%E0%A4%BF%E0%A4%95_%E0%A4%AD%E0%A4%BE%E0%A4%B7%E0%A4%BE_%E0%A4%B8%E0%A4%82%E0%A4%B8%E0%A4%BE%E0%A4%A7%E0%A4%A8\" hreflang=\"hi\" lang=\"hi\" title=\"प्राकृतिक भाषा संसाधन – Hindi\">हिन्दी</a></li><li class=\"interlanguage-link interwiki-hr\"><a class=\"interlanguage-link-target\" href=\"https://hr.wikipedia.org/wiki/Obrada_prirodnog_jezika\" hreflang=\"hr\" lang=\"hr\" title=\"Obrada prirodnog jezika – Croatian\">Hrvatski</a></li><li class=\"interlanguage-link interwiki-id\"><a class=\"interlanguage-link-target\" href=\"https://id.wikipedia.org/wiki/Pemrosesan_bahasa_alami\" hreflang=\"id\" lang=\"id\" title=\"Pemrosesan bahasa alami – Indonesian\">Bahasa Indonesia</a></li><li class=\"interlanguage-link interwiki-is\"><a class=\"interlanguage-link-target\" href=\"https://is.wikipedia.org/wiki/M%C3%A1lgreining\" hreflang=\"is\" lang=\"is\" title=\"Málgreining – Icelandic\">Íslenska</a></li><li class=\"interlanguage-link interwiki-it\"><a class=\"interlanguage-link-target\" href=\"https://it.wikipedia.org/wiki/Elaborazione_del_linguaggio_naturale\" hreflang=\"it\" lang=\"it\" title=\"Elaborazione del linguaggio naturale – Italian\">Italiano</a></li><li class=\"interlanguage-link interwiki-he\"><a class=\"interlanguage-link-target\" href=\"https://he.wikipedia.org/wiki/%D7%A2%D7%99%D7%91%D7%95%D7%93_%D7%A9%D7%A4%D7%94_%D7%98%D7%91%D7%A2%D7%99%D7%AA\" hreflang=\"he\" lang=\"he\" title=\"עיבוד שפה טבעית – Hebrew\">עברית</a></li><li class=\"interlanguage-link interwiki-kn\"><a class=\"interlanguage-link-target\" href=\"https://kn.wikipedia.org/wiki/%E0%B2%AA%E0%B3%8D%E0%B2%B0%E0%B2%BE%E0%B2%95%E0%B3%83%E0%B2%A4%E0%B2%BF%E0%B2%95_%E0%B2%AD%E0%B2%BE%E0%B2%B7%E0%B3%86%E0%B2%AF_%E0%B2%AA%E0%B2%B0%E0%B2%BF%E0%B2%B7%E0%B3%8D%E0%B2%95%E0%B2%B0%E0%B2%A3%E0%B3%86\" hreflang=\"kn\" lang=\"kn\" title=\"ಪ್ರಾಕೃತಿಕ ಭಾಷೆಯ ಪರಿಷ್ಕರಣೆ – Kannada\">ಕನ್ನಡ</a></li><li class=\"interlanguage-link interwiki-ka\"><a class=\"interlanguage-link-target\" href=\"https://ka.wikipedia.org/wiki/%E1%83%91%E1%83%A3%E1%83%9C%E1%83%94%E1%83%91%E1%83%A0%E1%83%98%E1%83%95%E1%83%98_%E1%83%94%E1%83%9C%E1%83%98%E1%83%A1_%E1%83%93%E1%83%90%E1%83%9B%E1%83%A3%E1%83%A8%E1%83%90%E1%83%95%E1%83%94%E1%83%91%E1%83%90\" hreflang=\"ka\" lang=\"ka\" title=\"ბუნებრივი ენის დამუშავება – Georgian\">ქართული</a></li><li class=\"interlanguage-link interwiki-lt\"><a class=\"interlanguage-link-target\" href=\"https://lt.wikipedia.org/wiki/Nat%C5%ABralios_kalbos_apdorojimas\" hreflang=\"lt\" lang=\"lt\" title=\"Natūralios kalbos apdorojimas – Lithuanian\">Lietuvių</a></li><li class=\"interlanguage-link interwiki-mk\"><a class=\"interlanguage-link-target\" href=\"https://mk.wikipedia.org/wiki/%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B0_%D0%BD%D0%B0_%D0%BF%D1%80%D0%B8%D1%80%D0%BE%D0%B4%D0%BD%D0%B8_%D1%98%D0%B0%D0%B7%D0%B8%D1%86%D0%B8\" hreflang=\"mk\" lang=\"mk\" title=\"Обработка на природни јазици – Macedonian\">Македонски</a></li><li class=\"interlanguage-link interwiki-mr\"><a class=\"interlanguage-link-target\" href=\"https://mr.wikipedia.org/wiki/%E0%A4%A8%E0%A5%88%E0%A4%B8%E0%A4%B0%E0%A5%8D%E0%A4%97%E0%A4%BF%E0%A4%95_%E0%A4%AD%E0%A4%BE%E0%A4%B7%E0%A4%BE_%E0%A4%AA%E0%A5%8D%E0%A4%B0%E0%A4%95%E0%A5%8D%E0%A4%B0%E0%A4%BF%E0%A4%AF%E0%A4%BE\" hreflang=\"mr\" lang=\"mr\" title=\"नैसर्गिक भाषा प्रक्रिया – Marathi\">मराठी</a></li><li class=\"interlanguage-link interwiki-mn\"><a class=\"interlanguage-link-target\" href=\"https://mn.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BC%D0%BF%D1%8C%D1%8E%D1%82%D0%B5%D1%80%D1%8B%D0%BD_%D1%85%D1%8D%D0%BB_%D1%88%D0%B8%D0%BD%D0%B6%D0%BB%D1%8D%D0%BB\" hreflang=\"mn\" lang=\"mn\" title=\"Компьютерын хэл шинжлэл – Mongolian\">Монгол</a></li><li class=\"interlanguage-link interwiki-my\"><a class=\"interlanguage-link-target\" href=\"https://my.wikipedia.org/wiki/%E1%80%99%E1%80%AD%E1%80%81%E1%80%84%E1%80%BA%E1%80%98%E1%80%AC%E1%80%9E%E1%80%AC%E1%80%85%E1%80%80%E1%80%AC%E1%80%B8%E1%80%9E%E1%80%AF%E1%80%B6%E1%80%B8_%E1%80%80%E1%80%BD%E1%80%94%E1%80%BA%E1%80%95%E1%80%BB%E1%80%B0%E1%80%90%E1%80%AC%E1%80%85%E1%80%94%E1%80%85%E1%80%BA\" hreflang=\"my\" lang=\"my\" title=\"မိခင်ဘာသာစကားသုံး ကွန်ပျူတာစနစ် – Burmese\">မြန်မာဘာသာ</a></li><li class=\"interlanguage-link interwiki-ja\"><a class=\"interlanguage-link-target\" href=\"https://ja.wikipedia.org/wiki/%E8%87%AA%E7%84%B6%E8%A8%80%E8%AA%9E%E5%87%A6%E7%90%86\" hreflang=\"ja\" lang=\"ja\" title=\"自然言語処理 – Japanese\">日本語</a></li><li class=\"interlanguage-link interwiki-or\"><a class=\"interlanguage-link-target\" href=\"https://or.wikipedia.org/wiki/%E0%AC%A8%E0%AD%8D%E0%AD%9F%E0%AC%BE%E0%AC%9A%E0%AD%81%E0%AC%B0%E0%AC%BE%E0%AC%B2_%E0%AC%B2%E0%AC%BE%E0%AC%99%E0%AD%8D%E0%AC%97%E0%AD%81%E0%AC%8F%E0%AC%9C_%E0%AC%AA%E0%AD%8D%E0%AC%B0%E0%AD%8B%E0%AC%B8%E0%AD%87%E0%AC%B8%E0%AC%BF%E0%AC%82\" hreflang=\"or\" lang=\"or\" title=\"ନ୍ୟାଚୁରାଲ ଲାଙ୍ଗୁଏଜ ପ୍ରୋସେସିଂ – Odia\">ଓଡ଼ିଆ</a></li><li class=\"interlanguage-link interwiki-pms\"><a class=\"interlanguage-link-target\" href=\"https://pms.wikipedia.org/wiki/NLP\" hreflang=\"pms\" lang=\"pms\" title=\"NLP – Piedmontese\">Piemontèis</a></li><li class=\"interlanguage-link interwiki-pl\"><a class=\"interlanguage-link-target\" href=\"https://pl.wikipedia.org/wiki/Przetwarzanie_j%C4%99zyka_naturalnego\" hreflang=\"pl\" lang=\"pl\" title=\"Przetwarzanie języka naturalnego – Polish\">Polski</a></li><li class=\"interlanguage-link interwiki-pt\"><a class=\"interlanguage-link-target\" href=\"https://pt.wikipedia.org/wiki/Processamento_de_linguagem_natural\" hreflang=\"pt\" lang=\"pt\" title=\"Processamento de linguagem natural – Portuguese\">Português</a></li><li class=\"interlanguage-link interwiki-ro\"><a class=\"interlanguage-link-target\" href=\"https://ro.wikipedia.org/wiki/Prelucrarea_limbajului_natural\" hreflang=\"ro\" lang=\"ro\" title=\"Prelucrarea limbajului natural – Romanian\">Română</a></li><li class=\"interlanguage-link interwiki-ru\"><a class=\"interlanguage-link-target\" href=\"https://ru.wikipedia.org/wiki/%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B0_%D0%B5%D1%81%D1%82%D0%B5%D1%81%D1%82%D0%B2%D0%B5%D0%BD%D0%BD%D0%BE%D0%B3%D0%BE_%D1%8F%D0%B7%D1%8B%D0%BA%D0%B0\" hreflang=\"ru\" lang=\"ru\" title=\"Обработка естественного языка – Russian\">Русский</a></li><li class=\"interlanguage-link interwiki-simple\"><a class=\"interlanguage-link-target\" href=\"https://simple.wikipedia.org/wiki/Natural_language_processing\" hreflang=\"en-simple\" lang=\"en-simple\" title=\"Natural language processing – Simple English\">Simple English</a></li><li class=\"interlanguage-link interwiki-ckb\"><a class=\"interlanguage-link-target\" href=\"https://ckb.wikipedia.org/wiki/%D9%BE%DB%8E%D9%88%D8%A7%DA%98%DB%86%DA%A9%D8%B1%D8%AF%D9%86%DB%8C_%D8%B2%D9%85%D8%A7%D9%86%DB%8C_%D8%B3%D8%B1%D9%88%D8%B4%D8%AA%DB%8C\" hreflang=\"ckb\" lang=\"ckb\" title=\"پێواژۆکردنی زمانی سروشتی – Central Kurdish\">کوردی</a></li><li class=\"interlanguage-link interwiki-sr\"><a class=\"interlanguage-link-target\" href=\"https://sr.wikipedia.org/wiki/Obrada_prirodnih_jezika\" hreflang=\"sr\" lang=\"sr\" title=\"Obrada prirodnih jezika – Serbian\">Српски / srpski</a></li><li class=\"interlanguage-link interwiki-sh\"><a class=\"interlanguage-link-target\" href=\"https://sh.wikipedia.org/wiki/Obrada_prirodnih_jezika\" hreflang=\"sh\" lang=\"sh\" title=\"Obrada prirodnih jezika – Serbo-Croatian\">Srpskohrvatski / српскохрватски</a></li><li class=\"interlanguage-link interwiki-ta\"><a class=\"interlanguage-link-target\" href=\"https://ta.wikipedia.org/wiki/%E0%AE%87%E0%AE%AF%E0%AE%B1%E0%AF%8D%E0%AE%95%E0%AF%88_%E0%AE%AE%E0%AF%8A%E0%AE%B4%E0%AE%BF_%E0%AE%AE%E0%AF%81%E0%AE%B1%E0%AF%88%E0%AE%AF%E0%AE%BE%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%AE%E0%AF%8D\" hreflang=\"ta\" lang=\"ta\" title=\"இயற்கை மொழி முறையாக்கம் – Tamil\">தமிழ்</a></li><li class=\"interlanguage-link interwiki-th\"><a class=\"interlanguage-link-target\" href=\"https://th.wikipedia.org/wiki/%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%A1%E0%B8%A7%E0%B8%A5%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B8%98%E0%B8%A3%E0%B8%A3%E0%B8%A1%E0%B8%8A%E0%B8%B2%E0%B8%95%E0%B8%B4\" hreflang=\"th\" lang=\"th\" title=\"การประมวลภาษาธรรมชาติ – Thai\">ไทย</a></li><li class=\"interlanguage-link interwiki-tr\"><a class=\"interlanguage-link-target\" href=\"https://tr.wikipedia.org/wiki/Do%C4%9Fal_dil_i%C5%9Fleme\" hreflang=\"tr\" lang=\"tr\" title=\"Doğal dil işleme – Turkish\">Türkçe</a></li><li class=\"interlanguage-link interwiki-uk\"><a class=\"interlanguage-link-target\" href=\"https://uk.wikipedia.org/wiki/%D0%9E%D0%B1%D1%80%D0%BE%D0%B1%D0%BA%D0%B0_%D0%BF%D1%80%D0%B8%D1%80%D0%BE%D0%B4%D0%BD%D0%BE%D1%97_%D0%BC%D0%BE%D0%B2%D0%B8\" hreflang=\"uk\" lang=\"uk\" title=\"Обробка природної мови – Ukrainian\">Українська</a></li><li class=\"interlanguage-link interwiki-vi\"><a class=\"interlanguage-link-target\" href=\"https://vi.wikipedia.org/wiki/X%E1%BB%AD_l%C3%BD_ng%C3%B4n_ng%E1%BB%AF_t%E1%BB%B1_nhi%C3%AAn\" hreflang=\"vi\" lang=\"vi\" title=\"Xử lý ngôn ngữ tự nhiên – Vietnamese\">Tiếng Việt</a></li><li class=\"interlanguage-link interwiki-zh-yue\"><a class=\"interlanguage-link-target\" href=\"https://zh-yue.wikipedia.org/wiki/%E8%87%AA%E7%84%B6%E8%AA%9E%E8%A8%80%E8%99%95%E7%90%86\" hreflang=\"yue\" lang=\"yue\" title=\"自然語言處理 – Cantonese\">粵語</a></li><li class=\"interlanguage-link interwiki-zh\"><a class=\"interlanguage-link-target\" href=\"https://zh.wikipedia.org/wiki/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7%90%86\" hreflang=\"zh\" lang=\"zh\" title=\"自然语言处理 – Chinese\">中文</a></li></ul>\n<div class=\"after-portlet after-portlet-lang\"><span class=\"wb-langlinks-edit wb-langlinks-link\"><a class=\"wbc-editpage\" href=\"https://www.wikidata.org/wiki/Special:EntityPage/Q30642#sitelinks-wikipedia\" title=\"Edit interlanguage links\">Edit links</a></span></div>\n</div>\n</nav>\n</div>\n</div>\n<footer class=\"mw-footer\" id=\"footer\" role=\"contentinfo\">\n<ul id=\"footer-info\">\n<li id=\"footer-info-lastmod\"> This page was last edited on 7 April 2021, at 03:07<span class=\"anonymous-show\"> (UTC)</span>.</li>\n<li id=\"footer-info-copyright\">Text is available under the <a href=\"//en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\" rel=\"license\">Creative Commons Attribution-ShareAlike License</a><a href=\"//creativecommons.org/licenses/by-sa/3.0/\" rel=\"license\" style=\"display:none;\"></a>;\nadditional terms may apply. By using this site, you agree to the <a href=\"//foundation.wikimedia.org/wiki/Terms_of_Use\">Terms of Use</a> and <a href=\"//foundation.wikimedia.org/wiki/Privacy_policy\">Privacy Policy</a>. Wikipedia® is a registered trademark of the <a href=\"//www.wikimediafoundation.org/\">Wikimedia Foundation, Inc.</a>, a non-profit organization.</li>\n</ul>\n<ul id=\"footer-places\">\n<li id=\"footer-places-privacy\"><a class=\"extiw\" href=\"https://foundation.wikimedia.org/wiki/Privacy_policy\" title=\"wmf:Privacy policy\">Privacy policy</a></li>\n<li id=\"footer-places-about\"><a href=\"/wiki/Wikipedia:About\" title=\"Wikipedia:About\">About Wikipedia</a></li>\n<li id=\"footer-places-disclaimer\"><a href=\"/wiki/Wikipedia:General_disclaimer\" title=\"Wikipedia:General disclaimer\">Disclaimers</a></li>\n<li id=\"footer-places-contact\"><a href=\"//en.wikipedia.org/wiki/Wikipedia:Contact_us\">Contact Wikipedia</a></li>\n<li id=\"footer-places-mobileview\"><a class=\"noprint stopMobileRedirectToggle\" href=\"//en.m.wikipedia.org/w/index.php?title=Natural_language_processing&amp;mobileaction=toggle_view_mobile\">Mobile view</a></li>\n<li id=\"footer-places-developers\"><a href=\"https://www.mediawiki.org/wiki/Special:MyLanguage/How_to_contribute\">Developers</a></li>\n<li id=\"footer-places-statslink\"><a href=\"https://stats.wikimedia.org/#/en.wikipedia.org\">Statistics</a></li>\n<li id=\"footer-places-cookiestatement\"><a href=\"https://foundation.wikimedia.org/wiki/Cookie_statement\">Cookie statement</a></li>\n</ul>\n<ul class=\"noprint\" id=\"footer-icons\">\n<li id=\"footer-copyrightico\"><a href=\"https://wikimediafoundation.org/\"><img alt=\"Wikimedia Foundation\" height=\"31\" loading=\"lazy\" src=\"/static/images/footer/wikimedia-button.png\" srcset=\"/static/images/footer/wikimedia-button-1.5x.png 1.5x, /static/images/footer/wikimedia-button-2x.png 2x\" width=\"88\"/></a></li>\n<li id=\"footer-poweredbyico\"><a href=\"https://www.mediawiki.org/\"><img alt=\"Powered by MediaWiki\" height=\"31\" loading=\"lazy\" src=\"/static/images/footer/poweredby_mediawiki_88x31.png\" srcset=\"/static/images/footer/poweredby_mediawiki_132x47.png 1.5x, /static/images/footer/poweredby_mediawiki_176x62.png 2x\" width=\"88\"/></a></li>\n</ul>\n</footer>\n<script>(RLQ=window.RLQ||[]).push(function(){mw.config.set({\"wgPageParseReport\":{\"limitreport\":{\"cputime\":\"1.005\",\"walltime\":\"1.382\",\"ppvisitednodes\":{\"value\":4406,\"limit\":1000000},\"postexpandincludesize\":{\"value\":98406,\"limit\":2097152},\"templateargumentsize\":{\"value\":5151,\"limit\":2097152},\"expansiondepth\":{\"value\":14,\"limit\":40},\"expensivefunctioncount\":{\"value\":3,\"limit\":500},\"unstrip-depth\":{\"value\":1,\"limit\":20},\"unstrip-size\":{\"value\":142685,\"limit\":5000000},\"entityaccesscount\":{\"value\":1,\"limit\":400},\"timingprofile\":[\"100.00% 1144.153 1 -total\",\" 44.83% 512.908 1 Template:Reflist\",\" 11.76% 134.511 7 Template:ISBN\",\" 11.63% 133.094 1 Template:Cite_conference\",\" 10.19% 116.587 18 Template:Cite_web\",\" 8.53% 97.569 1 Template:Short_description\",\" 7.23% 82.697 10 Template:Cite_journal\",\" 5.15% 58.934 1 Template:Natural_Language_Processing\",\" 5.01% 57.293 1 Template:Self-published_source\",\" 4.76% 54.473 1 Template:Authority_control\"]},\"scribunto\":{\"limitreport-timeusage\":{\"value\":\"0.495\",\"limit\":\"10.000\"},\"limitreport-memusage\":{\"value\":6443714,\"limit\":52428800}},\"cachereport\":{\"origin\":\"mw1267\",\"timestamp\":\"20210414012917\",\"ttl\":2592000,\"transientcontent\":false}}});});</script>\n<script type=\"application/ld+json\">{\"@context\":\"https:\\/\\/schema.org\",\"@type\":\"Article\",\"name\":\"Natural language processing\",\"url\":\"https:\\/\\/en.wikipedia.org\\/wiki\\/Natural_language_processing\",\"sameAs\":\"http:\\/\\/www.wikidata.org\\/entity\\/Q30642\",\"mainEntity\":\"http:\\/\\/www.wikidata.org\\/entity\\/Q30642\",\"author\":{\"@type\":\"Organization\",\"name\":\"Contributors to Wikimedia projects\"},\"publisher\":{\"@type\":\"Organization\",\"name\":\"Wikimedia Foundation, Inc.\",\"logo\":{\"@type\":\"ImageObject\",\"url\":\"https:\\/\\/www.wikimedia.org\\/static\\/images\\/wmf-hor-googpub.png\"}},\"datePublished\":\"2001-09-22T05:47:41Z\",\"dateModified\":\"2021-04-07T03:07:39Z\",\"image\":\"https:\\/\\/upload.wikimedia.org\\/wikipedia\\/commons\\/8\\/8b\\/Automated_online_assistant.png\",\"headline\":\"field of computer science and linguistics\"}</script>\n<script>(RLQ=window.RLQ||[]).push(function(){mw.config.set({\"wgBackendResponseTime\":173,\"wgHostname\":\"mw1385\"});});</script>\n</body></html>\n" ], [ "article_paragraphs = article_html.find_all('p') # find all stuff with the tag p\nprint(article_paragraphs)", "[<p><b>Natural language processing</b> (<b>NLP</b>) is a subfield of <a href=\"/wiki/Linguistics\" title=\"Linguistics\">linguistics</a>, <a href=\"/wiki/Computer_science\" title=\"Computer science\">computer science</a>, and <a href=\"/wiki/Artificial_intelligence\" title=\"Artificial intelligence\">artificial intelligence</a> concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of <a href=\"/wiki/Natural_language\" title=\"Natural language\">natural language</a> data. The result is a computer capable of \"understanding\" the contents of documents, including the contextual nuances of the language within them. The technology can then accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves. \n</p>, <p>Challenges in natural language processing frequently involve <a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">speech recognition</a>, <a class=\"mw-redirect\" href=\"/wiki/Natural_language_understanding\" title=\"Natural language understanding\">natural language understanding</a>, and <a href=\"/wiki/Natural-language_generation\" title=\"Natural-language generation\">natural-language generation</a>.\n</p>, <p>Natural language processing has its roots in the 1950s. Already in 1950, <a href=\"/wiki/Alan_Turing\" title=\"Alan Turing\">Alan Turing</a> published an article titled \"<a href=\"/wiki/Computing_Machinery_and_Intelligence\" title=\"Computing Machinery and Intelligence\">Computing Machinery and Intelligence</a>\" which proposed what is now called the <a href=\"/wiki/Turing_test\" title=\"Turing test\">Turing test</a> as a criterion of intelligence, a task that involves the automated interpretation and generation of natural language, but at the time not articulated as a problem separate from artificial intelligence.\n</p>, <p>The premise of symbolic NLP is well-summarized by <a href=\"/wiki/John_Searle\" title=\"John Searle\">John Searle</a>'s <a href=\"/wiki/Chinese_room\" title=\"Chinese room\">Chinese room</a> experiment: Given a collection of rules (e.g., a Chinese phrasebook, with questions and matching answers), the computer emulates natural language understanding (or other NLP tasks) by applying those rules to the data it is confronted with.\n</p>, <p>Up to the 1980s, most natural language processing systems were based on complex sets of hand-written rules. Starting in the late 1980s, however, there was a revolution in natural language processing with the introduction of <a href=\"/wiki/Machine_learning\" title=\"Machine learning\">machine learning</a> algorithms for language processing. This was due to both the steady increase in computational power (see <a href=\"/wiki/Moore%27s_law\" title=\"Moore's law\">Moore's law</a>) and the gradual lessening of the dominance of <a href=\"/wiki/Noam_Chomsky\" title=\"Noam Chomsky\">Chomskyan</a> theories of linguistics (e.g. <a href=\"/wiki/Transformational_grammar\" title=\"Transformational grammar\">transformational grammar</a>), whose theoretical underpinnings discouraged the sort of <a href=\"/wiki/Corpus_linguistics\" title=\"Corpus linguistics\">corpus linguistics</a> that underlies the machine-learning approach to language processing.<sup class=\"reference\" id=\"cite_ref-6\"><a href=\"#cite_note-6\">[6]</a></sup>\n</p>, <p>In the 2010s, <a class=\"mw-redirect\" href=\"/wiki/Representation_learning\" title=\"Representation learning\">representation learning</a> and <a href=\"/wiki/Deep_learning\" title=\"Deep learning\">deep neural network</a>-style machine learning methods became widespread in natural language processing, due in part to a flurry of results showing that such techniques<sup class=\"reference\" id=\"cite_ref-goldberg:nnlp17_7-0\"><a href=\"#cite_note-goldberg:nnlp17-7\">[7]</a></sup><sup class=\"reference\" id=\"cite_ref-goodfellow:book16_8-0\"><a href=\"#cite_note-goodfellow:book16-8\">[8]</a></sup> can achieve state-of-the-art results in many natural language tasks, for example in language modeling,<sup class=\"reference\" id=\"cite_ref-jozefowicz:lm16_9-0\"><a href=\"#cite_note-jozefowicz:lm16-9\">[9]</a></sup> parsing,<sup class=\"reference\" id=\"cite_ref-choe:emnlp16_10-0\"><a href=\"#cite_note-choe:emnlp16-10\">[10]</a></sup><sup class=\"reference\" id=\"cite_ref-vinyals:nips15_11-0\"><a href=\"#cite_note-vinyals:nips15-11\">[11]</a></sup> and many others.\n</p>, <p>In the early days, many language-processing systems were designed by symbolic methods, i.e., the hand-coding of a set of rules, coupled with a dictionary lookup:<sup class=\"reference\" id=\"cite_ref-winograd:shrdlu71_12-0\"><a href=\"#cite_note-winograd:shrdlu71-12\">[12]</a></sup><sup class=\"reference\" id=\"cite_ref-schank77_13-0\"><a href=\"#cite_note-schank77-13\">[13]</a></sup> such as by writing grammars or devising heuristic rules for <a href=\"/wiki/Stemming\" title=\"Stemming\">stemming</a>.\n</p>, <p>More recent systems based on <a href=\"/wiki/Machine_learning\" title=\"Machine learning\">machine-learning</a> algorithms have many advantages over hand-produced rules: \n</p>, <p>Despite the popularity of machine learning in NLP research, symbolic methods are still (2020) commonly used\n</p>, <p>Since the so-called \"statistical revolution\"<sup class=\"reference\" id=\"cite_ref-johnson:eacl:ilcl09_14-0\"><a href=\"#cite_note-johnson:eacl:ilcl09-14\">[14]</a></sup><sup class=\"reference\" id=\"cite_ref-resnik:langlog11_15-0\"><a href=\"#cite_note-resnik:langlog11-15\">[15]</a></sup> in the late 1980s and mid-1990s, much natural language processing research has relied heavily on machine learning. The machine-learning paradigm calls instead for using <a href=\"/wiki/Statistical_inference\" title=\"Statistical inference\">statistical inference</a> to automatically learn such rules through the analysis of large <i><a href=\"/wiki/Text_corpus\" title=\"Text corpus\">corpora</a></i> (the plural form of <i>corpus</i>, is a set of documents, possibly with human or computer annotations) of typical real-world examples.\n</p>, <p>Many different classes of machine-learning algorithms have been applied to natural-language-processing tasks. These algorithms take as input a large set of \"features\" that are generated from the input data. Increasingly, however, research has focused on <a class=\"mw-redirect\" href=\"/wiki/Statistical_models\" title=\"Statistical models\">statistical models</a>, which make soft, <a class=\"mw-redirect\" href=\"/wiki/Probabilistic\" title=\"Probabilistic\">probabilistic</a> decisions based on attaching <a class=\"mw-redirect\" href=\"/wiki/Real-valued\" title=\"Real-valued\">real-valued</a> weights to each input feature. Such models have the advantage that they can express the relative certainty of many different possible answers rather than only one, producing more reliable results when such a model is included as a component of a larger system.\n</p>, <p>Some of the earliest-used machine learning algorithms, such as <a href=\"/wiki/Decision_tree\" title=\"Decision tree\">decision trees</a>, produced systems of hard if-then rules similar to existing hand-written rules. However, <a class=\"mw-redirect\" href=\"/wiki/Part_of_speech_tagging\" title=\"Part of speech tagging\">part-of-speech tagging</a> introduced the use of <a class=\"mw-redirect\" href=\"/wiki/Hidden_Markov_models\" title=\"Hidden Markov models\">hidden Markov models</a> to natural language processing, and increasingly, research has focused on <a class=\"mw-redirect\" href=\"/wiki/Statistical_models\" title=\"Statistical models\">statistical models</a>, which make soft, <a class=\"mw-redirect\" href=\"/wiki/Probabilistic\" title=\"Probabilistic\">probabilistic</a> decisions based on attaching <a class=\"mw-redirect\" href=\"/wiki/Real-valued\" title=\"Real-valued\">real-valued</a> weights to the features making up the input data. The <a href=\"/wiki/Cache_language_model\" title=\"Cache language model\">cache language models</a> upon which many <a href=\"/wiki/Speech_recognition\" title=\"Speech recognition\">speech recognition</a> systems now rely are examples of such statistical models. Such models are generally more robust when given unfamiliar input, especially input that contains errors (as is very common for real-world data), and produce more reliable results when integrated into a larger system comprising multiple subtasks.\n</p>, <p>Since the neural turn, statistical methods in NLP research have been largely replaced by neural networks. However, they continue to be relevant for contexts in which statistical interpretability and transparency is required.\n</p>, <p>A major drawback of statistical methods is that they require elaborate feature engineering. Since 2015,<sup class=\"reference\" id=\"cite_ref-16\"><a href=\"#cite_note-16\">[16]</a></sup> the field has thus largely abandoned statistical methods and shifted to <a href=\"/wiki/Neural_network\" title=\"Neural network\">neural networks</a> for machine learning. Popular techniques include the use of <a href=\"/wiki/Word_embedding\" title=\"Word embedding\">word embeddings</a> to capture semantic properties of words, and an increase in end-to-end learning of a higher-level task (e.g., question answering) instead of relying on a pipeline of separate intermediate tasks (e.g., part-of-speech tagging and dependency parsing). In some areas, this shift has entailed substantial changes in how NLP systems are designed, such that deep neural network-based approaches may be viewed as a new paradigm distinct from statistical natural language processing. For instance, the term <i><a href=\"/wiki/Neural_machine_translation\" title=\"Neural machine translation\">neural machine translation</a></i> (NMT) emphasizes the fact that deep learning-based approaches to machine translation directly learn <a href=\"/wiki/Seq2seq\" title=\"Seq2seq\">sequence-to-sequence</a> transformations, obviating the need for intermediate steps such as word alignment and language modeling that was used in <a href=\"/wiki/Statistical_machine_translation\" title=\"Statistical machine translation\">statistical machine translation</a> (SMT). Latest works tend to use non-technical structure of a given task to build proper neural network.<sup class=\"reference\" id=\"cite_ref-17\"><a href=\"#cite_note-17\">[17]</a></sup>\n</p>, <p>The following is a list of some of the most commonly researched tasks in natural language processing. Some of these tasks have direct real-world applications, while others more commonly serve as subtasks that are used to aid in solving larger tasks.\n</p>, <p>Though natural language processing tasks are closely intertwined, they can be subdivided into categories for convenience. A coarse division is given below.\n</p>, <p>Based on long-standing trends in the field, it is possible to extrapolate future directions of NLP. As of 2020, three trends among the topics of the long-standing series of CoNLL Shared Tasks can be observed:<sup class=\"reference\" id=\"cite_ref-35\"><a href=\"#cite_note-35\">[35]</a></sup>\n</p>, <p>Most more higher-level NLP applications involve aspects that emulate intelligent behaviour and apparent comprehension of natural language. More broadly speaking, the technical operationalization of increasingly advanced aspects of cognitive behaviour represents one of the developmental trajectories of NLP (see trends among CoNLL shared tasks above).\n</p>, <p><a href=\"/wiki/Cognition\" title=\"Cognition\">Cognition</a> refers to \"the mental action or process of acquiring knowledge and understanding through thought, experience, and the senses.\"<sup class=\"reference\" id=\"cite_ref-36\"><a href=\"#cite_note-36\">[36]</a></sup> <a href=\"/wiki/Cognitive_science\" title=\"Cognitive science\">Cognitive science</a> is the interdisciplinary, scientific study of the mind and its processes.<sup class=\"reference\" id=\"cite_ref-37\"><a href=\"#cite_note-37\">[37]</a></sup> <a href=\"/wiki/Cognitive_linguistics\" title=\"Cognitive linguistics\">Cognitive linguistics</a> is an interdisciplinary branch of linguistics, combining knowledge and research from both psychology and linguistics.<sup class=\"reference\" id=\"cite_ref-38\"><a href=\"#cite_note-38\">[38]</a></sup> Especially during the age of <a href=\"#Symbolic_NLP_(1950s_-_early_1990s)\">symbolic NLP</a>, the area of computational linguistics maintained strong ties with cognitive studies. \n</p>, <p>As an example, <a href=\"/wiki/George_Lakoff\" title=\"George Lakoff\">George Lakoff</a> offers a methodology to build natural language processing (NLP) algorithms through the perspective of <a href=\"/wiki/Cognitive_science\" title=\"Cognitive science\">cognitive science</a>, along with the findings of <a href=\"/wiki/Cognitive_linguistics\" title=\"Cognitive linguistics\">cognitive linguistics</a>,<sup class=\"reference\" id=\"cite_ref-39\"><a href=\"#cite_note-39\">[39]</a></sup> with two defining aspects: \n</p>, <p>Ties with cognitive linguistics are part of the historical heritage of NLP, but they have been less frequently addressed since the statistical turn during the 1990s. Nevertheless, approaches to develop cognitive models towards technically operationalizable frameworks have been pursued in the context of various frameworks, e.g., of cognitive grammar,<sup class=\"reference\" id=\"cite_ref-41\"><a href=\"#cite_note-41\">[41]</a></sup> functional grammar,<sup class=\"reference\" id=\"cite_ref-42\"><a href=\"#cite_note-42\">[42]</a></sup> construction grammar,<sup class=\"reference\" id=\"cite_ref-43\"><a href=\"#cite_note-43\">[43]</a></sup> computational psycholinguistics and cognitive neuroscience (e.g., <a href=\"/wiki/ACT-R\" title=\"ACT-R\">ACT-R</a>), however, with limited uptake in mainstream NLP (as measured by presence on major conferences<sup class=\"reference\" id=\"cite_ref-44\"><a href=\"#cite_note-44\">[44]</a></sup> of the <a href=\"/wiki/Association_for_Computational_Linguistics\" title=\"Association for Computational Linguistics\">ACL</a>). More recently, ideas of cognitive NLP have been revived as an approach to achieve <a href=\"/wiki/Explainable_artificial_intelligence\" title=\"Explainable artificial intelligence\">explainability</a>, e.g., under the notion of \"cognitive AI\".<sup class=\"reference\" id=\"cite_ref-45\"><a href=\"#cite_note-45\">[45]</a></sup> Likewise, ideas of cognitive NLP are inherent to neural models multimodal NLP (although rarely made explicit).<sup class=\"reference\" id=\"cite_ref-46\"><a href=\"#cite_note-46\">[46]</a></sup>\n</p>]\n" ], [ "article_text = ''\nfor para in article_paragraphs:\n article_text += para.text\nprint(article_text)", "Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data. The result is a computer capable of \"understanding\" the contents of documents, including the contextual nuances of the language within them. The technology can then accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves. \nChallenges in natural language processing frequently involve speech recognition, natural language understanding, and natural-language generation.\nNatural language processing has its roots in the 1950s. Already in 1950, Alan Turing published an article titled \"Computing Machinery and Intelligence\" which proposed what is now called the Turing test as a criterion of intelligence, a task that involves the automated interpretation and generation of natural language, but at the time not articulated as a problem separate from artificial intelligence.\nThe premise of symbolic NLP is well-summarized by John Searle's Chinese room experiment: Given a collection of rules (e.g., a Chinese phrasebook, with questions and matching answers), the computer emulates natural language understanding (or other NLP tasks) by applying those rules to the data it is confronted with.\nUp to the 1980s, most natural language processing systems were based on complex sets of hand-written rules. Starting in the late 1980s, however, there was a revolution in natural language processing with the introduction of machine learning algorithms for language processing. This was due to both the steady increase in computational power (see Moore's law) and the gradual lessening of the dominance of Chomskyan theories of linguistics (e.g. transformational grammar), whose theoretical underpinnings discouraged the sort of corpus linguistics that underlies the machine-learning approach to language processing.[6]\nIn the 2010s, representation learning and deep neural network-style machine learning methods became widespread in natural language processing, due in part to a flurry of results showing that such techniques[7][8] can achieve state-of-the-art results in many natural language tasks, for example in language modeling,[9] parsing,[10][11] and many others.\nIn the early days, many language-processing systems were designed by symbolic methods, i.e., the hand-coding of a set of rules, coupled with a dictionary lookup:[12][13] such as by writing grammars or devising heuristic rules for stemming.\nMore recent systems based on machine-learning algorithms have many advantages over hand-produced rules: \nDespite the popularity of machine learning in NLP research, symbolic methods are still (2020) commonly used\nSince the so-called \"statistical revolution\"[14][15] in the late 1980s and mid-1990s, much natural language processing research has relied heavily on machine learning. The machine-learning paradigm calls instead for using statistical inference to automatically learn such rules through the analysis of large corpora (the plural form of corpus, is a set of documents, possibly with human or computer annotations) of typical real-world examples.\nMany different classes of machine-learning algorithms have been applied to natural-language-processing tasks. These algorithms take as input a large set of \"features\" that are generated from the input data. Increasingly, however, research has focused on statistical models, which make soft, probabilistic decisions based on attaching real-valued weights to each input feature. Such models have the advantage that they can express the relative certainty of many different possible answers rather than only one, producing more reliable results when such a model is included as a component of a larger system.\nSome of the earliest-used machine learning algorithms, such as decision trees, produced systems of hard if-then rules similar to existing hand-written rules. However, part-of-speech tagging introduced the use of hidden Markov models to natural language processing, and increasingly, research has focused on statistical models, which make soft, probabilistic decisions based on attaching real-valued weights to the features making up the input data. The cache language models upon which many speech recognition systems now rely are examples of such statistical models. Such models are generally more robust when given unfamiliar input, especially input that contains errors (as is very common for real-world data), and produce more reliable results when integrated into a larger system comprising multiple subtasks.\nSince the neural turn, statistical methods in NLP research have been largely replaced by neural networks. However, they continue to be relevant for contexts in which statistical interpretability and transparency is required.\nA major drawback of statistical methods is that they require elaborate feature engineering. Since 2015,[16] the field has thus largely abandoned statistical methods and shifted to neural networks for machine learning. Popular techniques include the use of word embeddings to capture semantic properties of words, and an increase in end-to-end learning of a higher-level task (e.g., question answering) instead of relying on a pipeline of separate intermediate tasks (e.g., part-of-speech tagging and dependency parsing). In some areas, this shift has entailed substantial changes in how NLP systems are designed, such that deep neural network-based approaches may be viewed as a new paradigm distinct from statistical natural language processing. For instance, the term neural machine translation (NMT) emphasizes the fact that deep learning-based approaches to machine translation directly learn sequence-to-sequence transformations, obviating the need for intermediate steps such as word alignment and language modeling that was used in statistical machine translation (SMT). Latest works tend to use non-technical structure of a given task to build proper neural network.[17]\nThe following is a list of some of the most commonly researched tasks in natural language processing. Some of these tasks have direct real-world applications, while others more commonly serve as subtasks that are used to aid in solving larger tasks.\nThough natural language processing tasks are closely intertwined, they can be subdivided into categories for convenience. A coarse division is given below.\nBased on long-standing trends in the field, it is possible to extrapolate future directions of NLP. As of 2020, three trends among the topics of the long-standing series of CoNLL Shared Tasks can be observed:[35]\nMost more higher-level NLP applications involve aspects that emulate intelligent behaviour and apparent comprehension of natural language. More broadly speaking, the technical operationalization of increasingly advanced aspects of cognitive behaviour represents one of the developmental trajectories of NLP (see trends among CoNLL shared tasks above).\nCognition refers to \"the mental action or process of acquiring knowledge and understanding through thought, experience, and the senses.\"[36] Cognitive science is the interdisciplinary, scientific study of the mind and its processes.[37] Cognitive linguistics is an interdisciplinary branch of linguistics, combining knowledge and research from both psychology and linguistics.[38] Especially during the age of symbolic NLP, the area of computational linguistics maintained strong ties with cognitive studies. \nAs an example, George Lakoff offers a methodology to build natural language processing (NLP) algorithms through the perspective of cognitive science, along with the findings of cognitive linguistics,[39] with two defining aspects: \nTies with cognitive linguistics are part of the historical heritage of NLP, but they have been less frequently addressed since the statistical turn during the 1990s. Nevertheless, approaches to develop cognitive models towards technically operationalizable frameworks have been pursued in the context of various frameworks, e.g., of cognitive grammar,[41] functional grammar,[42] construction grammar,[43] computational psycholinguistics and cognitive neuroscience (e.g., ACT-R), however, with limited uptake in mainstream NLP (as measured by presence on major conferences[44] of the ACL). More recently, ideas of cognitive NLP have been revived as an approach to achieve explainability, e.g., under the notion of \"cognitive AI\".[45] Likewise, ideas of cognitive NLP are inherent to neural models multimodal NLP (although rarely made explicit).[46]\n\n" ], [ "# Split corpus into individual sentences\ncorpus = nltk.sent_tokenize(article_text)\nprint(corpus)", "['Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data.', 'The result is a computer capable of \"understanding\" the contents of documents, including the contextual nuances of the language within them.', 'The technology can then accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves.', 'Challenges in natural language processing frequently involve speech recognition, natural language understanding, and natural-language generation.', 'Natural language processing has its roots in the 1950s.', 'Already in 1950, Alan Turing published an article titled \"Computing Machinery and Intelligence\" which proposed what is now called the Turing test as a criterion of intelligence, a task that involves the automated interpretation and generation of natural language, but at the time not articulated as a problem separate from artificial intelligence.', \"The premise of symbolic NLP is well-summarized by John Searle's Chinese room experiment: Given a collection of rules (e.g., a Chinese phrasebook, with questions and matching answers), the computer emulates natural language understanding (or other NLP tasks) by applying those rules to the data it is confronted with.\", 'Up to the 1980s, most natural language processing systems were based on complex sets of hand-written rules.', 'Starting in the late 1980s, however, there was a revolution in natural language processing with the introduction of machine learning algorithms for language processing.', \"This was due to both the steady increase in computational power (see Moore's law) and the gradual lessening of the dominance of Chomskyan theories of linguistics (e.g.\", 'transformational grammar), whose theoretical underpinnings discouraged the sort of corpus linguistics that underlies the machine-learning approach to language processing.', '[6]\\nIn the 2010s, representation learning and deep neural network-style machine learning methods became widespread in natural language processing, due in part to a flurry of results showing that such techniques[7][8] can achieve state-of-the-art results in many natural language tasks, for example in language modeling,[9] parsing,[10][11] and many others.', 'In the early days, many language-processing systems were designed by symbolic methods, i.e., the hand-coding of a set of rules, coupled with a dictionary lookup:[12][13] such as by writing grammars or devising heuristic rules for stemming.', 'More recent systems based on machine-learning algorithms have many advantages over hand-produced rules: \\nDespite the popularity of machine learning in NLP research, symbolic methods are still (2020) commonly used\\nSince the so-called \"statistical revolution\"[14][15] in the late 1980s and mid-1990s, much natural language processing research has relied heavily on machine learning.', 'The machine-learning paradigm calls instead for using statistical inference to automatically learn such rules through the analysis of large corpora (the plural form of corpus, is a set of documents, possibly with human or computer annotations) of typical real-world examples.', 'Many different classes of machine-learning algorithms have been applied to natural-language-processing tasks.', 'These algorithms take as input a large set of \"features\" that are generated from the input data.', 'Increasingly, however, research has focused on statistical models, which make soft, probabilistic decisions based on attaching real-valued weights to each input feature.', 'Such models have the advantage that they can express the relative certainty of many different possible answers rather than only one, producing more reliable results when such a model is included as a component of a larger system.', 'Some of the earliest-used machine learning algorithms, such as decision trees, produced systems of hard if-then rules similar to existing hand-written rules.', 'However, part-of-speech tagging introduced the use of hidden Markov models to natural language processing, and increasingly, research has focused on statistical models, which make soft, probabilistic decisions based on attaching real-valued weights to the features making up the input data.', 'The cache language models upon which many speech recognition systems now rely are examples of such statistical models.', 'Such models are generally more robust when given unfamiliar input, especially input that contains errors (as is very common for real-world data), and produce more reliable results when integrated into a larger system comprising multiple subtasks.', 'Since the neural turn, statistical methods in NLP research have been largely replaced by neural networks.', 'However, they continue to be relevant for contexts in which statistical interpretability and transparency is required.', 'A major drawback of statistical methods is that they require elaborate feature engineering.', 'Since 2015,[16] the field has thus largely abandoned statistical methods and shifted to neural networks for machine learning.', 'Popular techniques include the use of word embeddings to capture semantic properties of words, and an increase in end-to-end learning of a higher-level task (e.g., question answering) instead of relying on a pipeline of separate intermediate tasks (e.g., part-of-speech tagging and dependency parsing).', 'In some areas, this shift has entailed substantial changes in how NLP systems are designed, such that deep neural network-based approaches may be viewed as a new paradigm distinct from statistical natural language processing.', 'For instance, the term neural machine translation (NMT) emphasizes the fact that deep learning-based approaches to machine translation directly learn sequence-to-sequence transformations, obviating the need for intermediate steps such as word alignment and language modeling that was used in statistical machine translation (SMT).', 'Latest works tend to use non-technical structure of a given task to build proper neural network.', '[17]\\nThe following is a list of some of the most commonly researched tasks in natural language processing.', 'Some of these tasks have direct real-world applications, while others more commonly serve as subtasks that are used to aid in solving larger tasks.', 'Though natural language processing tasks are closely intertwined, they can be subdivided into categories for convenience.', 'A coarse division is given below.', 'Based on long-standing trends in the field, it is possible to extrapolate future directions of NLP.', 'As of 2020, three trends among the topics of the long-standing series of CoNLL Shared Tasks can be observed:[35]\\nMost more higher-level NLP applications involve aspects that emulate intelligent behaviour and apparent comprehension of natural language.', 'More broadly speaking, the technical operationalization of increasingly advanced aspects of cognitive behaviour represents one of the developmental trajectories of NLP (see trends among CoNLL shared tasks above).', 'Cognition refers to \"the mental action or process of acquiring knowledge and understanding through thought, experience, and the senses.', '\"[36] Cognitive science is the interdisciplinary, scientific study of the mind and its processes.', '[37] Cognitive linguistics is an interdisciplinary branch of linguistics, combining knowledge and research from both psychology and linguistics.', '[38] Especially during the age of symbolic NLP, the area of computational linguistics maintained strong ties with cognitive studies.', 'As an example, George Lakoff offers a methodology to build natural language processing (NLP) algorithms through the perspective of cognitive science, along with the findings of cognitive linguistics,[39] with two defining aspects: \\nTies with cognitive linguistics are part of the historical heritage of NLP, but they have been less frequently addressed since the statistical turn during the 1990s.', 'Nevertheless, approaches to develop cognitive models towards technically operationalizable frameworks have been pursued in the context of various frameworks, e.g., of cognitive grammar,[41] functional grammar,[42] construction grammar,[43] computational psycholinguistics and cognitive neuroscience (e.g., ACT-R), however, with limited uptake in mainstream NLP (as measured by presence on major conferences[44] of the ACL).', 'More recently, ideas of cognitive NLP have been revived as an approach to achieve explainability, e.g., under the notion of \"cognitive AI\".', '[45] Likewise, ideas of cognitive NLP are inherent to neural models multimodal NLP (although rarely made explicit).', '[46]']\n" ], [ "# We will remove punctuation marks, space, and turn all text into lower case\nfor i in range(len(corpus)):\n corpus[i] = corpus[i].lower() # Turn into lower case\n corpus[i] = re.sub(r'\\W', ' ', corpus[i]) # Eliminate the blank spaces\n corpus[i] = re.sub(r'\\s+', ' ', corpus[i]) # Eliminate the punctuations\nprint(corpus)", "['natural language processing nlp is a subfield of linguistics computer science and artificial intelligence concerned with the interactions between computers and human language in particular how to program computers to process and analyze large amounts of natural language data ', 'the result is a computer capable of understanding the contents of documents including the contextual nuances of the language within them ', 'the technology can then accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves ', 'challenges in natural language processing frequently involve speech recognition natural language understanding and natural language generation ', 'natural language processing has its roots in the 1950s ', 'already in 1950 alan turing published an article titled computing machinery and intelligence which proposed what is now called the turing test as a criterion of intelligence a task that involves the automated interpretation and generation of natural language but at the time not articulated as a problem separate from artificial intelligence ', 'the premise of symbolic nlp is well summarized by john searle s chinese room experiment given a collection of rules e g a chinese phrasebook with questions and matching answers the computer emulates natural language understanding or other nlp tasks by applying those rules to the data it is confronted with ', 'up to the 1980s most natural language processing systems were based on complex sets of hand written rules ', 'starting in the late 1980s however there was a revolution in natural language processing with the introduction of machine learning algorithms for language processing ', 'this was due to both the steady increase in computational power see moore s law and the gradual lessening of the dominance of chomskyan theories of linguistics e g ', 'transformational grammar whose theoretical underpinnings discouraged the sort of corpus linguistics that underlies the machine learning approach to language processing ', ' 6 in the 2010s representation learning and deep neural network style machine learning methods became widespread in natural language processing due in part to a flurry of results showing that such techniques 7 8 can achieve state of the art results in many natural language tasks for example in language modeling 9 parsing 10 11 and many others ', 'in the early days many language processing systems were designed by symbolic methods i e the hand coding of a set of rules coupled with a dictionary lookup 12 13 such as by writing grammars or devising heuristic rules for stemming ', 'more recent systems based on machine learning algorithms have many advantages over hand produced rules despite the popularity of machine learning in nlp research symbolic methods are still 2020 commonly used since the so called statistical revolution 14 15 in the late 1980s and mid 1990s much natural language processing research has relied heavily on machine learning ', 'the machine learning paradigm calls instead for using statistical inference to automatically learn such rules through the analysis of large corpora the plural form of corpus is a set of documents possibly with human or computer annotations of typical real world examples ', 'many different classes of machine learning algorithms have been applied to natural language processing tasks ', 'these algorithms take as input a large set of features that are generated from the input data ', 'increasingly however research has focused on statistical models which make soft probabilistic decisions based on attaching real valued weights to each input feature ', 'such models have the advantage that they can express the relative certainty of many different possible answers rather than only one producing more reliable results when such a model is included as a component of a larger system ', 'some of the earliest used machine learning algorithms such as decision trees produced systems of hard if then rules similar to existing hand written rules ', 'however part of speech tagging introduced the use of hidden markov models to natural language processing and increasingly research has focused on statistical models which make soft probabilistic decisions based on attaching real valued weights to the features making up the input data ', 'the cache language models upon which many speech recognition systems now rely are examples of such statistical models ', 'such models are generally more robust when given unfamiliar input especially input that contains errors as is very common for real world data and produce more reliable results when integrated into a larger system comprising multiple subtasks ', 'since the neural turn statistical methods in nlp research have been largely replaced by neural networks ', 'however they continue to be relevant for contexts in which statistical interpretability and transparency is required ', 'a major drawback of statistical methods is that they require elaborate feature engineering ', 'since 2015 16 the field has thus largely abandoned statistical methods and shifted to neural networks for machine learning ', 'popular techniques include the use of word embeddings to capture semantic properties of words and an increase in end to end learning of a higher level task e g question answering instead of relying on a pipeline of separate intermediate tasks e g part of speech tagging and dependency parsing ', 'in some areas this shift has entailed substantial changes in how nlp systems are designed such that deep neural network based approaches may be viewed as a new paradigm distinct from statistical natural language processing ', 'for instance the term neural machine translation nmt emphasizes the fact that deep learning based approaches to machine translation directly learn sequence to sequence transformations obviating the need for intermediate steps such as word alignment and language modeling that was used in statistical machine translation smt ', 'latest works tend to use non technical structure of a given task to build proper neural network ', ' 17 the following is a list of some of the most commonly researched tasks in natural language processing ', 'some of these tasks have direct real world applications while others more commonly serve as subtasks that are used to aid in solving larger tasks ', 'though natural language processing tasks are closely intertwined they can be subdivided into categories for convenience ', 'a coarse division is given below ', 'based on long standing trends in the field it is possible to extrapolate future directions of nlp ', 'as of 2020 three trends among the topics of the long standing series of conll shared tasks can be observed 35 most more higher level nlp applications involve aspects that emulate intelligent behaviour and apparent comprehension of natural language ', 'more broadly speaking the technical operationalization of increasingly advanced aspects of cognitive behaviour represents one of the developmental trajectories of nlp see trends among conll shared tasks above ', 'cognition refers to the mental action or process of acquiring knowledge and understanding through thought experience and the senses ', ' 36 cognitive science is the interdisciplinary scientific study of the mind and its processes ', ' 37 cognitive linguistics is an interdisciplinary branch of linguistics combining knowledge and research from both psychology and linguistics ', ' 38 especially during the age of symbolic nlp the area of computational linguistics maintained strong ties with cognitive studies ', 'as an example george lakoff offers a methodology to build natural language processing nlp algorithms through the perspective of cognitive science along with the findings of cognitive linguistics 39 with two defining aspects ties with cognitive linguistics are part of the historical heritage of nlp but they have been less frequently addressed since the statistical turn during the 1990s ', 'nevertheless approaches to develop cognitive models towards technically operationalizable frameworks have been pursued in the context of various frameworks e g of cognitive grammar 41 functional grammar 42 construction grammar 43 computational psycholinguistics and cognitive neuroscience e g act r however with limited uptake in mainstream nlp as measured by presence on major conferences 44 of the acl ', 'more recently ideas of cognitive nlp have been revived as an approach to achieve explainability e g under the notion of cognitive ai ', ' 45 likewise ideas of cognitive nlp are inherent to neural models multimodal nlp although rarely made explicit ', ' 46 ']" ], [ "# Tokenize the sentences in the corpus and create a dictionary wirh sentences and their frequencies\nwordfreq = {}\nfor sentence in corpus:\n tokens = nltk.word_tokenize(sentence) \n for t in tokens:\n if t not in wordfreq.keys():\n wordfreq[t] = 1\n else:\n wordfreq[t] += 1\nprint(wordfreq)", "{'natural': 20, 'language': 28, 'processing': 16, 'nlp': 16, 'is': 15, 'a': 25, 'subfield': 1, 'of': 68, 'linguistics': 9, 'computer': 4, 'science': 3, 'and': 27, 'artificial': 2, 'intelligence': 4, 'concerned': 1, 'with': 11, 'the': 68, 'interactions': 1, 'between': 1, 'computers': 2, 'human': 2, 'in': 27, 'particular': 1, 'how': 2, 'to': 28, 'program': 1, 'process': 2, 'analyze': 1, 'large': 3, 'amounts': 1, 'data': 5, 'result': 1, 'capable': 1, 'understanding': 4, 'contents': 1, 'documents': 4, 'including': 1, 'contextual': 1, 'nuances': 1, 'within': 1, 'them': 1, 'technology': 1, 'can': 5, 'then': 2, 'accurately': 1, 'extract': 1, 'information': 1, 'insights': 1, 'contained': 1, 'as': 16, 'well': 2, 'categorize': 1, 'organize': 1, 'themselves': 1, 'challenges': 1, 'frequently': 2, 'involve': 2, 'speech': 4, 'recognition': 2, 'generation': 2, 'has': 6, 'its': 2, 'roots': 1, '1950s': 1, 'already': 1, '1950': 1, 'alan': 1, 'turing': 2, 'published': 1, 'an': 5, 'article': 1, 'titled': 1, 'computing': 1, 'machinery': 1, 'which': 5, 'proposed': 1, 'what': 1, 'now': 2, 'called': 2, 'test': 1, 'criterion': 1, 'task': 3, 'that': 12, 'involves': 1, 'automated': 1, 'interpretation': 1, 'but': 2, 'at': 1, 'time': 1, 'not': 1, 'articulated': 1, 'problem': 1, 'separate': 2, 'from': 4, 'premise': 1, 'symbolic': 4, 'summarized': 1, 'by': 6, 'john': 1, 'searle': 1, 's': 2, 'chinese': 2, 'room': 1, 'experiment': 1, 'given': 4, 'collection': 1, 'rules': 9, 'e': 8, 'g': 7, 'phrasebook': 1, 'questions': 1, 'matching': 1, 'answers': 2, 'emulates': 1, 'or': 4, 'other': 1, 'tasks': 10, 'applying': 1, 'those': 1, 'it': 2, 'confronted': 1, 'up': 2, '1980s': 3, 'most': 3, 'systems': 6, 'were': 2, 'based': 7, 'on': 10, 'complex': 1, 'sets': 1, 'hand': 4, 'written': 2, 'starting': 1, 'late': 2, 'however': 5, 'there': 1, 'was': 3, 'revolution': 2, 'introduction': 1, 'machine': 13, 'learning': 13, 'algorithms': 6, 'for': 10, 'this': 2, 'due': 2, 'both': 2, 'steady': 1, 'increase': 2, 'computational': 3, 'power': 1, 'see': 2, 'moore': 1, 'law': 1, 'gradual': 1, 'lessening': 1, 'dominance': 1, 'chomskyan': 1, 'theories': 1, 'transformational': 1, 'grammar': 4, 'whose': 1, 'theoretical': 1, 'underpinnings': 1, 'discouraged': 1, 'sort': 1, 'corpus': 2, 'underlies': 1, 'approach': 2, '6': 1, '2010s': 1, 'representation': 1, 'deep': 3, 'neural': 8, 'network': 3, 'style': 1, 'methods': 6, 'became': 1, 'widespread': 1, 'part': 4, 'flurry': 1, 'results': 4, 'showing': 1, 'such': 10, 'techniques': 2, '7': 1, '8': 1, 'achieve': 2, 'state': 1, 'art': 1, 'many': 7, 'example': 2, 'modeling': 2, '9': 1, 'parsing': 2, '10': 1, '11': 1, 'others': 2, 'early': 1, 'days': 1, 'designed': 2, 'i': 1, 'coding': 1, 'set': 3, 'coupled': 1, 'dictionary': 1, 'lookup': 1, '12': 1, '13': 1, 'writing': 1, 'grammars': 1, 'devising': 1, 'heuristic': 1, 'stemming': 1, 'more': 8, 'recent': 1, 'have': 8, 'advantages': 1, 'over': 1, 'produced': 2, 'despite': 1, 'popularity': 1, 'research': 6, 'are': 9, 'still': 1, '2020': 2, 'commonly': 3, 'used': 4, 'since': 4, 'so': 1, 'statistical': 12, '14': 1, '15': 1, 'mid': 1, '1990s': 2, 'much': 1, 'relied': 1, 'heavily': 1, 'paradigm': 2, 'calls': 1, 'instead': 2, 'using': 1, 'inference': 1, 'automatically': 1, 'learn': 2, 'through': 3, 'analysis': 1, 'corpora': 1, 'plural': 1, 'form': 1, 'possibly': 1, 'annotations': 1, 'typical': 1, 'real': 5, 'world': 3, 'examples': 2, 'different': 2, 'classes': 1, 'been': 5, 'applied': 1, 'these': 2, 'take': 1, 'input': 6, 'features': 2, 'generated': 1, 'increasingly': 3, 'focused': 2, 'models': 9, 'make': 2, 'soft': 2, 'probabilistic': 2, 'decisions': 2, 'attaching': 2, 'valued': 2, 'weights': 2, 'each': 1, 'feature': 2, 'advantage': 1, 'they': 5, 'express': 1, 'relative': 1, 'certainty': 1, 'possible': 2, 'rather': 1, 'than': 1, 'only': 1, 'one': 2, 'producing': 1, 'reliable': 2, 'when': 3, 'model': 1, 'included': 1, 'component': 1, 'larger': 3, 'system': 2, 'some': 4, 'earliest': 1, 'decision': 1, 'trees': 1, 'hard': 1, 'if': 1, 'similar': 1, 'existing': 1, 'tagging': 2, 'introduced': 1, 'use': 3, 'hidden': 1, 'markov': 1, 'making': 1, 'cache': 1, 'upon': 1, 'rely': 1, 'generally': 1, 'robust': 1, 'unfamiliar': 1, 'especially': 2, 'contains': 1, 'errors': 1, 'very': 1, 'common': 1, 'produce': 1, 'integrated': 1, 'into': 2, 'comprising': 1, 'multiple': 1, 'subtasks': 2, 'turn': 2, 'largely': 2, 'replaced': 1, 'networks': 2, 'continue': 1, 'be': 4, 'relevant': 1, 'contexts': 1, 'interpretability': 1, 'transparency': 1, 'required': 1, 'major': 2, 'drawback': 1, 'require': 1, 'elaborate': 1, 'engineering': 1, '2015': 1, '16': 1, 'field': 2, 'thus': 1, 'abandoned': 1, 'shifted': 1, 'popular': 1, 'include': 1, 'word': 2, 'embeddings': 1, 'capture': 1, 'semantic': 1, 'properties': 1, 'words': 1, 'end': 2, 'higher': 2, 'level': 2, 'question': 1, 'answering': 1, 'relying': 1, 'pipeline': 1, 'intermediate': 2, 'dependency': 1, 'areas': 1, 'shift': 1, 'entailed': 1, 'substantial': 1, 'changes': 1, 'approaches': 3, 'may': 1, 'viewed': 1, 'new': 1, 'distinct': 1, 'instance': 1, 'term': 1, 'translation': 3, 'nmt': 1, 'emphasizes': 1, 'fact': 1, 'directly': 1, 'sequence': 2, 'transformations': 1, 'obviating': 1, 'need': 1, 'steps': 1, 'alignment': 1, 'smt': 1, 'latest': 1, 'works': 1, 'tend': 1, 'non': 1, 'technical': 2, 'structure': 1, 'build': 2, 'proper': 1, '17': 1, 'following': 1, 'list': 1, 'researched': 1, 'direct': 1, 'applications': 2, 'while': 1, 'serve': 1, 'aid': 1, 'solving': 1, 'though': 1, 'closely': 1, 'intertwined': 1, 'subdivided': 1, 'categories': 1, 'convenience': 1, 'coarse': 1, 'division': 1, 'below': 1, 'long': 2, 'standing': 2, 'trends': 3, 'extrapolate': 1, 'future': 1, 'directions': 1, 'three': 1, 'among': 2, 'topics': 1, 'series': 1, 'conll': 2, 'shared': 2, 'observed': 1, '35': 1, 'aspects': 3, 'emulate': 1, 'intelligent': 1, 'behaviour': 2, 'apparent': 1, 'comprehension': 1, 'broadly': 1, 'speaking': 1, 'operationalization': 1, 'advanced': 1, 'cognitive': 13, 'represents': 1, 'developmental': 1, 'trajectories': 1, 'above': 1, 'cognition': 1, 'refers': 1, 'mental': 1, 'action': 1, 'acquiring': 1, 'knowledge': 2, 'thought': 1, 'experience': 1, 'senses': 1, '36': 1, 'interdisciplinary': 2, 'scientific': 1, 'study': 1, 'mind': 1, 'processes': 1, '37': 1, 'branch': 1, 'combining': 1, 'psychology': 1, '38': 1, 'during': 2, 'age': 1, 'area': 1, 'maintained': 1, 'strong': 1, 'ties': 2, 'studies': 1, 'george': 1, 'lakoff': 1, 'offers': 1, 'methodology': 1, 'perspective': 1, 'along': 1, 'findings': 1, '39': 1, 'two': 1, 'defining': 1, 'historical': 1, 'heritage': 1, 'less': 1, 'addressed': 1, 'nevertheless': 1, 'develop': 1, 'towards': 1, 'technically': 1, 'operationalizable': 1, 'frameworks': 2, 'pursued': 1, 'context': 1, 'various': 1, '41': 1, 'functional': 1, '42': 1, 'construction': 1, '43': 1, 'psycholinguistics': 1, 'neuroscience': 1, 'act': 1, 'r': 1, 'limited': 1, 'uptake': 1, 'mainstream': 1, 'measured': 1, 'presence': 1, 'conferences': 1, '44': 1, 'acl': 1, 'recently': 1, 'ideas': 2, 'revived': 1, 'explainability': 1, 'under': 1, 'notion': 1, 'ai': 1, '45': 1, 'likewise': 1, 'inherent': 1, 'multimodal': 1, 'although': 1, 'rarely': 1, 'made': 1, 'explicit': 1, '46': 1}\n" ], [ "# Filter down to 200 most frequently ocurring words:\nimport heapq\nmost_freq = heapq.nlargest(200, wordfreq, key=wordfreq.get)\nprint(most_freq)", "['of', 'the', 'language', 'to', 'and', 'in', 'a', 'natural', 'processing', 'nlp', 'as', 'is', 'machine', 'learning', 'cognitive', 'that', 'statistical', 'with', 'tasks', 'on', 'for', 'such', 'linguistics', 'rules', 'are', 'models', 'e', 'neural', 'more', 'have', 'g', 'based', 'many', 'has', 'by', 'systems', 'algorithms', 'methods', 'research', 'input', 'data', 'can', 'an', 'which', 'however', 'real', 'been', 'they', 'computer', 'intelligence', 'understanding', 'documents', 'speech', 'from', 'symbolic', 'given', 'or', 'hand', 'grammar', 'part', 'results', 'used', 'since', 'some', 'be', 'science', 'large', 'task', '1980s', 'most', 'was', 'computational', 'deep', 'network', 'set', 'commonly', 'through', 'world', 'increasingly', 'when', 'larger', 'use', 'approaches', 'translation', 'trends', 'aspects', 'artificial', 'computers', 'human', 'how', 'process', 'then', 'well', 'frequently', 'involve', 'recognition', 'generation', 'its', 'turing', 'now', 'called', 'but', 'separate', 's', 'chinese', 'answers', 'it', 'up', 'were', 'written', 'late', 'revolution', 'this', 'due', 'both', 'increase', 'see', 'corpus', 'approach', 'techniques', 'achieve', 'example', 'modeling', 'parsing', 'others', 'designed', 'produced', '2020', '1990s', 'paradigm', 'instead', 'learn', 'examples', 'different', 'these', 'features', 'focused', 'make', 'soft', 'probabilistic', 'decisions', 'attaching', 'valued', 'weights', 'feature', 'possible', 'one', 'reliable', 'system', 'tagging', 'especially', 'into', 'subtasks', 'turn', 'largely', 'networks', 'major', 'field', 'word', 'end', 'higher', 'level', 'intermediate', 'sequence', 'technical', 'build', 'applications', 'long', 'standing', 'among', 'conll', 'shared', 'behaviour', 'knowledge', 'interdisciplinary', 'during', 'ties', 'frameworks', 'ideas', 'subfield', 'concerned', 'interactions', 'between', 'particular', 'program', 'analyze', 'amounts', 'result', 'capable', 'contents', 'including', 'contextual', 'nuances', 'within', 'them', 'technology', 'accurately', 'extract', 'information', 'insights']\n" ], [ "# Convert the sentence in the corpus into their corresponding vector representation:\nsent_vectors = []\nfor sentence in corpus:\n sent_tokens = nltk.word_tokenize(sentence)\n sent_vec = []\n for word in most_freq:\n if word in sent_tokens:\n sent_vec.append(1)\n else:\n sent_vec.append(0)\n sent_vectors.append(sent_vec)\nprint(sent_vectors)", "[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1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, 0, 0, 0]]\n" ], [ "sent_vectors = np.asarray(sent_vectors)\nprint(sent_vectors)", "[[1 1 1 ... 0 0 0]\n [1 1 1 ... 0 0 0]\n [0 1 0 ... 1 1 1]\n ...\n [1 1 0 ... 0 0 0]\n [1 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]]\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4f6e7c7d925c635c37c93de670f2afd042b3cb
8,353
ipynb
Jupyter Notebook
courses/machine_learning/deepdive/09_sequence/sinewaves.ipynb
aleistra/training-data-analyst
af6a59b56437c428f852d106de6e323717380ddb
[ "Apache-2.0" ]
null
null
null
courses/machine_learning/deepdive/09_sequence/sinewaves.ipynb
aleistra/training-data-analyst
af6a59b56437c428f852d106de6e323717380ddb
[ "Apache-2.0" ]
null
null
null
courses/machine_learning/deepdive/09_sequence/sinewaves.ipynb
aleistra/training-data-analyst
af6a59b56437c428f852d106de6e323717380ddb
[ "Apache-2.0" ]
null
null
null
28.606164
553
0.54244
[ [ [ "<h1> Time series prediction, end-to-end </h1>\n\nThis notebook illustrates several models to find the next value of a time-series:\n<ol>\n<li> Linear\n<li> DNN\n<li> CNN \n<li> RNN\n</ol>", "_____no_output_____" ] ], [ [ "# change these to try this notebook out\nBUCKET = 'cloud-training-demos-ml'\nPROJECT = 'cloud-training-demos'\nREGION = 'us-central1'\nSEQ_LEN = 50", "_____no_output_____" ], [ "import os\nos.environ['BUCKET'] = BUCKET\nos.environ['PROJECT'] = PROJECT\nos.environ['REGION'] = REGION\nos.environ['SEQ_LEN'] = str(SEQ_LEN)\nos.environ['TFVERSION'] = '1.8'", "_____no_output_____" ] ], [ [ "<h3> Simulate some time-series data </h3>\n\nEssentially a set of sinusoids with random amplitudes and frequencies.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nprint(tf.__version__)", "_____no_output_____" ], [ "import numpy as np\nimport seaborn as sns\n\ndef create_time_series():\n freq = (np.random.random()*0.5) + 0.1 # 0.1 to 0.6\n ampl = np.random.random() + 0.5 # 0.5 to 1.5\n noise = [np.random.random()*0.3 for i in range(SEQ_LEN)] # -0.3 to +0.3 uniformly distributed\n x = np.sin(np.arange(0,SEQ_LEN) * freq) * ampl + noise\n return x\n\nflatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\"]\nfor i in range(0, 5):\n sns.tsplot( create_time_series(), color=flatui[i%len(flatui)] ); # 5 series", "_____no_output_____" ], [ "def to_csv(filename, N):\n with open(filename, 'w') as ofp:\n for lineno in range(0, N):\n seq = create_time_series()\n line = \",\".join(map(str, seq))\n ofp.write(line + '\\n')\n\nimport os\ntry:\n os.makedirs('data/sines/')\nexcept OSError:\n pass\n\nnp.random.seed(1) # makes data generation reproducible\n\nto_csv('data/sines/train-1.csv', 1000) # 1000 sequences\nto_csv('data/sines/valid-1.csv', 250)", "_____no_output_____" ], [ "!head -5 data/sines/*-1.csv", "_____no_output_____" ] ], [ [ "<h3> Train model locally </h3>\n\nMake sure the code works as intended.", "_____no_output_____" ] ], [ [ "%%bash\nDATADIR=$(pwd)/data/sines\nOUTDIR=$(pwd)/trained/sines\nrm -rf $OUTDIR\ngcloud ml-engine local train \\\n --module-name=sinemodel.task \\\n --package-path=${PWD}/sinemodel \\\n -- \\\n --train_data_path=\"${DATADIR}/train-1.csv\" \\\n --eval_data_path=\"${DATADIR}/valid-1.csv\" \\\n --output_dir=${OUTDIR} \\\n --model=linear --train_steps=10 --sequence_length=$SEQ_LEN", "_____no_output_____" ] ], [ [ "<h3> Cloud ML Engine </h3>\n\nNow to train on Cloud ML Engine with more data.", "_____no_output_____" ] ], [ [ "import shutil\nshutil.rmtree('data/sines', ignore_errors=True)\nos.makedirs('data/sines/')\nnp.random.seed(1) # makes data generation reproducible\nfor i in range(0,10):\n to_csv('data/sines/train-{}.csv'.format(i), 1000) # 1000 sequences\n to_csv('data/sines/valid-{}.csv'.format(i), 250)", "_____no_output_____" ], [ "%%bash\ngsutil -m rm -rf gs://${BUCKET}/sines/*\ngsutil -m cp data/sines/*.csv gs://${BUCKET}/sines", "_____no_output_____" ], [ "%%bash\nfor MODEL in linear dnn cnn rnn rnn2 rnnN; do\n OUTDIR=gs://${BUCKET}/sinewaves/${MODEL}\n JOBNAME=sines_${MODEL}_$(date -u +%y%m%d_%H%M%S)\n gsutil -m rm -rf $OUTDIR\n gcloud ml-engine jobs submit training $JOBNAME \\\n --region=$REGION \\\n --module-name=sinemodel.task \\\n --package-path=${PWD}/sinemodel \\\n --job-dir=$OUTDIR \\\n --scale-tier=BASIC \\\n --runtime-version=$TFVERSION \\\n -- \\\n --train_data_path=\"gs://${BUCKET}/sines/train*.csv\" \\\n --eval_data_path=\"gs://${BUCKET}/sines/valid*.csv\" \\\n --output_dir=$OUTDIR \\\n --train_steps=3000 --sequence_length=$SEQ_LEN --model=$MODEL\ndone", "_____no_output_____" ] ], [ [ "## Monitor training with TensorBoard\n\nUse this cell to launch tensorboard. If tensorboard appears blank try refreshing after 5 minutes", "_____no_output_____" ] ], [ [ "from google.datalab.ml import TensorBoard\nTensorBoard().start('gs://{}/sinewaves'.format(BUCKET))", "_____no_output_____" ], [ "for pid in TensorBoard.list()['pid']:\n TensorBoard().stop(pid)\n print('Stopped TensorBoard with pid {}'.format(pid))", "_____no_output_____" ] ], [ [ "## Results\n\nWhen I ran it, these were the RMSEs that I got for different models:\n\n| Model | Sequence length | # of steps | Minutes | RMSE |\n| --- | ----| --- | --- | --- | \n| linear | 50 | 3000 | 10 min | 0.150 |\n| dnn | 50 | 3000 | 10 min | 0.101 |\n| cnn | 50 | 3000 | 10 min | 0.105 |\n| rnn | 50 | 3000 | 11 min | 0.100 |\n| rnn2 | 50 | 3000 | 14 min |0.105 |\n| rnnN | 50 | 3000 | 15 min | 0.097 |\n\n### Analysis\nYou can see there is a significant improvement when switching from the linear model to non-linear models. But within the the non-linear models (DNN/CNN/RNN) performance for all is pretty similar. \n\nPerhaps it's because this is too simple of a problem to require advanced deep learning models. In the next lab we'll deal with a problem where an RNN is more appropriate.", "_____no_output_____" ], [ "Copyright 2017 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", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
ec4f8f36ebb8cd49aeeb51a80f07a8bfb1213457
24,611
ipynb
Jupyter Notebook
chatbot/43.memory-network-basic.ipynb
huseinzol05/Tensorflow-NLP-Models
0741216aa8235e1228b3de7903cc36d73f8f2b45
[ "MIT" ]
1,705
2018-11-03T17:34:22.000Z
2022-03-29T04:30:01.000Z
chatbot/43.memory-network-basic.ipynb
eridgd/NLP-Models-Tensorflow
d46e746cd038f25e8ee2df434facbe12e31576a1
[ "MIT" ]
26
2019-03-16T17:23:00.000Z
2021-10-08T08:06:09.000Z
chatbot/43.memory-network-basic.ipynb
eridgd/NLP-Models-Tensorflow
d46e746cd038f25e8ee2df434facbe12e31576a1
[ "MIT" ]
705
2018-11-03T17:34:25.000Z
2022-03-24T02:29:14.000Z
38.156589
190
0.521596
[ [ [ "import numpy as np\nimport tensorflow as tf\nfrom sklearn.utils import shuffle\nimport re\nimport time\nimport collections\nimport os", "_____no_output_____" ], [ "def build_dataset(words, n_words, atleast=1):\n count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n counter = collections.Counter(words).most_common(n_words)\n counter = [i for i in counter if i[1] >= atleast]\n count.extend(counter)\n dictionary = dict()\n for word, _ in count:\n dictionary[word] = len(dictionary)\n data = list()\n unk_count = 0\n for word in words:\n index = dictionary.get(word, 0)\n if index == 0:\n unk_count += 1\n data.append(index)\n count[0][1] = unk_count\n reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n return data, count, dictionary, reversed_dictionary", "_____no_output_____" ], [ "lines = open('movie_lines.txt', encoding='utf-8', errors='ignore').read().split('\\n')\nconv_lines = open('movie_conversations.txt', encoding='utf-8', errors='ignore').read().split('\\n')\n\nid2line = {}\nfor line in lines:\n _line = line.split(' +++$+++ ')\n if len(_line) == 5:\n id2line[_line[0]] = _line[4]\n \nconvs = [ ]\nfor line in conv_lines[:-1]:\n _line = line.split(' +++$+++ ')[-1][1:-1].replace(\"'\",\"\").replace(\" \",\"\")\n convs.append(_line.split(','))\n \nquestions = []\nanswers = []\n\nfor conv in convs:\n for i in range(len(conv)-1):\n questions.append(id2line[conv[i]])\n answers.append(id2line[conv[i+1]])\n \ndef clean_text(text):\n text = text.lower()\n text = re.sub(r\"i'm\", \"i am\", text)\n text = re.sub(r\"he's\", \"he is\", text)\n text = re.sub(r\"she's\", \"she is\", text)\n text = re.sub(r\"it's\", \"it is\", text)\n text = re.sub(r\"that's\", \"that is\", text)\n text = re.sub(r\"what's\", \"that is\", text)\n text = re.sub(r\"where's\", \"where is\", text)\n text = re.sub(r\"how's\", \"how is\", text)\n text = re.sub(r\"\\'ll\", \" will\", text)\n text = re.sub(r\"\\'ve\", \" have\", text)\n text = re.sub(r\"\\'re\", \" are\", text)\n text = re.sub(r\"\\'d\", \" would\", text)\n text = re.sub(r\"\\'re\", \" are\", text)\n text = re.sub(r\"won't\", \"will not\", text)\n text = re.sub(r\"can't\", \"cannot\", text)\n text = re.sub(r\"n't\", \" not\", text)\n text = re.sub(r\"n'\", \"ng\", text)\n text = re.sub(r\"'bout\", \"about\", text)\n text = re.sub(r\"'til\", \"until\", text)\n text = re.sub(r\"[-()\\\"#/@;:<>{}`+=~|.!?,]\", \"\", text)\n return ' '.join([i.strip() for i in filter(None, text.split())])\n\nclean_questions = []\nfor question in questions:\n clean_questions.append(clean_text(question))\n \nclean_answers = [] \nfor answer in answers:\n clean_answers.append(clean_text(answer))\n \nmin_line_length = 2\nmax_line_length = 5\nshort_questions_temp = []\nshort_answers_temp = []\n\ni = 0\nfor question in clean_questions:\n if len(question.split()) >= min_line_length and len(question.split()) <= max_line_length:\n short_questions_temp.append(question)\n short_answers_temp.append(clean_answers[i])\n i += 1\n\nshort_questions = []\nshort_answers = []\n\ni = 0\nfor answer in short_answers_temp:\n if len(answer.split()) >= min_line_length and len(answer.split()) <= max_line_length:\n short_answers.append(answer)\n short_questions.append(short_questions_temp[i])\n i += 1\n \nquestion_test = short_questions[500:550]\nanswer_test = short_answers[500:550]\nshort_questions = short_questions[:500]\nshort_answers = short_answers[:500]", "_____no_output_____" ], [ "concat_from = ' '.join(short_questions+question_test).split()\nvocabulary_size_from = len(list(set(concat_from)))\ndata_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\nprint('vocab from size: %d'%(vocabulary_size_from))\nprint('Most common words', count_from[4:10])\nprint('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])\nprint('filtered vocab size:',len(dictionary_from))\nprint(\"% of vocab used: {}%\".format(round(len(dictionary_from)/vocabulary_size_from,4)*100))", "vocab from size: 657\nMost common words [('you', 132), ('is', 78), ('i', 68), ('what', 51), ('it', 50), ('that', 49)]\nSample data [7, 28, 129, 35, 61, 42, 12, 22, 82, 225] ['what', 'good', 'stuff', 'she', 'okay', 'they', 'do', 'to', 'hey', 'sweet']\nfiltered vocab size: 661\n% of vocab used: 100.61%\n" ], [ "concat_to = ' '.join(short_answers+answer_test).split()\nvocabulary_size_to = len(list(set(concat_to)))\ndata_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\nprint('vocab from size: %d'%(vocabulary_size_to))\nprint('Most common words', count_to[4:10])\nprint('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])\nprint('filtered vocab size:',len(dictionary_to))\nprint(\"% of vocab used: {}%\".format(round(len(dictionary_to)/vocabulary_size_to,4)*100))", "vocab from size: 660\nMost common words [('i', 97), ('you', 91), ('is', 62), ('it', 58), ('not', 47), ('what', 39)]\nSample data [12, 216, 5, 4, 94, 25, 59, 10, 8, 79] ['the', 'real', 'you', 'i', 'hope', 'so', 'they', 'do', 'not', 'hi']\nfiltered vocab size: 664\n% of vocab used: 100.61%\n" ], [ "GO = dictionary_from['GO']\nPAD = dictionary_from['PAD']\nEOS = dictionary_from['EOS']\nUNK = dictionary_from['UNK']", "_____no_output_____" ], [ "for i in range(len(short_answers)):\n short_answers[i] += ' EOS'", "_____no_output_____" ], [ "def str_idx(corpus, dic):\n X = []\n for i in corpus:\n ints = []\n for k in i.split():\n ints.append(dic.get(k,UNK))\n X.append(ints)\n return X\n\ndef pad_sentence_batch(sentence_batch, pad_int, maxlen):\n padded_seqs = []\n seq_lens = []\n max_sentence_len = maxlen\n for sentence in sentence_batch:\n padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n seq_lens.append(maxlen)\n return padded_seqs, seq_lens", "_____no_output_____" ], [ "X = str_idx(short_questions, dictionary_from)\nY = str_idx(short_answers, dictionary_to)\nX_test = str_idx(question_test, dictionary_from)\nY_test = str_idx(answer_test, dictionary_from)", "_____no_output_____" ], [ "maxlen_question = max([len(x) for x in X]) * 2\nmaxlen_answer = max([len(y) for y in Y]) * 2", "_____no_output_____" ], [ "def hop_forward(memory_o, memory_i, response_proj, inputs_len, questions_len):\n match = memory_i\n match = pre_softmax_masking(match, inputs_len)\n match = tf.nn.softmax(match)\n match = post_softmax_masking(match, questions_len)\n response = tf.multiply(match, memory_o)\n return response_proj(response)\n\n\ndef pre_softmax_masking(x, seq_len):\n paddings = tf.fill(tf.shape(x), float('-inf'))\n T = tf.shape(x)[1]\n max_seq_len = tf.shape(x)[2]\n masks = tf.sequence_mask(seq_len, max_seq_len, dtype = tf.float32)\n masks = tf.tile(tf.expand_dims(masks, 1), [1, T, 1])\n return tf.where(tf.equal(masks, 0), paddings, x)\n\n\ndef post_softmax_masking(x, seq_len):\n T = tf.shape(x)[2]\n max_seq_len = tf.shape(x)[1]\n masks = tf.sequence_mask(seq_len, max_seq_len, dtype = tf.float32)\n masks = tf.tile(tf.expand_dims(masks, -1), [1, 1, T])\n return x * masks\n\n\ndef shift_right(x):\n batch_size = tf.shape(x)[0]\n start = tf.to_int32(tf.fill([batch_size, 1], GO))\n return tf.concat([start, x[:, :-1]], 1)\n\n\ndef embed_seq(x, vocab_size, zero_pad = True):\n lookup_table = tf.get_variable(\n 'lookup_table', [vocab_size, size_layer], tf.float32\n )\n if zero_pad:\n lookup_table = tf.concat(\n (tf.zeros([1, size_layer]), lookup_table[1:, :]), axis = 0\n )\n return tf.nn.embedding_lookup(lookup_table, x)\n\n\ndef position_encoding(sentence_size, embedding_size):\n encoding = np.ones((embedding_size, sentence_size), dtype = np.float32)\n ls = sentence_size + 1\n le = embedding_size + 1\n for i in range(1, le):\n for j in range(1, ls):\n encoding[i - 1, j - 1] = (i - (le - 1) / 2) * (j - (ls - 1) / 2)\n encoding = 1 + 4 * encoding / embedding_size / sentence_size\n return np.transpose(encoding)\n\ndef quest_mem(x, vocab_size, max_quest_len):\n x = embed_seq(x, vocab_size)\n pos = position_encoding(max_quest_len, size_layer)\n return x * pos\n\nclass QA:\n def __init__(self, vocab_size_from, vocab_size_to, size_layer, learning_rate, n_hops = 3):\n self.X = tf.placeholder(tf.int32,[None,None])\n self.Y = tf.placeholder(tf.int32,[None,None])\n self.X_seq_len = tf.fill([tf.shape(self.X)[0]],maxlen_question)\n self.Y_seq_len = tf.fill([tf.shape(self.X)[0]],maxlen_answer)\n max_quest_len = maxlen_question\n max_answer_len = maxlen_answer\n \n lookup_table = tf.get_variable('lookup_table', [vocab_size_from, size_layer], tf.float32)\n \n with tf.variable_scope('memory_o'):\n memory_o = quest_mem(self.X, vocab_size_from, max_quest_len)\n \n with tf.variable_scope('memory_i'):\n memory_i = quest_mem(self.X, vocab_size_from, max_quest_len)\n \n with tf.variable_scope('interaction'):\n response_proj = tf.layers.Dense(size_layer)\n for _ in range(n_hops):\n answer = hop_forward(memory_o,\n memory_i,\n response_proj,\n self.X_seq_len,\n self.X_seq_len)\n memory_i = answer\n \n embedding = tf.Variable(tf.random_uniform([vocab_size_to, size_layer], -1, 1))\n cell = tf.nn.rnn_cell.BasicRNNCell(size_layer)\n vocab_proj = tf.layers.Dense(vocab_size_to)\n state_proj = tf.layers.Dense(size_layer)\n init_state = state_proj(tf.layers.flatten(answer))\n \n helper = tf.contrib.seq2seq.TrainingHelper(\n inputs = tf.nn.embedding_lookup(embedding, shift_right(self.Y)),\n sequence_length = tf.to_int32(self.Y_seq_len))\n decoder = tf.contrib.seq2seq.BasicDecoder(cell = cell,\n helper = helper,\n initial_state = init_state,\n output_layer = vocab_proj)\n decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder = decoder,\n maximum_iterations = max_answer_len)\n \n helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embedding = embedding,\n start_tokens = tf.tile(\n tf.constant([GO], \n dtype=tf.int32), \n [tf.shape(init_state)[0]]),\n end_token = EOS)\n decoder = tf.contrib.seq2seq.BasicDecoder(\n cell = cell,\n helper = helper,\n initial_state = init_state,\n output_layer = vocab_proj)\n predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n decoder = decoder,\n maximum_iterations = max_answer_len)\n self.training_logits = decoder_output.rnn_output\n self.predicting_ids = predicting_decoder_output.sample_id\n self.logits = decoder_output.sample_id\n masks = tf.sequence_mask(self.Y_seq_len, max_answer_len, dtype=tf.float32)\n self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n targets = self.Y,\n weights = masks)\n self.optimizer = tf.train.AdamOptimizer(learning_rate).minimize(self.cost)\n y_t = tf.argmax(self.training_logits,axis=2)\n y_t = tf.cast(y_t, tf.int32)\n self.prediction = tf.boolean_mask(y_t, masks)\n mask_label = tf.boolean_mask(self.Y, masks)\n correct_pred = tf.equal(self.prediction, mask_label)\n correct_index = tf.cast(correct_pred, tf.float32)\n self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))", "_____no_output_____" ], [ "epoch = 20\nbatch_size = 16\nsize_layer = 256\n\ntf.reset_default_graph()\nsess = tf.InteractiveSession()\nmodel = QA(len(dictionary_from), len(dictionary_to), size_layer, 1e-3)\nsess.run(tf.global_variables_initializer())", "WARNING:tensorflow:From <ipython-input-11-325e092a6241>:87: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n" ], [ "for i in range(epoch):\n total_loss, total_accuracy = 0, 0\n for k in range(0, len(short_questions), batch_size):\n index = min(k+batch_size, len(short_questions))\n batch_x, seq_x = pad_sentence_batch(X[k: index], PAD, maxlen_question)\n batch_y, seq_y = pad_sentence_batch(Y[k: index], PAD, maxlen_answer)\n predicted, accuracy,loss, _ = sess.run([model.predicting_ids, \n model.accuracy, model.cost, model.optimizer], \n feed_dict={model.X:batch_x,\n model.Y:batch_y})\n total_loss += loss\n total_accuracy += accuracy\n total_loss /= (len(short_questions) / batch_size)\n total_accuracy /= (len(short_questions) / batch_size)\n print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))", "epoch: 1, avg loss: 2.656108, avg accuracy: 0.651500\nepoch: 2, avg loss: 1.718702, avg accuracy: 0.745500\nepoch: 3, avg loss: 1.575576, avg accuracy: 0.748667\nepoch: 4, avg loss: 1.461585, avg accuracy: 0.754333\nepoch: 5, avg loss: 1.351241, avg accuracy: 0.760500\nepoch: 6, avg loss: 1.241524, avg accuracy: 0.768667\nepoch: 7, avg loss: 1.136217, avg accuracy: 0.784833\nepoch: 8, avg loss: 1.046826, avg accuracy: 0.805000\nepoch: 9, avg loss: 0.977793, avg accuracy: 0.823167\nepoch: 10, avg loss: 0.891704, avg accuracy: 0.836333\nepoch: 11, avg loss: 0.818897, avg accuracy: 0.856000\nepoch: 12, avg loss: 0.750899, avg accuracy: 0.865667\nepoch: 13, avg loss: 0.680844, avg accuracy: 0.880167\nepoch: 14, avg loss: 0.617358, avg accuracy: 0.894833\nepoch: 15, avg loss: 0.569545, avg accuracy: 0.901833\nepoch: 16, avg loss: 0.522961, avg accuracy: 0.909333\nepoch: 17, avg loss: 0.478646, avg accuracy: 0.917667\nepoch: 18, avg loss: 0.437554, avg accuracy: 0.926000\nepoch: 19, avg loss: 0.398225, avg accuracy: 0.934333\nepoch: 20, avg loss: 0.358397, avg accuracy: 0.945333\n" ], [ "for i in range(len(batch_x)):\n print('row %d'%(i+1))\n print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')", "row 1\nQUESTION: i am a werewolf\nREAL ANSWER: a werewolf\nPREDICTED ANSWER: a werewolf \n\nrow 2\nQUESTION: i was dreaming again\nREAL ANSWER: i would think so\nPREDICTED ANSWER: i would think so \n\nrow 3\nQUESTION: the kitchen\nREAL ANSWER: very nice\nPREDICTED ANSWER: very nice \n\nrow 4\nQUESTION: the bedroom\nREAL ANSWER: there is only one bed\nPREDICTED ANSWER: there is only one bed \n\n" ], [ "batch_x, seq_x = pad_sentence_batch(X_test[:batch_size], PAD, maxlen_question)\nbatch_y, seq_y = pad_sentence_batch(Y_test[:batch_size], PAD, maxlen_answer)\npredicted = sess.run(model.predicting_ids, feed_dict={model.X:batch_x})\n\nfor i in range(len(batch_x)):\n print('row %d'%(i+1))\n print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')", "row 1\nQUESTION: but david\nREAL ANSWER: is here that\nPREDICTED ANSWER: i will be another \n\nrow 2\nQUESTION: hopeless it is hopeless\nREAL ANSWER: tell ballet then back\nPREDICTED ANSWER: do you believe it \n\nrow 3\nQUESTION: miss price\nREAL ANSWER: yes learning\nPREDICTED ANSWER: we are you proposing \n\nrow 4\nQUESTION: mr kessler wake up please\nREAL ANSWER: is here are\nPREDICTED ANSWER: no i am okay \n\nrow 5\nQUESTION: there were witnesses\nREAL ANSWER: why she out\nPREDICTED ANSWER: hal maintain normal eva condition \n\nrow 6\nQUESTION: what about it\nREAL ANSWER: not you are\nPREDICTED ANSWER: i know honey me too \n\nrow 7\nQUESTION: go on ask them\nREAL ANSWER: i just home\nPREDICTED ANSWER: what for \n\nrow 8\nQUESTION: beware the moon\nREAL ANSWER: seen hi is he\nPREDICTED ANSWER: and i am asking you \n\nrow 9\nQUESTION: did you hear that\nREAL ANSWER: is down what\nPREDICTED ANSWER: how could i not \n\nrow 10\nQUESTION: i heard that\nREAL ANSWER: it here not\nPREDICTED ANSWER: no i am okay \n\nrow 11\nQUESTION: the hound of the baskervilles\nREAL ANSWER: heard\nPREDICTED ANSWER: how is she \n\nrow 12\nQUESTION: it is moving\nREAL ANSWER: not you hear\nPREDICTED ANSWER: you are a policeman \n\nrow 13\nQUESTION: nice doggie good boy\nREAL ANSWER: bill stupid\nPREDICTED ANSWER: how could i not \n\nrow 14\nQUESTION: it sounds far away\nREAL ANSWER: that pecos baby seen hi\nPREDICTED ANSWER: yes i thought so \n\nrow 15\nQUESTION: debbie klein cried a lot\nREAL ANSWER: is will srai not\nPREDICTED ANSWER: yes i thought so \n\nrow 16\nQUESTION: what are you doing here\nREAL ANSWER: is know look i\nPREDICTED ANSWER: i am afraid not therefore \n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4faa4fb51af3138f6b7e1d6b3eb58a37bb7bdb
3,939
ipynb
Jupyter Notebook
flux_pizzaoven/datagen/S2-simulator.ipynb
quantiaconsulting/linear-pizza-oven-2020
fa75a7b4544afcd0dc40cfb819f792fd2bac9edf
[ "Apache-2.0" ]
null
null
null
flux_pizzaoven/datagen/S2-simulator.ipynb
quantiaconsulting/linear-pizza-oven-2020
fa75a7b4544afcd0dc40cfb819f792fd2bac9edf
[ "Apache-2.0" ]
null
null
null
flux_pizzaoven/datagen/S2-simulator.ipynb
quantiaconsulting/linear-pizza-oven-2020
fa75a7b4544afcd0dc40cfb819f792fd2bac9edf
[ "Apache-2.0" ]
null
null
null
24.314815
145
0.540493
[ [ [ "# Sensor S1 Simulator", "_____no_output_____" ], [ "## Getting Started\n\nLet's start importing libraries and creating useful variables ", "_____no_output_____" ] ], [ [ "!pip install influxdb-client", "_____no_output_____" ], [ "from datetime import datetime\n\nfrom influxdb_client import InfluxDBClient, Point, WritePrecision\nfrom influxdb_client.client.write_api import SYNCHRONOUS\n\nurl = \"https://us-west-2-1.aws.cloud2.influxdata.com\"\ntoken = \"\"\norg = \"[email protected]\"\nbucket = \"training\"\n\nclient = InfluxDBClient(url=url, token=token)\nwrite_api = client.write_api(write_options=SYNCHRONOUS)", "_____no_output_____" ] ], [ [ "In order to write on cloud instance, use the following credentials:\n\n```\nurl = \"https://us-west-2-1.aws.cloud2.influxdata.com\"\ntoken = <create a token on your cloud>\norg = \"your username\"\n```", "_____no_output_____" ], [ "## Produce timed messages\n\nThe next cell will produce timed messages with temperature and humidity values distributed distributed according to a gaussian distribution", "_____no_output_____" ] ], [ [ "from random import gauss\nimport time\n\nwhile True:\n point = Point(\"iot-oven\").tag(\"sensor\", \"S2\").field(\"temperature\", gauss(110, 5.0)).field(\"humidity\", gauss(30, 5.0))\n print(point.to_line_protocol())\n write_api.write(bucket, org, point)\n time.sleep(5)", "_____no_output_____" ] ], [ [ "In order to explixitly add time to the data point use the `.point(...)` function.\n\n``` \npoint = (Point(\"iot-oven\")\n.tag(\"sensor\", \"S2\")\n.field(\"temperature\", gauss(110, 5.0))\n.field(\"humidity\", gauss(30, 5.0))\n.time(int(time.time_ns()))\n```\n\nYou can use a more readable date format\n\n```\n...\n.time('1996-02-25T21:20:00.001001231Z')\n```\n", "_____no_output_____" ], [ "## Change distribution parameters", "_____no_output_____" ] ], [ [ "# temperature controller partial failure, the stddev of S2 goes from 5 to 20\n\nwhile True:\n point = Point(\"iot-oven\").tag(\"sensor\", \"S2\").field(\"temperature\", gauss(110, 20.0)).field(\"humidity\", gauss(30, 5.0))\n print(point.to_line_protocol())\n write_api.write(bucket, org, point)\n time.sleep(5)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
ec4fadf2bff30515d5227cc3d168fe4b4d5e0a55
34,556
ipynb
Jupyter Notebook
Neuron_Address_Distribution.ipynb
TrentBrick/attention-approximates-sdm
4cb44d825408a2e5af488ef166a9aa82ad2a2b31
[ "MIT" ]
8
2021-11-27T20:01:55.000Z
2021-12-08T13:34:36.000Z
Neuron_Address_Distribution.ipynb
TrentBrick/attention-approximates-sdm
4cb44d825408a2e5af488ef166a9aa82ad2a2b31
[ "MIT" ]
null
null
null
Neuron_Address_Distribution.ipynb
TrentBrick/attention-approximates-sdm
4cb44d825408a2e5af488ef166a9aa82ad2a2b31
[ "MIT" ]
null
null
null
175.411168
15,248
0.912837
[ [ [ "## Summary \n\nAuthor: Trenton Bricken\n\nComputing the probability at least one neuronal address is within a given Hamming distance of an address. Assumes neurons are randomly distributed throughout the space and takes an expectation.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import binom, norm\nfrom scipy.sparse import csc_matrix, coo_matrix, csr_matrix\nimport pandas as pd\nimport time", "_____no_output_____" ], [ "n=1000\nnprime = 1000000\nds = np.arange(0,n//2)\nys = 1-np.exp( -nprime*norm.cdf(ds, loc=n/2, scale=np.sqrt(n/4)) ) \nplt.plot( ds, ys )\nplt.title('Probability of at least one neuronal address \\n being within $d$ Hamming distance. $n=1,000$, $r=1,000,000$.')\nplt.ylabel('Probability')\nplt.xlabel('Hamming distance $d$')\n#plt.axhline(0.5, color='red')\nplt.axvline(424, color='red')\n\nplt.gcf().savefig('figures/SDMProbAddressWithinDistanceD.png', dpi=250)\nplt.show()\n", "_____no_output_____" ] ], [ [ "## Experimenting with the Binomial CDF", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import binom, norm\nfrom scipy.sparse import csc_matrix, coo_matrix, csr_matrix\nimport pandas as pd\nimport time", "_____no_output_____" ], [ "\nn = 1000\nd = 500\nr =1000000", "_____no_output_____" ], [ "# inverse of the CDF to find specific values. \n# finding the first probability that there is one value here. \nnorm.ppf(1/r, loc=n/2, scale=np.sqrt(n/4))", "_____no_output_____" ], [ "\n\nfor ds in [np.arange(0,n//2), np.arange(0,n//3)]:\n ys = norm.cdf(ds, loc=n/2, scale=np.sqrt(n/4))*r\n plt.plot( ds, ys )\n #plt.title('Probability of at least one neuronal address \\n being within $d$ Hamming distance. $n=1,000$, $r=1,000,000$.')\n #plt.ylabel('Probability')\n plt.xlabel('Hamming distance $d$')\n plt.axhline(5)\n plt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ec4faff0588a10e3d526473c39268d0c7f8e2f07
670,702
ipynb
Jupyter Notebook
20200603/lifeCycleModel-housing.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
20200603/lifeCycleModel-housing.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
20200603/lifeCycleModel-housing.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
880.186352
169,584
0.948169
[ [ [ "### Calculate the policy of the agent\n* State Variable: x = [w, n_lag, h_lag, e, s, A], action variable a = [c, b, k, h], both of them are numpy array ", "_____no_output_____" ] ], [ [ "%pylab inline\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport pandas as pd\nfrom scipy.interpolate import RegularGridInterpolator as RS\nfrom multiprocessing import Pool\nfrom functools import partial \nfrom pyswarm import pso\nimport warnings\nfrom scipy import optimize\n\nwarnings.filterwarnings(\"ignore\")\nnp.printoptions(precision=2)\n# time line\nT_min = 0\nT_max = 70\nT_R = 45\nbeta = 1/(1+0.02)\n# All the money amount are denoted in thousand dollars\nearningShock = [0.8,1.2]\n# Define transition matrix of economical states\n# GOOD -> GOOD 0.8, BAD -> BAD 0.6 \nPs = np.array([[0.6, 0.4],[0.2, 0.8]])\n# current risk free interest rate \nr_f = np.array([0.01 ,0.03])\n# stock return depends on current and future econ states\nr_m = np.array([[-0.2, 0.15],[-0.15, 0.2]])\n# expected return on stock market \nr_bar = 0.0667\n# probability of survival\nPa = np.load(\"prob.npy\")\n# probability of employment transition \nPe = np.array([[[[0.3, 0.7], [0.1, 0.9]], [[0.25, 0.75], [0.05, 0.95]]],\n [[[0.25, 0.75], [0.05, 0.95]], [[0.2, 0.8], [0.01, 0.99]]]])\n# deterministic income\ndetEarning = np.load(\"detEarning.npy\")\n# tax rate \ntau_L = 0.2\ntau_R = 0.1\n# minimum consumption\nc_bar = 3", "Populating the interactive namespace from numpy and matplotlib\n" ], [ "#Define the new utility function as a funciton of consumption good cost and renting\ndef u(c, h):\n alpha = 0.88\n kappa = 0\n gamma = 2\n ch = np.float_power(max(c-c_bar,0),alpha) * np.float_power((1+kappa)*h,1-alpha)\n return (np.float_power(ch,1-gamma) - 1)/(1 - gamma)\n\n#Define the bequeath function, which is a function of wealth \ndef uB(w):\n B = 2\n gamma = 2\n return B*(np.float_power(max(w,0),1-gamma) - 1)/(1 - gamma)\n\n#Define the earning function \ndef y(t, x):\n w, n, h_lag, s, e, A = x\n if A == 0:\n return 0\n else:\n if t <= T_R:\n return detEarning[t] * earningShock[int(s)] * e + (1-e)*5\n else:\n return detEarning[t]\n\n# Define the reward funtion\ndef R(x, a):\n c, b, k, h = a\n w, n, h_lag, s, e, A = x\n if A == 0:\n return uB(w+n)\n else:\n return u(c,h)\n\n# Define the transtiion of state (test)\ndef transition(x, a, t):\n '''\n Input: x current state: (w, n, h_lag, e, s, A) \n a action taken: (c, b, k, h)\n Output: the next possible states with corresponding probabilities\n '''\n c, b, k, h = a\n w, n, h_lag, s, e, A = x\n \n x_next = []\n prob_next = []\n # Agent is dead \n if A == 0:\n for s_next in [0, 1]:\n x_next.append([0, 0, 0, s_next, 0, 0])\n return np.array(x_next), Ps[int(s)]\n else:\n # after retirement calculate the annuity payment\n N = np.sum(Pa[t:])\n discounting = ((1+r_bar)**N - 1)/(r_bar*(1+r_bar)**N)\n # A = 1, agent is still alive and for the next period\n Pat = [1-Pa[t], Pa[t]]\n r_bond = r_f[int(s)]\n if t < T_R:\n # before retirement agents put 5% of income to 401k\n if e == 1:\n n_next = (n+0.05*y(t,x))*(1+0.02)\n else:\n n_next = n*(1+0.02)\n else:\n n_next = n*(1+0.02)-n/discounting\n \n for s_next in [0, 1]:\n r_stock = r_m[int(s), s_next]\n w_next = b*(1+r_bond) + k*(1+r_stock)\n \n for e_next in [0,1]:\n for A_next in [0,1]:\n if A_next == 0:\n x_next.append([w_next, n*(1+0.02), h, s_next, 0, 0])\n else:\n # Age reaches 65 or agent is dead directly results in unemployment\n if t >= T_R:\n x_next.append([w_next, n_next, h, s_next, 0, 1])\n else:\n x_next.append([w_next, n_next, h, s_next, e_next, 1])\n prob_next.append(Pat[A_next] * Pe[int(s),s_next,int(e),e_next])\n return np.array(x_next), np.array(prob_next) \n \n \n# Value function is a function of state and time t\ndef V(x, t, Vmodel):\n # Define the objective function as a function of action\n potentialH = [2, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]\n w, n, h_lag, s, e, A = x\n if A == 0:\n return np.array([R(x,[0,0,0,0]),[0,0,0,0]])\n else: \n N = np.sum(Pa[t:])\n discounting = ((1+r_bar)**N - 1)/(r_bar*(1+r_bar)**N)\n pr = 2\n ytx = y(t, x)\n def obj(thetas, h):\n theta1, theta2 = thetas\n if t < T_R:\n if e == 1:\n bk = ((1-tau_L)*(ytx * 0.95) + w) * theta1\n ch = ((1-tau_L)*(ytx * 0.95) + w) *(1-theta1)\n else:\n bk = ((1-tau_L)*ytx + w) * theta1\n ch = ((1-tau_L)*ytx + w) * (1-theta1)\n else:\n bk = ((1-tau_R)*ytx + w + n_discount) * theta1\n ch = ((1-tau_R)*ytx + w + n_discount) * (1-theta1)\n \n b = bk * theta2\n k = bk * (1-theta2)\n c = ch - pr*h - 5*(h != h_lag)\n if c <= c_bar:\n return 999999999\n a = (c,b,k,h)\n x_next, prob_next = transition(x, a, t)\n return -(R(x, a) + beta * np.dot(Vmodel[int(s)][int(e)][int(A)](x_next[:,:3]), prob_next))\n \n xopts = []\n fopts = []\n for hval in potentialH:\n xopt, fopt = pso(partial(obj, h = hval), lb=[0,0,0], ub =[1,1,1], swarmsize = 60)\n xopts.append(xopt)\n fopts.append(-fopts)\n \n index = np.argmax(fopts)\n max_val = fopts[index]\n theta1_m, theta2_m = xopts[index]\n h_m = potentialH[index]\n \n if t < T_R:\n if e == 1:\n bk_m = ((1-tau_L)*(ytx * 0.95) + w) * theta1_m\n ch_m = ((1-tau_L)*(ytx * 0.95) + w) * (1-theta1_m)\n else:\n bk_m = ((1-tau_L)*ytx + w) * theta1_m\n ch_m = ((1-tau_L)*ytx + w) * (1-theta1_m)\n \n else:\n bk_m = ((1-tau_R)*ytx + w + n_discount) * theta1_m\n ch_m = ((1-tau_R)*ytx + w + n_discount) * (1-theta1_m)\n \n b_m = bk_m * theta2_m\n k_m = bk_m * (1-theta2_m)\n c_m = ch_m - pr*h_m - 5*(h_m != h_lag)\n return np.array([max_val, [c_m, b_m, k_m, h_m]])", "_____no_output_____" ], [ "# wealth discretization \nw_grid_size = 50\nw_lower = 5\nw_upper = 20000\n# 401k amount discretization \nn_grid_size = 10\nn_lower = 5\nn_upper = 20000\n# housing consumption discretization\nh_grid = np.array([2, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50])\nh_grid_size = 11 \n\ndef powspace(start, stop, power, num):\n start = np.power(start, 1/float(power))\n stop = np.power(stop, 1/float(power))\n return np.power( np.linspace(start, stop, num=num), power)\n\n# initialize the state discretization \nx_T = np.array([[w,n,h_lag,e,s,0] for w in powspace(w_lower, w_upper, 3, w_grid_size)\n for n in powspace(n_lower, n_upper, 3, n_grid_size)\n for h_lag in h_grid\n for s in [0,1]\n for e in [0,1]\n for A in [0,1]]).reshape((w_grid_size, n_grid_size, h_grid_size, 2,2,2,6))\n\nxgrid = np.array([[w,n,h_lag,e,s,A] for w in powspace(w_lower, w_upper, 3, w_grid_size)\n for n in powspace(n_lower, n_upper, 3, n_grid_size)\n for h_lag in h_grid\n for s in [0,1]\n for e in [0,1]\n for A in [0,1]]).reshape((w_grid_size, n_grid_size, h_grid_size, 2,2,2,6))\n\nVgrid = np.zeros((w_grid_size, n_grid_size, h_grid_size, 2, 2, 2, T_max+1))\ncgrid = np.zeros((w_grid_size, n_grid_size, h_grid_size, 2, 2, 2, T_max+1))\nbgrid = np.zeros((w_grid_size, n_grid_size, h_grid_size, 2, 2, 2, T_max+1))\nkgrid = np.zeros((w_grid_size, n_grid_size, h_grid_size, 2, 2, 2, T_max+1))\nhgrid = np.zeros((w_grid_size, n_grid_size, h_grid_size, 2, 2, 2, T_max+1))\n\n# apply function to state space, need to reshape the matrix and shape it back to the size\ndef applyFunToCalculateValue(fun, x = xgrid):\n return np.array(list(map(fun, x.reshape((w_grid_size * n_grid_size * h_grid_size* 2 * 2 * 2, 6))))).reshape((w_grid_size, n_grid_size,h_grid_size,2,2,2))\n\nVgrid[:,:,:,:,:,:, T_max] = applyFunToCalculateValue(partial(R, a = [0,0,0,0]), x = x_T)", "_____no_output_____" ] ], [ [ "### Backward Induction Part", "_____no_output_____" ] ], [ [ "%%time \nws = powspace(w_lower, w_upper, 3, w_grid_size)\nns = powspace(n_lower, n_upper, 3, n_grid_size)\nhs = np.array([2, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50])\n\nxs = xgrid.reshape((w_grid_size * n_grid_size * h_grid_size * 2 * 2 * 2, 6))\n\npool = Pool()\n\nfor t in range(T_max-1, T_max-5, -1):\n print(t)\n cs = [[[RS((ws, ns, hs), Vgrid[:,:,:,s,e,A,t+1],bounds_error=False, fill_value= None) for A in [0,1]] for e in [0,1]] for s in [0,1]]\n f = partial(V, t = t, Vmodel = cs)\n results = np.array(pool.map(f, xs)) \n Vgrid[:,:,:,:,:,:,t] = results[:,0].reshape((w_grid_size,n_grid_size,h_grid_size, 2,2,2))\n #########################################################[test function part] \n fig = plt.figure(figsize = [12, 8])\n ax = fig.add_subplot(111, projection='3d')\n ax.plot_surface(X = xgrid[:,:,0,1,1,1,0], Y = xgrid[:,:,0,1,1,1,1], Z=Vgrid[:,:,0,1,1,1,t])\n plt.show()\n #########################################################\n cgrid[:,:,:,:,:,:,t] = np.array([r[0] for r in results[:,1]]).reshape((w_grid_size, n_grid_size, h_grid_size,2,2,2))\n bgrid[:,:,:,:,:,:,t] = np.array([r[1] for r in results[:,1]]).reshape((w_grid_size, n_grid_size, h_grid_size,2,2,2))\n kgrid[:,:,:,:,:,:,t] = np.array([r[2] for r in results[:,1]]).reshape((w_grid_size, n_grid_size, h_grid_size,2,2,2))\n hgrid[:,:,:,:,:,:,t] = np.array([r[3] for r in results[:,1]]).reshape((w_grid_size, n_grid_size, h_grid_size,2,2,2))\npool.close()", "69\n" ], [ "def summaryPlotChoiceVStime(w_level, n_level, s, e, A, V = Vgrid, C = cgrid, B = bgrid, K = kgrid):\n plt.figure(figsize = [12,8])\n plt.plot(list(range(20,91)), cgrid[w_level, n_level, s,e,A,:], label= \"Consumption\")\n plt.plot(list(range(20,91)), bgrid[w_level, n_level, s,e,A,:], label= \"Bond Holding\")\n plt.plot(list(range(20,91)), kgrid[w_level, n_level, s,e,A,:], label= \"Stock Holding\")\n plt.legend()\n plt.show()\nsummaryPlotChoiceVStime(50, 0, 1, 1)", "_____no_output_____" ], [ "def summaryPlotWealthVSChoice(t, s, e, A, V = Vgrid, C = cgrid, B = bgrid, K = kgrid):\n plt.figure(figsize = [12,8])\n plt.plot(ws, cgrid[:,s,e,A,t], label=\"Consumption\")\n plt.plot(ws, bgrid[:,s,e,A,t], label=\"Bond Holding\")\n plt.plot(ws, kgrid[:,s,e,A,t], label=\"Stock Holding\")\n plt.legend()\n plt.show()\nsummaryPlotWealthVSChoice(60, 0, 1, 1)", "_____no_output_____" ] ], [ [ "### Simulation Part", "_____no_output_____" ] ], [ [ "import quantecon as qe\nmc = qe.MarkovChain(Ps)\n\ndef action(t, x):\n w,s,e,A = x\n if A == 1:\n c = interp1d(ws, cgrid[:,s,e,A,t], kind = \"linear\", fill_value = \"extrapolate\")(w)\n b = interp1d(ws, bgrid[:,s,e,A,t], kind = \"linear\", fill_value = \"extrapolate\")(w)\n k = interp1d(ws, kgrid[:,s,e,A,t], kind = \"linear\", fill_value = \"extrapolate\")(w)\n else:\n c = 0\n b = 0\n k = 0\n return (c,b,k)\n\n# Define the transtiion of state \ndef transition(x, a, t, s_next):\n '''\n Input: x current state: (w, n, s, A) \n a action taken: (c, b, k)\n Output: the next possible states with corresponding probabilities\n '''\n c, b, k = a\n w, s, e, A = x\n \n x_next = []\n prob_next = []\n if A == 0:\n return [0, s_next, 0, 0]\n else:\n # A = 1, agent is still alive and for the next period\n Pat = [1-Pa[t], Pa[t]]\n r_bond = r_f[int(s)]\n r_stock = r_m[int(s), s_next]\n w_next = b*(1+r_bond) + k*(1+r_stock)\n for e_next in [0,1]:\n for A_next in [0,1]:\n x_next.append([w_next, s_next, e_next, A_next])\n prob_next.append(Pat[A_next] * Pe[int(s),s_next,int(e),e_next])\n return x_next[np.random.choice(4, 1, p = prob_next)[0]]", "_____no_output_____" ], [ "def simulation(num):\n for sim in range(num):\n if sim%100 == 0:\n print(sim)\n # simulate an agent age 15 starting with wealth of 10\n w = 20\n wealth = []\n Consumption = []\n Bond = []\n Stock = []\n Salary = []\n econState = mc.simulate(ts_length=T_max - T_min)\n alive = True\n for t in range(len(econState)-1):\n if rd.random() > prob[t]:\n alive = False\n wealth.append(w)\n s = econState[t]\n s_next = econState[t+1]\n a = action(t, w, s, alive)\n if alive:\n Salary.append(y(t+T_min, s))\n else:\n Salary.append(0)\n Consumption.append(a[0])\n Bond.append(a[1])\n Stock.append(a[2])\n w = fixTransition(w,s,s_next, a, alive)\n # dictionary of lists \n dictionary = {'wealth': wealth,\n 'Consumption': Consumption, \n 'Bond': Bond, \n 'Stock': Stock,\n 'Salary': Salary}\n if sim == 0:\n df = pd.DataFrame(dictionary) \n else:\n df = df + pd.DataFrame(dictionary) \n return df/num ", "_____no_output_____" ], [ "# simulate an agent age 0 starting with wealth of 70\neconState = mc.simulate(ts_length=T_max - T_min)\ndef simulateAgent(sim):\n wealth = []\n Consumption = []\n Bond = []\n Stock = []\n Salary = []\n employ = []\n live = []\n x = [20, 0, 0, 1]\n for t in range(len(econState)-1):\n s = econState[t]\n s_next = econState[t+1]\n a = action(t, x)\n c, b, k = a\n w,_,e,A = x\n \n wealth.append(w)\n Consumption.append(c)\n Bond.append(b)\n Stock.append(k)\n Salary.append(y(t, x))\n employ.append(e)\n live.append(A)\n x = transition(x, a, t, s_next)\n # dictionary of lists \n dictionary = {'wealth': wealth,\n 'Consumption': Consumption, \n 'Bond': Bond, \n 'Stock': Stock,\n 'Salary': Salary,\n 'employ': employ,\n 'live': live}\n return pd.DataFrame(dictionary)", "_____no_output_____" ], [ "pool = Pool()\nsim = 10000\nagents = pool.map(simulateAgent, list(range(sim)))\npool.close()", "_____no_output_____" ], [ "df = pd.DataFrame()\nfor agent in agents:\n if df.size == 0:\n df = agent\n else:\n df = df + agent\ndf = df/sim", "_____no_output_____" ], [ "df = df/10000", "_____no_output_____" ], [ "df.plot()", "_____no_output_____" ], [ "df[[\"wealth\",\"Consumption\",\"Bond\",\"Stock\"]].plot()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4fba8ee0c7c61452bfff44af1fa9ec006973df
782
ipynb
Jupyter Notebook
bindings/python/docs/Reference.ipynb
open-space-collective/library-io
0d6c6844dc578afeda67e2078402ad9c9ca60a40
[ "Apache-2.0" ]
5
2018-08-20T06:47:18.000Z
2019-08-19T15:54:23.000Z
bindings/python/docs/Reference.ipynb
open-space-collective/library-io
0d6c6844dc578afeda67e2078402ad9c9ca60a40
[ "Apache-2.0" ]
15
2018-06-15T01:19:49.000Z
2020-01-05T02:33:30.000Z
bindings/python/docs/Reference.ipynb
open-space-collective/open-space-toolkit-io
bbdfe7c57aa47d64380eb952b2819217c3053b46
[ "Apache-2.0" ]
2
2020-03-05T18:17:50.000Z
2020-04-07T18:18:30.000Z
16.638298
40
0.501279
[ [ [ "# Open Space Toolkit ▸ I/O", "_____no_output_____" ], [ "[I/O ▸ URL](./Reference/URL.ipynb)", "_____no_output_____" ], [ "[I/O ▸ IP](./Reference/IP.ipynb)", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown" ] ]
ec4fc7ce7b3419de1a1e528e7b61f202092884f2
198,277
ipynb
Jupyter Notebook
modules/analysis.ipynb
augustobor/cryptocuirrencies--data-analysis
0d7009717d2aab75e7ceaf07c983a204ab7221e9
[ "MIT" ]
1
2022-03-03T00:43:40.000Z
2022-03-03T00:43:40.000Z
modules/analysis.ipynb
augustobor/cryptocuirrencies--data-analysis
0d7009717d2aab75e7ceaf07c983a204ab7221e9
[ "MIT" ]
null
null
null
modules/analysis.ipynb
augustobor/cryptocuirrencies--data-analysis
0d7009717d2aab75e7ceaf07c983a204ab7221e9
[ "MIT" ]
null
null
null
223.033746
44,478
0.899383
[ [ [ "### Analysis = correlaciones y reducción de dimensiones por PCA. Retorno de data frame ya procesado", "_____no_output_____" ] ], [ [ "import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport seaborn as sns", "_____no_output_____" ], [ "pd.options.display.float_format='{:.2f}'.format", "_____no_output_____" ], [ "coinmarketcap_data = pd.read_csv('../clean_dataframes/coinmarketcap_cleaned.csv')", "_____no_output_____" ], [ "coinmarketcap_data.head()", "_____no_output_____" ] ], [ [ "### 1. Which are the 5 cryptocurrencies more relevants in the market?", "_____no_output_____" ], [ "##### To answer it let's define \"relevant\" as those who has a great market cap and transaction volume.", "_____no_output_____" ], [ "##### Plot the top cryptos with best market cap", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,5))\n\ntop_5_market_cap = coinmarketcap_data.sort_values('market_cap_usd', ascending=0)[0:5]\nsns.barplot(x='name', y='market_cap_usd',palette=\"rocket\" ,data=top_5_market_cap)\n\nplt.title('Top 5 market cap', family='avenir', weight='bold', size=24, pad=20)\nplt.xlabel('name', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.ylabel('market_cap_usd', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.show()", "findfont: Font family ['avenir'] not found. Falling back to DejaVu Sans.\nfindfont: Font family ['avenir'] not found. Falling back to DejaVu Sans.\n" ] ], [ [ "##### Plot the volume of those cryptos with best market cap. ", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,5))\n\ntop_5_market_cap = coinmarketcap_data.sort_values('24h_volume_usd', ascending=0)[0:5]\nsns.barplot(x='name', y='24h_volume_usd',palette=\"rocket\" ,data=top_5_market_cap)\n\nplt.title('Top 5 24h_volume_usd', family='avenir', weight='bold', size=24, pad=20)\nplt.xlabel('name', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.ylabel('24h_volume_usd', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.show()\n", "_____no_output_____" ] ], [ [ "##### Notes\n\n- As we can see Bitcoin is so far the cryptocurrency in market and volume terms. Let's try to extract Bitcoin from the model to see in perspective the market cup in other assets.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,5))\n\ntop_5_market_cap = coinmarketcap_data.sort_values('market_cap_usd', ascending=0)[1:6]\nsns.barplot(x='name', y='market_cap_usd',palette=\"rocket\" ,data=top_5_market_cap)\n\nplt.title('Top 5 market cap without BTC', family='avenir', weight='bold', size=24, pad=20)\nplt.xlabel('name', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.ylabel('market_cap_usd', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.show()", "_____no_output_____" ], [ "plt.figure(figsize=(10,5))\n\ntop_5_market_cap = coinmarketcap_data.sort_values('24h_volume_usd', ascending=0)[1:6]\nsns.barplot(x='name', y='24h_volume_usd',palette=\"rocket\" ,data=top_5_market_cap)\n\nplt.title('Top 5 24h_volume_usd without BTC', family='avenir', weight='bold', size=24, pad=20)\nplt.xlabel('name', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.ylabel('24h_volume_usd', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.show()", "_____no_output_____" ] ], [ [ "- We have similar comparable values from Ethereum to Litecoin. So The top market cup without bitcoin have similar values.", "_____no_output_____" ], [ "#### Conclusions:\n\n- Bitcoin es la cryptomoneda indiscutible en cuanto a marketcap y volumen en USD\n- Another assets have comparable values. Variation in market cup is less if we cut out bitcoin.", "_____no_output_____" ], [ "### 2. The market cap and cryptocurrencies volume per 24 hours are correlated?", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,10))\n\n\nsns.scatterplot(x='market_cap_usd', y='24h_volume_usd',sizes=(20,200) ,hue='market_cap_usd',data=coinmarketcap_data)\nplt.xlim(0,50000000000)\nplt.ylim(0,50000000000)\nplt.show()", "_____no_output_____" ] ], [ [ "- As we can see. There are some point farther in 'market_cap_usd' ax. But at the same time there are lower in '24h_volume_usd' ax.", "_____no_output_____" ], [ "##### Conclusion:\n\n- Market_cap_usd and 24h_volume_usd are not correlated. And that means that give investement in some crypto to increase the market cap doesn't mean that would increase the volume in usd.", "_____no_output_____" ], [ "### 3. What is the crypto who has more available supply?", "_____no_output_____" ], [ "A crypto with available supply means that has cryptos that are not minned yet. So it could be a great business try to mine to give a reward", "_____no_output_____" ], [ "First we should cut off those cryptos who has no shortage. Example: Ethereum", "_____no_output_____" ] ], [ [ "\ncryptos_with_shortage = coinmarketcap_data[coinmarketcap_data['max_supply'].notna()]\ncryptos_with_shortage.head()", "_____no_output_____" ] ], [ [ "##### We set a column called 'available_supply_percent'", "_____no_output_____" ] ], [ [ "cryptos_with_shortage['available_supply_percent'] = cryptos_with_shortage['available_supply']/cryptos_with_shortage['max_supply']\ncryptos_with_shortage.head()", "C:\\Users\\Augusto\\AppData\\Local\\Temp/ipykernel_3872/791664934.py: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 cryptos_with_shortage['available_supply_percent'] = cryptos_with_shortage['available_supply']/cryptos_with_shortage['max_supply']\n" ] ], [ [ "##### Plot the top 5 cryptos with more % of available supply from max_supply", "_____no_output_____" ] ], [ [ "\nplt.figure(figsize=(10,5))\n\ntop_5_available_supply = cryptos_with_shortage.sort_values('available_supply_percent', ascending=0)[0:5]\nsns.barplot(x='name', y='available_supply_percent',palette=\"rocket\" ,data=top_5_available_supply)\n\nplt.title('top_5_cryptos_with_more_available_percent', family='avenir', weight='bold', size=24, pad=20)\nplt.xlabel('name', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.ylabel('available_supply_percent', family='avenir', weight=\"light\", size=16, labelpad=15)\nplt.show()", "_____no_output_____" ] ], [ [ "#### Notes\n\n- Cryptos with more available percent are not popular. That could be mean 2 things: The crypto project is awful or the project is good but is recently. In both case is important investigate the project value itself and then if its benefict then mine this crypto could have profits.", "_____no_output_____" ], [ "### Lab", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(15,10))\n\nplt.subplot(1, 2, 1)\n\nplt.title('latest_top_5_available_supply', family='avenir', weight=\"bold\", size=24, pad=20)\nsns.barplot(x='name',y='available_supply',palette=\"rocket\",data=coinmarketcap_data.sort_values('available_supply')[0:5])\n\nplt.subplot(1, 2, 2)", "_____no_output_____" ], [ "pie_crypto_volume = {coinmarketcap_data['name'][i]: coinmarketcap_data['24h_volume_usd'][i] for i in range(5)}\n\nplt.figure(figsize=(20,20))\n\ncolor= ['#DF5838', '#FF5733','#EFC12D', '#FFC30F', '#FFC26B']\n\nplt.subplot(1, 2, 1)\n\n\ntp = { 'weight': 'bold', 'color': 'white', 'size': '15'}\nplt.title('% volume by currency', family='avenir', weight=\"bold\",color=\"white\" ,size=30, pad=20)\nplt.pie(pie_crypto_volume.values(),startangle=90, textprops=tp ,labels=pie_crypto_volume.keys(), autopct='%1.1f%%',\n shadow=True, colors=color)\n\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
ec4fc9390d09ffc68802f10d7889b04e7190644a
11,933
ipynb
Jupyter Notebook
previous_final_project_examples/katepoole26/n-gram_frequency_analysis.ipynb
mbod/comm313_spring2021
58c3dd4b04245eac9f7df00efb56d146c4711b4b
[ "MIT" ]
null
null
null
previous_final_project_examples/katepoole26/n-gram_frequency_analysis.ipynb
mbod/comm313_spring2021
58c3dd4b04245eac9f7df00efb56d146c4711b4b
[ "MIT" ]
null
null
null
previous_final_project_examples/katepoole26/n-gram_frequency_analysis.ipynb
mbod/comm313_spring2021
58c3dd4b04245eac9f7df00efb56d146c4711b4b
[ "MIT" ]
1
2021-01-26T17:22:17.000Z
2021-01-26T17:22:17.000Z
24.50308
103
0.4268
[ [ [ "# n-Gram Frequency Distribution Analysis (R v. D)", "_____no_output_____" ], [ "## Setup", "_____no_output_____" ] ], [ [ "import os\n\nfrom collections import Counter\n\n%matplotlib inline\n\nimport os\nimport re\nimport csv\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom nltk import tokenize\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer", "_____no_output_____" ], [ "## Parameters\nto_strip = ',.\\xa0:-()\\';$\"/?][!`Ą@ڧ¨’–“”…ï‘>&\\\\%˝˘*'", "_____no_output_____" ], [ "## Open speeches\nall_speeches_r = open('data/republican_all.txt').read()\nall_speeches_d = open('data/democrat_all.txt').read()", "_____no_output_____" ] ], [ [ "## Functions", "_____no_output_____" ] ], [ [ " %run functions.ipynb", "_____no_output_____" ] ], [ [ "## Speech Tokens", "_____no_output_____" ] ], [ [ "republicantokens = tokenize(all_speeches_r)\ndemocrattokens = tokenize(all_speeches_d)\n\nprint('{} tokens in the Republican convention nominee speeches'.format(len(republicantokens)))\nprint('{} tokens in the Democratic convention nominee speeches'.format(len(democrattokens)))", "98055 tokens in the Republican convention nominee speeches\n91071 tokens in the Democratic convention nominee speeches\n" ] ], [ [ "## n-gram Frequencies - Republicans", "_____no_output_____" ] ], [ [ "## Split speeches by white space \nr_split = all_speeches_r.split('\\n\\n')", "_____no_output_____" ], [ "word_freq_r = Counter()\nbigram_freq_r = Counter()\ntrigram_freq_r = Counter()\n\nfor speech in r_split: \n r_replaced = speech.replace(': ', ' ').replace(',', '').replace('.', '')\n r_lower = r_replaced.lower()\n tokens_r = tokenize(r_lower)\n word_freq_r.update(tokens_r)\n bigrams_r = get_bigram_tokens(tokens_r)\n bigram_freq_r.update(bigrams_r)\n trigrams_r = get_ngram_tokens(tokens_r, n = 3)\n trigram_freq_r.update(trigrams_r)\n\nword_freq_r.most_common(30)", "_____no_output_____" ], [ "bigram_freq_r.most_common(30)", "_____no_output_____" ], [ "trigram_freq_r.most_common(30)", "_____no_output_____" ] ], [ [ "## n-gram Frequencies - Democrats", "_____no_output_____" ] ], [ [ "## Split speeches by white space \nd_split = all_speeches_d.split('\\n\\n')", "_____no_output_____" ], [ "word_freq_d = Counter()\nbigram_freq_d = Counter()\ntrigram_freq_d = Counter()\n\nfor speech in d_split: \n d_replaced = speech.replace(': ', ' ').replace(',', '').replace('.', '')\n d_lower = d_replaced.lower()\n tokens_d = tokenize(d_lower)\n word_freq_d.update(tokens_d)\n bigrams_d = get_bigram_tokens(tokens_d)\n bigram_freq_d.update(bigrams_d)\n trigrams_d = get_ngram_tokens(tokens_d, n = 3)\n trigram_freq_d.update(trigrams_d)\n \nword_freq_d.most_common(30)", "_____no_output_____" ], [ "bigram_freq_d.most_common(30)", "_____no_output_____" ], [ "trigram_freq_d.most_common(30)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ec4fcffaa41d6ebf12e40fc74239590cc4a143b8
759,785
ipynb
Jupyter Notebook
Code/Chapter 5 - First-Order Methods/5.4 Nesterov - Momentum.ipynb
JuliaChem/ModernCompAlg
ef28f85d9b676f37e6ce9664ddfc7c2fd7261ee4
[ "MIT" ]
null
null
null
Code/Chapter 5 - First-Order Methods/5.4 Nesterov - Momentum.ipynb
JuliaChem/ModernCompAlg
ef28f85d9b676f37e6ce9664ddfc7c2fd7261ee4
[ "MIT" ]
null
null
null
Code/Chapter 5 - First-Order Methods/5.4 Nesterov - Momentum.ipynb
JuliaChem/ModernCompAlg
ef28f85d9b676f37e6ce9664ddfc7c2fd7261ee4
[ "MIT" ]
null
null
null
556.211567
35,552
0.748075
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ec4fd417c99d56ae20b872be1c78c92eea8bb2c2
179,108
ipynb
Jupyter Notebook
notebooks/forecasting_growth.ipynb
just4jc/prophet
208399678c37254f2668160b9dd07d2d468a1d36
[ "BSD-3-Clause" ]
1
2018-08-11T17:29:45.000Z
2018-08-11T17:29:45.000Z
notebooks/forecasting_growth.ipynb
just4jc/prophet
208399678c37254f2668160b9dd07d2d468a1d36
[ "BSD-3-Clause" ]
2
2021-05-20T22:00:40.000Z
2021-09-28T05:39:04.000Z
notebooks/forecasting_growth.ipynb
just4jc/prophet
208399678c37254f2668160b9dd07d2d468a1d36
[ "BSD-3-Clause" ]
2
2018-05-02T12:09:50.000Z
2018-05-10T10:36:09.000Z
705.149606
100,278
0.94146
[ [ [ "%load_ext rpy2.ipython\n%matplotlib inline\nfrom fbprophet import Prophet\nimport pandas as pd", "_____no_output_____" ], [ "%%R\nlibrary(prophet)", "/usr/lib/python2.7/dist-packages/rpy2/rinterface/__init__.py:186: RRuntimeWarning: Loading required package: Rcpp\n\n warnings.warn(x, RRuntimeWarning)\n" ] ], [ [ "By default, Prophet uses a linear model for its forecast. When forecasting growth, there is usually some maximum achievable point: total market size, total population size, etc. This is called the carrying capacity, and the forecast should saturate at this point.\n\nProphet allows you to make forecasts using a [logistic growth](https://en.wikipedia.org/wiki/Logistic_function) trend model, with a specified carrying capacity. We illustrate this with the log number of page visits to the [R (programming language)](https://en.wikipedia.org/wiki/R_%28programming_language%29) page on Wikipedia:", "_____no_output_____" ] ], [ [ "df = pd.read_csv('../examples/example_wp_R.csv')\nimport numpy as np\ndf['y'] = np.log(df['y'])", "_____no_output_____" ], [ "%%R\ndf <- read.csv('../examples/example_wp_R.csv')\ndf$y <- log(df$y)", "_____no_output_____" ] ], [ [ "We must specify the carrying capacity in a column `cap`. Here we will assume a particular value, but this would usually be set using data or expertise about the market size.", "_____no_output_____" ] ], [ [ "df['cap'] = 8.5", "_____no_output_____" ], [ "%%R\ndf$cap <- 8.5", "_____no_output_____" ] ], [ [ "The important things to note are that `cap` must be specified for every row in the dataframe, and that it does not have to be constant. If the market size is growing, then `cap` can be an increasing sequence.\n\nWe then fit the model as before, except pass in an additional argument to specify logistic growth:", "_____no_output_____" ] ], [ [ "m = Prophet(growth='logistic')\nm.fit(df)", "_____no_output_____" ], [ "%%R\nm <- prophet(df, growth = 'logistic')", "_____no_output_____" ] ], [ [ "We make a dataframe for future predictions as before, except we must also specify the capacity in the future. Here we keep capacity constant at the same value as in the history, and forecast 3 years into the future:", "_____no_output_____" ] ], [ [ "future = m.make_future_dataframe(periods=1826)\nfuture['cap'] = 8.5\nfcst = m.predict(future)\nm.plot(fcst);", "_____no_output_____" ], [ "%%R -w 10 -h 6 -u in\nfuture <- make_future_dataframe(m, periods = 1826)\nfuture$cap <- 8.5\nfcst <- predict(m, future)\nplot(m, fcst);", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ec4fdc91ec8b8215ba5167573cdeef5b7abf4857
9,822
ipynb
Jupyter Notebook
notebooks/08b-Using_the_quick_deployment_app_-_remote_part.ipynb
garstka/idact
b9c8405c94db362c4a51d6bfdf418b14f06f0da1
[ "MIT" ]
5
2018-12-06T15:40:34.000Z
2019-06-19T11:22:58.000Z
notebooks/08b-Using_the_quick_deployment_app_-_remote_part.ipynb
garstka/idact
b9c8405c94db362c4a51d6bfdf418b14f06f0da1
[ "MIT" ]
9
2018-12-06T16:35:26.000Z
2019-04-28T19:01:40.000Z
notebooks/08b-Using_the_quick_deployment_app_-_remote_part.ipynb
garstka/idact
b9c8405c94db362c4a51d6bfdf418b14f06f0da1
[ "MIT" ]
2
2019-04-28T19:18:58.000Z
2019-06-17T06:56:28.000Z
23.441527
265
0.536449
[ [ [ "# 08b. Using the quick deployment app - remote part", "_____no_output_____" ], [ "## Overview", "_____no_output_____" ], [ "This notebook is intended to be executed on the cluster as a continuation of notebook\n\n```\n08a-Using_the_quick_deployment_app_-_local_part.ipynb\n```.", "_____no_output_____" ], [ "## Import idact", "_____no_output_____" ], [ "We will use a wildcard import for convenience:", "_____no_output_____" ] ], [ [ "from idact import *", "_____no_output_____" ] ], [ [ "## Load the cluster", "_____no_output_____" ], [ "Let's load the environment and the cluster. Make sure to use your cluster name.", "_____no_output_____" ] ], [ [ "load_environment()\ncluster = show_cluster(\"hpc\")\ncluster", "_____no_output_____" ], [ "node = cluster.get_access_node()\nnode", "_____no_output_____" ], [ "node.connect()", "_____no_output_____" ] ], [ [ "## Pull deployments", "_____no_output_____" ], [ "You can now access the deployments `idact-notebook` created for you:", "_____no_output_____" ] ], [ [ "deployments = cluster.pull_deployments()\ndeployments", "2018-11-24 21:34:48 INFO: Pulling deployments.\n2018-11-24 21:34:50 INFO: Creating the ssh directory.\n2018-11-24 21:35:01 INFO: Pulled allocation deployment: Nodes([Node(p0613:44654, 2018-11-24 20:53:36.191631+00:00),Node(p0629:34396, 2018-11-24 20:53:36.191631+00:00),Node(p0630:41649, 2018-11-24 20:53:36.191631+00:00)], SlurmAllocation(job_id=14337694))\n2018-11-24 21:35:01 INFO: Pulled Jupyter deployment: JupyterDeployment(8080 -> Node(p0613:44654, 2018-11-24 20:53:36.191631+00:00)\n" ] ], [ [ "There is the nodes deployment:", "_____no_output_____" ] ], [ [ "nodes = deployments.nodes[-1]\nnodes", "_____no_output_____" ] ], [ [ "And the Jupyter deployment this notebook is running on:", "_____no_output_____" ] ], [ [ "nb = deployments.jupyter_deployments[-1]\nnb", "_____no_output_____" ] ], [ [ "## Deploy Dask", "_____no_output_____" ], [ "You can deploy Dask from the remote notebook, though you won't be able to browse the dashboards this way:", "_____no_output_____" ] ], [ [ "dd = deploy_dask(nodes)\ndd", "2018-11-24 21:35:04 INFO: Deploying Dask on 3 nodes.\n2018-11-24 21:35:04 INFO: Connecting to p0613:44654 (1/3).\n2018-11-24 21:35:06 INFO: Connecting to p0629:34396 (2/3).\n2018-11-24 21:35:07 INFO: Connecting to p0630:41649 (3/3).\n2018-11-24 21:35:08 INFO: Deploying scheduler on the first node: p0613.\n2018-11-24 21:35:20 INFO: Desired local tunnel port 35898 is taken. Binding to random port instead.\n2018-11-24 21:35:21 INFO: Desired local tunnel port 34102 is taken. Binding to random port instead.\n2018-11-24 21:35:28 INFO: Checking scheduler connectivity from p0613 (1/3).\n2018-11-24 21:35:28 INFO: Checking scheduler connectivity from p0629 (2/3).\n2018-11-24 21:35:28 INFO: Checking scheduler connectivity from p0630 (3/3).\n2018-11-24 21:35:28 INFO: Deploying workers.\n2018-11-24 21:35:28 INFO: Deploying worker 1/3.\n2018-11-24 21:35:40 INFO: Desired local tunnel port 50383 is taken. Binding to random port instead.\n2018-11-24 21:35:41 INFO: Deploying worker 2/3.\n2018-11-24 21:35:49 INFO: Deploying worker 3/3.\n2018-11-24 21:36:03 INFO: Validating worker 1/3.\n2018-11-24 21:36:03 INFO: Validating worker 2/3.\n2018-11-24 21:36:03 INFO: Validating worker 3/3.\n" ], [ "client = dd.get_client()\nclient", "_____no_output_____" ], [ "x = client.submit(lambda value: value + 1, 10)", "_____no_output_____" ], [ "x.result() == 11", "_____no_output_____" ], [ "client.close()", "_____no_output_____" ] ], [ [ "## Cancel the allocation (recommended)", "_____no_output_____" ], [ "After you're done, you should cancel the nodes from the remote notebook, in order to avoid being charged for additional resources.\n\nYou will lose the connection to this notebook straight away, so make sure to save beforehand.", "_____no_output_____" ] ], [ [ "nodes.cancel()", "_____no_output_____" ] ], [ [ "## Continue with the local notebook", "_____no_output_____" ], [ "Perform the rest of instructions in the local notebook.", "_____no_output_____" ] ] ]
[ "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", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ec4fe0575e0a3f2697cdf90b2616fb9e1fe8b3b5
6,736
ipynb
Jupyter Notebook
docs/contents/user/tools/basic/view.ipynb
uibcdf/MolModMTs
4f6b6f671a9fa3e73008d1e9c48686d5f20a6573
[ "MIT" ]
null
null
null
docs/contents/user/tools/basic/view.ipynb
uibcdf/MolModMTs
4f6b6f671a9fa3e73008d1e9c48686d5f20a6573
[ "MIT" ]
null
null
null
docs/contents/user/tools/basic/view.ipynb
uibcdf/MolModMTs
4f6b6f671a9fa3e73008d1e9c48686d5f20a6573
[ "MIT" ]
null
null
null
24.948148
95
0.509947
[ [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "import molsysmt as msm\nimport nglview as nv\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "# View", "_____no_output_____" ] ], [ [ "molsys = msm.convert('pdb_id:181L', to_form='molsysmt.MolSys')", "_____no_output_____" ], [ "view = msm.view(molsys, standardize=True)\nview", "_____no_output_____" ], [ "msm.info(view)", "_____no_output_____" ], [ "molsys = msm.convert('pdb_id:181L', to_form='nglview.NGLWidget')\nmsm.get_form(molsys)", "_____no_output_____" ], [ "molsys = msm.convert('pdb_id:181L', to_form='molsysmt.MolSys')\nmolsys = msm.convert(molsys, to_form='nglview.NGLWidget')\nmsm.get_form(molsys)", "_____no_output_____" ], [ "molsys_A = msm.build.build_peptide('AceAlaNME')\nmolsys_B = msm.structure.translate(molsys_A, translation='[0.5, 0.0, 0.0] nm')", "_____no_output_____" ], [ "view = msm.view([molsys_A, molsys_B], standardize=True)\nview", "_____no_output_____" ], [ "view = msm.view([molsys_A, molsys_B], concatenate_structures=True, standardize=True)\nview", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec4ff57998dc2d7f9618620394843d092e5441dd
329,908
ipynb
Jupyter Notebook
jupyter_notebooks/practice4_fe1.ipynb
tejasbhagwat/geoinformatics_hm
17f4a3975c87765422263576946f55a448c7592e
[ "MIT" ]
null
null
null
jupyter_notebooks/practice4_fe1.ipynb
tejasbhagwat/geoinformatics_hm
17f4a3975c87765422263576946f55a448c7592e
[ "MIT" ]
null
null
null
jupyter_notebooks/practice4_fe1.ipynb
tejasbhagwat/geoinformatics_hm
17f4a3975c87765422263576946f55a448c7592e
[ "MIT" ]
null
null
null
416.025221
163,916
0.938483
[ [ [ "<img align=\"right\" width=\"240\" height=\"240\" src=\"img/HS_Mu__nchen_Logo.png\"/>", "_____no_output_____" ], [ "<style>\np.small {\n line-height: 1;\n}\n</style>\n<body>\n \n<p class=\"small\"> <b>Geoinformatics | Course Remote Sensing (1)</b><br> <small>Schmitt | Ulloa</small><br> <small>Summer Semester 2020</small><br></p>", "_____no_output_____" ], [ "<h1>Practice 4: Unsupervised classification</h1>", "_____no_output_____" ], [ "<h2>Overview</h2>", "_____no_output_____" ], [ "<p class=\"main\"><b>Objectives:</b> Perform an unsupervised classification of your AOI, on a multiband image data using Python you need GDAL, Numpy and Sklearn.</p>\n\n<p><b>Data:</b> For this practice, use the following files: </p>\n\n<p class=\"data\"></p>\n<ul>\n <li> Raster file: GeoTIFF (S2A_L2A_T32UPU_rstck_id1.tif, S2A_L2A_T32UPU_rstck_id2.tif, S2A_L2A_T32UPU_rstck_id3.tif)</li> \n</ul>\n\n<p><b>Tasks:</b> load your rasterfile in Python and perform an unsupervised classification. Export the classification file and visualize it.</p> \n", "_____no_output_____" ], [ "<h2>Procedure</h2>", "_____no_output_____" ], [ "<p>To do our unsupervised classification we are going to use the Scikit-Learn library.\nIt is a very commonly used python library for machine learning which includes all the classification algorithms presented in the lecture. For further information see <a href= \"https://en.wikipedia.org/wiki/Scikit-learn\nhttps://scikit-learn.org/stable/ \">this site.</a></p>", "_____no_output_____" ], [ "<h4>Load and visualize raster</h4>", "_____no_output_____" ] ], [ [ "from sklearn import cluster", "_____no_output_____" ] ], [ [ "If you wish to see the data you will also need Matplotlib", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "from matplotlib.patches import Patch\nfrom matplotlib.colors import ListedColormap\nimport matplotlib.colors as colors", "_____no_output_____" ] ], [ [ "These are the libraries we are going to use to read and write our imagery and prediction rasters", "_____no_output_____" ] ], [ [ "#from osgeo import gdal, gdal_array\nimport os\nimport rasterio as rio\nimport numpy as np\nfrom rasterio.plot import show\nfrom rasterio.plot import plotting_extent", "_____no_output_____" ] ], [ [ "<p>1. Read your rasterstack using the function <code>open</code> from the package rio(rasterio). Assign your raster to an object called \"s2_stack\". Remeber to specify first the path where your data is located. Store your path in an object called \"folder_src\".</p>", "_____no_output_____" ] ], [ [ "# Specify the path\n\nfolder_src = \n\n# Read in raster image \n\ns2_stack = ", "_____no_output_____" ] ], [ [ "<p>To check that you loaded your raster, you can print some of the properties of that raster. I'll check here the number of bands.</p>", "_____no_output_____" ] ], [ [ "# number of bands\ns2_stack.count", "_____no_output_____" ] ], [ [ "<p>2. Apply the necessary functions (see Practice 1) to extract the name, dimensions and resolution of your raster.</p>", "_____no_output_____" ], [ "<h4>Plot a single band: NIR</h4>\n<p>Let's make a visualization of one band from your RasterStack, in this case the NIR band</p>", "_____no_output_____" ] ], [ [ "#Plot Band NIR\nfig,ax = plt.subplots(figsize=(20,20))\nnirNpArray = s2_stack.read(4)\nax.set_title(\"NIR-Band\")\n# Be careful Numpy Array indexes start at zero!\n#This command equals the one we used before to visualize band 4 using the show() function from rasterio\nplot=ax.imshow(nirNpArray, cmap='magma')\nplt.colorbar(plot,shrink=0.6)\nplt.show()", "_____no_output_____" ] ], [ [ "<p>3. Change the settings of the previous function with the following values:\n <ul>\n <li>figsize=(5,5)</li>\n <li>plt.colorbar(plot,shrink=1)</li></p>", "_____no_output_____" ], [ "<p>4. Explain the purpose of the parameters <code>figsize</code> and <code>shrink</code></p>", "_____no_output_____" ], [ "<p>5. <code>cmap</code> is a parameter that defines some defined color scales for maps in the matplotlib package. Using the information on the next image, choose another color scale and change the color of your map.</p>\n\n<img src=\"img/img_p4_cmap_colormap.png\" width=\"700\"/>", "_____no_output_____" ], [ "<p>6. Using the previous line code, plot the bands BLUE and GREEN. Remember to update the title with the command <code>ax.set_title(\"your title\")</code> </p>", "_____no_output_____" ], [ "<p>7. Now we want to take a look at the structure of the RasterStack with a function you will use afterwards. Use the function <code>shape</code> to extract the information of the number of columns and rows of your rasterstack (hint: name_of_your_raster.shape)</p>", "_____no_output_____" ], [ "<p>8. Please explain the meaning of the values from the result of the function <code>shape</code>. Which other functions so far in this practice have returned the same values?</p>", "_____no_output_____" ], [ "<p>Now we will use the previous function and store the NIR band in an object called \"band\". This object will be turned into a vector for the classification purposes in the next step</p>", "_____no_output_____" ] ], [ [ "# Create an object called \"band\" that stores the 4th value of your rasterstack = NIR band\nband = s2_stack.read(4)\nband.shape", "_____no_output_____" ] ], [ [ "<h4>Perform unsupervised classification with k-means algorithm on NIR band</h4>", "_____no_output_____" ] ], [ [ "#Make linear vector for Sci-Kit Learn\nX = band.reshape((-1,1))\nprint ('linear Vector:',X.shape)\n\n# Lets use our classification Algorithm with 8 clusters.\n# The kmeans classification of the NIR band will be stored in the object \"kmeans_nir\"\nk_means = cluster.KMeans(n_clusters=8)\nk_means.fit(X)\n# Lets write and reshape our results into the original image dimensions\nX_NIR = k_means.labels_\nX_NIR = X_NIR.reshape(band.shape)\nprint ('reshaped vector:',X_NIR.shape)", "linear Vector: (7144, 1)\nreshaped vector: (76, 94)\n" ], [ "#Lets plot the Results\nfig,ax = plt.subplots(figsize=(20,20))\nax.set_title(\"K-Means Classification Result (one band: NIR)\")\nplot=ax.imshow(X_NIR, cmap=plt.cm.get_cmap('Set3', 8))\n#plot.clim(-0.5, 2.5)\nplt.colorbar(plot, ticks=[0, 1, 2, 3, 4, 5, 6, 7],shrink=0.6)\n\nplt.show()", "_____no_output_____" ] ], [ [ "<p>9. Run again the unsupervised classification. This time use 5 clusters instead of 8. Plot your results \n (hint: modify and adapt \n <code>k_means = cluster.KMeans(n_clusters=8); \n plot=ax.imshow(X_NIR, cmap=plt.cm.get_cmap('Set3', 8)); \n plt.colorbar(plot, ticks=[0, 1, 2, 3, 4, 5, 6, 7],shrink=0.6)</code>)</p>", "_____no_output_____" ], [ "<p>10. Which differences can you see among the unsupervised classification with 8 clusters vs 5 clusters? What does the clusters mean?</p>", "_____no_output_____" ], [ "<p>11. Repeat the previous procedure with 2 clusters. How accurate is the classification?</p>", "_____no_output_____" ], [ "<p>12. Based on the previous plot with 2 clusters, can you properly classify the raster band? In other words, are all landclasses represented in the classification output?</p>", "_____no_output_____" ], [ "<p>13. Based on the previous plot with 2 clusters, which is the minimum of clusters to choose in order to address all landclasses from your raster band?</p>", "_____no_output_____" ], [ "<h4>Perform unsupervised classification with k-means algorithm on the whole Rasterstack (4 bands)</h4>\n\n<p>Now you will apply everything you learned about kmeans classification on a RasterStack. Previously you did this for only one band: the NIR band. The procedure is similar, instead of 1 band, you will use now 4.</p>", "_____no_output_____" ] ], [ [ "# First we have to write all 4 bands \nstack = s2_stack.read()\nprint('Rasterio read multiband image shape equals',stack.shape)\ns2_stack.meta[\"dtype\"]\n\n# Be careful Numpy Array indexes start at zero!\nstack= np.zeros([stack.shape[1],stack.shape[2],stack.shape[0]],s2_stack.meta[\"dtype\"])\nprint(\"Our desired format is\",stack.shape)", "Rasterio read multiband image shape equals (4, 76, 94)\nOur desired format is (76, 94, 4)\n" ], [ "for b in range(stack.shape[2]):\n # Let's print the band indexes\n # Be careful Numpy Array indexes start at zero!\n print(b)\n stack[:, :, b] = s2_stack.read(b+1)", "0\n1\n2\n3\n" ] ], [ [ "<p>14. What does (4, 76, 94) mean? Hint: see question 8</p>", "_____no_output_____" ], [ "<p>To help you visualize all the bands that will be classified, you can use the command <code>plt.imshow(stack[:,:,0], cmap='')</code></p>", "_____no_output_____" ], [ "<p>15. Adapt the following code to write the correct labels in the x,y axis and the title depending on the case.</p>", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(2,2, figsize=(20,15), sharex=True, sharey=True)\n# Be careful Numpy Array indexes start at zero!\n\nplt.sca(axes[0,0])\nplt.imshow(stack[:,:,0], cmap='Blues')\nplt.colorbar(shrink=0.9)\nplt.title('Blue Band')\nplt.xlabel('Column number')\nplt.ylabel('Row number')\n\nplt.sca(axes[0,1])\nplt.imshow(stack[:,:,1], cmap='Greens')\nplt.colorbar(shrink=0.9)\nplt.title('')\nplt.xlabel('')\nplt.ylabel('')\n\nplt.sca(axes[1,0])\nplt.imshow(stack[:,:,2], cmap='Reds')\nplt.colorbar(shrink=0.9)\nplt.title('')\nplt.xlabel('')\nplt.ylabel('')\n\n#This command equals the one we used before to visualize band 4 using the show() function from rasterio\nplt.sca(axes[1,1])\nplt.imshow(stack[:,:,3], cmap='Purples')\nplt.colorbar(shrink=0.9)\nplt.title('')\nplt.xlabel('')\nplt.ylabel('')", "_____no_output_____" ] ], [ [ "<p>Now starts the classification code.</p>", "_____no_output_____" ] ], [ [ "# Now lets reshape our stack into 4 linear vectors like the one we had before\n# First we are going to calculate the dimnesions\nnew_shape = (stack.shape[0] * stack.shape[1], stack.shape[2])\nprint('The new dimensions are',new_shape)", "The new dimensions are (7144, 4)\n" ], [ "# Secondly we can use the calculated shape\nX = stack[:, :, :4].reshape(new_shape)", "_____no_output_____" ], [ "#Now we can use k_means like we did before\nk_means = cluster.KMeans(n_clusters=8)\nk_means.fit(X)\n\nX_cluster = k_means.labels_\n# and reshape it\nX_cluster = X_cluster.reshape(stack[:, :, 0].shape)", "_____no_output_____" ], [ "#Now lets plot our multiband classification together with the classfication if the NIR-Band\nfig, axes = plt.subplots(1,2, figsize=(20, 20), sharex=True, sharey=True)\n\nplt.sca(axes[0])\nplt.imshow(X_NIR, cmap=plt.cm.get_cmap('Set3', 8))\nplt.colorbar(ticks=[0, 1, 2, 3, 4, 5, 6, 7],shrink=0.3)\nplt.title(\"K-Means Classification Result (one band: NIR)\")\nplt.xlabel('Column number')\nplt.ylabel('Row number')\n\nplt.sca(axes[1])\nplt.imshow(X_cluster, cmap=plt.cm.get_cmap('Set3', 8))\nplt.colorbar(ticks=[0, 1, 2, 3, 4, 5, 6, 7],shrink=0.3)\nplt.title(\"K-Means Classification Result (multi-band)\")\nplt.xlabel('Column number')\nplt.ylabel('Row number')\n", "_____no_output_____" ] ], [ [ "<p>16. Repeat the unsupervised (kmeans) classification of the Rasterstack with the right number of clusters based on the landclasses that you recognize (hint: see questions 9, 11).</p>", "_____no_output_____" ], [ "NOTE: for more information about the color scales, visit: https://matplotlib.org/tutorials/colors/colormaps.html\n ", "_____no_output_____" ], [ "<div style=\"text-align: right\"> <small>This tutorial was prepared with the support from Gabriel Cevallos. May 2020</small> </div>", "_____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", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
ec500f09869bf6dd7a0e368d698f31a7a517084d
154,745
ipynb
Jupyter Notebook
nbs/tutorial_train_and_pred.ipynb
nicoelbert/deepflash2
dd8c03064c57fb22f7712f0879f0243ca02a8f26
[ "Apache-2.0" ]
null
null
null
nbs/tutorial_train_and_pred.ipynb
nicoelbert/deepflash2
dd8c03064c57fb22f7712f0879f0243ca02a8f26
[ "Apache-2.0" ]
null
null
null
nbs/tutorial_train_and_pred.ipynb
nicoelbert/deepflash2
dd8c03064c57fb22f7712f0879f0243ca02a8f26
[ "Apache-2.0" ]
null
null
null
385.897756
142,626
0.934544
[ [ [ "<a href=\"https://colab.research.google.com/github/nicoelbert/deepflash2/blob/master/nbs/tutorial_train_and_pred.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# deepflash2 - Train and Predict Tutorial\nThis notebook is optmizied to be executed on Google Colab (https://colab.research.google.com). It reproduces the results of the deepflash2 [paper](https://arxiv.org/abs/2111.06693) for semantic and instance segmentation.\n\n\n* Please read the instructions carefully.\n* Press the the *play* butten to execute the cells. It will show up between \\[ \\] on the left side of the code cells. \n* Run the cells consecutively.\n\n*References*:\n\nGriebel, M., Segebarth, D., Stein, N., Schukraft, N., Tovote, P., Blum, R., & Flath, C. M. (2021). Deep-learning in the bioimaging wild: Handling ambiguous data with deepflash2. arXiv preprint arXiv:2111.06693.", "_____no_output_____" ], [ "## Setup\nIn this section, you will set up the training environment, install all dependencies and connect to the drive with the prepared datasets.", "_____no_output_____" ] ], [ [ "!pip install deepflash2 --q\n\n# Imports\nimport numpy as np\nfrom deepflash2.all import *\nfrom pathlib import Path\n", "_____no_output_____" ] ], [ [ "### Settings\n\n", "_____no_output_____" ], [ "Prior to Training the dataset needs to be selected. If you don't run the notebook in Colab, the `OUTPUT_PATH`and `MODEL_PATH` need to be adjusted to point on existing directorys.", "_____no_output_____" ] ], [ [ "# Connect to drive\ntry:\n from google.colab import drive\n drive.mount('/gdrive')\nexcept:\n print('Google Drive is not available.')\n\nSEED = 0 # We used seeds [0,1,2] in our experiemnts\nOUTPUT_PATH = Path(\"/content/predictions\") # Save predictions here\nMODEL_PATH = Path(\"/content/models\") # Save models here\nTRAINED_MODEL_PATH= Path('/gdrive/MyDrive/deepflash2-paper/models/')\n\n# deepflash2 config class\ncfg = Config(random_state=SEED)", "_____no_output_____" ] ], [ [ "For training, either the data from a prepared example dataset or own datasets can be used. These can come from a publicly available `.zip` file, or a specified directory in your Google Drive(for colab execution) or on your machine(for local execution).", "_____no_output_____" ] ], [ [ "DATASOURCE = 'Example Data' #@param [\"Example Data\", \"ZIP File\", \"Own Directory\"]\n", "_____no_output_____" ] ], [ [ "### Example Data", "_____no_output_____" ], [ "Example data and trained models are available on [Google Drive](https://drive.google.com/drive/folders/1r9AqP9qW9JThbMIvT0jhoA5mPxWEeIjs?usp=sharing). To use the data in Google Colab, create a [**shortcut**](https://support.google.com/drive/answer/9700156?hl=en&co=GENIE.Platform%3DDesktop) of the data folder in your personal Google Drive. This shortcut only has to be created once and doesn't affect your personal Google Drive storage.", "_____no_output_____" ], [ "\nChoose from the perpared dataset from `PV_in_HC`, `cFOS_in_HC`, `mScarlet_in_PAG`, `YFP_in_CTX`, `GFAP_in_HC`. Choose the one most similar to yours. A brief describtion of the datasets can be found below. \n", "_____no_output_____" ] ], [ [ "if DATASOURCE == 'Example Data':\n DATASET = 'cFOS_in_HC' #@param [\"PV_in_HC\", \"cFOS_in_HC\", \"mScarlet_in_PAG\", \"YFP_in_CTX\", \"GFAP_in_HC\"]\n DATA_PATH = Path('/gdrive/MyDrive/deepflash2-paper/data')\n mask_directory = 'masks_STAPLE'\n", "_____no_output_____" ] ], [ [ "![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABawAAAHoCAYAAACl2KhUAAAMbGlDQ1BJQ0MgUHJvZmlsZQAASImVVwdYU8kWnluSkJDQAhGQEnoTRGoAKSG0ANK7jZAEEkqMCUHFXhYVXLuIYkVXRRQsKyB27Mqi2PtiQUVZF3WxofImJKDrvvK9831z758zZ/5T7kzuPQBof+BJpfmoDgAFkkJZQngwMy09g0l6CjCAAD1AA948vlzKjouLBlAG7n+XdzegLZSrzkquf87/V9ETCOV8AJAxEGcJ5PwCiI8DgK/jS2WFABCVeqtJhVIlngWxvgwGCPFKJc5R4R1KnKXCh/ttkhI4EF8GQIPK48lyANC6B/XMIn4O5NH6DLGrRCCWAKA9DOIAvogngFgZ+7CCgglKXAGxPbSXQgzjAays7zhz/safNcjP4+UMYlVe/aIRIpZL83lT/s/S/G8pyFcM+LCFgyqSRSQo84c1vJU3IUqJqRB3SbJiYpW1hviDWKCqOwAoRaSISFbZoyZ8OQfWDzAgdhXwQqIgNoE4TJIfE63WZ2WLw7gQw92CThYXcpMgNoR4gVAemqi22SSbkKD2hdZnyzhstf4cT9bvV+nrgSIvma3mfyMSctX8mFaxKCkVYgrE1kXilBiItSB2keclRqltRhaLODEDNjJFgjJ+a4gThJLwYBU/VpQtC0tQ25cWyAfyxTaJxNwYNd5XKEqKUNUHO8Xn9ccPc8EuCyXs5AEeoTwteiAXgTAkVJU79lwoSU5U83yQFgYnqNbiFGl+nNoetxTmhyv1lhB7yIsS1WvxlEK4OVX8eLa0MC5JFSdenMuLjFPFgy8F0YADQgATKODIAhNALhC3djV0wV+qmTDAAzKQA4TAWa0ZWJHaPyOB10RQDP6ASAjkg+uC+2eFoAjqvwxqVVdnkN0/W9S/Ig88hbgARIF8+FvRv0oy6C0FPIEa8T+88+Dgw3jz4VDO/3v9gPabhg010WqNYsAjU3vAkhhKDCFGEMOIDrgxHoD74dHwGgSHG87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OP9X2ZXkL91IDsGAAAAimVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA5KGAAcAAAASAAAAeKACAAQAAAABAAAFrKADAAQAAAABAAAB6AAAAABBU0NJSQAAAFNjcmVlbnNob3QyAwfTAAAACXBIWXMAABYlAAAWJQFJUiTwAAAB12lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj40ODg8L2V4aWY6UGl4ZWxZRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFhEaW1lbnNpb24+MTQ1MjwvZXhpZjpQaXhlbFhEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlVzZXJDb21tZW50PlNjcmVlbnNob3Q8L2V4aWY6VXNlckNvbW1lbnQ+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgoIHx6QAAAAHGlET1QAAAACAAAAAAAAAPQAAAAoAAAA9AAAAPQAAMlednjhvgAAQABJREFUeAHsnQfcLcP5x0fv5WpB1Ctq9ATRid5F9M7VCUISf50geu9BtIjeXT16i96iXKILgiBc/dr/fOd61px9d09/z91z3t98Pu97ztmdnZ39TtnZ3zz7zGiJD05BBERABERABERABERABERABERABERABERABERABERABEYxgdEkWI/iEtDpRUAEREAEREAEREAEREAEREAEREAEREAEREAEREAEAgEJ1qoIIiACIiACIiACIiACIiACIiACIiACIiACIiACIiACpSAgwboUxaBMiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAISLBWHRABERABERABERABERABERABERABERABERABERABESgFAQnWpSgGZUIEREAEREAEREAEREAEREAEREAEREAEREAEREAERECCteqACIiACIiACIiACIiACIiACIiACIiACIiACIiACIhAKQhIsC5FMSgTIiACIiACIiACIiACIiACIiACIiACIiACIiACIiACEqxVB0RABERABERABERABERABERABERABERABERABERABEpBQIJ1KYpBmRABERABERABERABERABERABERABERABERABERABEZBgrTogAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiJQCgISrEtRDMqECIiACIiACIiACIiACIiACIiACIiACIiACIiACIiABGvVAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQgVIQkGBdimJQJkRABERABERABERABERABERABERABERABERABERABCRYqw6IgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiUgoAE61IUgzIhAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgwVp1QAREQAREQAREQAREQAREQAREQAREQAREQAREQAREoBQEJFiXohiUCREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQnWqgMiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAKlICDBuhTFoEyIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhIsFYdEAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKAUBCdalKAZlQgREQAREQAREQAREQAREQAREQAREQAREQAREQAREQIK16oAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiEApCEiwLkUxKBMiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAISrFUHREAEREAEREAEREAEREAEREAEREAEREAEREAEREAESkFAgnUpikGZEAEREAEREAEREAEREAEREAEREAEREAEREAEREAERkGCtOiACIiACIiACIiACIiACIiACIiACIiACIiACIiACIlAKAhKsS1EMyoQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAEa9UBERABERABERABERABERABERABERABERABERABERCBUhCQYF2KYlAmREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEJFirDoiACIiACIiACIiACIiACIiACIiACIiACIiACIiACJSCgATrUhSDMiECIiACIiACIiACIiACIiACIiACIiACIiACIiACIiDBWnVABERABERABERABERABERABERABERABERABERABESgFAQkWJeiGJQJERABERABERABERABERABERABERABERABERABERABCdaqAyIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAqUgIMG6FMWgTIiACIiACIiACIiACIiACIiACIiACIiACIiACIiACEiwVh0QAREQAREQAREQAREQAREQAREQAREQAREQAREQAREoBQEJ1qUoBmVCBERABERABLqDwLfffuv++9//ug8//NCNO+64buaZZ24q499995376KOPQjqff/65m3/++ZtKZ6AfNGLECHffffe5p556yr399tvus88+c9NPP72bY4453CqrrOLGGWecFBHlduihh7ojjjjCjT322Ol2fRGBXiGQJIm75ZZb3COPPOLee+89N+ecc7rNN9/cTTTRRG2/RPot+sEPPvjAzTrrrG7CCSds+zmUoAiIgAiIgAiIgAgMVAISrAdqyeu6RUAEREAESk1g6623dp988knb8rjkkku63Xffven07r33XrfmmmuGPCEKEWaffXb3wgsvNJQmItJPf/rTIFYjWlv45ptv3Jhjjmk/S/H54osvuk8//dT9/Oc/L0V+4kwg9v/pT39y559/vnv//ffDLgSzqaee2r322muOiYUpp5zSHXTQQW6nnXYK+zfYYAN32WWXBSFvqqmmipPT9w4SQOi85pprwsQC7VKhPQRor/SbDzzwgFtggQXceOONF74zqfboo4+6ySabrC0n2nnnnd25557rvvjiizQ9JoH22muv9Le+iIAIiIAIiIAIiIAItEZAgnVr/HS0CIiACIiACPQLASxgEXEJCLmILj/60Y+CVfPXX38dLAhjwWS66aZzs802W4jP9jfeeCNY3IYN/t9KK63kbr75ZvvZ8OfLL7/sTj31VPfPf/7T3XbbbeF4rAqHDRvWUFpc0x//+Ef3/PPPB9EOC2FCmQRrBPkzzzzT/fa3vw2iYqPX2BCQJiJffPHFbpdddgmW7mOMMYbbcsst3bbbbusWWmghN/roowch7bHHHnNHH320u+6669xWW23lll122WBpyumYNJBg3QT4NhzCJA3W7y+99FJI7YILLnCbbbZZG1Ie2EkwsfSzn/0scN1iiy3cOeec49Zee213ww03BDD8RsxuR8CC+9prr3U33XRTmBwiTSaP9t5773YkrzREQAREQAREQAREQAQ8AQnWqgYiIAIiIAIiUDICH3/8sRs0aFDIFWIWYgiCdBwuvPDCVIBkO+4gpp122jiKe+ihh4LoyueCCy7oEDHbEXDfgQuKZgTr+Pwbb7yxQ3wljErB+n//+5975pln3FtvveUef/xxd8kllwTBn3zNNNNM7tVXX+VrKQIW0wcffHDIC5MYl156aRCqizJ3yimnuN/97nfuq6++SqNIsE5RdPzLk08+Gax/7cRYvzMRpNAaAcRirJwnmWSSICJPOumkbq211goTNqSMcL3aaqu1dpLM0U888UToV9ncCcH6D3/4Q7iGpZdeOpOT3vk5EK6xd0pLVyICIiACIiAC/UtAgnX/8lXqIiACIiACItAwASx6cbex4oorBn+seQlg3bfqqqumuxAk8/wSDx8+PIjduIt488030/itfFl99dXd0KFDWxasESewAiaMSsH6nnvucSYCTTPNNIHrX/7yF4eldZkEa8R9RH4CExi4aSF/tcKxxx4bRGuLJ8HaSHT+k/Y4yyyzBCt3zn7llVe6ddZZp/MZ6bEzLrHEEu7+++9366+/fpjE4fLeeecdd9ZZZwWL9l//+teOtxHaGf7zn/+Et15IsxOCNSI8bXnIkCHtvIxSpTUQrrFUwJUZERABERABESgxAQnWJS4cZU0EREAERGBgEkB4QYC58cYbw8J5eRTqFaw5FgtbLG2//PLLvKQa3rbGGmsEi8VWLazx+XrUUUeF849KwZoMYGGNdSYLFo422mhu4oknDv6ryyJYI47h+5sF3gi33367W2655cL3Wv9wu7LooosGNzLElWBdi1j/7udtCFy18KYC5aLQOoEJJpjA4Rt8n332cYcddljrCdaRAm0RP/GE/has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rHdceTD0wgFgWbMHnggQcqotR7jSZYszBqUUCkhhdv9yiIgAiIgAiIgAh0LwEJ1t1bdsq5CIiACIjAACZw8cUXpyIGD+f4p64WWFzNRI+f/OQnFeIdx3333XdB9LU4WHESzjnnnAQ/1HEwwZq46623Xp+0iPvwww8nE088cTjn5ptvHh+efsfvqJ0P6+5sOPHEE8N+hFL8lOYF89farF/nvDSxPseFCXlD9IBNrRAzwTKzPwKuQXbccceUGRbPr776atVT4aMYoXr88cdPXnnlldy4f/zjH0OaxGFhxmxgoU4Twlis85133slGSRC0rSyruSyxODfffHOfNNhw3XXXpekUWVHGVs2kd9999/VJCzHffNris/m5556riMOikZaXvIUK77777nQ/8WxRT1yzsCCjhTjen//8Z9tc9ZMF5+zce+65Z0VcEwzxqV1kHbr88suHyYPHH388Pfatt95KZphhhpAuEwp5x+JCxCYdilwCDRkyJM1bUd066qij0jitTs60o+7htsh4Zn2rp4Aa+MKipExwkCafeS6JEGXN3RHxYtHYTtWuOsb5mYjgPLGbEvop+prTTz/dTpm0es5m6x/uY6iz5JF+KW8ik4mUWWaZJSyWmGb4+y/1XqMJ1pwnr92SHP0B+/PeIMieV79FQAREQAREQATKS0CCdXnLRjkTAREQAREQgUAA8emMM85IEGcRi7CCnHrqqcNDOQ/m/GFhue+++ybHHntsEDCwls4GLKst/vbbb5/6lEZAQ1See+65w7HEYVHG4447Lpl//vmT7OJjJs7iaxffx+uvv36Cb18L11xzTfAzSjr4TI4FH8TP0047LTnkkEMSxE/LD1bUJ510UpL1iXvAAQeEOOTn4IMPTl544YVwGl7dhwMCHNtbCcaX8x966KHJkksumeaL/CH4Hn744cGytkiUNIGL+DPPPHMr2al5LOVigjp+xFkoDsEyDkwAUGcmnXTSIBI98sgj8e4+3/GFS94pTyYpEKDggoUpAin7ZppppiTrNgSBm4mFuG5hnU6ezj777ODaAutkrJKpY6TDHxaS1FUTyC+55JLwmn/sdoS8kw6TM3HICtYwuOqqq1I3N4iJc8wxRzgPgl6eqEo9G2e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rU8REAEREAEREIHuIzAaWfY3fgUREAEREAEREIEBQsC/Su68iwT3xhtvOL7PNttszltoV1y9X6TReSEp7KvYkfPDC9fOi93u2WefdV7wcl78dl7IyonZ/CaGK16Mc95yNeTZC+nOLx7ZfII9cqS3hHZeoApchg0b5rwrDOcF91Bu3vK0rvKLUcDZi04hPS8gOW9h77yVcRxllH/3FtvOT5iEfHifvs5b1IbrZrsX50Ndpk57kbauvHoRLNRfL9w6L8Q6b+XtvAVteiwcXn75ZecnJNper9OTfP+FNuStuJ0XqMMWL7w52iLl4ieBnBfVnRdQs4f1+e3dWoQy5FjaCdfkJwz6xCvThrLWPeoU/aW3IHZeyHde+A/1xL/F4PwbCM6L5RV/Xvjvg7Vddcy73gn9rLfidt7yO/S3fU72/YZmztmu+ucnt5y3+A99Ce3GT0w5L/QXZbVie7Vr5J7k/Ws7/5ZCaN9+stH5Nyqcd33k/GST8xNuzk9cVKSnHyIgAiIgAiIgAt1JQIJ1d5abci0CIiACIiACIiACA5JAnmA9IEHookVABERABERABERABESgRwlIsO7RgtVliYAIiIAIiIAIiEAvEpBg3YulqmsSAREQAREQAREQAREQgR8ISLD+gYW+iYAIiIAIiIAIiIAIlJyA9x3sFllkkZBL78/Z7bXXXiXPsbInAiIgAiIgAiIgAiIgAiLQCAEJ1o3QUlwREAEREAEREAEREIFRQuDbb791X3zxhTv++OPdgQceGPKw6qqruvPOO8/5hQDr9pE7SjKvk4qACIiACIiACIiACIiACNRNQIJ13agUUQREQAREQAREQAREYFQRWGKJJdz9999feHoWEK13YbfCRLRDBERABERABERABERABERglBOQYD3Ki0AZEAEREAEREAEREAERqEXghhtucB9//LEbd9xx3dhjj+1GG200980337gvv/zSjTfeeO5Xv/pVrSS0XwREQAREQAREQAREQAREoAsISLDugkJSFkVABERABERABERABERABERABERABERABERABERgIBCQYD0QSlnXKAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAJdQKCtgvUhhxziPvrooy64bGVRBERABERABERABERABERABERABERABERABERABAYWgemmm87tsccepb7otgrWM844o3vjjTdKfcHKnAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAgMRAILLrige+yxx0p96W0VrLfbbjv3wQcflPqClTkREAEREAEREAEREAEREAEREAEREAEREAEREAERGIgEBg8e7I455phSX3pbBetSX6kyJwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUGoCEqxLXTzKnAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAgMHAISrAdOWetKRUAEREAEREAEREAEREAEREAEREAEREAEREAERKDUBCRYl7p4lDkREAEREAEREAEREAEREAEREAEREAEREAEREAERGDgEJFgPnLLWlYqACIiACIiACIiACIiACIiACIiACIiACIiACIhAqQlIsC518ShzIiACIiACIiACIiACIiACIiACIiACIiACIiACIjBwCEiwHjhlrSsVAREQAREQAREQAREQAREQAREQAREQAREQAREQgVITkGBd6uJR5kRABERABERABERABERABERABERABERABERABERg4BCQYD1wylpXKgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAKlJiDButTFo8yJgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIwMAhIMF64JS1rlQEREAERKALCLz55pvukUceSXM6aNAgt+yyy6a/O/Hl2WefdcOGDUtPNfvss7uf/vSn6W99EQER+IHArbfe6j777LN0w2KLLeamnnrq9HcnvqjNdoKyziECIiACIiACIiACItApAhKsO0Va5xEBERABEegpAt9995378ssv3fjjj597XV999ZUbZ5xxcvdV2/jXv/7VbbbZZmmUn/3sZ+7RRx9Nf3fiy+9+9zt37LHHpqcaMmSIO/vss9Pf+lKbQJIk7osvviisH7VTGBnj22+/ddS1scceu+KQb775xo055phutNFGq9iuH8UEPv/889AmxxhjjD6Rmm2vJPSTn/zE/etf/0rTvP76693qq6+e/u7EF7XZYsqUe14/3UqZF59Ne3qVwMMPP+zoO7gntyv0V5/Urvwpnd4ioPo26sqzbOz7oz8bdXR778xlqy+jkrAE61FJX+cWAREYsAQ++OADd+GFF9Z1/VN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ff7/97Mjn73//e3fMMcek59ppp53cqaeemv7WFxEQgR8IzDrrrO7ll19ON9x6661uhRVWSH934ovabCco6xwiIAIiIAIiIAIiIAKdIiDBulOkdR4REAEREAEREAEREAEREAEREAEREAEREAEREAEREIGqBCRYV8WjnSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAp0iIMG6U6R1HhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQgaoEJFhXxaOdIiACIiACIiACIiACIiACIiACIiACIiACIiACIiACnSIgwbpTpHUeERABERABERABERABERABERABERABERABERABERCBqgQkWFfFo50iIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAKdItBWwfqTTz5x3333XafyrvOIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAjUSWCMMcZwE088cZ2xR020tgrWM844o3vjjTdGzZXorCIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAoUEFlxwQffYY48V7i/DjrYK1kOHDnWff/55Ga5LeRABERABERABERABERABERABERABERABERABERABEYgIDBo0yC2//PLRlvJ9batgXb7LU45EQAREQAREQAREQAREQAREQAREQAREQAREQAREQAS6hYAE624pKeVTBERABERABERABERABERABERABERABERABERABHqcgATrHi9gXZ4IiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIdAsBCdbdUlLKpwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj0OAEJ1j1ewLo8ERABERABERABERABERABERABERABERABERABEegWAhKsu6WklE8REAEREAEREAEREAEREAEREAEREAEREAEREAER6HECEqx7vIB1eSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQLQQkWHdLSSmfIiACIiACIiACIiACIiACIiACIiACIiACIiACItDjBCRY93gB6/JEQAREQAREQAREQAREQAREQAREQAREQAREQAREoFsISLDulpJSPkVABERABERABERABERABERABERABERABERABESgxwl0pWD98MMPuzHGGMP97Gc/6/Hi0eWJgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIwMAh0HWC9TfffOOmmWYaN84447g333zTjT766AOntEpwpUmSuBEjRrgxxxyzBLlRFkRABERABERABESg+whcfPHF7oknnnAffvih++CDD9xyyy3ndt1117ZcyNdff+3GHnvstqSlRERABERABERABESgPwhceOGF7plnngnjIMZDa665phsyZEh/nCpN8+2333ZnnXVWOv76+OOP3UUXXeQmm2yyNI6+lIdA1wnWN954o1tttdUCwTvuuMMtu+yy5aHZ4zl5/vnn3RprrOHeffddd95557l11123x69YlycCIiACIiACIiAC7Sew//77u8suu8wNGzYsJL711lu7c845p+UT/eEPf3AnnHCCW2SRRdzf//53CdctE1UCIiACIiACIiAC/UFgp512crfffrt76aWXQvI77rijO+200/rjVGmaTz/9tNtuu+3cP//5T/fZZ5+F7W+88Yabfvrp0zj6Uh4CXSdYb7bZZu6vf/1rIEhFO/PMM8tDs59ycsMNNwSL8hVWWKGfzuBcPec44IAD3CGHHBLysN5664UHrX7LUD8kjMXRfvvt54466qh+SL3cSdZTvuW+AuVOBESgGQIDud9rhpeOEYFOE/jVr37lrrnmGtcOwfqrr75yE000keNtRAIPY3PNNVenL0nnE4EBT0Dj7gFfBQTgewIah6oq1ENg1VVXdTfddJPrhGBt+Xnqqafc/PPPH35KsDYq5fvsKsH6iy++cD/60Y/cp59+GkhOPvnk7p133nFjjTVW+ci2MUdbbLGFm2mmmdzBBx/cxlQrk6rnHE8++aRbcMEFHW5BeI1im222qUyk5L9effVVN3jwYPfdd9+50UYbreS5bW/26inf9p5RqYmACJSBwEDu98rAX3kQgVoEfvvb3waL6HYI1pxrnXXWcVdffbWbeeaZg/W2XLjVKgHtF4H2E9C4u/1MlWJ3EtA4tDvLrdO5xtL69NNP76hg/cknn7hJJ500XKoE606XeP3n6yrB+oorrnCbbrqp+/nPf+7uv//+cJVDhw51zMj0cmBxydVXX71fBet6z4HPH2ZKeRDqtnD99dcHv0gDUbCut3y7rUyVXxEQgeoEBnK/V52M9opAOQjsscce7vjjj2+LhTVX9O233zped5177rnlDqQcRaxcDEACGncPwELXJecS0Dg0F4s2ZgjsvPPOwRVIJy2s//e//7lJJpkk5ESCdaZASvSzqwTrX//618G6l9cnN99884ARFyEXXHBBiZC2Nysvv/yym3XWWR3uOPrLwroT52gvleZSY7IDh/oDTbAeKOXbXK3QUSLQ2wQGar/X26Wqq+slAu0WrHuJja5FBLqRgMbd3VhqynN/EdA4tL/I9la6Eqx7qzzbeTVdI1gzA4I7kPPPP9+tssoq4TsuQvDV95///MeNO+647eRSirSwksF6/Lbbbus3wboT5ygDTBYeWnnllYPl0UASrAdK+ZahjikPIlA2AgO13ytbOSg/IlCNgATranS0TwS6i4DG3d1VXspt/xLQOLR/+fZS6hKse6k023stXSNYY0VNRX7vvffc+OOP71j0DxchBD6xvi4KV111VVh45oMPPnD84V5jo402cnfccUdY6AY3F7PMMov7xS9+4bDejv0bs++SSy4Jx3Hshx9+6Ejv448/dn/+858dztrxDzjvvPOGPOBrulrg2DvvvNP94x//CIvizDHHHCEva6yxRnpeFsu58sor3dlnnx1WeCc99q+11lpp0gsssEDwJ51u8F++/PLLcAxuUl577TU31VRTufnmm8/95je/CVbacdxGzwGrhx56KOWwxBJLhNVV4zTt+5tvvun+9re/hfjPP/+8m2666cJq9eRj6qmntmjhs5WyqUio4MeLL74YFuk85ZRTQpkRDf/bcRkPGTKkz9GU68knn+yeeeYZN3z48LBoEYteEnf00UeviM85rrvuusDm/fffdxNOOKE76aSTQtlRN3GhwuzysssuW3EcEy4sIPrYY4+FY6mDO+ywg5t44ondH/7wh1A3//vf/4b6t8EGG6THchx1A7c45JPzUT9468DqX6PlmyauLyLQYwToF2n/DzzwQFiBmgkrXtVdeumlQxt/9NFHQx8eX3Y7+7C33nrLTTnllKGNcu8hkIdLL73U3XPPPeGewqJoyy+/vKNfLQqN9kn0Lf3Z7xXlU9tFYFQSaGXMxnjkueeeC22Ssd6iiy4afCna9Zx66qmOezz7+GM8sNxyy9nuik/WV7nwwgvDWI+FDxn70O/stttuboYZZqiIW49gzfiLce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OXRRx+tsIg9e/YUNUUiOvMqOkNfYVh6kgAJkAAJkAAJkAAJkAAJkAAJkAAJkEB1EogTWFdn/sWQVz5yHjXvkqIIqeYrpWXLljJmzBhR03DFUL0aKwMF1jWGnhnXRgJqd1rUrrioiQLRZR4VIlAbu6JmZ0RtYYsup6kwLD1JgARIgARIgARIgARIgARIgARIgARIoDoJUGAtkqucB9rbuh+eKTTqviTWbNdcc43o5pW2yg8r7muzo8C6Nrc+617tBJYuXWrmO9QWkQmjdROl2DLcc889ojapzZyKbjhqpkFiA/IiCZAACZAACZAACZAACZAACZAACZAACdQAgaefflp69OhhOcMMCEwy1jaXq5zn+OOPl+HDh5t5OWhW60aconumiW5cKbqvSW3DmFZfCqzTkPACCRSWAGxP/+c//xHdUNHsWffp00d0c0qzLz5nzhx7OOkGj7LHHnsIBNe6EUBhC8TUSYAESIAESIAESIAESIAESIAESIAESCAhAZgvvfjii00T+Oeff7ZY2OMDAmvdZFHatm2bMKXyCJaLnEc3djSzH7oBpQwcOFCGDBkiOIYQm06EAmveBSRQQwRmzpwpU6dOtc0psUGl3xBTd/WVAw88UPBLRwIkQAIkQAIkQAIkQAIkQAIkQAIkQALFRAAbUT///POy4oorSr169axo2HwQNplh5mK11VYrpuJWW1mylfO8/PLLpsz47bffmqZ6v379uML+f61FgXW13bbMiARIgARIgARIgARIgARIgARIgARIgARIgARIgARIoCICFFhXRId+JEACJEACJEACJEACJEACJEACJEACJEACJEACJEAC1UaAAutqQ82MSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAEKiJAgXVFdOhHAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRQbQQosK421MyIBEiABEiABEiABEiABEiABEiABEiABEiABEiABEigIgIUWFdEh34kQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAL5CFGSAABAAElEQVQkQALVRqBkBNa//vqrrLzyymlgfv/9d1lhhRXSrvMCCZAACZAACZAACZAACZAACZAACZAACZAACZAACZBAaREoaoH1e++9JxdeeKG89dZbMn/+fFlppZVkq622khNPPFH69u0rjz/+uJx++uny0UcflRb1Iiutc07+/vtvqVu3bpGVjMUpJwJ//PGH1K9fv5yqxLqQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAlUMYGiFVgPHz5cBg0aJJtttplccsklJqhevHixPPHEE3LttdfKbrvtJi+//LIsv/zy8tlnn1UxltqT3OzZs6VXr16yYMECGTVqlBxwwAG1p/KsabURGDx4sAwbNkw6duwoU6dOpeC62sgzIxIgARIgARIgARIgARIgARIgARIgARIoLQJFKbCeMWOGdOjQQdq0aSOvvfZamnBr+vTp0q1bN1myZIm0bNmSAusM9xw00GEuZZdddskQQuT888+3CQEE6N27t0yYMCFjWHqUFgFoNJ977rkydOjQghU8SR4w29OgQQP5888/rRwzZ86UzTffvGBlYsIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAKlS6AoBdY9e/aUJ598Up5++mnTpI7D++yzz8rOO+9MgXUcnP9dO+KII4zPRRddlDEUJge23nprgVmQESNGSP/+/TOGpUdpEcDKg9atW8s///wjyy23XEEKnzSP/fbbTyZOnCitWrWSjz/+mOZnCtIaTJQESIAESIAESIAESIAESIAESIAESIAESp9AUQqs11prLVm0aJF89dVX0qxZs4yUt9tuOwtHkyDxiLbZZhvZc889pSKBNWKCMzRlIUykKx8Cjz32mOy1114FFVgnzeOvv/4S2KTfcsst01ZMlA9x1oQESIAESIAESIAESIAESIAESIAESIAESCBfAkUnsIad6jXXXNPq9eKLL8q///3vjHW84YYb5LrrrqNJkBhCn376qWy00UZm8qMygXVMdF4qAwLYmHTs2LEFFVhXRx5l0BSsAgmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQQEICRSewRrlbtGhhWr877bSTTJo0KaP5ANi3hsBszpw5CatbO4JBm3WPPfaQyZMnU2BdO5o8rZbY2HD33XcX3AuFMglSHXmkVYwXSIAESIAESIAESIAESIAESIAESIAESIAEyppAUQqsvdYmyGPDwMsvv1y23XbbtIaAMA72cOM2cPvtt9/kjjvukFdeeUXeffddWXXVVaVXr15y+OGHm11nn9hDDz0k2AQOJkjwBxMaBx98sMBG9sMPPyzz588XmChBXPjBQQB43333CTTAv//+e8u/e/fu0qVLF59s2i/KcOONN8r7778vv/zyi8VB3fr16yd16tRJCQ8THffee29QJuSBcv74449y++23W33q1q0rW221ley///5BfbCp3YMPPmj1hjARDuXee++9g/Tbt29vNqtxAXV8/fXXg3xQ/gEDBgRhwwfffPON3H333fLGG28YryZNmghMjgwaNEjWW2+9cNBEx9OmTZPbbrvN2g/1bdq0qW36+Pbbb1tbn3TSSSnpJG3PcCTkgY0n0b5of9g8R9vCjMWFF15oHLt27WqTIrCZXh33QdJ6VHZfgtkGG2wgnTp1kn333TewUf3RRx/JPffcIzfddJPdL+AB2+RhG9a456Ium/szmzyWLl1q96PvX1hBgXZv2LBhtAgyb948GTdunN2Ts2fPtomrjh07Cu4F3G9hlyufcBo8JoFSIID3HN439evXl3r16snff/8t2MgU1/E+82706NGy4oorWhj4r7HGGjZp5f3xrMf7ARO9CxcutPfHIYccYu+H6Dso2+ezz4O/JEACYmNDjB3RH9G3YHJt2bJlgvEXNhOHwzsX48GVVlrJ9hD59ddfZddddw3edUnHCkgLaeOd/+qrr8onn3xiY1SMz3bYYQcbd6I/Y8xIRwIkkJwAvvHYj5PzYsjyJcBxaPm2LWuWnEB19wOO7UJto5vtFZ17+eWX3QorrOC0mMGf2rJ2ffr0cbfccovTAXmFZVbBo9tiiy2cfgi4K664wunGgu7qq692a6+9tlNBmdMP9iC+bkzoVBgW5HP++ee7Cy64wKmWt8VR4Z/r0KGD+R9//PFOPzxct27dnNrPdip4cyoMdCpsdSoQtOMg4dDBmDFjnH4suDPOOMPyRnlUMGxpdu7c2amgLhTaORUsuM0228zieAYqoLR8VMDgUCYVuDr9EHINGjRws2bNsvgIoxso2p+Ph7L5a/i99dZbg7yGDh3qmjdvHtT96KOPDvzCB0899ZRTob3Tjy932WWXWR0eeeQRt+OOO1rcZ555Jhy80mOUQQUvltbcuXOd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gAF1oUmzPRJgARIgARIgARIgARIgARIgARIgARIgARIgARIgAQSEaDAOhEmBiIBEiABEiABEiABEiABEiABEiABEiABEiABEiABEig0AQqsC02Y6ZMACZAACZAACZAACZAACZAACZAACZAACZAACZAACSQiUHQC65EjR8rff/8t9evXlzp16shyyy0nzjn5559/5M8//5R69erJEUcckahyDEQCJFA9BP744w/rs9WTG3MhARIgARIgARIgARIgARIgARIgARIgARIoVwJFJ7AeMGCAvP/++zJnzhxZuHBhwL1hw4ay8cYbS4MGDWTKlCnBdR6QAAnULIHBgwfLsGHDpGPHjjJ16lQKrmu2OZg7CZAACZAACZAACZAACZAACZAACZAACZQ0gaITWHuav//+uzRr1kx++OEH07RetGiRrLHGGt67xn4ff/xxWWGFFWSXXXapsTIwYxKARvO5554rQ4cOLRiMJHmgn2ISCasf4GbOnCmbb755wcrEhEmABEiABEiABEiABEiABEiABEiABEiABMqbQNEKrIF9o402kk8//VRWXnll+eWXX4qiJWCOpGXLlnLRRRcVRXlYiNpJ4LPPPpPWrVubqRyYzSmES5rHfvvtJxMnTpRWrVrJxx9/LHXr1i1EcZgmCZAACZAACZAACZAACZAACZAACZAACZBALSBAgXWWjbzNNtvInnvuSYF1ltwYvGoJPPbYY7LXXnsVVGCdNI+//vpL3nvvPdlyyy1pDqRqm5mpkQAJkAAJkAAJkAAJkAAJkAAJkAAJkECtI0CBdRZNDm1vaH2ff/75FFhnwY1Bq55A3759ZezYsQUVWFdHHlVPhimSAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmUMgEKrBO2HrRI99hjD5k8eTIF1gmZMVhhCGBjw913311wT/7zzz9SCJMg1ZFHYegwVRIgARIgARIgARIgARIgARIgARIgARIggVImULIC66+++kruvfdewWaM+Pv+++/loYcekh9//FFuv/12effdd82W7lZbbSX777+/2Z2ONtSyZcvkpptukldffVU++eQTE/7B5McOO+wgN954o0ybNk2cc/Lggw/KHXfcIRDiwfXq1Uv23nvvILn27dvL1ltvHZzjAPkjjffff9/sb2MjOm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IgARIgARIgARIgARIgARKoLgIUWFcXaeZDAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRQIQEKrCvEQ08SIAESIAESIAESIAESIAESIAESIAESIAESIAESIIHqIkCBdXWRZj4kQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIVEig6gfVvv/0mL730UoWFTuLZrl07WXvttZMEzTuMc07+/vtvqVu3bt5p5ZrAH3/8IfXr1881OuORAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQQI0TKDqB9YwZM6R9+/YpYJZffnlZffXV5ZdffpHff/898KtXr56sttpq8vPPPwsEtmE3evRoOfzww8OXCnI8e/Zs6dWrlyxYsEBGjRolBxxwQEHyqSjRwYMHy7Bhw6Rjx44ydepUCq4rgkU/EiABEihzAt9//71cffXV8txzz8knn3wiK6ywgmy66ab2rjruuONkxRVXrJDAhx9+KPfee688//zzMn36dGndurXsvPPOctlll1laFUamJwmQQNYEnn76abnllltk1qxZ8t1330nLli2lbdu2cvrppwsUMCpy//zzj4wdO9bGfy+88IIsW7ZMtt56aznzzDNlxx13rCgq/UiABKqQwOOPPy5jxoyRt956SxYvXizrrbeedO3aVU444QTZbLPNMub08ccf2zt7ypQp9j3ZpEkT2X333QXfd3gW0JFAqRH48ccf5fLLL5dXXnlFPvjgA5PjbLzxxtK3b1855JBDMsoq8D4bOXKk3HXXXQIZC8632morOeaYY+Swww4rNQwsby0nwH5QRTeAagcXlZs0aZLTqjl9yTsdgLuFCxc61V62MqrA2jVr1sz8EWb+/PlB2XVg4J555hmnwm7z14/1wK+QB+edd15Qnt69excyq9i09cPEqeA+KMPMmTNjw/EiCZAACZBA+RN49913XcOGDZ1OYLoHH3zQ6Yew01VLbptttrH3BN6tn332WUYQ999/v1tllVXsHXzfffe5Tz/91OlEqGvatKnbddddM8ajBwmQQG4Ejj76aKcr5NzFF1/s9OPezZkzx11xxRWuTp06brnllnPnnntuxoQx9lXBlvXtgQMHOhWUOZ1wcmeffbZd00m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rcccdlrI5XosMEEB0JlCoB9oPsW66sBdbA4YXJeDh6+18QQp911lkpAmhoHPuBQ3STmu7du5tfJptJp5xyivnHCaxRBlz3aUc/PiDQ9rOK4ZlGxEvq1MRHkH6cwBofMj7/uM0ow3YSdZl4WrbQVkf8uN3mc+EGG6m+PNCCDjufHrQAo27gwIEWL9PmI9CkRrpeC2GPPfawc2gMRh04IWyc8CYaluckQAIkUGoEMNE3aNAgd8wxxzg/0Yvn65tvvplWFW/bGs9E7OAedWpWyZ6XmBDETu50JEACVU8AK96wugzjVnyQQ1lAzX04rJAIO9i79mMo/GLlWNipKbRg9R/SpCMBEqgZAhA4Y5US+ikmoKBI5R1Wl/p+DIWdOPfFF18EYdiX4wjxWikRwPsN9zyE05h49Q6rtX1fOP744/3ltF8vT1l++eVT+lJaQF4ggSImwH6QfeP8PwAAAP//wJfQsAAAQABJREFU7J0JvE3V+/8fmQuZItFERFREs0hKheaSorkklSappFkDaUZpoJSIooRSNKioVCIUKkmJQgOSSuv/fJ7/b+3vPufsc4dzz73OufezXq97z95r2mu991lnr/XsZz2PuCwL++yzjxMR+8tL04877jjLe9RRR+WYffLkya5OnToO+bds2RKT97LLLrM6TjrppJh4f3LVVVdZ+vnnn++jYj579epl6TvvvHNMvD/Zd999Lf3+++/3Ufn6/P333608uHz//fcJZX/++ecg/amnnkpInzhxYpC+cOHChPTrrrvO0jt06JCQlgq3QYMGWX0VK1ZMqK9v376WFs/qr7/+cmXKlLG0yy+/PKEcIq655hpLP/vssy394osvtvO6deu6e+65x3333XdBuf/++8/hvuKTgQRIgASKOwH/u4vnxOjRo2O6W6FCBfutRNr06dNj0nDy7bffBumoh4EESKBwCaxYscLtueeeNu72228/t2HDhuCCmM/4eXDr1q2D+PAB5kHIU716dbdp06ZwEo9JgASKgADWkocddpiNQ6zz1qxZE3PVPn36BON41apVMWn+ZNmyZUGem266yUfzkwSyjsC0adNcqVKl7O/xxx+PaT+eb/6Z1rNnz5i08Mk555wT5Pv333/DSTwmgaw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zwQhNeDBgwwNqAfkKoDaE/ArS6wRNthQ1UCPDVG72rX7++Q/u88Bocw9rpKFvY9wbXYCABEiABEsidAJ4VMP+EZxh2Mp1//vmuR48eDtvTypUr5+C0N+oZmHvNzEECJFAYBKCYgPkX5mydO3d22AkI59eY60FZAIoMDCRAAplNgOM4s+8PW1d0BDgPLTrWvFLmEuA4SLw3pRClQsViH9TxoqgmsaxatUpUaC3qOCqmzyo8la+++kpatmwparJC5s+fL6q5LHXr1hXVKBYVIMfkD5+o8FYWLVokak5DdJEgO+64Yzg5q45VU0dUq11UA1rUCaX133dABxBecARx48ePF9W4kyOOOELUDraoANxntU+16y0qCBfd3mA8+/btK+rVPiYPTgrz3iRcjBEkQAIkQAJJCSxYsED0JaqoeSfRl46iLyLlsMMOE32Jm7QME0iABLYOAXWGKpMnT7Y5KOZoqoxh81DMy1TRYes0ilclARLIFwGO43zhYuZiToDz0GJ+g9m9PBHgOPgfphIjsP5fl3mULgKtW7eWDz74QD799FNRLbyk1X7yySeiGtZy6KGHimqyJ83HBBIgARIgARIgARIgARIgARIgARIgARIgARIggZJNgALrkn3/C9R7aKOr7XD58ccfEzTWwxWrE0bT+unQoYNMmzYtnMRjEiABEiABEiABEiABEiABEiABEiABEiABEiABEggIUGAdoOBBfgkMHz5cevbsKW3btpVJkyaJ2k1MqEIdN0qnTp1EbSnKuHHjRJ1fJuRhBAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmAAAXW/B4UiMCoUaPk5ptvlt9//13OO+88M/1Ru3ZtWb16tXz44Yfy9NNPmx3UoUOHSteuXQt0LRYmARIgARIgARIgARIgARIgARIgARIgARIgARIo3gQosC7e97dIegcHjRMnTjSnP0uXLhU4/qlZs6bUq1dP2rRpI+q9XsqVK1ckbeFFSIAESIAESIAESIAESIAESIAESIAESIAESIAEspcABdbZe+/YchIgARIgARIgARIgARIgARIgARIgARIgARIgARIoVgQosC5Wt5OdIQESIAESIAESIAESIAESIAESIAESIAESIAESIIHsJUCBdfbeO7acBEiABEiABEiABEiABEiABEiABEiABEiABEiABIoVAQqsi9XtZGdIgARIgARIgARIgARIgARIgARIgARIgARIgARIIHsJUGCdvfeOLScBEiABEiABEiABEiABEiABEiABEiABEiABEiCBYkWAAutidTvZGRIgARIgARIgARIgARIgARIgARIgARIgARIgARLIXgIUWGfvvWPLSYAESIAESIAESIAESIAESIAESIAESIAESIAESKBYEaDAuljdTnaGBEiABEiABEiABEiABEiABEiABEiABEiABEiABLKXQMYJrKdPny6rVq1Kmeihhx4qu+++e8rlWZAESIAESIAESIAESIAESIAESIAEkhH48ssvpUqVKlK3bt1kWRhPAiWCwObNm+Xjjz+Www47rET0l50kARIoOgIZJ7C+6qqr5NVXX5WVK1fKpk2bAhI1atSQ2rVrS6lSpSxuy5YtJtj+7bffgjw4GDx4sFxzzTUxcTwhARIgARIgARJITmDatGlyySWXSOfOnaVTp06y2267SenSpeW7776TBQsWyLhx46R169YyaNCg5JUwhQRIoMgIHHHEETZGTzrpJDnwwAOlZs2asmbNGvn2228Fyh+TJk2ShQsXSvXq1YusTbwQCZQUAsuXL5dmzZpJr169ZODAgSl3m+M4ZXQsmEEELr/8chkyZIj8+eefUrFixZRaxnloSthYqBgSWLt2rck03377bVm6dKmUL19eGjduLMcdd5yt1SpUqFAMe528SxknsPZN/eOPP2TXXXcVCKQhpF63bp1UrVrVJwefGzZssIk5BN1YWF922WXyyCOPBOnF/eDvv/+W/v37U4hQ3G80+0cCJEAChUhg/Pjx0qVLl6RX2HnnneWdd96R+vXrJ83DBBIggaIj0LRpU1m0aFHSC954440yYMCApOlMIAESSJ1Ahw4d5M0335Q+ffrIvffem3JFHMcpo2PBDCHw/vvvS5s2bcQ5J5DLbLfddim1jPPQlLCxUDEjMH/+fGnbtq3sueee0rdvX9l7771l9erVcuWVV8qnn34qu+yyi7z77rumWFTMup60OxkrsEaLGzZsKF9//bVsu+22snHjxqSdQAIE21hIwyQINLRLSli2bJn1+7///gu0z0tK39lPEiABEiCB9BBItlDA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8mEYDDX8gn4HBxv/32C+QpapLVffDBB05t6+a7uZyH5hsZCxQzAlBArV69ujv55JOd+uSL6Z365wvGWUmb32WcwBrmMbyQOpVPdQZgN1eNkjt1pmjCW9x4CGbVrljMjVfHUq5ixYqmWYZjmPbA+Zo1a4J8XmANoS7MZ0BTG2/E69ata4Lojh07Omg65xSgXQ3NNPQH5bFFE4t/1IctYT6ojVAHgTsWIWgz2oNz9CPZDz+u3aZNG6sb/YOZk2HDhvkqnRpvd+r8wN7UqAMEhz+0GeZK8EIAW9mSCcODSnhAAiRAAiRQrAmoAzd3wgkn2HMNn5gMebNcaic3QZBdrGGwcySQBQRg2g5zxcaNG9t4xfwZc1hofqrTHgfTIAwkQALpI3DxxRfbugxrOay58OfXj1irqQ+IfF+M4zjfyFggAwisWLHCFAKhJIcx4McDnkl4DkE2kd/AeWh+iTF/cSSAF0EHH3ywPWvw2bNnT9e5c2eT9WF+N2jQoBhTwMWRQXyfMtrpogp4t3rwDhC900V9o2iODOFQAJ5y8+PIRn/czZunCqtFNaPzVTYnELooEXiBh1dqOJ1U24VBdniwVq04admypTkHgSF33fZtHq3hFFIfKkFeHpAACZAACZRsAvBQ/e677wqeV02aNBF9wSo6YZJtttmmZINh70kgAwnorj9RO4fmWFt3E9p4VaUKOtHOwHvFJpFAMgIcx8nIML4kEuA8tCTedfY5ngAcas+dO1fU+oSoMqvJ+Erq/I4C6/hvR9x5vMA6LpmnJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACaSJAgXUuICmwzgUQk0mABEiABEiABEiABEiABEiABEiABEiABEiABEggTQQosM4FpNqeNhMgZ555powePTqX3EwmARIgARIgARIgARIgARIgARIgARIgARIgARIgARJIlQAF1knInXLKKWYXGvafEdSZoahTRGnbtq08/PDDSUoxmgRIgARIgARIgARIgARIgARIgARIgARIgARIgARIIFUCFFgnITdhwgRZu3atwIlN6dKl5d9//xX1XisNGjSQ9u3bJynFaBIgARIgARIgARIgARIgARIgARIgARIgARIgARIggVQJUGCdKjmWIwESIAESIAESIAESIAESIAESIAESIAESIAESIAESSCsBCqzTipOVkQAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJpEqAAutUybEcCZAACZAACZAACZAACZAACZAACZAACZAACZAACZBAWglQYJ1WnKyMBEiABEiABEiABEiABEiABEiABEiABEiABEiABEggVQIUWKdKjuVIgARIgARIgARIgARIgARIgARIgARIgARIgARIgATSSoAC67TiZGUkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAKpEshKgfXHH38spUuXlpYtW6bab5YjARIgARIgARIgARIgARIgARIgARIgARIgARIgARLIMAJZJ7D+559/pE6dOlK+fHlZsWKFbLPNNgVC+scff8iDDz4oa9eulTVr1si6devksccek1133TVP9U6ZMkXef/99K4s6WrRoITfddFNk2b///lvKlSsXmZafSOecbNmyRcqUKZOfYhmVd8yYMTJ37tyAe/v27aV3794ptzFdbFNuAAuSAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAkUmEDWCaynTp0qnTp1so6/9dZb0q5duwJB+P333+X444+XL774Qn799Ver64MPPpBDDjkkT/UOGTJEhg8fLgsWLLD8Rx11lLzxxhsJZfv27WuC8QMPPFBmzJiRsuD6yy+/lOOOO05WrVolTz/9tJx66qkJ18qGCAj1x40bJ0uWLLHmnn/++fLUU0+l1PR0sU3p4ixEAiRAAiRAAiRAAkpg8uTJMmrUKJkzZ47NKXfZZRdp06aNXHrppdKkSZOkjKCAcccddwh2EH7zzTdSr14920XYp08fad68edrLJa2QCSRAAiRAAiRAAiRAAiSQIQSyTmB91llnyXPPPWf4evToYcLidLCEdnWtWrUE2sv5EVj7a0M7+JFHHpEogfXmzZulcuXKAu1whIULF8pee+3liwafWOhAcxx1JAs333yzLWqQftppp5nQN1nebIg/6aST5OWXX5ZUBdZ5ZZsNLNhGEiABEiABEiCB7COAuWOvXr1k5MiR0qFDBznxxBNl/fr1Jrz+7LPPpEKFCjbXOfrooxM6N2nSJMHctkuXLnLeeefJTjvtJIsXL/SW7QUAAEAASURBVJaBAwfK22+/LUOHDrW64wumWi6+Hp6TAAmQAAmQAAmQAAmQQCYSyCqB9aZNm6R27dq2CADMGjVqyE8//SRly5ZNC9sqVapY3akIrO+//3655pprIgXWaNzJJ58sEydOlN133920iqPMeZxzzjmy2267yW233Za0P59//rnst99+Jlh/4okn5MILL0yaNxsSrrrqKtM8T1VgjT7mhW02sGAbSYAESIAESIAEso/A448/LhdffLFpWPtdgOgF5q3YxTd9+nRTSIBiwpFHHhl08Pvvv5d9991X7rnnHisfJPzfwRlnnGGKCbNmzRLs0PMh1XK+PD9JgARIgARIgARIgARIINMJZJXA+sUXX5Tu3btLq1atTAsacGFDumPHjmnhvP322wtsWqcisH7ggQfk6quvTiqw/vfff2X+/PnSrFmzpOZA4ESyc+fOOQqs0dEff/xRYLMZwu9sD2AGdgURWOeFbbZzYvtJgARIgARIgAQyjwC0q6tXr26+TyBY3nbbbWMauWjRIpv7Id8xxxwjr732WpAOQfVdd90lv/32W6RPFph/g9+WG2+8UQYMGFDgckEFPCABEiABEiABEiABEiCBDCeQVQLrU045xTSLYUbi7LPPNrTYRgl7gekIhSmwzq19X3/9tTRs2FBg8iMnDevc6sm29HQIrLOtz2wvCZAACZAACZBA8SDg52/oTdu2beWdd95J6Bi0qKG0sN1225lta78zEPNamPZYvXq1Cb0TCmoEdv/BzAiUNnxItZwvz08SIAESIAESIAESIAESyHQCWSOwhuYzzIE888wzcuyxx9oxtlrCNvTPP/9s9gELCntrCayhIQwt8TfffJMC64LeRJYnARIgARIgARIggSIi8NFHH8lBBx1kV8M8EtrS8QG757AjEOGTTz4xh4o4ht3q8ePH2+48CKQhnA6Hr776ypw19u/fP/BfUpBy4bp5TAIkQAIkQAIkQAIkQAKZTCBrBNbQooaXdWihYLslHA56bRN8QtskL+G///4zW4LwxA5tF9iMhkYMBMZVq1bN1SQI7AbCFiEWHL///rsccsghZsZjwoQJkSZBNmzYIE8++aTAqSP+fv31V3MUiWvBCeNLL71k6TNmzLDmH3fccX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AmQQMkkUCIF1iXzVrPXmUBATXqI2vMWdYwp6jgpxyZ16tRJ1LyIqBa8qLZ0jnmZSAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQALFgQAF1sXhLrIPWUNA7U6L2vYWNdMhTzzxRI7tVjvTomZZRLcbi5r2yDEvE0mABEiABEiABEiABEiABEiABEiABEiABEigOBCgwLo43EX2IWsIbNiwwcx3wKwMhNHqyDGy7c8995yoTWpp3LixzJ8/P9I0TWRBRpIACZAACZAACZAACZAACZAACZAACZAACZBAFhOgwDqLbx6bnp0EYHu6X79+og4VzZ51165dpX79+mZf+ptvvpExY8aIOlmSjh07CgTX6lgxOzvKVpMACZAACZAACZAACZAACZAACZAACZAACZBAPglQYJ1PYMxOAukisHDhQpkxY4Y58IQTT++Uco899pAuXboIPhlIgARIgARIgARIgARIgARIgARIgARIgARIoCQRoMC6JN1t9pUESIAESIAESIAESIAESIAESIAESIAESIAESIAEMpgABdYZfHPYNBIgARIgARIgARIgARIgARIgARIgARIgARIgARIoSQQosC5Jd5t9JQESIAESIAESIAESIAESIAESIAESIAESIAESIIEMJkCBdQbfHDaNBEiABEiABEiABEiABEiABEiABEiABEiABEiABEoSAQqsS9LdZl9JgARIgARIgARIgARIgARIgARIgARIgARIgARIIIMJUGCdwTeHTSMBEiABEiABEiABEiABEiABEiABEiABEiABEiCBkkSAAuuSdLfZVxIgARIgARIgARIgARIgARIgARIgARIgARIgARLIYAIUWGfwzWHTSIAESIAEig+Bf/75R7bZZhspXbp08ekUe0ICxZjApk2bpGLFisW4h+waCZAACZAACZAACZAACWQmgYwTWE+fPl1WrVqVEi0IAs4880wr++OPP8oTTzwha9eulTVr1shvv/0mo0ePlurVq6dUNwuVXALTpk2TRYsWxQAoW7asdOvWTapVqxYTn9PJRx99JLNmzUrIcu6558bU8/fff0u5cuUS8jGCBEggOwm8+uqrctttt8nChQttbJ966qkyZMiQjBaE8Rmand81trrgBDBv7N+/v0yYMEHWr18vDRs2lAEDBshxxx1X8MoLsQ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wqAecV3/2i+4kB563anJ/gcd4di/OrB8LzQ/3xkxLOd7j7xYkP1Hs/47j6LgIQKFMPijzbg0G3bL7qYWBtIu86r5gO7aK9R/zkqvODA+cn3ZzvxA0GAl2zBwjwvPoVOK6e93ir+1ZlsDfS51OdLUNccURgYAjwLvQGP44xlV/t67bYYot+4z7GFX5FhvMrkpxXojmv1HN+grppGSS9Z555JryLvRGI8xNqTUtbCYlAUQLtUBf86qSgz2DMyHjUG1MVzb7CiUBTCKgeNAVjQ4lIYd0QPkUWAREQAREQAREQAREQAREQARHodAJ+1aPzbvuc34TcXXPNNVWL4/cjct61lvPW1c6vcq0aVidFoNMIqC502h1TfltBQPWgFVTrS1MK6/p4KbQIiIAIiIAIiIAIiIAIiIAIiECXEfD7Bbl11lnHeT/27o9//GPV0vn9gZx3ExZWjXiXjFXD6qQIdBoB1YVOu2PKbysIqB60gmp9aUphXR8vhRYBERABERABERABERABERABEegyAl9++WVwu+j3pQnKaL+Be2YJL774Yuf3EgpuIHGJh2sQiQh0EwHVhW66mypLWQKqB2XJNS+eFNbNY6mUREAEREAEREAEREAEREAEREAEOpQAe/QceOCBzm+oGPxZ+82/3dChQx37Ar366qvu0ksvdQ8++KDzGyw7FNd+s9YOLamyLQLVCaguVOejs71BQPVgcO+zFNaDy19XFwEREAEREAEREAEREAEREAERaCMCzz77rLv99tsdG7/yh8KajcWHDRvmNtlkk/DZRtlVVkSgZQRUF1qGVgl3EAHVg8G5WVJYDw53XVUEREAEREAEREAEREAEREAEREAEREAEREAEREAERCBFQArrFBD9FAEREAEREAEREAEREAEREAEREAEREAEREAEREAERGBwCUlgPDnddVQREQAREQAREQAREQAREQAREQAREQAREQAREQAREIEVACusUEP0UAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYHAJSWA8Od11VBERABERABERABERABERABERABERABERABERABEQgRUAK6xQQ/RQBERABERABERABERABERABERABERABERABERABERgcAlJYDw73qld95ZVX3AQTTOB++MMfVg3XbSeTJHEPPPCAW2qppbqtaCqPCIiACIiACIiACIiACIiACIiACIiACIiACIhAAQIdo7D+5z//6SaccMJ+RfrPf/7jxhtvvH7HO/XAtdde6zbffHPH5worrNCpxSiV76+//trNO++8bplllnHnnHOOG3vssUulo0giIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAKdSaCtFdZPPfWUO/zww90jjzzi3n777WB1PP/887vddtvNbbnllu66665zv/71r92LL77Yjz7Kz3HHHbff8XY+cNddd7lVVlnFHXjggW748OFNzSrWy//973/d97///aamW09il156qXviiSfcxx9/7D766CO30koruT322KNPEi+99JL7yU9+4n72s5+5s846q885/RABERCBRgg8//zzbpJJJum51SuNMCOuuDVKUPHLEtCzVz85DDn+9re/hcn/+mMrRrcQeOaZZ9yUU07ppptuum4pksohAqUIqC6UwqZIIiACItAeBLwisy3FKysTr3BOFlhggeSaa65JXn/99cQrO5OjjjoqmWKKKRJvhZzMOOOMySyzzNIv//vuu28yzjjjJEsvvXTiO+79zrfjgTfeeCOZaqqpkhVXXDHxiuWmZvG5555LZptttmSiiSZKrrzyyqamXU9iBx98cDL77LMn/skPf9tvv31mdPJImD/84Q+Z53VQBERg8Alcf/31yfTTT5+MGjWqZmZo0/74xz8mSy65ZDL55JMnk046aeJXUiQjR46sGvfTTz9NaM+J5xXNoc33E12RG6TxAABAAElEQVTJiBEj6m7beYf84Ac/SPbbb7+q12z1SXFrNWGln0dAz14emfzjn332WbLZZpslCy+8cH6g6Iw3oEh22mmnZNZZZ028a7fwucsuuySjR4+OQvX/6lfVJRtvvHHo09I+zjfffMmuu+6a0H+rV7xRR+hD+ZWJ9UZV+DYlUOZduMgii4Q+tzf8Cf3pCy+8MLnkkksy/26//fZKyW+66abw3O6+++4J31944YXk5ZdfTm699dbkpJNOSpZYYonwXq5EiL6UyWcUvelfy9arsvHK1v8333wztBuMeemnzDnnnIk33Anj3qZD6fAEyzxjqgtJUoYbj0rZeGX7/f/73/9CH3+11VZLhgwZkkw99dSJdxWanHLKKYneaYNTeRt5J5S9n2Wfn1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fgOUrixfF90qFUUEREAEREAEREAEREAEREAEREAEREAEREAEmkpACuum4mwssQ8++CBsaDLrrLO6m2++OWy04Xc0dnfddZcbf/zxw4aTXAHltt+x1Pnd553fRbqxi7ZZbDZY3Hnnnd3ll1/uNtxwwzbLnbIjAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQSgJSWLeSbom033vvPbfeeuu5Aw44wK2//volUujcKOySPXToUHf22We7ddZZp3MLopyLgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiUIiCFdSlsiiQCIiACIiACIiACIiACIiACIiACIiACIiACIiACItBsAlJYN5uo0hMBERABERABERABERABERABERABERABERABERABEShFQArrUtgUSQREQAREQAREQAREQAREQAREQAREQAREQAREQAREoNkEpLBuNlGlJwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIqAFNalsClSuxP473//6x566CG31FJLtXtWQ/4effRR98Mf/tBNN910HZHfV155xU000UQdk9+OgKpMioAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIOCms9RB0HYGvvvrKbbjhhu4///mPu/POO9u+fF9++aUbMmSI22OPPdwxxxzT9vklgyNGjHD77befu+GGG9wiiyzSEXlWJkVABERABERABERABERABERABERABERABNqfQNsprK+99lqH9WY1GXfccd0cc8zh5p57bjf99NNXC9q25y699FL3xBNPuI8//th99NFHbqWVVgoKy8HM8Ndff+1g28mCZfWaa67p/v73v4c/FMHtLiNHjnTbbLONu+2228Jz0O75tfz94he/cJdddpl7+OGHQ3204/oUAREQAREQAREQAREQARHIJ4DBytNPP+2WWGKJ/EA6IwI9QuCZZ55xU045pVbv9sj9VjGzCage9OfSdgrr3/72t+6vf/2re+ONN9y7775byfEss8ziZpppJvfNN984LGhffPHFYEE71VRTuQMOOMDtvvvuHaVsPeSQQ9wVV1zhXnrppVDG7bff3p133nmV8g70F6xlTz75ZLfYYou522+/vaNYxqz2339/97vf/c7deuutbsUVV4xPte33VVZZxT3//PPuzTffdN/73vfaNp/pjGHBjsuVL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Qi0qi5QPG+Y5fxqX+f3+nJ+dWCblFjZEIH+BFQP+jNp9pGuUVg3G4zS6ywCvNSYUEAh4y3PczOfVljnBmziCW8tHSYJVlllFXfFFVcUStmvDnCHHHKI8y45nF/WXyjOYAXy7kCc96PtyLP3ozlY2dB1RUAEREAEREAEREAEREAEREAEREAEREAEuoCAFNZdcBNVhO8IeDcfzm9YFqyTsG7PksFQWHvf6M4vy3fXXHON8y5JsrLV75h3S+O8ew3nXYs4vwy53/l2OuD9pzu/fDGsWsBSXSICIiACIiACIiACIiACIiACIiACIiACIiACZQlIYV2WnOK1HQFcZ7CM1vsZd37Dx+BOI53JxRdfPLgA2WKLLZz35Zw+3ZLf6623nrv//vsdLl28v+ua1/D+zp33he38Zpfuuuuuc2uuuWbNOIMVwKyrcXfiNyQdrGzouiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAl1CQArrLrmRKsZ3BFDw+h25g2uKI444ooJlww03DH688RGH4Gd5vvnmCy5E/CaKlXDN/vLxxx8Hv3b4sMYfVxHBJ/VSSy0VfJET32+UViTagId55plngt9sfMVffPHFA359XVAEREAEREAEREAEREAEREAEREAEREAERKD7CEhh3X33tOdLdOKJJ7r99tvP3XrrrWHzTYCMGjXKofwdb7zxguX1t99+6/AtPdtss7mVVlqpZczOOuss53c4dg899FDYQKnIhZ588km38MILB4vlCy64oEiUAQ/z5Zdfhk3csATHZ7jfNX3A86ALioAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIdB8BKay7756qRJ4AO22PHDkyKIoHE8jw4cPd1Vdf7R5//PG6svHNN98Uch9SV6JNDEy5KNOf/vQnJ7/VTQSrpERABERABERABERABERABERABERABESgxwlIYd3jD4CKLwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIALtQkAK63a5E8qHCIiACIiACIiACIiACIiACIiACIiACIiACIiACPQ4ASmse/wBUPFFQAREQAREQAREQAREQAREQAREQAREQAREQAREoF0ISGHdLndC+RABERABERABERABERABERABERABERABERABERCBHicghXWPPwAqvgiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAi0CwEprNvlTigfIiACIiACIiACIiACIiACIiACIiACIiACIiACItDjBKSw7vEHQMUXAREQAREQAREQAREQAREQAREQAREQAREQAREQgXYh0FSF9UUXXeS++OKLdimb8iECIiACIiACIiACIiACIiACIiACIiACIiACIiACIvB/BKaeemq38cYbtzWPpiqsZ555Zvfmm2+2dYGVOREQAREQAREQAREQAREQAREQAREQAREQAREQARHoRQILLbSQe+yxx9q66E1VWK+66qpuzJgxbV1gZU4EREAEREAEREAEREAEREAEREAEREAEREAEREAEepHAXHPN5S6//PK2LnpTFdZtXVJlTgREQAREQAREQAREQAREQAREQAREQAREQAREQAREoK0JSGHd1rdHmRMBERABERABERABERABERABERABERABERABERCB3iEghXXv3GuVVAREQAREQAREQAREQAREQAREQAREQAREQAREQATamoAU1m19e5Q5ERABERABERABERABERABERABERABERABERABEegdAlJY9869VklFQAREQAREQAREQAREQAREQAREQAREQAREQAREoK0JSGHd1rdHmRMBERABERABERABERABERABERABERABERABERCB3iEghXXv3GuVVAREQAREQAREQAREQAREQAREQAREQAREQAREQATamoAU1m19e5Q5ERABERABERABERABERABERABERABERABERABEegdAlJY9869VklFQAREQAREQAREQAREQAREQAREQAREQAREQAREoK0JSGHd1rdHmRMBERABERABERABERABERABERABERABERABERCB3iEghXXv3GuVVAREQAREQAREQAREQAREQAREQAREQAREQAREQATamoAU1m19e5Q5ERABERABERABERABERABERABERABERABERABEegdAlJY9869VklFQAREQAREQAREQAREQAREQAREQAREQAREQAREoK0JSGHd1rdHmRMBERABERABERABERABERABERABERABERABERCB3iEghXXv3GuVVAREQAREQAREQAREQAREQAREQAREQAREQAREQATamoAU1m19e5Q5ERABERABERABERABERABERABERABERABERABEegdAlJY9869VklFQAREQAREQAREQAREQAREQAREQAREQAREQAREoK0J/D+sBBxzO6KAmQAAAABJRU5ErkJggg==)", "_____no_output_____" ], [ "### Own Data\n\nTo use your own data sets, make sure that the folder structure is a described in the graphics below and adjust the `DATA_PATH` variable. You can either reference a folder from your personal google drive, give the url to a publicly available `.zip` file or reference a local folder if you run the notebook locally. The folder structure in the directory should be like the one shown below.\n\n\n* /`YOUR_DATASET_NAME`\n * /`train`\n * /`images`\n * /`masks`\n\n * /`test`(only necessary when testing) \n * /`images`\n * /`masks`\n\n\n", "_____no_output_____" ], [ "#### Google Drive & local\nTo use your own data from the Google Drive, or your machine if you run the notebook locally, change the `DATA_PATH` variable to the correct directory.\n \n", "_____no_output_____" ] ], [ [ "if DATASOURCE == 'Own Directory':\n #specify if the path of your directory\n DATA_PATH = Path('/path/to/your/directory')\n DATASET = 'your_dataset_name'\n mask_directory = 'masks'\n", "_____no_output_____" ] ], [ [ "#### .zip file", "_____no_output_____" ], [ "To use the data from a publicly avaialbe zip file, specify the url alongside the name of the dataset folder in the zip file.", "_____no_output_____" ] ], [ [ "if DATASOURCE == 'ZIP File':\n \n #specify url of the .zip file and dataset name\n DATASET = 'your_dataset_name'\n file_name = 'your_zipfile_name.zip'\n mask_directory = 'masks'\n\n from google.colab import files\n from zipfile import ZipFile\n import os\n from pathlib import Path\n\n # define extraction directory and check for existence\n \n DATA_PATH = Path('/content/data')\n if not os.path.isdir(DATA_PATH):\n os.makedirs('/content/data')\n\n upload = files.upload()\n\n zip = ZipFile('/content/'+file_name)\n zip.extractall(path=DATA_PATH)\n ", "_____no_output_____" ] ], [ [ "### Data preprocessing\n\n- Initialize `EnsembleLearner`\n- Plot images and masks to show if they are correctly loaded", "_____no_output_____" ] ], [ [ "train_data_path = DATA_PATH/DATASET/'train'\nensemble_path = MODEL_PATH/DATASET\n\nel = EnsembleLearner(image_dir='images', \n mask_dir=mask_directory, \n config=cfg, \n path=train_data_path, \n ensemble_path=ensemble_path)\n\nel.ds.show_data(max_n=2, overlay=True)", "_____no_output_____" ] ], [ [ "## Train models\n\n- Train model ensemble with 5 models\n - 2500 iterations for each model\n- You can skip this step use the trained models from our paper (see next section).", "_____no_output_____" ] ], [ [ "n_iter = 2500\nel.fit_ensemble(n_iter)", "_____no_output_____" ] ], [ [ "## Prediction on test set\n\nWe save\n- Semantic segmentation masks (.png)\n- Instance segmentation masks (.tif) using the cellpose flow representations\n- Foreground uncertainty scores *U*\n\nTo ensure reproducibilty we will use the trained models from our paper!", "_____no_output_____" ] ], [ [ "test_data_path = DATA_PATH/DATASET/'test'\nensemble_trained_path = TRAINED_MODEL_PATH/DATASET/f'{SEED+1}'\nprediction_path = OUTPUT_PATH/DATASET\n\nel_pred = EnsembleLearner('images',\n path=test_data_path, \n config=cfg, \n ensemble_path=ensemble_trained_path) \n\n# Predict and save semantic segmentation masks\nel_pred.get_ensemble_results(el_pred.files, \n use_tta=True, \n export_dir=prediction_path/'masks')\n# Save uncertainty scores\ndf_unc = el_pred.df_ens[['file', 'ensemble', 'n_models', 'uncertainty_score']]\ndf_unc.to_csv(prediction_path/'uncertainty_scores.csv', index=False)\n\n# Show results scores\nel_pred.show_ensemble_results()", "_____no_output_____" ], [ "# Predict and save instance segmentation masks\nel_pred.get_cellpose_results(export_dir=prediction_path/'instance_masks')\nel_pred.show_cellpose_results()", "_____no_output_____" ] ] ]
[ "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", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
ec50204d896626dfdaaff832af1912b17e6a6fcf
23,384
ipynb
Jupyter Notebook
DecisionTreeImplementation.ipynb
kshitijanand36/Machine-Learning-algorithms
b9c383d4a6b3a6416addaa75ec64636e6a580bbb
[ "MIT" ]
1
2020-03-27T06:28:58.000Z
2020-03-27T06:28:58.000Z
DecisionTreeImplementation.ipynb
kshitijanand36/Machine-Learning-algorithms
b9c383d4a6b3a6416addaa75ec64636e6a580bbb
[ "MIT" ]
null
null
null
DecisionTreeImplementation.ipynb
kshitijanand36/Machine-Learning-algorithms
b9c383d4a6b3a6416addaa75ec64636e6a580bbb
[ "MIT" ]
null
null
null
31.6
123
0.414471
[ [ [ "from sklearn import datasets\nimport pandas as pd", "_____no_output_____" ], [ "iris = datasets.load_iris()", "_____no_output_____" ], [ "df = pd.DataFrame(iris.data)\ndf.columns = [\"sl\", \"sw\", 'pl', 'pw']", "_____no_output_____" ], [ "#Function to find label for a value\n#if MIN_Value <=val < (m + Mean_Value) / 2 then it is assigned label a\n#if (m + Mean_Value) <=val < Mean_Value then it is assigned label b\n#if (Mean_Value) <=val < (Mean_Value + MAX_Value)/2 then it is assigned label c\n#if (Mean_Value + MAX_Value)/2 <=val <= MAX_Value then it is assigned label d\n\ndef label(val, *boundaries):\n if (val < boundaries[0]):\n return 'a'\n elif (val < boundaries[1]):\n return 'b'\n elif (val < boundaries[2]):\n return 'c'\n else:\n return 'd'\n\n#Function to convert a continuous data into labelled data\n#There are 4 lables - a, b, c, d\ndef toLabel(df, old_feature_name):\n second = df[old_feature_name].mean()\n minimum = df[old_feature_name].min()\n first = (minimum + second)/2\n maximum = df[old_feature_name].max()\n third = (maximum + second)/2\n return df[old_feature_name].apply(label, args= (first, second, third))", "_____no_output_____" ], [ "#Convert all columns to labelled data\ndf['sl_labeled'] = toLabel(df, 'sl')\ndf['sw_labeled'] = toLabel(df, 'sw')\ndf['pl_labeled'] = toLabel(df, 'pl')\ndf['pw_labeled'] = toLabel(df, 'pw')\ndf", "_____no_output_____" ], [ "df.drop(['sl', 'sw', 'pl', 'pw'], axis = 1, inplace = True)", "_____no_output_____" ], [ "set(df['sl_labeled'])", "_____no_output_____" ], [ "import math as m\ndef entropy(arr):\n ans = 0\n total = 0\n \n for i in range(len(arr)):\n total +=arr[i]\n for i in range(len(arr)):\n if arr[i]!=0:\n ans += (arr[i]/total)*(m.log(arr[i]/total))\n \n if(ans==0.0): \n return 0.0\n else:\n return ans*-1", "_____no_output_____" ], [ "def split_info(arr):\n total = 0\n for i in range(len(arr)):\n total +=arr[i]\n \n ans = 0\n for i in range(len(arr)):\n if arr[i]!=0:\n ans += (arr[i]/total)*(m.log(arr[i]/total))\n \n #using an if else here because otherwise it prints -0 when the ans is 0\n if(ans==0.0): \n return 0.0\n else:\n return ans*-1", "_____no_output_____" ], [ "#defining tree node\nclass tree_node:\n def __init__(self,count_0,count_1,count_2):\n self.a = None\n self.b = None \n self.c = None \n self.d = None\n self.no_of_0 = count_0\n self.no_of_1 = count_1\n self.no_of_2 = count_2 ", "_____no_output_____" ], [ "#Using for printing the tree\ndef print_tree(root,cnt):\n if root == None:\n return \n print(\"No. of zeroes at Level \",cnt,\"are =\",root.no_of_0)\n print(\"No. of ones at Level \",cnt,\"are =\",root.no_of_1)\n print(\"No. of two's at Level \",cnt,\"are =\",root.no_of_2)\n print(\"\")\n \n print_tree(root.a,cnt+1)\n print_tree(root.b,cnt+1) \n print_tree(root.c,cnt+1) \n print_tree(root.d,cnt+1) ", "_____no_output_____" ], [ "top_node = None\ndef build_tree(df, y, unused_features,count):\n \n best_feature = \"\" #the best feature that we will get after running the loop\n least_mistake=1e18 #the best feature is the one with least mistake\n \n #the count of all the elements at current i.e before spliiting\n count_0_b = 0\n count_1_b = 0\n count_2_b = 0\n \n #this loop calculates the count of 0,1 and 2 for the current level\n for i in range(len(y)):\n if y.iloc[i,0] == 0:\n count_0_b+=1\n elif y.iloc[i,0] == 1:\n count_1_b+=1\n elif y.iloc[i,0] ==2:\n count_2_b+=1\n \n #printing what was required in the question\n print(\"LEVEL \",count)\n print(\"count of 0 = \",count_0_b)\n print(\"count of 1 = \",count_1_b)\n print(\"count of 2 = \",count_2_b)\n \n #This is for tree implementation.We are building a new treenode here.\n curr_node = tree_node(count_0_b,count_1_b,count_2_b)\n \n \n #Now we are storing the counts of 0,1,2 in an array for better calculations(using the function declared above)\n arr = []\n arr.append(count_0_b)\n arr.append(count_1_b)\n arr.append(count_2_b)\n \n #calculating th current entropy\n curr_entropy = entropy(arr)\n \n #printing it\n print(\"Current Entropy is =\",curr_entropy)\n \n #The base case(where if further splitting is not possible then we will return from the current function)\n if len(set(y[0]))==1 or len(unused_features) == 0:\n print(\"Reached leaf node\")\n print(\"\")\n return curr_node\n \n #Now we are iterating over the unused features to find out the best feature\n for f in unused_features:\n possible_values = set(df[f])\n \n #mistake_count while predicting for the current feature\n mistake = 0\n #now iteratin over the different possible values in the selected feature\n for val in possible_values:\n #the required y that has rows corresponding to the curr val in the feature\n y_reqd = y[df[f]==val]\n \n #calculating the count of 0,1 and 2 for the particaular value in the currernt feature\n count_0 = 0\n count_1 = 0\n count_2 = 0\n for i in range(len(y_reqd)):\n if y_reqd.iloc[i,0] == 0:\n count_0+=1\n elif y_reqd.iloc[i,0] == 1:\n count_1+=1\n elif y_reqd.iloc[i,0] ==2:\n count_2+=1\n \n #prediction will be the max of the 3 counts\n ans = max(count_0,count_1,count_2)\n final_pred = 0\n if ans == count_0:\n final_pred = 0\n \n elif ans==count_1:\n final_pred = 1\n \n elif ans == count_2:\n final_pred = 2\n \n #claculating the mistkae for the current case\n mistake += len(y_reqd) - ans\n #updating overall mistake \n if mistake<least_mistake:\n least_mistake = mistake\n best_feature = f\n \n \n #Here calculating the count of 0,1,and 2 so as to get the gain ratio and entropy \n possible_values = set(df[best_feature])\n entropy_after = 0\n arr2 = []\n for val in possible_values:\n arr3 = []\n y_reqd = y[df[best_feature]==val]\n count_0_ = 0\n count_1_ = 0\n count_2_ = 0\n for i in range(len(y_reqd)):\n if y_reqd.iloc[i,0] == 0:\n count_0_+=1\n elif y_reqd.iloc[i,0] == 1:\n count_1_+=1\n elif y_reqd.iloc[i,0] ==2:\n count_2_+=1\n \n arr3.append(count_0_)\n arr3.append(count_1_)\n arr3.append(count_2_)\n entropy_after+= entropy(arr3)\n arr2.append(len(y_reqd))\n \n split_info_after = split_info(arr2)\n \n #it is the gain ratio which is shown in this formula\n gain_ratio = (curr_entropy - entropy_after)/split_info_after \n \n #printing as reqd\n print(\"Splitting on feature \", best_feature,\" with gain ratio \" , gain_ratio)\n print(\" \")\n\n # Now remove best feature from unused features\n unused_features.remove(best_feature)\n\n #loop over possible values of best feature\n possible_values = set(df[best_feature])\n \n for val in possible_values:\n # calling build tree recursively\n if(val == 'a'):#if val is 'a' then we have to link the current with that node\n curr_node.a = build_tree(df[df[best_feature]==val],y[df[best_feature]==val],unused_features,count+1)\n \n #similarly for b,c,d\n elif val == 'b':\n curr_node.b = build_tree(df[df[best_feature]==val],y[df[best_feature]==val],unused_features,count+1)\n \n elif val == 'c':\n curr_node.c = build_tree(df[df[best_feature]==val],y[df[best_feature]==val],unused_features,count+1)\n \n elif val == 'd':\n curr_node.d = build_tree(df[df[best_feature]==val],y[df[best_feature]==val],unused_features,count+1)\n \n \n return curr_node", "_____no_output_____" ], [ "y = pd.DataFrame(iris.target)\nunused_features = set(df.columns)\n\nroot = build_tree(df, y, unused_features,0)\nprint(\"Printing using tree built in the function :\")\nprint_tree(root,0)", "LEVEL 0\ncount of 0 = 50\ncount of 1 = 50\ncount of 2 = 50\nCurrent Entropy is = 1.0986122886681096\nSplitting on feature pw_labeled with gain ratio 0.3999492084908657\n \nLEVEL 1\ncount of 0 = 0\ncount of 1 = 10\ncount of 2 = 0\nCurrent Entropy is = 0.0\nReached leaf node\n\nLEVEL 1\ncount of 0 = 0\ncount of 1 = 0\ncount of 2 = 34\nCurrent Entropy is = 0.0\nReached leaf node\n\nLEVEL 1\ncount of 0 = 50\ncount of 1 = 0\ncount of 2 = 0\nCurrent Entropy is = 0.0\nReached leaf node\n\nLEVEL 1\ncount of 0 = 0\ncount of 1 = 40\ncount of 2 = 16\nCurrent Entropy is = 0.5982695885852573\nSplitting on feature pl_labeled with gain ratio 0.2858562221757157\n \nLEVEL 2\ncount of 0 = 0\ncount of 1 = 1\ncount of 2 = 0\nCurrent Entropy is = 0.0\nReached leaf node\n\nLEVEL 2\ncount of 0 = 0\ncount of 1 = 0\ncount of 2 = 8\nCurrent Entropy is = 0.0\nReached leaf node\n\nLEVEL 2\ncount of 0 = 0\ncount of 1 = 39\ncount of 2 = 8\nCurrent Entropy is = 0.45622342016761397\nSplitting on feature sl_labeled with gain ratio -0.10080142294546836\n \nLEVEL 3\ncount of 0 = 0\ncount of 1 = 14\ncount of 2 = 0\nCurrent Entropy is = 0.0\nReached leaf node\n\nLEVEL 3\ncount of 0 = 0\ncount of 1 = 2\ncount of 2 = 0\nCurrent Entropy is = 0.0\nReached leaf node\n\nLEVEL 3\ncount of 0 = 0\ncount of 1 = 0\ncount of 2 = 1\nCurrent Entropy is = 0.0\nReached leaf node\n\nLEVEL 3\ncount of 0 = 0\ncount of 1 = 23\ncount of 2 = 7\nCurrent Entropy is = 0.5432727813369008\nSplitting on feature sw_labeled with gain ratio -0.7317484436830594\n \nLEVEL 4\ncount of 0 = 0\ncount of 1 = 14\ncount of 2 = 6\nCurrent Entropy is = 0.6108643020548935\nReached leaf node\n\nLEVEL 4\ncount of 0 = 0\ncount of 1 = 3\ncount of 2 = 1\nCurrent Entropy is = 0.5623351446188083\nReached leaf node\n\nLEVEL 4\ncount of 0 = 0\ncount of 1 = 6\ncount of 2 = 0\nCurrent Entropy is = 0.0\nReached leaf node\n\nPrinting using tree built in the function :\nNo. of zeroes at Level 0 are = 50\nNo. of ones at Level 0 are = 50\nNo. of two's at Level 0 are = 50\n\nNo. of zeroes at Level 1 are = 50\nNo. of ones at Level 1 are = 0\nNo. of two's at Level 1 are = 0\n\nNo. of zeroes at Level 1 are = 0\nNo. of ones at Level 1 are = 10\nNo. of two's at Level 1 are = 0\n\nNo. of zeroes at Level 1 are = 0\nNo. of ones at Level 1 are = 40\nNo. of two's at Level 1 are = 16\n\nNo. of zeroes at Level 2 are = 0\nNo. of ones at Level 2 are = 1\nNo. of two's at Level 2 are = 0\n\nNo. of zeroes at Level 2 are = 0\nNo. of ones at Level 2 are = 39\nNo. of two's at Level 2 are = 8\n\nNo. of zeroes at Level 3 are = 0\nNo. of ones at Level 3 are = 0\nNo. of two's at Level 3 are = 1\n\nNo. of zeroes at Level 3 are = 0\nNo. of ones at Level 3 are = 14\nNo. of two's at Level 3 are = 0\n\nNo. of zeroes at Level 3 are = 0\nNo. of ones at Level 3 are = 23\nNo. of two's at Level 3 are = 7\n\nNo. of zeroes at Level 4 are = 0\nNo. of ones at Level 4 are = 3\nNo. of two's at Level 4 are = 1\n\nNo. of zeroes at Level 4 are = 0\nNo. of ones at Level 4 are = 14\nNo. of two's at Level 4 are = 6\n\nNo. of zeroes at Level 4 are = 0\nNo. of ones at Level 4 are = 6\nNo. of two's at Level 4 are = 0\n\nNo. of zeroes at Level 3 are = 0\nNo. of ones at Level 3 are = 2\nNo. of two's at Level 3 are = 0\n\nNo. of zeroes at Level 2 are = 0\nNo. of ones at Level 2 are = 0\nNo. of two's at Level 2 are = 8\n\nNo. of zeroes at Level 1 are = 0\nNo. of ones at Level 1 are = 0\nNo. of two's at Level 1 are = 34\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec50337931c0dc4ba1afaf4a55886ae05ca73772
616,160
ipynb
Jupyter Notebook
Celebrity_Deaths.ipynb
TheCuriousScientist/Interactive-Plots--Celebrity-Deaths-EDA
cad0f62a5e7a6b43af3b0da3863436c019538d98
[ "MIT" ]
1
2017-10-18T18:16:23.000Z
2017-10-18T18:16:23.000Z
Celebrity_Deaths.ipynb
hetpsheth/Interactive-Plots--Celebrity-Deaths-EDA
cad0f62a5e7a6b43af3b0da3863436c019538d98
[ "MIT" ]
null
null
null
Celebrity_Deaths.ipynb
hetpsheth/Interactive-Plots--Celebrity-Deaths-EDA
cad0f62a5e7a6b43af3b0da3863436c019538d98
[ "MIT" ]
null
null
null
332.520237
158,051
0.872752
[ [ [ "This is my first attempt of using Plotly and creating some interactive graphs like some maps and charts. Not all the visuals are interactive as Plotly lacks some features. In order to see the interactivity, do move your cursor on the visuals.\n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.tools as tls\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.", "_____no_output_____" ], [ "deaths=pd.read_csv('../input/celebrity_deaths_4.csv',encoding='ISO-8859-1')", "_____no_output_____" ], [ "deaths.head(2) #checking the top 2 rows", "_____no_output_____" ], [ "deaths.isnull().sum() #checking for null values", "_____no_output_____" ] ], [ [ "A lot many null values can be seen in the**cause_of_death** column. We just can't drop it so we will rename it as **Unknown**.\n\nSimilarly we will rename the null values in **famous_for** as **Unknown**.", "_____no_output_____" ] ], [ [ "for i in deaths[['cause_of_death','famous_for','nationality']]: #checking for no of unique values\n print('number of Unique Values for ',i,'are:',deaths[i].nunique())", "number of Unique Values for cause_of_death are: 1722\nnumber of Unique Values for famous_for are: 18603\nnumber of Unique Values for nationality are: 496\n" ] ], [ [ "**Observations:**\n\n 1. A lot too many unique values for the **cause_of_death** column. As we had seen that it already has many null values. So the presence of so many unique values clearly states that many similar causes are named differently. Similar is the case with **famous_for**.\n 2. Total Countries comes out to be 496 that is impossible. I will Try to reduce the number without loosing any valuable data.\n\nA lot of cleaning has to be done for this dataset.", "_____no_output_____" ], [ "## A lot of Data Cleaning", "_____no_output_____" ] ], [ [ "deaths['cause_of_death'].fillna('unknown',inplace=True) #replacing the null values in cause_of_death and famous_for\ndeaths['famous_for'].fillna('unknown',inplace=True)\ndeaths.drop('fame_score',axis=1,inplace=True) #the fame_score was no use to me", "_____no_output_____" ] ], [ [ "I will be plotting few interactive maps. Thus the values in the nationality column has to be changed to the name of the countries for representing them on the maps. \n\nI will be replacing each value in the column one-by-one to the proper country name. I will do it manually as there was no other way of mapping them. Anyone with a better solution can please suggest.", "_____no_output_____" ] ], [ [ "deaths['nationality'].replace(['American','Canadian','German','British','Indian','Russian','Italian','French','Australian','English','Turkish','Irish','Israeli','Emirati','Jordanian','Indian-born','Korean','Syrian','Malaysian','Swedish','Bulgarian', 'Greek', 'Chilean', 'Finnish', 'Iraqi',\n 'Austrian','Bangladeshi','Norwegian','Brazilian','Japanese','Dutch','Spanish','Scottish','Polish','Mexican','New','Argentine','Hungarian','Filipino','Romanian','Chinese','Belgian','Danish','Iranian','Pakistani','Ukrainian','Indonesian','Columbian','Nigerian','Swiss','Sri','Thai','Cuban','Taiwanese', 'Jamaican','Serbian','Colombian','Egyptian','Peruvian','Kenyan','Vietnamese','Tanzanian','Soviet','Hong','Argentinian','Singaporean','Canadian-born','German-born','Polish-born','Trinidadian','Trinidad','Namibian','Nepali','Portuguese','U.S.','Tibetan','Nepalese','Croatian','Afghan','Turkish-born','Spanish-born','Azerbaijani','Soviet-born','Zambian', 'Ghanaian'],\n \n ['United States','Canada','Germany','United Kingdom','India','Russia','Italy','France','Australia','United Kingdom','Turkey','Ireland','Israel','United Arab Emirates','Jordan',\n 'India','Korea','Syria','Malaysia','Sweden','Bulgaria','Greece','Chile','Finland','Iraq','Austria','Bangladesh','Norway','Brazil','Japan','Netherlands','Spain','Scotland','Poland','Mexico','New Zealand','Argentina','Hungary','Philippines','Romania','China','Belgium','Denmark','Iran','Pakistan','Ukraine','Indonesia','Columbia','Nigeria','Switzerland','Sri Lanka','Thailand','Cuba','Taiwan','Jamaica','Serbia','Colombia','Egypt','Peru','Kenya','Vietnam','Tanzania','Russia','Hongkong','Argentina','Singapore','Canada','Germany','Poland','Trinidad & Tobago','Trinidad & Tobago','Namibia','Nepal','Protugal','United States','Tibet','Nepal','Croatia','Afghanistan','Turkey','Spain','Azerbaijan','Russia','Zambia','Ghana'],inplace=True)\nmask1 = deaths['nationality'] == 'South'\nmask2 = deaths['famous_for'].str.contains('Korean')\nmask3 = deaths['famous_for'].str.contains('Africa')\n\ndeaths.loc[mask1 & mask2, 'nationality']='South Korea'\ndeaths.loc[mask1 & mask3, 'nationality']='South Africa'", "_____no_output_____" ] ], [ [ "Since the **famous_for** column has many unique values, it indicates presence of many related terms. Like **business** and **entreprenuer** are counted different but the meanings are same. Also the values in the columns are not restricted to a single word. I have tried the best to manually find out similar and related terms do that they can be grouped together for better analysis.\n\n**Any better solution please suggest .**", "_____no_output_____" ] ], [ [ "mask1 = deaths['famous_for'].str.contains('business|Business|entrepreneur')\nmask2 = deaths['famous_for'].str.contains('Olympic|football|baseball|rugby|cricket|player|soccer|basketball|NFL|golf|hockey')\nmask3 = deaths['famous_for'].str.contains('music|Music|sing|Sing|musician|composer|song|Song')\nmask4 = deaths['famous_for'].str.contains('politician|minister|Politician|Minister|Parliament|parliament|Governor|governor|leader|Leader|council|Council|Assembly|Mayor|mayor')\nmask5 = deaths['famous_for'].str.contains('actor|Actor|actress|Actress|film|Film|cinema|screenwriter')\nmask6 = deaths['famous_for'].str.contains('author|Author')\nmask7 = deaths['famous_for'].str.contains('Engineer|engineer')\nmask8 = deaths['famous_for'].str.contains('Military|military|army|Army')\n\ndeaths.loc[True & mask1, 'famous_for']='Business'\ndeaths.loc[True & mask2, 'famous_for']='Sports'\ndeaths.loc[True & mask3, 'famous_for']='Music'\ndeaths.loc[True & mask4, 'famous_for']='Politics'\ndeaths.loc[True & mask5, 'famous_for']='Movies'\ndeaths.loc[True & mask6, 'famous_for']='Authors'\ndeaths.loc[True & mask7, 'famous_for']='Engineers'\ndeaths.loc[True & mask8, 'famous_for']='Military'\ndeaths['famous_for'].nunique()", "_____no_output_____" ] ], [ [ "So I have reduced the number of unique values from **18603** to **7905**. More than 50% of the **famous_for** column values can now be grouped together for better analysis.", "_____no_output_____" ] ], [ [ "deaths['age_category']='' #adding a age category for the celebs\nmask1=deaths['age']<18\nmask2=(deaths['age']>=18) & (deaths['age']<30)\nmask3=(deaths['age']>=30) & (deaths['age']<=60)\nmask4=deaths['age']>60\n\ndeaths.loc[True & mask1, 'age_category']='Children'\ndeaths.loc[True & mask2, 'age_category']='Young'\ndeaths.loc[True & mask3, 'age_category']='Middle-Age'\ndeaths.loc[True & mask4, 'age_category']='Old'", "_____no_output_____" ] ], [ [ "I haven't made any changes to the **cause_of_death** till now. First we will do some generalized analysis and then dig in more in the later part.\n\nFinally the cleaning part is done...:). Lets check the new dataframe.", "_____no_output_____" ] ], [ [ "deaths.head()", "_____no_output_____" ] ], [ [ "## Exploratory Analysis", "_____no_output_____" ], [ "### Distribution Of Ages", "_____no_output_____" ] ], [ [ "deaths['age'].hist(color='#ff0cd5')\nplt.axvline(deaths['age'].mean(),linestyle='dashed',color='blue')", "_____no_output_____" ] ], [ [ "It can be seen that the majority of the age of the people in the dataset are in the age bracket of (80-100) with the average being around 80.", "_____no_output_____" ], [ "### Number of Deaths by Years", "_____no_output_____" ] ], [ [ "data = [go.Bar(\n x=deaths['death_year'].value_counts().index,\n y=deaths['death_year'].value_counts().values,\n marker = dict(\n color = 'rgba(255, 0, 0,0.8)',)\n \n)]\n\npy.iplot(data, filename='horizontal-bar')", "_____no_output_____" ] ], [ [ "**Observations:**\n\n 1. The number of deaths has steadily increased since 2006.", "_____no_output_____" ], [ "### Top Causes Of Deaths", "_____no_output_____" ] ], [ [ "type_deaths=deaths[deaths['cause_of_death']!='unknown']\ntype_deaths=type_deaths['cause_of_death'].value_counts()[:10]\ndata = [go.Bar(\n x=type_deaths.index,\n y=type_deaths.values,\n marker = dict(\n color = 'rgba(190, 130, 30,0.8)',)\n \n)]\n\npy.iplot(data, filename='horizontal-bar')", "_____no_output_____" ] ], [ [ "**Observations:**\n\n 1. Cancer is the major cause for death followed by heart attacks.\n 2. As said earlier, there are different types of cancer which are not generalized into one. We will now group the related terms together to check the cumulative values.", "_____no_output_____" ] ], [ [ "deaths_2=deaths.copy()\n\ndeaths_2.loc[deaths_2.cause_of_death.str.contains('cancer|Cancer'),'cause_of_death']='Cancer'\ndeaths_2.loc[deaths_2.cause_of_death.str.contains('heart|Heart|Cardiac|cardiac'),'cause_of_death']='Heart Problems'\ndeaths_2.loc[deaths_2.cause_of_death.str.contains('brain|Brain|stroke'),'cause_of_death']='Brain Complications'\ndeaths_2.loc[deaths_2.cause_of_death.str.contains('Alzheimer|alzheimer'),'cause_of_death']='Alzheimers'\ndeaths_2.loc[deaths_2.cause_of_death.str.contains('Parkinson|parkinson'),'cause_of_death']='Parkinsons'\ndeaths_2.loc[deaths_2.cause_of_death.str.contains('Suicide|suicide'),'cause_of_death']='Suicide'\ndeaths_2.loc[deaths_2.cause_of_death.str.contains('accident|Accident|crash|collision'),'cause_of_death']='Accident'\ndeaths_2.loc[deaths_2.cause_of_death.str.contains('Shot|shot|murder|Murder'),'cause_of_death']='Murdered'", "_____no_output_____" ] ], [ [ "### Top Causes Of Death (after merging related values)", "_____no_output_____" ] ], [ [ "deaths_2=deaths_2[deaths_2['cause_of_death']!='unknown']\nindex=list(deaths_2['cause_of_death'].value_counts()[:10].index)\nvalues=list(deaths_2['cause_of_death'].value_counts()[:10].values)\n\ndata = [go.Bar(\n x=index,\n y=values,\n marker = dict(\n color = 'rgba(190, 130, 130,0.8)',)\n \n)]\n\npy.iplot(data, filename='horizontal-bar')", "_____no_output_____" ] ], [ [ "**Observations:**\n\n 1. Cancer still is the leading cause of death, but the number of death count has increased due to merging of different types of cancer into one.\n 2. We can now see some new entries like **Accidents, brain complications, etc** in the top deaths reasons which were not visible during the basic analysis.", "_____no_output_____" ], [ "### Causes Of Deaths By Years", "_____no_output_____" ] ], [ [ "dd1=deaths_2.groupby(['cause_of_death','death_year'])['death_month'].count().reset_index()\ndd1=dd1[dd1['cause_of_death'].isin(deaths_2['cause_of_death'].value_counts()[:10].index)]\ndd1.columns=[['cause','year','count']]\ndd1.pivot('year','cause','count').plot(marker='o',colormap='Paired')\nfig=plt.gcf()\nfig.set_size_inches(12,6)", "_____no_output_____" ] ], [ [ "We can see that how the deaths by Cancer and Heart Problems have steadily increased in the past few years.", "_____no_output_____" ], [ "### Countries with highest Deaths", "_____no_output_____" ] ], [ [ "data = [go.Bar(\n x=deaths['nationality'].value_counts()[:10].index,\n y=deaths['nationality'].value_counts()[:10].values,\n marker = dict(\n color = 'rgba(41, 221, 239,0.8)',)\n \n)]\n\npy.iplot(data, filename='horizontal-bar')", "_____no_output_____" ] ], [ [ "### Deaths By Countries by Year", "_____no_output_____" ] ], [ [ "top_countries=deaths['nationality'].value_counts()[:15]\nall_deaths=deaths['cause_of_death'].value_counts()\ncountries=deaths[deaths['nationality'].isin(top_countries.index)]\ncountries=countries[countries['cause_of_death'].isin(all_deaths.index)]\ncountries=countries[['cause_of_death','death_year','nationality']]\ncountries=countries.groupby(['nationality','death_year'])['cause_of_death'].count().reset_index()\ncountries.columns=[['nationality','death_year','count']]\ncountries=countries.pivot('nationality','death_year','count')\nsns.heatmap(countries,cmap='Set3',annot=True,fmt='2.0f',linewidths=0.4)\nplt.title('Total Deaths By Countries Per Year')\nfig=plt.gcf()\nfig.set_size_inches(12,12)", "_____no_output_____" ] ], [ [ "The above heatmap shows the number of deaths in the Top Countries by Year.", "_____no_output_____" ], [ "### Types Of Deaths By Famous_for ", "_____no_output_____" ] ], [ [ "_deaths=deaths[deaths['cause_of_death']!='unknown']\ntype_deaths=_deaths['cause_of_death'].value_counts()[:15]\ntype_deaths.index\ndeaths_1=deaths[deaths['famous_for'].isin(['Business','Sports','Politics','Movies','Authors','Engineers','Military','Music'])]\ndeaths_1=deaths_1[deaths_1['cause_of_death']!='unknown']\ndeaths_1=deaths_1[deaths_1['cause_of_death'].isin(type_deaths.index)] \ndeaths_1=deaths_1.groupby(['famous_for','cause_of_death'])['death_year'].count().reset_index()\ndeaths_1=deaths_1.pivot('famous_for','cause_of_death','death_year')\nsns.heatmap(deaths_1,cmap='RdYlGn',annot=True,fmt='2.0f',linewidths=0.2)\nfig=plt.gcf()\nfig.set_size_inches(15,6)", "_____no_output_____" ] ], [ [ "### Types of Deaths By Countries", "_____no_output_____" ] ], [ [ "_countries=deaths[deaths['cause_of_death']!='unknown']\n_countries=_deaths['nationality'].value_counts()[:10]\ndeaths_1=deaths[deaths['nationality'].isin(_countries.index)]\ndeaths_1=deaths_1[deaths_1['cause_of_death']!='unknown']\ndeaths_1=deaths_1[deaths_1['cause_of_death'].isin(type_deaths.index)] \ndeaths_1=deaths_1.groupby(['cause_of_death','nationality'])['death_year'].count().reset_index()\ndeaths_1=deaths_1.pivot('cause_of_death','nationality','death_year')\nsns.heatmap(deaths_1,cmap='RdYlGn',annot=True,fmt='2.0f',linewidths=0.2)\nfig=plt.gcf()\nfig.set_size_inches(8,8)", "_____no_output_____" ] ], [ [ "**Observations From Above Heatmaps:**\n\n 1. **Cancer** is the leading cause of deaths across the world irrespective of the countries or the profession.\n 2. Not every cause of death is that relevant in different countries. The blank spots show that disease like **leukemia** has not killed anyone in countries like **Germany, India** , etc. Similar is the case with some professions.", "_____no_output_____" ], [ "### GeoMap For Deaths By Countries\n\nI am completely new to Plotly which we will be using for drawing the Geomaps. A big thanks to [Anistropic][1] for helping with the geomaps. Do check his notebooks.\n\n\n [1]: https://www.kaggle.com/arthurtok", "_____no_output_____" ], [ "Geomaps take the input as Country Code for determining a country. I have thus mapped the countries to their country codes dor showing the total deaths in a country. ", "_____no_output_____" ] ], [ [ "l1=list(['Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Andorra',\n 'Angola', 'Anguilla', 'Antigua and Barbuda', 'Argentina', 'Armenia',\n 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas, The',\n 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize',\n 'Benin', 'Bermuda', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina',\n 'Botswana', 'Brazil', 'British Virgin Islands', 'Brunei',\n 'Bulgaria', 'Burkina Faso', 'Burma', 'Burundi', 'Cabo Verde',\n 'Cambodia', 'Cameroon', 'Canada', 'Cayman Islands',\n 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombia',\n 'Comoros', 'Congo, Democratic Republic of the',\n 'Congo, Republic of the', 'Cook Islands', 'Costa Rica',\n \"Cote d'Ivoire\", 'Croatia', 'Cuba', 'Curacao', 'Cyprus',\n 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica',\n 'Dominican Republic', 'Ecuador', 'Egypt', 'El Salvador',\n 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia',\n 'Falkland Islands (Islas Malvinas)', 'Faroe Islands', 'Fiji',\n 'Finland', 'France', 'French Polynesia', 'Gabon', 'Gambia, The',\n 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece', 'Greenland',\n 'Grenada', 'Guam', 'Guatemala', 'Guernsey', 'Guinea-Bissau',\n 'Guinea', 'Guyana', 'Haiti', 'Honduras', 'Hong Kong', 'Hungary',\n 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland',\n 'Isle of Man', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jersey',\n 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea, North',\n 'Korea, South', 'Kosovo', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia',\n 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein',\n 'Lithuania', 'Luxembourg', 'Macau', 'Macedonia', 'Madagascar',\n 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta',\n 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico',\n 'Micronesia, Federated States of', 'Moldova', 'Monaco', 'Mongolia',\n 'Montenegro', 'Morocco', 'Mozambique', 'Namibia', 'Nepal',\n 'Netherlands', 'New Caledonia', 'New Zealand', 'Nicaragua',\n 'Nigeria', 'Niger', 'Niue', 'Northern Mariana Islands', 'Norway',\n 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea',\n 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal',\n 'Puerto Rico', 'Qatar', 'Romania', 'Russia', 'Rwanda',\n 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Martin',\n 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines',\n 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia',\n 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore',\n 'Sint Maarten', 'Slovakia', 'Slovenia', 'Solomon Islands',\n 'Somalia', 'South Africa', 'South Sudan', 'Spain', 'Sri Lanka',\n 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria',\n 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Timor-Leste',\n 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey',\n 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine',\n 'United Arab Emirates', 'United Kingdom', 'United States',\n 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Vietnam',\n 'Virgin Islands', 'West Bank', 'Yemen', 'Zambia', 'Zimbabwe']) #Country names", "_____no_output_____" ], [ "l2=list(['AFG', 'ALB', 'DZA', 'ASM', 'AND', 'AGO', 'AIA', 'ATG', 'ARG',\n 'ARM', 'ABW', 'AUS', 'AUT', 'AZE', 'BHM', 'BHR', 'BGD', 'BRB',\n 'BLR', 'BEL', 'BLZ', 'BEN', 'BMU', 'BTN', 'BOL', 'BIH', 'BWA',\n 'BRA', 'VGB', 'BRN', 'BGR', 'BFA', 'MMR', 'BDI', 'CPV', 'KHM',\n 'CMR', 'CAN', 'CYM', 'CAF', 'TCD', 'CHL', 'CHN', 'COL', 'COM',\n 'COD', 'COG', 'COK', 'CRI', 'CIV', 'HRV', 'CUB', 'CUW', 'CYP',\n 'CZE', 'DNK', 'DJI', 'DMA', 'DOM', 'ECU', 'EGY', 'SLV', 'GNQ',\n 'ERI', 'EST', 'ETH', 'FLK', 'FRO', 'FJI', 'FIN', 'FRA', 'PYF',\n 'GAB', 'GMB', 'GEO', 'DEU', 'GHA', 'GIB', 'GRC', 'GRL', 'GRD',\n 'GUM', 'GTM', 'GGY', 'GNB', 'GIN', 'GUY', 'HTI', 'HND', 'HKG',\n 'HUN', 'ISL', 'IND', 'IDN', 'IRN', 'IRQ', 'IRL', 'IMN', 'ISR',\n 'ITA', 'JAM', 'JPN', 'JEY', 'JOR', 'KAZ', 'KEN', 'KIR', 'KOR',\n 'PRK', 'KSV', 'KWT', 'KGZ', 'LAO', 'LVA', 'LBN', 'LSO', 'LBR',\n 'LBY', 'LIE', 'LTU', 'LUX', 'MAC', 'MKD', 'MDG', 'MWI', 'MYS',\n 'MDV', 'MLI', 'MLT', 'MHL', 'MRT', 'MUS', 'MEX', 'FSM', 'MDA',\n 'MCO', 'MNG', 'MNE', 'MAR', 'MOZ', 'NAM', 'NPL', 'NLD', 'NCL',\n 'NZL', 'NIC', 'NGA', 'NER', 'NIU', 'MNP', 'NOR', 'OMN', 'PAK',\n 'PLW', 'PAN', 'PNG', 'PRY', 'PER', 'PHL', 'POL', 'PRT', 'PRI',\n 'QAT', 'ROU', 'RUS', 'RWA', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT',\n 'WSM', 'SMR', 'STP', 'SAU', 'SEN', 'SRB', 'SYC', 'SLE', 'SGP',\n 'SXM', 'SVK', 'SVN', 'SLB', 'SOM', 'ZAF', 'SSD', 'ESP', 'LKA',\n 'SDN', 'SUR', 'SWZ', 'SWE', 'CHE', 'SYR', 'TWN', 'TJK', 'TZA',\n 'THA', 'TLS', 'TGO', 'TON', 'TTO', 'TUN', 'TUR', 'TKM', 'TUV',\n 'UGA', 'UKR', 'ARE', 'GBR', 'USA', 'URY', 'UZB', 'VUT', 'VEN',\n 'VNM', 'VGB', 'WBG', 'YEM', 'ZMB', 'ZWE']) #Country Codes", "_____no_output_____" ], [ "df=pd.DataFrame(l1,l2)\ndf.reset_index(inplace=True)\ndf.columns=[['Code','Country']]", "_____no_output_____" ], [ "dea1=deaths.merge(df,left_on='nationality',right_on='Country',how='outer')\ndea1=dea1.groupby('Country')['death_year'].count().reset_index().sort_values(by='death_year',ascending=False)\ndea1=dea1.merge(df,left_on='Country',right_on='Country',how='right')\ndea2=dea1[dea1['death_year']!=0]\ndea2.columns=[['Country','Deaths_Count','Code']]\ndea2.shape", "_____no_output_____" ] ], [ [ "So I was able to filter out **71** countries from the **496** unique country names given in the original dataset. The original dataset had a lot of noisy data and also not every value was a country name. Some of the values were related.\n\nMajority of the values were based on what the people of a certain countries are known as . Like for **India** it was **Indians** ,etc. ", "_____no_output_____" ] ], [ [ "data = [ dict(\n type = 'choropleth',\n autocolorscale = False,\n colorscale = 'Viridis',\n reversescale = True,\n showscale = True,\n locations = dea2['Code'],\n z = dea2['Deaths_Count'],\n locationmode = 'Code',\n text = dea2['Country'].unique(),\n marker = dict(\n line = dict(color = 'rgb(200,200,200)', width = 0.5)),\n colorbar = dict(autotick = True, tickprefix = '', \n title = 'Deaths')\n )\n ]\n\nlayout = dict(\n title = 'Total Deaths By Country',\n geo = dict(\n showframe = True,\n showocean = True,\n oceancolor = 'rgb(0,0,0)',\n projection = dict(\n type = 'Mercator',\n \n ),\n ),\n )\nfig = dict(data=data, layout=layout)\npy.iplot(fig, validate=False, filename='worldmap2010')", "_____no_output_____" ] ], [ [ "Till Now we have just got a brief overview of the dataset.\n\nSome Observations like **Cancer** is the leading cause of death\n\n**USA** has the highest death toll, etc have been identified. Now we will try to dig in the dataset to find out more inferences.", "_____no_output_____" ], [ "## Deaths By Cancer\n\nAs we had already seen that Cancer was the major cause of deaths, we will try to do some deeper analysis.\n", "_____no_output_____" ], [ "### Different Types Of Cancer", "_____no_output_____" ] ], [ [ "deaths_cancer=deaths[deaths['cause_of_death'].str.contains('cancer')]\ndeaths_cancer=deaths_cancer.groupby(['cause_of_death'])['death_year'].count().reset_index()\ndeaths_cancer=deaths_cancer.sort_values(by='death_year',ascending=False)[1:15]\nsns.barplot(x='death_year',y='cause_of_death',data=deaths_cancer,palette='RdYlGn').set_title('Top Types Of Death Causing Cancer')\nplt.xlabel('Total Deaths')\nplt.ylabel('Type of cancer')\nfig=plt.gcf()\nfig.set_size_inches(8,6)\nplt.show()", "_____no_output_____" ] ], [ [ "As seen above, Lungs cancer is the major type of cancer causing the deaths followed by pancreatic cancer. ", "_____no_output_____" ] ], [ [ "deaths_2=deaths[deaths['cause_of_death'].isin(deaths_cancer['cause_of_death'])]\nabc=deaths_2.groupby(['cause_of_death','death_year'])['death_month'].count().reset_index()\ndeaths=deaths_2\nabc.columns=[['cancer_type','death year','Count']]\nabc=abc.pivot('death year','cancer_type','Count')\nabc.plot(marker='o',colormap='Paired_r')\nticks=range(2006,2017)\nfig=plt.gcf()\nfig.set_size_inches(12,8)\nplt.xticks(ticks)", "_____no_output_____" ] ], [ [ "The above graph clearly shows the **peaks** for **Lungs Cancer** ,**Pancreatic Cancer** and **Prostate Cancer**. The number of these types of cancer has been increasing in the past years. ", "_____no_output_____" ], [ "### Map for Deaths By Cancer", "_____no_output_____" ] ], [ [ "deaths_cancer=deaths.copy()\nmask1 = deaths_cancer['cause_of_death'].str.contains('cancer|Cancer')\ndeaths_cancer.loc[True & mask1, 'cause_of_death']='Cancer'\ndeaths_cancer=deaths_cancer[deaths_cancer['cause_of_death']==\"Cancer\"]\ndeaths_cancer=deaths_cancer.groupby(['nationality'])['death_year'].count().reset_index()\ndeaths_cancer=deaths_cancer.merge(df,left_on='nationality',right_on='Country',how='right')\ndeaths_cancer.dropna(inplace=True)\ndeaths_cancer=deaths_cancer[['nationality','death_year','Code']]\ndeaths_cancer.columns=[['Country','Count','Code']]\n\ndata = [ dict(\n type = 'choropleth',\n autocolorscale = False,\n colorscale = 'Viridis',\n reversescale = True,\n showscale = True,\n locations = deaths_cancer['Code'],\n z = deaths_cancer['Count'],\n locationmode = 'Code',\n text = deaths_cancer['Country'],\n marker = dict(\n line = dict(color = 'rgb(200,200,200)', width = 0.5)),\n colorbar = dict(autotick = True, tickprefix = '', \n title = 'Deaths')\n )\n ]\n\nlayout = dict(\n title = 'Total Deaths By Cancer',\n geo = dict(\n showframe = True,\n showocean = True,\n coastlines = True,\n oceancolor = 'rgb(0,0,0)',\n projection = dict(\n type = 'Mercator',\n \n ),\n ),\n )\nfig = dict(data=data, layout=layout)\npy.iplot(fig, validate=False, filename='worldmap2010')", "_____no_output_____" ] ], [ [ "### 2016 Death Analysis", "_____no_output_____" ], [ "As we had seen earlier that the number of deaths were highest in the year 2016. So let us check for some deeper insights.", "_____no_output_____" ], [ "### Checking the Countries", "_____no_output_____" ] ], [ [ "year2016=deaths[deaths['death_year']==2016]\nbefore2016=deaths[deaths['death_year']!=2016]\ndf1=year2016['nationality'].value_counts().reset_index()\ndf2=before2016['nationality'].value_counts().reset_index()\ndf1=df1.merge(df2,left_on='index',right_on='index',how='right')[1:17]\ndf1.columns=[['country','2016','before 2016']]", "_____no_output_____" ], [ "x=list(df1['country'].values)\ny=list(df1['before 2016'].values)\ny1=list(df1['2016'].values)\ntrace0 = go.Bar(\n x=x,\n y=y,\n name='Deaths before 2016',\n \n)\ntrace1 = go.Bar(\n x=x,\n y=y1,\n name='Deaths 2016',\n \n)\n\ndata = [trace0, trace1]\nlayout = go.Layout(\n xaxis=dict(tickangle=-45),\n barmode='stack',\n)\n\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig, filename='angled-text-bar')", "_____no_output_____" ] ], [ [ "**Hover** over the graph to see the values.\n\nSome interesting observations were for **China** and **New Zealand**. A lot many people died in these 2 countries as compared to the previous years. \n\nChina has almost 30% of its total deaths in 2016.", "_____no_output_____" ], [ "### Checking The Causes", "_____no_output_____" ] ], [ [ "year2016=deaths_2[deaths_2['death_year']==2016]\nbefore2016=deaths_2[deaths_2['death_year']!=2016]\ndf1=year2016['cause_of_death'].value_counts().reset_index()[1:]\ndf2=before2016['cause_of_death'].value_counts().reset_index()[1:]\ndf1=df1.merge(df2,left_on='index',right_on='index',how='right')[:10]\ndf1.columns=[['cause','2016','before 2016']]\n\nx=list(df1['cause'].values)\ny=list(df1['before 2016'].values)\ny1=list(df1['2016'].values)\ntrace0 = go.Bar(\n x=x,\n y=y,\n name='Deaths before 2016',\n marker=dict(\n color='rgb(158,225,225)',)\n \n)\ntrace1 = go.Bar(\n x=x,\n y=y1,\n name='Deaths 2016',\n \n)\n\ndata = [trace0, trace1]\nlayout = go.Layout(\n xaxis=dict(tickangle=-45),\n barmode='stack',\n)\n\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig, filename='angled-text-bar')", "_____no_output_____" ] ], [ [ "### Deaths By Countries in 2016", "_____no_output_____" ] ], [ [ "year2016=deaths[deaths['death_year']==2016]\ndea1=year2016.merge(df,left_on='nationality',right_on='Country',how='outer')\ndea1=dea1.groupby('Country')['death_year'].count().reset_index().sort_values(by='death_year',ascending=False)\ndea1=dea1.merge(df,left_on='Country',right_on='Country',how='right')\ndea2=dea1[dea1['death_year']!=0]\ndea2.columns=[['Country','Deaths_Count','Code']]\n\n\ndata = [ dict(\n type = 'choropleth',\n autocolorscale = False,\n colorscale = 'Viridis',\n reversescale = True,\n showscale = True,\n locations = dea2['Code'],\n z = dea2['Deaths_Count'],\n locationmode = 'Code',\n text = dea2['Country'].unique(),\n marker = dict(\n line = dict(color = 'rgb(200,200,200)', width = 0.5)),\n colorbar = dict(autotick = True, tickprefix = '', \n title = 'Deaths')\n )\n ]\n\nlayout = dict(\n title = 'Total Deaths By Country in 2016',\n geo = dict(\n showframe = True,\n showocean = True,\n oceancolor = 'rgb(0,255,255)',\n projection = dict(\n type = 'Mercator',\n \n ),\n ),\n )\nfig = dict(data=data, layout=layout)\npy.iplot(fig, validate=False, filename='worldmap2010')", "_____no_output_____" ] ], [ [ "### Stay Tuned", "_____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" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ec5037fc20d3f93d935605d9d5b5002b7a5acb45
21,778
ipynb
Jupyter Notebook
train_model.ipynb
Hemant2801/Diabetes-prediction
9c606494aa771e0dcd84125431fa59461d93bb8b
[ "MIT" ]
1
2021-12-03T09:17:44.000Z
2021-12-03T09:17:44.000Z
train_model.ipynb
Hemant2801/Diabetes-prediction
9c606494aa771e0dcd84125431fa59461d93bb8b
[ "MIT" ]
null
null
null
train_model.ipynb
Hemant2801/Diabetes-prediction
9c606494aa771e0dcd84125431fa59461d93bb8b
[ "MIT" ]
null
null
null
27.532238
113
0.405547
[ [ [ "#importing the necessary libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler", "_____no_output_____" ] ], [ [ "# Data collection and analysis", "_____no_output_____" ] ], [ [ "#lloading dataset\ndf = pd.read_csv('C:/Users/Hemant/jupyter_codes/ML Project 1/Diabetes detection/diabetes.csv')", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "#shape of the dataset\ndf.shape", "_____no_output_____" ], [ "#getting the statistical measure of the dataset\ndf.describe()", "_____no_output_____" ], [ "df['Outcome'].value_counts() #give the total count of different values in the column\n'''\n0 ----> non-diabetic\n1 ----> diabetic\n'''", "_____no_output_____" ], [ "#let us check the mean of the data across the outcome column\ndf.groupby('Outcome').mean()", "_____no_output_____" ], [ "#sepearting data and labels\nX = df.drop(columns = 'Outcome', axis = 1)\nY = df['Outcome']", "_____no_output_____" ] ], [ [ "Standardize the data", "_____no_output_____" ] ], [ [ "scaler = StandardScaler()\nstandardize_data = scaler.fit(X)\nstandardize_data = scaler.transform(X)", "_____no_output_____" ], [ "standardize_data", "_____no_output_____" ], [ "X = standardize_data\ny = df['Outcome']", "_____no_output_____" ] ], [ [ "split the data in training and testing data", "_____no_output_____" ] ], [ [ "x_train , x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, stratify = y, random_state = 2)", "_____no_output_____" ] ], [ [ "# TRAINING THE MODEL", "_____no_output_____" ] ], [ [ "classifier = svm.SVC(kernel = 'linear')", "_____no_output_____" ], [ "#training the SUPPORT VECTOR MACHINE CLASSIFIER\nclassifier.fit(x_train, y_train)", "_____no_output_____" ] ], [ [ "evaluating the model", "_____no_output_____" ] ], [ [ "#accuracy score on the training data\nx_train_predict = classifier.predict(x_train)\ntraining_data_accuracy = accuracy_score(x_train_predict, y_train)", "_____no_output_____" ], [ "print('ACCURAY SCORE OF THE TRAINING DATA : ', training_data_accuracy)", "ACCURAY SCORE OF THE TRAINING DATA : 0.7866449511400652\n" ], [ "#accuracy score on the testing data\nx_test_predict = classifier.predict(x_test)\ntest_data_accuracy = accuracy_score(x_test_predict, y_test)", "_____no_output_____" ], [ "print('ACCURAY SCORE OF THE TESTING DATA : ', test_data_accuracy)", "ACCURAY SCORE OF THE TESTING DATA : 0.7727272727272727\n" ] ], [ [ "# MAKING A PREDICTING SYSTEM", "_____no_output_____" ] ], [ [ "# input_data = input()\n# input_array = [float(i) for i in input_data.split(',')]\ninput_array = (0,137,40,35,168,43.1,2.288,33)\n#convert the input into numpy array\ninput_array = np.asarray(input_array)\n\n#reshape the array as we are predicting only on one instance\nreshaped_array = input_array.reshape(1, -1)\n\n#standardize the input data\nstd_data = scaler.transform(reshaped_array)\nprint(std_data)\n\n#prediction\nprediction = classifier.predict(std_data)\nprint(prediction)\nif prediction == 0:\n print('NON-DIABETIC')\nelse:\n print('DIABETIC')\n", "[[-1.14185152 0.5040552 -1.50468724 0.90726993 0.76583594 1.4097456\n 5.4849091 -0.0204964 ]]\n[1]\nDIABETIC\n" ] ], [ [ "# Saving the trained model", "_____no_output_____" ] ], [ [ "import pickle", "_____no_output_____" ], [ "name = 'Trained_model.sav'\npickle.dump(classifier, open(name, 'wb'))", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
ec505883f717a4b5efdd32d1c4880c287d07d9d6
5,265
ipynb
Jupyter Notebook
nb/eo_utils_example.ipynb
lsst-camera-dh/EO-utilities
28418284fdaf2b2fb0afbeccd4324f7ad3e676c8
[ "BSD-3-Clause-LBNL" ]
1
2019-05-21T22:40:20.000Z
2019-05-21T22:40:20.000Z
nb/eo_utils_example.ipynb
lsst-camera-dh/EO-utilities
28418284fdaf2b2fb0afbeccd4324f7ad3e676c8
[ "BSD-3-Clause-LBNL" ]
2
2018-01-26T18:59:05.000Z
2020-12-03T17:50:46.000Z
nb/eo_utils_example.ipynb
lsst-camera-dh/EO-utilities
28418284fdaf2b2fb0afbeccd4324f7ad3e676c8
[ "BSD-3-Clause-LBNL" ]
1
2018-01-11T22:50:35.000Z
2018-01-11T22:50:35.000Z
20.328185
283
0.523267
[ [ [ "%pylab inline\n#%matplotlib qt\nplt.ion()", "_____no_output_____" ], [ "from lsst.eo_utils import EOUtils\nfrom lsst.eo_utils import bias, flat, fe55\nfrom lsst.eo_utils.base import TableDict\neo = EOUtils()", "_____no_output_____" ] ], [ [ "### This gets the list of available Tasks", "_____no_output_____" ] ], [ [ "eo._task_factory.keys()", "_____no_output_____" ] ], [ [ "### This gets the arguments and defaults for a particular task", "_____no_output_____" ] ], [ [ "eo.get_task_defaults('BiasFFT')", "_____no_output_____" ] ], [ [ "### This sets up the options to run a task. \n\nNote that the \"runs\" and \"slots\" arguments are slightly different from the \"run\" and \"slot\" values above and that they take lists as input. This will iterate the task over requested runs and slots. Setting \"slots\" to None will loop over all the slots in the raft.", "_____no_output_____" ] ], [ [ "run_opts = dict(bias='spline', superbias='spline', raft='RTM-004', runs=['6106D'], slots=['S00'], nfiles=2)", "_____no_output_____" ] ], [ [ "### This runs the job", "_____no_output_____" ] ], [ [ "eo.run_task('BiasFFT', **run_opts)", "_____no_output_____" ] ], [ [ "### Here we are asking for the FITS file with the tables produced by the task that we just ran\n\nNote that in this case we are using \"run\" and \"slot\", because we want to get back a single file.", "_____no_output_____" ] ], [ [ "opts = dict(bias='spline', superbias='spline', raft='RTM-004', run='6106D', slot='S00')\ntf = eo.get_task_tablefile('BiasFFT', **opts) + '.fits'", "_____no_output_____" ] ], [ [ "### Open the file as a TableDict object\n\nThis is just a keyed set of astropy.table.Table objects", "_____no_output_____" ] ], [ [ "td = TableDict(tf)", "_____no_output_____" ] ], [ [ "### Get the names of the tables in the TableDict \n\nThis is the same as the names of the HDUs in the FITS file", "_____no_output_____" ] ], [ [ "td.keys()", "_____no_output_____" ] ], [ [ "### Get a particular table, using the name as a key", "_____no_output_____" ] ], [ [ "tab = td['biasfft-s']", "_____no_output_____" ] ], [ [ "### List the columns in the table\n\nIn this case the first column is a set of frequencies, and the rest are the FFT of the serial overscan by row", "_____no_output_____" ] ], [ [ "tab.columns", "_____no_output_____" ] ], [ [ "### Create a figure with matplotlib", "_____no_output_____" ] ], [ [ "fig = plt.figure()\nax = fig.add_subplot(111)\nax.set_xlabel('Frequency [Hz]')\nax.set_ylabel('Power [ADU]')", "_____no_output_____" ] ], [ [ "### Plot the FFT for amp 0", "_____no_output_____" ] ], [ [ "ax.plot(tab['freqs'], tab['fftpow_S00_a00'])", "_____no_output_____" ], [ "fig.show()", "_____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" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
ec505de5b435b7e2f1218b2eb0a09c27b3d33ba6
26,213
ipynb
Jupyter Notebook
docs/examples/mab-thompson-sampling-tempo/README.ipynb
outerbounds/tempo
0878ae32ed6163a1c5115f20167d991a28535364
[ "Apache-2.0" ]
75
2021-02-15T09:49:02.000Z
2022-03-31T02:06:38.000Z
docs/examples/mab-thompson-sampling-tempo/README.ipynb
outerbounds/tempo
0878ae32ed6163a1c5115f20167d991a28535364
[ "Apache-2.0" ]
106
2021-02-13T09:25:19.000Z
2022-03-25T16:18:00.000Z
docs/examples/mab-thompson-sampling-tempo/README.ipynb
outerbounds/tempo
0878ae32ed6163a1c5115f20167d991a28535364
[ "Apache-2.0" ]
21
2021-02-12T17:12:50.000Z
2022-03-04T02:09:26.000Z
24.752597
175
0.521993
[ [ [ "# Multi-Armed Bandit with State", "_____no_output_____" ] ], [ [ "import logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nlogging.info(\"test\")", "INFO:root:test\n" ], [ "!kaggle datasets download -d uciml/default-of-credit-card-clients-dataset\n!unzip -o default-of-credit-card-clients-dataset.zip", "Downloading default-of-credit-card-clients-dataset.zip to /home/alejandro/Programming/kubernetes/seldon/tempo/docs/examples/mab-thompson-sampling-tempo\n100%|██████████████████████████████████████| 0.98M/0.98M [00:00<00:00, 2.16MB/s]\n100%|██████████████████████████████████████| 0.98M/0.98M [00:00<00:00, 2.15MB/s]\nArchive: default-of-credit-card-clients-dataset.zip\n inflating: UCI_Credit_Card.csv \n" ], [ "!mkdir -p artifacts/mab/\n!mkdir -p artifacts/mab/route/\n!mkdir -p artifacts/mab/feedback/", "_____no_output_____" ], [ "import pandas as pd\ndata = pd.read_csv('UCI_Credit_Card.csv')", "_____no_output_____" ], [ "target = 'default.payment.next.month'", "_____no_output_____" ], [ "import numpy as np\nfrom sklearn.model_selection import train_test_split\n\nOBSERVED_DATA = 15000\nTRAIN_1 = 10000\nTEST_1 = 5000\n\nREST_DATA = 15000\n\nRUN_DATA = 5000\nROUTE_DATA = 10000\n\n# get features and target\nX = data.loc[:, data.columns!=target].values\ny = data[target].values\n\n# observed/unobserved split\nX_obs, X_rest, y_obs, y_rest = train_test_split(X, y, random_state=1, test_size=REST_DATA)\n\n# observed split into train1/test1\nX_train1, X_test1, y_train1, y_test1 = train_test_split(X_obs, y_obs, random_state=1, test_size=TEST_1)\n\n# unobserved split into run/route\nX_run, X_route, y_run, y_route = train_test_split(X_rest, y_rest, random_state=1, test_size=ROUTE_DATA)\n\n# observed+run split into train2/test2\nX_rest = np.vstack((X_run, X_route))\ny_rest = np.hstack((y_run, y_route))\n\nX_train2 = np.vstack((X_train1, X_test1))\nX_test2 = X_run\n\ny_train2 = np.hstack((y_train1, y_test1))\ny_test2 = y_run", "_____no_output_____" ], [ "from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(random_state=1)\nrf.fit(X_train1, y_train1)", "_____no_output_____" ], [ "from xgboost import XGBClassifier\nxgb = XGBClassifier(random_state=1)\nxgb.fit(X_train2, y_train2)", "INFO:numexpr.utils:Note: NumExpr detected 16 cores but \"NUMEXPR_MAX_THREADS\" not set, so enforcing safe limit of 8.\nINFO:numexpr.utils:NumExpr defaulting to 8 threads.\n" ], [ "!mkdir -p artifacts/mab/sklearn/\n!mkdir -p artifacts/mab/xgboost/", "_____no_output_____" ], [ "import joblib\njoblib.dump(rf, 'artifacts/mab/sklearn/model.joblib')", "_____no_output_____" ], [ "xgb.save_model('artifacts/mab/xgboost/model.bst')", "_____no_output_____" ], [ "import os\nfrom tempo.serve.model import Model\nfrom tempo.serve.metadata import ModelFramework\n\nsklearn_tempo = Model(\n name=\"test-iris-sklearn\",\n platform=ModelFramework.SKLearn,\n uri=\"gs://seldon-models/mab/sklearn\",\n local_folder=os.getcwd()+\"/artifacts/mab/sklearn\")\n\nxgboost_tempo = Model(\n name=\"test-iris-xgboost\",\n platform=ModelFramework.XGBoost,\n uri=\"gs://seldon-models/mab/xgboost\",\n local_folder=os.getcwd()+\"/artifacts/mab/xgboost/\")", "INFO:tempo:Initialising Insights Manager with Args: ('', 1, 1, 3, 0)\nWARNING:tempo:Insights Manager not initialised as empty URL provided.\nINFO:tempo:Initialising Insights Manager with Args: ('', 1, 1, 3, 0)\nWARNING:tempo:Insights Manager not initialised as empty URL provided.\n" ], [ "from tempo import deploy_local\nremote_sklearn = deploy_local(sklearn_tempo)\nremote_xgboost = deploy_local(xgboost_tempo)", "_____no_output_____" ], [ "remote_sklearn.predict(X_test2[0:1])", "_____no_output_____" ], [ "remote_xgboost.predict(X_test2[0:1])", "_____no_output_____" ], [ "from tempo.docker.utils import deploy_redis\n\ndeploy_redis()", "_____no_output_____" ], [ "import logging\n\nimport numpy as np\nfrom tempo.serve.utils import pipeline, predictmethod\nfrom tempo.serve.metadata import InsightRequestModes, SeldonCoreOptions, StateTypes\nfrom tempo.serve.constants import DefaultRedisLocalHost, DefaultRedisPort, DefaultRedisK8sHost\nfrom tempo.serve.pipeline import PipelineModels\n\nfrom tempo.magic import t\n\nruntime_options = SeldonCoreOptions(**{\n \"local_options\": {\n \"state_options\": {\n \"state_type\": StateTypes.REDIS,\n \"host\": DefaultRedisLocalHost,\n \"port\": DefaultRedisPort,\n }\n },\n \"remote_options\": {\n \"state_options\": {\n \"state_type\": StateTypes.REDIS,\n \"host\": DefaultRedisK8sHost,\n \"port\": DefaultRedisPort,\n }\n }\n})\n\n@pipeline(name=\"mab-router\",\n runtime_options=runtime_options.local_options,\n uri=\"s3://tempo/mab/route\",\n local_folder=os.getcwd()+\"/artifacts/mab/router/\",\n models=PipelineModels(sklearn=sklearn_tempo, xgboost=xgboost_tempo))\nclass MABRouter(object):\n\n def __init__(self):\n self.n_branches = 2\n self.beta_params = [1 for _ in range(self.n_branches * 2)]\n \n logging.info(f\"Setting up MAB routing pipeline\")\n \n self._key = \"beta_params\"\n \n @predictmethod\n def predict(self, payload: np.ndarray) -> np.ndarray:\n \n if not t.state.exists(self._key):\n models_beta_params = [1 for _ in range(self.n_branches * 2)]\n t.state.internal_state.lpush(self._key, *models_beta_params)\n \n models_beta_params = [float(i) for i in t.state.internal_state.lrange(self._key, 0, -1)]\n branch_values = [np.random.beta(a, b) for a, b in zip(*[iter(models_beta_params)] * 2)]\n selected_branch = np.argmax(branch_values)\n logging.info(f\"routing to branch: {selected_branch}\")\n \n if selected_branch:\n return self.models.xgboost(payload)\n else:\n return self.models.sklearn(payload)", "INFO:tempo:Initialising Insights Manager with Args: ('', 1, 1, 3, 0)\nWARNING:tempo:Insights Manager not initialised as empty URL provided.\n" ], [ "mab_router = MABRouter()", "INFO:root:Setting up MAB routing pipeline\n" ], [ "for i in range(10):\n print(mab_router.predict(X_test2[0:1]))", "INFO:root:routing to branch: 1\nINFO:root:routing to branch: 1\nINFO:root:routing to branch: 1\nINFO:root:routing to branch: 0\nINFO:root:routing to branch: 0\nINFO:root:routing to branch: 0\n" ], [ "from IPython.core.magic import register_line_cell_magic\n\n@register_line_cell_magic\ndef writetemplate(line, cell):\n with open(line, 'w') as f:\n f.write(cell.format(**globals()))", "_____no_output_____" ], [ "import os\n\nTEMPO_DIR = os.path.abspath(os.path.join(os.getcwd(), '..', '..', '..'))", "_____no_output_____" ], [ "!mkdir -p artifacts/mab/router/", "_____no_output_____" ], [ "%%writetemplate artifacts/mab/router/conda.yaml\nname: tempo-insights\nchannels:\n - defaults\ndependencies:\n - pip=21.0.1\n - python=3.7.9\n - pip:\n - mlops-tempo @ file://{TEMPO_DIR}\n - mlserver==0.3.1.dev7", "_____no_output_____" ], [ "from tempo.serve.loader import save\nsave(MABRouter, save_env=True)", "INFO:tempo:Initialising Insights Manager with Args: ('', 1, 1, 3, 0)\nWARNING:tempo:Insights Manager not initialised as empty URL provided.\nINFO:tempo:Initialising Insights Manager with Args: ('', 1, 1, 3, 0)\nWARNING:tempo:Insights Manager not initialised as empty URL provided.\nINFO:tempo:Saving environment\nINFO:tempo:Saving tempo model to /home/alejandro/Programming/kubernetes/seldon/tempo/docs/examples/mab-thompson-sampling-tempo/artifacts/mab/router/model.pickle\n" ], [ "from tempo import deploy_local\nfrom tempo.serve.constants import DefaultRedisDockerHost\n\nruntime_options.local_options.state_options.host = DefaultRedisDockerHost\n\nremote_mab_router = deploy_local(mab_router, runtime_options)", "_____no_output_____" ], [ "for i in range(10):\n print(remote_mab_router.predict(X_test2[0:1]))", "[0]\n[0.0865844]\n[0.0865844]\n[0]\n[0.0865844]\n[0]\n[0]\n[0.0865844]\n[0]\n[0.0865844]\n" ], [ "@pipeline(name=\"mab-feedback\",\n runtime_options=runtime_options.local_options,\n uri=\"s3://tempo/mab/feedback\",\n local_folder=os.getcwd()+\"/artifacts/mab/feedback/\")\nclass MABFeedback(object):\n\n def __init__(self):\n self._key = \"beta_params\"\n\n @predictmethod\n def predict(self, payload: np.ndarray, parameters: dict) -> np.ndarray:\n \n logging.info(f\"Feedback method with truth {payload} and parameters {parameters}\")\n \n reward = parameters[\"reward\"]\n routing = parameters[\"routing\"]\n\n logging.info(f\"Sending feedback with route {routing} reward {reward}\")\n \n # Currently only support 1 feedback at a time\n n_predictions = 1\n n_success = int(reward * n_predictions)\n n_failures = n_predictions - n_success\n \n logging.info(f\"n_success: {n_success}, n_failures: {n_failures}\")\n\n # Non atomic, race condition op\n logging.info(f\"LINDEX key {self._key} on index {routing*2}\")\n success_val = float(t.state.internal_state.lindex(self._key, int(routing*2)))\n t.state.internal_state.lset(self._key, int(routing*2), str(success_val + n_success))\n fail_val = float(t.state.internal_state.lindex(self._key, int(routing*2 + 1)))\n t.state.internal_state.lset(self._key, int(routing*2 + 1), str(fail_val + n_failures))\n \n return np.array([n_success, n_failures])\n ", "INFO:tempo:Initialising Insights Manager with Args: ('', 1, 1, 3, 0)\nWARNING:tempo:Insights Manager not initialised as empty URL provided.\n" ], [ "mab_feedback = MABFeedback()", "_____no_output_____" ] ], [ [ "### Deploy Feedback Pipeline", "_____no_output_____" ] ], [ [ "%%writetemplate artifacts/mab/feedback/conda.yaml\nname: tempo-insights\nchannels:\n - defaults\ndependencies:\n - pip=21.0.1\n - python=3.7.9\n - pip:\n - mlops-tempo @ file://{TEMPO_DIR}\n - mlserver==0.3.1.dev7", "_____no_output_____" ], [ "save(MABFeedback, save_env=True)", "INFO:tempo:Saving environment\nINFO:tempo:Saving tempo model to /home/alejandro/Programming/kubernetes/seldon/tempo/docs/examples/mab-thompson-sampling-tempo/artifacts/mab/feedback/model.pickle\n" ], [ "remote_mab_feedback = deploy_local(mab_feedback, runtime_options)", "_____no_output_____" ] ], [ [ "## Send feedback showing that route sklearn model performs better", "_____no_output_____" ] ], [ [ "for i in range(10):\n print(remote_mab_feedback.predict(payload=X_rest[0:1], parameters={ \"reward\": 1, \"routing\": 0}))", "[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n" ] ], [ [ "## See now most requests being sent to sklearn model", "_____no_output_____" ] ], [ [ "for i in range(10):\n print(remote_mab_router.predict(X_test2[0:1]))", "[0]\n[0]\n[0]\n[0]\n[0]\n[0]\n[0]\n[0]\n[0]\n[0]\n" ] ], [ [ "### Now send 20 positive requests showing xgboost performing better", "_____no_output_____" ] ], [ [ "for i in range(20):\n print(remote_mab_feedback.predict(payload=X_rest[0:1], parameters={ \"reward\": 1, \"routing\": 1}))", "[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n[1 0]\n" ] ], [ [ "### We should now see the xgboost model receiving most requests", "_____no_output_____" ] ], [ [ "for i in range(10):\n print(remote_mab_router.predict(X_test2[0:1]))", "[0]\n[0.0865844]\n[0]\n[0.0865844]\n[0.0865844]\n[0.0865844]\n[0]\n[0.0865844]\n[0]\n[0.0865844]\n" ] ], [ [ "### Clean up Docker", "_____no_output_____" ] ], [ [ "remote_mab_router.undeploy()\nremote_mab_feedback.undeploy()", "INFO:tempo:Undeploying mab-router\nINFO:tempo:Undeploying test-iris-sklearn\nINFO:tempo:Undeploying test-iris-xgboost\nINFO:tempo:Undeploying mab-feedback\n" ], [ "from tempo.docker.utils import undeploy_redis\nundeploy_redis()", "_____no_output_____" ] ], [ [ "## Deploy to Kubernetes", "_____no_output_____" ] ], [ [ "!kubectl apply -f k8s/rbac -n default", "secret/minio-secret configured\r\nserviceaccount/tempo-pipeline unchanged\r\nrole.rbac.authorization.k8s.io/tempo-pipeline unchanged\r\nrolebinding.rbac.authorization.k8s.io/tempo-pipeline-rolebinding unchanged\r\n" ], [ "from tempo.examples.minio import create_minio_rclone\nimport os\ncreate_minio_rclone(os.getcwd()+\"/rclone.conf\")", "_____no_output_____" ], [ "from tempo.serve.loader import upload\nupload(mab_router)\nupload(mab_feedback)", "INFO:tempo:Uploading /home/alejandro/Programming/kubernetes/seldon/tempo/docs/examples/mab-thompson-sampling-tempo/artifacts/mab/router/ to s3://tempo/mab/route\nINFO:tempo:Uploading /home/alejandro/Programming/kubernetes/seldon/tempo/docs/examples/mab-thompson-sampling-tempo/artifacts/mab/feedback/ to s3://tempo/mab/feedback\n" ], [ "from tempo.k8s.utils import deploy_redis\n\ndeploy_redis()", "_____no_output_____" ], [ "runtime_options.remote_options.authSecretName = \"minio-secret\"\nprint(runtime_options.remote_options.authSecretName)", "minio-secret\n" ], [ "from tempo import deploy_remote\nk8s_mab_router = deploy_remote(mab_router, options=runtime_options)\nk8s_mab_feedback = deploy_remote(mab_feedback, options=runtime_options)", "_____no_output_____" ], [ "k8s_mab_router.predict(payload=X_rest[0:1])", "_____no_output_____" ], [ "k8s_mab_feedback.predict(payload=X_rest[0:1], parameters={\"reward\":0.0,\"routing\":0} )", "_____no_output_____" ], [ "k8s_mab_router.undeploy()\nk8s_mab_feedback.undeploy()", "_____no_output_____" ] ] ]
[ "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", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec50630938a77c7fc4d241084d169713f585a044
162,920
ipynb
Jupyter Notebook
PGDAV | Delhi | Data Science | 24-28 Jan | 2022/Day_3.ipynb
teenage-coder/Workshops
1bd5d6068e8f5d0df124bd2f4c66ce68509e3cbd
[ "Apache-2.0" ]
2
2022-01-25T09:45:15.000Z
2022-01-26T06:06:03.000Z
PGDAV | Delhi | Data Science | 24-28 Jan | 2022/Day_3.ipynb
teenage-coder/Workshops
1bd5d6068e8f5d0df124bd2f4c66ce68509e3cbd
[ "Apache-2.0" ]
1
2022-01-25T07:14:46.000Z
2022-01-25T07:14:46.000Z
PGDAV | Delhi | Data Science | 24-28 Jan | 2022/Day_3.ipynb
teenage-coder/Workshops
1bd5d6068e8f5d0df124bd2f4c66ce68509e3cbd
[ "Apache-2.0" ]
2
2022-01-26T12:19:47.000Z
2022-01-27T13:43:54.000Z
66.880131
39,350
0.61799
[ [ [ "import pandas as pd", "_____no_output_____" ], [ "df = pd.read_csv('googleplaystore.csv').dropna()", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "del df['Last Updated']\ndel df['Current Ver']\ndel df['Android Ver']", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "round(df['Rating'].sum() / len(df['Rating']), 2)", "_____no_output_____" ], [ "s = 0\n\nfor i in df['Reviews']:\n s += int(i)\n \nprint(int(s/len(df)))", "514376\n" ], [ "s = 0\n\nfor i in df['Category']:\n if (i == 'ART_AND_DESIGN'):\n s += 1\n \nprint(s)", "61\n" ], [ "s = 0\n\nfor i in df['Category']:\n if (i == 'FAMILY'):\n s += 1\n \nprint(s)", "1746\n" ], [ "df['Category'].unique()", "_____no_output_____" ], [ "for category in df['Category'].unique():\n\n s = 0\n for i in df['Category']:\n if (i == category):\n s += 1\n \n print(category,\":\", s)", "ART_AND_DESIGN : 61\nAUTO_AND_VEHICLES : 73\nBEAUTY : 42\nBOOKS_AND_REFERENCE : 178\nBUSINESS : 303\nCOMICS : 58\nCOMMUNICATION : 328\nDATING : 195\nEDUCATION : 155\nENTERTAINMENT : 149\nEVENTS : 45\nFINANCE : 323\nFOOD_AND_DRINK : 109\nHEALTH_AND_FITNESS : 297\nHOUSE_AND_HOME : 76\nLIBRARIES_AND_DEMO : 64\nLIFESTYLE : 314\nGAME : 1097\nFAMILY : 1746\nMEDICAL : 350\nSOCIAL : 259\nSHOPPING : 238\nPHOTOGRAPHY : 317\nSPORTS : 319\nTRAVEL_AND_LOCAL : 226\nTOOLS : 733\nPERSONALIZATION : 312\nPRODUCTIVITY : 351\nPARENTING : 50\nWEATHER : 75\nVIDEO_PLAYERS : 160\nNEWS_AND_MAGAZINES : 233\nMAPS_AND_NAVIGATION : 124\n" ], [ "df['Type'].unique()", "_____no_output_____" ], [ "s = 0\nfor i in df['Type']:\n if (i == 'Free'):\n s += 1\nprint(s)", "8715\n" ], [ "s = 0\nfor i in df['Type']:\n if (i == 'Paid'):\n s += 1\nprint(s)", "645\n" ], [ "df['Price'].unique()", "_____no_output_____" ], [ "df['Content Rating'].unique()", "_____no_output_____" ], [ "for category in df['Content Rating'].unique():\n\n s = 0\n for i in df['Content Rating']:\n if (i == category):\n s += 1\n \n print(category,\":\", s)", "Everyone : 7414\nTeen : 1084\nEveryone 10+ : 397\nMature 17+ : 461\nAdults only 18+ : 3\nUnrated : 1\n" ], [ "d = df.values", "_____no_output_____" ], [ "d[0]", "_____no_output_____" ], [ "s = 0\n\nfor i in range(len(d)):\n if(d[i][1] == 'ART_AND_DESIGN' and d[i][2] > 4.5):\n print(d[i][0])\n s += 1", "U Launcher Lite – FREE Live Cool Themes, Hide Apps\nKids Paint Free - Drawing Fun\nMandala Coloring Book\nPhoto Designer - Write your name with shapes\nibis Paint X\nSuperheroes Wallpapers | 4K Backgrounds\nHD Mickey Minnie Wallpapers\nHarley Quinn wallpapers HD\nColorfit - Drawing & Coloring\nI Creative Idea\nUNICORN - Color By Number & Pixel Art Coloring\nPIP Camera - PIP Collage Maker\nCanva: Poster, banner, card maker & graphic design\nInstall images with music to make video without Net - 2018\nCardi B Wallpaper\nX Launcher: With OS11 Style Theme & Control Center\nX Launcher Pro: PhoneX Theme, OS11 Control Center\nX Launcher Pro - IOS Style Theme & Control Center\nX Launcher Prime: With OS Style Theme & No Ads\nAJ Styles HD Wallpapers\nFantasy theme dark bw black building\nSpring flowers theme couleurs d t space\n" ] ], [ [ "# Q1). How many apps are there in GAME?", "_____no_output_____" ] ], [ [ "df_pr = df[df['Category'] == 'GAME']\nlen(df_pr[df_pr['Type'] == 'Free'])", "_____no_output_____" ] ], [ [ "# Q2) How many paid apps are there in Shopping?", "_____no_output_____" ] ], [ [ "df_pr = df[df['Category'] == 'SHOPPING']\ndf_pr[df_pr['Type'] == 'Paid']", "_____no_output_____" ] ], [ [ "# Q3) How many free apps are there in BEAUTY and having rating more than 4.5?", "_____no_output_____" ] ], [ [ "df_pr = df[df['Category'] == 'BEAUTY']\ndf_pr = df_pr[df_pr['Type'] == 'Free']\nlen(df_pr[df_pr['Rating'] > 4.5])", "_____no_output_____" ] ], [ [ "# Q4) Which category is having most number of paid apps?", "_____no_output_____" ] ], [ [ "lst = []\n\nfor i in df['Category'].unique():\n\n df_pr = df[df['Category'] == i]\n df_pr = df_pr[df_pr['Type'] == 'Paid']\n\n lst.append([i, len(df_pr)])", "_____no_output_____" ], [ "df_pr = pd.DataFrame(lst, columns = ['Category', 'Qn']).sort_values(by = 'Qn', ascending = False)", "_____no_output_____" ], [ "df_pr.plot(kind = 'bar')", "_____no_output_____" ], [ "df_pr", "_____no_output_____" ] ], [ [ "# Q5) How many Paid apps are there in SOCIAL category and Teen Content Rating?", "_____no_output_____" ] ], [ [ "df_pr = df[df['Category'] == 'SOCIAL']\ndf_pr = df_pr[df_pr['Type'] == 'Paid']\ndf_pr = df_pr[df_pr['Content Rating'] == 'Teen']\n\ndf_pr", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.groupby('Category')['Rating'].mean()", "_____no_output_____" ], [ "df.groupby('Category').size().sort_values().plot(kind = 'bar', figsize = (10,6))", "_____no_output_____" ], [ "df.groupby('Type').size().plot(kind = 'pie', autopct = \"%0.1f\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.groupby('Content Rating').size().sort_values(ascending = False).plot(kind = 'pie')", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "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", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec5083f3eb1c9cdd96c7fa951b64acde7268f243
26,116
ipynb
Jupyter Notebook
2-python packages/Top 3 NLP Libraries Tutorial.ipynb
Type-1aSN/10-steps-to-become-a-data-scientist
0fab2bf3ce7d813b08da322f9f03dc4699143f99
[ "Apache-2.0" ]
4
2019-04-15T09:40:20.000Z
2019-11-17T01:44:08.000Z
2-python packages/Top 3 NLP Libraries Tutorial.ipynb
htbkoo/10-steps-to-become-a-data-scientist
f432c04d046b4abd05833de6f046e7d404a246b3
[ "Apache-2.0" ]
null
null
null
2-python packages/Top 3 NLP Libraries Tutorial.ipynb
htbkoo/10-steps-to-become-a-data-scientist
f432c04d046b4abd05833de6f046e7d404a246b3
[ "Apache-2.0" ]
3
2019-02-13T08:40:45.000Z
2019-07-11T21:20:35.000Z
46.635714
1,232
0.610124
[ [ [ "# <div style=\"text-align: center\">Top 3 NLP Libraries Tutorial</div>\n\n### <div style=\"text-align: center\">Quite Practical and Far from any Theoretical Concepts</div>\n<img src='https://chengotto.com/wp-content/uploads/2018/02/images.duckduckgo2-600x338.jpg'>\n<div style=\"text-align:center\">last update: <b>11/22/2018</b></div>\n\n\n>###### you may be interested have a look at it: [**The Data Scientist’s Toolbox Tutorial - 1**](https://www.kaggle.com/mjbahmani/the-data-scientist-s-toolbox-tutorial-1)\n\n\n---------------------------------------------------------------------\nyou can Fork and Run this kernel on Github:\n> ###### [ GitHub](https://github.com/mjbahmani/10-steps-to-become-a-data-scientist)\n\n-------------------------------------------------------------------------------------------------------------\n\n **I hope you find this kernel helpful and some <font color=\"red\"><b>UPVOTES</b></font> would be very much appreciated**\n \n -----------", "_____no_output_____" ], [ " <a id=\"top\"></a> <br>\n## Notebook Content\n1. [Introduction](#1)\n 1. [Import](#2)\n 1. [Version](#3)\n1. [NLTK](#38)\n 1. [Tokenizing sentences](#39)\n 1. [NLTK and arrays](#40)\n 1. [NLTK stop words](#41)\n 1. [NLTK – stemming](#42)\n 1. [NLTK speech tagging](#43)\n 1. [Natural Language Processing – prediction](#44)\n 1. [nlp prediction example](#45)\n1. [Read more](#46)\n1. [conclusion](#47)\n1. [References](#48)", "_____no_output_____" ], [ "<a id=\"1\"></a> <br>\n# 1-Introduction\nThis Kernel is mostly for **beginners**, and of course, all **professionals** who think they need to review their knowledge.\nAlso, this is the second version for ( [The Data Scientist’s Toolbox Tutorial - 1](https://www.kaggle.com/mjbahmani/the-data-scientist-s-toolbox-tutorial-1) ) and we will continue with other important packages in this kernel.keep following!", "_____no_output_____" ], [ "<a id=\"2\"></a> <br>\n## 1-1 Import", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nfrom pandas import get_dummies\nimport plotly.graph_objs as go\nfrom sklearn import datasets\nfrom sklearn.svm import SVC\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport warnings\nimport sklearn\nimport scipy\nimport numpy\nimport json\nimport nltk\nimport sys\nimport csv\nimport os", "_____no_output_____" ] ], [ [ "<a id=\"3\"></a> <br>\n## 1-2 Version", "_____no_output_____" ] ], [ [ "print('matplotlib: {}'.format(matplotlib.__version__))\nprint('scipy: {}'.format(scipy.__version__))\nprint('seaborn: {}'.format(sns.__version__))\nprint('pandas: {}'.format(pd.__version__))\nprint('numpy: {}'.format(np.__version__))\nprint('Python: {}'.format(sys.version))", "_____no_output_____" ] ], [ [ "## 1-3 Setup\n\nA few tiny adjustments for better **code readability**", "_____no_output_____" ] ], [ [ "sns.set(style='white', context='notebook', palette='deep')\nwarnings.filterwarnings('ignore')\nsns.set_style('white')\n%matplotlib inline", "_____no_output_____" ] ], [ [ "\n", "_____no_output_____" ], [ "<a id=\"38\"></a> <br>\n# 2- NLTK\nThe Natural Language Toolkit (NLTK) is one of the leading platforms for working with human language data and Python, the module NLTK is used for natural language processing. NLTK is literally an acronym for Natural Language Toolkit. with it you can tokenizing words and sentences.\nNLTK is a library of Python that can mine (scrap and upload data) and analyse very large amounts of textual data using computational methods.\n<img src='https://arts.unimelb.edu.au/__data/assets/image/0005/2735348/nltk.jpg'>", "_____no_output_____" ] ], [ [ "from nltk.tokenize import sent_tokenize, word_tokenize\n \ndata = \"All work and no play makes jack a dull boy, all work and no play\"\nprint(word_tokenize(data))", "_____no_output_____" ] ], [ [ "<a id=\"39\"></a> <br>\nAll of them are words except the comma. Special characters are treated as separate tokens.\n\n## 2-1 Tokenizing sentences\nThe same principle can be applied to sentences. Simply change the to sent_tokenize()\nWe have added two sentences to the variable data:", "_____no_output_____" ] ], [ [ "from nltk.tokenize import sent_tokenize, word_tokenize\n \ndata = \"All work and no play makes jack dull boy. All work and no play makes jack a dull boy.\"\nprint(sent_tokenize(data))", "_____no_output_____" ] ], [ [ "<a id=\"40\"></a> <br>\n## 2-2 NLTK and arrays\nIf you wish to you can store the words and sentences in arrays", "_____no_output_____" ] ], [ [ "from nltk.tokenize import sent_tokenize, word_tokenize\n \ndata = \"All work and no play makes jack dull boy. All work and no play makes jack a dull boy.\"\n \nphrases = sent_tokenize(data)\nwords = word_tokenize(data)\n \nprint(phrases)\nprint(words)", "_____no_output_____" ] ], [ [ "<a id=\"41\"></a> <br>\n## 2-3 NLTK stop words\nNatural language processing (nlp) is a research field that presents many challenges such as natural language understanding.\nText may contain stop words like ‘the’, ‘is’, ‘are’. Stop words can be filtered from the text to be processed. There is no universal list of stop words in nlp research, however the nltk module contains a list of stop words.\n\nIn this article you will learn how to remove stop words with the nltk module.", "_____no_output_____" ] ], [ [ "from nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords\n \ndata = \"All work and no play makes jack dull boy. All work and no play makes jack a dull boy.\"\nstopWords = set(stopwords.words('english'))\nwords = word_tokenize(data)\nwordsFiltered = []\n \nfor w in words:\n if w not in stopWords:\n wordsFiltered.append(w)\n \nprint(wordsFiltered)", "_____no_output_____" ] ], [ [ "A module has been imported:\n\n", "_____no_output_____" ] ], [ [ "from nltk.corpus import stopwords\n", "_____no_output_____" ] ], [ [ "We get a set of English stop words using the line:\n\n", "_____no_output_____" ] ], [ [ "stopWords = set(stopwords.words('english'))\n", "_____no_output_____" ] ], [ [ "The returned list stopWords contains 153 stop words on my computer.\nYou can view the length or contents of this array with the lines:", "_____no_output_____" ] ], [ [ "print(len(stopWords))\nprint(stopWords)", "_____no_output_____" ] ], [ [ "We create a new list called wordsFiltered which contains all words which are not stop words.\nTo create it we iterate over the list of words and only add it if its not in the stopWords list.", "_____no_output_____" ] ], [ [ "for w in words:\n if w not in stopWords:\n wordsFiltered.append(w)", "_____no_output_____" ] ], [ [ "<a id=\"42\"></a> <br>\n## 2-4 NLTK – stemming\nStart by defining some words:", "_____no_output_____" ] ], [ [ "words = [\"game\",\"gaming\",\"gamed\",\"games\"]\n", "_____no_output_____" ], [ "from nltk.stem import PorterStemmer\nfrom nltk.tokenize import sent_tokenize, word_tokenize", "_____no_output_____" ] ], [ [ "And stem the words in the list using:", "_____no_output_____" ] ], [ [ "from nltk.stem import PorterStemmer\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\nwords = [\"game\",\"gaming\",\"gamed\",\"games\"]\nps = PorterStemmer()\n \nfor word in words:\n print(ps.stem(word))", "_____no_output_____" ] ], [ [ "<a id=\"43\"></a> <br>\n## 2-5 NLTK speech tagging\nThe module NLTK can automatically tag speech.\nGiven a sentence or paragraph, it can label words such as verbs, nouns and so on.\n\nNLTK – speech tagging example\nThe example below automatically tags words with a corresponding class.", "_____no_output_____" ] ], [ [ "import nltk\nfrom nltk.tokenize import PunktSentenceTokenizer\n \ndocument = 'Whether you\\'re new to programming or an experienced developer, it\\'s easy to learn and use Python.'\nsentences = nltk.sent_tokenize(document) \nfor sent in sentences:\n print(nltk.pos_tag(nltk.word_tokenize(sent)))", "_____no_output_____" ] ], [ [ "We can filter this data based on the type of word:", "_____no_output_____" ] ], [ [ "import nltk\nfrom nltk.corpus import state_union\nfrom nltk.tokenize import PunktSentenceTokenizer\n \ndocument = 'Today the Netherlands celebrates King\\'s Day. To honor this tradition, the Dutch embassy in San Francisco invited me to'\nsentences = nltk.sent_tokenize(document) \n \ndata = []\nfor sent in sentences:\n data = data + nltk.pos_tag(nltk.word_tokenize(sent))\n \nfor word in data: \n if 'NNP' in word[1]: \n print(word)", "_____no_output_____" ] ], [ [ "<a id=\"44\"></a> <br>\n## 2-6 Natural Language Processing – prediction\nWe can use natural language processing to make predictions. Example: Given a product review, a computer can predict if its positive or negative based on the text. In this article you will learn how to make a prediction program based on natural language processing.", "_____no_output_____" ], [ "<a id=\"45\"></a> <br>\n### 2-6-1 nlp prediction example\nGiven a name, the classifier will predict if it’s a male or female.\n\nTo create our analysis program, we have several steps:\n\n1. Data preparation\n1. Feature extraction\n1. Training\n1. Prediction\n1. Data preparation\nThe first step is to prepare data. We use the names set included with nltk.", "_____no_output_____" ] ], [ [ "from nltk.corpus import names\n \n# Load data and training \nnames = ([(name, 'male') for name in names.words('male.txt')] + \n\t [(name, 'female') for name in names.words('female.txt')])", "_____no_output_____" ] ], [ [ "This dataset is simply a collection of tuples. To give you an idea of what the dataset looks like:", "_____no_output_____" ] ], [ [ "[(u'Aaron', 'male'), (u'Abbey', 'male'), (u'Abbie', 'male')]\n[(u'Zorana', 'female'), (u'Zorina', 'female'), (u'Zorine', 'female')]", "_____no_output_____" ] ], [ [ "You can define your own set of tuples if you wish, its simply a list containing many tuples.\n\nFeature extraction\nBased on the dataset, we prepare our feature. The feature we will use is the last letter of a name:\nWe define a featureset using:", "_____no_output_____" ], [ "featuresets = [(gender_features(n), g) for (n,g) in names]\nand the features (last letters) are extracted using:", "_____no_output_____" ] ], [ [ "def gender_features(word): \n return {'last_letter': word[-1]}", "_____no_output_____" ] ], [ [ "Training and prediction\nWe train and predict using:", "_____no_output_____" ] ], [ [ "import nltk.classify.util\nfrom nltk.classify import NaiveBayesClassifier\nfrom nltk.corpus import names\n \ndef gender_features(word): \n return {'last_letter': word[-1]} \n \n# Load data and training \nnames = ([(name, 'male') for name in names.words('male.txt')] + \n\t [(name, 'female') for name in names.words('female.txt')])\n \nfeaturesets = [(gender_features(n), g) for (n,g) in names] \ntrain_set = featuresets\nclassifier = nltk.NaiveBayesClassifier.train(train_set) \n \n# Predict\nprint(classifier.classify(gender_features('Frank')))", "_____no_output_____" ] ], [ [ "If you want to give the name during runtime, change the last line to:\n\n", "_____no_output_____" ] ], [ [ "# Predict, you can change name\nname = 'Sarah'\nprint(classifier.classify(gender_features(name)))", "_____no_output_____" ] ], [ [ "<a id=\"45\"></a> <br>\n## 2-7 Python Sentiment Analysis\nIn Natural Language Processing there is a concept known as Sentiment Analysis.\n\nGiven a movie review or a tweet, it can be automatically classified in categories.\nThese categories can be user defined (positive, negative) or whichever classes you want.\nClassification is done using several steps: training and prediction.\n\nThe training phase needs to have training data, this is example data in which we define examples. The classifier will use the training data to make predictions.", "_____no_output_____" ], [ "We start by defining 3 classes: positive, negative and neutral.\nEach of these is defined by a vocabulary:", "_____no_output_____" ] ], [ [ "positive_vocab = [ 'awesome', 'outstanding', 'fantastic', 'terrific', 'good', 'nice', 'great', ':)' ]\nnegative_vocab = [ 'bad', 'terrible','useless', 'hate', ':(' ]\nneutral_vocab = [ 'movie','the','sound','was','is','actors','did','know','words','not' ]", "_____no_output_____" ] ], [ [ "Every word is converted into a feature using a simplified bag of words model:", "_____no_output_____" ] ], [ [ "def word_feats(words):\n return dict([(word, True) for word in words])\n \npositive_features = [(word_feats(pos), 'pos') for pos in positive_vocab]\nnegative_features = [(word_feats(neg), 'neg') for neg in negative_vocab]\nneutral_features = [(word_feats(neu), 'neu') for neu in neutral_vocab]", "_____no_output_____" ] ], [ [ "Our training set is then the sum of these three feature sets:", "_____no_output_____" ] ], [ [ "train_set = negative_features + positive_features + neutral_features", "_____no_output_____" ] ], [ [ "We train the classifier:", "_____no_output_____" ], [ "classifier = NaiveBayesClassifier.train(train_set)", "_____no_output_____" ], [ "This example classifies sentences according to the training set.", "_____no_output_____" ] ], [ [ "import nltk.classify.util\nfrom nltk.classify import NaiveBayesClassifier\nfrom nltk.corpus import names\n \ndef word_feats(words):\n return dict([(word, True) for word in words])\n \npositive_vocab = [ 'awesome', 'outstanding', 'fantastic', 'terrific', 'good', 'nice', 'great', ':)' ]\nnegative_vocab = [ 'bad', 'terrible','useless', 'hate', ':(' ]\nneutral_vocab = [ 'movie','the','sound','was','is','actors','did','know','words','not' ]\n \npositive_features = [(word_feats(pos), 'pos') for pos in positive_vocab]\nnegative_features = [(word_feats(neg), 'neg') for neg in negative_vocab]\nneutral_features = [(word_feats(neu), 'neu') for neu in neutral_vocab]\n \ntrain_set = negative_features + positive_features + neutral_features\n \nclassifier = NaiveBayesClassifier.train(train_set) \n \n# Predict\nneg = 0\npos = 0\nsentence = \"Awesome movie, I liked it\"\nsentence = sentence.lower()\nwords = sentence.split(' ')\nfor word in words:\n classResult = classifier.classify( word_feats(word))\n if classResult == 'neg':\n neg = neg + 1\n if classResult == 'pos':\n pos = pos + 1\n \nprint('Positive: ' + str(float(pos)/len(words)))\nprint('Negative: ' + str(float(neg)/len(words)))", "_____no_output_____" ] ], [ [ "<a id=\"47\"></a> <br>\n# 5- conclusion\nAfter the first version of this kernel, in the third edition, we introduced NLTK library. in addition, we examined each one in detail. this kernel it is not completed yet! Following up!", "_____no_output_____" ], [ ">###### you may be interested have a look at it: [**10-steps-to-become-a-data-scientist**](https://github.com/mjbahmani/10-steps-to-become-a-data-scientist)\n\n\n---------------------------------------------------------------------\nyou can Fork and Run this kernel on Github:\n> ###### [ GitHub](https://github.com/mjbahmani/10-steps-to-become-a-data-scientist)\n\n-------------------------------------------------------------------------------------------------------------\n\n **I hope you find this kernel helpful and some <font color=\"red\"><b>UPVOTES</b></font> would be very much appreciated**\n \n -----------", "_____no_output_____" ], [ "<a id=\"48\"></a> <br>\n# 6- References\n1. [Coursera](https://www.coursera.org/specializations/data-science-python)\n1. [GitHub](https://github.com/mjbahmani)\n1. [NLTK](https://pythonspot.com/category/nltk/)\n###### [Go to top](#top)", "_____no_output_____" ], [ "#### This Kernel is not completed and will be updated soon!!!", "_____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" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
ec508a3e62caf70c06ae1f3cbbbb0818bc5d155a
308,753
ipynb
Jupyter Notebook
src/codes/eemd_231_s.ipynb
nayanika15101/hht
2062a6d899d29d5dd89bf72e17bc3a29eca9fb3a
[ "MIT" ]
1
2021-03-13T08:32:54.000Z
2021-03-13T08:32:54.000Z
src/codes/eemd_231_s.ipynb
nayanika15101/hht
2062a6d899d29d5dd89bf72e17bc3a29eca9fb3a
[ "MIT" ]
null
null
null
src/codes/eemd_231_s.ipynb
nayanika15101/hht
2062a6d899d29d5dd89bf72e17bc3a29eca9fb3a
[ "MIT" ]
null
null
null
1,061.006873
174,832
0.954323
[ [ [ "from PyEMD import EMD,EEMD\nimport pylab as plt\n\n\nfrom pyhht.visualization import plot_imfs\nimport numpy as np\nimport math\nfrom pyhht.emd import EMD\nimport matplotlib.pyplot as plt\nfrom tftb.generators import fmconst\nfrom scipy import angle, unwrap\nfrom scipy.signal import hilbert\nimport pandas as pd\n\n\n\ndf=pd.read_excel(\"C:/Users/Dell/Documents/sem8/Data Set/231_s.xlsx\")\na1=df[\"t\"]\nlist(a1)\nimport numpy as np\nt=np.asarray(a1)\ntype(t)\n#print(a1ar)\na2=df[\"modes\"]\nlist(a2)\nimport numpy as np\ns=np.asarray(a2)\ntype(s)\n#print(a2ar)\nx=s+t\nplt.plot(t,s);\n\n\n\n# Define signal\n\n# Assign EEMD to `eemd` variable\neemd=EEMD()\n# Say we want detect extrema using parabolic method\nemd = eemd.EMD\nemd.extrema_detection=\"parabol\"\n# Execute EEMD on S\neIMFs = eemd.eemd(s, t)\nnIMFs = eIMFs.shape[0]\n# Plot results\nplt.figure(figsize=(12,9))\nplt.subplot(nIMFs+1, 1, 1)\nplt.plot(t, s, 'r')\nfor n in range(nIMFs):\n plt.subplot(nIMFs+1, 1, n+2)\n plt.plot(t, eIMFs[n], 'g')\n plt.ylabel(\"eIMF %i\" %(n+1))\n plt.locator_params(axis='y', nbins=5)\nplt.xlabel(\"Time [s]\")\nplt.tight_layout()\n#plt.savefig('eemd_example', dpi=120)\nplt.show()\n\n\n\nhs1 = hilbert(eIMFs[0])\nomega_imf_one = unwrap(angle(hs1))/(2*3.14)\nf_inst_imf_one = np.diff(omega_imf_one) \nplt.plot(t[1:658],abs(f_inst_imf_one[1:658])/0.001,'r')\n\nhs2 = hilbert(eIMFs[1])\nomega_imf_2 = unwrap(angle(hs2))/(2*3.14)\nf_inst_imf_2 = np.diff(omega_imf_2) \nplt.plot(t[1:658],abs(f_inst_imf_2[1:658])/0.001,'b')\n\nhs3 = hilbert(eIMFs[2])\nomega_imf_3 = unwrap(angle(hs3))/(2*3.14)\nf_inst_imf_3 = np.diff(omega_imf_3) \nplt.plot(t[1:658],abs(f_inst_imf_3[1:658])/0.001,'g')\n\nhs4 = hilbert(eIMFs[3])\nomega_imf_4 = unwrap(angle(hs4))/(2*3.14)\nf_inst_imf_4 = np.diff(omega_imf_4) \nplt.plot(t[1:658],abs(f_inst_imf_4[1:658])/0.001,'y')\n\nhs5 = hilbert(eIMFs[4])\nomega_imf_5 = unwrap(angle(hs5))/(2*3.14)\nf_inst_imf_5 = np.diff(omega_imf_one) \nplt.plot(t[1:658],abs(f_inst_imf_5[1:658])/0.001,'r')\n\nhs6 = hilbert(eIMFs[5])\nomega_imf_6 = unwrap(angle(hs6))/(2*3.14)\nf_inst_imf_6 = np.diff(omega_imf_6) \nplt.plot(t[1:658],abs(f_inst_imf_6[1:658])/0.001,'g')\n\nhs7 = hilbert(eIMFs[6])\nomega_imf_7 = unwrap(angle(hs7))/(2*3.14)\nf_inst_imf_7 = np.diff(omega_imf_7) \nplt.plot(t[1:658],abs(f_inst_imf_7[1:658])/0.001,'b')\n\nhs8 = hilbert(eIMFs[7])\nomega_imf_8 = unwrap(angle(hs8))/(2*3.14)\nf_inst_imf_8 = np.diff(omega_imf_8) \nplt.plot(t[1:658],abs(f_inst_imf_8[1:658])/0.001,'y')\n", "_____no_output_____" ], [ "from scipy import signal\n#sum1=np.abs(hs1+hs2+hs3+hs4+hs5+hs6+hs7+hs8)\nfs = 10e2\n#N = 1e5\namp = 2*np.sqrt(2)\n#noise_power = 0.001 * fs / 2\n#time = np.arange(N) / fs\n#x = amp*np.sin(2*np.pi*freq*time)\n#x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)\n\n#power in volt **2 /hz\nf, Pxx_den = signal.periodogram(eIMFs[0], fs)\nplt.semilogy(f, Pxx_den)\nf, Pxx_den1 = signal.periodogram(eIMFs[1], fs)\nplt.semilogy(f, Pxx_den1)\nf, Pxx_den2 = signal.periodogram(eIMFs[2], fs)\nplt.semilogy(f, Pxx_den2)\nf, Pxx_den3 = signal.periodogram(eIMFs[3], fs)\nplt.semilogy(f, Pxx_den3)\nf, Pxx_den4 = signal.periodogram(eIMFs[4], fs)\nplt.semilogy(f, Pxx_den4)\nf, Pxx_den5 = signal.periodogram(eIMFs[5], fs)\nplt.semilogy(f, Pxx_den5)\nf, Pxx_den6 = signal.periodogram(eIMFs[6], fs)\nplt.semilogy(f, Pxx_den6)\nf, Pxx_den7 = signal.periodogram(eIMFs[7], fs)\nplt.semilogy(f, Pxx_den7)\nplt.show()\n#plt.plot(Pxx_den[1:330],f_inst_imf_one[1:330])\n", "_____no_output_____" ], [ "import numpy as np\nprint('\\nmean are as follows')\nprint(np.mean(Pxx_den))\nprint(np.mean(Pxx_den1))\nprint(np.mean(Pxx_den2))\nprint(np.mean(Pxx_den3))\nprint(np.mean(Pxx_den4))\nprint(np.mean(Pxx_den5))\nprint(np.mean(Pxx_den6))\nprint(np.mean(Pxx_den7))\nprint('\\nstandard deviation are as follows')\nprint(np.std(Pxx_den))\nprint(np.std(Pxx_den1))\nprint(np.std(Pxx_den2))\nprint(np.std(Pxx_den3))\nprint(np.std(Pxx_den4))\nprint(np.std(Pxx_den5))\nprint(np.std(Pxx_den6))\nprint(np.std(Pxx_den7))\n", "\nmean are as follows\n2.1072447404696383e-06\n9.367379668794336e-07\n1.7558143917912016e-06\n2.6356264128117946e-06\n2.7861321092387013e-06\n5.300284862812177e-06\n1.3604983717260306e-05\n3.9638574497851e-05\n\nstandard deviation are as follows\n2.8700608342724556e-06\n1.899237753975364e-06\n5.858658058344385e-06\n1.4175262665182011e-05\n1.9798189146028354e-05\n4.65669697145687e-05\n0.00017908714352792097\n0.0006042900088290244\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
ec508f91d01e782308bc7b92280d90ddc01747cc
77,631
ipynb
Jupyter Notebook
Week 3/Assignment 3/Final_Assignment_3C.ipynb
vgaurav3011/EIP-3.0-
d0db0ae86a6f52b796435c4446c67d5a760f2bc9
[ "MIT" ]
null
null
null
Week 3/Assignment 3/Final_Assignment_3C.ipynb
vgaurav3011/EIP-3.0-
d0db0ae86a6f52b796435c4446c67d5a760f2bc9
[ "MIT" ]
null
null
null
Week 3/Assignment 3/Final_Assignment_3C.ipynb
vgaurav3011/EIP-3.0-
d0db0ae86a6f52b796435c4446c67d5a760f2bc9
[ "MIT" ]
2
2019-04-17T10:43:17.000Z
2019-11-11T11:00:54.000Z
79.703285
1,088
0.562623
[ [ [ "<a href=\"https://colab.research.google.com/github/vgaurav3011/EIP-3.0-/blob/master/Final_Assignment_3C.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "# https://keras.io/\n!pip install -q keras\nimport keras\n\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.models import Model, Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Input, AveragePooling2D, merge, Activation\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom keras.layers import Concatenate\nfrom keras.optimizers import Adam\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers import Reshape, Activation, Conv2D, Input, MaxPooling2D, BatchNormalization, Flatten, Dense, Lambda\nfrom keras.layers.merge import concatenate\n\n# this part will prevent tensorflow to allocate all the avaliable GPU Memory\n# backend\nimport tensorflow as tf\nfrom keras import backend as k\n\n# Don't pre-allocate memory; allocate as-needed\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n\n# Create a session with the above options specified.\nk.tensorflow_backend.set_session(tf.Session(config=config))\n\n# Hyperparameters\nbatch_size = 128\nnum_classes = 10\nepochs = 50\nl = 10\nnum_filter = 20\ncompression = 0.5", "_____no_output_____" ], [ "# Load CIFAR10 Data\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\nimg_height, img_width, channel = x_train.shape[1],x_train.shape[2],x_train.shape[3]\n\n# convert to one hot encoding \ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)", "_____no_output_____" ], [ "from keras.preprocessing.image import ImageDataGenerator\ndatagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True)", "_____no_output_____" ], [ "def add_block(input, num_filter = 20):\n global compression\n temp = input\n for _ in range(l):\n BatchNorm = BatchNormalization()(temp)\n relu = Activation('relu')(BatchNorm)\n x = Conv2D(int(num_filter*compression), (3,3), use_bias=False ,padding='same')(relu)\n x = Conv2D(int(32), (3, 3), use_bias = False, padding = 'same')(relu)\n x = Conv2D(int(64), (3, 3), use_bias = False, padding = 'same')(relu)\n x = Conv2D(int(128), (3, 3), use_bias = False, padding = 'same')(relu)\n x = Conv2D(int(256), (3, 3), use_bias = False, padding = 'same')(relu)\n x = Conv2D(int(512), (3, 3), use_bias = False, padding = 'same')(relu)\n \n concat = Concatenate(axis=-1)([temp,x])\n \n temp = concat\n \n return temp", "_____no_output_____" ], [ "def add_trans(input, num_filter = 20):\n global compression\n BatchNorm = BatchNormalization()(input)\n relu = Activation('relu')(BatchNorm)\n Conv2D_BottleNeck = Conv2D(int(num_filter*compression), (1,1), use_bias=False ,padding='same')(relu)\n avg = AveragePooling2D(pool_size=(2,2))(Conv2D_BottleNeck)\n return avg", "_____no_output_____" ], [ "def output_layer(input):\n global compression\n BatchNorm = BatchNormalization()(input)\n relu = Activation('relu')(BatchNorm)\n AvgPooling = AveragePooling2D(pool_size=(2,2))(relu)\n flat = Flatten()(AvgPooling)\n output = Dense(num_classes, activation='softmax')(flat)\n \n return output", "_____no_output_____" ], [ "def space_to_depth_x2(x):\n return tf.space_to_depth(x, block_size=2)", "_____no_output_____" ], [ "num_filter = 20\nl = 12\ninput = Input(shape=(img_height, img_width, channel,))\nFirst_Conv2D = Conv2D(num_filter, (3,3), use_bias=False ,padding='same')(input)\n\nFirst_Block = add_block(First_Conv2D, num_filter)\nFirst_Transition = add_trans(First_Block, num_filter)\n\nSecond_Block = add_block(First_Transition, num_filter)\nSecond_Transition = add_trans(Second_Block, num_filter)\n\nThird_Block = add_block(Second_Transition, num_filter)\nThird_Transition = add_trans(Third_Block, num_filter)\n\nFourth_Block = add_block(Third_Transition, num_filter)\noutput = output_layer(Fourth_Block)", "_____no_output_____" ], [ "model = Model(inputs=[input], outputs=[output])\nmodel.summary()", "__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_8 (InputLayer) (None, 32, 32, 3) 0 \n__________________________________________________________________________________________________\nconv2d_53 (Conv2D) (None, 32, 32, 20) 540 input_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_53 (BatchNo (None, 32, 32, 20) 80 conv2d_53[0][0] \n__________________________________________________________________________________________________\nactivation_53 (Activation) (None, 32, 32, 20) 0 batch_normalization_53[0][0] \n__________________________________________________________________________________________________\nconv2d_54 (Conv2D) (None, 32, 32, 10) 1800 activation_53[0][0] \n__________________________________________________________________________________________________\nconcatenate_55 (Concatenate) (None, 32, 32, 30) 0 conv2d_53[0][0] \n conv2d_54[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_54 (BatchNo (None, 32, 32, 30) 120 concatenate_55[0][0] \n__________________________________________________________________________________________________\nactivation_54 (Activation) (None, 32, 32, 30) 0 batch_normalization_54[0][0] \n__________________________________________________________________________________________________\nconv2d_55 (Conv2D) (None, 32, 32, 10) 2700 activation_54[0][0] \n__________________________________________________________________________________________________\nconcatenate_56 (Concatenate) (None, 32, 32, 40) 0 concatenate_55[0][0] \n conv2d_55[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_55 (BatchNo (None, 32, 32, 40) 160 concatenate_56[0][0] \n__________________________________________________________________________________________________\nactivation_55 (Activation) (None, 32, 32, 40) 0 batch_normalization_55[0][0] \n__________________________________________________________________________________________________\nconv2d_56 (Conv2D) (None, 32, 32, 10) 3600 activation_55[0][0] \n__________________________________________________________________________________________________\nconcatenate_57 (Concatenate) (None, 32, 32, 50) 0 concatenate_56[0][0] \n conv2d_56[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_56 (BatchNo (None, 32, 32, 50) 200 concatenate_57[0][0] \n__________________________________________________________________________________________________\nactivation_56 (Activation) (None, 32, 32, 50) 0 batch_normalization_56[0][0] \n__________________________________________________________________________________________________\nconv2d_57 (Conv2D) (None, 32, 32, 10) 4500 activation_56[0][0] \n__________________________________________________________________________________________________\nconcatenate_58 (Concatenate) (None, 32, 32, 60) 0 concatenate_57[0][0] \n conv2d_57[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_57 (BatchNo (None, 32, 32, 60) 240 concatenate_58[0][0] \n__________________________________________________________________________________________________\nactivation_57 (Activation) (None, 32, 32, 60) 0 batch_normalization_57[0][0] \n__________________________________________________________________________________________________\nconv2d_58 (Conv2D) (None, 32, 32, 10) 5400 activation_57[0][0] \n__________________________________________________________________________________________________\nconcatenate_59 (Concatenate) (None, 32, 32, 70) 0 concatenate_58[0][0] \n conv2d_58[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_58 (BatchNo (None, 32, 32, 70) 280 concatenate_59[0][0] \n__________________________________________________________________________________________________\nactivation_58 (Activation) (None, 32, 32, 70) 0 batch_normalization_58[0][0] \n__________________________________________________________________________________________________\nconv2d_59 (Conv2D) (None, 32, 32, 10) 6300 activation_58[0][0] \n__________________________________________________________________________________________________\nconcatenate_60 (Concatenate) (None, 32, 32, 80) 0 concatenate_59[0][0] \n conv2d_59[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_59 (BatchNo (None, 32, 32, 80) 320 concatenate_60[0][0] \n__________________________________________________________________________________________________\nactivation_59 (Activation) (None, 32, 32, 80) 0 batch_normalization_59[0][0] \n__________________________________________________________________________________________________\nconv2d_60 (Conv2D) (None, 32, 32, 10) 7200 activation_59[0][0] \n__________________________________________________________________________________________________\nconcatenate_61 (Concatenate) (None, 32, 32, 90) 0 concatenate_60[0][0] \n conv2d_60[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_60 (BatchNo (None, 32, 32, 90) 360 concatenate_61[0][0] \n__________________________________________________________________________________________________\nactivation_60 (Activation) (None, 32, 32, 90) 0 batch_normalization_60[0][0] \n__________________________________________________________________________________________________\nconv2d_61 (Conv2D) (None, 32, 32, 10) 8100 activation_60[0][0] \n__________________________________________________________________________________________________\nconcatenate_62 (Concatenate) (None, 32, 32, 100) 0 concatenate_61[0][0] \n conv2d_61[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_61 (BatchNo (None, 32, 32, 100) 400 concatenate_62[0][0] \n__________________________________________________________________________________________________\nactivation_61 (Activation) (None, 32, 32, 100) 0 batch_normalization_61[0][0] \n__________________________________________________________________________________________________\nconv2d_62 (Conv2D) (None, 32, 32, 10) 9000 activation_61[0][0] \n__________________________________________________________________________________________________\nconcatenate_63 (Concatenate) (None, 32, 32, 110) 0 concatenate_62[0][0] \n conv2d_62[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_62 (BatchNo (None, 32, 32, 110) 440 concatenate_63[0][0] \n__________________________________________________________________________________________________\nactivation_62 (Activation) (None, 32, 32, 110) 0 batch_normalization_62[0][0] \n__________________________________________________________________________________________________\nconv2d_63 (Conv2D) (None, 32, 32, 10) 9900 activation_62[0][0] \n__________________________________________________________________________________________________\nconcatenate_64 (Concatenate) (None, 32, 32, 120) 0 concatenate_63[0][0] \n conv2d_63[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_63 (BatchNo (None, 32, 32, 120) 480 concatenate_64[0][0] \n__________________________________________________________________________________________________\nactivation_63 (Activation) (None, 32, 32, 120) 0 batch_normalization_63[0][0] \n__________________________________________________________________________________________________\nconv2d_64 (Conv2D) (None, 32, 32, 10) 10800 activation_63[0][0] \n__________________________________________________________________________________________________\nconcatenate_65 (Concatenate) (None, 32, 32, 130) 0 concatenate_64[0][0] \n conv2d_64[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_64 (BatchNo (None, 32, 32, 130) 520 concatenate_65[0][0] \n__________________________________________________________________________________________________\nactivation_64 (Activation) (None, 32, 32, 130) 0 batch_normalization_64[0][0] \n__________________________________________________________________________________________________\nconv2d_65 (Conv2D) (None, 32, 32, 10) 11700 activation_64[0][0] \n__________________________________________________________________________________________________\nconcatenate_66 (Concatenate) (None, 32, 32, 140) 0 concatenate_65[0][0] \n conv2d_65[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_65 (BatchNo (None, 32, 32, 140) 560 concatenate_66[0][0] \n__________________________________________________________________________________________________\nactivation_65 (Activation) (None, 32, 32, 140) 0 batch_normalization_65[0][0] \n__________________________________________________________________________________________________\nconv2d_66 (Conv2D) (None, 32, 32, 10) 1400 activation_65[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_5 (AveragePoo (None, 16, 16, 10) 0 conv2d_66[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_66 (BatchNo (None, 16, 16, 10) 40 average_pooling2d_5[0][0] \n__________________________________________________________________________________________________\nactivation_66 (Activation) (None, 16, 16, 10) 0 batch_normalization_66[0][0] \n__________________________________________________________________________________________________\nconv2d_67 (Conv2D) (None, 16, 16, 10) 900 activation_66[0][0] \n__________________________________________________________________________________________________\nconcatenate_67 (Concatenate) (None, 16, 16, 20) 0 average_pooling2d_5[0][0] \n conv2d_67[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_67 (BatchNo (None, 16, 16, 20) 80 concatenate_67[0][0] \n__________________________________________________________________________________________________\nactivation_67 (Activation) (None, 16, 16, 20) 0 batch_normalization_67[0][0] \n__________________________________________________________________________________________________\nconv2d_68 (Conv2D) (None, 16, 16, 10) 1800 activation_67[0][0] \n__________________________________________________________________________________________________\nconcatenate_68 (Concatenate) (None, 16, 16, 30) 0 concatenate_67[0][0] \n conv2d_68[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_68 (BatchNo (None, 16, 16, 30) 120 concatenate_68[0][0] \n__________________________________________________________________________________________________\nactivation_68 (Activation) (None, 16, 16, 30) 0 batch_normalization_68[0][0] \n__________________________________________________________________________________________________\nconv2d_69 (Conv2D) (None, 16, 16, 10) 2700 activation_68[0][0] \n__________________________________________________________________________________________________\nconcatenate_69 (Concatenate) (None, 16, 16, 40) 0 concatenate_68[0][0] \n conv2d_69[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_69 (BatchNo (None, 16, 16, 40) 160 concatenate_69[0][0] \n__________________________________________________________________________________________________\nactivation_69 (Activation) (None, 16, 16, 40) 0 batch_normalization_69[0][0] \n__________________________________________________________________________________________________\nconv2d_70 (Conv2D) (None, 16, 16, 10) 3600 activation_69[0][0] \n__________________________________________________________________________________________________\nconcatenate_70 (Concatenate) (None, 16, 16, 50) 0 concatenate_69[0][0] \n conv2d_70[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_70 (BatchNo (None, 16, 16, 50) 200 concatenate_70[0][0] \n__________________________________________________________________________________________________\nactivation_70 (Activation) (None, 16, 16, 50) 0 batch_normalization_70[0][0] \n__________________________________________________________________________________________________\nconv2d_71 (Conv2D) (None, 16, 16, 10) 4500 activation_70[0][0] \n__________________________________________________________________________________________________\nconcatenate_71 (Concatenate) (None, 16, 16, 60) 0 concatenate_70[0][0] \n conv2d_71[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_71 (BatchNo (None, 16, 16, 60) 240 concatenate_71[0][0] \n__________________________________________________________________________________________________\nactivation_71 (Activation) (None, 16, 16, 60) 0 batch_normalization_71[0][0] \n__________________________________________________________________________________________________\nconv2d_72 (Conv2D) (None, 16, 16, 10) 5400 activation_71[0][0] \n__________________________________________________________________________________________________\nconcatenate_72 (Concatenate) (None, 16, 16, 70) 0 concatenate_71[0][0] \n conv2d_72[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_72 (BatchNo (None, 16, 16, 70) 280 concatenate_72[0][0] \n__________________________________________________________________________________________________\nactivation_72 (Activation) (None, 16, 16, 70) 0 batch_normalization_72[0][0] \n__________________________________________________________________________________________________\nconv2d_73 (Conv2D) (None, 16, 16, 10) 6300 activation_72[0][0] \n__________________________________________________________________________________________________\nconcatenate_73 (Concatenate) (None, 16, 16, 80) 0 concatenate_72[0][0] \n conv2d_73[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_73 (BatchNo (None, 16, 16, 80) 320 concatenate_73[0][0] \n__________________________________________________________________________________________________\nactivation_73 (Activation) (None, 16, 16, 80) 0 batch_normalization_73[0][0] \n__________________________________________________________________________________________________\nconv2d_74 (Conv2D) (None, 16, 16, 10) 7200 activation_73[0][0] \n__________________________________________________________________________________________________\nconcatenate_74 (Concatenate) (None, 16, 16, 90) 0 concatenate_73[0][0] \n conv2d_74[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_74 (BatchNo (None, 16, 16, 90) 360 concatenate_74[0][0] \n__________________________________________________________________________________________________\nactivation_74 (Activation) (None, 16, 16, 90) 0 batch_normalization_74[0][0] \n__________________________________________________________________________________________________\nconv2d_75 (Conv2D) (None, 16, 16, 10) 8100 activation_74[0][0] \n__________________________________________________________________________________________________\nconcatenate_75 (Concatenate) (None, 16, 16, 100) 0 concatenate_74[0][0] \n conv2d_75[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_75 (BatchNo (None, 16, 16, 100) 400 concatenate_75[0][0] \n__________________________________________________________________________________________________\nactivation_75 (Activation) (None, 16, 16, 100) 0 batch_normalization_75[0][0] \n__________________________________________________________________________________________________\nconv2d_76 (Conv2D) (None, 16, 16, 10) 9000 activation_75[0][0] \n__________________________________________________________________________________________________\nconcatenate_76 (Concatenate) (None, 16, 16, 110) 0 concatenate_75[0][0] \n conv2d_76[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_76 (BatchNo (None, 16, 16, 110) 440 concatenate_76[0][0] \n__________________________________________________________________________________________________\nactivation_76 (Activation) (None, 16, 16, 110) 0 batch_normalization_76[0][0] \n__________________________________________________________________________________________________\nconv2d_77 (Conv2D) (None, 16, 16, 10) 9900 activation_76[0][0] \n__________________________________________________________________________________________________\nconcatenate_77 (Concatenate) (None, 16, 16, 120) 0 concatenate_76[0][0] \n conv2d_77[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_77 (BatchNo (None, 16, 16, 120) 480 concatenate_77[0][0] \n__________________________________________________________________________________________________\nactivation_77 (Activation) (None, 16, 16, 120) 0 batch_normalization_77[0][0] \n__________________________________________________________________________________________________\nconv2d_78 (Conv2D) (None, 16, 16, 10) 10800 activation_77[0][0] \n__________________________________________________________________________________________________\nconcatenate_78 (Concatenate) (None, 16, 16, 130) 0 concatenate_77[0][0] \n conv2d_78[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_78 (BatchNo (None, 16, 16, 130) 520 concatenate_78[0][0] \n__________________________________________________________________________________________________\nactivation_78 (Activation) (None, 16, 16, 130) 0 batch_normalization_78[0][0] \n__________________________________________________________________________________________________\nconv2d_79 (Conv2D) (None, 16, 16, 10) 1300 activation_78[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_6 (AveragePoo (None, 8, 8, 10) 0 conv2d_79[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_79 (BatchNo (None, 8, 8, 10) 40 average_pooling2d_6[0][0] \n__________________________________________________________________________________________________\nactivation_79 (Activation) (None, 8, 8, 10) 0 batch_normalization_79[0][0] \n__________________________________________________________________________________________________\nconv2d_80 (Conv2D) (None, 8, 8, 10) 900 activation_79[0][0] \n__________________________________________________________________________________________________\nconcatenate_79 (Concatenate) (None, 8, 8, 20) 0 average_pooling2d_6[0][0] \n conv2d_80[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_80 (BatchNo (None, 8, 8, 20) 80 concatenate_79[0][0] \n__________________________________________________________________________________________________\nactivation_80 (Activation) (None, 8, 8, 20) 0 batch_normalization_80[0][0] \n__________________________________________________________________________________________________\nconv2d_81 (Conv2D) (None, 8, 8, 10) 1800 activation_80[0][0] \n__________________________________________________________________________________________________\nconcatenate_80 (Concatenate) (None, 8, 8, 30) 0 concatenate_79[0][0] \n conv2d_81[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_81 (BatchNo (None, 8, 8, 30) 120 concatenate_80[0][0] \n__________________________________________________________________________________________________\nactivation_81 (Activation) (None, 8, 8, 30) 0 batch_normalization_81[0][0] \n__________________________________________________________________________________________________\nconv2d_82 (Conv2D) (None, 8, 8, 10) 2700 activation_81[0][0] \n__________________________________________________________________________________________________\nconcatenate_81 (Concatenate) (None, 8, 8, 40) 0 concatenate_80[0][0] \n conv2d_82[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_82 (BatchNo (None, 8, 8, 40) 160 concatenate_81[0][0] \n__________________________________________________________________________________________________\nactivation_82 (Activation) (None, 8, 8, 40) 0 batch_normalization_82[0][0] \n__________________________________________________________________________________________________\nconv2d_83 (Conv2D) (None, 8, 8, 10) 3600 activation_82[0][0] \n__________________________________________________________________________________________________\nconcatenate_82 (Concatenate) (None, 8, 8, 50) 0 concatenate_81[0][0] \n conv2d_83[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_83 (BatchNo (None, 8, 8, 50) 200 concatenate_82[0][0] \n__________________________________________________________________________________________________\nactivation_83 (Activation) (None, 8, 8, 50) 0 batch_normalization_83[0][0] \n__________________________________________________________________________________________________\nconv2d_84 (Conv2D) (None, 8, 8, 10) 4500 activation_83[0][0] \n__________________________________________________________________________________________________\nconcatenate_83 (Concatenate) (None, 8, 8, 60) 0 concatenate_82[0][0] \n conv2d_84[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_84 (BatchNo (None, 8, 8, 60) 240 concatenate_83[0][0] \n__________________________________________________________________________________________________\nactivation_84 (Activation) (None, 8, 8, 60) 0 batch_normalization_84[0][0] \n__________________________________________________________________________________________________\nconv2d_85 (Conv2D) (None, 8, 8, 10) 5400 activation_84[0][0] \n__________________________________________________________________________________________________\nconcatenate_84 (Concatenate) (None, 8, 8, 70) 0 concatenate_83[0][0] \n conv2d_85[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_85 (BatchNo (None, 8, 8, 70) 280 concatenate_84[0][0] \n__________________________________________________________________________________________________\nactivation_85 (Activation) (None, 8, 8, 70) 0 batch_normalization_85[0][0] \n__________________________________________________________________________________________________\nconv2d_86 (Conv2D) (None, 8, 8, 10) 6300 activation_85[0][0] \n__________________________________________________________________________________________________\nconcatenate_85 (Concatenate) (None, 8, 8, 80) 0 concatenate_84[0][0] \n conv2d_86[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_86 (BatchNo (None, 8, 8, 80) 320 concatenate_85[0][0] \n__________________________________________________________________________________________________\nactivation_86 (Activation) (None, 8, 8, 80) 0 batch_normalization_86[0][0] \n__________________________________________________________________________________________________\nconv2d_87 (Conv2D) (None, 8, 8, 10) 7200 activation_86[0][0] \n__________________________________________________________________________________________________\nconcatenate_86 (Concatenate) (None, 8, 8, 90) 0 concatenate_85[0][0] \n conv2d_87[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_87 (BatchNo (None, 8, 8, 90) 360 concatenate_86[0][0] \n__________________________________________________________________________________________________\nactivation_87 (Activation) (None, 8, 8, 90) 0 batch_normalization_87[0][0] \n__________________________________________________________________________________________________\nconv2d_88 (Conv2D) (None, 8, 8, 10) 8100 activation_87[0][0] \n__________________________________________________________________________________________________\nconcatenate_87 (Concatenate) (None, 8, 8, 100) 0 concatenate_86[0][0] \n conv2d_88[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_88 (BatchNo (None, 8, 8, 100) 400 concatenate_87[0][0] \n__________________________________________________________________________________________________\nactivation_88 (Activation) (None, 8, 8, 100) 0 batch_normalization_88[0][0] \n__________________________________________________________________________________________________\nconv2d_89 (Conv2D) (None, 8, 8, 10) 9000 activation_88[0][0] \n__________________________________________________________________________________________________\nconcatenate_88 (Concatenate) (None, 8, 8, 110) 0 concatenate_87[0][0] \n conv2d_89[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_89 (BatchNo (None, 8, 8, 110) 440 concatenate_88[0][0] \n__________________________________________________________________________________________________\nactivation_89 (Activation) (None, 8, 8, 110) 0 batch_normalization_89[0][0] \n__________________________________________________________________________________________________\nconv2d_90 (Conv2D) (None, 8, 8, 10) 9900 activation_89[0][0] \n__________________________________________________________________________________________________\nconcatenate_89 (Concatenate) (None, 8, 8, 120) 0 concatenate_88[0][0] \n conv2d_90[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_90 (BatchNo (None, 8, 8, 120) 480 concatenate_89[0][0] \n__________________________________________________________________________________________________\nactivation_90 (Activation) (None, 8, 8, 120) 0 batch_normalization_90[0][0] \n__________________________________________________________________________________________________\nconv2d_91 (Conv2D) (None, 8, 8, 10) 10800 activation_90[0][0] \n__________________________________________________________________________________________________\nconcatenate_90 (Concatenate) (None, 8, 8, 130) 0 concatenate_89[0][0] \n conv2d_91[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_91 (BatchNo (None, 8, 8, 130) 520 concatenate_90[0][0] \n__________________________________________________________________________________________________\nactivation_91 (Activation) (None, 8, 8, 130) 0 batch_normalization_91[0][0] \n__________________________________________________________________________________________________\nconv2d_92 (Conv2D) (None, 8, 8, 10) 1300 activation_91[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_7 (AveragePoo (None, 4, 4, 10) 0 conv2d_92[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_92 (BatchNo (None, 4, 4, 10) 40 average_pooling2d_7[0][0] \n__________________________________________________________________________________________________\nactivation_92 (Activation) (None, 4, 4, 10) 0 batch_normalization_92[0][0] \n__________________________________________________________________________________________________\nconv2d_93 (Conv2D) (None, 4, 4, 10) 900 activation_92[0][0] \n__________________________________________________________________________________________________\nconcatenate_91 (Concatenate) (None, 4, 4, 20) 0 average_pooling2d_7[0][0] \n conv2d_93[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_93 (BatchNo (None, 4, 4, 20) 80 concatenate_91[0][0] \n__________________________________________________________________________________________________\nactivation_93 (Activation) (None, 4, 4, 20) 0 batch_normalization_93[0][0] \n__________________________________________________________________________________________________\nconv2d_94 (Conv2D) (None, 4, 4, 10) 1800 activation_93[0][0] \n__________________________________________________________________________________________________\nconcatenate_92 (Concatenate) (None, 4, 4, 30) 0 concatenate_91[0][0] \n conv2d_94[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_94 (BatchNo (None, 4, 4, 30) 120 concatenate_92[0][0] \n__________________________________________________________________________________________________\nactivation_94 (Activation) (None, 4, 4, 30) 0 batch_normalization_94[0][0] \n__________________________________________________________________________________________________\nconv2d_95 (Conv2D) (None, 4, 4, 10) 2700 activation_94[0][0] \n__________________________________________________________________________________________________\nconcatenate_93 (Concatenate) (None, 4, 4, 40) 0 concatenate_92[0][0] \n conv2d_95[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_95 (BatchNo (None, 4, 4, 40) 160 concatenate_93[0][0] \n__________________________________________________________________________________________________\nactivation_95 (Activation) (None, 4, 4, 40) 0 batch_normalization_95[0][0] \n__________________________________________________________________________________________________\nconv2d_96 (Conv2D) (None, 4, 4, 10) 3600 activation_95[0][0] \n__________________________________________________________________________________________________\nconcatenate_94 (Concatenate) (None, 4, 4, 50) 0 concatenate_93[0][0] \n conv2d_96[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_96 (BatchNo (None, 4, 4, 50) 200 concatenate_94[0][0] \n__________________________________________________________________________________________________\nactivation_96 (Activation) (None, 4, 4, 50) 0 batch_normalization_96[0][0] \n__________________________________________________________________________________________________\nconv2d_97 (Conv2D) (None, 4, 4, 10) 4500 activation_96[0][0] \n__________________________________________________________________________________________________\nconcatenate_95 (Concatenate) (None, 4, 4, 60) 0 concatenate_94[0][0] \n conv2d_97[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_97 (BatchNo (None, 4, 4, 60) 240 concatenate_95[0][0] \n__________________________________________________________________________________________________\nactivation_97 (Activation) (None, 4, 4, 60) 0 batch_normalization_97[0][0] \n__________________________________________________________________________________________________\nconv2d_98 (Conv2D) (None, 4, 4, 10) 5400 activation_97[0][0] \n__________________________________________________________________________________________________\nconcatenate_96 (Concatenate) (None, 4, 4, 70) 0 concatenate_95[0][0] \n conv2d_98[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_98 (BatchNo (None, 4, 4, 70) 280 concatenate_96[0][0] \n__________________________________________________________________________________________________\nactivation_98 (Activation) (None, 4, 4, 70) 0 batch_normalization_98[0][0] \n__________________________________________________________________________________________________\nconv2d_99 (Conv2D) (None, 4, 4, 10) 6300 activation_98[0][0] \n__________________________________________________________________________________________________\nconcatenate_97 (Concatenate) (None, 4, 4, 80) 0 concatenate_96[0][0] \n conv2d_99[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_99 (BatchNo (None, 4, 4, 80) 320 concatenate_97[0][0] \n__________________________________________________________________________________________________\nactivation_99 (Activation) (None, 4, 4, 80) 0 batch_normalization_99[0][0] \n__________________________________________________________________________________________________\nconv2d_100 (Conv2D) (None, 4, 4, 10) 7200 activation_99[0][0] \n__________________________________________________________________________________________________\nconcatenate_98 (Concatenate) (None, 4, 4, 90) 0 concatenate_97[0][0] \n conv2d_100[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_100 (BatchN (None, 4, 4, 90) 360 concatenate_98[0][0] \n__________________________________________________________________________________________________\nactivation_100 (Activation) (None, 4, 4, 90) 0 batch_normalization_100[0][0] \n__________________________________________________________________________________________________\nconv2d_101 (Conv2D) (None, 4, 4, 10) 8100 activation_100[0][0] \n__________________________________________________________________________________________________\nconcatenate_99 (Concatenate) (None, 4, 4, 100) 0 concatenate_98[0][0] \n conv2d_101[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_101 (BatchN (None, 4, 4, 100) 400 concatenate_99[0][0] \n__________________________________________________________________________________________________\nactivation_101 (Activation) (None, 4, 4, 100) 0 batch_normalization_101[0][0] \n__________________________________________________________________________________________________\nconv2d_102 (Conv2D) (None, 4, 4, 10) 9000 activation_101[0][0] \n__________________________________________________________________________________________________\nconcatenate_100 (Concatenate) (None, 4, 4, 110) 0 concatenate_99[0][0] \n conv2d_102[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_102 (BatchN (None, 4, 4, 110) 440 concatenate_100[0][0] \n__________________________________________________________________________________________________\nactivation_102 (Activation) (None, 4, 4, 110) 0 batch_normalization_102[0][0] \n__________________________________________________________________________________________________\nconv2d_103 (Conv2D) (None, 4, 4, 10) 9900 activation_102[0][0] \n__________________________________________________________________________________________________\nconcatenate_101 (Concatenate) (None, 4, 4, 120) 0 concatenate_100[0][0] \n conv2d_103[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_103 (BatchN (None, 4, 4, 120) 480 concatenate_101[0][0] \n__________________________________________________________________________________________________\nactivation_103 (Activation) (None, 4, 4, 120) 0 batch_normalization_103[0][0] \n__________________________________________________________________________________________________\nconv2d_104 (Conv2D) (None, 4, 4, 10) 10800 activation_103[0][0] \n__________________________________________________________________________________________________\nconcatenate_102 (Concatenate) (None, 4, 4, 130) 0 concatenate_101[0][0] \n conv2d_104[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_104 (BatchN (None, 4, 4, 130) 520 concatenate_102[0][0] \n__________________________________________________________________________________________________\nactivation_104 (Activation) (None, 4, 4, 130) 0 batch_normalization_104[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_8 (AveragePoo (None, 2, 2, 130) 0 activation_104[0][0] \n__________________________________________________________________________________________________\nflatten_8 (Flatten) (None, 520) 0 average_pooling2d_8[0][0] \n__________________________________________________________________________________________________\ndense_8 (Dense) (None, 10) 5210 flatten_8[0][0] \n==================================================================================================\nTotal params: 316,430\nTrainable params: 308,890\nNon-trainable params: 7,540\n__________________________________________________________________________________________________\n" ], [ "# determine Loss function and Optimizer\nmodel.compile(loss='categorical_crossentropy',\n optimizer=Adam(),\n metrics=['accuracy'])", "_____no_output_____" ], [ "model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test))", "Train on 50000 samples, validate on 10000 samples\nEpoch 1/50\n50000/50000 [==============================] - 180s 4ms/step - loss: 1.4545 - acc: 0.4669 - val_loss: 1.4870 - val_acc: 0.4805\nEpoch 2/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 1.0447 - acc: 0.6253 - val_loss: 1.4468 - val_acc: 0.5152\nEpoch 3/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.8664 - acc: 0.6911 - val_loss: 1.1894 - val_acc: 0.5982\nEpoch 4/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.7459 - acc: 0.7351 - val_loss: 1.1462 - val_acc: 0.6042\nEpoch 5/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.6584 - acc: 0.7654 - val_loss: 0.8778 - val_acc: 0.7000\nEpoch 6/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.5926 - acc: 0.7918 - val_loss: 0.7641 - val_acc: 0.7360\nEpoch 7/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.5369 - acc: 0.8094 - val_loss: 0.8744 - val_acc: 0.7031\nEpoch 8/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.4904 - acc: 0.8267 - val_loss: 0.8466 - val_acc: 0.7261\nEpoch 9/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.4425 - acc: 0.8442 - val_loss: 0.7918 - val_acc: 0.7431\nEpoch 10/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.4124 - acc: 0.8541 - val_loss: 0.9630 - val_acc: 0.6955\nEpoch 11/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.3712 - acc: 0.8702 - val_loss: 0.7149 - val_acc: 0.7642\nEpoch 12/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.3375 - acc: 0.8808 - val_loss: 0.6844 - val_acc: 0.7744\nEpoch 13/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.3120 - acc: 0.8886 - val_loss: 0.7542 - val_acc: 0.7663\nEpoch 14/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.2817 - acc: 0.9001 - val_loss: 0.8027 - val_acc: 0.7620\nEpoch 15/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.2562 - acc: 0.9093 - val_loss: 0.7962 - val_acc: 0.7711\nEpoch 16/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.2384 - acc: 0.9139 - val_loss: 0.8849 - val_acc: 0.7597\nEpoch 17/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.2050 - acc: 0.9269 - val_loss: 0.9263 - val_acc: 0.7541\nEpoch 18/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.1970 - acc: 0.9290 - val_loss: 1.0754 - val_acc: 0.7388\nEpoch 19/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.1770 - acc: 0.9382 - val_loss: 0.8758 - val_acc: 0.7667\nEpoch 20/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.1595 - acc: 0.9439 - val_loss: 0.8421 - val_acc: 0.7815\nEpoch 21/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.1467 - acc: 0.9478 - val_loss: 0.9560 - val_acc: 0.7753\nEpoch 22/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.1354 - acc: 0.9515 - val_loss: 1.0912 - val_acc: 0.7477\nEpoch 23/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.1250 - acc: 0.9555 - val_loss: 0.9770 - val_acc: 0.7785\nEpoch 24/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.1158 - acc: 0.9582 - val_loss: 1.2133 - val_acc: 0.7418\nEpoch 25/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.1084 - acc: 0.9609 - val_loss: 0.9636 - val_acc: 0.7790\nEpoch 26/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.0958 - acc: 0.9661 - val_loss: 0.9585 - val_acc: 0.7848\nEpoch 27/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0902 - acc: 0.9684 - val_loss: 1.1402 - val_acc: 0.7639\nEpoch 28/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0938 - acc: 0.9672 - val_loss: 1.1056 - val_acc: 0.7749\nEpoch 29/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.0856 - acc: 0.9699 - val_loss: 1.0415 - val_acc: 0.7772\nEpoch 30/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.0878 - acc: 0.9686 - val_loss: 0.9899 - val_acc: 0.7906\nEpoch 31/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0734 - acc: 0.9736 - val_loss: 1.0923 - val_acc: 0.7811\nEpoch 32/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0671 - acc: 0.9766 - val_loss: 1.0998 - val_acc: 0.7842\nEpoch 33/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0874 - acc: 0.9690 - val_loss: 1.1965 - val_acc: 0.7679\nEpoch 34/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.0697 - acc: 0.9753 - val_loss: 1.0613 - val_acc: 0.7924\nEpoch 35/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.0637 - acc: 0.9772 - val_loss: 1.1539 - val_acc: 0.7792\nEpoch 36/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.0536 - acc: 0.9809 - val_loss: 1.2131 - val_acc: 0.7756\nEpoch 37/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.0713 - acc: 0.9759 - val_loss: 1.1403 - val_acc: 0.7774\nEpoch 38/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.0579 - acc: 0.9791 - val_loss: 1.4185 - val_acc: 0.7547\nEpoch 39/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.0601 - acc: 0.9790 - val_loss: 1.3267 - val_acc: 0.7589\nEpoch 40/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.0559 - acc: 0.9802 - val_loss: 1.3408 - val_acc: 0.7591\nEpoch 41/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.0519 - acc: 0.9817 - val_loss: 1.2716 - val_acc: 0.7768\nEpoch 42/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.0617 - acc: 0.9780 - val_loss: 1.1797 - val_acc: 0.7827\nEpoch 43/50\n50000/50000 [==============================] - 157s 3ms/step - loss: 0.0469 - acc: 0.9834 - val_loss: 1.1297 - val_acc: 0.7910\nEpoch 44/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0507 - acc: 0.9824 - val_loss: 1.2727 - val_acc: 0.7715\nEpoch 45/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.0509 - acc: 0.9820 - val_loss: 1.2945 - val_acc: 0.7746\nEpoch 46/50\n50000/50000 [==============================] - 158s 3ms/step - loss: 0.0503 - acc: 0.9827 - val_loss: 1.3407 - val_acc: 0.7789\nEpoch 47/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0425 - acc: 0.9853 - val_loss: 1.0995 - val_acc: 0.8047\nEpoch 48/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0366 - acc: 0.9876 - val_loss: 1.3071 - val_acc: 0.7775\nEpoch 49/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0543 - acc: 0.9813 - val_loss: 1.2440 - val_acc: 0.7888\nEpoch 50/50\n50000/50000 [==============================] - 159s 3ms/step - loss: 0.0467 - acc: 0.9838 - val_loss: 1.4180 - val_acc: 0.7568\n" ], [ "# Test the model\nscore = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n# Save the trained weights in to .h5 format\nmodel.save_weights(\"Yolo_Basic_model2.h5\")\nprint(\"Saved the model to disk\")", "10000/10000 [==============================] - 11s 1ms/step\nTest loss: 1.4179688464164735\nTest accuracy: 0.7568\nSaved the model to disk\n" ], [ "model.save_weights(\"Yolo_Basic_model2.h5\")\nprint(\"Saved the model to disk\")\nfrom google.colab import files\n\nfiles.download('Yolo_Basic_model.h5')", "Saved the model to disk\n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec50948cb4ca014c2854d7339de456f72456f648
33,404
ipynb
Jupyter Notebook
Flask_notebooks/_archive/User_Table_DB_Updates.ipynb
BloomTech-Labs/sound-drip-ds-x
35963e6ab26e6c35cd1ace48f4cfeafb5f55e915
[ "MIT" ]
6
2020-01-23T18:00:46.000Z
2020-05-07T20:39:24.000Z
Flask_notebooks/_archive/User_Table_DB_Updates.ipynb
BloomTech-Labs/sound-drip-ds-x
35963e6ab26e6c35cd1ace48f4cfeafb5f55e915
[ "MIT" ]
1
2020-02-24T23:51:50.000Z
2020-02-24T23:51:50.000Z
Flask_notebooks/_archive/User_Table_DB_Updates.ipynb
BloomTech-Labs/sound-drip-ds-x
35963e6ab26e6c35cd1ace48f4cfeafb5f55e915
[ "MIT" ]
null
null
null
30.901018
1,285
0.53757
[ [ [ "import psycopg2 as ps\nimport spotipy\nimport spotipy.util as util\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.preprocessing import MinMaxScaler, Normalizer\nimport pandas as pd\nfrom pandas.io.json import json_normalize\nfrom flask import jsonify\nfrom joblib import load\nimport pickle\nimport numpy as np\nfrom flask import request\nfrom joblib import dump\nfrom joblib import load\nimport pandas as pd\nimport importlib\n\nfrom env_vars import * \n\nimport SD_mod", "_____no_output_____" ], [ "type(SD_mod)", "_____no_output_____" ], [ "importlib.reload(SD_mod)", "_____no_output_____" ], [ "from SD_mod import *", "_____no_output_____" ] ], [ [ "# Variables for DB inserts", "_____no_output_____" ] ], [ [ "# USERNAME = 'rileypence4' #your spotify username\n# CLIENT_ID = '47c4f0d3dcaa433c9ef4ec6686e5b1f1' #set at your developer account\n# CLIENT_SECRET = '65812a5fb52b4a3486f59ec672d499ff' #set at your developer account\n# REDIRECT_URI = 'https://google.com/' #set at your developer account, usually \"http://localhost:8000\"\n# SCOPE = 'user-library-read' # or else\n# # ps. REDIRECT_URI is crucial here. if http://localhost:8000 is not set, or with a single '/' misplaced, it will generate a connection error.\n\n# then pass them:\n\ntoken = util.prompt_for_user_token(username = USERNAME, \n scope = SCOPE, \n client_id = CLIENT_ID, \n client_secret = CLIENT_SECRET, \n redirect_uri = REDIRECT_URI)\n\nif token:\n sp = spotipy.Spotify(auth=token)", "_____no_output_____" ], [ "token", "_____no_output_____" ], [ "token = 'BQAHmweLxptaAB2jWC0fj2FateE-y98orcBbygQIdwZanpBAaIkk7niAouIV2WtAkmzlJAz3VXdB1HBv7mwiFe-eDxOus4WsmPFBbsPaDiCul6h3OxJURcWRk69QfyD34TXoKEruluj1M-cbl-2ato2CkGr3nQ'", "_____no_output_____" ], [ "# class Sound_Drip:\n \n# def __init__(self, token):\n# self.token = token\n \n# def instantiate_sp(self,token):\n# sp = spotipy.Spotify(auth=token)\n# return sp\n\n# def get_user_song_id(self,sp):\n# results = sp.current_user_saved_tracks()\n# genre = []\n# counter = 0 \n# for song_number in range(0,19):\n# counter += 1 \n# song_id = results['items'][song_number]['track']['id']\n# artist_id = self.get_artist_id(song_id)\n# genre = self.get_genres(artist_id)\n# if genre != []:\n# break\n# return song_id\n\n# def get_acoustical_features(self,song_id,sp):\n# acoustical_features = sp.audio_features(song_id)[0]\n# return acoustical_features\n\n# def get_popularity(self, song_id):\n# popularity = sp.track(song_id)['popularity']\n# return popularity\n\n# def get_artist_id(self, song_id):\n# artist = sp.track(song_id)['artists'][0]['id']\n# return artist\n\n# def get_genres(self, artist):\n# genre = sp.artist(artist)['genres']\n# return genre\n \n# def create_feature_object(self,popularity, acoustical_features):\n# popularity_dict = {'popularity': popularity}\n# song_features = acoustical_features\n# song_features.update(popularity_dict)\n# song_features = {\n# \"audio_features\": {\n# key: song_features[key] for key in song_features.keys() & {\n# 'popularity',\n# 'acousticness',\n# 'danceability',\n# 'energy',\n# 'instrumentalness',\n# 'key',\n# 'liveness',\n# 'loudness',\n# 'mode',\n# 'speechiness',\n# 'tempo',\n# 'time_signature',\n# 'valence'}}}\n\n# df = pd.DataFrame.from_dict(json_normalize(song_features[\"audio_features\"]),orient='columns') \n# df = df.reindex(sorted(df.columns), axis=1)\n# return df\n \n# def get_results(self,song_features_df):\n# scaler = load(\"./models/scalar3.joblib\")\n# print('Scaling data...')\n# data_scaled = scaler.transform(song_features_df)\n# normalizer = Normalizer()\n# data_normalized = normalizer.fit_transform(data_scaled)\n# print('Loading pickled model...')\n# model = load('./models/model5.joblib')\n# results = model.kneighbors([data_normalized][0])[1:]\n# print('results returned')\n# return results[0]\n \n# def filter_model(self,model_results,source_genre_list): \n# #loop takes KNN results and filters by source track genres\n# print(\"filter for genres initiated\")\n# genre_array = pickle.load(open(\"./data/genres_array_2.pkl\",\"rb\"))\n# filtered_list = []\n# song_list_length = 20\n# for output_song_index in model_results[0][1:]:\n# output_genre_list = genre_array[output_song_index]\n# for output_genre in output_genre_list:\n# output_genre = output_genre.strip(\" \")\n# for source_genre in source_genre_list:\n# source_genre = \"'\" + source_genre + \"'\"\n# if source_genre == output_genre:\n# filtered_list.append(output_song_index)\n# else:\n# continue\n# if len(set(filtered_list)) > song_list_length:\n# print(\"filter found at least 20 genre matches\")\n# filtered_list = set(filtered_list)\n# filtered_list = list(filtered_list)[0:20]\n# else:\n# counter = song_list_length - len(set(filtered_list))\n# print(len(set(filtered_list)))\n# print(counter)\n# print(f'need to add {counter} items to final song output')\n# for output_song_index in model_results[1:]:\n# if output_song_index not in filtered_list:\n# if counter > 0:\n# filtered_list.append(output_song_index)\n# counter -= 1\n# else:\n# break\n# print(\"filtered list with 20 unique song indices returned\")\n# return filtered_list\n \n# def song_id_prediction_output(self,filtered_list): \n# similar_songs = []\n# print('song_id_list loading...')\n# song_id_array = pickle.load(open('./data/song_id_array3.pkl', 'rb'))\n# print('song_id_list loaded')\n# for song_row in filtered_list:\n# song_id = song_id_array[song_row]\n# similar_songs.append({'similarity': [.99], 'values': song_id})\n# json_dict = {\"songs\": similar_songs}\n# print(\"Results returned\")\n# return json_dict\n \n# def get_user_ids(self, sp):\n# current_user_dict = sp.current_user()\n# display_name = current_user_dict['display_name']\n# user_id = current_user_dict['id']\n# return user_id, display_name", "_____no_output_____" ], [ "importlib.reload(SD_mod)\nfrom SD_mod import *\nsd_obj = Sound_Drip(token)", "retrieving user id and display name for current token\n['3E940gpOthnGBcxuWkp8UY', '627k7rjvtLuo9nE4n2s3SI', '5nyHz4PQWvru7EUesNAt0O', '43ile6cBzr9uaC4bJf6J3N', '3seoFkiuUwCVrjnPpp4jRb', '7sqgV3wwdHFWCkaYNJkY7o', '5Jyb7sh76nwgmBqx5V1v51', '27r5zOoscJYQOkWpDmv4Pm', '5lZ5FU8kf7vyOlECQmtw4u', '6qK0apPspdUTGwUERX6kxb', '22t3vCXfjQhIiXzGVSZNOz', '6XLAJtcObiSdliKMO8uZAA', '3V1oeP60i7Er7QbwzQTYdO', '3WzGnwyAWuYzYXPJWCH4dL', '3wUMQpY40eJrnqIDsyfYfQ', '0XLjSQWYkZQOjyOcMe11cV', '1VqSNvqsOCfPmy7klz0i6f', '090a3fK6DnEKCECdfctvYy', '5zb7npjQqoJ7Kcpq4yD9qn', '3lLClwUDcHYsCInBKn57r4', '5udMby0ZOIAASL5qwFnUuM', '1WbwlYiiMZGQlrFGirRnHv', '340nQIqGeYYIdrWaUyeAOf', '7znZstuIvZjldNIO1E11U4', '72BLFDUJWvAEwvVf0JDIfO', '2nBtV4NSZJiarMBMpsn6UH', '7A1d0qBQL2IiDhrDrhUqE8', '3khnwbi2ZxydY4rlnK6FDU', '2JwfiG3QhMaj9BRpbIEyGN', '34nixLtq739l1cY1eGCSW0', '6vUA999IXXgLNPS8lQ89zF', '4yJDr9tJqnngXZ7cQl0g15', '4v9rHzCDgQXbDdB7t4Nwcz', '0FfxiP97Bj0tT5WcEiwmDo', '7yx9rpfQVdXD0674hX4Zl0', '2tA5dpjf7xzzkMXCOWikdk', '1tRjY29xhTYP6QJOO9v7lg', '1FDNASh3QfLrG2N7vNoBOw', '11HpNMd6I6cpi64Y36U3ju', '7Hr8doHwfnAsaeme57NNpX', '7mB5AgvBYc6QasgzTxrugB', '3vZGa55PU49qfgrZYgr0v8', '0WMgVB4OEm5JEj08lBtBgf', '0zmHKnEvizzz9AXFyBd3yK', '4oPq32lOh8Eg5kkdzt1VMp', '7DpYj9ZxQ9FTRhDdN18e2E', '1Qg7tAfpy2tuvJ4WSDv247', '0EJAJbxjHV4b4MAtD9fCB4', '2F1XmP93IwOwhBo5gOhwqt']\n50\nsong number: 0\n34nixLtq739l1cY1eGCSW0\nnot enough songs found\nsong number: 1\n090a3fK6DnEKCECdfctvYy\nnot enough songs found\nsong number: 2\n27r5zOoscJYQOkWpDmv4Pm\nnot enough songs found\nsong number: 3\n2nBtV4NSZJiarMBMpsn6UH\nnot enough songs found\nsong number: 4\n72BLFDUJWvAEwvVf0JDIfO\nnot enough songs found\nsong number: 5\n340nQIqGeYYIdrWaUyeAOf\nnot enough songs found\nsong number: 6\n3wUMQpY40eJrnqIDsyfYfQ\nnot enough songs found\nsong number: 7\n4v9rHzCDgQXbDdB7t4Nwcz\nnot enough songs found\nsong number: 8\n22t3vCXfjQhIiXzGVSZNOz\nnot enough songs found\nsong number: 9\n5Jyb7sh76nwgmBqx5V1v51\nnot enough songs found\nsong number: 10\n3seoFkiuUwCVrjnPpp4jRb\nnot enough songs found\nsong number: 11\n7znZstuIvZjldNIO1E11U4\nnot enough songs found\nsong number: 12\n0FfxiP97Bj0tT5WcEiwmDo\nnot enough songs found\nsong number: 13\n627k7rjvtLuo9nE4n2s3SI\nnot enough songs found\nsong number: 14\n43ile6cBzr9uaC4bJf6J3N\nnot enough songs found\nsong number: 15\n2tA5dpjf7xzzkMXCOWikdk\nnot enough songs found\nsong number: 16\n7mB5AgvBYc6QasgzTxrugB\nnot enough songs found\nsong number: 17\n6XLAJtcObiSdliKMO8uZAA\nnot enough songs found\nsong number: 18\n5zb7npjQqoJ7Kcpq4yD9qn\nnot enough songs found\nsong number: 19\n1VqSNvqsOCfPmy7klz0i6f\nnot enough songs found\nsong number: 20\n0EJAJbxjHV4b4MAtD9fCB4\nnot enough songs found\nsong number: 21\n7sqgV3wwdHFWCkaYNJkY7o\nnot enough songs found\nsong number: 22\n3khnwbi2ZxydY4rlnK6FDU\nnot enough songs found\nsong number: 23\n4yJDr9tJqnngXZ7cQl0g15\nnot enough songs found\nsong number: 24\n0dgkso7LCJ0oQRIOVEefO1\nartist_id: 2ZDXyjvjJDtBUKahm32zoO\ngenre: []\nsong number: 25\n2JwfiG3QhMaj9BRpbIEyGN\nnot enough songs found\nsong number: 26\n7yx9rpfQVdXD0674hX4Zl0\nnot enough songs found\nsong number: 27\n1WbwlYiiMZGQlrFGirRnHv\nnot enough songs found\nsong number: 28\n4fvKMNF4VCvy1BB9YDyZCi\nartist_id: 18UXMAe8MYg68DcC7qynaT\ngenre: []\nsong number: 29\n7DpYj9ZxQ9FTRhDdN18e2E\nnot enough songs found\nsong number: 30\n7Hr8doHwfnAsaeme57NNpX\nnot enough songs found\nsong number: 31\n3lLClwUDcHYsCInBKn57r4\nnot enough songs found\nsong number: 32\n0WMgVB4OEm5JEj08lBtBgf\nnot enough songs found\nsong number: 33\n5udMby0ZOIAASL5qwFnUuM\nnot enough songs found\nsong number: 34\n3vZGa55PU49qfgrZYgr0v8\nnot enough songs found\nsong number: 35\n1Qg7tAfpy2tuvJ4WSDv247\nnot enough songs found\nsong number: 36\n1FDNASh3QfLrG2N7vNoBOw\nnot enough songs found\nsong number: 37\n11HpNMd6I6cpi64Y36U3ju\nnot enough songs found\nsong number: 38\n2F1XmP93IwOwhBo5gOhwqt\nnot enough songs found\nsong number: 39\n4oPq32lOh8Eg5kkdzt1VMp\nnot enough songs found\nsong number: 40\n5lZ5FU8kf7vyOlECQmtw4u\nnot enough songs found\nsong number: 41\n6qK0apPspdUTGwUERX6kxb\nnot enough songs found\nsong number: 42\n1tRjY29xhTYP6QJOO9v7lg\nnot enough songs found\nsong number: 43\n3V1oeP60i7Er7QbwzQTYdO\nnot enough songs found\nsong number: 44\n0zmHKnEvizzz9AXFyBd3yK\nnot enough songs found\nsong number: 45\n7A1d0qBQL2IiDhrDrhUqE8\nnot enough songs found\nsong number: 46\n0XLjSQWYkZQOjyOcMe11cV\nnot enough songs found\nsong number: 47\n6vUA999IXXgLNPS8lQ89zF\nnot enough songs found\nsong number: 48\n3WzGnwyAWuYzYXPJWCH4dL\nnot enough songs found\nsong number: 49\n5nyHz4PQWvru7EUesNAt0O\nnot enough songs found\n3E940gpOthnGBcxuWkp8UY\nthe genre is: ['bass house', 'deep rai', 'jump up', 'uk dnb']\nScaling data...\nLoading pickled model...\nresults returned\n['bass house', 'deep rai', 'jump up', 'uk dnb']\nfilter for genres initiated\n414 stale tracks were removed for the user\nlength of filtered list: 0\nneed to add 20 items to final song output\nfiltered list with 20 unique song indices returned\nsong_id_list loading...\nsong_id_list loaded\nResults returned\npredicts inserted into db\n" ], [ "sd = Sound_Drip(token)\nsp = sd.instantiate_sp(token)\nsong_id = sd.get_user_song_id(sp)\nacoustical_features = sd.get_acoustical_features(song_id, sp)\npopularity = sd.get_popularity(song_id)\nsong_features_df = sd.create_feature_object(popularity, acoustical_features)\nresults = sd.get_results(song_features_df)\nsource_genre = sd.get_genres(sd.get_artist_id(song_id))\nfiltered_list = sd.filter_model(results,source_genre)\nsd.song_id_prediction_output(filtered_list)", "_____no_output_____" ], [ "sd_obj.get_stale_seed()", "_____no_output_____" ], [ "sd_obj.get_stale_results()", "_____no_output_____" ] ], [ [ "# Db Calls Sandbox", "_____no_output_____" ] ], [ [ "def connect():\n conn = ps.connect(host=POSTGRES_ADDRESS,\n database=POSTGRES_DBNAME,\n user=POSTGRES_USERNAME,\n password=POSTGRES_PASSWORD,\n port=POSTGRES_PORT)\n cur = conn.cursor()\n return conn,cur", "_____no_output_____" ], [ "# def run_query():\n# try:\n# cur.execute(query)\n# except Exception as e:\n# print (e.message)\n# return reconnect()", "_____no_output_____" ], [ "# run_query()", "_____no_output_____" ], [ "user_id = sd_obj.user_id", "_____no_output_____" ], [ "user_id", "_____no_output_____" ], [ "query = f'SELECT DISTINCT (songlistindex) FROM recommendations WHERE userid = \\'{user_id}\\';'\n\ncur.execute(query)\nlist_of_goodies = cur.fetchall()", "_____no_output_____" ], [ "stale_results = []\nfor index in list_of_goodies:\n stale_results.append(index[0])\nstale_results", "_____no_output_____" ], [ "sd_obj.insert_user_predictions()", "_____no_output_____" ], [ "sd_obj.song_id_predictions[1]", "_____no_output_____" ], [ "conn,cur = sd_obj.db_connect()", "_____no_output_____" ], [ "query = \"\"\"DELETE FROM recommendations WHERE userid = 'rileypence4';\"\"\"\n\ncur.execute(query)\n# cur.fetchall()\nconn.commit()", "_____no_output_____" ], [ "query = \"\"\"ALTER TABLE recommendations DROP CONSTRAINT recommendations_id;\"\"\"\ncur.execute(query)\nconn.commit()\n# conn.close()\n\n# ALTER TABLE recommendations DROP CONSTRAINT id", "_____no_output_____" ], [ "f'ewfjhewjfhewjhfew'", "_____no_output_____" ], [ "# cur.execute(\"\"\"DROP TABLE recommendations;\"\"\")\n# conn.commit()", "_____no_output_____" ], [ "#deciding to remove users table as it is redundant \n\n# cur.execute(\"\"\"CREATE TABLE users\n# (id serial PRIMARY KEY, \n# display_name varchar(50),\n# userID varchar(50)\n# );\"\"\")\n# # Commit table creation\n# conn.commit()", "_____no_output_____" ], [ "# cur.execute(\"\"\"CREATE TABLE recommendations\n# (id serial PRIMARY KEY,\n# userID varchar(50), \n# songID varchar(50),\n# songlistindex integer,\n# recDate DATE \n# )\"\"\")\n# # Commit table creation\n# conn.commit()", "_____no_output_____" ], [ "# query = \"\"\"SELECT * FROM users\n# WHERE schemaname != 'pg_catalog'\n# AND schemaname != 'information_schema';\"\"\"\n# cur.execute(query)\n# cur.fetchall()", "_____no_output_____" ], [ "user_id", "_____no_output_____" ], [ "song_id", "_____no_output_____" ], [ "sd_obj.song_id_predictions", "_____no_output_____" ], [ "song_id_index = sd_obj.song_id_predictions[1]", "_____no_output_____" ], [ "user_id = sd_obj.user_id", "_____no_output_____" ], [ "user_id", "_____no_output_____" ], [ "conn, cur = connect()", "_____no_output_____" ], [ "#only insert statement that we're using\nfor song_id,song_index in song_id_index.items():\n cur.execute(\n 'INSERT INTO recommendations'\n '(userid,songid,songlistindex,recdate)'\n f' VALUES (\\'{user_id}\\',\\'{song_id}\\',\\'{song_index}\\',current_timestamp);')\nconn.commit()", "_____no_output_____" ], [ "# cur.execute(\n# f'INSERT INTO users'\n# f'(display_name,userid)'\n# f' VALUES (\\'{display_name}\\',\\'{user_id}\\');')\n# conn.commit()", "_____no_output_____" ], [ "insertstatement1 {songid_lis[0]}\ninsertstatement1 {songid_lis[1]}", "_____no_output_____" ], [ "(f'INSERT INTO users (songid, artist, track) VALUES (\\\"{f[\"songid\"]}\\\",\\\"{f[\"artist\"]}\\\",\\\"{f[\"track\"]}\\\", {f[\"danceability\"]}, {f[\"energy\"]}, {f[\"key\"]}, {f[\"loudness\"]}, {f[\"mode\"]}, {f[\"speechiness\"]}, {f[\"acousticness\"]}, {f[\"instrumentalness\"]}, {f[\"liveness\"]}, {f[\"valence\"]}, {f[\"tempo\"]}, {f[\"duration_ms\"]},{f[\"time_signature\"]});')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "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", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec5098560be0c70756144cfbbc3a08a882a76c3b
261,878
ipynb
Jupyter Notebook
P1.ipynb
cseHdz/LaneLines
1735c1bc54f595a9858434ca919df3713befcecb
[ "MIT" ]
null
null
null
P1.ipynb
cseHdz/LaneLines
1735c1bc54f595a9858434ca919df3713befcecb
[ "MIT" ]
null
null
null
P1.ipynb
cseHdz/LaneLines
1735c1bc54f595a9858434ca919df3713befcecb
[ "MIT" ]
null
null
null
282.196121
116,972
0.917989
[ [ [ "# Self-Driving Car Engineer Nanodegree\n\n\n## Project: **Finding Lane Lines on the Road** \n***\nIn this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n\nOnce you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n\nIn addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n\n---\nLet's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n\n**Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n\n---", "_____no_output_____" ], [ "**The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.**\n\n---\n\n<figure>\n <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n </figcaption>\n</figure>\n <p></p> \n<figure>\n <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n </figcaption>\n</figure>", "_____no_output_____" ], [ "**Run the cell below to import some packages. If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.** ", "_____no_output_____" ], [ "## Import Packages", "_____no_output_____" ] ], [ [ "#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Read in an Image", "_____no_output_____" ] ], [ [ "#reading in an image\nimage = mpimg.imread('test_images/solidWhiteRight.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(image), 'with dimensions:', image.shape)\nplt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')", "This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)\n" ] ], [ [ "## Ideas for Lane Detection Pipeline", "_____no_output_____" ], [ "**Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**\n\n`cv2.inRange()` for color selection \n`cv2.fillPoly()` for regions selection \n`cv2.line()` to draw lines on an image given endpoints \n`cv2.addWeighted()` to coadd / overlay two images\n`cv2.cvtColor()` to grayscale or change color\n`cv2.imwrite()` to output images to file \n`cv2.bitwise_and()` to apply a mask to an image\n\n**Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**", "_____no_output_____" ], [ "## Helper Functions", "_____no_output_____" ], [ "Below are some helper functions to help get you started. They should look familiar from the lesson!", "_____no_output_____" ] ], [ [ "import math\n\ndef grayscale(img):\n \"\"\"Applies the Grayscale transform\n This will return an image with only one color channel\n but NOTE: to see the returned image as grayscale\n (assuming your grayscaled image is called 'gray')\n you should call plt.imshow(gray, cmap='gray')\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Or use BGR2GRAY if you read an image with cv2.imread()\n # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \ndef canny(img, low_threshold, high_threshold):\n \"\"\"Applies the Canny transform\"\"\"\n return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n `vertices` should be a numpy array of integer points.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, [vertices], ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=2):\n \"\"\"\n NOTE: this is the function you might want to use as a starting point once you want to \n average/extrapolate the line segments you detect to map out the full\n extent of the lane (going from the result shown in raw-lines-example.mp4\n to that shown in P1_example.mp4). \n \n Think about things like separating line segments by their \n slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n line vs. the right line. Then, you can average the position of each of \n the lines and extrapolate to the top and bottom of the lane.\n \n This function draws `lines` with `color` and `thickness`. \n Lines are drawn on the image inplace (mutates the image).\n If you want to make the lines semi-transparent, think about combining\n this function with the weighted_img() function below\n \"\"\"\n for line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(img, (x1, y1), (x2, y2), color, thickness)\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\"\n `img` should be the output of a Canny transform.\n \n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n draw_lines(line_img, lines)\n return line_img\n\n# Python 3 has support for cool math symbols.\n\ndef weighted_img(img, initial_img, α=0.8, β=1., γ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n \n `initial_img` should be the image before any processing.\n \n The result image is computed as follows:\n \n initial_img * α + img * β + γ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, γ)", "_____no_output_____" ] ], [ [ "## Test Images\n\nBuild your pipeline to work on the images in the directory \"test_images\" \n**You should make sure your pipeline works well on these images before you try the videos.**", "_____no_output_____" ] ], [ [ "import os\nos.listdir(\"test_images/\")", "_____no_output_____" ] ], [ [ "## Build a Lane Finding Pipeline\n\n", "_____no_output_____" ], [ "Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n\nTry tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.", "_____no_output_____" ] ], [ [ "def get_mean_lines(lines, y_max):\n \n \"\"\"\n Get the left and right average lines based on Hough Lines\n Parameters:\n lines ([np.array]): An array of numpy arrays of lines \n in the form [[x1,y1,x2,y2]]\n \n Returns:\n A numpy array of lines in the form [[x1,y1,x2,y2]]\n \"\"\"\n def calc_slope(line):\n for x1,y1,x2,y2 in line:\n return (y2-y1)/(x2-x1)\n \n def calc_intercept(line, slope):\n for x1,y1,x2,y2 in line:\n return y1 - slope*x1 \n \n def calc_length(line):\n for x1,y1,x2,y2 in line:\n return math.sqrt(math.pow((x2-x1),2)+math.pow((y2-y1),2))\n \n def get_weighted_mean(lines):\n \n distances = np.array([calc_length(line) for line in lines])\n total_distance = distances.sum()\n \n distances = distances/total_distance\n \n means = np.array(lines)\n for i in range(0, len(distances)):\n \n d = distances[i]\n means[i] = means[i] * d \n \n means = means.sum(axis=0)\n \n return means\n \n\n def get_mean_parameters(lines):\n means = np.array(lines).mean(axis=0)\n m = calc_slope(means)\n b = calc_intercept(means, m)\n\n return m, b\n \n def get_lines_instersection(m1, b1, m2, b2):\n \n x = int((b2-b1)/(m1-m2))\n y = int(m1*x + b1)\n return x, y\n \n def get_line(m, b, y1, y2):\n x1 = int((y1 - b)/m)\n x2 = int((y2 - b)/m)\n\n return np.array([[x1,y1,x2,y2]])\n\n def split_lines(lines):\n\n left_lines = []\n right_lines = []\n\n for line in lines:\n\n slope = calc_slope(line)\n \n if slope >= 0.3:\n right_lines.append(line) \n elif slope <= -0.3:\n left_lines.append(line) \n\n return left_lines, right_lines\n \n left_lines, right_lines = split_lines(lines)\n \n # Get Line Parameters\n left_m, left_b = get_mean_parameters(left_lines)\n right_m, right_b = get_mean_parameters(right_lines)\n \n # Draw the lines until they intersect\n y1 = get_lines_instersection(left_m, left_b, right_m, right_b)[1]\n y2 = y_max\n \n # Calculate average lines\n left_line = get_line(left_m, left_b, y1, y2)\n right_line = get_line(right_m, right_b, y1, y2)\n \n return [left_line, right_line]", "_____no_output_____" ], [ "def get_hough_connected_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \n \"\"\"\n Returns hough connected lines by mean\n \"\"\"\n\n thresholds = [max_line_gap, max_line_gap*1.5, max_line_gap*2]\n \n for t in thresholds:\n \n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([])\n , minLineLength=t, maxLineGap=max_line_gap)\n try:\n mean_lines = get_mean_lines(lines, img.shape[0])\n return mean_lines\n except:\n return lines\n \n return mean_lines", "_____no_output_____" ], [ "def draw_hough_connected_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\"\n `img` should be the output of a Canny transform.\n \n Returns an image with hough lines drawn.\n \"\"\"\n \n lines = get_hough_connected_lines(img, rho, theta, threshold, min_line_len, max_line_gap) \n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n draw_lines(line_img, lines, thickness=10)\n \n return line_img", "_____no_output_____" ], [ "def process_img(img):\n \"\"\"\n Processes an image to recognize line lanes\n Parameters:\n img(Image): The image to be processed\n Returns an image with line lanes identified in red\n \"\"\"\n \n # 1. Convert image to gray scale\n gray = grayscale(img)\n \n # 2. De-noise the image through gaussian blur\n kernel_size = 7\n blur = gaussian_blur(gray, kernel_size)\n \n # 3. Apply Canny Edges to find image edges\n low_threshold = 60\n high_threshold = low_threshold*3\n canny = cv2.Canny(blur, low_threshold, high_threshold)\n \n # 4. Bound image to region of interest\n # Define vertices aligned with image shape\n left_bottom = [int(img.shape[1]*0.1), img.shape[0]]\n right_bottom = [int(img.shape[1]*0.9), img.shape[0]]\n \n # Prioritize the bottom half of the image (horizon line perspective)\n apex = [int(img.shape[1]/2), int(img.shape[0]*0.5)] \n \n region = region_of_interest(canny, np.array([left_bottom, right_bottom, apex]))\n \n # 5. Draw Hough Lines \n rho = 2 # Distance resolution - Perpendicular distance from origin to the line\n theta = np.pi/180 # Angular Resolution - Angle of perpendicular line\n threshold = 10 # Minimum number of ocurrences (votes)\n min_line_len = 40 # Minimum length of a line to be recognized\n max_line_gap = 20 # Maximum gap in pixes between lines\n\n lines=draw_hough_connected_lines(region, rho, theta, threshold, min_line_len, max_line_gap) \n# lines=hough_lines(region, rho, theta, threshold, min_line_len, max_line_gap) \n \n # 6 . Add Hough Lines to Original Image\n processed_img = weighted_img(lines, img) \n\n return processed_img\n", "_____no_output_____" ], [ "base_dir = \"test_images/\"\nimages = os.listdir(\"test_images/\")\n\nimg = mpimg.imread(base_dir + images[3])\nprocessed_img = process_img(img)\n\nplt.imshow(processed_img)", "_____no_output_____" ], [ "base_dir = \"test_images/\"\n\nfor img_path in os.listdir(\"test_images/\"):\n \n output_dir = \"test_images_output/\"\n \n img = mpimg.imread(base_dir + img_path)\n processed_img = process_img(img)\n\n plt.imsave(output_dir + img_path, processed_img)", "_____no_output_____" ] ], [ [ "## Test on Videos\n\nYou know what's cooler than drawing lanes over images? Drawing lanes over video!\n\nWe can test our solution on two provided videos:\n\n`solidWhiteRight.mp4`\n\n`solidYellowLeft.mp4`\n\n**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n\n**If you get an error that looks like this:**\n```\nNeedDownloadError: Need ffmpeg exe. \nYou can download it by calling: \nimageio.plugins.ffmpeg.download()\n```\n**Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**", "_____no_output_____" ] ], [ [ "# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML", "_____no_output_____" ], [ "def process_image(image):\n \n return process_img(image)", "_____no_output_____" ] ], [ [ "Let's try the one with the solid white lane on the right first ...", "_____no_output_____" ] ], [ [ "white_output = 'test_videos_output/solidWhiteRight.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n%time white_clip.write_videofile(white_output, audio=False)", "[MoviePy] >>>> Building video test_videos_output/solidWhiteRight.mp4\n[MoviePy] Writing video test_videos_output/solidWhiteRight.mp4\n" ] ], [ [ "Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.", "_____no_output_____" ] ], [ [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))", "_____no_output_____" ] ], [ [ "## Improve the draw_lines() function\n\n**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n\n**Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**", "_____no_output_____" ], [ "Now for the one with the solid yellow lane on the left. This one's more tricky!", "_____no_output_____" ] ], [ [ "yellow_output = 'test_videos_output/solidYellowLeft.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\nyellow_clip = clip2.fl_image(process_image)\n%time yellow_clip.write_videofile(yellow_output, audio=False)", "[MoviePy] >>>> Building video test_videos_output/solidYellowLeft.mp4\n[MoviePy] Writing video test_videos_output/solidYellowLeft.mp4\n" ], [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))", "_____no_output_____" ] ], [ [ "## Writeup and Submission\n\nIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.\n", "_____no_output_____" ], [ "## Optional Challenge\n\nTry your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!", "_____no_output_____" ] ], [ [ "challenge_output = 'test_videos_output/challenge.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)\nclip3 = VideoFileClip('test_videos/challenge.mp4')\nchallenge_clip = clip3.fl_image(process_image)\n%time challenge_clip.write_videofile(challenge_output, audio=False)", "[MoviePy] >>>> Building video test_videos_output/challenge.mp4\n[MoviePy] Writing video test_videos_output/challenge.mp4\n" ], [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(challenge_output))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
ec509cfa976009df7357934b1e6c54d7ee2c1637
80,150
ipynb
Jupyter Notebook
main.py.ipynb
gayathrivs7/MakeComplaint
d09dcd9a67414ffae199765b4e6d4b4397769916
[ "MIT" ]
null
null
null
main.py.ipynb
gayathrivs7/MakeComplaint
d09dcd9a67414ffae199765b4e6d4b4397769916
[ "MIT" ]
null
null
null
main.py.ipynb
gayathrivs7/MakeComplaint
d09dcd9a67414ffae199765b4e6d4b4397769916
[ "MIT" ]
null
null
null
106.866667
27,832
0.694261
[ [ [ "import nltk\nimport spacy\nimport pandas as pd\n\nnlp = spacy.load('en') #loading English\n\n\n#opening csv\nmyfile = open('/home/gayathri/project/MakeComplaint/data.csv').read()\ndata=nlp(myfile)\n\n#df=pd.DataFrame(data=data)\n#df=nlp(df)\n#print(df)\nprint(type(data))\nfor token in data[:8]:\n print(token.text)\n#fetching the headers\n\n#for colname in frames:\n #print(colname.columns)\n \n \n \n#keys = ['Water Authority','KSEB','KSRTC','PWD','Environment and climate change','MVD']\n#df=pd.concat(frames,keys=keys)\n#df\n\n\n\n#print(doc_file)\n\n#tokenizer=nltk.tokenize.TreebankWordTokenizer()\n#tokens=tokenizer.tokenize(text)\n#print(\"Tree\", tokens)", "<class 'spacy.tokens.doc.Doc'>\nid\n,\nSubject\n,\nComplaint\n,\nDepartments\n\n\n" ], [ "import pandas as pd\nimport matplotlib.pyplot as plt\n\ndataset= pd.read_csv('/home/gayathri/project/MakeComplaint/data.csv')\ndataset['Departments'].unique() ", "_____no_output_____" ], [ "import pandas as pd\nimport matplotlib.pyplot as plt\n\ndataset= pd.read_csv('/home/gayathri/project/MakeComplaint/data.csv')\n\ndataset.head()\n\n\n\n\n\n", "_____no_output_____" ], [ "import pandas as pd\nimport matplotlib.pyplot as plt\n\ndataset= pd.read_csv('/home/gayathri/project/MakeComplaint/data.csv')\n\n\n\n\ndataset.Departments.value_counts().plot(kind='pie', \n figsize=(8,6), \n fontsize=13, \n autopct='%1.1f%%', \n wedgeprops={'linewidth': 5}\n )\nplt.axis('off')\nplt.axis('equal')", "_____no_output_____" ], [ "import pandas as pd\nimport matplotlib.pyplot as plt\nfrom nltk.corpus import stopwords \nimport nltk\nfrom nltk.tokenize import word_tokenize \nfrom collections import Counter\nfrom gensim.summarization import summarize\n\n\n\n#Data cleaning\n\n# 1. unpunctuate /home/gayathri/Complaint/MakeComplaint/\n# 2. to lower\n# 3. Remove numerals\n# 4. Remove Newline for subject\n\n\n# Data loading\ndataset= pd.read_csv('/home/gayathri/project/MakeComplaint/data.csv')\n\n\n# unpunctuate and lower case\ndataset['Subject'] = dataset['Subject'].str.replace('[^\\w\\s]','').str.lower()\n\n\n# unpunctuate and lower case\ndataset['Complaint'] = dataset['Complaint'].str.replace('[^\\w\\s]','').str.lower() \n\n\n#rRemoving new lines in the subject field\ndataset['Subject'] = dataset['Subject'].str.rstrip('\\n')\n\n#removing Numeric \ndataset['Complaint'] = dataset['Complaint'].str.replace('[^a-zA-Z ]','').str.lower()\n#print(dataset.head())\n\n\n\n# creating dataframe for each departments\nwater = dataset.loc[dataset['Departments'] == 'Water Authority']\npwd = dataset.loc[dataset['Departments'] == 'PWD']\nksrtc = dataset.loc[dataset['Departments'] == 'KSRTC']\nkseb = dataset.loc[dataset['Departments'] == 'KSEB']\nenv = dataset.loc[dataset['Departments'] == 'Environment and climate change']\n\n#print(env.shape) #(30, 4)\n#print(water.shape) #(39, 4)\n#print(pwd.shape) #(42, 4)\n#print(ksrtc.shape) #(17, 4)\n#print(kseb.shape) #(22, 4)\n#dataset.head()\n#print(pwd)\n\n#Filtering out Subjects and complaints from the dataframe\ndf_water = water[['Subject','Complaint']]\ndf_pwd = pwd[['Subject','Complaint']]\ndf_ksrtc = ksrtc[['Subject','Complaint']]\ndf_kseb = kseb[['Subject','Complaint']]\ndf_env = env[['Subject','Complaint']]\n\ndfwater = df_water[['Subject','Complaint']]\ndfpwd = df_pwd[['Subject','Complaint']]\ndfksrtc = df_ksrtc[['Subject','Complaint']]\ndfkseb = df_kseb[['Subject','Complaint']]\ndfenv = df_env[['Subject','Complaint']]\n\n\n#Dataframe with complaint and subject as one column = Water\ndfwater['Subject_and_Complaint'] = df_water['Subject'] + \" \"+ df_water['Complaint']\ndfwater=dfwater[['Subject_and_Complaint']]\n\n\n\n\n\n#Dataframe with complaint and subject as one column = PWD\ndfpwd['Subject_and_Complaint'] = df_pwd['Subject'] + \" \"+ df_pwd['Complaint']\ndfpwd=dfpwd[['Subject_and_Complaint']]\n#print(dfpwd)\n\n#Dataframe with complaint and subject as one column = ksrtc\ndfksrtc['Subject_and_Complaint'] = df_ksrtc['Subject'] + \" \"+ df_ksrtc['Complaint']\ndfksrtc=dfksrtc[['Subject_and_Complaint']]\n#print(dfksrtc)\n\n#Dataframe with complaint and subject as one column = kseb\ndfkseb['Subject_and_Complaint'] = df_kseb['Subject'] + \" \"+ df_kseb['Complaint']\ndfkseb=dfkseb[['Subject_and_Complaint']]\n#print(dfkseb)\n\n\n#Dataframe with complaint and subject as one column = env\ndfenv ['Subject_and_Complaint'] = df_env['Subject'] + \" \"+ df_env['Complaint']\ndfenv =dfenv [['Subject_and_Complaint']]\nprint(dfenv )\n\n#==================================Tokenization Begins : =============================================\n\n\n \n\n\nwater_token = []\nwater_list=[]\n#Tokenising water data\nstop_words = set(stopwords.words('english'))\nfor i, row in dfwater.iterrows():\n #print(i,row['Subject'], row['Complaint'])\n #tokenizer=nltk.tokenize.TreebankWordTokenizer()\n water_token = word_tokenize(row['Subject_and_Complaint'])\n result = [i for i in water_token if not i in stop_words]\n water_list.append(result)\nprint(\"+++WATER TOKENS+++\")\nprint(water_list)\n #water_token.append(tokenizer.tokenize(row['Subject_and_Complaint']))\n\n \n \n\n#print(type(tokens))\n\n\n\npwd_token = []\n\npwd_list = []\n#Tokenising pwd data \nfor i, row in dfpwd.iterrows():\n #print(i,row['Subject'], row['Complaint'])\n pwd_token = word_tokenize(row['Subject_and_Complaint'])\n\n result1 = [i for i in pwd_token if not i in stop_words]\n pwd_list.append(result1)\nprint(\"\\n+++PWD Tokens+++\")\nprint(pwd_list)\n#print( pwd_token)\n\nksrtc_token =[]\nksrtc_list =[]\n#Tokenising ksrtc data \nfor i, row in dfksrtc.iterrows():\n #print(i,row['Subject'], row['Complaint'])\n ksrtc_token = word_tokenize(row['Subject_and_Complaint'])\n result = [i for i in ksrtc_token if not i in stop_words]\n ksrtc_list.append(result)\n#print(ksrtc_list)\n#print( ksrtc_token)\n\nkseb_token = []\nkseb_list= []\n#Tokenising kseb data \nfor i, row in dfkseb.iterrows():\n #print(i,row['Subject'], row['Complaint'])\n kseb_token = word_tokenize(row['Subject_and_Complaint'])\n result = [i for i in kseb_token if not i in stop_words]\n kseb_list.append(result)\n#print(kseb_list)\n#print(kseb_token)\n\n\n\n\n \n \n\nenv_token = []\nenv_list = []\n#Tokenising env data \nfor i, row in dfenv.iterrows():\n #print(i,row['Subject'], row['Complaint'])\n env_token = word_tokenize(row['Subject_and_Complaint'])\n result = [i for i in env_token if not i in stop_words]\n env_list.append(result)\n#print(env_list)\n#print(env_token)\n\n\n#word frequencies Environment department\n\nwordfreq = [1]\n\ncount = 0\nfor word in env_list: \n count+=1\n wordfreq.append([])\n for i in word:\n \n wordfreq[count].append(word.count(i))\n#print(env_list)\n\nwordfreq.pop(0)\n#print(wordfreq)\n#print(len(wordfreq))\n#print(len(env_list))\n\nenv_freq=list(map(dict, map(zip, env_list, wordfreq)))\nprint(\"\\n========= Word Frequency of Environment =========== \\n\\n\")\nprint(env_freq)\n\n#word frequencies KSEB department\n\nwordfreq = [1]\ncount = 0\nfor word in kseb_list:\n count+=1\n wordfreq.append([])\n for i in word:\n wordfreq[count].append(word.count(i))\nwordfreq.pop(0)\n\nkseb_freq=list(map(dict, map(zip, kseb_list, wordfreq)))\nprint(\"\\n========= Word Frequency of KSEB =========== \\n\\n\")\n#print(kseb_freq)\n\n\n#word frequencies KSRTC department\n\nwordfreq = [1]\ncount = 0\nfor word in ksrtc_list:\n count+=1\n wordfreq.append([])\n for i in word:\n wordfreq[count].append(word.count(i))\nwordfreq.pop(0)\n\nksrtc_freq=list(map(dict, map(zip, ksrtc_list, wordfreq)))\nprint(\"\\n========= Word Frequency of KSEB =========== \\n\\n\")\nprint(type(ksrtc_freq))\n\n\n#word frequencies pwd department\n\nwordfreq = [1]\ncount = 0\nfor word in pwd_list:\n count+=1\n wordfreq.append([])\n for i in word:\n wordfreq[count].append(word.count(i))\nwordfreq.pop(0)\n\npwd_freq=list(map(dict, map(zip, pwd_list, wordfreq)))\nprint(\"\\n========= Word Frequency of PWD =========== \\n\\n\")\n#print(pwd_freq)\n\n#word frequencies water department\n\nwordfreq = []\ncount = 0\nfor word in water_list:\n count+=1\n #wordfreq.append([])\n for i in word:\n wordfreq[count].append(word.count(i))\n#wordfreq.pop(0)\n\nwater_freq=list(map(dict, map(zip, water_list, wordfreq)))\nprint(\"\\n========= Word Frequency of WATER =========== \\n\\n\")\n\nprint(water_freq)\n\n# Finding the most repeated words\nwater_lis =[]\nwater_freq_list = { }\nfor lists in water_freq:\n water_freq_list.update({})\n lists=dict(lists)\n items = [(v, k) for k, v in lists.items()]\n items.sort()\n items.reverse()\n items = [k for v, k in items]\n #print(items)\n water_dict=(items[:4])\n water_lis.append(water_dict)\n#print(water_lis)\n\n \n#print(water_lis) \n\n# Finding the most repeated words pwd\npwd_lis =[]\npwd_freq_list = { }\nfor lists in pwd_freq:\n pwd_freq_list.update({})\n lists=dict(lists)\n items = [(v, k) for k, v in lists.items()]\n items.sort()\n items.reverse()\n items = [k for v, k in items]\n #print(items)\n pwd_dict=(items[:4])\n pwd_lis.append(pwd_dict)\nprint(pwd_lis)\n\n# Finding the most repeated words kseb\nkseb_lis =[]\nkseb_freq_list = { }\nfor lists in kseb_freq:\n kseb_freq_list.update({})\n lists=dict(lists)\n items = [(v, k) for k, v in lists.items()]\n items.sort()\n items.reverse()\n items = [k for v, k in items]\n #print(items)\n kseb_dict=(items[0:4])\n kseb_lis.append(kseb_dict)\n#print(kseb_lis)\n \n# Finding the most repeated words ksrtc\nksrtc_lis =[]\nksrtc_freq_list = { }\nfor lists in ksrtc_freq:\n kseb_freq_list.update({})\n lists=dict(lists)\n items = [(v, k) for k, v in lists.items()]\n items.sort()\n items.reverse()\n items = [k for v, k in items]\n #print(items)\n ksrtc_dict=(items[:4])\n ksrtc_lis.append(ksrtc_dict)\n#print(ksrtc_lis)\n \n# Finding the most repeated words env\nenv_lis =[]\nenv_freq_list = { }\nfor lists in env_freq:\n \n env_freq_list.update({})\n lists=dict(lists)\n #print(lists)\n items = [(v, k) for k, v in lists.items()]\n #print(type(items))\n items.sort()\n items.reverse()\n items = [k for v, k in items]\n print(items)\n env_dict=(items[0:4])\n #print(\"\\n\\nENVDICT\\n\\n\")\n #print(env_dict)\n env_lis.append(env_dict) \nprint(\"\\n\\n ENV list \\n\\n\")\nprint(env_lis)\n\n\n# Keyword extraction using Libaray\n#print(dfenv)\n#for i, row in dfenv.iterrows():\n \n #env_token = summarize(row['Subject_and_Complaint'])\n #print(env_token)\n #result = [i for i in env_token if not i in stop_words]\n #env_list.append(env_token)\n#print(env_list)\n \n\n ", " Subject_and_Complaint\n12 increasing deaths from air pollution \\nair pol...\n13 waste disposal to water bodies people make riv...\n19 illegal sand mines due to the sand mining ther...\n20 waste disposal on roads in our areas during ni...\n33 fishes dying massively fishes in the river pam...\n40 construction of paddy fields construction is g...\n42 water pollution is a major issue many industri...\n43 burning of plastics issue burning of plastics ...\n44 waste collecting mechanism dumping of wastes i...\n45 save water bodies activities like waste dispos...\n46 overfishing in rivers overfishing which causes...\n47 light pollution artificial light at night is o...\n48 we make a lot of ewaste the electronic waste p...\n49 ocean acidification ocean acidification is cau...\n50 city dwellers are prone to noise pollution noi...\n58 cutting down of trees now a days many people a...\n62 pollution by ksrtc bus pollution by ksrtc bus ...\n65 horrible effects of quarrying quarries are bad...\n70 mining save alappad stop mining\n72 regarding waste dumping in cities i would like...\n74 environment and climate change\\n is one of the...\n100 intolerable temperature rise in summer\\n seaso...\n103 environment intense heat during summer\n110 take immediate and necessary \\nsteps to regula...\n112 excessive use of chlorine due to excessive use...\n113 increase in heat and temperature we should hav...\n114 pollution everywhere need proper regulations t...\n116 rise in temperature increased deforestation un...\n118 the bad air and water quality in kochi the pol...\n120 waste disposal waste disposal in public premi...\n+++WATER TOKENS+++\n[['water', 'supply', 'connection', 'water', 'pipeline', 'connection', 'amma', 'gardens', 'residential', 'area', 'erattakalangu', 'malayinkeezhu'], ['scarcity', 'water', 'day', 'time', 'scarcity', 'water', 'area', 'vanchiyooron', 'day', 'time', 'creates', 'great', 'trouble', 'people', 'getting', 'ready', 'work', 'schools', 'office', 'etc'], ['water', 'scarcity', 'huge', 'scarcity', 'water', 'remote', 'areas', 'people', 'walk', 'large', 'distancesstanding', 'queue', 'fetch', 'water', 'problem', 'exiss', 'hilly', 'areas', 'idukki', 'district', 'kerala', 'humbly', 'request', 'take', 'necessary', 'actions', 'tackle', 'problem', 'near', 'future'], ['water', 'scarcity', 'frequent', 'scarcity', 'water', 'morning'], ['water', 'supply', 'available', 'houses', 'area', 'water', 'supply', 'available', 'therepeople', 'get', 'water', 'needs', 'therefore', 'request', 'concerning', 'authorities', 'look', 'matter', 'seriously', 'take', 'necessary', 'steps', 'solving', 'problem', 'water', 'supply', 'may', 'kindly', 'made', 'daily', 'locality', 'people', 'may', 'get', 'rid', 'problem', 'water', 'supply'], ['stealing', 'water', 'sealed', 'pipes', 'stayed', 'hotel', 'kovalam', 'beach', 'called', 'palm', 'grove', 'second', 'beach', 'road', 'kovalam', 'near', 'kovalam', 'bus', 'stand', 'came', 'know', 'hotel', 'water', 'connection', 'without', 'water', 'supplybecause', 'authority', 'sealed', 'pipe', 'big', 'dues', 'bill', 'stealing', 'water', 'sealed', 'pipe', 'last', 'year', 'huge', 'capacity', 'water', 'storage', 'building', 'approx', 'litres', 'capacity', 'stayed', 'hotel', 'nights', 'staff', 'told', 'things', 'regarding', 'please', 'take', 'immediate', 'action', 'fix', 'small', 'lengthy', 'pipe', 'two', 'side', 'thread', 'connector', 'connected', 'sealed', 'pipe', 'also', 'caped', 'glue', 'closed', 'thread', 'cap', 'usually', 'water', 'supply', 'hardly', 'days', 'per', 'week', 'day', 'steal', 'water', 'fill', 'liters', 'filled', 'use', 'week', 'please', 'take', 'necessary', 'action'], ['water', 'leakage', 'water', 'leakage', 'locality', 'still', 'unrepairedit', 'causes', 'water', 'shortage', 'areas'], ['smelling', 'water', 'water', 'flowing', 'pipe', 'foul', 'smell', 'therefore', 'unfits', 'drinking', 'cooking', 'purposes'], ['water', 'theft', 'amount', 'unauthorised', 'connection', 'water', 'mains', 'cause', 'huge', 'bills', 'authorised', 'consumer'], ['leaking', 'pipes', 'public', 'pipes', 'public', 'pipe', 'triivandrum', 'city', 'leaking', 'thus', 'leads', 'water', 'shortagep'], ['water', 'leakage', 'summer', 'season', 'drinking', 'water', 'pipe', 'near', 'puthoor', 'junction', 'broken', 'water', 'flowing', 'days', 'please', 'take', 'necessary', 'action'], ['water', 'related', 'complaint', 'shortage', 'drinking', 'water'], ['water', 'scarcity', 'scarcity', 'drinking', 'water', 'summer'], ['water', 'leakage', 'leakage', 'water', 'mg', 'road'], ['water', 'enough', 'please', 'setup', 'enough', 'water', 'resource', 'rural', 'areas'], ['water', 'coming', 'edathua', 'residing', 'edathua', 'panchayat', 'kuttanad', 'taluk', 'staying', 'rented', 'house', 'water', 'connection', 'meter', 'water', 'getting', 'waterour', 'house', 'consumer', 'number', 'eda', 'neighbouring', 'house', 'consumer', 'noeda', 'also', 'getting', 'water', 'well', 'also', 'waterwe', 'facing', 'great', 'difficulties', 'daytoday', 'needs', 'kindly', 'request', 'take', 'necessary', 'action'], ['non', 'availability', 'drinking', 'water', 'totally', 'residing', 'attuparambil', 'eravipuram', 'kollam', 'locality', 'facing', 'severe', 'problem', 'growing', 'instances', 'insufficient', 'water', 'supply', 'last', 'days', 'locality', 'already', 'given', 'many', 'complaints', 'kindly', 'requesting', 'look', 'matter', 'personally', 'needful', 'shall', 'much', 'thankful'], ['little', 'water', 'supply', 'neighborhood', 'last', 'one', 'month', 'kochi', 'facing', 'acute', 'shortage', 'water', 'supply', 'kwa', 'supply', 'systemthe', 'summer', 'getting', 'bad', 'worse', 'shortage', 'water', 'aggravating', 'condition'], ['shortage', 'water', 'supply', 'writing', 'inform', 'residents', 'punnakunnam', 'pulinkunnu', 'kuttanadu', 'alappuzha', 'facing', 'shortage', 'drinking', 'water', 'last', 'monthsin', 'fact', 'every', 'member', 'society', 'disturbed', 'account', 'unavailability', 'water', 'supply', 'basic', 'need', 'every', 'human'], ['water', 'pipe', 'leaking', 'new', 'water', 'pipe', 'connection', 'installed', 'front', 'house', 'leaking', 'water', 'leaking', 'great', 'force', 'getting', 'wasted'], ['water', 'leaking', 'please', 'note', 'informing', 'drinking', 'water', 'keep', 'flowing', 'road', 'always', 'wet', 'compound', 'fully', 'accumulated', 'meter', 'cabin'], ['irregular', 'supply', 'water', 'may', 'one', 'two', 'week', 'dont', 'get', 'water', 'even', 'provide', 'water', 'supply', 'time', 'late', 'like', 'midnight', 'low', 'pressure'], ['erroneous', 'water', 'meter', 'reading', 'please', 'issue', 'good', 'water', 'meter'], ['water', 'supply', 'house', 'consumer', 'wate', 'rworks', 'sub', 'division', 'thrissur', 'per', 'mentioned', 'consumer', 'number', 'getting', 'water', 'past', 'four', 'months', 'house', 'leakage', 'tiled', 'portion', 'road', 'thrissur', 'corporation', 'noticed', 'andthe', 'reported', 'assistant', 'engineer', 'action', 'taken', 'rectify', 'leakage', 'restore', 'water', 'supply', 'house'], ['muddy', 'water', 'supply', 'since', 'january', 'consuming', 'muddy', 'water', 'every', 'supply', 'water', 'authority', 'storage', 'tank', 'destroy', 'mud', 'resulted', 'taps', 'bathroom', 'systems', 'also'], ['water', 'public', 'tap', 'public', 'tap', 'remains', 'idle', 'past', 'couple', 'weeks', 'affected', 'lives', 'people', 'neighborhood', 'awkwardly'], ['wrongly', 'charged', 'water', 'bills', 'recieved', 'bill', 'rs', 'house', 'closed', 'state', 'months', 'information', 'consumption', 'details', 'previous', 'reading', 'information', 'bill'], ['water', 'supply', 'water', 'supply', 'vazhathope', 'panchayath', 'two', 'weeks', 'people', 'need', 'look', 'upon', 'water', 'sources', 'much', 'frustrating'], ['non', 'supply', 'drinking', 'water', 'regular', 'water', 'supply', 'september', 'onwards', 'till', 'date'], ['water', 'leaking', 'water', 'loosing', 'distribution', 'line', 'every', 'day', 'pumping', 'progressthis', 'water', 'trapped', 'walk', 'way', 'public', 'useand', 'time', 'mosqitos', 'growingseveral', 'time', 'iform', 'water', 'athority', 'kochi', 'office'], ['water', 'supply', 'interrupted', 'domestic', 'water', 'supply', 'houses', 'situated', 'near', 'kunnathuvathucal', 'bridge', 'last', 'days'], ['wrong', 'consumer', 'name', 'water', 'connection', 'record', 'name', 'wrongly', 'recorded', 'water', 'connection', 'records'], ['able', 'pay', 'water', 'bill', 'online', 'able', 'complete', 'payment', 'transaction', 'water', 'authority', 'website'], ['online', 'payment', 'service', 'available', 'pay', 'utility', 'bills', 'mostly', 'via', 'online', 'payment', 'services', 'water', 'bill', 'facing', 'problem', 'paying', 'bill', 'water', 'authority', 'website'], ['water', 'wastage', 'wastage', 'drinking', 'water', 'due', 'damaged', 'pipeline'], ['unable', 'login', 'water', 'authority', 'website', 'trying', 'make', 'bill', 'payment', 'entered', 'credentials', 'tried', 'login', 'account', 'everytime', 'try', 'login', 'get', 'error', 'message'], ['water', 'meter', 'complaint', 'request', 'check', 'meter', 'replace', 'repair', 'early', 'possible'], ['shortage', 'drinking', 'water', 'location', 'water', 'connection', 'since', 'summer', 'facing', 'severe', 'water', 'scarcity', 'please', 'set', 'connection', 'loction'], ['extra', 'cost', 'water', 'bill', 'payment', 'online', 'pay', 'bill', 'e', 'payment', 'web', 'site', 'charge', 'additional', 'rupees', 'transaction']]\n\n+++PWD Tokens+++\n[['road', 'retarring', 'resident', 'sreekaryam', 'ambadinagar', 'lane', 'road', 'full', 'potholeskindly', 'necessary', 'steps', 'maintenance', 'road'], ['poor', 'condition', 'road', 'rural', 'areas', 'kerala', 'condition', 'road', 'rural', 'areas', 'kerala', 'miserable', 'corruption', 'contract', 'maintenance', 'road', 'causing', 'problems', 'leads', 'frequent', 'damage', 'newly', 'constructed', 'tared', 'roads', 'potholes', 'road', 'leads', 'accidents', 'losing', 'balance', 'vehicles', 'paved', 'way', 'damage', 'road'], ['new', 'road', 'taring', 'living', 'area', 'road', 'harsh', 'people', 'living', 'area', 'travelling', 'unpaved', 'road', 'difficult', 'taskirequests', 'tar', 'road', 'early', 'possible'], ['roads', 'shattered', 'landslides', 'due', 'recent', 'landslide', 'activity', 'roads', 'got', 'shattered', 'traffic', 'stopped', 'many', 'days', 'please', 'make', 'tarring', 'process', 'faster'], ['construction', 'walls', 'pwd', 'space', 'mr', 'kumar', 'locality', 'constructing', 'awall', 'taking', 'footpath', 'pwd'], ['road', 'work', 'day', 'time', 'road', 'works', 'without', 'prior', 'notice', 'day', 'time', 'cause', 'heavy', 'traffic', 'congestion'], ['road', 'retarring', 'melattumoozhy', 'thannippara', 'road', 'bad', 'condition', 'accidents', 'increasing', 'day', 'day', 'please', 'take', 'necessary', 'actions', 'retarring', 'process'], ['road', 'well', 'maintained', 'road', 'sreekaryam', 'proper', 'width', 'well', 'maintained'], ['potholes', 'id', 'like', 'make', 'public', 'works', 'department', 'aware', 'number', 'potholes', 'impeding', 'traffic', 'also', 'causing', 'undue', 'wear', 'tear', 'vehicles', 'hitting', 'pothole', 'even', 'speed', 'limit', 'pop', 'tire', 'damage', 'car', 'even', 'pose', 'physical', 'threat', 'drivers', 'pedestrians', 'know', 'state', 'law', 'permits', 'drivers', 'seek', 'reimbursement', 'losses', 'due', 'road', 'hazards', 'defects', 'result', 'negligence', 'potential', 'liability', 'claims', 'high', 'several', 'potholes', 'located', 'maple', 'street', 'th', 'th', 'streets', 'one', 'least', 'two', 'feet', 'diameter', 'intersection', 'th', 'pine', 'know', 'crew', 'cant', 'get', 'every', 'pothole', 'right', 'away', 'growing', 'many', 'months', 'attached', 'photos', 'illustrate', 'problem'], ['road', 'transportation', 'problems', 'roads', 'safe', 'running', 'heavyweight', 'vehicle', 'poor', 'maintenance', 'problem', 'aggravates', 'especially', 'rainy', 'seasona', 'major', 'problem', 'india', 'roads', 'high', 'traffic', 'condition', 'road', 'used', 'various', 'types', 'vehicles', 'highspeed', 'trucks', 'cars', 'tractors', 'two', 'wheelers', 'driven', 'carts', 'cyclists', 'etc', 'things', 'create', 'high', 'traffic', 'jam', 'congestion', 'road', 'accident', 'etcthe', 'roads', 'india', 'lack', 'wayside', 'amenities', 'like', 'first', 'aid', 'centers', 'telephone', 'booths', 'repair', 'shops', 'restaurants', 'clean', 'toilets', 'create', 'serious', 'problems', 'drivers', 'moreover', 'little', 'attention', 'given', 'road', 'safety', 'issues', 'also', 'road', 'safety', 'rules', 'violation', 'lawsthe', 'road', 'transportation', 'system', 'country', 'requires', 'immediate', 'modernization', 'latest', 'technology', 'road', 'transport', 'sector', 'use', 'old', 'technology', 'vehicles', 'still', 'prevalent', 'ultimately', 'increase', 'number', 'road', 'accidents', 'due', 'bad', 'road', 'condition', 'transport', 'companies', 'bear', 'huge', 'amount', 'per', 'year', 'wear', 'tear', 'vehicles', 'important', 'point', 'proper', 'attention', 'givenroad', 'direction', 'railway', 'department', 'always', 'indifferent', 'attitude', 'biggest', 'barrier', 'transport', 'india', 'railway', 'crossings', 'despite', 'government', 'permissions', 'government', 'employees', 'make', 'reasonable', 'contributions', 'even', 'bribe', 'time', 'consuming', 'transport', 'traders', 'also', 'large', 'businessmen', 'businessmen', 'also', 'raised'], ['road', 'related', 'roads', 'many', 'pitfalls', 'sometimes', 'cause', 'accidents', 'unwary', 'drivers'], ['rising', 'peak', 'hour', 'traffic', 'congestion', 'rising', 'peak', 'hour', 'traffic', 'congestion', 'inescapable', 'condition', 'many', 'areas', 'trivandrum', 'city', 'sufficient', 'traffic', 'control', 'signal', 'systems', 'handle', 'situations'], ['poor', 'road', 'maintenance', 'roads', 'properly', 'maintained', 'repair', 'works', 'roads', 'last', 'days', 'proper', 'transportation', 'facility', 'basic', 'right', 'citizens'], ['good', 'roads', 'actually', 'dont', 'good', 'roads', 'worthy', 'tax', 'pay', 'hopefully', 'government', 'find', 'way', 'fix'], ['road', 'repair', 'complaint', 'pathholes', 'road', 'extremly', 'half', 'feet', 'size', 'accident', 'prone', 'today', 'effect', 'daily', 'travelling', 'student', 'employees', 'suffering', 'also', 'may', 'cause', 'health', 'problems'], ['concreting', 'bottom', 'compound', 'wall', 'outlet', 'roadside', 'water', 'drainage', 'drainage', 'work', 'muthambi', 'oorallur', 'road', 'thadolithazha', 'junction', 'koyilandy', 'taluk', 'calicut', 'district', 'length', 'mtr', 'progressing', 'outlet', 'crossing', 'road', 'directed', 'towards', 'compound', 'wall', 'letting', 'water', 'flow', 'nayadan', 'puzha', 'lake', 'completion', 'water', 'flow', 'directly', 'bottom', 'compound', 'wall', 'hitting', 'compound', 'wall', 'changes', 'direction', 'flow', 'damage', 'wall', 'nature', 'place', 'loose', 'mud', 'learnt', 'provision', 'continue', 'drainage', 'limit', 'road', 'requested', 'kindly', 'needful', 'avoid', 'damage', 'wall', 'length', 'mtr', 'early', 'action', 'requested', 'canal', 'water', 'open', 'last', 'january'], ['poor', 'roads', 'sir', 'please', 'initiate', 'surprise', 'visit', 'kerala', 'know', 'conditions', 'roads', 'monthsafter', 'rainy', 'season', 'since', 'roads', 'repaired', 'also', 'roads', 'broken', 'instead', 'chipping', 'existing', 'roads', 'resurfaced', 'increases', 'height', 'roads', 'height', 'roads', 'increased', 'height', 'houses', 'office', 'complexes', 'increased', 'know', 'take', 'help', 'media', 'channels', 'like', 'asianet', 'news', 'manorama', 'news', 'indiavision', 'etc', 'also', 'common', 'trend', 'ie', 'roads', 'repaired', 'broken', 'manually', 'underlying', 'cables', 'underground', 'left', 'without', 'repairing', 'sirmadam', 'per', 'day', 'lacs', 'vehicles', 'entering', 'roads', 'showrooms', 'much', 'tax', 'collected', 'isnt', 'sufficient', 'repair', 'roads', 'roads', 'leveled', 'properly', 'much', 'fuel', 'saved', 'prices', 'fuel', 'controlled', 'certain', 'extent', 'right', 'hope', 'would', 'take', 'factors', 'consideration'], ['footpath', 'vendors', 'dear', 'sir', 'due', 'intervention', 'politicians', 'every', 'footpath', 'flooded', 'vendors', 'selling', 'tender', 'cocanuts', 'shoe', 'repairs', 'petty', 'shops', 'filled', 'pan', 'masalas', 'liquiors', 'tea', 'snacks', 'notnot', 'traders', 'blocking', 'view', 'side', 'roads', 'motorist', 'predict', 'see', 'going', 'emerge', 'side', 'roads', 'petty', 'shops', 'well', 'concreated', 'base', 'running', 'businesses', 'like', 'real', 'estate', 'rentals', 'etcetc', 'idea', 'growing', 'nation', 'city', 'clean', 'roadswho', 'responsible', 'pwd', 'authority', 'issue', 'notice', 'people', 'evict', 'themgod', 'bad', 'country', 'pity', 'consideration', 'appeal', 'something', 'stop'], ['vehicle', 'parking', 'heavy', 'traffic', 'ss', 'kovil', 'road', 'thampanoor', 'large', 'amount', 'vehicle', 'parking'], ['bus', 'waiting', 'shed', 'construction', 'connection', 'othukkungal', 'town', 'malappuram', 'district', 'kerala', 'beautification', 'existing', 'bus', 'waiting', 'shed', 'towards', 'kottakkal', 'removed', 'last', 'year', 'till', 'date', 'new', 'shed', 'constructed', 'makes', 'difficult', 'common', 'passengers', 'kindly', 'take', 'necessary', 'action', 'construction', 'waiting', 'shed', 'helpful', 'layman'], ['road', 'tarring', 'road', 'sreekaryam', 'ambadi', 'nagar', 'chithravila', 'lot', 'gutter', 'please', 'necessary', 'action', 'retar', 'road'], ['road', 'damaged', 'japan', 'water', 'scheme', 'road', 'kotooli', 'mangotu', 'vayal', 'road', 'completely', 'digged', 'middle', 'pregnant', 'ladies', 'may', 'give', 'delivery', 'go', 'road', 'slippery', 'chance', 'high', 'please', 'something', 'kind', 'accidents', 'lot', 'kids', 'also', 'passing', 'road', 'chances', 'hitting', 'kids', 'driver', 'try', 'avoid', 'digged', 'part', 'middle', 'road', 'make', 'pedestrians', 'edge', 'may', 'result', 'hit', 'fall', 'resulting', 'injury', 'please', 'consider', 'solve', 'early', 'possible'], ['road', '95', 'damaged', 'road', 'going', 'towards', 'trivandrum', 'technopark', 'phase', 'gate', 'towards', 'technopark', 'buildings', 'road', 'starting', 'nippon', 'toyota', 'going', 'towards', 'kallingal', 'road', 'name', 'kallingal', 'attinkuzhy', 'road', 'road', 'damaged', 'last', 'years', 'one', 'caring', 'minimum', 'vehicles', 'daily', 'goes', 'morning', 'evening', 'towards', 'offices', 'like', 'meter', 'gutter', 'middle', 'road', 'making', 'health', 'issues', 'people', 'danger', 'situation', 'urgent', 'action', 'required'], ['driving', 'licence', 'current', 'driving', 'licence', 'poor', 'make', 'like', 'pvc', 'card', 'digital', 'card'], ['roads', 'villages', 'proper', 'condition', 'people', 'travel', 'roads', 'villages', 'proper', 'condition', 'people', 'travelplease', 'take', 'necessary', 'action', 'regarding'], ['full', 'pits', 'road', 'full', 'pits'], ['village', 'road', 'required', 'repairs', 'submitted', 'road', 'condition', 'karukaputhurpallipadam', 'thichur', 'palakkad', 'pathetic', 'condition', 'even', 'suitable', 'footwalk', 'due', 'boarder', 'villages', 'two', 'constituency', 'mla', 'bothers', 'area', 'please', 'needful', 'earliest'], ['stop', 'bridge', 'toll', 'fee', 'sir', 'public', 'wants', 'know', 'pwd', 'still', 'continuing', 'toll', 'charge', 'poovathumkadavu', 'bridge', 'poor', 'maintenance', 'road', 'street', 'light', 'misbehaviour', 'toll', 'collectors', 'passengers', 'every', 'day', 'public', 'suffering', 'area', 'whole', 'money', 'bridge', 'collected', 'public', 'gst', 'road', 'tax', 'insurance', 'money', 'going', 'nearby', 'mathilakam', 'bridge', 'toll', 'fee', 'stopped', 'year', 'back'], ['complaint', 'road', 'road', 'ramamangalam', 'choondy', 'dug', 'works', 'related', 'kwh', 'condition', 'travel', 'used', 'travel', 'around', 'km', 'daily', 'include', 'road', 'also'], ['damaged', 'roads', 'register', 'complaint', 'poor', 'road', 'conditions', 'big', 'pot', 'holes', 'arookutty', 'aroor', 'road', 'alappuzha', 'district'], ['damaged', 'roads', 'damaged', 'long', 'duration', 'potholes', 'converted', 'hidden', 'hazards', 'bikers', 'potential', 'risk', 'road', 'accidents'], ['poor', 'infrastructure', 'roads', 'city', 'damaged', 'quality', 'needed'], ['traffic', 'block', 'keshavadasapuram', 'traffic', 'block', 'lack', 'planning'], ['bad', 'roads', 'low', 'quality', 'roads'], ['public', 'transport', 'main', 'issue', 'government', 'departments', 'drivers', 'dont', 'know', 'correct', 'times', 'roots', 'many', 'bus', 'times'], ['suddenly', 'damaged', 'roads', 'tarring', 'roads', 'damaged', 'suddenly', 'reason', 'behind'], ['bumps', 'cracks', 'public', 'roads', 'road', 'maintained', 'properly'], ['lack', 'road', 'discipline', 'many', 'drivers', 'reckless', 'follow', 'road', 'rules', 'law', 'enforcement', 'lax', 'violations', 'makes', 'things', 'difficult', 'drivers', 'unpredictable', 'driving', 'others', 'roadand', 'pedestrians', 'walking', 'roadside', 'crossing', 'roads', 'makes', 'roads', 'dangerous', 'ordinary', 'citizens'], ['pothole', 'proper', 'maintenance', 'roads', 'leads', 'pot', 'holes', 'roads'], ['unauthorized', 'road', 'side', 'business', 'everybody', 'knows', 'highway', 'connecting', 'kochi', 'muvattupzha', 'one', 'busiest', 'crowed', 'road', 'ernakulam', 'city', 'withing', 'last', 'years', 'steady', 'increase', 'unauthorized', 'road', 'side', 'business', 'establishments', 'small', 'tent', 'establishments', 'unauthorized', 'illegal', 'creating', 'lot', 'accidents', 'past', 'months', 'cars', 'bikes', 'tent', 'stop', 'immediately', 'see', 'shacks', 'created', 'sudden', 'unexpected', 'accidents', 'build', 'road', 'reduce', 'road', 'visibility', 'example', 'shack', 'next', 'peruvammuzhy', 'selling', 'fish', 'created', 'countless', 'accidents', 'hope', 'department', 'takes', 'actions', 'business', 'establishments', 'immediately'], ['road', 'maintained', 'pathanapurm', 'pattazhy', 'road', 'maintained', 'road', 'width', 'plan', 'less'], ['road', 'requires', 'retarring', 'manathoor', 'maniykumpparakarimkunnam', 'road', 'worst', 'condition', 'construction', 'pala', 'thodupuzha', 'road', 'many', 'vehicles', 'used', 'road', 'shortcut', 'road', 'fully', 'destroyed', 'please', 'retarr', 'road', 'implement', 'proper', 'sign', 'boards', 'road', 'markings']]\n\n========= Word Frequency of Environment =========== \n\n\n[{'increasing': 1, 'deaths': 3, 'air': 3, 'pollution': 4, 'number': 1, 'cardiovascular': 1, 'disease': 1, 'attributed': 1, 'much': 1, 'higher': 1, 'expectedair': 1, 'caused': 1, 'twice': 1, 'many': 1, 'cvd': 1, 'respiratory': 1, 'diseases': 1}, {'waste': 1, 'disposal': 1, 'water': 2, 'bodies': 1, 'people': 1, 'make': 1, 'river': 1, 'polluted': 1, 'dumping': 1, 'household': 1, 'wastage': 2, 'industrial': 1}, {'illegal': 1, 'sand': 2, 'mines': 1, 'due': 1, 'mining': 1, 'effect': 1, 'ecosystem': 1, 'severe': 1, 'impact': 1, 'plants': 1, 'animals': 1, 'rivers': 1}, {'waste': 3, 'disposal': 1, 'roads': 1, 'areas': 1, 'night': 1, 'strangers': 1, 'dumping': 1, 'hotel': 1, 'domestic': 1, 'foul': 1, 'smelling': 1, 'sides': 1, 'road': 2, 'wastes': 2, 'remain': 1, 'th': 1, 'uncleaned': 1, 'shouldbe': 1, 'camerasurvelliance': 1, 'facility': 1, 'catchthe': 1, 'people': 1, 'throwing': 1}, {'fishes': 2, 'dying': 2, 'massively': 2, 'river': 1, 'pampa': 1, 'due': 1, 'deposits': 1, 'oil': 1, 'factories': 1, 'nearby': 1}, {'construction': 2, 'paddy': 2, 'fields': 2, 'going': 1, 'trivandrum': 1, 'please': 1, 'take': 1, 'necessary': 1, 'steps': 1, 'save': 1, 'farming': 1}, {'water': 2, 'pollution': 1, 'major': 2, 'issue': 1, 'many': 1, 'industries': 1, 'dump': 1, 'wastes': 2, 'rivers': 1, 'lakes': 1, 'ponds': 1, 'streams': 1, 'attempt': 1, 'hide': 1, 'epa': 1, 'inspectors': 1, 'sources': 1, 'feed': 1, 'crops': 1, 'food': 1, 'becomes': 1, 'contaminated': 1, 'variety': 1, 'chemicals': 1, 'bacteria': 1, 'causing': 1, 'rampant': 1, 'health': 1, 'problems': 1}, {'burning': 2, 'plastics': 2, 'issue': 1, 'public': 1, 'places': 1, 'cause': 1, 'major': 1, 'health': 1, 'concern': 1, 'rate': 1, 'lung': 1, 'cancer': 1, 'patients': 1, 'increasing': 1, 'day': 2, 'high': 1, 'time': 1, 'check': 1, 'activities': 1}, {'waste': 1, 'collecting': 1, 'mechanism': 2, 'dumping': 1, 'wastes': 2, 'public': 1, 'places': 1, 'causes': 1, 'major': 1, 'health': 1, 'issues': 1, 'inviting': 1, 'eradicated': 1, 'disease': 1, 'collect': 1, 'households': 1, 'disposed': 1, 'properly': 1}, {'save': 1, 'water': 2, 'bodies': 2, 'activities': 1, 'like': 1, 'waste': 1, 'disposal': 1, 'residential': 1, 'commercial': 1, 'industrial': 1, 'areas': 1, 'oil': 1, 'spills': 1, 'runoff': 1, 'agriculture': 1, 'contaminate': 1}, {'overfishing': 2, 'rivers': 1, 'causes': 1, 'reduction': 1, 'diversity': 1, 'marine': 1, 'life': 1, 'fishermen': 1, 'considering': 1, 'breeding': 1, 'time': 1}, {'light': 3, 'pollution': 1, 'artificial': 2, 'night': 1, 'one': 1, 'obvious': 1, 'physical': 1, 'changes': 1, 'humans': 1, 'made': 1, 'biosphere': 1, 'also': 1, 'affects': 1, 'dispersal': 1, 'orientation': 1, 'migration': 1, 'hormone': 1, 'levels': 1, 'resulting': 1, 'disrupted': 1, 'circadian': 1, 'rhythms': 1}, {'make': 1, 'lot': 1, 'ewaste': 1, 'electronic': 1, 'waste': 1, 'problem': 1, 'huge': 1, 'electronics': 1, 'end': 1, 'landfills': 1, 'toxics': 1, 'like': 1, 'lead': 1, 'mercury': 1, 'cadmium': 1, 'leach': 1, 'soil': 1, 'water': 1}, {'ocean': 3, 'acidification': 2, 'caused': 1, 'carbondioxide': 1, 'dissolves': 1, 'bonding': 1, 'sea': 1, 'water': 2, 'creating': 1, 'carbonic': 1, 'acid': 2, 'reduces': 1, 'ph': 1, 'levels': 1}, {'city': 1, 'dwellers': 1, 'prone': 1, 'noise': 2, 'pollution': 1, 'produced': 1, 'vehicles': 1, 'political': 1, 'parties': 1, 'religious': 1, 'centers': 1, 'causes': 1, 'great': 1, 'harm': 1, 'human': 1, 'ears': 1}, {'cutting': 2, 'trees': 3, 'days': 1, 'many': 2, 'people': 1, 'purposes': 1, 'example': 1, 'oragansations': 1, 'builders': 1, 'cut': 1, 'build': 1, 'projects': 1, 'cause': 1, 'real': 2, 'harm': 2, 'humans': 1, 'also': 2, 'utilizing': 1, 'fertile': 1, 'paddy': 1, 'fields': 1, 'construction': 1, 'affect': 1, 'environment': 1, 'oxygen': 2, 'content': 2, 'air': 2, 'become': 1, 'low': 1, 'level': 1, 'decreases': 1, 'survival': 1, 'living': 2, 'beings': 2, 'move': 1, 'harder': 1, 'way': 2, 'major': 1, 'factor': 1, 'ozone': 2, 'depletion': 1, 'holes': 2, 'formed': 1, 'harmful': 1, 'radiations': 1, 'enter': 1, 'earth': 1, 'causes': 1, 'continues': 1, 'threatening': 1, 'part': 1, 'lives': 1, 'please': 1, 'take': 1, 'serious': 1, 'issue': 1, 'make': 1, 'necessary': 1, 'useful': 1, 'remedies': 1}, {'pollution': 2, 'ksrtc': 2, 'bus': 2, 'heavy': 1, 'today': 1, 'government': 1, 'fix': 1, 'soon': 1, 'possible': 1}, {'horrible': 1, 'effects': 1, 'quarrying': 3, 'quarries': 1, 'bad': 1, 'environment': 1, 'several': 1, 'ways': 1, 'abruptly': 1, 'interrupt': 1, 'continuity': 1, 'open': 1, 'space': 1, 'cause': 1, 'soil': 1, 'erosionair': 1, 'dust': 1, 'pollution': 1, 'deterioration': 1, 'water': 1, 'qualitywhen': 1, 'residential': 1, 'areathey': 1, 'create': 2, 'noise': 1, 'hazards': 1, 'request': 1, 'higher': 1, 'authority': 1, 'investigate': 1, 'punish': 1, 'officials': 1, 'hand': 1, 'illegal': 1, 'mining': 1, 'time': 1, 'government': 1, 'awareness': 1, 'potentially': 1, 'negative': 1, 'impact': 1}, {'mining': 2, 'save': 1, 'alappad': 1, 'stop': 1}, {'regarding': 1, 'waste': 1, 'dumping': 1, 'cities': 1, 'would': 1, 'like': 1, 'inform': 1, 'city': 1, 'residents': 1, 'facing': 1, 'difficulties': 1, 'dump': 1, 'domestic': 1, 'wastes': 1, 'sohumbly': 1, 'request': 1, 'take': 1, 'necessary': 1, 'actions': 1}, {'environment': 1, 'climate': 1, 'change': 1, 'one': 1, 'big': 1, 'challenge': 1, 'facing': 1, 'right': 1, 'preserving': 1, 'biodiversity': 1, 'saving': 1, 'forest': 1, 'help': 1, 'overcome': 1, 'issuesalso': 1, 'recycling': 1, 'avoiding': 1, 'usage': 1, 'plastic': 1, 'efficient': 1, 'use': 1, 'fuel': 1}, {'intolerable': 2, 'temperature': 2, 'rise': 1, 'summer': 2, 'season': 2, 'change': 1, 'cause': 1, 'dried': 1, 'rivers': 1, 'skin': 1, 'disease': 1}, {'environment': 1, 'intense': 1, 'heat': 1, 'summer': 1}, {'take': 1, 'immediate': 1, 'necessary': 1, 'steps': 1, 'regulate': 1, 'global': 1, 'climate': 2, 'change': 1, 'one': 1, 'among': 1, 'factors': 1, 'shaped': 1, 'kerala': 2, 'gods': 1, 'country': 1, 'euphoric': 1, 'never': 1, 'touched': 1, 'extremes': 1, 'thanks': 1, 'moderating': 1, 'influence': 1, 'sea': 1, 'mighty': 1, 'western': 1, 'ghats': 1, 'scenario': 1, 'changed': 1, 'lot': 1, 'witnessing': 1, 'unprecedental': 1, 'surge': 1, 'temperature': 1, 'kumbhachoodu': 1, 'termed': 1, 'old': 1, 'generation': 1, 'alltime': 1, 'highimpacting': 1, 'livelihood': 1, 'many': 1}, {'excessive': 2, 'use': 2, 'chlorine': 2, 'due': 1, 'disinfectants': 2, 'water': 2, 'causing': 1, 'long': 1, 'term': 1, 'health': 1, 'problems': 1, 'like': 1, 'hair': 1, 'fall': 1, 'rashes': 1, 'etc': 1, 'amount': 1, 'used': 1, 'supplied': 1, 'need': 1, 'reconsidered': 1}, {'increase': 1, 'heat': 1, 'temperature': 1, 'projects': 1, 'planting': 1, 'trees': 2, 'dont': 1, 'cut': 1, 'big': 1, 'grownup': 1}, {'pollution': 2, 'everywhere': 1, 'need': 1, 'proper': 1, 'regulations': 1, 'control': 1}, {'rise': 1, 'temperature': 2, 'increased': 1, 'deforestation': 1, 'uncontrolled': 1, 'constructiondevelopment': 1, 'activities': 1, 'vehicle': 1, 'emissions': 1, 'heavily': 1, 'contribute': 1, 'increase': 1, 'government': 1, 'build': 1, 'new': 1, 'policies': 1, 'also': 1, 'consider': 1, 'switching': 1, 'renewable': 1, 'energy': 1, 'sources': 1}, {'bad': 1, 'air': 1, 'water': 1, 'quality': 1, 'kochi': 2, 'pollution': 1, 'levels': 1, 'city': 1, 'rising': 1, 'rapidly': 1, 'government': 1, 'initiate': 1, 'steps': 1, 'curb': 1}, {'waste': 2, 'disposal': 2, 'public': 1, 'premises': 1, 'make': 1, 'life': 1, 'hard': 1, 'people': 1, 'living': 1, 'around': 1}]\n\n========= Word Frequency of KSEB =========== \n\n\n\n========= Word Frequency of KSEB =========== \n\n\n<class 'list'>\n\n========= Word Frequency of PWD =========== \n\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
ec50a4a806257694921f3a41ccbc7320feb52f66
43,247
ipynb
Jupyter Notebook
steerable-nafx.ipynb
csteinmetz1/steerable-nafx
e2345e69427fa0ce62adc4609430d87efa285144
[ "Apache-2.0" ]
159
2021-12-06T12:12:27.000Z
2022-03-08T03:09:56.000Z
steerable-nafx.ipynb
soon0698/steerable-nafx
9758e3b347aa92602017a1a9e804fcbdf73ab91f
[ "Apache-2.0" ]
4
2021-12-11T22:18:19.000Z
2022-03-26T13:33:48.000Z
steerable-nafx.ipynb
soon0698/steerable-nafx
9758e3b347aa92602017a1a9e804fcbdf73ab91f
[ "Apache-2.0" ]
8
2021-12-07T05:49:44.000Z
2022-03-16T11:22:01.000Z
44.447071
7,053
0.578977
[ [ [ "<div align=\"center\">\n\n# Steerable discovery of neural audio effects\n\n [Christian J. Steinmetz](https://www.christiansteinmetz.com/) and [Joshua D. Reiss](http://www.eecs.qmul.ac.uk/~josh/)\n\n\n[Code](https://github.com/csteinmetz1/steerable-nafx) • [Paper](https://arxiv.org/abs/2112.02926) • [Demo](https://csteinmetz1.github.io/steerable-nafx)\t• [Slides]()\n\n<img src=\"https://csteinmetz1.github.io/steerable-nafx/assets/steerable-headline.svg\">\n\n</div>\n\n## Abtract\nApplications of deep learning for audio effects often focus on modeling analog effects or learning to control effects to emulate a trained audio engineer. \nHowever, deep learning approaches also have the potential to expand creativity through neural audio effects that enable new sound transformations. \nWhile recent work demonstrated that neural networks with random weights produce compelling audio effects, control of these effects is limited and unintuitive.\nTo address this, we introduce a method for the steerable discovery of neural audio effects.\nThis method enables the design of effects using example recordings provided by the user. \nWe demonstrate how this method produces an effect similar to the target effect, along with interesting inaccuracies, while also providing perceptually relevant controls.\n\n\n\\* *Accepted to NeurIPS 2021 Workshop on Machine Learning for Creativity and Design*\n\n", "_____no_output_____" ], [ "# Setup\nRun this first to install and import the relevant things...", "_____no_output_____" ] ], [ [ "!pip install torchaudio auraloss pyloudnorm", "_____no_output_____" ] ], [ [ "Download some sounds.", "_____no_output_____" ] ], [ [ "!wget https://csteinmetz1.github.io/sounds/assets/drum_kit_clean.wav \n!wget https://csteinmetz1.github.io/sounds/assets/drum_kit_comp_agg.wav \n!wget https://csteinmetz1.github.io/sounds/assets/acgtr_clean.wav \n!wget https://csteinmetz1.github.io/sounds/assets/acgtr_reverb.wav \n!wget https://csteinmetz1.github.io/sounds/assets/piano_clean.wav ", "_____no_output_____" ] ], [ [ "Download the pre-trained models.", "_____no_output_____" ] ], [ [ "!wget https://csteinmetz1.github.io/steerable-nafx/models/compressor_full.pt > /dev/null\n!wget https://csteinmetz1.github.io/steerable-nafx/models/reverb_full.pt > /dev/null\n!wget https://csteinmetz1.github.io/steerable-nafx/models/amp_full.pt > /dev/null\n!wget https://csteinmetz1.github.io/steerable-nafx/models/delay_full.pt > /dev/null\n!wget https://csteinmetz1.github.io/steerable-nafx/models/synth2synth_full.pt > /dev/null", "_____no_output_____" ], [ "import sys\nimport math\nimport torch\nimport librosa.display\nimport IPython\nimport auraloss\nimport torchaudio\nimport numpy as np\nimport scipy.signal\nfrom google.colab import files\nfrom tqdm.notebook import tqdm\nfrom time import sleep\nimport matplotlib\nimport pyloudnorm as pyln\nimport matplotlib.pyplot as plt\nfrom IPython.display import Image\n%matplotlib inline", "_____no_output_____" ], [ "# Sources from:\n# https://github.com/LCAV/pyroomacoustics/blob/master/pyroomacoustics/experimental/rt60.py\ndef measure_rt60(h, fs=1, decay_db=30, rt60_tgt=None):\n \"\"\"\n Analyze the RT60 of an impulse response.\n Args:\n h (ndarray): The discrete time impulse response as 1d array.\n fs (float, optional): Sample rate of the impulse response. (Default: 48000)\n decay_db (float, optional): The decay in decibels for which we actually estimate the time. (Default: 60)\n rt60_tgt (float, optional): This parameter can be used to indicate a target RT60. (Default: None)\n Returns:\n est_rt60 (float): Estimated RT60.\n \"\"\"\n\n h = np.array(h)\n fs = float(fs)\n\n # The power of the impulse response in dB\n power = h ** 2\n energy = np.cumsum(power[::-1])[::-1] # Integration according to Schroeder\n\n try:\n # remove the possibly all zero tail\n i_nz = np.max(np.where(energy > 0)[0])\n energy = energy[:i_nz]\n energy_db = 10 * np.log10(energy)\n energy_db -= energy_db[0]\n\n # -5 dB headroom\n i_5db = np.min(np.where(-5 - energy_db > 0)[0])\n e_5db = energy_db[i_5db]\n t_5db = i_5db / fs\n\n # after decay\n i_decay = np.min(np.where(-5 - decay_db - energy_db > 0)[0])\n t_decay = i_decay / fs\n\n # compute the decay time\n decay_time = t_decay - t_5db\n est_rt60 = (60 / decay_db) * decay_time\n except:\n est_rt60 = np.array(0.0)\n\n return est_rt60", "_____no_output_____" ], [ "def causal_crop(x, length: int):\n if x.shape[-1] != length:\n stop = x.shape[-1] - 1\n start = stop - length\n x = x[..., start:stop]\n return x\n\nclass FiLM(torch.nn.Module):\n def __init__(\n self,\n cond_dim, # dim of conditioning input\n num_features, # dim of the conv channel\n batch_norm=True,\n ):\n super().__init__()\n self.num_features = num_features\n self.batch_norm = batch_norm\n if batch_norm:\n self.bn = torch.nn.BatchNorm1d(num_features, affine=False)\n self.adaptor = torch.nn.Linear(cond_dim, num_features * 2)\n\n def forward(self, x, cond):\n\n cond = self.adaptor(cond)\n g, b = torch.chunk(cond, 2, dim=-1)\n g = g.permute(0, 2, 1)\n b = b.permute(0, 2, 1)\n\n if self.batch_norm:\n x = self.bn(x) # apply BatchNorm without affine\n x = (x * g) + b # then apply conditional affine\n\n return x\n\nclass TCNBlock(torch.nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, dilation, cond_dim=0, activation=True):\n super().__init__()\n self.conv = torch.nn.Conv1d(\n in_channels, \n out_channels, \n kernel_size, \n dilation=dilation, \n padding=0, #((kernel_size-1)//2)*dilation,\n bias=True)\n if cond_dim > 0:\n self.film = FiLM(cond_dim, out_channels, batch_norm=False)\n if activation:\n #self.act = torch.nn.Tanh()\n self.act = torch.nn.PReLU()\n self.res = torch.nn.Conv1d(in_channels, out_channels, 1, bias=False)\n\n def forward(self, x, c=None):\n x_in = x\n x = self.conv(x)\n if hasattr(self, \"film\"):\n x = self.film(x, c)\n if hasattr(self, \"act\"):\n x = self.act(x)\n x_res = causal_crop(self.res(x_in), x.shape[-1])\n x = x + x_res\n\n return x\n\nclass TCN(torch.nn.Module):\n def __init__(self, n_inputs=1, n_outputs=1, n_blocks=10, kernel_size=13, n_channels=64, dilation_growth=4, cond_dim=0):\n super().__init__()\n self.kernel_size = kernel_size\n self.n_channels = n_channels\n self.dilation_growth = dilation_growth\n self.n_blocks = n_blocks\n self.stack_size = n_blocks\n\n self.blocks = torch.nn.ModuleList()\n for n in range(n_blocks):\n if n == 0:\n in_ch = n_inputs\n out_ch = n_channels\n act = True\n elif (n+1) == n_blocks:\n in_ch = n_channels\n out_ch = n_outputs\n act = True\n else:\n in_ch = n_channels\n out_ch = n_channels\n act = True\n \n dilation = dilation_growth ** n\n self.blocks.append(TCNBlock(in_ch, out_ch, kernel_size, dilation, cond_dim=cond_dim, activation=act))\n\n def forward(self, x, c=None):\n for block in self.blocks:\n x = block(x, c)\n\n return x\n \n def compute_receptive_field(self):\n \"\"\"Compute the receptive field in samples.\"\"\"\n rf = self.kernel_size\n for n in range(1, self.n_blocks):\n dilation = self.dilation_growth ** (n % self.stack_size)\n rf = rf + ((self.kernel_size - 1) * dilation)\n return rf", "_____no_output_____" ], [ "# setup the pre-trained models\nmodel_comp = torch.load(\"compressor_full.pt\", map_location=\"cpu\").eval()\nmodel_verb = torch.load(\"reverb_full.pt\", map_location=\"cpu\").eval()\nmodel_amp = torch.load(\"amp_full.pt\", map_location=\"cpu\").eval()\nmodel_delay = torch.load(\"delay_full.pt\", map_location=\"cpu\").eval()\nmodel_synth = torch.load(\"synth2synth_full.pt\", map_location=\"cpu\").eval()", "_____no_output_____" ] ], [ [ "# 1. Pre-trained models\nJump right in by processing your own audio with some pre-trained models. \n\n1. Upload your input audio.\n2. Select your desired pre-trained model.\n3. Set the audio effect parameters.", "_____no_output_____" ] ], [ [ "#@title Upload input audio\nprocess_upload = files.upload()\nprocess_file = list(process_upload.keys())[-1]\nx_p, sample_rate = torchaudio.load(process_file)\nprint(process_file, x_p.shape)\nIPython.display.display(IPython.display.Audio(data=x_p, rate=sample_rate))", "_____no_output_____" ] ], [ [ "Now set the audio effect parameters. \nHere are some more insights into the controls:\n\n- `effect_type` - Choose from one of the pre-trained models.\n- `gain_dB` - Adjust the input gain. This can have a big effect since the effects are very nonlinear.\n- `c0` and `c1` - These are the effect controls which will adjust perceptual aspects of the effect, depending on the effect type. Very large values will often result in more extreme effects.\n- `mix` - Control the wet/dry mix of the effect.\n- `width` - Increase stereo width of the effect.\n- `max_length` - If you uploaded a very long file this will truncate it.\n- `stereo` - Convert mono input to stereo output.\n- `tail` - If checked, we will also compute the effect tail (nice for reverbs). \n", "_____no_output_____" ] ], [ [ "effect_type = \"Compressor\" #@param [\"Compressor\", \"Reverb\", \"Amp\", \"Analog Delay\", \"Synth2Synth\"]\ngain_dB = -24 #@param {type:\"slider\", min:-24, max:24, step:0.1}\nc0 = -1.4 #@param {type:\"slider\", min:-10, max:10, step:0.1}\nc1 = 3 #@param {type:\"slider\", min:-10, max:10, step:0.1}\nmix = 70 #@param {type:\"slider\", min:0, max:100, step:1}\nwidth = 50 #@param {type:\"slider\", min:0, max:100, step:1}\nmax_length = 30 #@param {type:\"slider\", min:5, max:120, step:1}\nstereo = True #@param {type:\"boolean\"}\ntail = True #@param {type:\"boolean\"}\n\n# select model type\nif effect_type == \"Compressor\":\n pt_model = model_comp\nelif effect_type == \"Reverb\":\n pt_model = model_verb\nelif effect_type == \"Amp\":\n pt_model = model_amp\nelif effect_type == \"Analog Delay\":\n pt_model = model_delay\nelif effect_type == \"Synth2Synth\":\n pt_model = model_synth\n\n# measure the receptive field\npt_model_rf = pt_model.compute_receptive_field()\n\n# crop input signal if needed\nmax_samples = int(sample_rate * max_length)\nx_p_crop = x_p[:,:max_samples]\nchs = x_p_crop.shape[0]\n\n# if mono and stereo requested\nif chs == 1 and stereo:\n x_p_crop = x_p_crop.repeat(2,1)\n chs = 2\n\n# pad the input signal\nfront_pad = pt_model_rf-1\nback_pad = 0 if not tail else front_pad\nx_p_pad = torch.nn.functional.pad(x_p_crop, (front_pad, back_pad))\n\n# design highpass filter\nsos = scipy.signal.butter(\n 8, \n 20.0, \n fs=sample_rate, \n output=\"sos\", \n btype=\"highpass\"\n)\n\n# compute linear gain \ngain_ln = 10 ** (gain_dB / 20.0)\n\n# process audio with pre-trained model\nwith torch.no_grad():\n y_hat = torch.zeros(x_p_crop.shape[0], x_p_crop.shape[1] + back_pad)\n for n in range(chs):\n if n == 0:\n factor = (width*5e-3)\n elif n == 1:\n factor = -(width*5e-3)\n c = torch.tensor([float(c0+factor), float(c1+factor)]).view(1,1,-1)\n y_hat_ch = pt_model(gain_ln * x_p_pad[n,:].view(1,1,-1), c)\n y_hat_ch = scipy.signal.sosfilt(sos, y_hat_ch.view(-1).numpy())\n y_hat_ch = torch.tensor(y_hat_ch)\n y_hat[n,:] = y_hat_ch\n\n# pad the dry signal \nx_dry = torch.nn.functional.pad(x_p_crop, (0,back_pad))\n\n# normalize each first\ny_hat /= y_hat.abs().max()\nx_dry /= x_dry.abs().max()\n\n# mix\nmix = mix/100.0\ny_hat = (mix * y_hat) + ((1-mix) * x_dry)\n\n# remove transient\ny_hat = y_hat[...,8192:]\ny_hat /= y_hat.abs().max()\n\ntorchaudio.save(\"output.mp3\", y_hat.view(chs,-1), sample_rate, compression=320.0)\nprint(\"Done.\")\nprint(\"Sending audio to browser...\")\n\n# show the audio\nIPython.display.display(IPython.display.Audio(\"output.mp3\"))", "_____no_output_____" ] ], [ [ "Click the three dots to download your processed audio file.", "_____no_output_____" ], [ "# 2. Steering (training)\nUse a pair of audio examples in order to construct neural audio effects.\n\nThere are two options. Either start with the pre-loaded audio examples, or upload your own clean/processed audio recordings for the steering process.", "_____no_output_____" ], [ "a.) Use some of our pre-loaded audio examples. Choose from the compressor or reverb effect.", "_____no_output_____" ] ], [ [ "#@title Use pre-loaded audio examples for steering\neffect_type = \"Compressor\" #@param [\"Compressor\", \"Reverb\"]\n\nif effect_type == \"Compressor\":\n input_file = \"drum_kit_clean.wav\"\n output_file = \"drum_kit_comp_agg.wav\"\nelif effect_type == \"Reverb\":\n input_file = \"acgtr_clean.wav\"\n output_file = \"acgtr_reverb.wav\"\n\nx, sample_rate = torchaudio.load(input_file)\nx = x[0:1,:]\n\ny, sample_rate = torchaudio.load(output_file)\ny = y[0:1,:]\n\nprint(\"input file\", x.shape)\nIPython.display.display(IPython.display.Audio(data=x, rate=sample_rate))\nprint(\"output file\", y.shape)\nIPython.display.display(IPython.display.Audio(data=y, rate=sample_rate))", "_____no_output_____" ] ], [ [ " b.) or, load you own input/output sounds. \n \n The files must have the same length.\n ", "_____no_output_____" ] ], [ [ "#@title Upload clean sound (x)\n# upload the clean input file\ninput_upload = files.upload()\ninput_file = list(input_upload.keys())[-1]\nx, sample_rate = torchaudio.load(input_file)\nprint(input_file, x.shape)\nIPython.display.display(IPython.display.Audio(data=x, rate=sample_rate))", "_____no_output_____" ], [ "# upload the same file processed with an effect\n#@title Upload processed sound (y)\noutput_upload = files.upload()\noutput_file = list(output_upload.keys())[-1]\ny, sample_rate = torchaudio.load(output_file)\n\nif not y.shape[-1] == x.shape[-1]:\n print(f\"Input and output files are different lengths! Found clean: {x.shape[-1]} processed: {y.shape[-1]}.\")\n if y.shape[-1] > x.shape[-1]:\n print(f\"Cropping target...\")\n y = y[:,:x.shape[-1]]\n else:\n print(f\"Cropping input...\")\n x = x[:,:y.shape[-1]]\n\nprint(output_file, y.shape)\nIPython.display.display(IPython.display.Audio(data=y, rate=sample_rate))", "_____no_output_____" ] ], [ [ "Now its time to generate the neural audio effect by training the TCN to emulate the input/output function from the target audio effect. Adjusting the parameters will enable you to tweak the optimization process. ", "_____no_output_____" ] ], [ [ "#@title TCN model training parameters\ncond_dim = 2 #@param {type:\"slider\", min:1, max:10, step:1}\nkernel_size = 13 #@param {type:\"slider\", min:3, max:32, step:1}\nn_blocks = 5 #@param {type:\"slider\", min:2, max:30, step:1}\ndilation_growth = 8 #@param {type:\"slider\", min:1, max:10, step:1}\nn_channels = 8 #@param {type:\"slider\", min:1, max:128, step:1}\nn_iters = 2499 #@param {type:\"slider\", min:0, max:10000, step:1}\nlength = 228308 #@param {type:\"slider\", min:0, max:524288, step:1}\nlr = 0.001 #@param {type:\"number\"}\n\nif torch.cuda.is_available():\n device = \"cuda\"\nelse:\n device = \"cpu\"\n\n# reshape the audio\nx_batch = x.view(1,x.shape[0],-1)\ny_batch = y.view(1,y.shape[0],-1)\nc = torch.tensor([0.0, 0.0], device=device).view(1,1,-1)\n\n# crop length\nx_batch = x_batch[:,0:1,:]\ny_batch = y_batch[:,0:1,:]\n\n_, x_ch, x_samp = x_batch.size()\n_, y_ch, y_samp = y_batch.size()\n\n# build the model\nmodel = TCN(\n n_inputs=x_ch,\n n_outputs=y_ch,\n cond_dim=cond_dim, \n kernel_size=kernel_size, \n n_blocks=n_blocks, \n dilation_growth=dilation_growth, \n n_channels=n_channels)\nrf = model.compute_receptive_field()\nparams = sum(p.numel() for p in model.parameters() if p.requires_grad)\n\nprint(f\"Parameters: {params*1e-3:0.3f} k\")\nprint(f\"Receptive field: {rf} samples or {(rf/sample_rate)*1e3:0.1f} ms\")\n\n# setup loss function, optimizer, and scheduler\nloss_fn = auraloss.freq.MultiResolutionSTFTLoss(\n fft_sizes=[32, 128, 512, 2048],\n win_lengths=[32, 128, 512, 2048],\n hop_sizes=[16, 64, 256, 1024])\nloss_fn_l1 = torch.nn.L1Loss()\n\noptimizer = torch.optim.Adam(model.parameters(), lr)\nms1 = int(n_iters * 0.8)\nms2 = int(n_iters * 0.95)\nmilestones = [ms1, ms2]\nprint(\n \"Learning rate schedule:\",\n f\"1:{lr:0.2e} ->\",\n f\"{ms1}:{lr*0.1:0.2e} ->\",\n f\"{ms2}:{lr*0.01:0.2e}\",\n)\nscheduler = torch.optim.lr_scheduler.MultiStepLR(\n optimizer,\n milestones,\n gamma=0.1,\n verbose=False,\n)\n\n# move tensors to GPU\nif torch.cuda.is_available():\n model.to(device)\n x_batch = x_batch.to(device)\n y_batch = y_batch.to(device)\n c = c.to(device)\n\n# pad input so that output is same size as input\n#x_pad = torch.nn.functional.pad(x_batch, (rf-1, 0))\n\n# iteratively update the weights\npbar = tqdm(range(n_iters))\nfor n in pbar:\n optimizer.zero_grad()\n\n start_idx = rf #np.random.randint(rf, x_batch.shape[-1]-length-1)\n stop_idx = start_idx + length\n x_crop = x_batch[...,start_idx-rf+1:stop_idx]\n y_crop = y_batch[...,start_idx:stop_idx]\n\n y_hat = model(x_crop, c)\n loss = loss_fn(y_hat, y_crop) #+ loss_fn_l1(y_hat, y_crop)\n\n loss.backward()\n optimizer.step()\n \n scheduler.step()\n if (n+1) % 1 == 0:\n pbar.set_description(f\" Loss: {loss.item():0.3e} | \")\n\ny_hat /= y_hat.abs().max()\n\nmodel.eval()\nx_pad = torch.nn.functional.pad(x_batch, (rf-1, 0))\nwith torch.no_grad():\n y_hat = model(x_pad, c)\n\ninput = causal_crop(x_batch.view(-1).detach().cpu().numpy(), y_hat.shape[-1])\noutput = y_hat.view(-1).detach().cpu().numpy()\ntarget = causal_crop(y_batch.view(-1).detach().cpu().numpy(), y_hat.shape[-1])\n\n# apply highpass to output\nsos = scipy.signal.butter(8, 20.0, fs=sample_rate, output=\"sos\", btype=\"highpass\")\noutput = scipy.signal.sosfilt(sos, output)\n\ninput /= np.max(np.abs(input))\noutput /= np.max(np.abs(output))\ntarget /= np.max(np.abs(target))\n\nfig, ax = plt.subplots(nrows=1, sharex=True)\nlibrosa.display.waveshow(target, sr=sample_rate, alpha=0.5, ax=ax, label='Target')\nlibrosa.display.waveshow(output, sr=sample_rate, color='r', alpha=0.5, ax=ax, label='Output')\n\nprint(\"Input (clean)\")\nIPython.display.display(IPython.display.Audio(data=input, rate=sample_rate))\nprint(\"Target\")\nIPython.display.display(IPython.display.Audio(data=target, rate=sample_rate))\nprint(\"Output\")\nIPython.display.display(IPython.display.Audio(data=output, rate=sample_rate))\nplt.legend()\nplt.show(fig)", "_____no_output_____" ] ], [ [ "## 2D Plot\nNow we can generate a 2D plot of the parameter space...", "_____no_output_____" ] ], [ [ "#@title Generate plot\nsize = 22 * 2\nmax_cond = 5\nmin_cond = -5\nvalues = np.zeros((size,size))\nspace = np.linspace(min_cond, max_cond, num=size, dtype=np.float32)\n\nmodel.eval()\n\nif effect_type == \"Reverb\": \n impulse = torch.zeros(1, 1, 65536*3)\n impulse[..., 16384*2] = 1.2\n impulse = impulse.to(device)\n for xidx, x_c in enumerate(tqdm(space)):\n for yidx, y_c in enumerate(space):\n c = torch.tensor([x_c,y_c], device=device).view(1,1,-1).float()\n with torch.no_grad():\n y_hat = model(impulse, c).cpu().view(-1)\n sos = scipy.signal.butter(8, 20.0, fs=sample_rate, output=\"sos\", btype=\"highpass\")\n y_hat = scipy.signal.sosfilt(sos, y_hat.numpy())\n rt60 = measure_rt60(y_hat)\n rt60_sec = rt60 / sample_rate\n values[xidx,yidx] = rt60_sec\n\n fig, ax = plt.subplots(1,1, figsize=(5,5))\n img = plt.imshow(values, interpolation='nearest', origin=\"lower\")\n ticks = np.linspace(min_cond, max_cond, num=10)\n ticks_str = [f\"{t:0.1f}\" for t in ticks]\n ax.set_xticks([])\n ax.set_xticklabels([])\n ax.set_yticks([])\n ax.set_yticklabels([])\n cbar = fig.colorbar(img,fraction=0.046, pad=0.04)\n cbar.set_label(r\"$T_{60}$ (sec)\")\n ax.set_xlabel(r\"$c_0$\")\n ax.set_ylabel(r\"$c_1$\")\n \nelif effect_type == \"Compressor\":\n test_signal, _ = torchaudio.load(\"piano_clean.wav\")\n test_signal = test_signal[0,:65536*3]\n test_signal = test_signal.view(1,1,-1)\n test_signal = test_signal.to(device)\n\n meter = pyln.Meter(sample_rate)\n\n for xidx, x_c in enumerate(tqdm(space)):\n for yidx, y_c in enumerate(space):\n c = torch.tensor([x_c,y_c], device=device).view(1,1,-1)\n with torch.no_grad():\n y_hat = model(test_signal, c).cpu().view(-1)\n sos = scipy.signal.butter(8, 20.0, fs=sample_rate, output=\"sos\", btype=\"highpass\")\n y_hat = scipy.signal.sosfilt(sos, y_hat.numpy())\n y_hat /= np.max(np.abs(y_hat))\n dB_lufs = meter.integrated_loudness(y_hat.reshape(-1,1))\n values[xidx,yidx] = dB_lufs\n\n fig, ax = plt.subplots(1,1, figsize=(5,5))\n img = plt.imshow(values, interpolation='nearest', origin=\"lower\")\n ax.set_xticks([])\n ax.set_xticklabels([])\n ax.set_yticks([])\n ax.set_yticklabels([])\n cbar = fig.colorbar(img,fraction=0.046, pad=0.04)\n cbar.set_label(\"dBFS LUFS\")\n ax.set_xlabel(r\"$c_0$\")\n ax.set_ylabel(r\"$c_1$\")\n", "_____no_output_____" ], [ "fig.tight_layout()\nfig.savefig(\"plot.pdf\", dpi=300)\nfiles.download(\"plot.pdf\")", "_____no_output_____" ] ], [ [ "## Process new sounds", "_____no_output_____" ] ], [ [ "x_whole, sample_rate = torchaudio.load(\"acgtr_clean.wav\")\nx_whole = torch.nn.functional.pad(x_whole, (rf-1, rf-1))\nx_whole = x_whole[0,:]\nx_whole = x_whole.view(1,1,-1).to(device)\nc_rand = torch.tensor([-0.1,0.0], device=device).view(1,1,-1)\n\nwith torch.no_grad():\n y_whole = model(0.2 * x_whole, c_rand)\n x_whole = causal_crop(x_whole, y_whole.shape[-1])\n\ny_whole /= y_whole.abs().max()\n\n# apply high pass filter to remove DC\nsos = scipy.signal.butter(8, 20.0, fs=sample_rate, output=\"sos\", btype=\"highpass\")\ny_whole = scipy.signal.sosfilt(sos, y_whole.cpu().view(-1).numpy())\n\n# remove start transient\ny_whole = y_whole[4410:]\nx_whole = x_whole.view(-1)[4410:].cpu().numpy()\n\ny_whole = (y_whole * 0.8)\nIPython.display.display(IPython.display.Audio(data=x_whole, rate=sample_rate))\nIPython.display.display(IPython.display.Audio(data=y_whole, rate=sample_rate))\n\nx_whole /= np.max(np.abs(x_whole))\ny_whole /= np.max(np.abs(y_whole))\n\nfig, ax = plt.subplots(nrows=1, sharex=True)\nlibrosa.display.waveshow(y_whole, sr=sample_rate, color='r', alpha=0.5, ax=ax, label='Output')\nlibrosa.display.waveshow(causal_crop(x_whole, y_whole.shape[-1]), sr=sample_rate, alpha=0.5, ax=ax, label='Input')\nplt.legend()\nplt.show(fig)\n", "_____no_output_____" ], [ "#torch.save(model, \"./reverb_full.pt\")\n#torch.save(model, \"./compressor_full.pt\")\ntorch.save(model, \"./delay_full.pt\")\n", "_____no_output_____" ], [ "#files.download(\"./reverb_full.pt\")\n#files.download(\"./compressor_full.pt\")\nfiles.download(\"./delay_full.pt\")\n", "_____no_output_____" ] ] ]
[ "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", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ec50ab8b59d6d8a37a331996f1b293c4bcc51e90
12,017
ipynb
Jupyter Notebook
_notebooks/2020-03-01-Rust-KickStarter.ipynb
byteshiva/fastpages-template
7e7ca5348d90cd15ae88a1ae946d2212d9d56ce6
[ "Apache-2.0" ]
null
null
null
_notebooks/2020-03-01-Rust-KickStarter.ipynb
byteshiva/fastpages-template
7e7ca5348d90cd15ae88a1ae946d2212d9d56ce6
[ "Apache-2.0" ]
150
2020-03-04T11:32:37.000Z
2022-03-18T08:44:21.000Z
_notebooks/2020-03-01-Rust-KickStarter.ipynb
byteshiva/blog
43f3abc3993b0bd5b54849fd7d213daa9db08640
[ "Apache-2.0" ]
null
null
null
26.35307
245
0.490555
[ [ [ "# Rust Notebook KickStarter\n> A tutorial of RUST for Jupyter notebooks.\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [rust, jupyter]", "_____no_output_____" ] ], [ [ "(1..13).map(fib).collect::<Vec<i32>>()\n", "_____no_output_____" ], [ "let values = (1..13).map(fib).collect::<Vec<i32>>();\nvalues", "_____no_output_____" ], [ "use std::sync::{Mutex, Arc};\nlet counter = Arc::new(Mutex::new(0i32));\nstd::thread::spawn({\n let counter = Arc::clone(&counter);\n move || {\n for i in 1..300 {\n *counter.lock().unwrap() += 1;\n std::thread::sleep(std::time::Duration::from_millis(100));\n }\n}});\n", "_____no_output_____" ], [ "*counter.lock()?\n", "_____no_output_____" ], [ "*counter.lock()?\n", "_____no_output_____" ], [ "*counter.lock()?\n", "_____no_output_____" ], [ ":dep base64 = \"0.10.1\"\nbase64::encode(&vec![1, 2, 3, 4])\n", "_____no_output_____" ], [ "pub fn fib(x: i32) -> i32 {\n if x <= 2 {2} else {fib(x - 2) + fib(x - 1)}\n}\n", "_____no_output_____" ], [ "use std::fmt::Debug;\npub struct Matrix<T> {pub values: Vec<T>, pub row_size: usize}\nimpl<T: Debug> Matrix<T> {\n pub fn evcxr_display(&self) {\n let mut html = String::new();\n html.push_str(\"<table>\");\n for r in 0..(self.values.len() / self.row_size) {\n html.push_str(\"<tr>\");\n for c in 0..self.row_size {\n html.push_str(\"<td>\");\n html.push_str(&format!(\"{:?}\", self.values[r * self.row_size + c]));\n html.push_str(\"</td>\");\n }\n html.push_str(\"</tr>\"); \n }\n html.push_str(\"</table>\");\n println!(\"EVCXR_BEGIN_CONTENT text/html\\n{}\\nEVCXR_END_CONTENT\", html);\n }\n}\n", "_____no_output_____" ], [ "let m = Matrix {values: vec![1,2,3,4,5,6,7,8,9], row_size: 3};\nm\n", "_____no_output_____" ], [ "extern crate image;\nextern crate base64;\npub trait EvcxrResult {fn evcxr_display(&self);}\nimpl EvcxrResult for image::RgbImage {\n fn evcxr_display(&self) {\n let mut buffer = Vec::new();\n image::png::PNGEncoder::new(&mut buffer).encode(&**self, self.width(), self.height(),\n image::ColorType::RGB(8)).unwrap();\n let img = base64::encode(&buffer);\n println!(\"EVCXR_BEGIN_CONTENT image/png\\n{}\\nEVCXR_END_CONTENT\", img); \n }\n}\nimpl EvcxrResult for image::GrayImage {\n fn evcxr_display(&self) {\n let mut buffer = Vec::new();\n image::png::PNGEncoder::new(&mut buffer).encode(&**self, self.width(), self.height(),\n image::ColorType::Gray(8)).unwrap();\n let img = base64::encode(&buffer);\n println!(\"EVCXR_BEGIN_CONTENT image/png\\n{}\\nEVCXR_END_CONTENT\", img); \n }\n}\n", "_____no_output_____" ], [ "image::ImageBuffer::from_fn(256, 256, |x, y| {\n if (x as i32 - y as i32).abs() < 3 {\n image::Rgb([0, 0, 255])\n } else {\n image::Rgb([0, 0, 0])\n }\n})\n", "_____no_output_____" ], [ ":dep tokio = {version = \"0.2\", features = [\"full\"]}\n", "_____no_output_____" ], [ "let mut stream : tokio::net::TcpStream = tokio::net::TcpStream::connect(\"127.0.0.1:99999\").await?;\n", "invalid port value\n" ], [ "let mut stream : tokio::net::TcpStream = tokio::net::TcpStream::connect(\"127.0.0.1:6573\").await?;\n", "Connection refused (os error 111)\n" ], [ "use tokio::io::AsyncWriteExt;\nstream.write(b\"Hello, world!\\n\").await?;\n", "_____no_output_____" ], [ ":vars", "_____no_output_____" ], [ ":help", "_____no_output_____" ], [ "let _immutable_binding = 1;\nlet mut mutable_binding = 1;\n\nprintln!(\"Before mutation: {}\", mutable_binding);\n\n// Ok\nmutable_binding += 1;\n\nprintln!(\"After mutation: {}\", mutable_binding);\n_immutable_binding += 1;\n", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ec50b192a76eb2f0032e7a0cacc877d117cedf99
71,990
ipynb
Jupyter Notebook
sample-cifar10.ipynb
rozay2/aoa-sample
29479d02caef458beb6c41b712395805e0fa6325
[ "MIT" ]
null
null
null
sample-cifar10.ipynb
rozay2/aoa-sample
29479d02caef458beb6c41b712395805e0fa6325
[ "MIT" ]
null
null
null
sample-cifar10.ipynb
rozay2/aoa-sample
29479d02caef458beb6c41b712395805e0fa6325
[ "MIT" ]
1
2019-06-24T00:20:12.000Z
2019-06-24T00:20:12.000Z
94.351245
29,740
0.757327
[ [ [ "## CIFAR10 Sample\n\nCIFAR10 sample with preparing large datasets\n\n- CIFAR10 dataset: https://www.cs.toronto.edu/~kriz/cifar.html\n- original sample: https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py\n\nThis sample demonstrates:\n\n- preparing large dataset\n- use `ImageDataGenerator` to load dataset\n- predict using url image", "_____no_output_____" ], [ "### Data Prep\n\nreference source: https://cntk.ai/pythondocs/CNTK_201A_CIFAR-10_DataLoader.html", "_____no_output_____" ] ], [ [ "from __future__ import print_function # Use a function definition from future version (say 3.x from 2.7 interpreter)\n\nfrom PIL import Image\nimport numpy as np\nimport pickle as cp\nimport os\nimport shutil\nimport sys", "_____no_output_____" ], [ "imgSize = 32", "_____no_output_____" ] ], [ [ "__Note__: download/unzip/untar `https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz` to `../datasets` directory before run below code", "_____no_output_____" ] ], [ [ "def saveImage(fname, data, pad, **key_parms):\n # data in CIFAR-10 dataset is in CHW format.\n pixData = data.reshape((3, imgSize, imgSize))\n \n if pad > 0:\n pixData = np.pad(pixData, ((0, 0), (pad, pad), (pad, pad)), mode='constant', constant_values=128)\n\n img = Image.new('RGB', (imgSize + 2 * pad, imgSize + 2 * pad))\n pixels = img.load()\n \n for x in range(img.size[0]):\n for y in range(img.size[1]):\n pixels[x, y] = (pixData[0][y][x], pixData[1][y][x], pixData[2][y][x])\n img.save(fname)\n \ndef saveTrainImages(datapath, foldername):\n if not os.path.exists(foldername):\n os.makedirs(foldername)\n data = {}\n\n for ifile in range(1, 6):\n print('... reading file `data_batch_%d`' % ifile)\n with open(os.path.join(datapath, 'data_batch_' + str(ifile)), 'rb') as f:\n if sys.version_info[0] < 3:\n data = cp.load(f)\n else:\n data = cp.load(f, encoding='latin1')\n \n for i in range(10000):\n fdir = os.path.join(os.path.abspath(foldername), ('%d') % (data['labels'][i]))\n fname = os.path.join(fdir, ('%d-%05d.png' % (data['labels'][i], i + (ifile - 1) * 10000)))\n saveImage(fname, data['data'][i, :], 0)\n\n\ndef saveTestImages(datapath, foldername):\n if not os.path.exists(foldername):\n os.makedirs(foldername)\n\n with open(os.path.join(datapath, 'test_batch'), 'rb') as f:\n if sys.version_info[0] < 3:\n data = cp.load(f)\n else:\n data = cp.load(f, encoding='latin1')\n for i in range(10000):\n fdir = os.path.join(os.path.abspath(foldername), ('%d') % (data['labels'][i]))\n fname = os.path.join(fdir, ('%d-%05d.png' % (data['labels'][i], i)))\n saveImage(fname, data['data'][i, :], 0)", "_____no_output_____" ], [ "# create label folders\ndatapath = '../datasets/cifar-10-batches-py'\ntrainpath = os.path.join(os.path.abspath(datapath), 'train')\ntestpath = os.path.join(os.path.abspath(datapath), 'test')\n\n# created labeled folders\nfor label in range(0, 10):\n directory = os.path.join(trainpath, '%d' % label)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\nfor label in range(0, 10):\n directory = os.path.join(testpath, '%d' % label)\n if not os.path.exists(directory):\n os.makedirs(directory)", "_____no_output_____" ], [ "# create png images from original datasets\nprint ('Converting train data to png images...')\nsaveTrainImages(datapath, os.path.join(datapath, trainpath))\nprint ('Done.')\nprint ('Converting test data to png images...')\nsaveTestImages(datapath, os.path.join(datapath, testpath))\nprint ('Done.')", "Converting train data to png images...\n... reading file `data_batch_1`\n... reading file `data_batch_2`\n... reading file `data_batch_3`\n... reading file `data_batch_4`\n... reading file `data_batch_5`\nDone.\nConverting test data to png images...\nDone.\n" ] ], [ [ "### CIFAR10 training\n\nreference source: https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py", "_____no_output_____" ] ], [ [ "import keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\nimport os\nimport matplotlib.pyplot as plt", "/anaconda/envs/py35/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\nUsing TensorFlow backend.\n" ], [ "batch_size = 32\nnum_classes = 10\nepochs = 100\n#data_augmentation = True\n#num_predictions = 20\nsave_dir = os.path.abspath('../models')\nmodel_name = 'sample_cifar10_model.h5'", "_____no_output_____" ], [ "# read dataset from directory\n# this is the augmentation configuration we will use for training\ntrain_datagen = ImageDataGenerator(\n rescale=1. / 255,\n #shear_range=0.2,\n #zoom_range=0.2,\n horizontal_flip=True)\n\n# this is the augmentation configuration we will use for testing:\n# only rescaling\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\ntrain_generator = train_datagen.flow_from_directory(\n trainpath,\n target_size=(imgSize, imgSize),\n batch_size=batch_size,\n class_mode='categorical')\n\nvalidation_generator = test_datagen.flow_from_directory(\n testpath,\n target_size=(imgSize, imgSize),\n batch_size=batch_size,\n class_mode='categorical')", "Found 50000 images belonging to 10 classes.\nFound 10000 images belonging to 10 classes.\n" ], [ "nb_train_samples = 50000\nnb_validation_samples = 10000\n\nif K.image_data_format() == 'channels_first':\n input_shape = (3, imgSize, imgSize)\nelse:\n input_shape = (imgSize, imgSize, 3)", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(Conv2D(32, (3, 3), padding='same',\n input_shape=input_shape))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes))\nmodel.add(Activation('softmax'))\n\n# initiate RMSprop optimizer\nopt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)\n\n# Let's train the model using RMSprop\nmodel.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])", "_____no_output_____" ], [ "history = model.fit_generator(\n train_generator,\n steps_per_epoch=nb_train_samples // batch_size,\n epochs=epochs,\n validation_data=validation_generator,\n validation_steps=nb_validation_samples // batch_size)", "WARNING:tensorflow:Variable *= will be deprecated. Use variable.assign_mul if you want assignment to the variable value or 'x = x * y' if you want a new python Tensor object.\nEpoch 1/100\n1562/1562 [==============================] - 25s 16ms/step - loss: 1.8047 - acc: 0.3396 - val_loss: 1.5255 - val_acc: 0.4468\nEpoch 2/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 1.5170 - acc: 0.4484 - val_loss: 1.3558 - val_acc: 0.5153\nEpoch 3/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 1.3871 - acc: 0.5004 - val_loss: 1.3051 - val_acc: 0.5383\nEpoch 4/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 1.2969 - acc: 0.5383 - val_loss: 1.1772 - val_acc: 0.5882\nEpoch 5/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 1.2269 - acc: 0.5637 - val_loss: 1.1346 - val_acc: 0.5977\nEpoch 6/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 1.1631 - acc: 0.5896 - val_loss: 1.0603 - val_acc: 0.6259\nEpoch 7/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 1.1099 - acc: 0.6088 - val_loss: 1.0094 - val_acc: 0.6476\nEpoch 8/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 1.0588 - acc: 0.6286 - val_loss: 0.9600 - val_acc: 0.6609\nEpoch 9/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 1.0213 - acc: 0.6411 - val_loss: 0.9343 - val_acc: 0.6716\nEpoch 10/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.9839 - acc: 0.6556 - val_loss: 0.9443 - val_acc: 0.6712\nEpoch 11/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.9522 - acc: 0.6676 - val_loss: 0.8820 - val_acc: 0.6945\nEpoch 12/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.9231 - acc: 0.6785 - val_loss: 0.8397 - val_acc: 0.7068\nEpoch 13/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.9019 - acc: 0.6868 - val_loss: 0.8806 - val_acc: 0.6973\nEpoch 14/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.8808 - acc: 0.6924 - val_loss: 0.8244 - val_acc: 0.7148\nEpoch 15/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.8612 - acc: 0.7019 - val_loss: 0.7994 - val_acc: 0.7259\nEpoch 16/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.8444 - acc: 0.7084 - val_loss: 0.7773 - val_acc: 0.7309\nEpoch 17/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.8306 - acc: 0.7135 - val_loss: 0.7936 - val_acc: 0.7320\nEpoch 18/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.8187 - acc: 0.7161 - val_loss: 0.7731 - val_acc: 0.7388\nEpoch 19/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.8047 - acc: 0.7225 - val_loss: 0.7640 - val_acc: 0.7371\nEpoch 20/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7952 - acc: 0.7258 - val_loss: 0.7451 - val_acc: 0.7475\nEpoch 21/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7839 - acc: 0.7292 - val_loss: 0.7354 - val_acc: 0.7441\nEpoch 22/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7791 - acc: 0.7314 - val_loss: 0.7295 - val_acc: 0.7518\nEpoch 23/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7734 - acc: 0.7351 - val_loss: 0.7216 - val_acc: 0.7525\nEpoch 24/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7681 - acc: 0.7386 - val_loss: 0.7271 - val_acc: 0.7491\nEpoch 25/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7607 - acc: 0.7402 - val_loss: 0.7204 - val_acc: 0.7552\nEpoch 26/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7593 - acc: 0.7426 - val_loss: 0.7144 - val_acc: 0.7610\nEpoch 27/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7508 - acc: 0.7441 - val_loss: 0.7302 - val_acc: 0.7551\nEpoch 28/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7489 - acc: 0.7459 - val_loss: 0.6979 - val_acc: 0.7613\nEpoch 29/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7400 - acc: 0.7482 - val_loss: 0.7059 - val_acc: 0.7601\nEpoch 30/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7378 - acc: 0.7524 - val_loss: 0.6920 - val_acc: 0.7648\nEpoch 31/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7386 - acc: 0.7488 - val_loss: 0.6969 - val_acc: 0.7648\nEpoch 32/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7298 - acc: 0.7510 - val_loss: 0.6903 - val_acc: 0.7643\nEpoch 33/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7287 - acc: 0.7517 - val_loss: 0.6901 - val_acc: 0.7616\nEpoch 34/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7205 - acc: 0.7549 - val_loss: 0.7127 - val_acc: 0.7596\nEpoch 35/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7202 - acc: 0.7542 - val_loss: 0.7026 - val_acc: 0.7688\nEpoch 36/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7158 - acc: 0.7586 - val_loss: 0.6633 - val_acc: 0.7776\nEpoch 37/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7155 - acc: 0.7581 - val_loss: 0.6569 - val_acc: 0.7742\nEpoch 38/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7055 - acc: 0.7601 - val_loss: 0.6659 - val_acc: 0.7781\nEpoch 39/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7091 - acc: 0.7622 - val_loss: 0.6726 - val_acc: 0.7747\nEpoch 40/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7008 - acc: 0.7643 - val_loss: 0.6765 - val_acc: 0.7765\nEpoch 41/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6996 - acc: 0.7660 - val_loss: 0.6502 - val_acc: 0.7792\nEpoch 42/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6959 - acc: 0.7644 - val_loss: 0.6815 - val_acc: 0.7702\nEpoch 43/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6959 - acc: 0.7657 - val_loss: 0.6414 - val_acc: 0.7829\nEpoch 44/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.7001 - acc: 0.7669 - val_loss: 0.7181 - val_acc: 0.7726\nEpoch 45/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6919 - acc: 0.7686 - val_loss: 0.6571 - val_acc: 0.7834\nEpoch 46/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6872 - acc: 0.7683 - val_loss: 0.6561 - val_acc: 0.7808\nEpoch 47/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6880 - acc: 0.7691 - val_loss: 0.6585 - val_acc: 0.7851\nEpoch 48/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6842 - acc: 0.7703 - val_loss: 0.6615 - val_acc: 0.7846\nEpoch 49/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6816 - acc: 0.7726 - val_loss: 0.6488 - val_acc: 0.7872\nEpoch 50/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6788 - acc: 0.7705 - val_loss: 0.6350 - val_acc: 0.7938\nEpoch 51/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6850 - acc: 0.7707 - val_loss: 0.6735 - val_acc: 0.7875\nEpoch 52/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6790 - acc: 0.7733 - val_loss: 0.6700 - val_acc: 0.7799\nEpoch 53/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6734 - acc: 0.7778 - val_loss: 0.6361 - val_acc: 0.7928\nEpoch 54/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6769 - acc: 0.7730 - val_loss: 0.6459 - val_acc: 0.7848\nEpoch 55/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6700 - acc: 0.7762 - val_loss: 0.7255 - val_acc: 0.7754\nEpoch 56/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6753 - acc: 0.7761 - val_loss: 0.6259 - val_acc: 0.7897\nEpoch 57/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6684 - acc: 0.7747 - val_loss: 0.6760 - val_acc: 0.7828\nEpoch 58/100\n1562/1562 [==============================] - 20s 13ms/step - loss: 0.6730 - acc: 0.7753 - val_loss: 0.6524 - val_acc: 0.7893\nEpoch 59/100\n" ], [ "# Save model and weights\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\nmodel_path = os.path.join(save_dir, model_name)\nmodel.save(model_path)\nprint('Saved trained model at %s ' % model_path)", "Saved trained model at /home/iljoong/models/sample_cifar10_model.h5 \n" ], [ "# Load model\nmodel_path = os.path.join(save_dir, model_name)\n\nmodel = keras.models.load_model(model_path)", "_____no_output_____" ] ], [ [ "# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])", "_____no_output_____" ] ], [ [ "# Get training and test loss histories\nloss = history.history['loss']\nacc = history.history['acc']\nval_loss = history.history['val_loss']\nval_acc = history.history['val_acc']\n# Create count of the number of epochs\nepoch_count = range(1, len(loss) + 1)\n\n# Visualize loss history\nfig=plt.figure(figsize=(12, 4))\nplt.figure(1)\n\nfig.add_subplot(121)\nplt.plot(epoch_count, acc, 'b--')\nplt.plot(epoch_count, loss, 'r--')\nplt.legend(['acc', 'loss'])\nplt.xlabel('epoch')\nplt.ylabel('acc vs. loss')\n\nfig.add_subplot(122)\nplt.plot(epoch_count, acc, 'b--')\nplt.plot(epoch_count, val_acc, 'r--')\nplt.legend(['acc', 'val_acc'])\nplt.xlabel('epoch')\nplt.ylabel('acc vs. val_acc')\n\nplt.show()", "_____no_output_____" ] ], [ [ "### Predict\n\ntest url or get url from search", "_____no_output_____" ] ], [ [ "import requests\nfrom PIL import Image\nimport cv2\nfrom keras.preprocessing import image\nfrom io import BytesIO", "_____no_output_____" ], [ "#test_url = \"https://boygeniusreport.files.wordpress.com/2017/01/cat.jpg\"\ntest_url = \"https://www.pensketruckrental.com/img/hero/hero_trucks_22.jpg\"\n\nr = requests.get(test_url)\n\nimg = Image.open(BytesIO(r.content))\nrsimg = cv2.resize(np.array(img), (32, 32), interpolation = cv2.INTER_AREA)\nplt.imshow(rsimg)", "_____no_output_____" ], [ "img = Image.fromarray(rsimg)\n\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx /= 255.\nclasses = model.predict(x)", "_____no_output_____" ], [ "print(classes, np.argmax(classes))\n\nl = np.argmax(classes)\nlabels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\nprint(labels[l])", "[[5.5321667e-08 6.8723911e-04 1.0592832e-13 4.5877880e-12 9.1466650e-15\n 5.7555109e-14 5.7450507e-13 2.9905965e-12 1.2686054e-07 9.9931264e-01]] 9\ntruck\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "raw", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "raw" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ec50b61c148ae590d1b0475091e9c1f1afe4748d
8,019
ipynb
Jupyter Notebook
js/italy-ht/notebooks/.ipynb_checkpoints/0 - createData-checkpoint.ipynb
tropiano/tropianhs
40bca0903186b3352b79100533192ea7df8ab961
[ "MIT" ]
null
null
null
js/italy-ht/notebooks/.ipynb_checkpoints/0 - createData-checkpoint.ipynb
tropiano/tropianhs
40bca0903186b3352b79100533192ea7df8ab961
[ "MIT" ]
null
null
null
js/italy-ht/notebooks/.ipynb_checkpoints/0 - createData-checkpoint.ipynb
tropiano/tropianhs
40bca0903186b3352b79100533192ea7df8ab961
[ "MIT" ]
null
null
null
31.324219
542
0.415638
[ [ [ "import pyhattrick.pyhattrick.pyhattrick as pht \nimport pandas as pd \n", "_____no_output_____" ], [ " team_data = []\nseries = []\nteams = []\n\n\nseriesid = pht.get_series_id_from_name(\"Serie A\")\nteams.append((pht.get_teams_from_series_id(seriesid),\"Serie A\"))\n\nfor i in range(4):\n seriesid = pht.get_series_id_from_name(\"II.\"+str(i+1))\n teams.append((pht.get_teams_from_series_id(seriesid),\"II.\"+str(i+1)))\n \nfor i in range(16):\n seriesid = pht.get_series_id_from_name(\"III.\"+str(i+1))\n teams.append((pht.get_teams_from_series_id(seriesid),\"III.\"+str(i+1)))\n\nfor i in range(64):\n seriesid = pht.get_series_id_from_name(\"IV.\"+str(i+1))\n teams.append((pht.get_teams_from_series_id(seriesid),\"IV.\"+str(i+1)))\n\n\nfor team in teams:\n league = team[1]\n for t in team[0]:\n name = t['team_name']\n id = t['team_id'] \n gF = t['team_gFor']\n gA = t['team_gAga']\n points = t['team_points']\n details = pht.get_team_details_from_team_id(id)\n region = details['team_region']\n team_data.append((name, gF, gA, points, region,league))\n\ndf = pd.DataFrame(columns=('name','gF','gA','points','region','league'),data=team_data)\n", "_____no_output_____" ], [ "df.tail(10)\ndf.to_csv(\"teamdata.csv\", encoding='utf-8')", "_____no_output_____" ], [ "df.tail(10)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
ec50c45c3aebe8035e2aeff81b373626d002891f
17,694
ipynb
Jupyter Notebook
sgan-dataset/Best of N Analyses.ipynb
yaqlee/Trajectron
0992c92913d14ced2aae639b288cf649f1fbb78d
[ "MIT" ]
95
2019-07-19T10:39:51.000Z
2022-03-12T06:56:34.000Z
sgan-dataset/Best of N Analyses.ipynb
yaqlee/Trajectron
0992c92913d14ced2aae639b288cf649f1fbb78d
[ "MIT" ]
9
2019-07-08T12:55:14.000Z
2021-04-05T18:59:21.000Z
sgan-dataset/Best of N Analyses.ipynb
yaqlee/Trajectron
0992c92913d14ced2aae639b288cf649f1fbb78d
[ "MIT" ]
34
2019-10-08T02:30:07.000Z
2021-12-02T12:38:59.000Z
35.53012
150
0.441562
[ [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport glob\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\n\nfrom collections import OrderedDict", "_____no_output_____" ], [ "def pretty_dataset_name(dataset_name):\n if dataset_name == 'eth':\n return 'ETH - Univ'\n elif dataset_name == 'hotel':\n return 'ETH - Hotel'\n elif dataset_name == 'univ':\n return 'UCY - Univ'\n elif dataset_name == 'zara1':\n return 'UCY - Zara 1'\n elif dataset_name == 'zara2':\n return 'UCY - Zara 2'\n else:\n return dataset_name", "_____no_output_____" ] ], [ [ "# Displacement Error Analyses", "_____no_output_____" ] ], [ [ "errors_df = pd.concat([pd.read_csv(f) for f in glob.glob('plots/data/*_errors.csv')], ignore_index=True)", "_____no_output_____" ], [ "errors_df.head()", "_____no_output_____" ], [ "dataset_names = ['eth', 'hotel', 'univ', 'zara1', 'zara2']", "_____no_output_____" ], [ "sgan_err_df = errors_df[(errors_df['data_precondition'] == 'prev') & (errors_df['method'] == 'sgan')]\nour_ml_err_df = errors_df[(errors_df['data_precondition'] == 'prev') & (errors_df['method'] == 'our_most_likely')]\nour_full_err_df = errors_df[(errors_df['data_precondition'] == 'prev') & (errors_df['method'] == 'our_full')]", "_____no_output_____" ], [ "sgan_err_df.head()", "_____no_output_____" ], [ "sgan_err_df.dtypes", "_____no_output_____" ], [ "random_subsamples = np.random.choice(2000, size=100, replace=False).astype(int).tolist()\n\nfor dataset_name in dataset_names:\n print(dataset_name)\n curr_sgan_df = sgan_err_df[sgan_err_df['dataset'] == dataset_name]\n curr_our_ml_df = our_ml_err_df[our_ml_err_df['dataset'] == dataset_name]\n curr_our_full_df = our_full_err_df[our_full_err_df['dataset'] == dataset_name]\n\n subsamp_sgan_df = curr_sgan_df[curr_sgan_df['sample'].isin(random_subsamples)]\n subsamp_our_ml_df = curr_our_ml_df[curr_our_ml_df['sample'].isin(random_subsamples)]\n subsamp_our_full_df = curr_our_full_df[curr_our_full_df['sample'].isin(random_subsamples)] \n \n sgan_sample_errs_df = subsamp_sgan_df.groupby(['run', 'sample', 'error_type'])['error_value'].agg(['sum', 'count']).reset_index()\n sgan_best_sample_errs_df = sgan_sample_errs_df.iloc[sgan_sample_errs_df.groupby([\"run\", \"error_type\"])['sum'].idxmin()]\n described_sgan_errs = sgan_best_sample_errs_df.groupby(['error_type']).sum().reset_index()\n described_sgan_errs['best_of_100_mean_error'] = described_sgan_errs['sum'] / described_sgan_errs['count']\n \n our_ml_sample_errs_df = subsamp_our_ml_df.groupby(['run', 'sample', 'error_type'])['error_value'].agg(['sum', 'count']).reset_index()\n our_ml_best_sample_errs_df = our_ml_sample_errs_df.iloc[our_ml_sample_errs_df.groupby([\"run\", \"error_type\"])['sum'].idxmin()]\n described_our_ml_errs = our_ml_best_sample_errs_df.groupby(['error_type']).sum().reset_index()\n described_our_ml_errs['best_of_100_mean_error'] = described_our_ml_errs['sum'] / described_our_ml_errs['count']\n\n our_full_sample_errs_df = subsamp_our_full_df.groupby(['run', 'sample', 'error_type'])['error_value'].agg(['sum', 'count']).reset_index()\n our_full_best_sample_errs_df = our_full_sample_errs_df.iloc[our_full_sample_errs_df.groupby([\"run\", \"error_type\"])['sum'].idxmin()]\n described_our_full_errs = our_full_best_sample_errs_df.groupby(['error_type']).sum().reset_index()\n described_our_full_errs['best_of_100_mean_error'] = described_our_full_errs['sum'] / described_our_full_errs['count']\n \n print('-- SGAN --')\n print(described_sgan_errs)\n \n print('-- OUR ML --')\n print(described_our_ml_errs)\n \n print('-- OUR FULL --')\n print(described_our_full_errs)\n \n print()", "eth\n-- SGAN --\n error_type run sample sum count best_of_100_mean_error\n0 fse 2211 62218 330.756034 303 1.091604\n1 mse 2211 60360 187.259471 303 0.618018\n-- OUR ML --\n error_type run sample sum count best_of_100_mean_error\n0 fse 2211 59183 237.275175 303 0.783086\n1 mse 2211 65033 121.070910 303 0.399574\n-- OUR FULL --\n error_type run sample sum count best_of_100_mean_error\n0 fse 2211 58188 213.465223 303 0.704506\n1 mse 2211 65980 111.925879 303 0.369392\n\nhotel\n-- SGAN --\n error_type run sample sum count best_of_100_mean_error\n0 fse 3486 79891 286.875943 346 0.829121\n1 mse 3486 78395 137.182538 346 0.396481\n-- OUR ML --\n error_type run sample sum count best_of_100_mean_error\n0 fse 3486 67682 118.749363 346 0.343206\n1 mse 3486 83359 66.028388 346 0.190833\n-- OUR FULL --\n error_type run sample sum count best_of_100_mean_error\n0 fse 3486 85047 118.278807 346 0.341846\n1 mse 3486 85038 68.310196 346 0.197428\n\nuniv\n-- SGAN --\n error_type run sample sum count best_of_100_mean_error\n0 fse 4560 79505 3302.869519 3330 0.991853\n1 mse 4560 85978 1573.466880 3330 0.472513\n-- OUR ML --\n error_type run sample sum count best_of_100_mean_error\n0 fse 4560 101885 3272.794825 3330 0.982821\n1 mse 4560 98572 1568.208344 3330 0.470933\n-- OUR FULL --\n error_type run sample sum count best_of_100_mean_error\n0 fse 4560 87353 3317.191868 3330 0.996154\n1 mse 4560 90096 1599.160129 3330 0.480228\n\nzara1\n-- SGAN --\n error_type run sample sum count best_of_100_mean_error\n0 fse 3321 81815 201.047816 408 0.492764\n1 mse 3321 87830 102.807640 408 0.251980\n-- OUR ML --\n error_type run sample sum count best_of_100_mean_error\n0 fse 3321 79607 260.272658 408 0.637923\n1 mse 3321 83563 130.729929 408 0.320416\n-- OUR FULL --\n error_type run sample sum count best_of_100_mean_error\n0 fse 3321 76541 252.584577 408 0.619080\n1 mse 3321 78204 129.721354 408 0.317944\n\nzara2\n-- SGAN --\n error_type run sample sum count best_of_100_mean_error\n0 fse 4950 101741 457.605461 806 0.567749\n1 mse 4950 103890 225.396435 806 0.279648\n-- OUR ML --\n error_type run sample sum count best_of_100_mean_error\n0 fse 4950 100477 525.231610 806 0.651652\n1 mse 4950 102690 264.631571 806 0.328327\n-- OUR FULL --\n error_type run sample sum count best_of_100_mean_error\n0 fse 4950 103110 528.249139 806 0.655396\n1 mse 4950 99067 269.720342 806 0.334641\n\n" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]