markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Vidíme, že naše výsledné pole by mělo být 50x50 pixelů velké, aby se do něj data vešla.
result = numpy.zeros((50, 50)) #tady bude vysledek for i, fname in enumerate(temp_dict): #print(i, fname) x = xs[i] y = ys[i] T = temp_dict[fname] result[y, x] = T
lekce_08/N2spec.ipynb
ziky5/F4500_Python_pro_fyziky
mit
Pomocí plt.imshow() můžeme výsledek vykreslit.
#plt.imshow(result) #plt.colorbar()
lekce_08/N2spec.ipynb
ziky5/F4500_Python_pro_fyziky
mit
read file content
data = pd.read_csv('ex1data1.txt', header=None, names=['population', 'profit']) data.head() data.plot.scatter('population', 'profit')
linear_regression/linear_regression1.ipynb
Misteir/Machine_Learning
gpl-3.0
Dots seem to follow a line, we could have done a correlation test to check if the two variabes are linked. Now we transform the data matrix into two numpy arrays.
X = np.array(data["population"]) y = np.array(data["profit"])
linear_regression/linear_regression1.ipynb
Misteir/Machine_Learning
gpl-3.0
now we will developp the two functions predict (apply theta to the X matrix) and gradient_descent1 (update theta)
def predict(X, theta): return (X * theta[1] + theta[0]) def gradient_descent1(X, y, theta, alpha, num_iters): m = X.shape[0] for i in range(0, num_iters): theta0 = theta[0] - (alpha / m) * np.sum(predict(X, theta) - y) theta1 = theta[1] - (alpha / m) * np.dot(predict(X, theta) - y, np.trans...
linear_regression/linear_regression1.ipynb
Misteir/Machine_Learning
gpl-3.0
Expected output (for alpha 0.01 and 1500 iterations):[-3.6302914394043597, 1.166362350335582] The visualize plot our dataset with the regression line corresponding to theta
def visualize(theta): fig = plt.figure() ax = plt.axes() ax.set_xlim([4.5,22.5]) ax.set_ylim([-5, 25]) ax.scatter(X, y) line_x = np.linspace(0,22.5, 20) line_y = theta[0] + line_x * theta[1] ax.plot(line_x, line_y) plt.show() visualize(theta)
linear_regression/linear_regression1.ipynb
Misteir/Machine_Learning
gpl-3.0
the cost function will allow us to record the evolution of the cost during the gradient descent
def cost(X, y, theta): loss = predict(X, theta) - y cost = (1 / (2 * X.shape[0])) * np.dot(loss, np.transpose(loss)) return(cost) cost(X, y, [0, 0])
linear_regression/linear_regression1.ipynb
Misteir/Machine_Learning
gpl-3.0
expected output for [0, 0]: 32.072733877455676 the full version of gradient descent now records the cost history
def gradient_descent(X, y, theta, alpha, num_iters): m = X.shape[0] J_history = [] for i in range(0, num_iters): theta0 = theta[0] - (alpha / m) * np.sum(predict(X, theta) - y) theta1 = theta[1] - (alpha / m) * np.dot(predict(X, theta) - y, np.transpose(X)) theta = [theta0, theta1] ...
linear_regression/linear_regression1.ipynb
Misteir/Machine_Learning
gpl-3.0
Expected output for alhpa 0.01 and 1500 iterations: [-3.6302914394043597, 1.166362350335582]
fit = plt.figure() ax = plt.axes() ax.plot(J_history)
linear_regression/linear_regression1.ipynb
Misteir/Machine_Learning
gpl-3.0
Historical data from previous students: each student has two exams scores associated and the final admission result (1=yes, 0= no). Let's plot the points in a chart (green means admitted, red not admitted).
import matplotlib.pyplot as plt %matplotlib inline colours = ['red' if i==0 else 'green' for i in data.Admitted] fig,ax = plt.subplots() ax.scatter(data.Exam1, data.Exam2, c=colours) ax.grid(True) ax.set_xlabel("Exam 1 score") ax.set_ylabel("Exam 2 score") fig.suptitle("Student admission vs. past two exams")
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
If the score of the first or the second exam was too low, it might be not enough to be admitted. You need a good balance. Let's try to quantify it. The sigmoid function Logistic regression uses a special function to model how the probability of the event "Admitted" P(y=1) is affected by our variables (the exams score)....
import numpy as np def sigmoid(z): """ Compute the sigmoid function of each input value. It uses numpy to leverage the vectorised format. Argument: z: matrix, vector or scalar (float) Returns: matrix, vector or float """ return 1 / (1 + np.exp(-z))
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
Let's plot it:
x = np.arange(-10., 10., 0.2) sig = sigmoid(x) fig,ax = plt.subplots() ax.plot(x,sig) ax.grid(True) ax.set_xlabel("x") ax.set_ylabel("Sigmoid(x)") fig.suptitle("The sigmoid function")
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
Unit tests:
sigmoid(1) sigmoid(np.array([2,3]))
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
Logistic Response function: cost and gradient This is the logistic function to model our admission: $P(y=1) = \frac{1}{1 + e^{-(\beta_{0} + \beta_{1} \cdot x_{1} + ... + \beta_{n} \cdot x_{n}) }} $ where y is the admission result (0 or 1) and x are the exams scores. We have in our example x1 and x2 (two exams). Our ...
def getCostGradient(beta, X, y): """ Compute the cost of a particular choice of beta as the parameter for logistic regression and the gradient of the cost w.r.t. to the parameters. Returns cost and gradient Arguments: beta: parameters, list X: input data points, array ...
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
Unit test:
getCostGradient(np.array([-1,0.2]), np.array([[1,34], [1,35]]), np.array([0,1]))
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
Split data into X (training data) and y (target variable)
cols = data.shape[1] cols # add the intercept data.insert(0, 'Ones', 1) X = data.iloc[:,0:cols] # the first columns but the last are X X = np.array(X.values) y = data.iloc[:,cols:cols+1] # last column is the y y = np.array(y.values) initialBeta = np.zeros(cols) # could be random also
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
what is the cost given these initial beta parameters?
getCostGradient(initialBeta, X, y)
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
Initial cost is 0.69 Fit the beta parameters To find the optimal beta parameters we use a highly tuned function (minimize) from the package SciPy. We need to provide the cost and the gradient function, the input data and which method to use (we use the classic Newton). The argument Jac=True tells that cost and gradient...
import scipy.optimize as opt result = opt.minimize(fun = getCostGradient, x0 = initialBeta, args = (X, y), method = 'Newton-CG',jac = True) result.message optimalBeta = result.x
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
and here we have our final beta parameters:
optimalBeta
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
$$P(y=1) = \frac{1}{1 + e^{25.17 - 0.21 \cdot x_{1} - 0.20 \cdot x_{2} }} $$ Plot the decision boundary We can use these beta parameters to plot the decision boundary on the training data. We only need two points to plot a line, so we choose two endpoints: the min and the max among the X training data (we add a small m...
plot_x = np.array([min(X[:,2])-2, max(X[:,2])+2]) plot_x
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
The boundary lies where the P(y=1) = P(y=0) = 0.5 which means that beta * X shall be zero
plot_y = (-1./optimalBeta[2]) * (optimalBeta[1] * plot_x + optimalBeta[0]) plot_y fig,ax = plt.subplots() ax.scatter(data.Exam1, data.Exam2, c=colours) ax.plot(plot_x, plot_y) ax.grid(True) ax.set_xlabel("Exam 1 score") ax.set_ylabel("Exam 2 score") fig.suptitle("Student admission vs. past two exams")
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
The blue line is our decision boundary: when your exams score lie below the line then probably (that is the prediction) you will not be admitted to University. If they lie above, probably you will. As you can see, the boundary is not predicting perfectly on the training historical data. It's a model. Not perfect but us...
def predict(beta, X): probabilities = sigmoid(np.dot(X, beta)) return [1 if x >= 0.5 else 0 for x in probabilities] predictions = predict(optimalBeta, X) correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)] accuracy = (sum(map(int, correct)) % ...
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
Just for fun, let's say that my scores are 40 in the first exam and 78 in the second one:
myExams = np.array([1., 40., 78.]) sigmoid(np.dot(myExams, optimalBeta))
01-Regression/LogisticRegression.ipynb
Mashimo/datascience
apache-2.0
Model Machine
mp = phantasy.MachinePortal(machine='FRIB_FLAME', segment='LINAC')
docs/source/src/notebooks/phantasy_lattice.ipynb
archman/phantasy
bsd-3-clause
Inspect mp
mp.inspect_mconf()
docs/source/src/notebooks/phantasy_lattice.ipynb
archman/phantasy
bsd-3-clause
Load another lattice (segment)
mp.load_lattice('LS1') # Please note: 'LS1' maybe not consistent with the real configuration, just for demonstration. # The configuration for 'LS1' segment should be updated.
docs/source/src/notebooks/phantasy_lattice.ipynb
archman/phantasy
bsd-3-clause
List all loaded lattices
mp.lattice_names # Current working lattice: mp.work_lattice_name # Switch lattice to 'LINAC' mp.use_lattice('LINAC') # Current working lattice now: mp.work_lattice_name
docs/source/src/notebooks/phantasy_lattice.ipynb
archman/phantasy
bsd-3-clause
Currently (phantasy of version 0.5.0), one can operate lattice by explicitly getting working lattice, The future plan is most operation should be able to reach through MachinePortal. Get working lattice
lat = mp.work_lattice_conf
docs/source/src/notebooks/phantasy_lattice.ipynb
archman/phantasy
bsd-3-clause
Inspect lattice
print("Lattice name : %s" % lat.name) print("Machine name : %s" % lat.mname) print("Lattice groups : %s" % lat.group.keys()) ## more to be shown, not final version.
docs/source/src/notebooks/phantasy_lattice.ipynb
archman/phantasy
bsd-3-clause
Locate Elements Two methods (to date) could be used to locate elements: get_elements() and next_elements(). get_elements()
# Invalid name: lat.get_elements(name='NOEXISTS') # name: lat.get_elements(name='FS1_BMS:DCV_D2662') # name pattern lat.get_elements(name=['FS1_B?*D266?', 'LS1_B*DCV*']) # multiple filters, e.g. type: lat.get_elements(name=['FS1_B?*D266?', 'LS1_B*DCV*'], type='BPM') assert lat.get_elements(name=['FS1_B?*D266?', 'LS1...
docs/source/src/notebooks/phantasy_lattice.ipynb
archman/phantasy
bsd-3-clause
next_elements()
# locate reference element: ref_elem = lat.get_elements(name='*')[6] ref_elem # get the next element of ref_elem, i.e. the first element downstream lat.next_elements(ref_elem) # get the last one of the next two elements lat.next_elements(ref_elem, count=2) # get all of the next two elements lat.next_elements(ref_el...
docs/source/src/notebooks/phantasy_lattice.ipynb
archman/phantasy
bsd-3-clause
The test mrio includes several extensions:
list(io.get_extensions())
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
For the example here, we use 'emissions' - 'emission_type1':
io.emissions.F et1_diag = io.emissions.diag_stressor(('emission_type1', 'air'), name = 'emtype1_diag')
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
The parameter name is optional, if not given the name is set to the stressor name + '_diag' The new emission matrix now looks like this:
et1_diag.F.head(15)
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
And can be connected back to the system with:
io.et1_diag = et1_diag
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
Finally we can calulate the all stressor accounts with:
io.calc_all()
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
This results in a square footprint matrix. In this matrix, every column respresents the amount of stressor occuring in each region - sector driven by the consumption stated in the column header. Conversly, each row states where the stressor impacts occuring in the row are distributed due (from where they are driven).
io.et1_diag.D_cba.head(20)
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
The total footprints of a region - sector are given by summing the footprints along rows:
io.et1_diag.D_cba.sum(axis=0).reg1 io.emissions.D_cba.reg1
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
The total stressor in a sector corresponds to the sum of the columns:
io.et1_diag.D_cba.sum(axis=1).reg1 io.emissions.F.reg1
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
Aggregation of source footprints If only one specific aspect of the source is of interest for the analysis, the footprint matrix can easily be aggregated with the standard pandas groupby function. For example, to aggregate to the source region of stressor, do:
io.et1_diag.D_cba.groupby(level='region', axis=0).sum()
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
In addition, the aggregation function of pymrio also work on the diagonalized footprints. Here as example together with the country converter coco:
import country_converter as coco io.aggregate(region_agg = coco.agg_conc(original_countries=io.get_regions(), aggregates={'reg1': 'World Region A', 'reg2': 'World Region A', '...
doc/source/notebooks/buildflowmatrix.ipynb
konstantinstadler/pymrio
gpl-3.0
Deploy Spark ML Models
from pyspark.ml.linalg import Vectors from pyspark.ml.feature import VectorAssembler, StandardScaler from pyspark.ml.feature import OneHotEncoder, StringIndexer from pyspark.ml import Pipeline, PipelineModel from pyspark.ml.regression import LinearRegression from pyspark.sql import SparkSession spark = SparkSession.b...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Step 8: Serialize PipelineModel
from jpmml import toPMMLBytes model_bytes = toPMMLBytes(spark, training_dataset, pipeline_model) print(model_bytes.decode("utf-8"))
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Step 9: Push Model to Live, Running Spark ML Model Server (Mutable)
import urllib.request namespace = 'default' model_name = 'airbnb' version = '1' update_url = 'http://prediction-pmml-aws.demo.pipeline.io/update-pmml-model/%s/%s/%s' % (namespace, model_name, version) update_headers = {} update_headers['Content-type'] = 'application/xml' req = urllib.request.Request(update_url, \ ...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Step 10: Evalute Model
import urllib.parse import json namespace = 'default' model_name = 'airbnb' version = '1' evaluate_url = 'http://prediction-pmml-aws.demo.pipeline.io/evaluate-pmml-model/%s/%s/%s' % (namespace, model_name, version) evaluate_headers = {} evaluate_headers['Content-type'] = 'application/json' input_params = '{"bathroom...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Bonus Demos! Deploy Java-based Model Create Java-based Model
from urllib import request sourceBytes = ' \n\ private String str; \n\ \n\ public void initialize(Map<String, Object> args) { \n\ ...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Deploy Java-based Model
from urllib import request namespace = 'default' model_name = 'java_equals' version = '1' update_url = 'http://prediction-java-aws.demo.pipeline.io/update-java/%s/%s/%s' % (namespace, model_name, version) update_headers = {} update_headers['Content-type'] = 'text/plain' req = request.Request("%s" % update_url, head...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Evaluate Java-based Model
from urllib import request namespace = 'default' model_name = 'java_equals' version = '1' evaluate_url = 'http://prediction-java-aws.demo.pipeline.io/evaluate-java/%s/%s/%s' % (namespace, model_name, version) evaluate_headers = {} evaluate_headers['Content-type'] = 'application/json' input_params = '{"id":"21618"}' ...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Deploy Scikit-Learn Model
!pip install sklearn_pandas !pip install git+https://github.com/jpmml/sklearn2pmml.git
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Create Scikit-Learn Model
import pandas as pd import numpy as np import urllib.request import urllib.parse import json from sklearn.datasets import load_diabetes,load_iris from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error as mse, r2_score from sklearn2pmml import PMMLPipeline from sklearn.tree imp...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Serialize Scikit-Learn Model
sklearn2pmml(iris_pipeline, "DecisionTreeIris.pmml", with_repr = True) model_bytes = bytearray(open('DecisionTreeIris.pmml', 'rb').read())
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Deploy Scikit-Learn Model
import urllib.request import urllib.parse namespace = 'default' model_name = 'iris' version = '1' update_url = 'http://prediction-pmml-aws.demo.pipeline.io/update-pmml-model/%s/%s/%s' % (namespace, model_name, version) update_headers = {} update_headers["Content-type"] = "application/xml" req = urllib.request.Reque...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Monitoring Your Models Netflix Microservices Dashboard (Hystrix)
from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) from IPython.display import clear_output, Image, display, HTML html = '<iframe width=1200px height=500px src="http://hystrix.demo.pipeline.io/hystrix-dashboard/monitor/monitor.html?streams=%5B%7B%22nam...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Grafana + Prometheus Dashboard
from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) from IPython.display import clear_output, Image, display, HTML html = '<iframe width=1200px height=500px src="http://grafana.demo.pipeline.io">' display(HTML(html))
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Load-Test Your Model Servers Run JMeter Tests from Local Laptop (Limited by Laptop Performance) Run Headless JMeter Tests from Training Clusters in Cloud
# Spark ML - Airbnb !kubectl create --context=awsdemo -f /root/pipeline/loadtest.ml/loadtest-aws-airbnb-rc.yaml # Codegen - Java - Simple !kubectl create --context=awsdemo -f /root/pipeline/loadtest.ml/loadtest-aws-equals-rc.yaml # Tensorflow AI - Tensorflow Serving - Simple !kubectl create --context=awsdemo -f /roo...
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
End Load Tests
!kubectl delete --context=awsdemo rc loadtest-aws-airbnb !kubectl delete --context=awsdemo rc loadtest-aws-equals !kubectl delete --context=awsdemo rc loadtest-aws-minimal
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Rolling Deploy
!kubectl rolling-update prediction-tensorflow --context=awsdemo --image-pull-policy=Always --image=fluxcapacitor/prediction-tensorflow
jupyterhub.ml/notebooks/train_deploy/zz_under_construction/zz_old/talks/DataWeekends/SparkMLDeployment/DataWeekends-Mar182017-SparkMLDeployment.ipynb
fluxcapacitor/source.ml
apache-2.0
Here I have loaded the iris dataset and replicated it so as to have 15MM rows of data. The space requirement for 15MM rows of data in a pandas dataframe is more than twice that of a numpy recarray.
MB = 1024*1024 print("Pandas %d MB " % (sys.getsizeof(data)/MB)) print("Numpy %d MB " % (sys.getsizeof(data_rec)/MB))
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
A snippet of the data shown below.
data.head() # <!-- collapse=True --> def perf(inp, statement, grid=None): length = len(inp) gap = int(length/5) #grid = np.array([int(x) for x in np.logspace(np.log10(gap), np.log10(length+1) , 5)]) if grid is None: grid = np.array([10000, 100000, 1000000, 5000000, 10000000]) num = 100 ...
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
In this post, performance metrics for a few different categories are compared between numpy and pandas: - operations on a column of data, such as mean or applying a vectorised function - operations on a filtered column of data - vector operations on a column or filtered column Operations on a Column Here some performan...
bench(data, "data.loc[:, 'sepal_length'].mean()", data_rec, "np.mean(data_rec.sepal_length)", title="Mean on Unfiltered Column")
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
Below, the vectorized log operation is faster in numpy for sizes less than 100K but pandas costs about the same for sizes larger than 100K.
bench(data, "np.log(data.loc[:, 'sepal_length'])", data_rec, "np.log(data_rec.sepal_length)", title="Vectorised log on Unfiltered Column")
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
The one differentiating aspect about the test below is that the column species is of string type. The operation demonstrated is a unique calculation. We observe that the unique calculation is roughly an order of magnitude faster in pandas for sizes larger than 1K rows.
bench(data, "data.loc[:,'species'].unique()", data_rec, "np.unique(data_rec.species)", grid=np.array([100, 1000, 10000, 100000, 1000000]), title="Unique on Unfiltered String Column")
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
Operations on a Filtered Column Below we perform the same tests as above, except that the column is not a full view, but is instead a filtered view. The filters are simple filters with an arithmetic bool comparison for the first two and a string comparison for the third below. Below, mean is calculated for a filtered ...
bench(data, "data.loc[(data.sepal_width>3) & \ (data.petal_length<1.5), 'sepal_length'].mean()", data_rec, "np.mean(data_rec[(data_rec.sepal_width>3) & \ (data_rec.petal_length<1.5)].sepal_length)", grid=np.array([1000, 10000, 100000, 1000000]), title="Mean on Filtered Col...
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
For vectorised log operation on a unfiltered column shown above, numpy performed better than pandas for number of records less than 100K while the performance was comparable for the two for sizes larger than 100K. But the moment you introduce a filter on a column, pandas starts to show an edge over numpy for number of ...
bench(data, "np.log(data.loc[(data.sepal_width>3) & \ (data.petal_length<1.5), 'sepal_length'])", data_rec, "np.log(data_rec[(data_rec.sepal_width>3) & \ (data_rec.petal_length<1.5)].sepal_length)", grid=np.array([1000, 10000, 100000, 1000000]), title="Vectorised log on Fil...
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
Here is another example of a mean reduction on a column but with a string filter. We see a similar behavior where numpy performs significantly better at small sizes and pandas takes a gentle lead for larger number of records.
bench(data, "data[data.species=='setosa'].sepal_length.mean()", data_rec, "np.mean(data_rec[data_rec.species=='setosa'].sepal_length)", grid=np.array([1000, 10000, 100000, 1000000]), title="Mean on (String) Filtered Column")
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
Vectorized Operation on a Column In this last section, we do vectorised arithmetic using multiple columns. This involves creating a view and vectorised math on these views. Even when there is no filter, pandas has a slight edge over numpy for large number of records. For smaller than 100K records, numpy performs signif...
bench(data, "data.petal_length * data.sepal_length + \ data.petal_width * data.sepal_width", data_rec, "data_rec.petal_length*data_rec.sepal_length + \ data_rec.petal_width * data_rec.sepal_width", title="Vectorised Math on Unfiltered Columns")
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
In the following figure, the filter involves vectorised arithmetic operation, and mean reduction is computed on the filtered column. The presence of a filter makes pandas significantly faster for sizes larger than 100K, while numpy maitains a lead for smaller than 10K number of records.
bench(data, "data.loc[data.sepal_width * data.petal_length > \ data.sepal_length, 'sepal_length'].mean()", data_rec, "np.mean(data_rec[data_rec.sepal_width * data_rec.petal_length \ > data_rec.sepal_length].sepal_length)", title="Vectorised Math in Filtering Columns", grid=...
content/extra/notebooks/pandas_vs_numpy.ipynb
gouthambs/karuth-source
artistic-2.0
<a id="bld1" name="bld1"></a> Building a Simple DataFrame <a id="dixndf" name="dixndf"></a> Create DF from Dictionary
# create a dictionary stateData = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], \ 'year': [2000, 2001, 2002, 2001, 2002], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]} # convert to DataFrame df_stdt = pd.DataFrame(stateData) df_stdt print("Index: %s" %df_stdt.index) print("Values: \n%s" %df_stdt.values...
PY_Basics/TMWP_Pandas_Dataframe_Basics.ipynb
TheMitchWorksPro/DataTech_Playground
mit
<a id="lbldf" name="lbldf"></a> Create Empty DF And Add Rows One At A Time A common scenario in code: a loop or function call needs to add a row to a dataframe but first you need a blank one. This code may come in handy as that scenario comes up.
solutionPD = pd.DataFrame({ 'disk':[],'fromPeg':[], 'toPeg':[]}, dtype=np.int64 ) solutionPD = solutionPD.append(pd.DataFrame({ 'disk':[5],'fromPeg':[1], 'toPeg':[3]}), ignore_index=True) solutionPD = solutionPD.append(pd.DataFrame({ 'disk':[4],'fromPeg':[1], 'toPeg':[2] }), ignore_index=True) print("disk column type:...
PY_Basics/TMWP_Pandas_Dataframe_Basics.ipynb
TheMitchWorksPro/DataTech_Playground
mit
<a id="setDtype1" name="setDtype1"></a> Setting Data Types on Columns Read comments as well as code in cells which follow:
# Recommended: To set dtype for all columns, build the Dataframe, # and then use astype() to set the columns as shown here # though online help topics indicate it should be possible to pass in a dictionary or list of tuples # to set all the datatypes initially, under Python 2.7, this does not seem to work. # came cl...
PY_Basics/TMWP_Pandas_Dataframe_Basics.ipynb
TheMitchWorksPro/DataTech_Playground
mit
<a id="rname" name="rname"></a> Renaming Dataframe Columns Study these tests. They show what works and what doesn't as counterintuitive as that is. This code was written python 3.6.1
testDF = pd.DataFrame({"color":["red", "green", "blue"], "thing":["house", "dog", "machine"]}) testDF ## get single column name testDF.columns[0] ## rename one column testDF.columns.values[0]='primaries' testDF testDF.primaries testDF.color testDF.color.name testDF.columns = ['primary', 'somethin...
PY_Basics/TMWP_Pandas_Dataframe_Basics.ipynb
TheMitchWorksPro/DataTech_Playground
mit
<a id="display1" name="display1"></a> Displaying DataFrames in Python Notebooks To the uninitiated, dataframes appear to display nicely in notebooks if they are the last command in a cell. But printing them and/or outputting them from functions does not work unless you "know the trick" illustrated in this section. The...
## this does not work: def printDF(df): print(df) def displayDF(df): df df_stdt # fails to output since this is not the last command in the cell print(df_stdt) # outputs but without the nice built-in formatting print("="*72) printDF(df_stdt) # outputs without format displayDF(df_stdt) # fail...
PY_Basics/TMWP_Pandas_Dataframe_Basics.ipynb
TheMitchWorksPro/DataTech_Playground
mit
The Solution A Stack Overflow post indicates to use the import statement that is commented out in the cell that follows. The one that is not commented out works with the Python 3.6 Anaconda implementation tested here. By default: this Anaconda implementation installed ipython and ipython_genutils packages. If these a...
## use this line if it works ... if not, try the one used at start of this code cell ## this cell tested with Anaconda / Python 3.6 # from Ipython.display import display import ipython_genutils def presentDF(df): display(df) presentDF(df_stdt) print("="*72) display(solutionPD) print("="*72) display(solutio...
PY_Basics/TMWP_Pandas_Dataframe_Basics.ipynb
TheMitchWorksPro/DataTech_Playground
mit
<a id="indx" name="indx"></a> Indexing for DataFrame Slices There are some good resources on the web about this. This list will get added to as they are discovered. Tutorial: selecting dataframes Pandas Dataframe by Exaple - see the sections on selecting and indexing Quick Example: .loc[], .iloc[]
testDF testDF.iloc[:,0] # all rows, column 0 testDF.iloc[0,0] # row 0, column 0 testDF.iloc[1,:] # row 1, all columns testDF.loc[1] # row at index 1 ## note: this DF had the names changed but indicies for columns are different testDF.loc[:, 'TruColors'] # all rows, column by index name testDF.loc[:, 'TruColors...
PY_Basics/TMWP_Pandas_Dataframe_Basics.ipynb
TheMitchWorksPro/DataTech_Playground
mit
Put it all together Below I've strung together all the pieces to do an entire Hillmaker run. Change inputs as needed (e.g. scenario_name and associated parameter values) and run all the cells below. You can skip rereading the main input file if that isn't changing. Read main stop data file
file_stopdata = 'data/ShortStay.csv' df = pd.read_csv(file_stopdata, parse_dates=['InRoomTS','OutRoomTS']) df.info()
hillmaker/examples/hillPyTesting-Core.ipynb
misken/hillmaker
apache-2.0
Set input parameters
# Required inputs scenario_name = 'sstest_60' in_fld_name = 'InRoomTS' out_fld_name = 'OutRoomTS' cat_fld_name = 'PatType' start_analysis = '1/1/1996' end_analysis = '3/30/1996 23:45' # Optional inputs # This next field wasn't in original Hillmaker. Use it to specify the name to use for the overall totals. # At this...
hillmaker/examples/hillPyTesting-Core.ipynb
misken/hillmaker
apache-2.0
Create the by datetime table
df2 = df[df['PatType'].isin(includecats)] df2.info() df2.groupby('PatType').describe() df = df[df['PatType'].isin(includecats)] df.groupby('PatType').describe() bydt_df = bydatetime.make_bydatetime(df, in_fld_name, out_fld_name, ...
hillmaker/examples/hillPyTesting-Core.ipynb
misken/hillmaker
apache-2.0
Compute summary stats
def get_occstats(group, stub=''): return {stub+'count': group.count(), stub+'mean': group.mean(), stub+'min': group.min(), stub+'max': group.max(), 'stdev': group.std(), stub+'p50': group.quantile(0.5), stub+'p55': group.quantile(0.55), stub+'p60': group.quantile(0....
hillmaker/examples/hillPyTesting-Core.ipynb
misken/hillmaker
apache-2.0
Write summaries and by datetime out to CSV
file_bydt_csv = 'testing/bydate_' + scenario_name + '.csv' bydt_df.to_csv(file_bydt_csv, index=False) file_occ_csv = 'testing/occ_stats_' + scenario_name + '.csv' file_arr_csv = 'testing/arr_stats_' + scenario_name + '.csv' file_dep_csv = 'testing/dep_stats_' + scenario_name + '.csv' occ_stats_summary.to_csv(file_occ...
hillmaker/examples/hillPyTesting-Core.ipynb
misken/hillmaker
apache-2.0
Debugging
ts = pd.Timestamp('19960103 00:00:00') print(ts) 24000/24 df_ART = df[(df.PatType == 'ART') & (df.InRoomTS < ts)] df_ART.info() df_ART bydt_df.head() bydt_df[25:50] import numpy as np import pandas as pd from pandas import Timestamp import hillmaker as hm file_stopdata = 'data/unit_stop_log_Experiment1_Scenari...
hillmaker/examples/hillPyTesting-Core.ipynb
misken/hillmaker
apache-2.0
Computing occupancy statistics Need to compute a bunch of output stats to use for visualization, metamodeling and to evaluate scenarios. Overall utilization It would be nice if we could just Hillmaker with bin size of one week. Let's try it.
scenario_name = 'log_unitocc_test_steadystate' hm.run_hillmaker(scenario_name,df,in_fld_name, out_fld_name,cat_fld_name, start_analysis,end_analysis,tot_fld_name,1440, categories=includecats,totals=False,outputpath='./testing') occ_df = pd.read_csv('testing/occ_stats_summary_log_unito...
hillmaker/examples/hillPyTesting-Core.ipynb
misken/hillmaker
apache-2.0
Extracting information From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Return-Path: &lt;postmaster@collab.sakaiproject.org&gt; for &lt;source@collab.sakaiproject.org&gt;; Received: (from apache@localhost) Author: stephen.marquard@uct.ac.za
import re s = 'Hello from csev@umich.edu to cwen@iupui.edu about the meeting @2PM' lst = re.findall('\S+@\S+', s) print(lst)
wk4/notebooks/wk4.1.ipynb
saashimi/code_guild
mit
The regular expression would match twice (csev@umich.edu and cwen@iupui.edu) but it would not match the string "@2PM" because there are no non-blank characters before the at-sign. We can use this regular expression in a program to read all the lines in a file and print out anything that looks like an e-mail address as ...
import re hand = open('mbox-short.txt') for line in hand: line = line.rstrip() x = re.findall('\S+@\S+', line) # some emails contain gross < characters! if len(x) > 0 : print(x)
wk4/notebooks/wk4.1.ipynb
saashimi/code_guild
mit
Some of our E-mail addresses have incorrect characters like "<" or ";" at the beginning or end. Let's declare that we are only interested in the portion of the string that starts and ends with a letter or a number. To do this, we use another feature of regular expressions. Square brackets are used to indicate a set of ...
import re hand = open('mbox-short.txt') for line in hand: line = line.rstrip() x = re.findall('[a-zA-Z0-9]\S*@\S*[a-zA-Z]', line) if len(x) > 0 : print(x)
wk4/notebooks/wk4.1.ipynb
saashimi/code_guild
mit
Combining search and extraction If we want to find numbers on lines that start with the string "X-" such as: X-DSPAM-Confidence: 0.8475 X-DSPAM-Probability: 0.0000 We don't just want any floating point numbers from any lines. We only to extract numbers from lines that have the above syntax. To match we write ^X-.*: [0-...
import re hand = open('mbox-short.txt') for line in hand: line = line.rstrip() if re.search('^X\S*: [0-9.]+', line) : print(line)
wk4/notebooks/wk4.1.ipynb
saashimi/code_guild
mit
But now we have to solve the problem of extracting the numbers using split. While it would be simple enough to use split, we can use another feature of regular expressions to both search and parse the line at the same time. Parentheses are another special character in regular expressions. When you add parentheses to a...
import re hand = open('mbox-short.txt') for line in hand: line = line.rstrip() x = re.findall('^X\S*: ([0-9]\.[0-9]+)', line) if len(x) > 0 : print(x)
wk4/notebooks/wk4.1.ipynb
saashimi/code_guild
mit
Escape characters What if we want to match $, ^, * etc? Use escape character (forward slash)
import re x = 'We just received $10.00 for cookies.' y = re.findall('\$[0-9.]+',x) print(y) import re x = 'We just received $10.00 for cookies.' y = re.findall('c\S+$',x) print(y)
wk4/notebooks/wk4.1.ipynb
saashimi/code_guild
mit
Summary ^ Matches the beginning of the line. $ Matches the end of the line. . Matches any character (a wildcard). \s Matches a whitespace character. \S Matches a non-whitespace character (opposite of \s). * Applies to the immediately preceding character and indicates to match zero or more of the preceding charact...
import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('www.py4inf.com', 80)) mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n') while True: data = mysock.recv(512) if ( len(data) < 1 ) : break print(data) mysock.close() import socket import ti...
wk4/notebooks/wk4.1.ipynb
saashimi/code_guild
mit
Fixed-Point Iteration The function fixpoint takes two arguments: - $S_0$ is a set of elements, - $f$ is a function mapping elements to sets of elements. The function fixpoint computes the smallest set $S$ such the following conditions holds: - $S_0 \subseteq S$, - $S = \bigcup { f(x) \mid x \in S }$.
def fixpoint(S0, f): Result = S0.copy() # don't change S0 while True: NewElements = { x for o in Result for x in f(o) } if NewElements.issubset(Result): return Result Result |= NewElements
Python/FixedPoint.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
The function fixpoint2 takes two arguments: - $S_0$ is a set of elements, - $f$ is a function mapping sets of elements to sets of elements. The function fixpoint2 computes the smallest set $S$ such the following conditions holds: - $S_0 \subseteq S$, - $S = f(S)$.
def fixpoint2(S0, f): Result = S0.copy() # don't change S0 while True: NewElements = f(Result) if NewElements.issubset(Result): return Result Result |= NewElements
Python/FixedPoint.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
Problema físico Definimos un SR con el origen en el orificio donde el hilo atravieza el plano, la coordenada $\hat{z}$ apuntando hacia abajo. Con esto sacamos, de la segunda ley de Newton para las particulas: $$ \begin{align} \text{Masa 1)}\quad&\vec{F}_1 = m_1 \vec{a}_1 \ &-T \hat{r} = m_1 \vec{a}_1 \ &-T \hat{r} = m...
# Constantes del problema: M1 = 3 M2 = 3 g = 9.81 # Condiciones iniciales del problema: r0 = 2 r_punto0 = 0 tita0 = 0 tita_punto0 = 1 C1 = (M2*g)/(M1+M2) # Defino constantes utiles C2 = (M1)/(M1+M2) cond_iniciales = [r0, r_punto0, tita0, tita_punto0] def derivada(X, t, c1, c2): # esto sería la f del caso { x' = f(x,...
python/Extras/Fisica1/simulacion.ipynb
fifabsas/talleresfifabsas
mit
Todo muy lindo!! Cómo podemos verificar si esto está andando ok igual? Porque hasta acá solo sabemos que dio razonable, pero el ojímetro no es una medida cuantitativa. Una opción para ver que el algoritmo ande bien (y que no hay errores numéricos, y que elegimos un integrador apropiado ojo con esto eh... te estoy miran...
from scipy.integrate import solve_ivp def resuelvo_sistema(m1, m2, tmax = 20, metodo='RK45'): t0 = 0 c1 = (m2*g)/(m1+m2) # Defino constantes utiles c2 = (m1)/(m1+m2) t = np.arange(t0, tmax, 0.001) # acá hago uso de las lambda functions, solamente para usar # la misma funcion que definimos...
python/Extras/Fisica1/simulacion.ipynb
fifabsas/talleresfifabsas
mit
Ven cómo los distintos métodos van modificando más y más la curva de $r(t)$ a medida que van pasando los pasos de integración. Tarea para ustedes es correr el mismo código con la conservación de energía. Cuál es mejor, por qué y cómo saberlo son preguntas que deberán hacerse e investigar si en algún momento trabajan co...
from matplotlib import animation %matplotlib notebook result = resuelvo_sistema(M1, M2, tmax=30, metodo='Radau') t = result.t r, rp, tita, titap = result.y fig, ax = plt.subplots() ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1]) ax.plot(r*np.cos(tita)/r0, r*np.sin(tita)/r0, 'm', lw=0.2) line, = ax.plot([], [], 'ko', ms=5) ...
python/Extras/Fisica1/simulacion.ipynb
fifabsas/talleresfifabsas
mit
Recuerden que esta animación no va a parar eh, sabemos que verla te deja en una especie de trance místico, pero recuerden pararla cuando haya transcurrido suficiente tiempo Animación Interactiva Usando ipywidgets podemos agregar sliders a la animación, para modificar el valor de las masitas
from ipywidgets import interactive, interact, FloatProgress from IPython.display import clear_output, display %matplotlib inline @interact(m1=(0,5,0.5), m2=(0,5,0.5), tmax=(0.01,20,0.5)) #Permite cambiar el parámetro de la ecuación def resuelvo_sistema(m1, m2, tmax = 20): t0 = 0 c1 = (m2*g)/(m1+m2) # Defino co...
python/Extras/Fisica1/simulacion.ipynb
fifabsas/talleresfifabsas
mit
Load the pretrained SqueezeNet model. This model has been ported from PyTorch, see cs231n/classifiers/squeezenet.py for the model architecture. To use SqueezeNet, you will need to first download the weights by changing into the cs231n/datasets directory and running get_squeezenet_tf.sh . Note that if you ran get_assig...
from cs231n.classifiers.squeezenet import SqueezeNet import tensorflow as tf tf.reset_default_graph() # remove all existing variables in the graph sess = get_session() # start a new Session # Load pretrained SqueezeNet model SAVE_PATH = 'cs231n/datasets/squeezenet.ckpt' if not os.path.exists(SAVE_PATH): raise Va...
cs231n/assignment3/StyleTransfer-TensorFlow.ipynb
kabrapratik28/Stanford_courses
apache-2.0
Computing Loss We're going to compute the three components of our loss function now. The loss function is a weighted sum of three terms: content loss + style loss + total variation loss. You'll fill in the functions that compute these weighted terms below. Content loss We can generate an image that reflects the content...
def content_loss(content_weight, content_current, content_original): """ Compute the content loss for style transfer. Inputs: - content_weight: scalar constant we multiply the content_loss by. - content_current: features of the current image, Tensor with shape [1, height, width, channels] -...
cs231n/assignment3/StyleTransfer-TensorFlow.ipynb
kabrapratik28/Stanford_courses
apache-2.0
Test your content loss. You should see errors less than 0.001.
def content_loss_test(correct): content_layer = 3 content_weight = 6e-2 c_feats = sess.run(model.extract_features()[content_layer], {model.image: content_img_test}) bad_img = tf.zeros(content_img_test.shape) feats = model.extract_features(bad_img)[content_layer] student_output = sess.run(content...
cs231n/assignment3/StyleTransfer-TensorFlow.ipynb
kabrapratik28/Stanford_courses
apache-2.0
Style loss Now we can tackle the style loss. For a given layer $\ell$, the style loss is defined as follows: First, compute the Gram matrix G which represents the correlations between the responses of each filter, where F is as above. The Gram matrix is an approximation to the covariance matrix -- we want the activatio...
def gram_matrix(features, normalize=True): """ Compute the Gram matrix from features. Inputs: - features: Tensor of shape (1, H, W, C) giving features for a single image. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram matrix by the number of n...
cs231n/assignment3/StyleTransfer-TensorFlow.ipynb
kabrapratik28/Stanford_courses
apache-2.0
Test your Gram matrix code. You should see errors less than 0.001.
def gram_matrix_test(correct): gram = gram_matrix(model.extract_features()[5]) student_output = sess.run(gram, {model.image: style_img_test}) error = rel_error(correct, student_output) print('Maximum error is {:.3f}'.format(error)) gram_matrix_test(answers['gm_out'])
cs231n/assignment3/StyleTransfer-TensorFlow.ipynb
kabrapratik28/Stanford_courses
apache-2.0
Next, implement the style loss:
def style_loss(feats, style_layers, style_targets, style_weights): """ Computes the style loss at a set of layers. Inputs: - feats: list of the features at every layer of the current image, as produced by the extract_features function. - style_layers: List of layer indices into feats givi...
cs231n/assignment3/StyleTransfer-TensorFlow.ipynb
kabrapratik28/Stanford_courses
apache-2.0