markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Finally a little bit of glue to make it all go together. | def animate_param(data, arg_name='n_neighbors', arg_list=[]):
frame_data = generate_frame_data(data, arg_name, arg_list)
return create_animation(frame_data, arg_name, arg_list) | notebooks/AnimatingUMAP.ipynb | lmcinnes/umap | bsd-3-clause |
Now we can create an animation. It will be embedded as an HTML5 video into this notebook. | animate_param(data, 'n_neighbors', [3, 4, 5, 7, 10, 15, 25, 50, 100, 200])
animate_param(data, 'min_dist', [0.0, 0.01, 0.1, 0.2, 0.4, 0.6, 0.9])
animate_param(data, 'local_connectivity', [0.1, 0.2, 0.5, 1, 2, 5, 10])
animate_param(data, 'set_op_mix_ratio', np.linspace(0.0, 1.0, 10)) | notebooks/AnimatingUMAP.ipynb | lmcinnes/umap | bsd-3-clause |
Za začetek povsem sledimo korakom, ki smo jih naredili „na roke“. Povzamimo „algoritem“
vse člene damo na levo stran
enačbo pomnožimo z $x$
levo stran faktoriziramo
iz faktorjev preberemo rešitev | enacba = sym.Eq(x+2/x,3)
enacba | 01a_enacbe.ipynb | mrcinv/matpy | gpl-2.0 |
Vključimo izpis formul v lepši obliki, ki ga omogoča SymPy. | sym.init_printing() # lepši izpis formul
enacba
# vse člene damo na levo stran in pomnožimo z x
leva = (enacba.lhs - enacba.rhs)*x
leva
# levo stran razpišemo/zmnožimo
leva = sym.expand(leva)
leva
# levo stran faktoriziramo
leva = sym.factor(leva)
leva | 01a_enacbe.ipynb | mrcinv/matpy | gpl-2.0 |
Od tu naprej postane precej komplicirano, kako rešitve programsko izluščiti iz zadnjega rezultata. Če nas zanimajo le rešitve, lahko zgornji postopek izpustimo in preprosto uporabimo funkcijo solve. | # rešitve enačbe najlažje dobimo s funkcijo solve
resitve = sym.solve(enacba)
resitve | 01a_enacbe.ipynb | mrcinv/matpy | gpl-2.0 |
Grafična rešitev
Rešitve enačbe si lahko predstavljamo grafično. Iščemo vrednosti $x$, pri katerih je leva stran enaka desni. Če narišemo graf leve in desne strani na isto sliko, so rešitve enačbe ravno x-koordinate presečišča obeh grafov. Za risanje grafov uporabimo knjižnico matplotlib. Graf funkcije narišemo tako, d... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
t = np.arange(-1,3,0.01) # zaporedje x-ov, v katerih bomo tabelirali funkcijo
leva_f = sym.lambdify(x,enacba.lhs) # lambdify iz leve strani enačbe naredi python funkcijo, ki jo uporabimo na t
desna_f = sym.lambdify(x,enacba.rhs) # podobno za desno st... | 01a_enacbe.ipynb | mrcinv/matpy | gpl-2.0 |
Naloga
Poišči vse rešitve enačbe
$$x^2-2=1/x.$$
Uporabi sympy.solve in grafično predstavi rešitve.
naprej: neenačbe >> | import disqus
%reload_ext disqus
%disqus matpy | 01a_enacbe.ipynb | mrcinv/matpy | gpl-2.0 |
Input | bloboftext = """
This little piggy went to market,
This little piggy stayed home,
This little piggy had roast beef,
This little piggy had none,
And this little piggy went wee wee wee all the way home.
""" | text/2015-07-23_nltk-and-POS.ipynb | csiu/datasci | mit |
Workflow
Tokenization to break text into units e.g. words, phrases, or symbols
Stop word removal to get rid of common words
e.g. this, a, is | ## Tokenization
bagofwords = nltk.word_tokenize(bloboftext.lower())
print len(bagofwords)
## Stop word removal
stop = stopwords.words('english')
bagofwords = [i for i in bagofwords if i not in stop]
print len(bagofwords) | text/2015-07-23_nltk-and-POS.ipynb | csiu/datasci | mit |
About stemmers and lemmatisation
Stemming to reduce a word to its roots
e.g. having => hav
Lemmatisation to determine a word's lemma/canonical form
e.g. having => have
English Stemmers and Lemmatizers
For stemming English words with NLTK, you can choose between the PorterStemmer or the LancasterStemmer. The Po... | snowball_stemmer = SnowballStemmer("english")
## What words was stemmed?
_original = set(bagofwords)
_stemmed = set([snowball_stemmer.stem(i) for i in bagofwords])
print 'BEFORE:\t%s' % ', '.join(map(lambda x:'"%s"'%x, _original-_stemmed))
print ' AFTER:\t%s' % ', '.join(map(lambda x:'"%s"'%x, _stemmed-_original))
... | text/2015-07-23_nltk-and-POS.ipynb | csiu/datasci | mit |
Count & POS tag of each stemmed/non-stop word
meaning of POS tags: Penn Part of Speech Tags
NN Noun, singular or mass
VBD Verb, past tense | for token, count in Counter(bagofwords).most_common():
print '%d\t%s\t%s' % (count, nltk.pos_tag([token])[0][1], token) | text/2015-07-23_nltk-and-POS.ipynb | csiu/datasci | mit |
Proportion of POS tags | record = {}
for token, count in Counter(bagofwords).most_common():
postag = nltk.pos_tag([token])[0][1]
if record.has_key(postag):
record[postag] += count
else:
record[postag] = count
recordpd = pd.DataFrame.from_dict([record]).T
recordpd.columns = ['count']
N = sum(recordpd['count'])
reco... | text/2015-07-23_nltk-and-POS.ipynb | csiu/datasci | mit |
The first step is to create and object using the SampleSize class with the parameter of interest, the sample size calculation method, and the stratification status. In this example, we want to calculate sample size for proportions, using wald method for a stratified design. This is achived with the following snippet of... | # target coverage rates
expected_coverage = {
"Dakar": 0.849,
"Ziguinchor": 0.809,
"Diourbel": 0.682,
"Saint-Louis": 0.806,
"Tambacounda": 0.470,
"Kaolack": 0.797,
"Thies": 0.834,
"Louga": 0.678,
"Fatick": 0.766,
"Kolda": 0.637,
"Matam": 0.687,
"Kaffrine": 0.766,
"Ked... | docs/source/tutorial/sample_size_calculation.ipynb | survey-methods/samplics | mit |
The sample size calculation above assumes that the design effect (DEFF) was equal to 1. A design effect of 1 correspond to sampling design with a variance equivalent to a simple random selection of same sample size. In the context of complex sampling designs, DEFF is often different from 1. Stage sampling and unequal w... | sen_vaccine_wald.calculate(target=expected_coverage, half_ci=0.07, deff=1.401 ** 2)
sen_vaccine_wald.to_dataframe() | docs/source/tutorial/sample_size_calculation.ipynb | survey-methods/samplics | mit |
Since the sample design is stratified, the sample size calculation will be more precised if DEFF is specified at the stratum level which is available from the 2017 Senegal DHS provided report. Some regions have a design effect below 1. To be conservative with our sample size calculation, we will use 1.21 as the minimum... | # Target coverage rates
expected_deff = {
"Dakar": 1.100 ** 2,
"Ziguinchor": 1.100 ** 2,
"Diourbel": 1.346 ** 2,
"Saint-Louis": 1.484 ** 2,
"Tambacounda": 1.366 ** 2,
"Kaolack": 1.360 ** 2,
"Thies": 1.109 ** 2,
"Louga": 1.902 ** 2,
"Fatick": 1.100 ** 2,
"Kolda": 1.217 ** 2,
"... | docs/source/tutorial/sample_size_calculation.ipynb | survey-methods/samplics | mit |
The sample size calculation above does not account for attrition of sample sizes due to non-response. In the 2017 Semegal DHS, the overal household and women reponse rate was abou 94.2%. | # Calculate sample sizes with a resp_rate of 94.2%
sen_vaccine_wald.calculate(
target=expected_coverage, half_ci=0.07, deff=expected_deff, resp_rate=0.942
)
# Convert sample sizes to a dataframe
sen_vaccine_wald.to_dataframe(
col_names=["region", "vaccine_coverage", "precision", "number_12_23_months"]
) | docs/source/tutorial/sample_size_calculation.ipynb | survey-methods/samplics | mit |
Fleiss method
The World Health OR=rganization (WHO) recommends using the Fleiss method for calculating sample size for vaccination coverage survey (see https://www.who.int/immunization/documents/who_ivb_18.09/en/). To use the Fleiss method, the examples shown above are the same with method="fleiss". | sen_vaccine_fleiss = SampleSize(
parameter="proportion", method="fleiss", stratification=True
)
sen_vaccine_fleiss.calculate(
target=expected_coverage, half_ci=0.07, deff=expected_deff, resp_rate=0.942
)
sen_vaccine_sample = sen_vaccine_fleiss.to_dataframe(
col_names=["region", "vaccine_coverage", "preci... | docs/source/tutorial/sample_size_calculation.ipynb | survey-methods/samplics | mit |
2. Explore the data and process the missing values | train.info()
test.info()
# Define the function to fill the missing values
def replace_nan(data):
# в столбцах 'START_PACK' и 'OFFER_GROUP' заменим NaN на 'Unknown'
data['START_PACK'] = data['START_PACK'].fillna('Unknown')
data['OFFER_GROUP'] = data['OFFER_GROUP'].fillna('Unknown')
# столбцы с дат... | Vasilev_Sergey_eng.ipynb | Vasilyeu/mobile_customer | mit |
Now we have test and train data sets without missing data and with a few new features
3. Preparing data for machine learning | # Conversion of categorical data
le = LabelEncoder()
for n in ['STATUS', 'TP_CURRENT', 'START_PACK', 'OFFER_GROUP', 'GENDER', 'MLLS_STATE',
'PORTED_IN', 'PORTED_OUT', 'OBLIG_ON_START', 'ASSET_TYPE_LAST', 'DEVICE_TYPE_BUS', 'USAGE_AREA']:
le.fit(train[n])
train[n] = le.transform(train[n])
test[n] =... | Vasilev_Sergey_eng.ipynb | Vasilyeu/mobile_customer | mit |
4. Built the first model to all features | # Ensemble of classifiers by Weighted Average Probabilities
clf1 = LogisticRegression(random_state=42)
clf2 = RandomForestClassifier(random_state=42)
clf3 = SGDClassifier(loss='log', random_state=42)
eclf = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), ('sgd', clf3)], voting='soft', weights=[1,1,1])
# Qual... | Vasilev_Sergey_eng.ipynb | Vasilyeu/mobile_customer | mit |
On the training data, the best result is provided by an ensemble of three algorithms
5. Determine the importance of attributes using the Random Forest | # Построим лес и подсчитаем важность признаков
forest = ExtraTreesClassifier(n_estimators=250,
random_state=0)
forest.fit(X_train, y_train)
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_],
axis=0)
indices = np.... | Vasilev_Sergey_eng.ipynb | Vasilyeu/mobile_customer | mit |
As we can see, the most important features are STATUS, USAGE_AREA, DEVICE_TYPE_BUS и REVENUE_NOV_16
6. Select the features for classification | # Create a list of features sorted by importance
imp_features = []
for i in indices:
imp_features.append(features[i])
# the best accuracy is obtained by using the 17 most important features
best_features = imp_features[:17]
X_train2 = X_train[best_features]
# Quality control of the model by cross-validation with c... | Vasilev_Sergey_eng.ipynb | Vasilyeu/mobile_customer | mit |
7. Building a classifier based on test data | # roc curve on test data
colors = ['black', 'orange', 'blue', 'green']
linestyles = [':', '--', '-.', '-']
for clf, label, clr, ls in zip([clf1, clf2, clf3, eclf],
['Logistic Regression', 'Random Forest', 'SGD', 'Ensemble'],
colors, linestyles):
y_pred... | Vasilev_Sergey_eng.ipynb | Vasilyeu/mobile_customer | mit |
The ROC AUC values obtained for the cross validation and for the test sample are the same, which indicates that the model is not overfitted and not underfitted.
8. Getting the final result | result_pred = eclf.fit(X_train[best_features], y_train).predict_proba(test[best_features])
result = pd.DataFrame(test['USER_ID'])
result['ACTIVITY_DEC_16_PROB'] = list(result_pred[:, 1])
result.to_csv('result.csv', encoding='utf8', index=None) | Vasilev_Sergey_eng.ipynb | Vasilyeu/mobile_customer | mit |
We also prepared a simple tabulated file with the description of each GSM. It will be usefull to calculate LFC. | experiments = pd.read_table("GSE6207_experiments.tab") | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
We can look in to this file: | experiments | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
Now we select the GSMs that are controls. | controls = experiments[experiments.Type == 'control'].Experiment.tolist() | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
Using GEOparse we can download experiments and look into the data: | gse = GEOparse.get_GEO("GSE6207") | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
The GPL we are interested: | gse.gpls['GPL570'].columns | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
And the columns that are available for exemplary GSM: | gse.gsms["GSM143385"].columns | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
We take the opportunity and check if everything is OK with the control samples. For this we just use simple histogram. To obtain table with each GSM as column, ID_REF as index and VALUE in each cell we use pivot_samples method from GSE object (we restrict the columns to the controls): | pivoted_control_samples = gse.pivot_samples('VALUE')[controls]
pivoted_control_samples.head() | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
And we plot: | pivoted_control_samples.hist()
sns.despine(offset=10, trim=True) | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
Next we would like to filter out probes that are not expressed. The gene is expressed (in definition here) when its average log2 intensity in control samples is above 0.25 quantile. I.e. we filter out worst 25% genes. | pivoted_control_samples_average = pivoted_control_samples.median(axis=1)
print "Number of probes before filtering: ", len(pivoted_control_samples_average)
expression_threshold = pivoted_control_samples_average.quantile(0.25)
expressed_probes = pivoted_control_samples_average[pivoted_control_samples_average >= express... | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
We can see that the filtering succeeded. Now we can pivot all the samples and filter out probes that are not expressed: | samples = gse.pivot_samples("VALUE").ix[expressed_probes] | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
The most important thing is to calculate log fold changes. What we have to do is for each time-point identify control and transfected sample and subtract the VALUES (they are provided as log2 transformed already, we subtract transfection from the control). In the end we create new DataFrame with LFCs: | lfc_results = {}
sequence = ['4 hours',
'8 hours',
'16 hours',
'24 hours',
'32 hours',
'72 hours',
'120 hours']
for time, group in experiments.groupby("Time"):
print time
control_name = group[group.Type == "control"].Experiment.iloc[0... | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
Let's look at the data sorted by 24-hours time-point: | lfc_results.sort("24 hours").head() | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
We are interested in the gene expression changes upon transfection. Thus, we have to annotate each probe with ENTREZ gene ID, remove probes without ENTREZ or with multiple assignments. Although this strategy might not be optimal, after this we average the LFC for each gene over probes. | # annotate with GPL
lfc_result_annotated = lfc_results.reset_index().merge(gse.gpls['GPL570'].table[["ID", "ENTREZ_GENE_ID"]],
left_on='index', right_on="ID").set_index('index')
del lfc_result_annotated["ID"]
# remove probes without ENTREZ
lfc_result_annotated = lfc_result_annotated.drop... | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
We can now look at the data: | lfc_result_annotated.sort("24 hours").head() | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
At that point our job is basicaly done. However, we might want to check if the experiments worked out at all. To do this we will use hsa-miR-124a-3p targets predicted by MIRZA-G algorithm. The targets should be downregulated. First we read MIRZA-G results: | header = ["GeneID", "miRNA", "Total score without conservation", "Total score with conservation"]
miR124_targets = pd.read_table("seed-mirza-g_all_mirnas_per_gene_scores_miR_124a.tab", names=header)
miR124_targets.head() | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
We shall extract targets as a simple list of strings: | miR124_targets_list = map(str, miR124_targets.GeneID.tolist())
print "Number of targets:", len(miR124_targets_list) | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
As can be seen there is a lot of targets (genes that posses a seed match in their 3'UTRs). We will use all of them. As first stem we will annotate genes if they are targets or not and add this information as a column to DataFrame: | lfc_result_annotated["Is miR-124a target"] = [i in miR124_targets_list for i in lfc_result_annotated.index]
cols_to_plot = [i for i in lfc_result_annotated.columns if "hour" in i] | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
In the end we can plot the results: | a = sns.pointplot(data=lfc_result_annotated[lfc_result_annotated["Is miR-124a target"]][cols_to_plot],
color=c2,
label="miR-124a target")
b = sns.pointplot(data=lfc_result_annotated[~lfc_result_annotated["Is miR-124a target"]][cols_to_plot],
color=c1,
labe... | tests/Analyse_hsa-miR-124a-3p_transfection_time-course.ipynb | guma44/GEOparse | bsd-3-clause |
Columns Interested
loan_status -- Current status of the loan<br/>
loan_amnt -- The listed amount of the loan applied for by the borrower. If at some point in time, the credit department reduces the loan amount, then it will be reflected in this value.<br/>
int_rate -- interest rate of the loan <br/>
grade -- LC ... | ## 2015
df_app_2015 = pd.read_csv('data/LoanStats3d_securev1.csv.zip', compression='zip', low_memory=False,\
header=1)
df_app_2015.loan_status.unique()
df_app_2015.head(5)
df_app_2015['delinq_amnt'].unique()
df_app_2015.info(max_cols=111)
df_app_2015.groupby('title').loan_amnt.mean()
df_a... | Data_Preprocessing/LendingClub_DataExploratory.ipynb | kayzhou22/DSBiz_Project_LendingClub | mit |
Decriptive Analyss
Annual income distribution
Total loan amount groupby interest rate chunks
Average loan amount groupby grade
Average loan amount groupby | ## selected columns
df = df_app_2015.ix[:, ['loan_status','loan_amnt', 'int_rate', 'grade', 'sub_grade',\
'purpose',\
'annual_inc', 'emp_length', 'home_ownership',\
'fico_range_low','fico_range_high',\
'num_actv_bc_tl', 'tot... | Data_Preprocessing/LendingClub_DataExploratory.ipynb | kayzhou22/DSBiz_Project_LendingClub | mit |
Fig 1a shows the sorted issued loan amounts from low to high.<br/>
Fig 2c is a histogram showing the distribution of the issued loan amounts.
Obeservation<br/>
The Loan amounts vary from $1000 to $35,000, and the most frequent loan amounts issued are around $10,000. | inc_75 = df.describe().loc['75%', 'annual_inc']
count_75 = int(len(df)*0.75)
# 2. Applicant Anual Income Distribution
fig = pl.figure(figsize=(8,16))
ax0 = fig.add_subplot(311)
ax0.plot(range(len(df.annual_inc)), sorted(df.annual_inc), '.', color='blue')
ax0.set_xlabel('Loan Applicant Count')
ax0.set_ylabel('Applica... | Data_Preprocessing/LendingClub_DataExploratory.ipynb | kayzhou22/DSBiz_Project_LendingClub | mit |
Fig 2a and Fig 2b both show the sorted applicant annual income from low to high. The former indicates extreme values, and the latter plots only those values below the 75% quantile, which looks more sensible.<br/>
Fig 2c is a histogram showing the distribution of the applicants' income (below 75% quantile).
Obeservation... | 4.600000e+04
# 3. Loan amount and Applicant Annual Income
# View all
pl.figure(figsize=(6,4))
pl.plot(df.annual_inc, df.loan_amnt, '.')
pl.ylim(0, 40000)
pl.xlim(0, 0.2e7) # df.annual_inc.max()
pl.title('Fig 3a - Loan Amount VS Applicant Annual Income_all', size=15)
pl.ylabel('Loan Amount ($)', size=15)
pl.xlabel('A... | Data_Preprocessing/LendingClub_DataExploratory.ipynb | kayzhou22/DSBiz_Project_LendingClub | mit |
Fig 3a shows the approved loan amount against the applicants' annual income. <br/>
Oberservation:<br/>
We can see that there are a few people with self-reported income that is very high, while majority of the applicants are with income less than $100,000. These extreme values indicate a possibility of outliers.
Metho... | # 3b
pl.figure(figsize=(6,4))
pl.plot(df.annual_inc, df.loan_amnt, '.')
pl.ylim(0, 40000)
pl.xlim(0, inc_75)
pl.title('Fig 3b - Loan Amount VS Applicant Annual Income_75%', size=15)
pl.ylabel('Loan Amount ($)', size=15)
pl.xlabel('Applicant Annual Income ($)', size=15) | Data_Preprocessing/LendingClub_DataExploratory.ipynb | kayzhou22/DSBiz_Project_LendingClub | mit |
Fig 3b is plot of the loan amount VS applicant annual income with all extreme income amounts being excluded.
Observation:<br/>
Now it is clearer to see that there is quite "rigid" standard to determine loan amounts based on income, however, there are still exceptions (sparse points above the "division line". | pl.plot(np.log(df.annual_inc), np.log(df.loan_amnt), '.')
# 4. Average loan amount groupby grade
mean_loan_grade = df.groupby('grade')['loan_amnt'].mean()
mean_loan_grade
sum_loan_grade = df.groupby('grade')['loan_amnt'].sum()
sum_loan_grade
fig = pl.figure(figsize=(8,12)) #16,5
ax0 = fig.add_subplot(211)
ax0.plot... | Data_Preprocessing/LendingClub_DataExploratory.ipynb | kayzhou22/DSBiz_Project_LendingClub | mit |
Initialize | folder = '../zHat/'
metric = get_metric() | MES/polAvg/calculations/exactSolutions.ipynb | CELMA-project/CELMA | lgpl-3.0 |
Define the function to take the derivative of
NOTE:
These do not need to be fulfilled in order to get convergence
z must be periodic
The field $f(\rho, \theta)$ must be of class infinity in $z=0$ and $z=2\pi$
The field $f(\rho, \theta)$ must be continuous in the $\rho$ direction with $f(\rho, \theta + \pi)$
But this ... | # We need Lx
from boututils.options import BOUTOptions
myOpts = BOUTOptions(folder)
Lx = eval(myOpts.geom['Lx'])
# Z hat function
# NOTE: The function is not continuous over origo
s = 2
c = pi
w = pi/2
the_vars['f'] = ((1/2)*(tanh(s*(z-(c-w/2)))-tanh(s*(z-(c+w/2)))))*sin(3*2*pi*x/Lx) | MES/polAvg/calculations/exactSolutions.ipynb | CELMA-project/CELMA | lgpl-3.0 |
Calculating the solution | the_vars['S'] = (integrate(the_vars['f'], (z, 0, 2*np.pi))/(2*np.pi)).evalf() | MES/polAvg/calculations/exactSolutions.ipynb | CELMA-project/CELMA | lgpl-3.0 |
DecisionTreeClassifier is capable of both binary (where the labels are [-1, 1]) classification and multiclass (where the labels are [0, …, K-1]) classification.
Applying to Iris Dataset | from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
iris.data[0:5]
iris.feature_names
X = iris.data[:, 2:]
y = iris.target
y
clf = tree.DecisionTreeClassifier(random_state=42)
clf = clf.fit(X, y)
from sklearn.tree import export_graphviz
export_graphviz(clf,
out_fi... | test05_machine_learning/Code snippets.ipynb | GitYiheng/reinforcement_learning_test | mit |
Start Here | df = sns.load_dataset('iris')
df.head()
col = ['petal_length', 'petal_width']
X = df.loc[:, col]
species_to_num = {'setosa': 0,
'versicolor': 1,
'virginica': 2}
df['tmp'] = df['species'].map(species_to_num)
y = df['tmp']
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, y)
X[0... | test05_machine_learning/Code snippets.ipynb | GitYiheng/reinforcement_learning_test | mit |
matplotlib documentation | fig = plt.figure(figsize=(16,10))
ax = plt.contourf(xx, yy, z, cmap = 'afmhot', alpha=0.3);
fig = plt.figure(figsize=(16,10))
plt.scatter(X.values[:, 0], X.values[:, 1], c=y, s=80,
alpha=0.9, edgecolors='g');
fig = plt.figure(figsize=(16,10))
ax = plt.contourf(xx, yy, z, cmap = 'afmhot', alpha=0.3);
plt.... | test05_machine_learning/Code snippets.ipynb | GitYiheng/reinforcement_learning_test | mit |
Part 2 : For three or more files
Set 1: download and unzip files, and read data.
Create a list for all files, and two dictionaries to conect to their url and file name of .csv.
Check which file exists by using os.path.exists in for and if loop, and print out results.
Only download files which don't exist by putting c... | import os
import requests
import zipfile
import pandas as pd
zipfiles = ['HCEPDB_moldata_set1.zip','HCEPDB_moldata_set2.zip','HCEPDB_moldata_set3.zip']
url = {'HCEPDB_moldata_set1.zip':'http://faculty.washington.edu/dacb/HCEPDB_moldata_set1.zip','HCEPDB_moldata_set2.zip':'http://faculty.washington.edu/dacb/HCEPDB_mold... | SEDS_Hw/seds-hw-2-procedural-python-part-1-danielfather7/SEDS-HW2.ipynb | danielfather7/teach_Python | gpl-3.0 |
Set 2: analyza data | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import math
alldata['(xi-x)^2'] = (alldata['mass'] - alldata['mass'].mean())**2
SD = math.sqrt(sum(alldata['(xi-x)^2'])/alldata.shape[0])
M = alldata['mass'].mean()
print('standard diviation of mass = ',SD,', mean of mass = ',M,"\... | SEDS_Hw/seds-hw-2-procedural-python-part-1-danielfather7/SEDS-HW2.ipynb | danielfather7/teach_Python | gpl-3.0 |
Benchmark of vectorization | pi=np.array([.3,.3,.4])
A=np.array([[.2,.3,.5],[.1,.5,.4],[.6,.1,.3]])
B=np.array([[0.1,0.5,0.4],[0.2,0.4,0.4],[0.3,0.6,0.1]])
states,sequence=HMM.sim_HMM(A,B,pi,100)
%timeit HMM.Baum_Welch(A,B,pi,sequence,1000,0,scale=True)
%timeit HMM.hmm_unoptimized.Baum_Welch(A,B,pi,sequence,1000,0,scale=True)
%timeit HMM.Baum_Wel... | Code_Report.ipynb | xiaozhouw/663 | mit |
As for the optimization, we employed vectorization to avoid the use of triple for-loops under the update section of the Baum-Welch algorithm. We used broadcasting with numpy.newaxis to implement Baum-Welch algorithm much faster. As we can see from Benchmark part in the report, under class HMM we have 2 functions for Ba... | A=np.array([[0.1,0.5,0.4],[0.3,0.5,0.2],[0.7,0.2,0.1]])
B=np.array([[0.1,0.1,0.1,0.7],[0.5,0.5,0,0],[0.7,0.1,0.1,0.1]])
pi=np.array([0.25,0.25,0.5])
A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]])
B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]])
pi_init=np.array([0.3,0.3,0.4])
... | Code_Report.ipynb | xiaozhouw/663 | mit |
From the plot we can see that the length of the chain does have an effect on the performance of Baum-Welch Algorithm and Viterbi decoding. We can see that when the chain is too long, the algorithms tend to have a bad results.
Effects of initial values in Baum-Welch Algorithm | A=np.array([[0.1,0.5,0.4],[0.3,0.5,0.2],[0.7,0.2,0.1]])
B=np.array([[0.1,0.1,0.1,0.7],[0.5,0.5,0,0],[0.7,0.1,0.1,0.1]])
pi=np.array([0.25,0.25,0.5])
############INITIAL VALUES 1###############
A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]])
B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2... | Code_Report.ipynb | xiaozhouw/663 | mit |
From this part, we can see that the choice of initial values are greatly important. Because Baum-Welch algorithm does not guarantee global maximum, a bad choice of initial values will make Baum-Welch Algorithm to be trapped in a local maximum. Moreover, our experiments show that the initial values for emission matrix $... | ############INITIAL VALUES 1###############
A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]])
B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]])
pi_init=np.array([0.3,0.3,0.4])
n_iter=[1,5,10,25,50,100,500]
acc=np.zeros([k,len(n_iter)])
k=30
for j in range(k):
states,sequence=HM... | Code_Report.ipynb | xiaozhouw/663 | mit |
In this initial condition, we can see one feature of Baum-Welch Algorithm: Baum-Welch Algorithm tends to overfit the data, which is $P(Y|\theta_{final})>P(Y|\theta_{true})$. | ############INITIAL VALUES 2###############
A_init=np.array([[0.5,0.25,0.25],[0.1,0.4,0.5],[0.25,0.1,0.65]])
B_init=np.array([[0.3,0.4,0.2,0.1],[0.1,0.5,0.2,0.2],[0.1,0.1,0.4,0.4]])
pi_init=np.array([0.5,0.2,0.3])
n_iter=[1,5,10,25,50,100,500]
acc=np.zeros([k,len(n_iter)])
k=30
for j in range(k):
states,sequence=HM... | Code_Report.ipynb | xiaozhouw/663 | mit |
In other situations, increasing the number of iterations in Baum-Welch Algorithm tends to better fit the data.
Applications | dat=pd.read_csv("data/weather-test2-1000.txt",skiprows=1,header=None)
dat.head(5)
seq=dat[1].map({"no":0,"yes":1}).tolist()
states=dat[0].map({"sunny":0,"rainy":1,"foggy":2})
initial_A=np.array([[0.7,0.2,0.1],[0.3,0.6,0.1],[0.1,0.6,0.3]])
initial_B=np.array([[0.9,0.1],[0.1,0.9],[0.4,0.6]])
initial_pi=np.array([0.4,0.4... | Code_Report.ipynb | xiaozhouw/663 | mit |
Comparative Analysis | A=np.array([[0.1,0.5,0.4],[0.3,0.5,0.2],[0.7,0.2,0.1]])
B=np.array([[0.1,0.1,0.1,0.7],[0.5,0.5,0,0],[0.7,0.1,0.1,0.1]])
pi=np.array([0.25,0.25,0.5])
A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]])
B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]])
pi_init=np.array([0.3,0.3,0.4])
s... | Code_Report.ipynb | xiaozhouw/663 | mit |
Comparing Viterbi decoding | mod=hmm.MultinomialHMM(n_components=3)
mod.startprob_=pi
mod.transmat_=A
mod.emissionprob_=B
res_1=mod.decode(np.array(sequence).reshape([100,1]))[1]
res_2=HMM.Viterbi(A,B,pi,sequence)
np.array_equal(res_1,res_2)
%timeit -n100 mod.decode(np.array(sequence).reshape([100,1]))
%timeit -n100 HMM.Viterbi(A,B,pi,sequence) | Code_Report.ipynb | xiaozhouw/663 | mit |
From the above we can see that we coded our Viterbi algorith correctly. But the time complexity is not good enought. When we check the source code of hmmlearn, we see that they used C to make things faster. In the future, we might want to use c++ to implement this algorithm and wrap it for python.
Comparing Baum-Welch ... | k=50
acc=[]
for i in range(k):
Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,
pi_init,sequence,max_iter=10,
threshold=0,scale=True)
states_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence)
acc.append(np.mean(states_hat==states))
plt.plot(acc)
k=5... | Code_Report.ipynb | xiaozhouw/663 | mit |
Lab Task 1: Create the convolutional base
The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.
As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_chan... | # TODO 1 - Write a code to configure our CNN to process inputs of CIFAR images.
| courses/machine_learning/deepdive2/image_understanding/labs/cnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.
Lab Task 2: Compile and train the model | # TODO 2 - Write a code to compile and train a model
| courses/machine_learning/deepdive2/image_understanding/labs/cnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task 3: Evaluate the model | # TODO 3 - Write a code to evaluate a model.
# Print the test accuracy.
print(test_acc) | courses/machine_learning/deepdive2/image_understanding/labs/cnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Graphical excellence and integrity
Find a data-focused visualization on one of the following websites that is a positive example of the principles that Tufte describes in The Visual Display of Quantitative Information.
Vox
Upshot
538
BuzzFeed
Upload the image for the visualization to this directory and display the im... | # Add your filename and uncomment the following line:
Image(filename='main.0 (1).png') | assignments/assignment04/TheoryAndPracticeEx01.ipynb | ajhenrikson/phys202-2015-work | mit |
Define manifactured solutions
We have that
$$S = \nabla\cdot(S_n\nabla_\perp\phi) = S_n\nabla_\perp^2\phi + \nabla S_n\cdot \nabla_\perp \phi = S_n\nabla_\perp^2\phi + \nabla_\perp S_n\cdot \nabla_\perp \phi$$
We will use the Delp2 operator for the perpendicular Laplace operator (as the y-derivatives vanishes in cylind... | # We need Lx
from boututils.options import BOUTOptions
myOpts = BOUTOptions(folder)
Lx = eval(myOpts.geom['Lx'])
# Two normal gaussians
# The gaussian
# In cartesian coordinates we would like
# f = exp(-(1/(2*w^2))*((x-x0)^2 + (y-y0)^2))
# In cylindrical coordinates, this translates to
# f = exp(-(1/(2*w^2))*(x^2 + y... | MES/divOfScalarTimesVector/2a-divSource/calculations/exactSolutions.ipynb | CELMA-project/CELMA | lgpl-3.0 |
Calculate the solution | the_vars['S'] = the_vars['S_n']*Delp2(the_vars['phi'], metric=metric)\
+ metric.g11*DDX(the_vars['S_n'], metric=metric)*DDX(the_vars['phi'], metric=metric)\
+ metric.g33*DDZ(the_vars['S_n'], metric=metric)*DDZ(the_vars['phi'], metric=metric) | MES/divOfScalarTimesVector/2a-divSource/calculations/exactSolutions.ipynb | CELMA-project/CELMA | lgpl-3.0 |
Analyzing structured data with Tensorflow Data Validation
This notebook demonstrates how TensorFlow Data Validation (TFDV) can be used to analyze and validate structured data, including generating descriptive statistics, inferring and fine tuning schema, checking for and fixing anomalies, and detecting drift and skew. ... | import os
import tempfile
import tensorflow as tf
import tensorflow_data_validation as tfdv
import time
from apache_beam.options.pipeline_options import PipelineOptions, GoogleCloudOptions, StandardOptions, SetupOptions, DebugOptions, WorkerOptions
from google.protobuf import text_format
from tensorflow_metadata.proto... | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Set the GCS locations of datasets used during the lab | TRAINING_DATASET='gs://workshop-datasets/covertype/training/dataset.csv'
TRAINING_DATASET_WITH_MISSING_VALUES='gs://workshop-datasets/covertype/training_missing/dataset.csv'
EVALUATION_DATASET='gs://workshop-datasets/covertype/evaluation/dataset.csv'
EVALUATION_DATASET_WITH_ANOMALIES='gs://workshop-datasets/covertype/e... | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Set the local path to the lab's folder. | LAB_ROOT_FOLDER='/home/mlops-labs/lab-31-tfdv-structured-data' | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Configure GCP project, region, and staging bucket | PROJECT_ID = 'mlops-workshop'
REGION = 'us-central1'
STAGING_BUCKET = 'gs://{}-staging'.format(PROJECT_ID) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Computing and visualizing descriptive statistics
TFDV can compute descriptive statistics that provide a quick overview of the data in terms of the features that are present and the shapes of their value distributions.
Internally, TFDV uses Apache Beam's data-parallel processing framework to scale the computation of sta... | train_stats = tfdv.generate_statistics_from_csv(
data_location=TRAINING_DATASET_WITH_MISSING_VALUES
) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
You can now use tfdv.visualize_statistics to create a visualization of your data. tfdv.visualize_statistics uses Facets that provides succinct, interactive visualizations to aid in understanding and analyzing machine learning datasets. | tfdv.visualize_statistics(train_stats) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
The interactive widget you see is Facets Overview.
- Numeric features and categorical features are visualized separately, including charts showing the distributions for each feature.
- Features with missing or zero values display a percentage in red as a visual indicator that there may be issues with examples in those... | schema = tfdv.infer_schema(train_stats)
tfdv.display_schema(schema=schema) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
In general, TFDV uses conservative heuristics to infer stable data properties from the statistics in order to avoid overfitting the schema to the specific dataset. It is strongly advised to review the inferred schema and refine it as needed, to capture any domain knowledge about the data that TFDV's heuristics might ha... | tfdv.get_feature(schema, 'Soil_Type').type = schema_pb2.FeatureType.BYTES
tfdv.set_domain(schema, 'Soil_Type', schema_pb2.StringDomain(name='Soil_Type', value=[]))
tfdv.set_domain(schema, 'Cover_Type', schema_pb2.IntDomain(name='Cover_Type', min=1, max=7, is_categorical=True))
tfdv.get_feature(schema, 'Slope').type =... | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Generate new statistics using the updated schema. | stats_options = tfdv.StatsOptions(schema=schema, infer_type_from_schema=True)
train_stats = tfdv.generate_statistics_from_csv(
data_location=TRAINING_DATASET_WITH_MISSING_VALUES,
stats_options=stats_options,
)
tfdv.visualize_statistics(train_stats) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Finalize the schema
The train_stats object is a instance of the statistics_pb2 class, which is a Python wrapper around the statistics.proto protbuf. You can use the protobuf Python interface to retrieve the generated statistics, including the infered domains of categorical features. | soil_type_stats = [feature for feature in train_stats.datasets[0].features if feature.path.step[0]=='Soil_Type'][0].string_stats
soil_type_domain = [bucket.label for bucket in soil_type_stats.rank_histogram.buckets]
tfdv.set_domain(schema, 'Soil_Type', schema_pb2.StringDomain(name='Soil_Type', value=soil_type_domain))... | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Creating statistics using Cloud Dataflow
Previously, you created descriptive statistics using local compute. This may work for smaller datasets. But for large datasets you may not have enough local compute power. The tfdv.generate_statistics_* functions can utilize DataflowRunner to run Beam processing on a distributed... | %%writefile setup.py
from setuptools import setup
setup(
name='tfdv',
description='TFDV Runtime.',
version='0.1',
install_requires=[
'tensorflow_data_validation==0.15.0'
]
) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Regenerate statistics
Re-generate the statistics using Dataflow and the final schema. You can monitor the job progress using Dataflow UI | options = PipelineOptions()
options.view_as(GoogleCloudOptions).project = PROJECT_ID
options.view_as(GoogleCloudOptions).region = REGION
options.view_as(GoogleCloudOptions).job_name = "tfdv-{}".format(time.strftime("%Y%m%d-%H%M%S"))
options.view_as(GoogleCloudOptions).staging_location = STAGING_BUCKET + '/staging/'
opt... | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Analyzing evaluation data
So far we've only been looking at the training data. It's important that our evaluation data is consistent with our training data, including that it uses the same schema. It's also important that the evaluation data includes examples of roughly the same ranges of values for our numerical featu... | stats_options = tfdv.StatsOptions(schema=schema, infer_type_from_schema=True)
eval_stats = tfdv.generate_statistics_from_csv(
data_location=EVALUATION_DATASET_WITH_ANOMALIES,
stats_options=stats_options
)
tfdv.visualize_statistics(lhs_statistics=eval_stats, rhs_statistics=train_stats,
... | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Checking for anomalies
Does our evaluation dataset match the schema from our training dataset? This is especially important for categorical features, where we want to identify the range of acceptable values.
What would happen if we tried to evaluate using data with categorical feature values that were not in our traini... | anomalies = tfdv.validate_statistics(statistics=eval_stats, schema=schema)
tfdv.display_anomalies(anomalies) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Fixing evaluation anomalies in the schema
It looks like we have some new values for Soil_Type and some out-of-range values for Slope in our evaluation data, that we didn't have in our training data. Whever it should be considered anomaly, depends on our domain knowledge of the data. If an anomaly truly indicates a data... | tfdv.get_domain(schema, 'Soil_Type').value.append('5151') | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Re-validate with the updated schema | updated_anomalies = tfdv.validate_statistics(eval_stats, schema)
tfdv.display_anomalies(updated_anomalies) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
The unexpected string values error in Soil_Type is gone but the out-of-range error in Slope is still there. Let's pretend you have fixed the source and re-evaluate the evaluation split without corrupted Slope. | stats_options = tfdv.StatsOptions(schema=schema, infer_type_from_schema=True)
eval_stats = tfdv.generate_statistics_from_csv(
data_location=EVALUATION_DATASET,
stats_options=stats_options
)
updated_anomalies = tfdv.validate_statistics(eval_stats, schema)
tfdv.display_anomalies(updated_anomalies)
tfdv.display_... | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Schema environments
In supervised learning we need to include labels in our dataset, but when we serve the model for inference the labels will not be included. In cases like that introducing slight schema variations is necessary.
For example, in this dataset the Cover_Type feature is included as the label for training,... | stats_options = tfdv.StatsOptions(schema=schema, infer_type_from_schema=True)
eval_stats = tfdv.generate_statistics_from_csv(
data_location=SERVING_DATASET,
stats_options=stats_options
)
serving_anomalies = tfdv.validate_statistics(eval_stats, schema)
tfdv.display_anomalies(serving_anomalies) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Environments can be used to address such scenarios. In particular, specific features in schema can be associated with specific environments. | schema.default_environment.append('TRAINING')
schema.default_environment.append('SERVING')
tfdv.get_feature(schema, 'Cover_Type').not_in_environment.append('SERVING') | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
If you validate the serving statistics against the serving environment in schema you will not get anomaly | serving_anomalies = tfdv.validate_statistics(eval_stats, schema, environment='SERVING')
tfdv.display_anomalies(serving_anomalies) | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Freezing the schema
When the schema is finalized it can be saved as a textfile and managed under source control like any other code artifact. | output_dir = os.path.join(tempfile.mkdtemp(),'covertype_schema')
tf.io.gfile.makedirs(output_dir)
schema_file = os.path.join(output_dir, 'schema.pbtxt')
tfdv.write_schema_text(schema, schema_file)
!cat {schema_file} | examples/tfdv-structured-data/tfdv-covertype.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Table of Contents
1.- Anaconda
2.- GIT
3.- IPython
4.- Jupyter Notebook
5.- Inside Ipython and Kernels
6.- Magics
<div id='anaconda' />
1.- Anaconda
Although Python is an open-source, cross-platform language, installing it with the usual scientific packages used to be overly complicated. Fortunately, there is now an ... | xgrid = np.linspace(-3,3,50)
f1 = np.exp(-xgrid**2)
f2 = np.tanh(xgrid)
plt.figure(figsize=(8,6))
plt.plot(xgrid, f1, 'bo-')
plt.plot(xgrid, f2, 'ro-')
plt.title('Just a demo plot')
plt.grid()
plt.show() | 01_intro/01_intro.ipynb | mavillan/SciProg | gpl-3.0 |
IPython also comes with a sophisticated display system that lets us insert rich web elements in the notebook. Here you can see an example of how to add Youtube videos in a notebook | from IPython.display import YouTubeVideo
YouTubeVideo('HrxX9TBj2zY') | 01_intro/01_intro.ipynb | mavillan/SciProg | gpl-3.0 |
<div id='inside' />
5.- Inside Ipython and Kernels
The IPython Kernel is a separate IPython process which is responsible for running user code, and things like computing possible completions. Frontends, like the notebook or the Qt console, communicate with the IPython Kernel using JSON messages sent over ZeroMQ sockets... | # this will list all magic commands
%lsmagic
# also work in ls, cd, mkdir, etc
%pwd
%history
# this will execute and show the output of the program
%run ./hola_mundo.py
def naive_loop():
for i in range(100):
for j in range(100):
for k in range(100):
a = 1+1
return None
%... | 01_intro/01_intro.ipynb | mavillan/SciProg | gpl-3.0 |
lets you capture the standard output and error output of some code into a Python variable.
Here is an example (the outputs are captured in the output Python variable). | %%capture output
!ls
%%writefile myfile.txt
Holanda que talca!
!cat myfile.txt
!rm myfile.txt | 01_intro/01_intro.ipynb | mavillan/SciProg | gpl-3.0 |
Writting our own magics!
In this section we will create a new cell magic that compiles and executes C++ code in the Notebook. | from IPython.core.magic import register_cell_magic | 01_intro/01_intro.ipynb | mavillan/SciProg | gpl-3.0 |
To create a new cell magic, we create a function that takes a line (containing possible options) and a cell's contents as its arguments, and we decorate it with @register_cell_magic. | @register_cell_magic
def cpp(line, cell):
"""Compile, execute C++ code, and return the
standard output."""
# We first retrieve the current IPython interpreter instance.
ip = get_ipython()
# We define the source and executable filenames.
source_filename = '_temp.cpp'
program_filename = '_temp... | 01_intro/01_intro.ipynb | mavillan/SciProg | gpl-3.0 |
This cell magic is currently only available in your interactive session. To distribute it, you need to create an IPython extension. This is a regular Python module or package that extends IPython.
To create an IPython extension, copy the definition of the cpp() function (without the decorator) to a Python module, named... | %load_ext cpp_ext | 01_intro/01_intro.ipynb | mavillan/SciProg | gpl-3.0 |
You can then use this integer model to index into an array of rock properties: | import numpy as np
vps = np.array([2320, 2350, 2350])
rhos = np.array([2650, 2600, 2620]) | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.