markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
``xyz`` is now a 3-column float array and can now probably be treated as a data frame.Here we use a ``pandas`` method to build the dataframe.
df = pandas.DataFrame(xyz)
_____no_output_____
CC0-1.0
1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb
dustykat/engr-1330-psuedo-course
Get some info, yep three columns (ordered triples to be precise!)
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 774 entries, 0 to 773 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 0 774 non-null float64 1 1 774 non-null float64 2 2 774 non-null float64 dtypes: float64(3) memory usage...
CC0-1.0
1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb
dustykat/engr-1330-psuedo-course
And some summary statistics (meaningless for these data), but now have taken data from the internet and prepared it for analysis.
df.describe()
_____no_output_____
CC0-1.0
1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb
dustykat/engr-1330-psuedo-course
And lets look at the first few rows
df.head()
_____no_output_____
CC0-1.0
1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb
dustykat/engr-1330-psuedo-course
--- ReferencesOverland, B. (2018). Python Without Fear. Addison-Wesley ISBN 978-0-13-468747-6. Grus, Joel (2015). Data Science from Scratch: First Principles with Python O’ReillyMedia. Kindle Edition.Precord, C. (2010) wxPython 2.8 Application Development Cookbook Packt Publishing Ltd. Birmingham , B27 6PA, UK ISBN 978...
# Preamble script block to identify host, user, and kernel import sys ! hostname ! whoami print(sys.executable) print(sys.version) print(sys.version_info)
atomickitty.aws engr1330content /opt/conda/envs/python/bin/python 3.8.3 (default, Jul 2 2020, 16:21:59) [GCC 7.3.0] sys.version_info(major=3, minor=8, micro=3, releaselevel='final', serial=0)
CC0-1.0
1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb
dustykat/engr-1330-psuedo-course
Create a histogram to visualize the most common salary ranges for employees.
#display salaries table salaries = pd.read_sql('select * from salaries', connection) salaries.head() #finding the maximum value of salary max_salary = salaries["salary"].max() max_salary #finding the minimum value of salary min_salary = salaries["salary"].min() min_salary #calculate gap for 6 bins bin_value = (max_sala...
_____no_output_____
ADSL
bonus.ipynb
SandraTeh/sql-challenge
Create a bar chart of average salary by title.
#display salaries table salaries = pd.read_sql('select * from salaries', connection) salaries.head() #display titles table titles = pd.read_sql('select * from titles', connection) titles.head() #display employees table employees= pd.read_sql('select * from employees', connection) employees.head() #Merge salaries table ...
_____no_output_____
ADSL
bonus.ipynb
SandraTeh/sql-challenge
Measles Incidence in Altair This is an example of reproducing the Wall Street Journal's famous [Measles Incidence Plot](http://graphics.wsj.com/infectious-diseases-and-vaccines/b02g20t20w15) in Python using [Altair](http://github.com/ellisonbg/altair/). The DataWe'll start by downloading the data. Fortunately, others...
import pandas as pd url = 'https://raw.githubusercontent.com/blmoore/blogR/master/data/measles_incidence.csv' data = pd.read_csv(url, skiprows=2, na_values='-') data.head()
_____no_output_____
BSD-3-Clause
notebooks/09-Measles.ipynb
pydatawrangler/altair_notebooks
Data Munging with Pandas This data needs to be cleaned-up a bit; we can do this with the Pandas library.We first need to aggregate the incidence data by year:
annual = data.drop('WEEK', axis=1).groupby('YEAR').sum() annual.head()
_____no_output_____
BSD-3-Clause
notebooks/09-Measles.ipynb
pydatawrangler/altair_notebooks
Next, because Altair is built to handle data where each row corresponds to a single sample, we will stack the data, re-labeling the columns for clarity:
measles = annual.reset_index() measles = measles.melt('YEAR', var_name='state', value_name='incidence') measles.head()
_____no_output_____
BSD-3-Clause
notebooks/09-Measles.ipynb
pydatawrangler/altair_notebooks
Initial Visualization Now we can use Altair's syntax for generating a heat map:
import altair as alt alt.Chart(measles).mark_rect().encode( x='YEAR:O', y='state:N', color='incidence' ).properties( width=600, height=400 )
_____no_output_____
BSD-3-Clause
notebooks/09-Measles.ipynb
pydatawrangler/altair_notebooks
Adjusting Aesthetics All operative components of the visualization appear above, we now just have to adjust the aesthetic features to reproduce the original plot.Altair allows a wide range of flexibility for such adjustments, including size and color of markings, axis labels and titles, and more.Here is the data visua...
# Define a custom colormape using Hex codes & HTML color names colormap = alt.Scale(domain=[0, 100, 200, 300, 1000, 3000], range=['#F0F8FF', 'cornflowerblue', 'mediumseagreen', '#FFEE00', 'darkorange', 'firebrick'], type='sqrt') alt.Chart(measles).mark_rect().encode( alt.X...
_____no_output_____
BSD-3-Clause
notebooks/09-Measles.ipynb
pydatawrangler/altair_notebooks
The result clearly shows the impact of the the measles vaccine introduced in the mid-1960s. Layering & SelectionsHere is another view of the data, using layering and selections to allow zooming-in
hover = alt.selection_single(on='mouseover', nearest=True, fields=['state'], empty='none') line = alt.Chart().mark_line().encode( alt.X('YEAR:Q', scale=alt.Scale(zero=False), axis=alt.Axis(format='f', title='year') ), alt.Y('incidence:Q', axis=alt.Axis(title='measles incidence')), detai...
_____no_output_____
BSD-3-Clause
notebooks/09-Measles.ipynb
pydatawrangler/altair_notebooks
Sparkify Project WorkspaceThis workspace contains a tiny subset (128MB) of the full dataset available (12GB). Feel free to use this workspace to build your project, or to explore a smaller subset with Spark before deploying your cluster on the cloud. Instructions for setting up your Spark cluster is included in the la...
# import libraries import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt from pyspark.sql import SparkSession from pyspark.ml.feature import RegexTokenizer, VectorAssembler, Normalizer, StandardScaler from pyspark.sql.functions import isnan, when, count, col from pyspark.sql.funct...
_____no_output_____
MIT
.ipynb_checkpoints/Sparkify-checkpoint.ipynb
rabadzhiyski/projectSpark
Load and Clean DatasetIn this workspace, the mini-dataset file is `mini_sparkify_event_data.json`. Load and clean the dataset, checking for invalid or missing data - for example, records without userids or sessionids.
pwd path = '/home/freemo/Projects/largeData/mini_sparkify_event_data.json' df = spark.read.json(file) df.take(1) print((df.count(), len(df.columns))) mising_values.show() df.show(5) spark.conf.set('spark.sql.repl.eagerEval.enabled', True) df df.show(1, vertical=True) df.printSchema() df.select([count(when(col(c).isNull...
+---------------+----------+---------+------+-------------+--------+---------+-----+--------------------+------+-----------+-------------+---------+--------------------+------+-------------+--------------------+------+ | artist| auth|firstName|gender|itemInSession|lastName| length|level| locat...
MIT
.ipynb_checkpoints/Sparkify-checkpoint.ipynb
rabadzhiyski/projectSpark
USER INPUT
tickers = get_ticker_list() asset_list = [ticker['Ticker'] for ticker in tickers] #asset_list.remove("GAIL") #asset_list = ['ICICIBANK', 'HDFC', 'HDFCBANK', 'INFY', 'RELIANCE', 'ASIANPAINT', 'TCS', 'MARUTI', 'TATAMOTORS', 'CIPLA'] asset_list = ["ABBOTINDIA", "ACC", "ADANIENT", "ADANIGREEN", "ADANITRANS", "ALKEM", "AMBU...
_____no_output_____
MIT
jupyter notebooks/Analysis/Stocks/.ipynb_checkpoints/Portfolio Analysis-checkpoint 5.ipynb
rahulspsec/JupyterNB_PortfolioTools
Portfolio Strategy Tools
strat = PortfolioStrategy(asset_list, period = 1000, cob = cob)
_____no_output_____
MIT
jupyter notebooks/Analysis/Stocks/.ipynb_checkpoints/Portfolio Analysis-checkpoint 5.ipynb
rahulspsec/JupyterNB_PortfolioTools
Correlation Matrix
fig = strat.plot_correlation_matrix() fig.show()
_____no_output_____
MIT
jupyter notebooks/Analysis/Stocks/.ipynb_checkpoints/Portfolio Analysis-checkpoint 5.ipynb
rahulspsec/JupyterNB_PortfolioTools
Correlated Stocks
corr_pair = strat.get_correlation_pair() print("Highly Correlated:") display_html(corr_pair[corr_pair['Correlation'] > .95]) print("\nInversely Correlated:") display_html(corr_pair[corr_pair['Correlation'] < -.90])
_____no_output_____
MIT
jupyter notebooks/Analysis/Stocks/.ipynb_checkpoints/Portfolio Analysis-checkpoint 5.ipynb
rahulspsec/JupyterNB_PortfolioTools
Efficient Frontier
market_portfolio = strat.get_efficient_market_portfolio(plot = True, num_ports = 500, show_frontier =True) #plot =True to plot Frontier
_____no_output_____
MIT
jupyter notebooks/Analysis/Stocks/.ipynb_checkpoints/Portfolio Analysis-checkpoint 5.ipynb
rahulspsec/JupyterNB_PortfolioTools
Market Portfolio
market_portfolio = market_portfolio.T market_portfolio = market_portfolio[market_portfolio['MP'] != 0.00] plt.pie(market_portfolio.iloc[:-3,0], labels=market_portfolio.index.tolist()[:-3]) market_portfolio
_____no_output_____
MIT
jupyter notebooks/Analysis/Stocks/.ipynb_checkpoints/Portfolio Analysis-checkpoint 5.ipynb
rahulspsec/JupyterNB_PortfolioTools
**Ticker Performance**
strat.calcStat(format_result = True)
_____no_output_____
MIT
jupyter notebooks/Analysis/Stocks/.ipynb_checkpoints/Portfolio Analysis-checkpoint 5.ipynb
rahulspsec/JupyterNB_PortfolioTools
Bayes's Theorem Think Bayes, Second EditionCopyright 2020 Allen B. DowneyLicense: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) In the previous chapter, we derived Bayes's Theorem:$$P(A|B) = \frac{P(A) P(B|A)}{P(B)}$$As an example, we use...
import pandas as pd table = pd.DataFrame(index=['Bowl 1', 'Bowl 2'])
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
Now I'll add a column to represent the priors:
table['prior'] = 1/2, 1/2 table
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
And a column for the likelihoods:
table['likelihood'] = 3/4, 1/2 table
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
Here we see a difference from the previous method: we compute likelihoods for both hypotheses, not just Bowl 1:* The chance of getting a vanilla cookie from Bowl 1 is 3/4.* The chance of getting a vanilla cookie from Bowl 2 is 1/2.You might notice that the likelihoods don't add up to 1. That's OK; each of them is a pr...
table['unnorm'] = table['prior'] * table['likelihood'] table
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
I call the result `unnorm` because these values are the **"unnormalized posteriors"**. Each of them is the product of a prior and a likelihood:$$P(B_i)~P(D|B_i)$$which is the numerator of Bayes's Theorem. If we add them up, we have$$P(B_1)~P(D|B_1) + P(B_2)~P(D|B_2)$$which is the denominator of Bayes's Theorem, $P(D)$...
prob_data = table['unnorm'].sum() prob_data
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
Notice that we get 5/8, which is what we got by computing $P(D)$ directly.And we can compute the posterior probabilities like this:
table['posterior'] = table['unnorm'] / prob_data table
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
The posterior probability for Bowl 1 is 0.6, which is what we got using Bayes's Theorem explicitly.As a bonus, we also get the posterior probability of Bowl 2, which is 0.4.When we add up the unnormalized posteriors and divide through, we force the posteriors to add up to 1. **This process is called "normalization"**,...
table2 = pd.DataFrame(index=[6, 8, 12])
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
I'll use fractions to represent the prior probabilities and the likelihoods. That way they don't get rounded off to floating-point numbers.
from fractions import Fraction table2['prior'] = Fraction(1, 3) table2['likelihood'] = Fraction(1, 6), Fraction(1, 8), Fraction(1, 12) table2
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
Once you have priors and likelhoods, the remaining steps are always the same, so I'll put them in a function:
def update(table): """Compute the posterior probabilities.""" table['unnorm'] = table['prior'] * table['likelihood'] prob_data = table['unnorm'].sum() table['posterior'] = table['unnorm'] / prob_data return prob_data
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
And call it like this.
prob_data = update(table2)
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
Here is the final Bayes table:
table2
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
The posterior probability of the 6-sided die is 4/9, which is a little more than the probabilities for the other dice, 3/9 and 2/9.Intuitively, the 6-sided die is the most likely because it had the highest likelihood of producing the outcome we saw. The Monty Hall ProblemNext we'll use a Bayes table to solve one of th...
table3 = pd.DataFrame(index=['Door 1', 'Door 2', 'Door 3']) table3['prior'] = Fraction(1, 3) table3
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
The data is that Monty opened Door 3 and revealed a goat. So let'sconsider the probability of the data under each hypothesis:* If the car is behind Door 1, Monty chooses Door 2 or 3 at random, so the probability he opens Door 3 is $1/2$.* If the car is behind Door 2, Monty has to open Door 3, so the probability of the ...
table3['likelihood'] = Fraction(1, 2), 1, 0 table3
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
Now that we have priors and likelihoods, we can use `update` to compute the posterior probabilities.
update(table3) table3
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
After Monty opens Door 3, the posterior probability of Door 1 is $1/3$;the posterior probability of Door 2 is $2/3$.So you are better off switching from Door 1 to Door 2. As this example shows, our intuition for probability is not alwaysreliable. Bayes's Theorem can help by providing a divide-and-conquer strategy:1. F...
# Solution goes here coins=pd.DataFrame(index=['Tricky','Normal']) coins['prior']=Fraction(1,2) coins['likelihood']=1,Fraction(1,2) update(coins) coins.loc['Tricky','posterior']
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
**My Answer was right!** ✅ **Exercise:** Suppose you meet someone and learn that they have two children.You ask if either child is a girl and they say yes.What is the probability that both children are girls?Hint: Start with four equally likely hypotheses.
# Solution goes here
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
**My Answer was wrong!** ❎ :I don't understand problem correctly. **Exercise:** There are many variations of the [Monty Hall problem](https://en.wikipedia.org/wiki/Monty_Hall_problem). For example, suppose Monty always chooses Door 2 if he can, andonly chooses Door 3 if he has to (because the car is behind Door 2).If ...
# Solution goes here monty_1=pd.DataFrame(index=['Door 1','Door 2','Door 3']) monty_1['prior']=Fraction(1,3) monty_1['likelihood']=1,0,1 update(monty_1) monty_1.loc['Door 3','posterior']
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
**My Answer was right!** ✅ Solution goes heremonty_2=pd.DataFrame(index=['Door 1','Door 2','Door 3'])monty_2['prior']=Fraction(1,3)monty_2['likelihood']=0,1,0update(monty_2)monty_2.loc['Door 2','posterior']monty_2 **My Answer was right!** ✅ **Exercise:** M&M's are small candy-coated chocolates that come in a variety o...
# Solution goes here MandM=pd.DataFrame(index=['From 1994','From 1996']) MandM['prior']=Fraction(1,2) MandM['likelihood']=Fraction(2,10),Fraction(13,100) update(MandM) MandM.loc['From 1994','posterior'] MandM
_____no_output_____
MIT
notebooks/chap02.ipynb
anvaari/ThinkBayes2
Using the Prediction Model Environment
import getpass import json import os import sys import time import pandas as pd from tqdm import tqdm_notebook as tqdm from seffnet.constants import ( DEFAULT_EMBEDDINGS_PATH, DEFAULT_GRAPH_PATH, DEFAULT_MAPPING_PATH, DEFAULT_PREDICTIVE_MODEL_PATH, RESOURCES ) from seffnet.literature import query_europe_p...
aldis
MIT
notebooks/Using the Predictive Model.ipynb
AldisiRana/SE_KGE
Loading the Data
from seffnet.default_predictor import predictor print(f"""Loaded default predictor using paths: embeddings: {DEFAULT_EMBEDDINGS_PATH} graph: {DEFAULT_GRAPH_PATH} model: {DEFAULT_PREDICTIVE_MODEL_PATH} mapping: {DEFAULT_MAPPING_PATH} """)
Loaded default predictor using paths: embeddings: c:\users\aldis\documents\github\seffnet\resources\embeddings\0812_weighted_node2vec_emb.embeddings graph: c:\users\aldis\documents\github\seffnet\resources\basic_graphs\fullgraph_with_chemsim.edgelist model: c:\users\aldis\documents\github\seffnet\resources\p...
MIT
notebooks/Using the Predictive Model.ipynb
AldisiRana/SE_KGE
Examples of different kinds of predictions with literature evidence side effect - target association
r = predictor.find_new_relation( source_name='EGFR_HUMAN', target_name='Papulopustular rash', ) print(json.dumps(r, indent=2)) #PMID: 18165622 r = predictor.find_new_relation( source_id='9451', # Histamine receptor H1 target_id='331', # Drowsiness ) print(json.dumps(r, indent=2)) #PMID: 26626077 r = pre...
{ "source": { "node_id": "8670", "namespace": "uniprot", "identifier": "P22303", "name": "ACES_HUMAN", "entity_type": "target" }, "target": { "node_id": "309", "namespace": "umls", "identifier": "C0428977", "name": "Bradycardia", "entity_type": "phenotype" }, "lor": 0.8...
MIT
notebooks/Using the Predictive Model.ipynb
AldisiRana/SE_KGE
drug- side effect association
r = predictor.find_new_relation( source_id='3534', # diazepam target_id='670', # Libido decreased ) print(json.dumps(r, indent=2)) #PMID: 29888057 r = predictor.find_new_relation( source_id='1148', # Cytarabine target_id='1149', # Anaemia megaloblastic ) print(json.dumps(r, indent=2)) # PMID: 23157...
{ "source": { "node_id": "1148", "namespace": "pubchem.compound", "identifier": "6175", "name": "Cytidine", "entity_type": "experimental drug" }, "target": { "node_id": "1149", "namespace": "umls", "identifier": "C0002888", "name": "Anaemia megaloblastic", "entity_type": "p...
MIT
notebooks/Using the Predictive Model.ipynb
AldisiRana/SE_KGE
drug-target association
r = predictor.find_new_relation( source_id='14672', # Sertindole target_id='9350', # CHRM1 receptor ) print(json.dumps(r, indent=2)) # PMID: 29942259
{ "source": { "node_id": "14672", "namespace": "pubchem.compound", "identifier": "60149", "name": "Sertindole", "entity_type": "approved drug" }, "target": { "node_id": "9350", "namespace": "uniprot", "identifier": "P11229", "name": "ACM1_HUMAN", "entity_type": "target" }...
MIT
notebooks/Using the Predictive Model.ipynb
AldisiRana/SE_KGE
Example of predicting relations using node2vec model and embeddings
def get_predictions_df(curie, results_type=None): results = predictor.find_new_relations( node_curie=curie, results_type=results_type, k=50, ) results_df = pd.DataFrame(results['predictions']) results_df = results_df[['node_id', 'namespace', 'identifier', 'name', 'lor', 'novel']]...
{ "source": { "node_id": "5265", "namespace": "pubchem.compound", "identifier": "37542", "name": "Ribavirin", "entity_type": "approved drug" }, "target": { "node_id": "947", "namespace": "umls", "identifier": "C0006840", "name": "Candida infection", "entity_type": "phenotyp...
MIT
notebooks/Using the Predictive Model.ipynb
AldisiRana/SE_KGE
from google.colab import drive drive.mount('/content/drive') import pandas as pd import numpy as np import seaborn as sns from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.impute import SimpleImputer from sklearn.preprocessing import LabelEncoder cardata_df = pd.read_csv('/content/drive/MyDr...
Dataset after preprocessing Price Age KM ... Automatic CC Doors 0 0.763763 -1.822802e+00 -0.583476 ... 0.0 2.314976 3.0 1 0.832715 -1.822802e+00 0.115551 ... 0.0 2.314976 3.0 2 0.887877 -1.767012e+00 -0.725566 ... 0.0 2.314976 3.0 3 ...
MIT
lab2/Lab_02_Data_Preprocessing.ipynb
dnhirapara/049_DarshikHirapara
Submission Instructions
# Now click the 'Submit Assignment' button above.
_____no_output_____
MIT
ConvolutionalNeuralNetworks/Week4/Exercise_4_Multi_class_classifier_Question-FINAL.ipynb
wilsonjr/Tensorflow-Developer
When you're done or would like to take a break, please run the two cells below to save your work and close the Notebook. This will free up resources for your fellow learners.
%%javascript <!-- Save the notebook --> IPython.notebook.save_checkpoint(); %%javascript IPython.notebook.session.delete(); window.onbeforeunload = null setTimeout(function() { window.close(); }, 1000);
_____no_output_____
MIT
ConvolutionalNeuralNetworks/Week4/Exercise_4_Multi_class_classifier_Question-FINAL.ipynb
wilsonjr/Tensorflow-Developer
octavemagic: Octave inside IPython Installation The `octavemagic` extension provides the ability to interact with Octave. It is provided by the `oct2py` package,which may be installed using `pip` or `easy_install`.To enable the extension, load it as follows:
%load_ext oct2py.ipython
_____no_output_____
MIT
example/octavemagic_extension.ipynb
ankostis/oct2py
Overview Loading the extension enables three magic functions: `%octave`, `%octave_push`, and `%octave_pull`.The first is for executing one or more lines of Octave, while the latter allow moving variables between the Octave and Python workspace.Here you see an example of how to execute a single line of Octave, and how ...
x = %octave [1 2; 3 4]; x a = [1, 2, 3] %octave_push a %octave a = a * 2; %octave_pull a a
_____no_output_____
MIT
example/octavemagic_extension.ipynb
ankostis/oct2py
When using the cell magic, `%%octave` (note the double `%`), multiple lines of Octave can be executed together. Unlikewith the single cell magic, no value is returned, so we use the `-i` and `-o` flags to specify input and output variables. Also note the use of the semicolon to suppress the Octave output.
%%octave -i x -o U,S,V [U, S, V] = svd(x); print(U, S, V)
[[-0.40455358 -0.9145143 ] [-0.9145143 0.40455358]] [[ 5.4649857 0. ] [ 0. 0.36596619]] [[-0.57604844 0.81741556] [-0.81741556 -0.57604844]]
MIT
example/octavemagic_extension.ipynb
ankostis/oct2py
Plotting Plot output is automatically captured and displayed, and using the `-f` flag you may choose its format (currently, `png` and `svg` are supported).
%%octave -f svg p = [12 -2.5 -8 -0.1 8]; x = 0:0.01:1; polyout(p, 'x') plot(x, polyval(p, x));
_____no_output_____
MIT
example/octavemagic_extension.ipynb
ankostis/oct2py
The width or the height can be specified to constrain the image while maintaining the original aspect ratio.
%%octave -f png -w 600 % butterworth filter, order 2, cutoff pi/2 radians b = [0.292893218813452 0.585786437626905 0.292893218813452]; a = [1 0 0.171572875253810]; freqz(b, a, 32); %%octave -s 600,200 -f png % Note: On Windows, this will not show the plots unless Ghostscript is installed. subplot(121); [x, y] = ...
_____no_output_____
MIT
example/octavemagic_extension.ipynb
ankostis/oct2py
Multiple figures can be drawn. Note that when using imshow the image will be created as a PNG with the rawimage dimensions.
%%octave -f svg -h 300 sombrero figure imshow(rand(200,200))
_____no_output_____
MIT
example/octavemagic_extension.ipynb
ankostis/oct2py
Plots can be drawn inline (default) or bring up the Octave plotting GUI by using the -g (or --gui) flag:
%%octave -g plot([1,2,3]) # brings up an Octave plotting GUI
_____no_output_____
MIT
example/octavemagic_extension.ipynb
ankostis/oct2py
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.png) Automated Machine Lea...
import json import logging import warnings import numpy as np import pandas as pd import azureml.core from azureml.core.workspace import Workspace from azureml.core.experiment import Experiment from azureml.train.automl import AutoMLConfig
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.ipynb
MustAl-Du/MachineLearningNotebooks
Accessing the Azure ML workspace requires authentication with Azure.The default authentication is interactive authentication using the default tenant. Executing the ws = Workspace.from_config() line in the cell below will prompt for authentication the first time that it is run.If you have multiple Azure tenants, you ca...
ws = Workspace.from_config() ds = ws.get_default_datastore() # choose a name for the run history container in the workspace experiment_name = 'automl-grouping-oj' # project folder project_folder = './sample_projects/{}'.format(experiment_name) experiment = Experiment(ws, experiment_name) output = {} output['SDK vers...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.ipynb
MustAl-Du/MachineLearningNotebooks
DataUpload data to your default datastore and then load it as a `TabularDataset`
from azureml.core.dataset import Dataset # upload training and test data to your default datastore ds = ws.get_default_datastore() ds.upload(src_dir='./data', target_path='groupdata', overwrite=True, show_progress=True) # load data from your datastore data = Dataset.Tabular.from_delimited_files(path=ds.path('groupdata/...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.ipynb
MustAl-Du/MachineLearningNotebooks
Compute Create or Attach existing AmlComputeYou will need to create a compute target for your automated ML run. In this tutorial, you create AmlCompute as your training compute resource. Creation of AmlCompute takes approximately 5 minutes. If the AmlCompute with that name is already in your workspace this code will ...
from azureml.core.compute import AmlCompute from azureml.core.compute import ComputeTarget # Choose a name for your cluster. amlcompute_cluster_name = "cpu-cluster-11" found = False # Check if this compute target already exists in the workspace. cts = ws.compute_targets if amlcompute_cluster_name in cts and cts[amlco...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.ipynb
MustAl-Du/MachineLearningNotebooks
AutoMLConfig Create a base AutoMLConfigThis configuration will be used for all the groups in the pipeline.
target_column = 'Quantity' time_column_name = 'WeekStarting' grain_column_names = ['Brand'] group_column_names = ['Store'] max_horizon = 20 automl_settings = { "iteration_timeout_minutes" : 5, "experiment_timeout_minutes" : 15, "primary_metric" : 'normalized_mean_absolute_error', "time_column_name": tim...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.ipynb
MustAl-Du/MachineLearningNotebooks
PipelineWe've written a script to generate the individual pipeline steps used to create each automl step. Calling this script will return a list of PipelineSteps that will train multiple groups concurrently and then deploy these models.This step requires an Enterprise workspace to gain access to this feature. To learn...
from azureml.core.webservice import Webservice from azureml.exceptions import WebserviceException service_name = 'grouped-model' try: # if you want to get existing service below is the command # since aci name needs to be unique in subscription deleting existing aci if any # we use aci_service_name to crea...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.ipynb
MustAl-Du/MachineLearningNotebooks
TrainUse the list of steps generated from above to build the pipeline and submit it to your compute for remote training.
from azureml.pipeline.core import Pipeline pipeline = Pipeline( description="A pipeline with one model per data group using Automated ML.", workspace=ws, steps=steps) pipeline_run = experiment.submit(pipeline) from azureml.widgets import RunDetails RunDetails(pipeline_run).show() pipeline_run.wait_for_...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.ipynb
MustAl-Du/MachineLearningNotebooks
TestNow we can use the holdout set to test our models and ensure our web-service is running as expected.
from azureml.core.webservice import AciWebservice service = AciWebservice(ws, service_name) X_test = data_test.to_pandas_dataframe() # Drop the column we are trying to predict (target column) x_pred = X_test.drop(target_column, inplace=False, axis=1) x_pred.head() # Get Predictions test_sample = X_test.drop(target_colu...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/forecasting-grouping/auto-ml-forecasting-grouping.ipynb
MustAl-Du/MachineLearningNotebooks
ex05-Filtering a Query with WHERESometimes, you’ll want to only check the rows returned by a query, where one or more columns meet certain criteria. This can be done with a WHERE statement. The WHERE clause is an optional clause of the SELECT statement. It appears after the FROM clause as the following statement:>SELE...
%load_ext sql
_____no_output_____
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
1. Connet to the given database of demo.db3
%sql sqlite:///data/demo.db3
_____no_output_____
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
If you do not remember the tables in the demo data, you can always use the follow command to query. Here we select the table of watershed_yearly as an example.
%sql SELECT name FROM sqlite_master WHERE type='table'
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
2. Retrieving data with WHERETake the table of ***rch*** as an example. 2.1 Check the table colums firstly.
%sql SELECT * From rch LIMIT 5
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
2.2 Check the number of rowsThere should be 8280 rows. This can be done with the SQLite ***COUNT*** function. We will touch other SQLite function over the next few notebooks.
%sql SELECT COUNT(*) as nrow From rch
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
2.3 Use WHERE to retrieve dataLet’s say we are interested in records for only the year 1981. Using a WHERE is pretty straightforward for a simple criterion like this.
%sql SELECT RCH, YR, MO, FLOW_INcms, FLOW_OUTcms From rch WHERE YR=1981
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
2.4 use *AND* to further filter dataThere are 23 RCHs. We are only intersted in the 10th RCH. We can add another filter condition with an ***AND*** statement.
%sql SELECT RCH, YR, MO, FLOW_INcms, FLOW_OUTcms From rch WHERE YR=1981 AND RCH=10
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
2.5 More combinations of filters We also can further filter data with the operators of ***!=*** or ****** to get data except 1981.
%sql SELECT RCH, YR, MO, FLOW_INcms, FLOW_OUTcms From rch WHERE YR<>1981 and RCH=10 and MO=6
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
We can further filter the data to spefic months using ***OR*** statement. For example, we'd like check the data in the months of 3, 6 and 9. However, we have to use ***()*** to make them as one condition.:) It is a trick. You can try!
%sql SELECT RCH, YR, MO, FLOW_INcms, FLOW_OUTcms From rch WHERE YR>2009 and RCH=10 and (MO=3 or MO=6 or MO=9 or MO=12)
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
Or we can simplify the above filter using the ***IN*** statement.
%sql SELECT RCH, YR, MO, FLOW_INcms, FLOW_OUTcms From rch WHERE YR>2009 and RCH=10 and MO in (3, 6, 9, 12)
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
Or the months are ***NOT*** in 3, 6, 9, 12
%sql SELECT RCH, YR, MO, FLOW_INcms, FLOW_OUTcms From rch WHERE YR>2009 and RCH=10 and MO NOT IN (3,6,9,12)
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
2.6 Filter with math operatorsFor example, we could use the modulus operator (%) to filter the MOs.
%sql SELECT RCH, YR, MO, FLOW_INcms, FLOW_OUTcms From rch WHERE YR>2009 and RCH=10 and MO % 3 = 0
* sqlite:///data/demo.db3 Done.
MIT
ex05-Filtering a Query with WHERE.ipynb
hoganbyun/Practice-SQL-with-SQLite-and-Jupyter-Notebook
Scheme 2Non-transfer of xMore secureRequires one-time additional sharing of a dictionaryFrom the two dictionaries is inferred the total number of output states(in the cell below, 2 + 2 = 4)
constant_index_dictionary = {} constant_index_dictionary['0000'] = [0, 2] constant_index_dictionary['0001'] = [2, 3] constant_index_dictionary['0010'] = [0, 1] constant_index_dictionary['0011'] = [1, 3] constant_index_dictionary['0100'] = [2, 3] constant_index_dictionary['0101'] = [1, 2] constant_index_dictionary['0110...
Message: 0101 1110 10 0100 00 1110 11 0100 00 0010 00 1110 10 0100 00 0010 00 1100 00 REJECT 2.47572660446167
MIT
Quantum Cryptography/Quantum_inspired_digital_signatures.ipynb
NimishMishra/research
k-Path dependent scheme
constant_index_dictionary = {} constant_index_dictionary['0000'] = [0, 2] constant_index_dictionary['0001'] = [2, 3] constant_index_dictionary['0010'] = [0, 1] constant_index_dictionary['0011'] = [1, 3] constant_index_dictionary['0100'] = [2, 3] constant_index_dictionary['0101'] = [1, 2] constant_index_dictionary['0110...
_____no_output_____
MIT
Quantum Cryptography/Quantum_inspired_digital_signatures.ipynb
NimishMishra/research
Creating a long message100 *bits*
def create_random_message(NUMBER_OF_BITS): message = "" c = qiskit.ClassicalRegister(1) q = qiskit.QuantumRegister(1) s = qiskit.Aer.get_backend('qasm_simulator') for i in range(NUMBER_OF_BITS): print(i) random_circuit = qiskit.QuantumCircuit(q, c) random_circuit.h(q[0]) random_circuit.measur...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 101100000101101011001111101101...
MIT
Quantum Cryptography/Quantum_inspired_digital_signatures.ipynb
NimishMishra/research
Signing a long message
def sign_message(message): signature = "" ITER = int(len(message)/4) start_time = time.time() STEPS = 5 # security parameter: length of the walk iter = 0 while True: if(iter == ITER): break state = message[0:4] initialise_starting_state(int(state[0]), int(s...
_____no_output_____
MIT
Quantum Cryptography/Quantum_inspired_digital_signatures.ipynb
NimishMishra/research
Table of Contents1&nbsp;&nbsp;Goal2&nbsp;&nbsp;Var3&nbsp;&nbsp;Init4&nbsp;&nbsp;Merging4.1&nbsp;&nbsp;SV artifact4.2&nbsp;&nbsp;rep-seqs4.3&nbsp;&nbsp;Taxonomy5&nbsp;&nbsp;Alignment5.1&nbsp;&nbsp;Creating alignment5.2&nbsp;&nbsp;Masking alignment6&nbsp;&nbsp;Phylogeny6.1&nbsp;&nbsp;Unrooted tree6.2&nbsp;&nbsp;Rooted tr...
work_dir = '/ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA/merged/' run_dir = '/ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA/' miseq_runs = c('Run0116', 'Run0122', 'Run0126', 'Run0189', 'Run0190') # params conda_env = 'qiime2-2019.10' ...
_____no_output_____
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
Init
library(dplyr) library(tidyr) library(ggplot2) library(LeyLabRMisc) df.dims() make_dir(work_dir)
Directory already exists: /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA/merged/
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
Merging SV artifact
# artifacts for individual runs P = file.path(run_dir, '{run}', 'table_merged_filt.qza') runs = miseq_runs %>% as.list %>% lapply(function(x) glue::glue(P, run=x)) runs # function to merge tables merge_tables = function(in_tbls, out_tbl, conda_env){ cmd = 'qiime feature-table merge --i-tables {in_tbls}...
CMD: qiime feature-table merge --i-tables /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA//Run0116/table_merged_filt.qza /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA//Run0122/table_merged_filt.qza /ebio/abt3_projects/Georg_animal_feces/d...
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
rep-seqs
# artifacts for individual runs P = file.path(run_dir, '{run}', 'rep-seqs_merged_filt.qza') runs = miseq_runs %>% as.list %>% lapply(function(x) glue::glue(P, run=x)) runs # function to merge seqs merge_seqs = function(in_seqs, out_seq, conda_env){ cmd = 'qiime feature-table merge-seqs --i-data {in_se...
CMD: qiime feature-table merge-seqs --i-data /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA//Run0116/rep-seqs_merged_filt.qza /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA//Run0122/rep-seqs_merged_filt.qza /ebio/abt3_projects/Georg_anima...
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
Taxonomy
# artifacts for individual runs P = file.path(run_dir, '{run}', 'taxonomy.qza') runs = miseq_runs %>% as.list %>% lapply(function(x) glue::glue(P, run=x)) runs # function to merge tax merge_tax = function(in_taxs, out_tax, conda_env){ cmd = 'qiime feature-table merge-taxa --i-data {in_seqs} --o-merged...
CMD: qiime feature-table merge-taxa --i-data /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA//Run0116/taxonomy.qza /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA//Run0122/taxonomy.qza /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/Mi...
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
Alignment Creating alignment
aln_file = file.path(work_dir, 'aligned-rep-seqs_filt.qza') cmd = 'qiime alignment mafft --p-n-threads {threads} --i-sequences {in_seq} --o-alignment {out_aln}' cmd = glue::glue(cmd, threads=threads, in_seq=seqs_merged_file, out_aln=aln_file) bash_job(cmd, conda_env=conda_env, stderr=TRUE)
Saved FeatureData[AlignedSequence] to: /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA/merged//aligned-rep-seqs_filt.qza
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
Masking alignment
aln_mask_file = file.path(work_dir, 'aligned-rep-seqs_filt_masked.qza') cmd = 'qiime alignment mask --i-alignment {in_aln} --o-masked-alignment {out_aln}' cmd = glue::glue(cmd, in_aln=aln_file, out_aln=aln_mask_file) bash_job(cmd, conda_env=conda_env, stderr=TRUE)
Saved FeatureData[AlignedSequence] to: /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA/merged//aligned-rep-seqs_filt_masked.qza
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
Phylogeny Unrooted tree
phy_unroot_file = file.path(work_dir, 'aligned-rep-seqs_filt_masked_unroot-tree.qza') cmd = 'qiime phylogeny fasttree --p-n-threads {threads} --i-alignment {in_aln} --o-tree {out_phy}' cmd = glue::glue(cmd, threads=threads, in_aln=aln_mask_file, out_phy=phy_unroot_file) bash_job(cmd, conda_env=conda_env, stderr=TRUE)
Saved Phylogeny[Unrooted] to: /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA/merged//aligned-rep-seqs_filt_masked_unroot-tree.qza
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
Rooted tree
phy_root_file = file.path(work_dir, 'aligned-rep-seqs_filt_masked_midroot-tree.qza') cmd = 'qiime phylogeny midpoint-root --i-tree {in_phy} --o-rooted-tree {out_phy}' cmd = glue::glue(cmd, in_phy=phy_unroot_file, out_phy=phy_root_file) bash_job(cmd, conda_env=conda_env, stderr=TRUE)
Saved Phylogeny[Rooted] to: /ebio/abt3_projects/Georg_animal_feces/data/16S_arch/MiSeq-Runs-116-122-126-189-190/LLA/merged//aligned-rep-seqs_filt_masked_midroot-tree.qza
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
sessionInfo
sessionInfo()
_____no_output_____
MIT
01_LLA/02_LLA_run_merge.ipynb
leylabmpi/16S-arc_vertebrate_paper
Test web application locally This notebook pulls some images and tests them against the local web app running inside the Docker container we made previously.
import matplotlib.pyplot as plt import numpy as np from testing_utilities import * import requests %matplotlib inline %load_ext autoreload %autoreload 2 docker_login = 'fboylu' image_name = docker_login + '/kerastf-gpu'
_____no_output_____
MIT
Keras_Tensorflow/03_TestLocally.ipynb
marabout2015/AKSDeploymentTutorial
Run the Docker conatainer in the background and open port 80. Notice we are using nvidia-docker and not docker command.
%%bash --bg -s "$image_name" nvidia-docker run -p 80:80 $1
_____no_output_____
MIT
Keras_Tensorflow/03_TestLocally.ipynb
marabout2015/AKSDeploymentTutorial
Wait a few seconds for the application to spin up and then check that everything works.
!curl 'http://0.0.0.0:80/' !curl 'http://0.0.0.0:80/version'
1.4.1
MIT
Keras_Tensorflow/03_TestLocally.ipynb
marabout2015/AKSDeploymentTutorial
Pull an image of a Lynx to test our local web app with.
IMAGEURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Lynx_lynx_poing.jpg/220px-Lynx_lynx_poing.jpg" plt.imshow(to_img(IMAGEURL)) jsonimg = img_url_to_json(IMAGEURL) jsonimg[:100] headers = {'content-type': 'application/json'} %time r = requests.post('http://0.0.0.0:80/score', data=jsonimg, headers=hea...
CPU times: user 4.86 ms, sys: 0 ns, total: 4.86 ms Wall time: 2.4 s <Response [200]>
MIT
Keras_Tensorflow/03_TestLocally.ipynb
marabout2015/AKSDeploymentTutorial
Let's try a few more images.
images = ('https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Lynx_lynx_poing.jpg/220px-Lynx_lynx_poing.jpg', 'https://upload.wikimedia.org/wikipedia/commons/3/3a/Roadster_2.5_windmills_trimmed.jpg', 'http://www.worldshipsociety.org/wp-content/themes/construct/lib/scripts/timthumb/thumb.php?s...
/anaconda/envs/AKSDeploymentKeras/lib/python3.5/site-packages/matplotlib/cbook/deprecation.py:107: MatplotlibDeprecationWarning: Passing one of 'on', 'true', 'off', 'false' as a boolean is deprecated; use an actual boolean (True/False) instead. warnings.warn(message, mplDeprecation, stacklevel=1)
MIT
Keras_Tensorflow/03_TestLocally.ipynb
marabout2015/AKSDeploymentTutorial
Next let's quickly check what the request response performance is for the locally running Docker container.
image_data = list(map(img_url_to_json, images)) # Retrieve the images and data timer_results = list() for img in image_data: res=%timeit -r 1 -o -q requests.post(url, data=img, headers=headers) timer_results.append(res.best) timer_results print('Average time taken: {0:4.2f} ms'.format(10**3 * np.mean(timer_resu...
edb629d68eca
MIT
Keras_Tensorflow/03_TestLocally.ipynb
marabout2015/AKSDeploymentTutorial
Homework part I: Prohibited Comment Classification (3 points)![img](https://github.com/yandexdataschool/nlp_course/raw/master/resources/banhammer.jpg)__In this notebook__ you will build an algorithm that classifies social media comments into normal or toxic.Like in many real-world cases, you only have a small (10^3) d...
import pandas as pd data = pd.read_csv("comments.tsv", sep='\t') texts = data['comment_text'].values target = data['should_ban'].values data[50::200] from sklearn.model_selection import train_test_split texts_train, texts_test, y_train, y_test = train_test_split(texts, target, test_size=0.5, random_state=42)
_____no_output_____
MIT
week02_classification/homework_part1.ipynb
andnlv/natural-language-processing
__Note:__ it is generally a good idea to split data into train/test before anything is done to them.It guards you against possible data leakage in the preprocessing stage. For example, should you decide to select words present in obscene tweets as features, you should only count those words over the training set. Other...
from nltk.tokenize import TweetTokenizer tokenizer = TweetTokenizer() preprocess = lambda text: ' '.join(tokenizer.tokenize(text.lower())) text = 'How to be a grown-up at work: replace "fuck you" with "Ok, great!".' print("before:", text,) print("after:", preprocess(text),) # task: preprocess each comment in train and...
_____no_output_____
MIT
week02_classification/homework_part1.ipynb
andnlv/natural-language-processing
Solving it: bag of words![img](http://www.novuslight.com/uploads/n/BagofWords.jpg)One traditional approach to such problem is to use bag of words features:1. build a vocabulary of frequent words (use train data only)2. for each training sample, count the number of times a word occurs in it (for each word in vocabulary...
# task: find up to k most frequent tokens in texts_train, # sort them by number of occurences (highest first) k = 10000 from collections import Counter bow_vocabulary = list(zip(*Counter((' '.join(texts_train)).split()).most_common(k)))[0] print('example features:', sorted(bow_vocabulary)[::100]) def text_to_bow(tex...
_____no_output_____
MIT
week02_classification/homework_part1.ipynb
andnlv/natural-language-processing
Machine learning stuff: fit, predict, evaluate. You know the drill.
from sklearn.linear_model import LogisticRegression bow_model = LogisticRegression().fit(X_train_bow, y_train) from sklearn.metrics import roc_auc_score, roc_curve for name, X, y, model in [ ('train', X_train_bow, y_train, bow_model), ('test ', X_test_bow, y_test, bow_model) ]: proba = model.predict_proba(...
_____no_output_____
MIT
week02_classification/homework_part1.ipynb
andnlv/natural-language-processing