markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Again, we can commit such changes to the repository using the git commit -m "message" command. | !git commit -m "added one more line in README" README
!git status | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Removing files
To remove file that has been added to the repository, use git rm filename, which works similar to git add filename: | %%file tmpfile
A short-lived file. | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Add it: | !git add tmpfile
!git commit -m "adding file tmpfile" tmpfile | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Remove it again: | !git rm tmpfile
!git commit -m "remove file tmpfile" tmpfile | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Commit logs
The messages that are added to the commit command are supposed to give a short (often one-line) description of the changes/additions/deletions in the commit. If the -m "message" is omitted when invoking the git commit message an editor will be opened for you to type a commit message (for example useful when... | !git log | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
In the commit log, each revision is shown with a timestampe, a unique has tag that, and author information and the commit message.
Diffs
All commits results in a changeset, which has a "diff" describing the changes to the file associated with it. We can use git diff so see what has changed in a file: | %%file README
A file with information about the gitdemo repository.
README files usually contains installation instructions, and information about how to get started using the software (for example).
!git diff README | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
That looks quite cryptic but is a standard form for describing changes in files. We can use other tools, like graphical user interfaces or web based systems to get a more easily understandable diff.
In github (a web-based GIT repository hosting service) it can look like this: | Image(filename='images/github-diff.png') | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Discard changes in the working directory
To discard a change (revert to the latest version in the repository) we can use the checkout command like this: | !git checkout -- README
!git status | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Checking out old revisions
If we want to get the code for a specific revision, we can use "git checkout" and giving it the hash code for the revision we are interested as argument: | !git log
!git checkout 1f26ad648a791e266fbb951ef5c49b8d990e6461 | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Now the content of all the files like in the revision with the hash code listed above (first revision) | !cat README | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
We can move back to "the latest" (master) with the command: | !git checkout master
!cat README
!git status | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Tagging and branching
Tags
Tags are named revisions. They are useful for marking particular revisions for later references. For example, we can tag our code with the tag "paper-1-final" when when simulations for "paper-1" are finished and the paper submitted. Then we can always retreive the exactly the code used for th... | !git log
!git tag -a demotag1 -m "Code used for this and that purpuse"
!git tag -l
!git show demotag1 | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
To retreive the code in the state corresponding to a particular tag, we can use the git checkout tagname command:
$ git checkout demotag1
Branches
With branches we can create diverging code bases in the same repository. They are for example useful for experimental development that requires a lot of code changes that c... | !git branch expr1 | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
We can list the existing branches like this: | !git branch | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
And we can switch between branches using checkout: | !git checkout expr1 | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Make a change in the new branch. | %%file README
A file with information about the gitdemo repository.
README files usually contains installation instructions, and information about how to get started using the software (for example).
Experimental addition.
!git commit -m "added a line in expr1 branch" README
!git branch
!git checkout master
!git... | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
We can merge an existing branch and all its changesets into another branch (for example the master branch) like this:
First change to the target branch: | !git checkout master
!git merge expr1
!git branch | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
We can delete the branch expr1 now that it has been merged into the master: | !git branch -d expr1
!git branch
!cat README | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
pulling and pushing changesets between repositories
If the respository has been cloned from another repository, for example on github.com, it automatically remembers the address of the parant repository (called origin): | !git remote
!git remote show origin | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
pull
We can retrieve updates from the origin repository by "pulling" changesets from "origin" to our repository: | !git pull origin | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
We can register addresses to many different repositories, and pull in different changesets from different sources, but the default source is the origin from where the repository was first cloned (and the work origin could have been omitted from the line above).
push
After making changes to our local repository, we can ... | !git status
!git add Lecture-7-Revision-Control-Software.ipynb
!git commit -m "added lecture notebook about RCS" Lecture-7-Revision-Control-Software.ipynb
!git push | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Hosted repositories
Github.com is a git repository hosting site that is very popular with both open source projects (for which it is free) and private repositories (for which a subscription might be needed).
With a hosted repository it easy to collaborate with colleagues on the same code base, and you get a graphical u... | Image(filename='images/github-project-page.png') | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
Graphical user interfaces
There are also a number of graphical users interfaces for GIT. The available options vary a little bit from platform to platform:
http://git-scm.com/downloads/guis | Image(filename='images/gitk.png') | material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb | geography-munich/sciprog | apache-2.0 |
So now what? What does this mean? Correlation uses information about the variance of X and Y to normalize this metric. Once we've normalized the metric to the -1 to 1 scale, we can make meaningful statements and compare correlations.
To see how this is done consider the formula.
$$\frac{Cov(X, Y)}{std(X)std(Y)}$$
$$= \... | X = np.random.rand(50)
Y = 2 * X + 4
print 'Covariance of X and Y: \n' + str(np.cov(X, Y))
print 'Correlation of X and Y: \n' + str(np.corrcoef(X, Y)) | notebooks/lectures/Linear_Correlation_Analysis/notebook.ipynb | quantopian/research_public | apache-2.0 |
Why do both np.cov and np.corrcoef return matrices?
The covariance matrix is an important concept in statistics. Often people will refer to the covariance of two variables $X$ and $Y$, but in reality that is just one entry in the covariance matrix of $X$ and $Y$. For each input variable we have one row and one column. ... | cov_matrix = np.cov(X, Y)
# We need to manually set the degrees of freedom on X to 1, as numpy defaults to 0 for variance
# This is usually fine, but will result in a slight mismatch as np.cov defaults to 1
error = cov_matrix[0, 0] - X.var(ddof=1)
print 'error: ' + str(error)
X = np.random.rand(50)
Y = np.random.ran... | notebooks/lectures/Linear_Correlation_Analysis/notebook.ipynb | quantopian/research_public | apache-2.0 |
Now let's see what two correlated sets of data look like. | X = np.random.rand(50)
Y = X + np.random.normal(0, 0.1, 50)
plt.scatter(X,Y)
plt.xlabel('X Value')
plt.ylabel('Y Value')
print 'Correlation: ' + str(np.corrcoef(X, Y)[0, 1]) | notebooks/lectures/Linear_Correlation_Analysis/notebook.ipynb | quantopian/research_public | apache-2.0 |
Let's dial down the relationship by introducing more noise. | X = np.random.rand(50)
Y = X + np.random.normal(0, .2, 50)
plt.scatter(X,Y)
plt.xlabel('X Value')
plt.ylabel('Y Value')
print 'Correlation: ' + str(np.corrcoef(X, Y)[0, 1]) | notebooks/lectures/Linear_Correlation_Analysis/notebook.ipynb | quantopian/research_public | apache-2.0 |
Finally, let's see what an inverse relationship looks like. | X = np.random.rand(50)
Y = -X + np.random.normal(0, .1, 50)
plt.scatter(X,Y)
plt.xlabel('X Value')
plt.ylabel('Y Value')
print 'Correlation: ' + str(np.corrcoef(X, Y)[0, 1]) | notebooks/lectures/Linear_Correlation_Analysis/notebook.ipynb | quantopian/research_public | apache-2.0 |
We see a little bit of rounding error, but they are clearly the same value.
How is this useful in finance?
Determining related assets
Once we've established that two series are probably related, we can use that in an effort to predict future values of the series. For example, let's look at the price of Apple and a semi... | # Pull the pricing data for our two stocks and S&P 500
start = '2013-01-01'
end = '2015-01-01'
bench = get_pricing('SPY', fields='price', start_date=start, end_date=end)
a1 = get_pricing('LRCX', fields='price', start_date=start, end_date=end)
a2 = get_pricing('AAPL', fields='price', start_date=start, end_date=end)
plt... | notebooks/lectures/Linear_Correlation_Analysis/notebook.ipynb | quantopian/research_public | apache-2.0 |
Constructing a portfolio of uncorrelated assets
Another reason that correlation is useful in finance is that uncorrelated assets produce the best portfolios. The intuition for this is that if the assets are uncorrelated, a drawdown in one will not correspond with a drawdown in another. This leads to a very stable retur... | rolling_correlation = pd.rolling_corr(a1, a2, 60)
plt.plot(rolling_correlation)
plt.xlabel('Day')
plt.ylabel('60-day Rolling Correlation') | notebooks/lectures/Linear_Correlation_Analysis/notebook.ipynb | quantopian/research_public | apache-2.0 |
Non-Linear Relationships
The correlation coefficient can be useful for examining the strength of the relationship between two variables. However, it's important to remember that two variables may be associated in different, predictable ways which this analysis would not pick up. For instance, one variable might precise... | X = np.random.rand(100)
Y = X + np.random.poisson(size=100)
plt.scatter(X, Y)
np.corrcoef(X, Y)[0, 1] | notebooks/lectures/Linear_Correlation_Analysis/notebook.ipynb | quantopian/research_public | apache-2.0 |
=========================================
Reading/Writing a noise covariance matrix
=========================================
Plot a noise covariance matrix. | # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
from os import path as op
import mne
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_evo = op.join(data_path,... | 0.17/_downloads/73d54262ed918b5836ccb242d27450bb/plot_read_noise_covariance_matrix.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Show covariance | cov.plot(evoked.info, exclude='bads', show_svd=False) | 0.17/_downloads/73d54262ed918b5836ccb242d27450bb/plot_read_noise_covariance_matrix.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Validate lab package version installation | !python -c "import tfx; print('TFX version: {}'.format(tfx.__version__))"
!python -c "import kfp; print('KFP version: {}'.format(kfp.__version__))" | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Note: this lab was built and tested with the following package versions:
TFX version: 0.25.0
KFP version: 1.0.4
(Optional) If running the above command results in different package versions or you receive an import error, upgrade to the correct versions by running the cell below: | %pip install --upgrade --user tfx==0.25.0
%pip install --upgrade --user kfp==1.0.4 | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Note: you may need to restart the kernel to pick up the correct package versions.
Validate creation of AI Platform Pipelines cluster
Navigate to AI Platform Pipelines page in the Google Cloud Console.
Note you may have already deployed an AI Pipelines instance during the Setup for the lab series. If so, you can proceed... | %cd pipeline
!ls -la | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
The config.py module configures the default values for the environment specific settings and the default values for the pipeline runtime parameters.
The default values can be overwritten at compile time by providing the updated values in a set of environment variables. You will set custom environment variables later o... | # Use the following command to identify the GCS bucket for metadata and pipeline storage.
!gsutil ls | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
CUSTOM_SERVICE_ACCOUNT - In the gcp console Click on the Navigation Menu. Navigate to IAM & Admin, then to Service Accounts and use the service account starting with prefix - 'tfx-tuner-caip-service-account'. This enables CloudTuner and the Google Cloud AI Platform extensions Tuner component to work together and al... | #TODO: Set your environment resource settings here for GCP_REGION, ARTIFACT_STORE_URI, ENDPOINT, and CUSTOM_SERVICE_ACCOUNT.
GCP_REGION = 'us-central1'
ARTIFACT_STORE_URI = 'gs://dougkelly-sandbox-kubeflowpipelines-default' #Change
ENDPOINT = '6f857f6a72ef2a99-dot-us-central2.pipelines.googleusercontent.com' #Change
CU... | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Set the compile time settings to first create a pipeline version without hyperparameter tuning
Default pipeline runtime environment values are configured in the pipeline folder config.py. You will set their values directly below:
PIPELINE_NAME - the pipeline's globally unique name. For each pipeline update, each pipe... | PIPELINE_NAME = 'tfx_covertype_continuous_training'
MODEL_NAME = 'tfx_covertype_classifier'
DATA_ROOT_URI = 'gs://workshop-datasets/covertype/small'
CUSTOM_TFX_IMAGE = 'gcr.io/{}/{}'.format(PROJECT_ID, PIPELINE_NAME)
RUNTIME_VERSION = '2.3'
PYTHON_VERSION = '3.7'
USE_KFP_SA=False
ENABLE_TUNING=False
%env PIPELINE_NAME... | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Compile your pipeline code
You can build and upload the pipeline to the AI Platform Pipelines instance in one step, using the tfx pipeline create command. The tfx pipeline create goes through the following steps:
- (Optional) Builds the custom image to that provides a runtime environment for TFX components or uses the ... | !tfx pipeline compile --engine kubeflow --pipeline_path runner.py | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Note: you should see a {PIPELINE_NAME}.tar.gz file appear in your current pipeline directory.
Exercise: deploy your pipeline container to AI Platform Pipelines with TFX CLI
After the pipeline code compiles without any errors you can use the tfx pipeline create command to perform the full build and deploy the pipeline. ... | # TODO: Your code here to use the TFX CLI to deploy your pipeline image to AI Platform Pipelines.
!tfx pipeline create \
--pipeline_path=runner.py \
--endpoint={ENDPOINT} \
--build_target_image={CUSTOM_TFX_IMAGE} | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Hint: review the TFX CLI documentation on the "pipeline group" to create your pipeline. You will need to specify the --pipeline_path to point at the pipeline DSL and runner defined locally in runner.py, --endpoint, and --build_target_image arguments using the environment variables specified above.
Note: you should see ... | # TODO: your code here to trigger a pipeline run with the TFX CLI
!tfx run create --pipeline_name={PIPELINE_NAME} --endpoint={ENDPOINT} | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
To view the status of existing pipeline runs: | !tfx run list --pipeline_name {PIPELINE_NAME} --endpoint {ENDPOINT} | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
To retrieve the status of a given run: | RUN_ID='[YOUR RUN ID]'
!tfx run status --pipeline_name {PIPELINE_NAME} --run_id {RUN_ID} --endpoint {ENDPOINT} | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Important
A full pipeline run without tuning enabled will take about 40 minutes to complete. You can view the run's progress using the TFX CLI commands above or in the
Exercise: deploy a pipeline version with tuning enabled
Incorporating automatic model hyperparameter tuning into a continuous training TFX pipeline work... | ENABLE_TUNING=True
%env ENABLE_TUNING={ENABLE_TUNING} | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Compile your pipeline code | !tfx pipeline compile --engine kubeflow --pipeline_path runner.py | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Deploy your pipeline container to AI Platform Pipelines with the TFX CLI | #TODO: your code to update your pipeline
!tfx pipeline update --pipeline_path runner.py --endpoint {ENDPOINT} | workshops/tfx-caip-tf23/lab-02-tfx-pipeline/solutions/lab-02.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Assets
we need to get the following assets into the local directory for the code to run (once the assets are there the wget statements can be commented out) | !wget http://blogs.oditorium.com/technology/wp-content/uploads/2014/08/logo-oditorium-whitebg.jpg
!wget http://blogs.oditorium.com/technology/wp-content/uploads/2014/08/graph.png | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
2. Reportlab - canvas
Writing text to the canvas
This code fragment generates a one-page file t1.pdf with some text lines written onto it using drawString | from reportlab.pdfgen import canvas
msg = "This is not a message"
c = canvas.Canvas("test1.pdf")
for i in range(1,10):
c.drawString(50*i,50*i,msg)
c.showPage()
c.save()
!ls -l test1.pdf | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
Writing images from disk to the canvas
The function drawImage writes an image from disk to the canvas. An image written that way is stored in the pdf file only once, which makes this important for multiple-use images, eg logos. There is another function drawInlineImage that places an image directly into the pdf flow. ... | msg = "This is really not a message"
c = canvas.Canvas("test2.pdf")
for i in range(1,10):
c.drawString(50*i,50*i,msg)
c.drawImage('graph.png',100,100)
c.showPage()
c.save()
!ls -l test2.pdf | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
Writing images to the canvas on the fly
Often we generate images on the fly - eg using matplotlib - and dont want to save them to include them. The following code shows how this is done source | import matplotlib.pyplot as plt
from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
from reportlab.lib.utils import ImageReader
fig = plt.figure(figsize=(4, 3))
plt.plot([1,4,3,2])
plt.ylabel('some numbers')
imgdata = BytesIO()
fig.savefig(imgdata, format='png')
imgdata... | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
3. Reportlab - platypus
Platypus is reportlab's layout engine (see the user guide from page 59). It defines the following hierarchy of templates
DocTemplate - a DocTemplate describes the overall document
PageTemplate - a PageTemplate describes a page in the document; usually different pages of the same document sha... | def lipsum():
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ultrices ligula et libero tempus, ac pretium velit ultricies. Pellentesque sit amet vestibulum quam. Maecenas turpis ante, feugiat eu ultricies feugiat, ultricies ac elit. Praesent eleifend, nibh eu tempor consequat, nisi nunc he... | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
Flowables and frames
It is possible to construct a document solely based on flowables and frames | !rm test5.pdf
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph, Frame
styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']
story = []
story.append(Paragraph("Thi... | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
Two column layout
source | from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, PageBreak, PageTemplate
from reportlab.lib.styles import getSampleStyleSheet
import random
words = "lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et".split()
styles=getSampleStyleSheet()
story=[... | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
Mixed layout, one and two cols, title and back
source | from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, NextPageTemplate, PageBreak, PageTemplate, Image
from reportlab.lib.units import inch
from reportlab.lib.styles import getSampleStyleSheet
doc = BaseDocTemplate('test7.pdf',showBoundary=1)
styles=getSampleStyleSheet()
story=[]
def static_title(canvas,d... | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
Landscape | from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, NextPageTemplate, PageBreak, FrameBreak, PageTemplate, Image
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import A4, A5, landscape, portrait
from reportlab.lib.styles import getSampleStyleSheet
doc = BaseDocTemplate('test8.pdf',show... | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
HTTPServer
to get access to the whole current directory, uncomment the below line and navigate the browser to this server's IP address at port :8080 (note that this command is blocking and needs to be interrupted using the command in the Kernel menu above; this is a feature not a bug, because the server should be only ... | #!python -m SimpleHTTPServer 8080
#!netstat -tulpn
#!kill 25239 | iPython/ReportLab1-Intro.ipynb | oditorium/blog | agpl-3.0 |
Configuración
Para una adecuada identificación de nuestros aportes en los repositorios, es necesario configurar nuestro nombre y correo en git.
git config --global user.name "YOUR NAME"
git config --global user.email "YOUR EMAIL ADDRESS"
Creación de repositorios
Una vez creada la cuenta github, debe crear un reposit... | %%bash
git clone https://github.com/cosmoscalibur/herramientas_computacionales.git herramientas | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
De esta forma crearemos una copia del repositorio git herramientas_computacionales en el directorio ./herramientas. Si no se indica el directorio, se crea un directorio nuevo en la posición actual.
Tras el clonado, tenemos a disposición todo el directorio del repositorio, incluido el directorio .git que almacena la i... | %%bash
cd herramientas
ls -oha | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Se evidencia que tras el clonado, tenemos configurados los repositorios remotos por defecto. | %%bash
cd herramientas
git remote -v | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
En caso de ser un repositorio nuevo o desear reinicializar (aceptar nuevas plantillas o mover el directorio), debemos crear el directorio .git y agregar los elementos que teniamos en nuestro directorio. Siempre que se agreguen (o se realiza cualquier actualización de los archivos y directorios, se sugiere realizar un c... | %%bash
cd herramientas
git init | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Repositorios remotos
Una vez se inicializa o se clona, podemos agregar nuestro reposotorio remoto, que previamente fue creado en github o bitbucket. Si solo se desea un uso local o si es justo el repositorio clonado no será necesario. | %%bash
cd herramientas
git remote add pruebas https://github.com/cosmoscalibur/pruebas.git
git remote -v | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Tambien es posible eliminar el acceso al servidor remoto, con git remote rm. | %%bash
cd herramientas
git remote rm origin
git remote -v | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Objetos y referencias
A continuación, y para evitar posibles conflictos de los archivos, es recomendable iniciar con un fetch o pull para obtener los objetos y referencias del repositorio remoto (esto si creamos el repositorio con los archivos de licencia y README.md que nos invita a crear el servicio git), y hacer la ... | %%bash
cd herramientas
echo "linea 1" > probar_1
printf "s\n 5" > probar_2 | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Aunque en este caso es claro que nuestros archivos no se encuentran agregados al repositorio, consultaremos por el estado de los archivos frente a su registro en el repositorio. | %%bash
cd herramientas
git status | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Ahora agregamos al registro los archivos de nuestro repositorio local. | %%bash
cd herramientas
git add . # Con la indicación "." agrega todo.
git commit -m "Agregados archivos de prueba 1 y 2." | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Realizaremos una modificación en uno de los archivos y agregaremos directamente a este. | %%bash
cd herramientas
echo "linea 2" >> probar_1
printf "otro\narchivo\npara probar." > probar_3
git add probar_1 probar_3
git commit -m "Actualizado prueba 1 y agregado prueba 3." | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Es posible indicar directamente a git la eliminación de archivos mediante
git rm archivo
o tambien al eliminar el archivo de manera directa, se incluye en git
git add -A
con el fin de actualizar el arbol de archivos y rastrear incluso los archivos eliminados. Sin embargo, es recomendable que la adición y remoción de ... | %%bash
cd herramientas
git push pruebas master | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Durante la ejecución del push se nos solicitará el usuario y contraseña de nuestra cuenta en el servicio git. Al usar el protocolo https por defecto tendremos 3600 segundos tras cada autenticación, o si lo preferimos podemos usar ssh y crear la llave de autenticación con el fin de tener acceso permanente en nuestro equ... | %%bash
cd herramientas
git log --oneline
%%bash
cd herramientas
git show d193ae6
%%bash
cd herramientas
echo "Actual"
ls
git checkout e4a4be5
echo "Anterior"
ls
git checkout master
%%bash
cd herramientas
echo "Actual"
cat probar_1
git checkout d193ae6 probar_1
echo "Anterior"
cat probar_1
git checkout HEAD probar_1 | Presentaciones/Notas/06_Versionamiento_git.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Message Threads
Forchan messages are all part of a message thread, which can be reassembled by following the parents for each post and chaining them back together. This code creates a thread ID and maps that thread ID to the corresponding messages.
I don't know currently whether or not messages are linear, or if they... | threads = full['parent'].unique()
full_text = {}
for thread in threads:
full_text[int(thread)] = ". ".join(full[full['parent'] == thread]['text']) | exploratory_notebooks/4chan_sample_thread_exploration.ipynb | jss367/assemble | mit |
Now we can do some topic modeling on the different threads
Following along with the topic modelling tweet exploration, we're going to tokenize our messages and then build a corpus from it. We'll then use the gensim library to run our topic model over the tokenized messages | import gensim
import pyLDAvis.gensim as gensimvis
import pyLDAvis
tokenized_messages = []
for msg in nlp.pipe(full['text'], n_threads = 100, batch_size = 100):
ents = msg.ents
msg = [token.lemma_ for token in msg if token.is_alpha and not token.is_stop]
tokenized_messages.append(msg)
# Build the corpus us... | exploratory_notebooks/4chan_sample_thread_exploration.ipynb | jss367/assemble | mit |
Creating an Emotion Sentiment Classifier
Labeled dataset provided by @crowdflower hosted on data.world. Dataset contains 40,000 tweets which are labeled as one of 13 emotions. Here I looked at the top 5 emotions, since the bottom few had very tweets by comparison, so it would be hard to get a properly split dataset on ... | import nltk
from nltk.classify import NaiveBayesClassifier
from nltk.classify import accuracy
from nltk import WordNetLemmatizer
lemma = nltk.WordNetLemmatizer()
df = pd.read_csv('https://query.data.world/s/8c7bwy8c55zx1t0c4yyrnjyax')
emotions = list(df.groupby("sentiment").agg("count").sort_values(by = "content", asc... | exploratory_notebooks/4chan_sample_thread_exploration.ipynb | jss367/assemble | mit |
64% test accuracy on the test is nothing to phone home about. It's also likely to be a lot less accurate on our data from the 4chan messages, since those will be using much different language than the messages in our training set. | emotion_classifier.show_most_informative_features()
for comment in full['text'].head(10):
print(emotion_classifier.classify(format_sentence(comment)), ": ", comment) | exploratory_notebooks/4chan_sample_thread_exploration.ipynb | jss367/assemble | mit |
Looking at this sample of 10 posts, I'm not convinced in the accuracy of this classifier on the far-right data, but out of curiosity, what did it classifer the | full['emotion'] = full['text'].apply(lambda x: emotion_classifier.classify(format_sentence(x)))
grouped_emotion_messages = full.groupby('emotion').count()[[2]]
grouped_emotion_messages.columns = ["count"]
grouped_emotion_messages
grouped_emotion_messages.plot.bar() | exploratory_notebooks/4chan_sample_thread_exploration.ipynb | jss367/assemble | mit |
Example 4
Can also do more complicated arithmetic: | # Convert Celsius to Fahrenheit
celsius = [0,10,20.1,34.5]
fahrenheit = [ ((float(9)/5)*temp + 32) for temp in Celsius ]
fahrenheit | PythonBootCamp/Complete-Python-Bootcamp-master/List Comprehensions.ipynb | yashdeeph709/Algorithms | apache-2.0 |
R-style formula
| 기호 | 설명 |
|-|-|
|+| 설명 변수 추가 |
|-| 설명 변수 제거 |
|1, 0| intercept. (제거시 사용) |
|:| interaction (곱) |
|*| a*b = a + b + a:b |
|/| a/b = a + a:b |
|~| 종속 - 독립 관계 | | dmatrix("x1 - 1")
dmatrix("x1 + 0")
dmatrix("x1 + x2")
dmatrix("x1 + x2 - 1")
df = pd.DataFrame(np.array([x1, x2]).T, columns=["x1", "x2"])
df
dmatrix("x1 + x2 - 1", data=df) | Lecture/14. 선형 회귀 분석/8) patsy 패키지 소개.ipynb | junhwanjang/DataSchool | mit |
변환(Transform)
numpy 함수 이름 사용 가능
사용자 정의 함수 사용 가능
patsy 전용 함수 이름 사용 가능
center(x)
standardize(x)
scale(x) | dmatrix("x1 + np.log(np.abs(x2))", data=df)
def doubleit(x):
return 2 * x
dmatrix("doubleit(x1)", data=df)
dmatrix("center(x1) + standardize(x2)", data=df) | Lecture/14. 선형 회귀 분석/8) patsy 패키지 소개.ipynb | junhwanjang/DataSchool | mit |
변수 보호 I()
다른 formula 기호로부터 보호 | dmatrix("x1 + x2", data=df)
dmatrix("I(x1 + x2)", data=df) | Lecture/14. 선형 회귀 분석/8) patsy 패키지 소개.ipynb | junhwanjang/DataSchool | mit |
다항 선형 회귀 | dmatrix("x1 + I(x1**2) + I(x1**3) + I(x1**4)", data=df) | Lecture/14. 선형 회귀 분석/8) patsy 패키지 소개.ipynb | junhwanjang/DataSchool | mit |
카테고리 변수 | df["a1"] = pd.Series(["a1", "a1", "a2", "a2", "a3", "a5"])
df["a2"] = pd.Series([1, 4, 5, 6, 8, 9])
df
dmatrix("a1", data=df)
dmatrix("a2", data=df)
dmatrix("C(a2)", data=df) | Lecture/14. 선형 회귀 분석/8) patsy 패키지 소개.ipynb | junhwanjang/DataSchool | mit |
Say $f(t) = t * exp(- t)$, and $F(s)$ is the Laplace transform of $f(t)$. Let us first evaluate this transform using sympy. | t, f, s, F = variables('t, f, s, F')
model = Model({f: t * exp(- t)})
laplace_model = Model(
{F: laplace_transform(model[f], t, s, noconds=True)}
)
print(laplace_model)
| docs/examples/ex_tikhonov.ipynb | tBuLi/symfit | mit |
Suppose we are confronted with a dataset $F(s)$, but we need to know $f(t)$. This means an inverse Laplace transform has to be performed. However, numerically this operation is ill-defined. In order to solve this, Tikhonov regularization can be performed.
To demonstrate this, we first generate mock data corresponding t... | epsilon = 0.01 # 1 percent noise
s_data = np.linspace(0, 10, 101)
F_data = laplace_model(s=s_data).F
F_sigma = epsilon * F_data
np.random.seed(2)
F_data = np.random.normal(F_data, F_sigma)
plt.errorbar(s_data, F_data, yerr=F_sigma, fmt='none', label=r'$\mathcal{L}[f] = F(s)$')
plt.xlabel(r'$s_i$')
plt.ylabel(r'$F(s_i... | docs/examples/ex_tikhonov.ipynb | tBuLi/symfit | mit |
We will now invert this data, using the procedure outlined in \cite{}. | N_s = symbols('N_s', integer=True) # Number of s_i points
M = MatrixSymbol('M', N_s, N_s)
W = MatrixSymbol('W', N_s, N_s)
Fs = MatrixSymbol('Fs', N_s, 1)
c = MatrixSymbol('c', N_s, 1)
d = MatrixSymbol('d', 1, 1)
I = MatrixSymbol('I', N_s, N_s)
a, = parameters('a')
model_dict = {
W: Inverse(I + M / a**2),
c: ... | docs/examples/ex_tikhonov.ipynb | tBuLi/symfit | mit |
A CallableModel is needed because derivatives of matrix expressions sometimes cause problems.
Build required matrices, ignore s=0 because it causes a singularity. | I_mat = np.eye(len(s_data[1:]))
s_i, s_j = np.meshgrid(s_data[1:], s_data[1:])
M_mat = 1 / (s_i + s_j)
delta = np.atleast_2d(np.linalg.norm(F_sigma))
print('d', delta)
| docs/examples/ex_tikhonov.ipynb | tBuLi/symfit | mit |
Perform the fit | model_data = {
I.name: I_mat,
M.name: M_mat,
Fs.name: F_data[1:],
}
all_data = dict(**model_data, **{d.name: delta})
fit = Fit(tikhonov_model, **all_data)
fit_result = fit.execute()
print(fit_result)
| docs/examples/ex_tikhonov.ipynb | tBuLi/symfit | mit |
Check the quality of the reconstruction | ans = tikhonov_model(**model_data, **fit_result.params)
F_re = - M_mat.dot(ans.c) / fit_result.value(a)**2
print(ans.c.shape, F_re.shape)
plt.errorbar(s_data, F_data, yerr=F_sigma, label=r'$F(s)$', fmt='none')
plt.plot(s_data[1:], F_re, label=r'$F_{re}(s)$')
plt.xlabel(r'$x$')
plt.xlabel(r'$F(s)$')
plt.xlim(0, None)
p... | docs/examples/ex_tikhonov.ipynb | tBuLi/symfit | mit |
Reconstruct $f(t)$ and compare with the known original. | t_data = np.linspace(0, 10, 101)
f_data = model(t=t_data).f
f_re_func = lambda x: - np.exp(- x * s_data[1:]).dot(ans.c) / fit_result.value(a)**2
f_re = [f_re_func(t_i) for t_i in t_data]
plt.axhline(0, color='black')
plt.axvline(0, color='black')
plt.plot(t_data, f_data, label=r'$f(t)$')
plt.plot(t_data, f_re, label=r... | docs/examples/ex_tikhonov.ipynb | tBuLi/symfit | mit |
Imports | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from ggplot import * | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
Read data | df = pd.read_csv("data/babynames.csv") | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
Basic statistics
Looking at the first samples: | df.head() | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
How many unique names are collected? | (df['name'].nunique(), df['name'].size)
df['name'].nunique() / float(df['name'].size) | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
We might thhink that approx. 20 entries per name are collected. Should it be equal to the length of the years period? | df['year'].max() - df['year'].min() | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
Not really. That means there are many zero entries in n column for many names.
Filter
By a single name | df['name'].isin(['Andrew']).value_counts()
df.query('name == "Andrew"').shape
ggplot(df.query('name == "Joe"'), aes(x = 'year', y = 'n')) + geom_point() + ggtitle("name: Joe") | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
Don't forget the names are given for two genders. | ggplot(df.query('name == "Joe"'), aes(x = 'year', y = 'n', color = 'sex')) +\
geom_point(size = 10) + geom_smooth(span = 0.1) + ggtitle("name: Joe") | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
Joe as a name for girls seems to be OK. What about Mary? | ggplot(df.query('name == "Mary"'), aes(x = 'year', y = 'n', color = 'sex')) +\
geom_point(size = 10) + geom_smooth(span = 0.1) + ggtitle("name: Mary") | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
Name Mary for boys? Let's do a bit more subsetting by n < 500 filter. | ggplot(df.query('name == "Mary" & n < 500'), aes(x = 'year', y = 'n', color = 'sex')) +\
geom_point(size = 10) + geom_smooth(span = 0.1) + ggtitle("name: Mary, n < 500") | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
Now let's get a record, where the number of female names Mary was the maximum. | ind = np.argmax(df.query('name == "Mary" & sex == "M"')['n'])
ind
df.query('index == @ind') | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
By multiple names | df.query('name in ["Andrew", "Andrey"]').shape
anames = ['Andrew', 'Andrey', 'Andres', 'Andre', 'And']
df.query('name in @anames').shape
ggplot(df.query('name in @anames'), aes(x = 'year', y = 'n', color = 'name')) +\
geom_point(size = 10) + geom_smooth(span = 0.1) + facet_wrap("sex")
ggplot(df.query('name in @... | 02-intro-python/projects/pandas/babynames.ipynb | variani/study | cc0-1.0 |
The Shyft Environment
This next step is highly specific on how and where you have installed Shyft. If you have followed the guidelines at github, and cloned the three shyft repositories: i) shyft, ii) shyft-data, and iii) shyft-doc, then you may need to tell jupyter notebooks where to find shyft. Uncomment the relevant... | # try to auto-configure the path, -will work in all cases where doc and data
# are checked out at same level
shyft_data_path = path.abspath("../../../shyft-data")
if path.exists(shyft_data_path) and 'SHYFT_DATA' not in os.environ:
os.environ['SHYFT_DATA']=shyft_data_path
# shyft should be available either by i... | notebooks/nea-example/simulation-configured.ipynb | statkraft/shyft-doc | lgpl-3.0 |
2. Configuration of a SHyFT simulation
The following shows how to set up a Shyft simulation using the yaml_configs.YAMLSimConfig class. Note that this is a high level approach, providing a working example for a simple simulation. More advanced users will want to eventually make use of direct API calls, as outlined in P... | # set up configuration using *.yaml configuration files
# here is the *.yaml file that configures the simulation:
config_file_path = os.path.abspath("./nea-config/neanidelva_simulation.yaml")
# and here we pass it to the configurator, together with the name of the region
# stated in the simulation.yaml file (here... | notebooks/nea-example/simulation-configured.ipynb | statkraft/shyft-doc | lgpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.