markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
The performance is really bad, and the cost does not really decrease, and the algorithm performs no better than random guessing. Why? Lets look at the details of the predictions and the decision boundary:
print ("predictions_train = " + str(predictions_train)) print ("predictions_test = " + str(predictions_test)) plt.title("Model with Zeros initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.set_ylim([-1.5,1.5]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb
diegocavalca/Studies
cc0-1.0
The model is predicting 0 for every example. In general, initializing all the weights to zero results in the network failing to break symmetry. This means that every neuron in each layer will learn the same thing, and you might as well be training a neural network with $n^{[l]}=1$ for every layer, and the network is n...
# GRADED FUNCTION: initialize_parameters_random def initialize_parameters_random(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": ...
deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb
diegocavalca/Studies
cc0-1.0
Expected Output: <table> <tr> <td> **W1** </td> <td> [[ 17.88628473 4.36509851 0.96497468] [-18.63492703 -2.77388203 -3.54758979]] </td> </tr> <tr> <td> **b1** </td> <td> [[ 0.] [ 0.]] </td> </tr> <tr> <td> **W2** </td> ...
parameters = model(train_X, train_Y, initialization = "random") print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters)
deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb
diegocavalca/Studies
cc0-1.0
If you see "inf" as the cost after the iteration 0, this is because of numerical roundoff; a more numerically sophisticated implementation would fix this. But this isn't worth worrying about for our purposes. Anyway, it looks like you have broken symmetry, and this gives better results. than before. The model is no lo...
print (predictions_train) print (predictions_test) plt.title("Model with large random initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.set_ylim([-1.5,1.5]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb
diegocavalca/Studies
cc0-1.0
Observations: - The cost starts very high. This is because with large random-valued weights, the last activation (sigmoid) outputs results that are very close to 0 or 1 for some examples, and when it gets that example wrong it incurs a very high loss for that example. Indeed, when $\log(a^{[3]}) = \log(0)$, the loss go...
# GRADED FUNCTION: initialize_parameters_he def initialize_parameters_he(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- ...
deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb
diegocavalca/Studies
cc0-1.0
Expected Output: <table> <tr> <td> **W1** </td> <td> [[ 1.78862847 0.43650985] [ 0.09649747 -1.8634927 ] [-0.2773882 -0.35475898] [-0.08274148 -0.62700068]] </td> </tr> <tr> <td> **b1** </td> <td> [[ 0.] [ 0.] [ 0.] [ 0.]] </td> </tr> ...
parameters = model(train_X, train_Y, initialization = "he") print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters) plt.title("Model with He initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.s...
deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb
diegocavalca/Studies
cc0-1.0
Load the component using KFP SDK
import kfp.components as comp dataproc_submit_sparksql_job_op = comp.load_component_from_url( 'https://raw.githubusercontent.com/kubeflow/pipelines/01a23ae8672d3b18e88adf3036071496aca3552d/components/gcp/dataproc/submit_sparksql_job/component.yaml') help(dataproc_submit_sparksql_job_op)
components/gcp/dataproc/submit_sparksql_job/sample.ipynb
kubeflow/kfp-tekton-backend
apache-2.0
Sample Note: The following sample code works in an IPython notebook or directly in Python code. See the sample code below to learn how to execute the template. Setup a Dataproc cluster Create a new Dataproc cluster (or reuse an existing one) before running the sample code. Prepare a SparkSQL job Either put your SparkSQ...
PROJECT_ID = '<Please put your project ID here>' CLUSTER_NAME = '<Please put your existing cluster name here>' REGION = 'us-central1' QUERY = ''' DROP TABLE IF EXISTS natality_csv; CREATE EXTERNAL TABLE natality_csv ( source_year BIGINT, year BIGINT, month BIGINT, day BIGINT, wday BIGINT, state STRING, is_male BOOL...
components/gcp/dataproc/submit_sparksql_job/sample.ipynb
kubeflow/kfp-tekton-backend
apache-2.0
Example pipeline that uses the component
import kfp.dsl as dsl import json @dsl.pipeline( name='Dataproc submit SparkSQL job pipeline', description='Dataproc submit SparkSQL job pipeline' ) def dataproc_submit_sparksql_job_pipeline( project_id = PROJECT_ID, region = REGION, cluster_name = CLUSTER_NAME, queries = json.dumps([QUERY]), ...
components/gcp/dataproc/submit_sparksql_job/sample.ipynb
kubeflow/kfp-tekton-backend
apache-2.0
Compile the pipeline
pipeline_func = dataproc_submit_sparksql_job_pipeline pipeline_filename = pipeline_func.__name__ + '.zip' import kfp.compiler as compiler compiler.Compiler().compile(pipeline_func, pipeline_filename)
components/gcp/dataproc/submit_sparksql_job/sample.ipynb
kubeflow/kfp-tekton-backend
apache-2.0
Machine learning on the iris dataset Framed as a supervised learning problem: Predict the species of an iris using the measurements Famous dataset for machine learning because prediction is easy Learn more about the iris dataset: UCI Machine Learning Repository Loading the iris dataset into scikit-learn
# import load_iris function from datasets module from sklearn.datasets import load_iris # save "bunch" object containing iris dataset and its attributes iris = load_iris() type(iris) # print the iris data print(iris.data)
03-example_iris.ipynb
dmolina/es_intro_python
gpl-3.0
Machine learning terminology Each row is an observation (also known as: sample, example, instance, record) Each column is a feature (also known as: predictor, attribute, independent variable, input, regressor, covariate)
# print the names of the four features print(iris.feature_names) # print integers representing the species of each observation print(iris.target) # print the encoding scheme for species: 0 = setosa, 1 = versicolor, 2 = virginica print(iris.target_names)
03-example_iris.ipynb
dmolina/es_intro_python
gpl-3.0
Each value we are predicting is the response (also known as: target, outcome, label, dependent variable) Classification is supervised learning in which the response is categorical Regression is supervised learning in which the response is ordered and continuous Requirements for working with data in scikit-learn Featu...
# check the types of the features and response print(type(iris.data)) print(type(iris.target)) # check the shape of the features (first dimension = number of observations, second dimensions = number of features) print(iris.data.shape) # check the shape of the response (single dimension matching the number of observat...
03-example_iris.ipynb
dmolina/es_intro_python
gpl-3.0
Data Set Information This radar data was collected by a system in Goose Bay, Labrador. This system consists of a phased array of 16 high-frequency antennas with a total transmitted power on the order of 6.4 kilowatts. See the paper for more details. The targets were free electrons in the ionosphere. "Good" radar return...
# data = np.genfromtxt("data/ionosphere.data") data = pd.read_csv('data/ionosphere.data', sep=",", header=None) data.head() data.describe()
IONOSPHERE_Autoencoder.ipynb
philippgrafendorfe/stackedautoencoders
mit
This is a very small dataset.
df_tab = data df_tab[34] = df_tab[34].astype('category') tab = pd.crosstab(index=df_tab[34], columns="frequency") tab.index.name = 'Class/Direction' tab/tab.sum() data.drop(data.columns[1], inplace=True, axis=1) data[34] = [1 if e is "g" else 0 for e in data[34]] # sample the dataframe data_train = data.sample(frac=0...
IONOSPHERE_Autoencoder.ipynb
philippgrafendorfe/stackedautoencoders
mit
About 63% of all observations are good. preprocessing
x_train = np.array(df_x_train.as_matrix()) y_train = np.array(pd.DataFrame(df_y_train).as_matrix()) x_val = np.array(df_x_valid.as_matrix()) y_val = np.array(pd.DataFrame(df_y_valid).as_matrix()) y_eval = y_val y_train = keras.utils.to_categorical(y_train, 2) y_val = keras.utils.to_categorical(y_val, 2)
IONOSPHERE_Autoencoder.ipynb
philippgrafendorfe/stackedautoencoders
mit
Set Global Parameters
epochsize = 60 batchsize = 4 shuffle = False dropout = 0.1 num_classes = 2 input_dim = x_train.shape[1] hidden1_dim = 40 hidden2_dim = 40 # weights = keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=42)
IONOSPHERE_Autoencoder.ipynb
philippgrafendorfe/stackedautoencoders
mit
Train Classifier The goal is to get a very accurate classifier.
input_data = Input(shape=(input_dim,), dtype='float32', name='main_input') hidden_layer1 = Dense(hidden1_dim , activation='relu' , input_shape=(input_dim,) # , kernel_initializer=weights )(input_data) dropout1 = Dropout(dropout)(hidd...
IONOSPHERE_Autoencoder.ipynb
philippgrafendorfe/stackedautoencoders
mit
Whats the best dimensionality reduction with single autoencoder?
# the initial coding dimension s.t. there is no dim reduction at the beginning encoding_dim = input_dim result = {'encoding_dim': [], 'auto_classifier_acc': []} while encoding_dim > 0: main_input = Input(shape=(input_dim,), dtype='float32', name='main_input') encoding_layer = Dense(encoding_dim ...
IONOSPHERE_Autoencoder.ipynb
philippgrafendorfe/stackedautoencoders
mit
The result is implausible. This might be due to a very small number ob observations.
result_df.to_csv('results/ionosphere_results.csv')
IONOSPHERE_Autoencoder.ipynb
philippgrafendorfe/stackedautoencoders
mit
Provide one or two visualizations that show the distribution of the sample data. Write one or two sentences noting what you observe about the plot or plots.
df.hist()
P01/Project1_Statistics_The_Science_of_Decisions_Project_Instructions.ipynb
luiscruz/udacity_data_analyst
mit
R: This histograms show that, in this sample, times are longer in the incrongruent experiment than in the congruent experiment. In the congruent experiment, the interval with more values is aproximately between 14 and 16 values. In the incronguent experiment the interval with more values is aproximately (20,22). No...
import math df['differences'] = df['Incongruent']-df['Congruent'] N =df['differences'].count() print "Sample size:\t\t%d"% N print "DoF:\t\t\t%d"%(df['differences'].count()-1) mean = df['differences'].mean() std = df['differences'].std() tscore = mean/(std/math.sqrt(N)) print "Differences Mean:\t%.3f" % mean print "Dif...
P01/Project1_Statistics_The_Science_of_Decisions_Project_Instructions.ipynb
luiscruz/udacity_data_analyst
mit
We'll use a semi-detached system so that we can see some interesting cases of distribution propagation from orbital parameters to the equivalent radius of the star filling its roche lobe.
b = phoebe.default_binary(semidetached='primary')
2.3/tutorials/distribution_propagation.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Here we'll add some distributions directly to parameters... but the concepts below apply just as well to distributions extracted from posteriors.
b.add_distribution({'sma@binary': phoebe.gaussian_around(1), 'incl@binary': phoebe.uniform(85, 90), 'q@binary': phoebe.gaussian_around(0.05)}, distribution='mydist')
2.3/tutorials/distribution_propagation.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Plotting Distributions By calling plot_distribution_collection, we can see a corner plot of all of these parameters. Since we created these as univariate distributions (see Advanced: Distribution Types for multivariate examples), we can see that there are no correlations between the distributions. By default, this sho...
_ = b.plot_distribution_collection(distribution='mydist', show=True)
2.3/tutorials/distribution_propagation.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
We can pass a list of parameters (as twigs) to the parameters keyword argument to only plot a subset of the available parameters.
_ = b.plot_distribution_collection(distribution='mydist', parameters=['sma@binary', 'q@binary'], show=True)
2.3/tutorials/distribution_propagation.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
But we can also use parameters to propagate the distributions through the constraints linking parameters together. For example, since we have distributions on sma and incl, including asini should combine the two distributions according to the constraint and showing the resulting correlations.
_ = b.plot_distribution_collection(distribution='mydist', parameters=['sma@binary', 'q@binary', 'asini@binary'], show=True)
2.3/tutorials/distribution_propagation.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Accessing Uncertainties from Distributions Similarly, we can access the resulting uncertainties (taken from the 1-sigma percentiles by default), by calling uncertainties_from_distribution_collection. Note that the input gaussian distributions are automatically exposed with symmetric uncertainties, whereas the propagate...
b.uncertainties_from_distribution_collection(distribution='mydist', parameters=['sma@binary', 'q@binary', 'asini@binary'], tex=True)
2.3/tutorials/distribution_propagation.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
To expose at a different "sigma-level", we can pass sigma.
b.uncertainties_from_distribution_collection(distribution='mydist', parameters=['sma@binary', 'q@binary', 'asini@binary'], sigma=3, tex=True)
2.3/tutorials/distribution_propagation.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
And to expose a machine-readable list with lower, centeral, and upper bounds represented, we just exclude the tex=True.
b.uncertainties_from_distribution_collection(distribution='mydist', parameters=['sma@binary', 'q@binary', 'asini@binary'], sigma=3)
2.3/tutorials/distribution_propagation.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Build the model
model = keras.Sequential( [ keras.Input(shape=(784,)), RandomFourierFeatures( output_dim=4096, scale=10.0, kernel_initializer="gaussian" ), layers.Dense(units=10), ] ) model.compile( optimizer=keras.optimizers.Adam(learning_rate=1e-3), loss=keras.losses.hinge...
examples/keras_recipes/ipynb/quasi_svm.ipynb
keras-team/keras-io
apache-2.0
Prepare the data
# Load MNIST (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # Preprocess the data by flattening & scaling it x_train = x_train.reshape(-1, 784).astype("float32") / 255 x_test = x_test.reshape(-1, 784).astype("float32") / 255 # Categorical (one hot) encoding of the labels y_train = keras.util...
examples/keras_recipes/ipynb/quasi_svm.ipynb
keras-team/keras-io
apache-2.0
Train the model
model.fit(x_train, y_train, epochs=20, batch_size=128, validation_split=0.2)
examples/keras_recipes/ipynb/quasi_svm.ipynb
keras-team/keras-io
apache-2.0
Loading data We begin by loading two tables. For the purpose of this tutorial, we use the books dataset that comes with the package.
table_A_path = os.sep.join([ssj.get_install_path(), 'datasets', 'data', 'books_A.csv.gz']) table_B_path = os.sep.join([ssj.get_install_path(), 'datasets', 'data', 'books_B.csv.gz']) # Load csv files as dataframes. Since we are reading a compressed csv file, we provide the compression argument. # If you are reading an ...
notebooks/jaccard_books.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Profiling data In order to perform the join, you need to identify on which attribute to perform the join. Using the profiling command, you can inspect which attributes are suitable for join. For example, if an attribute contains many missing values, you may not want to perform join on that attribute.
# profile attributes in table A ssj.profile_table_for_join(A) # profile attributes in table B ssj.profile_table_for_join(B)
notebooks/jaccard_books.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Based on the profile output, we find that the 'Title' attribute in both tables does not contain any missing values. Hence, for the purpose of this tutorial, we will now join tables A and B on 'Title' attribute using jaccard measure. Next, we need to decide on what threshold to use for the join. For this tutorial, w...
# create whitespace tokenizer for tokenizing 'Title' attribute. The return_set flag should be set to True since # jaccard is a set based measure. ws = sm.WhitespaceTokenizer(return_set=True)
notebooks/jaccard_books.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Performing join Next, you need to perform the join using the following command:
# find all pairs from A and B such that the jaccard score on 'Title' is at least 0.5. Setting n_jobs=-1 exploits all # CPU cores available. output_pairs = ssj.jaccard_join(A, B, 'ID', 'ID', 'Title', 'Title', ws, 0.5, l_out_attrs=['Title'], r_out_attrs=['Title'], n_jobs=-1) len(output_p...
notebooks/jaccard_books.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Combine constructiveness and toxicity annotations from different batches
dfs = [] for batch in batches: filename = aggregated_data_path + 'batch' + str(batch) + '_constructiveness_and_toxicity_combined.csv' dfs.append(pd.read_csv(filename)) combined_annotations_df = pd.concat(dfs) # Sort the merged dataframe on constructiveness and toxicity combined_annotations_df.shape # Relevan...
constructiveness_toxicity_crowdsource/jupyter-notebooks/annotation_aggregation/combine_annotated_batches.ipynb
conversationai/conversationai-crowdsource
apache-2.0
Write contructiveness and toxicity combined CSV
output_dir = '../../CF_output/annotated_data/' combined_annotations_df.to_csv( output_dir + 'constructiveness_and_toxicity_annotations.csv', columns = cols, index = False)
constructiveness_toxicity_crowdsource/jupyter-notebooks/annotation_aggregation/combine_annotated_batches.ipynb
conversationai/conversationai-crowdsource
apache-2.0
The logarithmic derivative $D_n$. This routine uses a continued fraction method to compute $D_n(z)$ proposed by Lentz. Lentz uses the notation $A_n$ instead of $D_n$, but I prefer the notation used by Bohren and Huffman. This method eliminates many weaknesses in previous algorithms using forward recursion. The logari...
m = 1 x = 1 nstop = 10 dn = np.zeros(nstop, dtype=np.complex128) print("both techniques work up to 5") n=5 print(" Lentz",n,miepython._Lentz_Dn(m*x,n).real) miepython._D_downwards(m*x,nstop, dn) print("downwards",n, dn[n].real) miepython._D_upwards(m*x,nstop, dn) print(" upwards",n, dn[n].real) print("but upward...
docs/07_algorithm.ipynb
scottprahl/miepython
mit
Calculating $A_n$ and $B_n$ OK, Here we go. We need to start up the arrays. First, recall (page 128 Bohren and Huffman) that $$ \psi_n(x) = x j_n(x)\qquad\hbox{and}\qquad \xi_n(x) = x j_n(x) + i x y_n(x) $$ where $j_n$ and $y_n$ are spherical Bessel functions. The first few terms may be worked out as, $$ \psi_0(x) ...
m=4/3 x=50 print("m=4/3 test, m=",m, " x=",x) a, b = miepython._mie_An_Bn(m,x) print("a_1=", a[0]) print("a_1= (0.531105889295-0.499031485631j) #test") print("b_1=", b[0]) print("b_1= (0.791924475935-0.405931152229j) #test") print() m=3/2-1j x=2 print("upward recurrence test, m=",m, " x=",x) a, b = miepython._mie_An...
docs/07_algorithm.ipynb
scottprahl/miepython
mit
Small Spheres This calculates everything accurately for small spheres. This approximation is necessary because in the small particle or Rayleigh limit $x\rightarrow0$ the Mie formulas become ill-conditioned. The method was taken from Wiscombe's paper and has been tested for several complex indices of refraction. ...
m=1.5-0.1j x=0.0665 print("abs(m*x)=",abs(m*x)) qext, qsca, qback, g = miepython._small_mie(m,x) print("Qext=",qext) print("Qsca=",qsca) print("Qabs=",qext-qsca) print("Qback=",qback) print("g=",g) print() print('The following should be nearly the same as those above:') print() x=0.067 print("abs(m*x)=",abs(m*x)) qex...
docs/07_algorithm.ipynb
scottprahl/miepython
mit
Small Perfectly Reflecting Spheres The above equations fail when m.real=0 so use these approximations when the sphere is small and refective
m = 0 - 0.01j x=0.099 qext, qsca, qback, g = miepython._small_conducting_mie(m,x) print("Qext =",qext) print("Qsca =",qsca) print("Qabs =",qext-qsca) print("Qback=",qback) print("g =",g) print() print('The following should be nearly the same as those above:') print() m = 0 - 0.01j x=0.1001 qext, qsca, qback2, g =...
docs/07_algorithm.ipynb
scottprahl/miepython
mit
Mie scattering calculations From page 120 of Bohren and Huffman the anisotropy is given by $$ Q_{\rm sca}\langle \cos\theta\rangle = \frac{4}{x^2} \left[ \sum_{n=1}^{\infty} \frac{n(n+2)}{n+1} \mbox{Re}\lbrace a_na_{n+1}^+b_nb_{n+1}^\rbrace + \sum_{n=1}^{\infty} \frac{2n+1}{n(n+1)} \mbox{Re}\lbrace a_nb_n^*\rbrace\righ...
qext, qsca, qback, g = miepython.mie(1.55-0.0j,2*np.pi/0.6328*0.525) print("Qext=",qext) print("Qsca=",qsca) print("Qabs=",qext-qsca) print("Qback=",qback) print("g=",g) x=1000.0 m=1.5-0.1j qext, qsca, qback, g = miepython.mie(m,x) print("Qext=",qext) print("Qsca=",qsca) print("Qabs=",qext-qsca) print("Qback=",qback) ...
docs/07_algorithm.ipynb
scottprahl/miepython
mit
Scattering Matrix The scattering matrix is given by Equation 4.74 in Bohren and Huffman. Namely, $$ S_1(\cos\theta) = \sum_{n=1}^\infty \frac{2n+1}{n(n+1)} \left[ a_n \pi_n(\cos\theta)+b_n\tau_n(\cos\theta)\right] $$ and $$ S_2(\cos\theta) = \sum_{n=1}^\infty \frac{2n+1}{n(n+1)} \left[a_n \tau_n(\cos\theta)+b_n\pi_n(\...
m=1.55-0.1j x=5.213 mu = np.array([0.0,0.5,1.0]) S1,S2 = miepython.mie_S1_S2(m,x,mu) for i in range(len(mu)): print(mu[i], S2[i].real, S2[i].imag)
docs/07_algorithm.ipynb
scottprahl/miepython
mit
Test to match Bohren's Sample Calculation
# Test to match Bohren's Sample Calculation theta = np.arange(0,181,9) mu=np.cos(theta*np.pi/180) S1,S2 = miepython.mie_S1_S2(1.55,5.213,mu) qext, qsca, qback, g = miepython.mie(m,x) norm = np.sqrt(qext * x**2 * np.pi) S1 /= norm S2 /= norm S11 = (abs(S2)**2 + abs(S1)**2)/2 S12 = (abs(S2)**2 - abs(S1)**2)/2 S33 = (S2 ...
docs/07_algorithm.ipynb
scottprahl/miepython
mit
Using a manufactured solution that satisfies the boundary conditions we can create just about any corresponding right hand side $f(x)$
import sympy x = sympy.symbols('x') ue = (1-x**2)*(sympy.cos(4*x)*sympy.sin(6*x)) fe = ue.diff(x, 2)
binder/Poisson1D.ipynb
spectralDNS/shenfun
bsd-2-clause
Note that fe is the right hand side that corresponds to the exact solution ue. We now want to use fe to compute a numerical solution $u$ that can be compared directly with the given ue. First, to compute the inner product $(f, v)$, we need to evaluate fe on the quadrature mesh
fl = sympy.lambdify(x, fe, 'numpy') ul = sympy.lambdify(x, ue, 'numpy') fj = Array(V, buffer=fl(V.mesh()))
binder/Poisson1D.ipynb
spectralDNS/shenfun
bsd-2-clause
fj holds the analytical fe on the nodes of the quadrature mesh. Assemble right hand side $\tilde{\textbf{f}} = -(f, v)_w$ using the shenfun function inner
f_tilde = inner(-fj, v)
binder/Poisson1D.ipynb
spectralDNS/shenfun
bsd-2-clause
All that remains is to solve the linear algebra system $$ \begin{align} A \hat{\textbf{u}} &= \tilde{\textbf{f}} \ \hat{\textbf{u}} &= A^{-1} \tilde{\textbf{f}} \end{align} $$
u_hat = Function(V) u_hat = A/f_tilde
binder/Poisson1D.ipynb
spectralDNS/shenfun
bsd-2-clause
Get solution in real space, i.e., evaluate $u(x_i) = \sum_{j=0}^{N-3} \hat{u}j \phi_j(x_i)$ for all quadrature points ${x_i}{i=0}^{N-1}$.
uj = u_hat.backward() X = V.mesh() plt.plot(X, uj)
binder/Poisson1D.ipynb
spectralDNS/shenfun
bsd-2-clause
Lorenz system The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic behavior, such as bifurcations, attractors, and sensitive dependence on initial conditions. The differential equations read: $$ \frac{dx}{dt} = \sigma(y-x) $$ $$ \frac{dy}{dt} = x(\rho-z) ...
def lorentz_derivs(yvec, t, sigma, rho, beta): """Compute the the derivatives for the Lorentz system at yvec(t).""" x= yvec[0] y= yvec[1] z= yvec[2] dx= sigma*(y-x) dy= x*(rho-z)-y dz= x*y -beta*z return np.array([dx,dy,dz]) assert np.allclose(lorentz_derivs((1,1,1),0, 1.0, 1.0, 2.0),[0...
assignments/assignment10/ODEsEx02.ipynb
JackDi/phys202-2015-work
mit
Write a function solve_lorenz that solves the Lorenz system above for a particular initial condition $[x(0),y(0),z(0)]$. Your function should return a tuple of the solution array and time array.
def solve_lorentz(ic, max_time=4.0, sigma=10.0, rho=28.0, beta=8.0/3.0): """Solve the Lorenz system for a single initial condition. Parameters ---------- ic : array, list, tuple Initial conditions [x,y,z]. max_time: float The max time to use. Integrate with 250 points per time u...
assignments/assignment10/ODEsEx02.ipynb
JackDi/phys202-2015-work
mit
Write a function plot_lorentz that: Solves the Lorenz system for N different initial conditions. To generate your initial conditions, draw uniform random samples for x, y and z in the range $[-15,15]$. Call np.random.seed(1) a single time at the top of your function to use the same seed each time. Plot $[x(t),z(t)]$ u...
N = 5 colors = plt.cm.hot(np.linspace(0,1,N)) for i in range(N): # To use these colors with plt.plot, pass them as the color argument print(colors[i]) def plot_lorentz(N=10, max_time=4.0, sigma=10.0, rho=28.0, beta=8.0/3.0): """Plot [x(t),z(t)] for the Lorenz system. Parameters ---------- ...
assignments/assignment10/ODEsEx02.ipynb
JackDi/phys202-2015-work
mit
Use interact to explore your plot_lorenz function with: max_time an integer slider over the interval $[1,10]$. N an integer slider over the interval $[1,50]$. sigma a float slider over the interval $[0.0,50.0]$. rho a float slider over the interval $[0.0,50.0]$. beta fixed at a value of $8/3$.
# YOUR CODE HERE interact(plot_lorentz, N=(1,50,1), max_time=(1,10), sigma=(0,50,.1), rho=(0,50,0.1),beta=fixed(8.0/3.0))
assignments/assignment10/ODEsEx02.ipynb
JackDi/phys202-2015-work
mit
Now let's run a simulation for 20 years (in default units where $G=1$, and thus AU, yr/2$\pi$, and $M_\odot$, see Units.ipynb for how to change units), and set up a 50 AU sphere beyond which we remove particles from the simulation. We can do this by setting the exit_max_distance flag of the simulation object. If a pa...
sim = setupSimulation() # Resets everything sim.exit_max_distance = 50. Noutputs = 1000 times = np.linspace(0,20.*2.*np.pi,Noutputs) xvenus, yvenus = np.zeros(Noutputs), np.zeros(Noutputs) for i,time in enumerate(times): try: sim.integrate(time) except rebound.Escape as error: print(error) ...
ipython_examples/EscapingParticles.ipynb
eford/rebound
gpl-3.0
So this worked as expected. Now let's plot what we got:
%matplotlib inline import matplotlib.pyplot as plt fig,ax = plt.subplots(figsize=(15,5)) ax.plot(xvenus, yvenus) ax.set_aspect('equal') ax.set_xlim([-2,10]);
ipython_examples/EscapingParticles.ipynb
eford/rebound
gpl-3.0
This doesn't look right. The problem here is that when we removed particles[1] from the simulation, all the particles got shifted down in the particles array. So following the removal, xvenus all of a sudden started getting populated by the values for Earth (the new sim.particles[2]). A more robust way to access par...
sim = setupSimulation() # Resets everything sim.exit_max_distance = 50. Noutputs = 1000 times = np.linspace(0,20.*2.*np.pi,Noutputs) xvenus, yvenus = np.zeros(Noutputs), np.zeros(Noutputs) for i,time in enumerate(times): try: sim.integrate(time) except rebound.Escape as error: print(error) ...
ipython_examples/EscapingParticles.ipynb
eford/rebound
gpl-3.0
Sample from the Gaussian Process by use of the Cholesky decomposition of the Kernel matrix
n_sample = 50000 u = np.random.randn(N, n_sample) X = L.dot(u) _ = plt.plot(X[:, np.random.permutation(n_sample)[:500]], c='k', alpha=0.05) _ = plt.plot(X.mean(axis=1), c='k', linewidth=2) _ = plt.plot(2*X.std(axis=1), c='r', linewidth=2) _ = plt.plot(-2*X.std(axis=1), c='r', linewidth=2)
scripts/gp_first_principles_01.ipynb
mattmcd/PyBayes
apache-2.0
Sample from the posterior given points at (0.1, 0.0), (0.5, 1.0)
_ = plt.plot(x, X[:, (np.abs(X[np.where(x == 0.1)[0][0], :] - 0.0) < 0.05) & (np.abs(X[np.where(x == 0.5)[0][0], :] -1) < 0.05)], c='k', alpha=0.25)
scripts/gp_first_principles_01.ipynb
mattmcd/PyBayes
apache-2.0
A classification algorithm may be used to draw a dividing boundary between the two clusters of points:
from sklearn.linear_model import SGDClassifier clf = SGDClassifier(loss="hinge", alpha=0.01, n_iter=200, fit_intercept=True) clf.fit(X, Y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_mi...
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
This may seem like a trivial task, but it is a simple version of a very important concept. By drawing this separating line, we have learned a model which can generalize to new data: if you were to drop another point onto the plane which is unlabeled, this algorithm could now predict whether it's a blue or a red point. ...
a = 0.5 b = 1.0 # x from 0 to 10 x = 30 * np.random.random(20) # y = a*x + b with noise y = a * x + b + np.random.normal(size=x.shape) plt.scatter(x, y) from sklearn.linear_model import LinearRegression clf = LinearRegression() clf.fit(x[:, None], y) # underscore at the end indicates a fit parameter print(clf.coef...
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
Again, this is an example of fitting a model to data, such that the model can make generalizations about new data. The model has been learned from the training data, and can be used to predict the result of test data: here, we might be given an x-value, and the model would allow us to predict the y value. Again, this...
from IPython.core.display import Image, display display(Image(url='images/iris_setosa.jpg')) print("Iris Setosa\n") display(Image(url='images/iris_versicolor.jpg')) print("Iris Versicolor\n") display(Image(url='images/iris_virginica.jpg')) print("Iris Virginica") display(Image(url='images/iris_with_length.png')) pr...
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
Quick Question: If we want to design an algorithm to recognize iris species, what might the data be? Remember: we need a 2D array of size [n_samples x n_features]. What would the n_samples refer to? What might the n_features refer to? Remember that there must be a fixed number of features for each sample, and fea...
from sklearn.datasets import load_iris iris = load_iris() iris.keys() n_samples, n_features = iris.data.shape print((n_samples, n_features)) print(iris.data[0]) print(iris.data.shape) print(iris.target.shape) print(iris.target) print(iris.target_names)
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
Dimensionality Reduction: PCA Principal Component Analysis (PCA) is a dimension reduction technique that can find the combinations of variables that explain the most variance. Consider the iris dataset. It cannot be visualized in a single 2D plot, as it has 4 features. We are going to extract 2 combinations of sepal an...
X, y = iris.data, iris.target from sklearn.decomposition import PCA pca = PCA(n_components=3) pca.fit(X) X_reduced = pca.transform(X) plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y) X, y = iris.data, iris.target from sklearn.manifold import Isomap pca = Isomap(n_components=3) pca.fit(X) X_reduced2 = pca.transform(X...
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
Clustering: K-means Clustering groups together observations that are homogeneous with respect to a given criterion, finding ''clusters'' in the data. Note that these clusters will uncover relevent hidden structure of the data only if the criterion used highlights it.
from sklearn.cluster import KMeans k_means = KMeans(n_clusters=3, random_state=0) # Fixing the RNG in kmeans k_means.fit(X) y_pred = k_means.predict(X) plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y_pred);
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
Lets then evaluate the performance of the clustering versus the ground truth
from sklearn.metrics import confusion_matrix # Compute confusion matrix cm = confusion_matrix(y, y_pred) np.set_printoptions(precision=2) print(cm) def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar()...
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
Classification Logistic Regression
from sklearn.linear_model import LogisticRegression from sklearn import cross_validation errors = [] for i in range(1000): X_train, X_test, y_train, y_test = cross_validation.train_test_split(iris.data, iris.target, test_size=0.4, random_state=i) clf = LogisticRegression() clf.fit(X_train, y_train) y...
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
Recap: Scikit-learn's estimator interface Scikit-learn strives to have a uniform interface across all methods, and we'll see examples of these below. Given a scikit-learn estimator object named model, the following methods are available: Available in all Estimators model.fit() : fit training data. For supervised learn...
from IPython.display import Image Image(url="http://scikit-learn.org/dev/_static/ml_map.png")
notebooks/01-IntroMachineLearning.ipynb
albahnsen/ML_SecurityInformatics
mit
Set this to the path of your GMAT installation:
GMAT_PATH = '/home/daniel/GMAT/R2018a/' import numpy as np import matplotlib.pyplot as plt import subprocess # Larger figure size fig_size = [10, 6] plt.rcParams['figure.figsize'] = fig_size
dslwp/DSLWP-B Doppler analysis.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Below we set the published frequency of the S-band beacon of DSLWP-B. There is an offset in the Doppler measurements by VE7TIL that we must correct. Probably, this Doppler is due to the beacon not been perfectly in frequency.
freq = 2275222e3 c = 299792458 # speed of light f_shift = -3400 # Shift to apply to VE7TIL Doppler measurement
dslwp/DSLWP-B Doppler analysis.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Utility functions to load reports from GMAT and write Doppler information in the format expected by GMAT.
def load_report(path): ncols = 14 data = np.fromfile(path, sep=' ') return data.reshape((data.size // ncols, ncols)) def load_ve7til_doppler(path): ncols = 4 leap_seconds = 37 # for UTC to TAI conversion data = np.fromfile(path, sep=' ') data = data.reshape((data.size // ncols, ncols))[:,:2...
dslwp/DSLWP-B Doppler analysis.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Position of each field in the GMAT report.
utc = 0 tai = 1 dslwp_x = 2 dslwp_v = 5 luna_x = 8 luna_v = 11
dslwp/DSLWP-B Doppler analysis.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Load report file as computed by GMAT (note that the GMAT script dslwp_doppler.script must have been run before this in simulation mode to generate Doppler data). The report contains the position and velocity of DSLWP-B and the Moon in VE7TIL's frame of reference. This can be used to compute Doppler, disregarding the fi...
report = load_report('VE7TIL.txt') report_old = load_report('VE7TIL_old.txt') report_gs = load_report('GS.txt')
dslwp/DSLWP-B Doppler analysis.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Load Doppler data by VE7TIL, select some points to exclude because they do not give a good match, and write the Doppler information in GMAT's format.
doppler = load_ve7til_doppler('ve7til_doppler/dslwpb_lunarday1.dat') ground_lock = ((doppler[:,0] > 28285.543) & (doppler[:,0] < 28286)) | ((doppler[:,0] > 28286.5417) & (doppler[:,0] < 28286.585)) | ((doppler[:,0] > 28282.4175) & (doppler[:,0] < 28283)) | ((doppler[:,0] > 28283.4165) & (doppler[:,0] < 28284)) | ((dopp...
dslwp/DSLWP-B Doppler analysis.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Load simulated RangeRate information from GMAT (note that the GMAT script dslwp_doppler.script must have been run before this in estimation mode). Compute Doppler using the data from GMAT report.
gmat_doppler = load_rangerate(GMAT_PATH + 'output/DSLWP_Doppler.gmd') #gs_gmat_doppler = load_twoway(GMAT_PATH + 'output/TwoWay_Doppler.gmd') def rangerate(rep): return np.sum(rep[:,dslwp_v:dslwp_v+3] * rep[:,dslwp_x:dslwp_x+3], axis=1) / np.sqrt(np.sum(rep[:,dslwp_x:dslwp_x+3]**2, axis=1)) dslwp_rangerate = rang...
dslwp/DSLWP-B Doppler analysis.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Plot Doppler simulation from GMAT and VE7TIL's measurements.
start = 0 end = 28293 select = (doppler[:,0] > start) & (doppler[:,0] < end) report_select = (report[:,tai] > start) & (report[:,tai] < end) report_old_select = (report_old[:,tai] > start) & (report_old[:,tai] < end) plt.figure(figsize = [15,10], facecolor='w') plt.plot(report_old[report_old_select, tai], -old_rangerat...
dslwp/DSLWP-B Doppler analysis.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Load and prepare the data A critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon!
data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head(50)
first-neural-network/Your_first_neural_network.ipynb
dewitt-li/deep-learning
mit
Checking out the data This dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the cnt column. You can see the first few rows of the data above. Below is a plot showing the number of bike riders ove...
rides[:24*100].plot(x='dteday', y='cnt')
first-neural-network/Your_first_neural_network.ipynb
dewitt-li/deep-learning
mit
Scaling target variables To make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1. The scaling factors are saved so we can go backwards when we use the network for predictions.
quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed'] # Store scalings in a dictionary so we can convert back later scaled_features = {} for each in quant_features: mean, std = data[each].mean(), data[each].std() scaled_features[each] = [mean, std] data.loc[:, each] = (data[each] - me...
first-neural-network/Your_first_neural_network.ipynb
dewitt-li/deep-learning
mit
Time to build the network Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes. <img src="assets/neural_network.p...
class NeuralNetwork(object): def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # Set number of nodes in input, hidden and output layers. self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nodes # Initialize we...
first-neural-network/Your_first_neural_network.ipynb
dewitt-li/deep-learning
mit
Training the network Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se...
import sys ### Set the hyperparameters here ### iterations = 2000 learning_rate = 0.08 hidden_nodes = 60 output_nodes = 1 N_i = train_features.shape[1] network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate) losses = {'train':[], 'validation':[]} for ii in range(iterations): # Go through a random...
first-neural-network/Your_first_neural_network.ipynb
dewitt-li/deep-learning
mit
Read in the list of 100 questions, as a list of 25 sub-lists, 4 questions per sub-list
# string info: http://www.openbookproject.net/books/bpp4awd/ch03.html # [lists] are mutable, (tuples) and 'strings' are not # Read in the list of 100 questions, putting it into 25 groups of 4 questions = [] rowQuestions= [] with open('questions.csv', 'rb') as csvfile: myreader = csv.reader(csvfile) for index,r...
notebooks/20Q/data/MakeTurkInput.ipynb
jamesfolberth/NGC_STEM_camp_AWS
bsd-3-clause
Read in all 250 movies
# Read in the list of 250 movies, making sure to remove commas from their names # (actually, if it has commas, it will be read in as different fields) movies = [] with open('movies.csv','rb') as csvfile: myreader = csv.reader(csvfile) for index, row in enumerate(myreader): movies.append( ' '.join(row) )...
notebooks/20Q/data/MakeTurkInput.ipynb
jamesfolberth/NGC_STEM_camp_AWS
bsd-3-clause
Write an output file to be used as the input file for Amazon Mechanical Turk. Each row will be one HIT
N = len(movies) with open('input.csv', 'wb') as csvfile: mywriter = csv.writer(csvfile) mywriter.writerow( ['MOVIE','QUESTION1','QUESTION2','QUESTION3','QUESTION4']) for i in range(5): for q in questions: mywriter.writerow( [movies[i], q[0], q[1], q[2], q[3] ]) #mywriter.writ...
notebooks/20Q/data/MakeTurkInput.ipynb
jamesfolberth/NGC_STEM_camp_AWS
bsd-3-clause
After submitting to Mechanical Turk... Read in the results. Note that the order of the questions is the same as the input file, so we can use that to simplify recording the answers. Let's encode 1 = Yes, 2 = No, 0 = Unsure
with open('Batch_2832525_batch_results.csv', 'rb') as csvfile: myreader = csv.DictReader(csvfile) #myreader = csv.reader(csvfile) # see dir(myreader) to list available methods for row in myreader: #print row print row['Input.MOVIE'] +": " + row['Input.QUESTION1'] , row['Answer.MovieAnswe...
notebooks/20Q/data/MakeTurkInput.ipynb
jamesfolberth/NGC_STEM_camp_AWS
bsd-3-clause
Time-frequency beamforming using LCMV Compute LCMV source power in a grid of time-frequency windows and display results. The original reference is: Dalal et al. Five-dimensional neuroimaging: Localization of the time-frequency dynamics of cortical activity. NeuroImage (2008) vol. 40 (4) pp. 1686-1700
# Author: Roman Goj <roman.goj@gmail.com> # # License: BSD (3-clause) import mne from mne import compute_covariance from mne.datasets import sample from mne.event import make_fixed_length_events from mne.beamformer import tf_lcmv from mne.viz import plot_source_spectrogram print(__doc__) data_path = sample.data_path...
0.12/_downloads/plot_tf_lcmv.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Read raw data, preload to allow filtering
raw = mne.io.read_raw_fif(raw_fname, preload=True) raw.info['bads'] = ['MEG 2443'] # 1 bad MEG channel # Pick a selection of magnetometer channels. A subset of all channels was used # to speed up the example. For a solution based on all MEG channels use # meg=True, selection=None and add grad=4000e-13 to the reject d...
0.12/_downloads/plot_tf_lcmv.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Time-frequency beamforming based on LCMV
# Setting frequency bins as in Dalal et al. 2008 (high gamma was subdivided) freq_bins = [(4, 12), (12, 30), (30, 55), (65, 299)] # Hz win_lengths = [0.3, 0.2, 0.15, 0.1] # s # Setting the time step tstep = 0.05 # Setting the whitened data covariance regularization parameter data_reg = 0.001 # Subtract evoked resp...
0.12/_downloads/plot_tf_lcmv.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Setup
EXPERIMENT_NAME = 'Simple notebook pipeline' # Name of the experiment in the UI BASE_IMAGE = 'tensorflow/tensorflow:2.0.0b0-py3' # Base image used for components in the pipeline import kfp import kfp.dsl as dsl from kfp import compiler from kfp import components
pipelines/simple-notebook-pipeline/Simple Notebook Pipeline.ipynb
kubeflow/examples
apache-2.0
Create pipeline component Create a python function
@dsl.python_component( name='add_op', description='adds two numbers', base_image=BASE_IMAGE # you can define the base image here, or when you build in the next step. ) def add(a: float, b: float) -> float: '''Calculates sum of two arguments''' print(a, '+', b, '=', a + b) return a + b
pipelines/simple-notebook-pipeline/Simple Notebook Pipeline.ipynb
kubeflow/examples
apache-2.0
Build a pipeline component from the function
# Convert the function to a pipeline operation. add_op = components.func_to_container_op( add, base_image=BASE_IMAGE, )
pipelines/simple-notebook-pipeline/Simple Notebook Pipeline.ipynb
kubeflow/examples
apache-2.0
Build a pipeline using the component
@dsl.pipeline( name='Calculation pipeline', description='A toy pipeline that performs arithmetic calculations.' ) def calc_pipeline( a: float =0, b: float =7 ): #Passing pipeline parameter and a constant value as operation arguments add_task = add_op(a, 4) #Returns a dsl.ContainerOp class instance. ...
pipelines/simple-notebook-pipeline/Simple Notebook Pipeline.ipynb
kubeflow/examples
apache-2.0
Compile and run the pipeline Kubeflow Pipelines lets you group pipeline runs by Experiments. You can create a new experiment, or call kfp.Client().list_experiments() to see existing ones. If you don't specify the experiment name, the Default experiment will be used. You can directly run a pipeline given its function de...
# Specify pipeline argument values arguments = {'a': '7', 'b': '8'} # Launch a pipeline run given the pipeline function definition kfp.Client().create_run_from_pipeline_func(calc_pipeline, arguments=arguments, experiment_name=EXPERIMENT_NAME) # The generated links below lead ...
pipelines/simple-notebook-pipeline/Simple Notebook Pipeline.ipynb
kubeflow/examples
apache-2.0
Alternately, you can separately compile the pipeline and then upload and run it as follows:
# Compile the pipeline pipeline_func = calc_pipeline pipeline_filename = pipeline_func.__name__ + '.pipeline.zip' compiler.Compiler().compile(pipeline_func, pipeline_filename) # Get or create an experiment client = kfp.Client() experiment = client.create_experiment(EXPERIMENT_NAME)
pipelines/simple-notebook-pipeline/Simple Notebook Pipeline.ipynb
kubeflow/examples
apache-2.0
Submit the compiled pipeline for execution:
# Specify pipeline argument values arguments = {'a': '7', 'b': '8'} # Submit a pipeline run run_name = pipeline_func.__name__ + ' run' run_result = client.run_pipeline(experiment.id, run_name, pipeline_filename, arguments) # The generated link below leads to the pipeline run information page.
pipelines/simple-notebook-pipeline/Simple Notebook Pipeline.ipynb
kubeflow/examples
apache-2.0
Define source paths
source_path = "/Users/sandrapietrowska/Documents/Trainings/luigi/data_source/"
Luigi_et_le_Machine_Learning_lui_dit_merci.ipynb
xebia-france/luigi-airflow
apache-2.0
Import data
raw_dataset = pd.read_csv(source_path + "Speed_Dating_Data.csv")
Luigi_et_le_Machine_Learning_lui_dit_merci.ipynb
xebia-france/luigi-airflow
apache-2.0
Data exploration Shape, types
raw_dataset.shape raw_dataset.head() raw_dataset.dtypes.value_counts()
Luigi_et_le_Machine_Learning_lui_dit_merci.ipynb
xebia-france/luigi-airflow
apache-2.0
Missing values
raw_dataset.isnull().sum().head(10) summary = raw_dataset.describe().transpose() print summary.head(15) plt.hist(raw_dataset['age'].dropna());
Luigi_et_le_Machine_Learning_lui_dit_merci.ipynb
xebia-france/luigi-airflow
apache-2.0