markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
visualize with plotly: we make three diagrams: 1) a horizontal bar plot comparing the overall papers per db 2) a vertical bar plot differentiating time and db 3) a vertical bar plot differentiating tima and db with a logarithmic y-scale (allows for better inspection of smaller numbers)
#set data for horizontal bar plot: data = [go.Bar( x=[pd.DataFrame.sum(df2)['wos'],pd.DataFrame.sum(df2)['scopus'],pd.DataFrame.sum(df2)['ARTICLE_TITLE']], y=['Web of Science', 'Scopus', 'Total'], orientation = 'h', marker=dict( color=colorlist ...
1-number of papers over time/Creating overview bar-plots.ipynb
MathiasRiechert/BigDataPapers
gpl-3.0
Source localization with MNE/dSPM/sLORETA/eLORETA The aim of this tutorial is to teach you how to compute and apply a linear inverse method such as MNE/dSPM/sLORETA/eLORETA on evoked/raw/epochs data.
import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse
0.19/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Process MEG data
data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' raw = mne.io.read_raw_fif(raw_fname) # already has an average reference events = mne.find_events(raw, stim_channel='STI 014') event_id = dict(aud_l=1) # event trigger and conditions tmin = -0.2 # start of each epoc...
0.19/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Compute the evoked response Let's just use MEG channels for simplicity.
evoked = epochs.average().pick('meg') evoked.plot(time_unit='s') evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag', time_unit='s') # Show whitening evoked.plot_white(noise_cov, time_unit='s') del epochs # to save memory
0.19/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Note that there is a relationship between the orientation of the dipoles and the surface of the cortex. For this reason, we do not use an inflated cortical surface for visualization, but the original surface used to define the source space. For more information about dipole orientations, see tut-dipole-orientations. No...
for mi, (method, lims) in enumerate((('dSPM', [8, 12, 15]), ('sLORETA', [3, 5, 7]), ('eLORETA', [0.75, 1.25, 1.75]),)): surfer_kwargs['clim']['lims'] = lims stc = apply_inverse(evoked, inverse_operator, lambda2, me...
0.19/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
์œ ์˜ ํ™•๋ฅ ์˜ ๊ฐ’์ด ์•„์ฃผ ์ž‘์œผ๋ฉด ๊ท€๋ฌด ๊ฐ€์„ค์ด ๋งž๋‹ค๋Š” ๊ฐ€์ •ํ•˜์— ๊ณ„์‚ฐ๋œ ๊ฒ€์ • ํ†ต๊ณ„๋Ÿ‰์ด ๋‚˜์˜ฌ ๊ฐ€๋Šฅ์„ฑ์ด ํฌ๊ท€ํ•˜๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค. ๋‹ค์‹œ ์˜ˆ๋ฅผ ๋“ค์ž๋ฉด "์–ด๋–ค ๋ณ‘์— ๊ฑธ๋ ธ๋‹ค"๋Š” ๊ท€๋ฌด ๊ฐ€์„ค์„ ์ฆ๋ช…ํ•˜๊ธฐ ์œ„ํ•œ ๊ฒ€์ •์—์„œ ํ˜ˆ์•ก ๊ฒ€์‚ฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ณ„์‚ฐํ•œ ์œ ์˜ํ™•๋ฅ ์ด 0.02%๋ผ๋Š” ์˜๋ฏธ๋Š” ์‹ค์ œ๋กœ ๋ณ‘์— ๊ฑธ๋ฆฐ ํ™˜์ž๋“ค ์ค‘ ํ˜ˆ์•ก ๊ฒ€์‚ฌ ์ˆ˜์น˜๊ฐ€ ํ•ด๋‹น ํ™˜์ž์˜ ํ˜ˆ์•ก ๊ฒ€์‚ฌ ์ˆ˜์น˜๋ณด๋‹ค ๋‚ฎ์€ ์‚ฌ๋žŒ์€ 0.02% ๋ฟ์ด์—ˆ๋‹ค๋Š” ๋œป์ด๊ณ  "์–ด๋–ค ํ•™์ƒ์ด ์šฐ๋“ฑ์ƒ์ด๋‹ค."๋ผ๋Š” ๊ท€๋ฌด์‚ฌ์„ค์„ ์ฆ๋ช…ํ•˜๊ธฐ ์œ„ํ•œ ๊ฒ€์ •์—์„œ ์‹œํ—˜ ์„ฑ์ ์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ณ„์‚ฐํ•œ ์œ ์˜ํ™•๋ฅ ์ด 0.3%๋ผ๋Š” ์˜๋ฏธ๋Š” ์‹ค์ œ๋กœ ์šฐ๋“ฑ์ƒ์˜ ์„ฑ์ ์„ ๋ถ„์„ํ•ด ๋ณด๋ฉด ์‹ค์ˆ˜๋กœ ์‹œํ—˜์„ ์ž˜ ๋ชป์น˜๋ฅธ ๊ฒฝ์šฐ๋ฅผ ํฌํ•จ...
1 - sp.stats.binom(15, 0.5).cdf(12-1)
12. ์ถ”์ • ๋ฐ ๊ฒ€์ •/02. ๊ฒ€์ •๊ณผ ์œ ์˜ ํ™•๋ฅ .ipynb
zzsza/Datascience_School
mit
์ด ๊ฐ’์€ 5% ๋ณด๋‹ค๋Š” ์ž‘๊ณ  1% ๋ณด๋‹ค๋Š” ํฌ๊ธฐ ๋•Œ๋ฌธ์— ์œ ์˜ ์ˆ˜์ค€์ด 5% ๋ผ๋ฉด ๊ธฐ๊ฐํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ(์ฆ‰ ๊ณต์ •ํ•œ ๋™์ „์ด ์•„๋‹ˆ๋ผ๊ณ  ๋งํ•  ์ˆ˜ ์žˆ๋‹ค.) ์œ ์˜ ์ˆ˜์ค€์ด 1% ๋ผ๋ฉด ๊ธฐ๊ฐํ•  ์ˆ˜ ์—†๋‹ค.(์ฆ‰, ๊ณต์ •ํ•œ ๋™์ „์ด ์•„๋‹ˆ๋ผ๊ณ  ๋งํ•  ์ˆ˜ ์—†๋‹ค.) ๋ฌธ์ œ2 <blockquote> ์–ด๋–ค ํŠธ๋ ˆ์ด๋”์˜ ์ผ์ฃผ์ผ ์ˆ˜์ต๋ฅ ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.:<br> -2.5%, -5%, 4.3%, -3.7% -5.6% <br> ์ด ํŠธ๋ ˆ์ด๋”๋Š” ๋ˆ์„ ๋ฒŒ์–ด๋‹ค ์ค„ ์‚ฌ๋žŒ์ธ๊ฐ€, ์•„๋‹ˆ๋ฉด ๋ˆ์„ ์žƒ์„ ์‚ฌ๋žŒ์ธ๊ฐ€? </blockquote> ์ˆ˜์ต๋ฅ ์ด ์ •๊ทœ ๋ถ„ํฌ๋ฅผ ๋”ฐ๋ฅธ ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฉด ์ด ํŠธ๋ ˆ์ด๋”์˜ ๊ฒ€์ •ํ†ต๊ณ„๋Ÿ‰์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ณ„์‚ฐ๋œ๋‹ค. $$...
x = np.array([-0.025, -0.05, 0.043, -0.037, -0.056]) t = x.mean()/x.std(ddof=1)*np.sqrt(len(x)) t, sp.stats.t(df=4).cdf(t)
12. ์ถ”์ • ๋ฐ ๊ฒ€์ •/02. ๊ฒ€์ •๊ณผ ์œ ์˜ ํ™•๋ฅ .ipynb
zzsza/Datascience_School
mit
Incremental Incremental returns a sequence of numbers that increase in regular steps.
g = Incremental(start=200, step=4) print_generated_sequence(g, num=20, seed=12345)
notebooks/v6/Primitive_generators.ipynb
maxalbert/tohu
mit
Integer Integer returns a random integer between low and high (both inclusive).
g = Integer(low=100, high=200) print_generated_sequence(g, num=20, seed=12345)
notebooks/v6/Primitive_generators.ipynb
maxalbert/tohu
mit
Timestamp
g = Timestamp(start="2018-01-01 11:22:33", end="2018-02-13 12:23:34") type(next(g)) print_generated_sequence(g, num=10, seed=12345, sep='\n') g = Timestamp(start="2018-01-01 11:22:33", end="2018-02-13 12:23:34").strftime("%-d %b %Y, %H:%M (%a)") type(next(g)) print_generated_sequence(g, num=10, seed=12345, sep='\n...
notebooks/v6/Primitive_generators.ipynb
maxalbert/tohu
mit
Date
g = Date(start="2018-01-01", end="2018-02-13") type(next(g)) print_generated_sequence(g, num=10, seed=12345, sep='\n') g = Date(start="2018-01-01", end="2018-02-13").strftime("%-d %b %Y") type(next(g)) print_generated_sequence(g, num=10, seed=12345, sep='\n')
notebooks/v6/Primitive_generators.ipynb
maxalbert/tohu
mit
Ensure the two .xls data files are in the same folder as the Jupyter notebook Before we proceed, let's make sure the two .xls data files are in the same folder as our running Jupyter notebook. We'll use a Jupyter notebook magic command to print out the contents of the folder that our notebook is in. The %ls command lis...
%ls
content/code/matplotlib_plots/stress_strain_curves/stress_strain_curve_with_python.ipynb
ProfessorKazarinoff/staticsite
gpl-3.0
We can see our Jupyter notebook stress_strain_curve_with_python.ipynb as well as the two .xls data files aluminum6061.xls and steel1045.xls are in our current folder. Now that we are sure the two .xls data files are in the same folder as our notebook, we can import the data in the two two .xls files using Panda's pd.r...
steel_df = pd.read_excel("steel1045.xls") al_df = pd.read_excel("aluminum6061.xls")
content/code/matplotlib_plots/stress_strain_curves/stress_strain_curve_with_python.ipynb
ProfessorKazarinoff/staticsite
gpl-3.0
We can use Pandas .head() method to view the first five rows of each dataframe.
steel_df.head() al_df.head()
content/code/matplotlib_plots/stress_strain_curves/stress_strain_curve_with_python.ipynb
ProfessorKazarinoff/staticsite
gpl-3.0
We see a number of columns in each dataframe. The columns we are interested in are FORCE, EXT, and CH5. Below is a description of what these columns mean. FORCE Force measurements from the load cell in pounds (lb), force in pounds EXT Extension measurements from the mechanical extensometer in percent (%), strain in pe...
strain_steel = steel_df['CH5']*0.01 d_steel = 0.506 # test bar diameter = 0.506 inches stress_steel = (steel_df['FORCE']*0.001)/(np.pi*((d_steel/2)**2)) strain_al = al_df['CH5']*0.01 d_al = 0.506 # test bar diameter = 0.506 inches stress_al = (al_df['FORCE']*0.001)/(np.pi*((d_al/2)**2))
content/code/matplotlib_plots/stress_strain_curves/stress_strain_curve_with_python.ipynb
ProfessorKazarinoff/staticsite
gpl-3.0
Build a quick plot Now that we have the data from the tensile test in four series, we can build a quick plot using Matplotlib's plt.plot() method. The first x,y pair we pass to plt.plot() is strain_steel,stress_steel and the second x,y pair we pass in is strain_al,stress_al. The command plt.show() shows the plot.
plt.plot(strain_steel,stress_steel,strain_al,stress_al) plt.show()
content/code/matplotlib_plots/stress_strain_curves/stress_strain_curve_with_python.ipynb
ProfessorKazarinoff/staticsite
gpl-3.0
We see a plot with two lines. One line represents the steel sample and one line represents the aluminum sample. We can improve our plot by adding axis labels with units, a title and a legend. Add axis labels, title and a legend Axis labels, titles and a legend are added to our plot with three Matplotlib methods. The me...
plt.plot(strain_steel,stress_steel,strain_al,stress_al) plt.xlabel('strain (in/in)') plt.ylabel('stress (ksi)') plt.title('Stress Strain Curve of Steel 1045 and Aluminum 6061 in tension') plt.legend(['Steel 1045','Aluminum 6061']) plt.show()
content/code/matplotlib_plots/stress_strain_curves/stress_strain_curve_with_python.ipynb
ProfessorKazarinoff/staticsite
gpl-3.0
The plot we see has two lines, axis labels, a title and a legend. Next we'll save the plot to a .png image file. Save the plot as a .png image Now we can save the plot as a .png image using Matplotlib's plt.savefig() method. The code cell below builds the plot and saves an image file called stress-strain_curve.png. The...
plt.plot(strain_steel,stress_steel,strain_al,stress_al) plt.xlabel('strain (in/in)') plt.ylabel('stress (ksi)') plt.title('Stress Strain Curve of Steel 1045 and Aluminum 6061 in tension') plt.legend(['Steel 1045','Aluminum 6061']) plt.savefig('stress-strain_curve.png', dpi=300, bbox_inches='tight') plt.show()
content/code/matplotlib_plots/stress_strain_curves/stress_strain_curve_with_python.ipynb
ProfessorKazarinoff/staticsite
gpl-3.0
Label Network Embeddings The label network embeddings approaches require a working tensorflow installation and the OpenNE library. To install them, run the following code: bash pip install networkx tensorflow git clone https://github.com/thunlp/OpenNE/ pip install -e OpenNE/src For an example we will use the LINE embe...
from skmultilearn.embedding import OpenNetworkEmbedder from skmultilearn.cluster import LabelCooccurrenceGraphBuilder graph_builder = LabelCooccurrenceGraphBuilder(weighted=True, include_self_edges=False) openne_line_params = dict(batch_size=1000, order=3) embedder = OpenNetworkEmbedder( graph_builder, 'LINE...
docs/source/multilabelembeddings.ipynb
scikit-multilearn/scikit-multilearn
bsd-2-clause
We now need to select a regressor and a classifier, we use random forest regressors with MLkNN which is a well working combination often used for multi-label embedding:
from skmultilearn.embedding import EmbeddingClassifier from sklearn.ensemble import RandomForestRegressor from skmultilearn.adapt import MLkNN clf = EmbeddingClassifier( embedder, RandomForestRegressor(n_estimators=10), MLkNN(k=5) ) clf.fit(X_train, y_train) predictions = clf.predict(X_test)
docs/source/multilabelembeddings.ipynb
scikit-multilearn/scikit-multilearn
bsd-2-clause
Cost-Sensitive Label Embedding with Multidimensional Scaling CLEMS is another well-perfoming method in multi-label embeddings. It uses weighted multi-dimensional scaling to embedd a cost-matrix of unique label combinations. The cost-matrix contains the cost of mistaking a given label combination for another, thus real-...
from skmultilearn.embedding import CLEMS, EmbeddingClassifier from sklearn.ensemble import RandomForestRegressor from skmultilearn.adapt import MLkNN dimensional_scaler_params = {'n_jobs': -1} clf = EmbeddingClassifier( CLEMS(metrics.jaccard_similarity_score, is_score=True, params=dimensional_scaler_params), ...
docs/source/multilabelembeddings.ipynb
scikit-multilearn/scikit-multilearn
bsd-2-clause
Scikit-learn based embedders Any scikit-learn embedder can be used for multi-label classification embeddings with scikit-multilearn, just select one and try, here's a spectral embedding approach with 10 dimensions of the embedding space:
from skmultilearn.embedding import SKLearnEmbedder, EmbeddingClassifier from sklearn.manifold import SpectralEmbedding from sklearn.ensemble import RandomForestRegressor from skmultilearn.adapt import MLkNN clf = EmbeddingClassifier( SKLearnEmbedder(SpectralEmbedding(n_components = 10)), RandomForestRegressor(...
docs/source/multilabelembeddings.ipynb
scikit-multilearn/scikit-multilearn
bsd-2-clause
On the GeoIDE Wiki they give some example CSW examples to illustrate the range possibilities. Here's one where to search for PACIOOS WMS services:
HTML('<iframe src=https://geo-ide.noaa.gov/wiki/index.php?title=ESRI_Geoportal#PacIOOS_WAF width=950 height=350></iframe>')
CSW/CSW_ISO_Queryables-IOOS.ipynb
rsignell-usgs/notebook
mit
Also on the GEO-IDE Wiki we find the list of UUIDs for each region/provider, which we turn into a dictionary here:
regionids = {'AOOS': '{1E96581F-6B73-45AD-9F9F-2CC3FED76EE6}', 'CENCOOS': '{BE483F24-52E7-4DDE-909F-EE8D4FF118EA}', 'CARICOOS': '{0C4CA8A6-5967-4590-BFE0-B8A21CD8BB01}', 'GCOOS': '{E77E250D-2D65-463C-B201-535775D222C9}', 'GLOS': '{E4A9E4F4-78A4-4BA0-B653-F548D74F68FA}', 'MARACOOS': '{A26F8553-798B-4B1C-8755-1031D752F7C...
CSW/CSW_ISO_Queryables-IOOS.ipynb
rsignell-usgs/notebook
mit
The filters can be passed as a list to getrecords2, with AND or OR implied by syntax: <pre> [a,b,c] --> a || b || c [[a,b,c]] --> a && b && c [[a,b],[c],[d],[e]] or [[a,b],c,d,e] --> (a && b) || c || d || e </pre>
# try simple query with serviceType and keyword first csw.getrecords2(constraints=[[serviceType,keywords]],maxrecords=15,esn='full') for rec,item in csw.records.iteritems(): print item.title # check out references for one of the returned records csw.records['NOAA.NOS.CO-OPS SOS'].references # filter for GCOOS SOS...
CSW/CSW_ISO_Queryables-IOOS.ipynb
rsignell-usgs/notebook
mit
Implement Preprocessing Function Text to Word Ids As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the &lt;EOS&gt; word id at the end of target_text. Th...
def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int): """ Convert source and target text to proper word ids :param source_text: String that contains all the source text. :param target_text: String that contains all the target text. :param source_vocab_to_int: Dictionar...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
""" DON'T MODIFY ANYTHING IN THIS CELL """ import numpy as np import helper import problem_unittests as tests (source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Check the Version of TensorFlow and Access to GPU This will check to make sure you have the correct version of TensorFlow and access to a GPU
""" DON'T MODIFY ANYTHING IN THIS CELL """ from distutils.version import LooseVersion import warnings import tensorflow as tf from tensorflow.python.layers.core import Dense # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.1'), 'Please use TensorFlow version 1.1 or newer' print('Tensor...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Build the Neural Network You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below: - model_inputs - process_decoder_input - encoding_layer - decoding_layer_train - decoding_layer_infer - decoding_layer - seq2seq_model Input Implement the model_inputs() fu...
def model_inputs(): """ Create TF Placeholders for input, targets, learning rate, and lengths of source and target sequences. :return: Tuple (input, targets, learning rate, keep probability, target sequence length, max target sequence length, source sequence length) """ input_data = tf.placehold...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Encoding Implement encoding_layer() to create a Encoder RNN layer: * Embed the encoder input using tf.contrib.layers.embed_sequence * Construct a stacked tf.contrib.rnn.LSTMCell wrapped in a tf.contrib.rnn.DropoutWrapper * Pass cell and embedded input to tf.nn.dynamic_rnn()
from imp import reload reload(tests) def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size): """ Create encoding layer :param rnn_inputs: Inputs for the RNN :param rnn_size: RNN Size ...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Decoding - Training Create a training decoding layer: * Create a tf.contrib.seq2seq.TrainingHelper * Create a tf.contrib.seq2seq.BasicDecoder * Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode
def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_summary_length, output_layer, keep_prob): """ Create a decoding layer for training :param encoder_state: Encoder State :param dec_cell: Decoder RNN Cell ...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Decoding - Inference Create inference decoder: * Create a tf.contrib.seq2seq.GreedyEmbeddingHelper * Create a tf.contrib.seq2seq.BasicDecoder * Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode
def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob): """ Create a decoding layer for inference :param encoder_state: Encoder ...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Build the Decoding Layer Implement decoding_layer() to create a Decoder RNN layer. Embed the target sequences Construct the decoder LSTM cell (just like you constructed the encoder cell above) Create an output layer to map the outputs of the decoder to the elements of our vocabulary Use the your decoding_layer_train(e...
def decoding_layer(dec_input, encoder_state, target_sequence_length, max_target_sequence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, decoding_embedding_size): """ Create decoding layer ...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Build the Neural Network Apply the functions you implemented above to: Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size). Process target data using your process_decoder_input(target_data, target_vocab_to_int, bat...
def seq2seq_model(input_data, target_data, keep_prob, batch_size, source_sequence_length, target_sequence_length, max_target_sentence_length, source_vocab_size, target_vocab_size, enc_embedding_size, dec_embedding_size, rnn_size, ...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Neural Network Training Hyperparameters Tune the following parameters: Set epochs to the number of epochs. Set batch_size to the batch size. Set rnn_size to the size of the RNNs. Set num_layers to the number of layers. Set encoding_embedding_size to the size of the embedding for the encoder. Set decoding_embedding_siz...
# Number of Epochs epochs = 3 # Batch Size batch_size = 256 # RNN Size rnn_size = 256 # Number of Layers num_layers = 2 # Embedding Size encoding_embedding_size = 300 decoding_embedding_size = 300 # Learning Rate learning_rate = 0.01 # Dropout Keep Probability keep_probability = 0.75 display_step = 20
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Build the Graph Build the graph using the neural network you implemented.
""" DON'T MODIFY ANYTHING IN THIS CELL """ save_path = 'checkpoints/dev' (source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess() max_target_sentence_length = max([len(sentence) for sentence in source_int_text]) train_graph = tf.Graph() with train_graph.as_default():...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Batch and pad the source and target sequences
""" DON'T MODIFY ANYTHING IN THIS CELL """ def pad_sentence_batch(sentence_batch, pad_int): """Pad sentences with <PAD> so that each sentence of a batch has the same length""" max_sentence = max([len(sentence) for sentence in sentence_batch]) return [sentence + [pad_int] * (max_sentence - len(sentence)) for...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Train Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem.
""" DON'T MODIFY ANYTHING IN THIS CELL """ def get_accuracy(target, logits): """ Calculate accuracy """ max_seq = max(target.shape[1], logits.shape[1]) if max_seq - target.shape[1]: target = np.pad( target, [(0,0),(0,max_seq - target.shape[1])], 'constant'...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Sentence to Sequence To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences. Convert the sentence to lowercase Convert words into ids using vocab_to_int Convert words not in the vocabulary, to the &lt;UNK&gt; word id.
def sentence_to_seq(sentence, vocab_to_int): """ Convert a sentence to a sequence of ids :param sentence: String :param vocab_to_int: Dictionary to go from the words to an id :return: List of word ids """ return [vocab_to_int.get(word, vocab_to_int['<UNK>']) for word in sentence.lower().spli...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
Translate This will translate translate_sentence from English to French.
translate_sentence = 'he saw a old yellow truck .' """ DON'T MODIFY ANYTHING IN THIS CELL """ translate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int) loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load saved model loader = tf.train.import_meta_graph(load_path +...
language-translation/dlnd_language_translation.ipynb
mu4farooqi/deep-learning-projects
gpl-3.0
We will create a Twitter API handle for fetching data Inorder to qualify for a Twitter API handle you need to be a Phone Verified Twitter user. Goto Twitter settings page twitter.com/settings/account Choose Mobile tab on left pane, then enter your phone number and verify by OTP Now you should be able to register ne...
# make sure to exclued this folder in git ignore path_to_cred_file = path.abspath('../restricted/api_credentials.p') # we will store twitter handle credentials in a pickle file (object de-serialization) # code for pickling credentials need to be run only once during initial configuration # fill the following dictionar...
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
From second run you can load the credentials securely form stored file If you want to check the credentials uncomment the last line in below code block
# make sure to exclued this folder in git ignore path_to_cred_file = path.abspath('../restricted/api_credentials.p') # load saved twitter credentials twitter_credentials = pickle.load(open(path_to_cred_file,'rb')) #print("\n".join(["{:20} : {}".format(key,value) for key,value in twitter_credentials.items()]))
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
Creating an Open Auth Instance With the created api and token we will open an open auth instance to authenticate our twitter account. If you feel that your twitter api credentials have been compromised you can just generate a new set of access token-secret pair, access token is like RSA to authenticate your api key.
# lets create an open authentication handler and initialize it with our twitter handlers api key auth = tweepy.OAuthHandler(twitter_credentials['api_key'],twitter_credentials['api_secret']) # access token is like password for the api key, auth.set_access_token(twitter_credentials['access_token'],twitter_credentials['...
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
Twitter API Handle Tweepy comes with a Twitter API wrapper class called 'API', passing the open auth instance to this API creates a live Twitter handle to our account. ATTENTION: Please beware that this is a handle you your own account not any pseudo account, if you tweet something with this it will be your tweet This ...
# lets create an instance of twitter api wrapper api = tweepy.API(auth) # lets do some self check user = api.me() print("{}\n{}".format(user.name,user.location))
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
Inspiration for this Project I drew inspiration for this project from the ongoing issue on traditional bull fighting AKA Jallikattu. Here I'm trying read pulse of the people based on tweets. We are searching for key word Jallikattu in Twitters public tweets, in the retured search result we are taking 150 tweets to do ...
# now lets get some data to check the sentiment on it # lets search for key word jallikattu and check the sentiment on it query = 'jallikattu' tweet_cnt = 150 peta_tweets = api.search(q=query,count=tweet_cnt)
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
Processing Tweets Once we get the tweets, we will iterate through the tweets and do following oprations 1. Pass the tweet text to TextBlob to process the tweet 2. Processed tweets will have two attributes * Polarity which is a numerical value between -1 to 1, the sentiment of the text can be infered from this. * S...
# lets go over the tweets sentiment_polarity = [0,0,0] tags = [] for tweet in peta_tweets: processed_tweet = textblob.TextBlob(tweet.text) polarity = processed_tweet.sentiment.polarity upd_index = 0 if polarity > 0 else (1 if polarity == 0 else 2) sentiment_polarity[upd_index] = sentiment_polarity[upd...
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
Sentiment Analysis We can see that majority is neutral which is contributed by 1. Tweets with media only(photo, video) 2. Tweets in regional language. Textblob do not work on our indian languages. 3. Some tweets contains only stop words or the words that do not give any positive or negative perspective. 4. Polarity ...
# lets process the hash tags in the tweets and make a word cloud visualization # normalizing tags by converting all tags to lowercase tags = [t.lower() for t in tags] # get unique count of tags to take count for each uniq_tags = list(set(tags)) tag_count = [] # for each unique hash tag take frequency of occurance for...
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
Simple Word Cloud with Twitter #tags Let us viualize the tags used in for Jallikattu by creating a tag cloud. The wordcloud package takes a single string of tags separated by whitespace. We will concatinate the tags and pass it to generate method to create a tag cloud image.
# we will create a vivid tag cloud visualization # creating a single string of texts from tags, the tag's font size is proportional to its frequency text = " ".join(tags) # this generates an image from the long string, if you wish you may save it to local wc = WordCloud().generate(text) # we will display the image w...
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
Masked Word Cloud The tag cloud can be masked using a grascale stencil image the wordcloud package neatly arranges the word in side the mask image. I have supreimposed generated word cloud image on to the mask image to provide a detailing otherwise the background of the word cloud will be white and it will appeare like...
# we can also create a masked word cloud from the tags by using grayscale image as stencil # lets load the mask image from local bull_mask = np.array(Image.open(path.abspath('../asset/bull_mask_1.jpg'))) wc_mask = WordCloud(background_color="white", mask=bull_mask).generate(text) mask_image = plt.imshow(bull_mask, cma...
sentiment_analysis/twitter_sentiment_analysis-jallikattu/code/twitter_sentiment_analysis-jallikattu_FINAL.ipynb
nixphix/ml-projects
mit
Gromov-Wasserstein example This example is designed to show how to use the Gromov-Wassertsein distance computation in POT.
# Author: Erwan Vautier <erwan.vautier@gmail.com> # Nicolas Courty <ncourty@irisa.fr> # # License: MIT License import scipy as sp import numpy as np import matplotlib.pylab as pl from mpl_toolkits.mplot3d import Axes3D # noqa import ot
docs/source/auto_examples/plot_gromov.ipynb
rflamary/POT
mit
Sample two Gaussian distributions (2D and 3D) The Gromov-Wasserstein distance allows to compute distances with samples that do not belong to the same metric space. For demonstration purpose, we sample two Gaussian distributions in 2- and 3-dimensional spaces.
n_samples = 30 # nb samples mu_s = np.array([0, 0]) cov_s = np.array([[1, 0], [0, 1]]) mu_t = np.array([4, 4, 4]) cov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s) P = sp.linalg.sqrtm(cov_t) xt = np.random.randn(n_samples, 3).dot(P) + mu_t
docs/source/auto_examples/plot_gromov.ipynb
rflamary/POT
mit
Plotting the distributions
fig = pl.figure() ax1 = fig.add_subplot(121) ax1.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples') ax2 = fig.add_subplot(122, projection='3d') ax2.scatter(xt[:, 0], xt[:, 1], xt[:, 2], color='r') pl.show()
docs/source/auto_examples/plot_gromov.ipynb
rflamary/POT
mit
Compute distance kernels, normalize them and then display
C1 = sp.spatial.distance.cdist(xs, xs) C2 = sp.spatial.distance.cdist(xt, xt) C1 /= C1.max() C2 /= C2.max() pl.figure() pl.subplot(121) pl.imshow(C1) pl.subplot(122) pl.imshow(C2) pl.show()
docs/source/auto_examples/plot_gromov.ipynb
rflamary/POT
mit
Compute Gromov-Wasserstein plans and distance
p = ot.unif(n_samples) q = ot.unif(n_samples) gw0, log0 = ot.gromov.gromov_wasserstein( C1, C2, p, q, 'square_loss', verbose=True, log=True) gw, log = ot.gromov.entropic_gromov_wasserstein( C1, C2, p, q, 'square_loss', epsilon=5e-4, log=True, verbose=True) print('Gromov-Wasserstein distances: ' + str(log0['...
docs/source/auto_examples/plot_gromov.ipynb
rflamary/POT
mit
Resolviendo el problema en forma analรญtica con SymPy Para resolver el problema, debemos utilizar la La Ecuaciรณn diferencial de la ley del enfriamiento de Newton. Los datos que tenemos son: Temperatura inicial = 34.5 Temperatura 1 hora despues = 33.9 Temperatura del ambiente = 15 Temperatura normal promedio de un ser h...
# defino las incognitas t, k = sympy.symbols('t k') y = sympy.Function('y') # expreso la ecuacion f = k*(y(t) -15) sympy.Eq(y(t).diff(t), f) # Resolviendo la ecuaciรณn edo_sol = sympy.dsolve(y(t).diff(t) - f) edo_sol
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Ahora que tenemos la soluciรณn de la Ecuaciรณn diferencial, despejemos constante de integraciรณn utilizando la condiciรณn inicial.
# Condiciรณn inicial ics = {y(0): 34.5} C_eq = sympy.Eq(edo_sol.lhs.subs(t, 0).subs(ics), edo_sol.rhs.subs(t, 0)) C_eq C = sympy.solve(C_eq)[0] C
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Ahora que ya sabemos el valor de C, podemos determinar el valor de $k$.
eq = sympy.Eq(y(t), C * sympy.E**(k*t) +15) eq ics = {y(1): 33.9} k_eq = sympy.Eq(eq.lhs.subs(t, 1).subs(ics), eq.rhs.subs(t, 1)) kn = round(sympy.solve(k_eq)[0], 4) kn
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Ahora que ya tenemos todos los datos, podemos determinar la hora aproximada de la muerte.
hmuerte = sympy.Eq(37, 19.5 * sympy.E**(kn*t) + 15) hmuerte t = round(sympy.solve(hmuerte)[0],2) t h, m = divmod(t*-60, 60) print "%d horas, %d minutos" % (h, m)
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Es decir, que pasaron aproximadamente 3 horas y 51 minutos desde que ocurriรณ el crimen, por lo tanto la hora del asesinato debio haber sido alredor de las 10:50 pm. Transformada de Laplace Un mรฉtodo alternativo que podemos utilizar para resolver en forma analรญtica Ecuaciones diferenciales ordinarias complejas, es utili...
# Ejemplo de transformada de Laplace # Defino las incognitas t = sympy.symbols("t", positive=True) y = sympy.Function("y") # simbolos adicionales. s, Y = sympy.symbols("s, Y", real=True) # Defino la ecuaciรณn edo = y(t).diff(t, t) + 3*y(t).diff(t) + 2*y(t) sympy.Eq(edo) # Calculo la transformada de Laplace L_edo = s...
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Aquรญ ya logramos convertir a la Ecuaciรณn diferencial en una ecuaciรณn algebraica. Ahora podemos aplicarle las condiciones iniciales para resolverla.
# Definimos las condiciones iniciales ics = {y(0): 2, y(t).diff(t).subs(t, 0): -3} ics # Aplicamos las condiciones iniciales L_edo_4 = L_edo_3.subs(ics) # Resolvemos la ecuaciรณn y arribamos a la Transformada de Laplace # que es equivalente a nuestra ecuaciรณn diferencial Y_sol = sympy.solve(L_edo_4, Y) Y_sol # Por รบl...
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Las Transformadas de Laplace, pueden ser una buena alternativa para resolver Ecuaciones diferenciales en forma analรญtica. Pero aรบn asรญ, siguen existiendo ecuaciones que se resisten a ser resueltas por medios analรญticos, para estos casos, debemos recurrir a los mรฉtodos numรฉricos. Series de potencias y campos de direccio...
# Defino incognitas x = sympy.symbols('x') y = sympy.Function('y') # Defino la funciรณn f = y(x)**2 + x**2 -1 # Condiciรณn inicial ics = {y(0): 0} # Resolviendo la ecuaciรณn diferencial edo_sol = sympy.dsolve(y(x).diff(x) - f, ics=ics) edo_sol
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
El resultado que nos da SymPy, es una aproximaciรณn con Series de potencias (una serie de Taylor); y el problema con las Series de potencias es que sus resultados sรณlo suelen vรกlidos para un rango determinado de valores. Una herramienta que nos puede ayudar a visualizar el rango de validez de una aproximaciรณn con Series...
# grafico de campo de direcciรณn fig, axes = plt.subplots(1, 1, figsize=(7, 5)) campo_dir = plot_direction_field(x, y(x), f, ax=axes)
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Rango de validez de la soluciรณn de series de potencia Ahora que ya conocemos a los Campos de direcciones, volvamos a la soluciรณn aproximada con Series de potencias que habiamos obtenido anteriormente. Podemos graficar esa soluciรณn en el Campos de direcciones, y compararla con una soluciรณn por mรฉtodo nรบmericos. <img tit...
fig, axes = plt.subplots(1, 2, figsize=(10, 5)) # panel izquierdo - soluciรณn aproximada por Serie de potencias plot_direction_field(x, y(x), f, ax=axes[0]) x_vec = np.linspace(-3, 3, 100) axes[0].plot(x_vec, sympy.lambdify(x, edo_sol.rhs.removeO())(x_vec), 'b', lw=2) # panel derecho - Soluciรณn por mรฉtodo...
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
<center><h1>Soluciones numรฉricas con Python</h1> <br> <h2>SciPy<h2> <br> <a href="https://scipy.org/" target="_blank"><img src="https://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/scipy_logo.png?maxWidth=175&maxHeight=61" title="SciPy"></a> </center> # SciPy [SciPy](https://www.scipy.org/) es un...
# Defino la funciรณn f = y(x)**2 + x f # la convierto en una funciรณn ejecutable f_np = sympy.lambdify((y(x), x), f) # Definimos los valores de la condiciรณn inicial y el rango de x sobre los # que vamos a iterar para calcular y(x) y0 = 0 xp = np.linspace(0, 1.9, 100) # Calculando la soluciรณn numerica para los valores...
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Los resultados son dos matrices unidimensionales de NumPy $yp$ y $yn$, de la misma longitud que las correspondientes matrices de coordenadas $xp$ y $xn$, que contienen las soluciones numรฉricas de la ecuaciรณn diferencial ordinaria para esos puntos especรญficos. Para visualizar la soluciรณn, podemos graficar las matrices $...
# graficando la solucion con el campo de direcciones fig, axes = plt.subplots(1, 1, figsize=(8, 6)) plot_direction_field(x, y(x), f, ax=axes) axes.plot(xn, yn, 'b', lw=2) axes.plot(xp, yp, 'r', lw=2) plt.show()
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Sistemas de ecuaciones diferenciales En este ejemplo, solucionamos solo una ecuaciรณn. Generalmente, la mayorรญa de los problemas se presentan en la forma de sistemas de ecuaciones diferenciales ordinarias, es decir, que incluyen varias ecuaciones a resolver. Para ver como podemos utilizar a integrate.odeint para resolve...
# Definimos el sistema de ecuaciones def f(xyz, t, sigma, rho, beta): x, y, z = xyz return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z] # Asignamos valores a los parรกmetros sigma, rho, beta = 8, 28, 8/3.0 # Condiciรณn inicial y valores de t sobre los que calcular xyz0 = [1.0, 1...
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Ecuaciones en derivadas parciales Los casos que vimos hasta ahora, se trataron de ecuaciones diferenciales ordinarias, pero ยฟcรณmo podemos hacer para resolver ecuaciones en derivadas parciales? Estas ecuaciones son mucho mรกs difรญciles de resolver, pero podes recurrir a la poderosa herramienta que nos proporciona el Mรฉto...
# Discretizando el problema N1 = N2 = 75 mesh = dolfin.RectangleMesh(dolfin.Point(0, 0), dolfin.Point(1, 1), N1, N2) # grafico de la malla. dolfin.RectangleMesh(dolfin.Point(0, 0), dolfin.Point(1, 1), 10, 10)
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
El siguiente paso es definir una representaciรณn del espacio funcional para las funciones de ensayo y prueba. Para esto vamos a utilizar la clase FunctionSpace. El constructor de esta clase tiene al menos tres argumentos: un objeto de malla, el nombre del tipo de funciรณn base, y el grado de la funciรณn base. En este caso...
# Funciones bases V = dolfin.FunctionSpace(mesh, 'Lagrange', 1) u = dolfin.TrialFunction(V) v = dolfin.TestFunction(V)
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Ahora debemos definir a nuestra EDP en su formulaciรณn dรฉbil equivalente para poder tratarla como un problema de รกlgebra lineal que podamos resolver con el MEF.
# Formulaciรณn debil de la EDP a = dolfin.inner(dolfin.nabla_grad(u), dolfin.nabla_grad(v)) * dolfin.dx f = dolfin.Constant(0.0) L = f * v * dolfin.dx
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Y definimos las condiciones de frontera.
# Defino condiciones de frontera def u0_top_boundary(x, on_boundary): return on_boundary and abs(x[1]-1) < 1e-8 def u0_bottom_boundary(x, on_boundary): return on_boundary and abs(x[1]) < 1e-8 def u0_left_boundary(x, on_boundary): return on_boundary and abs(x[0]) < 1e-8 def u0_right_boundary(x, on_boundar...
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Ahora ya podemos resolver la EDP utilizando la funciรณn dolfin.solve. El vector resultante, luego lo podemos convertir a una matriz de NumPy y utilizarla para graficar la soluciรณn con Matplotlib.
# Resolviendo la EDP u_sol = dolfin.Function(V) dolfin.solve(a == L, u_sol, bcs) # graficando la soluciรณn u_mat = u_sol.vector().array().reshape(N1+1, N2+1) x = np.linspace(0, 1, N1+2) y = np.linspace(0, 1, N1+2) X, Y = np.meshgrid(x, y) fig, ax = plt.subplots(1, 1, figsize=(8, 6)) c = ax.pcolor(X, Y, u_mat, vmin=-...
content/notebooks/ecuaciones-diferenciales.ipynb
relopezbriega/mi-python-blog
gpl-2.0
Inintialize model and solve
# Input model parameters beta = 0.99 sigma= 1 eta = 1 omega= 0.8 kappa= (sigma+eta)*(1-omega)*(1-beta*omega)/omega rhor = 0.9 phipi= 1.5 phiy = 0 rhog = 0.5 rhou = 0.5 rhov = 0.9 Sigma = 0.001*np.eye(3) # Store parameters parameters = pd.Series({ 'beta':beta, 'sigma':sigma, 'eta':eta, 'omega':omega...
examples/nk_model.ipynb
letsgoexploring/linearsolve-package
mit
Compute impulse responses and plot Compute impulse responses of the endogenous variables to a one percent shock to each exogenous variable.
# Compute impulse responses nk.impulse(T=11,t0=1,shocks=None) # Create the figure and axes fig = plt.figure(figsize=(12,12)) ax1 = fig.add_subplot(3,1,1) ax2 = fig.add_subplot(3,1,2) ax3 = fig.add_subplot(3,1,3) # Plot commands nk.irs['e_g'][['g','y','i','pi','r']].plot(lw='5',alpha=0.5,grid=True,title='Demand shock'...
examples/nk_model.ipynb
letsgoexploring/linearsolve-package
mit
Construct a stochastic simulation and plot Contruct a 151 period stochastic simulation by first siumlating the model for 251 periods and then dropping the first 100 values. The seed for the numpy random number generator is set to 0.
# Compute stochastic simulation nk.stoch_sim(T=151,drop_first=100,cov_mat=Sigma,seed=0) # Create the figure and axes fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) # Plot commands nk.simulated[['y','i','pi','r']].plot(lw='5',alpha=0.5,grid=True,title='Output, inflation, and...
examples/nk_model.ipynb
letsgoexploring/linearsolve-package
mit
Filling in Missing Values
# Impute missing values # Manually set metadata properties, as current py_entitymatching.impute_table() # requires 'fk_ltable', 'fk_rtable', 'ltable', 'rtable' properties em.set_property(A, 'fk_ltable', 'id') em.set_property(A, 'fk_rtable', 'id') em.set_property(A, 'ltable', A) em.set_property(A, 'rtable', A) A_all_a...
stage4/stage4_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Generating Features Here, we generate all the features we decided upon after our final iteration of cross validation and debugging. We only use the relevant subset of all these features in the reported iterations below.
# Generate a set of features #import pdb; pdb.set_trace(); import py_entitymatching.feature.attributeutils as au import py_entitymatching.feature.simfunctions as sim import py_entitymatching.feature.tokenizers as tok ltable = A1 rtable = B1 # Get similarity functions for generating the features for matching sim_funcs...
stage4/stage4_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Cross Validation Method
def cross_validation_eval(H): cv_iter = pd.DataFrame(columns=['Precision', 'Recall', 'F1']) # Matchers matchers = [em.DTMatcher(name='DecisionTree', random_state=0), em.RFMatcher(name='RandomForest', random_state=0), em.SVMMatcher(name='SVM', random_state=0), em.NBMatcher(name='NaiveBayes'),...
stage4/stage4_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Iteration 1: CV
# Subset of features we used on our first iteration include_features = [ 'min_num_players_min_num_players_lev_dist', 'max_num_players_max_num_players_lev_dist', 'min_gameplay_time_min_gameplay_time_lev_dist', 'max_gameplay_time_max_gameplay_time_lev_dist', ] F_1 = F.loc[F['feature_name'].isin(include_fe...
stage4/stage4_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Iteration 2: Debug
PQ = em.split_train_test(H_1, train_proportion=0.80, random_state=0) P = PQ['train'] Q = PQ['test'] # Convert the I into a set of feature vectors using F # Here, we add name edit distance as a feature include_features_2 = [ 'min_num_players_min_num_players_lev_dist', 'max_num_players_max_num_players_lev_dist'...
stage4/stage4_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Iteration 3: CV
# Convert the I into a set of feature vectors using F # Here, we add name edit distance as a feature include_features_3 = [ 'min_num_players_min_num_players_lev_dist', 'max_num_players_max_num_players_lev_dist', 'min_gameplay_time_min_gameplay_time_lev_dist', 'max_gameplay_time_max_gameplay_time_lev_dis...
stage4/stage4_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Iteration 4: CV
# Convert the I into a set of feature vectors using F # Here, we add name edit distance as a feature include_features_4 = [ 'min_num_players_min_num_players_lev_dist', 'max_num_players_max_num_players_lev_dist', 'min_gameplay_time_min_gameplay_time_lev_dist', 'max_gameplay_time_max_gameplay_time_lev_dis...
stage4/stage4_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Train-Test Set Accuracy
# Apply train, test set evaluation I_table = em.extract_feature_vecs(I, feature_table=F_2, attrs_after='label', show_progress=False) J_table = em.extract_feature_vecs(J, feature_table=F_2, attrs_after='label', show_progress=False) matchers = [ #em.DTMatcher(name='DecisionTree', random_state=0), #em.RFMatcher(name='R...
stage4/stage4_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
In that case libm_cbrt is expected to be a capsule containing the function pointer to libm's cbrt (cube root) function. This capsule can be created using ctypes:
import ctypes # capsulefactory PyCapsule_New = ctypes.pythonapi.PyCapsule_New PyCapsule_New.restype = ctypes.py_object PyCapsule_New.argtypes = ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p # load libm libm = ctypes.CDLL('libm.so.6') # extract the proper symbol cbrt = libm.cbrt # wrap it cbrt_capsule = PyCapsul...
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
The capsule is not usable from Python context (it's some kind of opaque box) but Pythran knows how to use it. beware, it does not try to do any kind of type verification. It trusts your #pythran export line.
pythran_cbrt(cbrt_capsule, 8.)
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
With Pointers Now, let's try to use the sincos function. It's C signature is void sincos(double, double*, double*). How do we pass that to Pythran?
%%pythran #pythran export pythran_sincos(None(float64, float64*, float64*), float64) def pythran_sincos(libm_sincos, val): import numpy as np val_sin, val_cos = np.empty(1), np.empty(1) libm_sincos(val, val_sin, val_cos) return val_sin[0], val_cos[0]
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
There is some magic happening here: None is used to state the function pointer does not return anything. In order to create pointers, we actually create empty one-dimensional array and let pythran handle them as pointer. Beware that you're in charge of all the memory checking stuff! Apart from that, we can now ca...
sincos_capsule = PyCapsule_New(libm.sincos, "unchecked anyway".encode(), None) pythran_sincos(sincos_capsule, 0.)
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
With Pythran It is naturally also possible to use capsule generated by Pythran. In that case, no type shenanigans is required, we're in our small world. One just need to use the capsule keyword to indicate we want to generate a capsule.
%%pythran ## This is the capsule. #pythran export capsule corp((int, str), str set) def corp(param, lookup): res, key = param return res if key in lookup else -1 ## This is some dummy callsite #pythran export brief(int, int((int, str), str set)): def brief(val, capsule): return capsule((val, "doctor"), {"...
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
It's not possible to call the capsule directly, it's an opaque structure.
try: corp((1,"some"),set()) except TypeError as e: print(e)
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
It's possible to pass it to the according pythran function though.
brief(1, corp)
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
With Cython The capsule pythran uses may come from Cython-generated code. This uses a little-known feature from cython: api and __pyx_capi__. nogil is of importance here: Pythran releases the GIL, so better not call a cythonized function that uses it.
!find -name 'cube*' -delete %%file cube.pyx #cython: language_level=3 cdef api double cube(double x) nogil: return x * x * x from setuptools import setup from Cython.Build import cythonize _ = setup( name='cube', ext_modules=cythonize("cube.pyx"), zip_safe=False, # fake CLI call script_name='...
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
The cythonized module has a special dictionary that holds the capsule we're looking for.
import sys sys.path.insert(0, '.') import cube print(type(cube.__pyx_capi__['cube'])) cython_cube = cube.__pyx_capi__['cube'] pythran_cbrt(cython_cube, 2.)
docs/examples/Third Party Libraries.ipynb
pombredanne/pythran
bsd-3-clause
Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Flux Correction 3. Key Properties --&gt; Genealogy 4. Key Properties --&gt; Software Properties 5. Key Properties --&gt; Coupling 6. Key Properties --&gt; Tuning Applied 7. Key Properties --&gt; Conservation --&gt; Heat 8. Key Properties --&gt; Conse...
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of coupled model.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
2. Key Properties --&gt; Flux Correction Flux correction properties of the model 2.1. Details Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how flux corrections are applied in the model
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.flux_correction.details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
3. Key Properties --&gt; Genealogy Genealogy and history of the model 3.1. Year Released Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Year the model was released
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.genealogy.year_released') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
3.2. CMIP3 Parent Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 CMIP3 parent if any
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.genealogy.CMIP3_parent') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
3.3. CMIP5 Parent Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 CMIP5 parent if any
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.genealogy.CMIP5_parent') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
3.4. Previous Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Previously known as
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.genealogy.previous_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
4. Key Properties --&gt; Software Properties Software properties of model 4.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
4.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s)
notebooks/hammoz-consortium/cmip6/models/sandbox-1/toplevel.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0