markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Initial model | # Proposed Initial Model
xgb1 = xgb.XGBClassifier( learning_rate =0.1, n_estimators=200, max_depth=5,
min_child_weight=1, gamma=0, subsample=0.6,
colsample_bytree=0.6, reg_alpha=0, reg_lambda=1, objective='multi:softmax',
nthread=4, scale_pos... | HouMath/Face_classification_HouMath_XGB_01.ipynb | esa-as/2016-ml-contest | apache-2.0 |
The typical range for learning rate is around 0.01~0.2, so we vary ther learning rate a bit and at the same time, scan over the number of boosted trees to fit. This will take a little bit of time to finish. | print("Parameter optimization")
grid_search1 = GridSearchCV(xgb1,{'learning_rate':[0.05,0.01,0.1,0.2] , 'n_estimators':[200,400,600,800]},
scoring='accuracy' , n_jobs = 4)
grid_search1.fit(X_train,Y_train)
print("Best Set of Parameters")
grid_search1.grid_scores_, grid_search1.best_pa... | HouMath/Face_classification_HouMath_XGB_01.ipynb | esa-as/2016-ml-contest | apache-2.0 |
It seems that we need to adjust the learning rate and make it smaller, which could help to reduce overfitting in my opinion. The number of boosted trees to fit also requires to be updated. | # Proposed Model with optimized learning rate and number of boosted trees to fit
xgb2 = xgb.XGBClassifier( learning_rate =0.01, n_estimators=400, max_depth=5,
min_child_weight=1, gamma=0, subsample=0.6,
colsample_bytree=0.6, reg_alpha=0, reg_lambda=1, objective='multi... | HouMath/Face_classification_HouMath_XGB_01.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Try it out | U = 4 * 10** -np.arange(11.) # generates values 4, 4e-1, 4e-2 .. 4e-10
print("{:>10s} {:>10s} {:>10s}".format('u ', 'W(u)','W1(u) '))
for u in U:
print("{0:10.1e} {1:10.4e} {2:10.4e}".format(u, W(u), W1(u))) | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Is seems that our numerical integration is a fair approximation to four significant digits, but not better, even when computed with 1000 steps as we did. So it is relatively easy to create one's own numerically computed value of an analytical expression like the exponential integral
Theis well function as a power serie... | def W2(u):
"""Returns Theis well function computed as a power series"""
tol = 1e-5
w = -0.5772 -np.log(u) + u
a = u
for n in range(1, 100):
a = -a * u * n / (n+1)**2 # new term (next term)
w += a
if np.all(a) < tol:
return w | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Compare the three methods of computing the well function. | U = 4.0 * 10** -np.arange(11.) # generates values 4, 4e-1, 4e-2 .. 4e-10
print("{:>10s} {:>10s} {:>10s} {:>10s}".format('u ', 'W(u) ','W1(u) ', 'W2(u) '))
for u in U:
print("{0:10.1e} {1:10.4e} {2:10.4e} {2:10.4e}".format(u, W(u), W1(u), W2(u))) | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
We see that all three methods yiedld the same results.
Next we show the well function as it shown in groundwater hydrology books. | u = np.logspace(-7, 1, 71)
import matplotlib.pylab as plt
fig1= plt.figure()
ax1 = fig1.add_subplot(111)
ax1.set(xlabel='1/u', ylabel='W(u)', title='Theis type curve versus u', yscale='log', xscale='log')
ax1.grid(True)
ax1.plot(u, W(u), 'b', label='-expi(-u)')
#ax1.plot(u, W1(u), 'rx', label='integal') # works only f... | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
The curve W(u) versus u runs counter intuitively which and is, therefore, confusing. Therefore, it generally presented as W(u) versus 1/u instead as shown below | fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.set(xlabel='1/u', ylabel='W(u)', title='Theis type curve versus 1/u', yscale='log', xscale='log')
ax2.grid(True)
ax2.plot(1/u, W(u))
plt.show() | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Now W(u) resembles the actual drawdown, which increases with time.
The reason that this is so, becomes clear from the fact that
$$ u = \frac {r^2 S} {4 kD t} $$
and that
$$ \frac 1 u = \frac {4 kDt} {r^2 S} = \frac {4 kD} S \frac t {r^2} $$
which shows that $\frac 1 u$ increases with time, so that the values of $\frac ... | fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.set(xlabel='1/u', ylabel='W(u)', title='Theis type curve versus 1/u', yscale='linear', xscale='log')
ax2.grid(True)
ax2.plot(1/u, W(u))
ax2.invert_yaxis()
plt.show() | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Logarithmic approximaion of the Theis type curve
We see that after some time, the drawdown is linear when only the time-axis is logarithmic. This suggests that a logarithmic approximation of time-drawdown curve is accurate after some time.
That this is indeed the case can be deduced from the power series description of... | U = np.logspace(-2, 0, 21)
Wa = lambda u : -0.5772 - np.log(u)
print("{:>12s} {:>12s} {:>12s} {:>12s}".format('u','W(u)','Wa(u)','1-Wa(u)/W(u)'))
print("{:>12s} {:>12s} {:>12s} {:>12s}".format(' ',' ',' ','the error'))
for u in U:
print("{:12.3g} {:12.3g} {:12.3g} {:12.1%}".format(u, W(u), Wa(... | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Hence, in any practical situation, the logarithmic approximation is accurate enough when $u<0.01$.
The approximatin of the Theis type curve can no be elaborated:
$$ Wa (u) \approx -0.5772 - \ln(u) = \ln(e^{-0.5772}) - \ln(u) = \ln(0.5615) - \ln(u) = \ln \frac {0.5615} {u} $$
Because $u = \frac {r^2 S} {4 kD t}$ we have... | U = np.logspace(-7, 1, 81)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlabel='u', ylabel='W(u)', title='Theis type curve and its logarithmic approximation', yscale='linear', xscale='log')
ax.grid(True)
ax.plot(U, W(U), 'b', linewidth = 2., label='Theis type curve')
ax.plot(U, Wa(U), 'r', linewidth = 0.25, lab... | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
This shows that the radius of influence is limited. We can now approximate this radius of influence by saying that the radius is where the appoximated Theis curve, that is the straight red line in the graph intersects the zero drawdown, i.e. $W(u) = 0$.
Hence, for the radius of influence, R, we have
$$ \ln \frac {2.25 ... | # t[min], s[m]
H30 = [ [0.0, 0.0],
[0.1, 0.04],
[0.25, 0.08],
[0.50, 0.13],
[0.70, 0.18],
[1.00, 0.23],
[1.40, 0.28],
[1.90, 0.33],
[2.33, 0.36],
[2.80, 0.39],
[3.36, 0.42],
[4.00, 0.45],
[5.35, 0.50],
[6.80, ... | exercises_notebooks/TheisWellFunction.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Configure GCP environment settings
Update the following variables to reflect the values for your GCP environment:
PROJECT_ID: The ID of the Google Cloud project you are using to implement this solution.
PROJECT_NUMBER: The number of the Google Cloud project you are using to implement this solution. You can find this i... | PROJECT_ID = 'yourProject' # Change to your project.
PROJECT_NUMBER = 'yourProjectNumber' # Change to your project number
BUCKET = 'yourBucketName' # Change to the bucket you created.
REGION = 'yourPredictionRegion' # Change to your AI Platform Prediction region.
ARTIFACTS_REPOSITORY_NAME = 'ml-serving'
EMBEDDNIG_LOOK... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Authenticate your GCP account
This is required if you run the notebook in Colab. If you use an AI Platform notebook, you should already be authenticated. | try:
from google.colab import auth
auth.authenticate_user()
print("Colab user is authenticated.")
except: pass | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Deploy the embedding lookup model to AI Platform Prediction
Create the embedding lookup model resource in AI Platform: | !gcloud ai-platform models create {EMBEDDNIG_LOOKUP_MODEL_NAME} --region={REGION} | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Next, deploy the model: | !gcloud ai-platform versions create {EMBEDDNIG_LOOKUP_MODEL_VERSION} \
--region={REGION} \
--model={EMBEDDNIG_LOOKUP_MODEL_NAME} \
--origin={EMBEDDNIG_LOOKUP_MODEL_OUTPUT_DIR} \
--runtime-version=2.2 \
--framework=TensorFlow \
--python-version=3.7 \
--machine-type=n1-standard-2
print("The model version i... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Once the model is deployed, you can verify it in the AI Platform console.
Test the deployed embedding lookup AI Platform Prediction model
Set the AI Platform Prediction API information: | import googleapiclient.discovery
from google.api_core.client_options import ClientOptions
api_endpoint = f'https://{REGION}-ml.googleapis.com'
client_options = ClientOptions(api_endpoint=api_endpoint)
service = googleapiclient.discovery.build(
serviceName='ml', version='v1', client_options=client_options) | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Run the caip_embedding_lookup method to retrieve item embeddings. This method accepts item IDs, calls the embedding lookup model in AI Platform Prediction, and returns the appropriate embedding vectors. | def caip_embedding_lookup(input_items):
request_body = {'instances': input_items}
service_name = f'projects/{PROJECT_ID}/models/{EMBEDDNIG_LOOKUP_MODEL_NAME}/versions/{EMBEDDNIG_LOOKUP_MODEL_VERSION}'
print(f'Calling : {service_name}')
response = service.projects().predict(
name=service_name, body=request_b... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Test the caip_embedding_lookup method with three item IDs: | input_items = ['2114406', '2114402 2120788', 'abc123']
embeddings = caip_embedding_lookup(input_items)
print(f'Embeddings retrieved: {len(embeddings)}')
for idx, embedding in enumerate(embeddings):
print(f'{input_items[idx]}: {embedding[:5]}') | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
ScaNN matching service
The ScaNN matching service performs the following steps:
Receives one or more item IDs from the client.
Calls the embedding lookup model to fetch the embedding vectors of those item IDs.
Uses these embedding vectors to query the ANN index to find approximate nearest neighbor embedding vectors.
M... | !gcloud beta artifacts repositories create {ARTIFACTS_REPOSITORY_NAME} \
--location={REGION} \
--repository-format=docker
!gcloud beta auth configure-docker {REGION}-docker.pkg.dev --quiet | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Use Cloud Build to build the Docker container image
The container runs the gunicorn HTTP web server and executes the Flask app variable defined in the main.py module.
The container image to deploy to AI Platform Prediction is defined in a Dockerfile, as shown in the following code snippet:
```
FROM python:3.8-slim
COPY... | IMAGE_URL = f'{REGION}-docker.pkg.dev/{PROJECT_ID}/{ARTIFACTS_REPOSITORY_NAME}/{SCANN_MODEL_NAME}:{SCANN_MODEL_VERSION}'
PORT=5001
SUBSTITUTIONS = ''
SUBSTITUTIONS += f'_IMAGE_URL={IMAGE_URL},'
SUBSTITUTIONS += f'_PORT={PORT}'
!gcloud builds submit --config=index_server/cloudbuild.yaml \
--substitutions={SUBSTITUTI... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Run the following command to verify the container image has been built: | repository_id = f'{REGION}-docker.pkg.dev/{PROJECT_ID}/{ARTIFACTS_REPOSITORY_NAME}'
!gcloud beta artifacts docker images list {repository_id} | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Create a service account for AI Platform Prediction
Create a service account to run the custom container. This is required in cases where you want to grant specific permissions to the service account. | SERVICE_ACCOUNT_NAME = 'caip-serving'
SERVICE_ACCOUNT_EMAIL = f'{SERVICE_ACCOUNT_NAME}@{PROJECT_ID}.iam.gserviceaccount.com'
!gcloud iam service-accounts create {SERVICE_ACCOUNT_NAME} \
--description="Service account for AI Platform Prediction to access cloud resources." | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Grant the Cloud ML Engine (AI Platform) service account the iam.serviceAccountAdmin privilege, and grant the caip-serving service account the privileges required by the ScaNN matching service, which are storage.objectViewer and ml.developer. | !gcloud projects describe {PROJECT_ID} --format="value(projectNumber)"
!gcloud projects add-iam-policy-binding {PROJECT_ID} \
--role=roles/iam.serviceAccountAdmin \
--member=serviceAccount:service-{PROJECT_NUMBER}@cloud-ml.google.com.iam.gserviceaccount.com
!gcloud projects add-iam-policy-binding {PROJECT_ID} \
... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Deploy the custom container to AI Platform Prediction
Create the ANN index model resource in AI Platform: | !gcloud ai-platform models create {SCANN_MODEL_NAME} --region={REGION} | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Deploy the custom container to AI Platform prediction. Note that you use the env-vars parameter to pass environmental variables to the Flask application in the container. | HEALTH_ROUTE=f'/v1/models/{SCANN_MODEL_NAME}/versions/{SCANN_MODEL_VERSION}'
PREDICT_ROUTE=f'/v1/models/{SCANN_MODEL_NAME}/versions/{SCANN_MODEL_VERSION}:predict'
ENV_VARIABLES = f'PROJECT_ID={PROJECT_ID},'
ENV_VARIABLES += f'REGION={REGION},'
ENV_VARIABLES += f'INDEX_DIR={INDEX_DIR},'
ENV_VARIABLES += f'EMBEDDNIG_LOO... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Test the Deployed ScaNN Index Service
After deploying the custom container, test it by running the caip_scann_match method. This method accepts the parameter query_items, whose value is converted into a space-separated string of item IDs and treated as a single query. That is, a single embedding vector is retrieved fro... | from google.cloud import datastore
import requests
client = datastore.Client(PROJECT_ID)
def caip_scann_match(query_items, show=10):
request_body = {
'instances': [{
'query':' '.join(query_items),
'show':show
}]
}
service_name = f'projects/{PROJECT_ID}/models/{SCANN_MODEL_NAM... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Call the caip_scann_match method with five item IDs and request five match items for each: | songs = {
'2120788': 'Limp Bizkit: My Way',
'1086322': 'Jacques Brel: Ne Me Quitte Pas',
'833391': 'Ricky Martin: Livin\' la Vida Loca',
'1579481': 'Dr. Dre: The Next Episode',
'2954929': 'Black Sabbath: Iron Man'
}
for item_Id, desc in songs.items():
print(desc)
print("==================")
s... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
(Optional) Deploy the matrix factorization model to AI Platform Prediction
Optionally, you can deploy the matrix factorization model in order to perform exact item matching. The model takes Item1_Id as an input and outputs the top 50 recommended item2_Ids.
Exact matching returns better results, but takes significantly ... | BQ_DATASET_NAME = 'recommendations'
BQML_MODEL_NAME = 'item_matching_model'
BQML_MODEL_VERSION = 'v1'
BQML_MODEL_OUTPUT_DIR = f'gs://{BUCKET}/bqml/item_matching_model'
!bq --quiet extract -m {BQ_DATASET_NAME}.{BQML_MODEL_NAME} {BQML_MODEL_OUTPUT_DIR}
!saved_model_cli show --dir {BQML_MODEL_OUTPUT_DIR} --tag_set serv... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Deploy the exact matching model to AI Platform Prediction | !gcloud ai-platform models create {BQML_MODEL_NAME} --region={REGION}
!gcloud ai-platform versions create {BQML_MODEL_VERSION} \
--region={REGION} \
--model={BQML_MODEL_NAME} \
--origin={BQML_MODEL_OUTPUT_DIR} \
--runtime-version=2.2 \
--framework=TensorFlow \
--python-version=3.7 \
--machine-type=n1-sta... | retail/recommendation-system/bqml-scann/05_deploy_lookup_and_scann_caip.ipynb | GoogleCloudPlatform/analytics-componentized-patterns | apache-2.0 |
Creating Series
A Series can be created and initialised by passing either a scalar value, a NumPy nd array, a Python list or a Python Dict as the data parameter of the Series constructor. | # create one item series
s1 = pd.Series(1)
s1 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
'0' is the index and '1' is the value. The data type (dtype) is also shown. We can also retrieve the value using the associated index. | # get value with label 0
s1[0]
# create from list
s2 = pd.Series([1,2,3,4,5])
s2
# get the values in the series
s2.values
# get the index of the series
s2.index | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Creating Series with named index
Pandas will create different index types based on the type of data identified in the index parameter. These different index types are optimized to perform indexing operations for that specific data type. To specify the index at the time of creation of the Series, use the index parameter... | # explicitly create an index
# index is alpha, not an integer
s3 = pd.Series([1,2,3], index=['a','b','c'])
s3
s3.index | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Please note the type of the index items. It is not string but 'object'. | # look up by label value and not object position
s3['b']
# position also works
s3[2]
# create series from an existing index
# scalar value will be copied at each index label
s4 = pd.Series(2,index=s2.index)
s4 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
It is a common practice to initialize the Series objects using NumPy ndarrays, and with various NumPy functions that create arrays. The following code creates a Series from five normally distributed values: | np.random.seed(123456)
pd.Series(np.random.randn(5))
# 0 through 9
pd.Series(np.linspace(0,9,10))
# o through 8
pd.Series(np.arange(0,9)) | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
A Series can also be created from a Python dictionary. The keys of the dictionary are used as the index lables for the Series: | s6 = pd.Series({'a':1,'b':2,'c':3,'d':4})
s6 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Size, Shape, Count and Uniqueness of Values | # example series which also contains a NaN
s = pd.Series([0,1,1,2,3,4,5,6,7,np.NaN])
s
# length of the Series
len(s)
s.size
# shape is a tuple with one value
s.shape
# number of values not part of NaN can be found using count() method
s.count()
# all unique values
s.unique()
# count of non-NaN values, returned ma... | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Peeking at data with heads, tails and take
pandas provides the .head() and .tail() methods to examine just the first few or last records in a Series. By default, these return the first five or last rows respectively, but you can use the n parameter or just pass an integer to specify the number of rows: | # first five
s.head()
# first three
s.head(3)
# last five
s.tail()
# last 2
s.tail(n=2) # equivalent to s.tail(2) | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
The .take() method will return the rows in a series that correspond to the zero-based positions specified in a list: | # only take specific items
s.take([0,3,9]) | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Looking up values in Series
Values in a Series object can be retrieved using the [] operator and passing either a single index label or a list of index labels. | # single item lookup
s3['a']
# lookup by position since index is not an integer
s3[2]
# multiple items
s3[['a','c']]
# series with an integer index but not starting with 0
s5 = pd.Series([1,2,3], index =[11,12,13])
s5[12] # by value as value passed and index are both integer | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
To alleviate the potential confusion in determining the label-based lookups versus position-based lookups, index based lookup can be enforced using the .loc[] accessor: | # force lookup by index label
s5.loc[12] | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Lookup by position can be enforced using the iloc[] accessor: | # force lookup by position or location
s5.iloc[1]
# multiple items by index label
s5.loc[[12,10]]
# multiple items by position or location
s5.iloc[[1,2]] | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
If a location / position passed to .iloc[] in a list is out of bounds, an exception will be thrown. This is different than with .loc[], which if passed a label that does not exist, will return NaN as the value for that label: | s5.loc[[12,-1,15]] | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
A Series also has a property .ix that can be used to look up items either by label or by zero-based array position. | s3
# label based lookup
s3.ix[['a','b']]
# position based lookup
s3.ix[[1,2]] | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
This can become complicated if the indexes are integers and you pass a list of integers to ix. Since they are of the same type, the lookup will be by index label instead of position: | # this looks by label and not position
# note that 1,2 have NaN as those labels do not exist in the index
s5.ix[[1,2,10,11]] | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Alignment via index labels
A fundamental difference between a NumPy ndarray and a pandas Series is the ability of a Series to automatically align data from another Series based on label values before performing an operation. | s6 = pd.Series([1,2,3,4], index=['a','b','c','d'])
s6
s7 = pd.Series([4,3,2,1], index=['d','c','b','a'])
s7
s6 + s7 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
This is a very different result that what it would have been if it were two pure NumPy arrays being added. A NumPy ndarray would add the items in identical positions of each array resulting in different values. | a1 = np.array([1,2,3,4,5])
a2 = np.array([5,4,3,2,1])
a1 + a2 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
The process of adding two Series objects differs from the process of addition of arrays as it first aligns data based on index label values instead of simply applying the operation to elements in the same position. This becomes significantly powerful when using pandas Series to combine data based on labels instead of h... | # multiply all values in s3 by 2
s3 * 2
# scalar series using the s3's index
# not efficient as it will no use vectorisation
t = pd.Series(2,s3.index)
s3 * t | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
To reinforce the point that alignment is being performed when applying arithmetic operations across two Series objects, look at the following two Series as examples: | # we will add this to s9
s8 = pd.Series({'a':1,'b':2,'c':3,'d':5})
s8
s9 = pd.Series({'b':6,'c':7,'d':9,'e':10})
s9
# NaN's result for a and e demonstrates alignment
s8 + s9
s10 = pd.Series([1.0,2.0,3.0],index=['a','a','b'])
s10
s11 = pd.Series([4.0,5.0,6.0], index=['a','a','c'])
s11
# will result in four 'a' inde... | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
The reason for the above result is that during alignment, pandas actually performs a cartesian product of the sets of all the unique index labels in both Series objects, and then applies the specified operation on all items in the products.
To explain why there are four 'a' index values s10 contains two 'a' labels and ... | nda = np.array([1,2,3,4,5])
nda.mean()
# mean of numpy array values with a NaN
nda = np.array([1,2,3,4,np.NaN])
nda.mean()
# Series object ignores NaN values - does not get factored
s = pd.Series(nda)
s.mean()
# handle NaN values like Numpy
s.mean(skipna=False) | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Boolean selection
Items in a Series can be selected, based on the value instead of index labels, via the utilization of a Boolean selection. | # which rows have values that are > 5
s = pd.Series(np.arange(0,10))
s > 5
# select rows where values are > 5
# overloading the Series object [] operator
logicalResults = s > 5
s[logicalResults]
# a little shorter version
s[s > 5]
# using & operator
s[(s>5)&(s<9)]
# using | operator
s[(s > 3) | (s < 5)]
# are all ... | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
The result of these logical expressions is a Boolean selection, a Series of True and False values. The .sum() method of a Series, when given a series of Boolean values, will treat True as 1 and False as 0. The following demonstrates using this to determine the number of items in a Series that satisfy a given expression... | (s < 2).sum() | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Reindexing a Series
Reindexing in pandas is a process that makes the data in a Series or DataFrame match a given set of labels.
This process of performing a reindex includes the following steps:
1. Reordering existing data to match a set of labels.
2. Inserting NaN markers where no data exists for a label.
3. Possibly,... | # sample series of five items
s = pd.Series(np.random.randn(5))
s
# change the index
s.index = ['a','b','c','d','e']
s
# concat copies index values verbatim
# potentially making duplicates
np.random.seed(123456)
s1 = pd.Series(np.random.randn(3))
s2 = pd.Series(np.random.randn(3))
combined = pd.concat([s1,s2])
combin... | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Greater flexibility in creating a new index is provided using the .reindex() method. An example of the flexibility of .reindex() over assigning the .index property directly is that the list provided to .reindex() can be of a different length than the number of rows in the Series: | np.random.seed(123456)
s1 = pd.Series(np.random.randn(4),['a','b','c','d'])
# reindex with different number of labels
# results in dropped rows and/or NaN's
s2 = s1.reindex(['a','c','g'])
s2 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
There are several things here that are important to point out about .reindex() method.
First is that the result of .reindex() method is a new Series. This new Series has an index with labels that are provided as parameter to reindex().
For each item in the given parameter list, if the original Series contains that lab... | # s2 is a different series than s1
s2['a'] = 0
s2
# this did not modify s1
s1 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Reindex is also useful when you want to align two Series to perform an operation on matching elements from each series; however, for some reason, the two Series has index labels that will not initially align. | # different types for the same values of labels causes big issue
s1 = pd.Series([0,1,2],index=[0,1,2])
s2 = pd.Series([3,4,5],index=['0','1','2'])
s1 + s2 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
The reason why this happens in pandas are as follows:
pandas first tries to align by the indexes and finds no matches, so it copies the index labels from the first series and tries to append the indexes from the second Series.
However, since they are different type, it defaults back to zero-based integer sequence that... | # reindex by casting the label types and we will get the desired result
s2.index = s2.index.values.astype(int)
s1 + s2 | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
The default action of inserting NaN as a missing value during reindexing can be changed by using the fill_value parameter of the method. | # fill with 0 instead on NaN
s2 = s.copy()
s2.reindex(['a','f'],fill_value=0) | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
When performing a reindex on ordered data such as a time series, it is possible to perform interpolation or filling of values. The following example demonstrates forward filling, often referred to as "last known value". | # create example to demonstrate fills
s3 = pd.Series(['red','green','blue'],index=[0,3,5])
s3
# forward fill using ffill method
s3.reindex(np.arange(0,7), method='ffill')
# backward fill using bfill method
s3.reindex(np.arange(0,7),method='bfill') | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Modifying a Series in-place
There are several ways that an existing Series can be modified in-place having either its values changed or having rows added or deleted.
A new item can be added to a Series by assigning a value to an index label that does not already exist. | np.random.seed(123456)
s = pd.Series(np.random.randn(3),index=['a','b','c'])
s
# change a value in the Series
# this done in-place
# a new Series is not returned that has a modified value
s['d'] = 100
s
# value at a specific index label can be changed by assignment:
s['d'] = -100
s | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Items can be removed from a Series using the del() function and passing the index label(s) to be removed. | del(s['a'])
s | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Slicing a Series | # a series to use for slicing
# using index labels not starting at 0 to demonstrate
# position based slicing
s = pd.Series(np.arange(100,110),index=np.arange(10,20))
s
# items at position 0,2,4
s[0:6:2]
# equivalent to
s.iloc[[0,2,4]]
# first five by slicing, same as .head(5)
s[:5]
# fourth position to the end
s[4... | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
An important thing to keep in mind when using slicing, is that the result of the slice is actually a view into the original Series. Modification of values through the result of the slice will modify the original Series. | # preserve s
# slice with first 2 rows
copy = s.copy()
slice = copy[:2]
slice | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Now the assignment of a value to an element of a slice will change the value in the original Series: | slice[11] = 1000
copy | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Slicing can be performed on Series objects with a non-integer index. | # used to demonstrate the next two slices
s = pd.Series(np.arange(0,5),index=['a','b','c','d','e'])
s
# slicing with integer values will extract items based on position:
s[1:3]
# with non-integer index, it is also possible to slice with values in the same type of the index:
s['b':'d'] | pandas/01.Pandas - Series Object.ipynb | vravishankar/Jupyter-Books | mit |
Load in the SIF file for Pathway Commons, using pandas.read_csv and specifying the three column names species1, interaction_type, and species2: | sif_data = pandas.read_csv("shared/pathway_commons.sif",
sep="\t", names=["species1","interaction_type","species2"]) | class10_closeness_python3_template.ipynb | ramseylab/networkscompbio | apache-2.0 |
Subset the data frame to include only rows for which the interaction_type column contains the string controls-expression-of; subset columns to include only columns species1 and species2 using the [ operator and the list ["species1","species2"]; and eliminate redundant edges in the edge-list using the drop_duplicates me... | interac_grn = sif_data[sif_data.interaction_type == "controls-expression-of"]
interac_grn_unique = interac_grn[["species1","species2"]].drop_duplicates() | class10_closeness_python3_template.ipynb | ramseylab/networkscompbio | apache-2.0 |
Create an undirected graph in igraph, from the dataframe edge-list, using Graph.TupleList and specifying directed=False. Print out the graph summary using the summary instance method. | grn_igraph = igraph.Graph.TupleList(interac_grn_unique.values.tolist(), directed=False)
grn_igraph.summary() | class10_closeness_python3_template.ipynb | ramseylab/networkscompbio | apache-2.0 |
For one vertex at a time (iterating over the vertex sequence grn_igraph.vs), compute that vertex's harmonic mean closeness centrality using Eq. 7.30 from Newman's book. Don't forget to eliminate the "0" distance between a vertex and itself, in the results you get back from calling the shortest_paths method on the Verte... | N = len(grn_igraph.vs)
# allocate a vector to contain the vertex closeness centralities; initialize to zeroes
# (so if a vertex is a singleton we don't have to update its closeness centrality)
closeness_centralities = numpy.zeros(N)
# initialize a counter
ctr = 0
# start the timer
start_time = timeit.default_timer()... | class10_closeness_python3_template.ipynb | ramseylab/networkscompbio | apache-2.0 |
Histogram the harmonic-mean closeness centralities. Do they have a large dynamic range? | import matplotlib.pyplot
matplotlib.pyplot.hist(closeness_centralities)
matplotlib.pyplot.xlabel("Ci")
matplotlib.pyplot.ylabel("Frequency")
matplotlib.pyplot.show() | class10_closeness_python3_template.ipynb | ramseylab/networkscompbio | apache-2.0 |
Scatter plot the harmonic-mean closeness centralities vs. the log10 degree. Is there any kind of relationship? | ax = matplotlib.pyplot.gca()
ax.scatter(grn_igraph.degree(), closeness_centralities)
ax.set_xscale("log")
matplotlib.pyplot.xlabel("degree")
matplotlib.pyplot.ylabel("closeness")
matplotlib.pyplot.show() | class10_closeness_python3_template.ipynb | ramseylab/networkscompbio | apache-2.0 |
Which protein has the highest harmonic-mean closeness centrality in the network, and what is its centrality value? use numpy.argmax | print(numpy.max(closeness_centralities))
grn_igraph.vs[numpy.argmax(closeness_centralities)]["name"] | class10_closeness_python3_template.ipynb | ramseylab/networkscompbio | apache-2.0 |
Print names of the top 10 proteins in the network, by harmonic-mean closeness centrality:, using numpy.argsort: | grn_igraph.vs[numpy.argsort(closeness_centralities)[::-1][0:9].tolist()]["name"] | class10_closeness_python3_template.ipynb | ramseylab/networkscompbio | apache-2.0 |
Будем совсем неразумно обучаться на всем train'е, так как тогда мы переобучимся,
то есть наш алгоритм "подгониться" под закономерности, присущие только train'у,
а на реальных данных будет неистово лажать. Так что train разделим на две части:
на 75% будем обучаться, а на 25% проверять, что мы лажаем не неистово.
Если во... | # Выделяем outdoor'ы и indoor'ы.
sample_out = sample[result[:, 0] == 1]
sample_in = sample[result[:, 1] == 1]
result_out = result[result[:, 0] == 1]
result_in = result[result[:, 1] == 1]
# Считаем размер indoor- и outdoor-частей в train'е.
train_size_in = int(sample_in.shape[0] * 0.75)
train_size_out = int(sample_out.... | optimizaion/kaggle/eshlykov-kaggle.ipynb | eshlykov/mipt-day-after-day | unlicense |
Для каждой картинки мы хотим найти вектор $(p_0, p_1)$, вероятностей такой, что $p_i$ - вероятность того, что картинка принадлежит классу $i$ ($0$ — outdoor, $1$ — indoor).
Реализуя логистическую регрессию, мы хотим приближать вероятности к их настоящему распределению.
Выражение выдает ответ вида $$ W x + b, $$
где $... | def softmax(W, x):
# Функция logsumexp более стабтильно вычисляет функцию экспонент, почти
# избавляя нас от проблемы переполнения.
p = np.dot(x, W.T)
return np.exp(p - scm.logsumexp(p, axis=1).reshape(-1, 1))
def loss(y, softmax, W, l):
# Формула из Википедии по ссылке выше c добавленным регуляриз... | optimizaion/kaggle/eshlykov-kaggle.ipynb | eshlykov/mipt-day-after-day | unlicense |
Посчитаем среднюю квадратичную ошибку на тесте, чтобы прикинуть, что будет на Kaggle. | # Добавляем 1 к выборке.
nx_test = np.hstack([x_test, np.ones(x_test.shape[0]).reshape(x_test.shape[0], 1)])
probabilities = softmax(W, nx_test) # Считаем вероятности.
recognized = np.argmax(probabilities, axis=1) # Что распознано.
answers = np.argmax(y_test, axis=1) # Правильные ответы.
np.sqrt(np.mean((recognized... | optimizaion/kaggle/eshlykov-kaggle.ipynb | eshlykov/mipt-day-after-day | unlicense |
Теперь применяем найденную матрицу к исследумемым данным. | # Добавляем 1 к выборке.
ntest = np.hstack([test, np.ones(test.shape[0]).reshape(test.shape[0], 1)])
probabilities = softmax(W, ntest) # Считаем вероятности.
ress = np.argmax(probabilities, axis=1).reshape(-1, 1) # Что распознано.
# Осталось загнать все в табличку, чтобы ее записать в csv.
ids = np.arange(ress.size)... | optimizaion/kaggle/eshlykov-kaggle.ipynb | eshlykov/mipt-day-after-day | unlicense |
Write a function derivs for usage with scipy.integrate.odeint that computes the derivatives for the damped, driven harmonic oscillator. The solution vector at each time will be $\vec{y}(t) = (\theta(t),\omega(t))$. | def derivs(y, t, a, b, omega0):
"""Compute the derivatives of the damped, driven pendulum.
Parameters
----------
y : ndarray
The solution vector at the current time t[i]: [theta[i],omega[i]].
t : float
The current time t[i].
a, b, omega0: float
The parameters in the ... | assignments/assignment10/ODEsEx03.ipynb | Jackporter415/phys202-2015-work | mit |
Simple pendulum
Use the above functions to integrate the simple pendulum for the case where it starts at rest pointing vertically upwards. In this case, it should remain at rest with constant energy.
Integrate the equations of motion.
Plot $E/m$ versus time.
Plot $\theta(t)$ and $\omega(t)$ versus time.
Tune the atol ... | # YOUR CODE HERE
raise NotImplementedError()
# YOUR CODE HERE
raise NotImplementedError()
# YOUR CODE HERE
raise NotImplementedError()
assert True # leave this to grade the two plots and their tuning of atol, rtol. | assignments/assignment10/ODEsEx03.ipynb | Jackporter415/phys202-2015-work | mit |
Damped pendulum
Write a plot_pendulum function that integrates the damped, driven pendulum differential equation for a particular set of parameters $[a,b,\omega_0]$.
Use the initial conditions $\theta(0)=-\pi + 0.1$ and $\omega=0$.
Decrease your atol and rtol even futher and make sure your solutions have converged.
Ma... | def plot_pendulum(a=0.0, b=0.0, omega0=0.0):
"""Integrate the damped, driven pendulum and make a phase plot of the solution."""
# YOUR CODE HERE
raise NotImplementedError() | assignments/assignment10/ODEsEx03.ipynb | Jackporter415/phys202-2015-work | mit |
Use interact to explore the plot_pendulum function with:
a: a float slider over the interval $[0.0,1.0]$ with steps of $0.1$.
b: a float slider over the interval $[0.0,10.0]$ with steps of $0.1$.
omega0: a float slider over the interval $[0.0,10.0]$ with steps of $0.1$. | # YOUR CODE HERE
raise NotImplementedError() | assignments/assignment10/ODEsEx03.ipynb | Jackporter415/phys202-2015-work | mit |
BEM method | #Q = 2000/3 #strength of the source-sheet,stb/d
h=25.26 #thickness of local gridblock,ft
phi=0.2 #porosity
kx=200 #pemerability in x direction,md
ky=200 #pemerability in y direction,md
kr=kx/ky #pemerability ratio
miu=1 #viscosity,cp
Nw=1 #Number of well
Qwell... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
Boundary Discretization
we will create a discretization of the body geometry into panels (line segments in 2D). A panel's attributes are: its starting point, end point and mid-point, its length and its orientation. See the following figure for the nomenclature used in the code and equations below.
<img src="./resources... | class Panel:
"""Contains information related to a panel."""
def __init__(self, xa, ya, xb, yb):
"""Creates a panel.
Arguments
---------
xa, ya -- Cartesian coordinates of the first end-point.
xb, yb -- Cartesian coordinates of the second end-point.
"""
... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
We create a node distribution on the boundary that is refined near the corner with cosspace function | def cosspace(st,ed,N):
N=N+1
AngleInc=numpy.pi/(N-1)
CurAngle = AngleInc
space=numpy.linspace(0,1,N)
space[0]=st
for i in range(N-1):
space[i+1] = 0.5*numpy.abs(ed-st)*(1 - math.cos(CurAngle));
CurAngle += AngleInc
if ed<st:
space[0]=ed
space=space[::-1]
r... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
Discretize boundary element along the boundary
Here we implement BEM in a squre grid | N=80 #Number of boundary element
Nbd=20 #Number of boundary element in each boundary
Dx=1. #Grid block length in X direction
Dy=1. #Gird block lenght in Y direction
#Create the array
x_ends = numpy.linspace(0, Dx, N) # computes a 1D-array for x
y_ends = numpy.linspace(0, Dy, N) # computes a 1D-array ... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
Plot boundary elements and wells | #Plot the panel
%matplotlib inline
val_x, val_y = 0.3, 0.3
x_min, x_max = min(panel.xa for panel in panels), max(panel.xa for panel in panels)
y_min, y_max = min(panel.ya for panel in panels), max(panel.ya for panel in panels)
x_start, x_end = x_min-val_x*(x_max-x_min), x_max+val_x*(x_max-x_min)
y_start, y_end = y_min... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
Boundary element implementation
<img src="./resources/BEMscheme2.png" width="400">
<center>Figure 2. Representation of a local gridblock with boundary elements</center>
Generally, the influence of all the j panels on the i BE node can be expressed as follows:
\begin{matrix}
{{c}{ij}}{{p}{i}}+{{p}{i}}\int{{{s}{j}}}{{{H}... | #Panel infuence factor Bij
def InflueceP(x, y, panel):
"""Evaluates the contribution of a panel at one point.
Arguments
---------
x, y -- Cartesian coordinates of the point.
panel -- panel which contribution is evaluated.
Returns
-------
Integral over the panel of the influence... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
Well source function
Line source solution for pressure and velocity (Datta-Gupta, 2007)
\begin{equation}
P(x,y)=B{{Q}{w}}=-\frac{70.60\mu }{h\sqrt{{{k}{x}}{{k}{y}}}}\ln \left{ {{(x-{{x}{w}})}^{2}}+\frac{{{k}{x}}}{{{k}{y}}}{{(y-{{y}{w}})}^{2}} \right}{{Q}{w}}+{{P}_{avg}}
\end{equation}
\begin{equation}
\frac{\partial P}... | #Well influence factor
def InflueceP_W(x, y, well):
"""Evaluates the contribution of a panel at one point.
Arguments
---------
x, y -- Cartesian coordinates of the point.
panel -- panel which contribution is evaluated.
Returns
-------
Integral over the panel of the influence at... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
BEM function solution
Generally, the influence of all the j panels on the i BE node can be expressed as follows:
\begin{matrix}
{{c}{ij}}{{p}{i}}+{{p}{i}}\int{{{s}{j}}}{{{H}{ij}}d{{s}{j}}}=({{v}{i}}\cdot \mathbf{n})\int_{{{s}{j}}}{{{G}{ij}}}d{{s}_{j}}
\end{matrix}
Applying boundary condition along the boundary on above... | def build_matrix(panels):
"""Builds the source matrix.
Arguments
---------
panels -- array of panels.
Returns
-------
A -- NxN matrix (N is the number of panels).
"""
N = len(panels)
A = numpy.empty((N, N), dtype=float)
#numpy.fill_diagonal(A, 0.5)
for i, p... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
Plot results | #Visulize the pressure and velocity field
#Define meshgrid
Nx, Ny = 50, 50 # number of points in the x and y directions
x_start, x_end = -0.01, 1.01 # x-direction boundaries
y_start, y_end = -0.01, 1.01 # y-direction boundaries
x = numpy.linspace(x_start, x_end, Nx) # computes... | BEM_problem.ipynb | BradHub/SL-SPH | mit |
Create a graph and pass it to the VersionedGraph wrapper that will take care of the version control. | graph_obj = NXGraph()
g = VersionedGraph(graph_obj) | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
Now let's create a rule that adds to the graph two nodes connected with an edge and apply it. If we want the changes to be commited to the version control we rewrite through the rewrite method of a VersioneGraph object. | rule = Rule.from_transform(NXGraph())
rule.inject_add_node("a")
rule.inject_add_node("b")
rule.inject_add_edge("a", "b")
rhs_instance, _ = g.rewrite(rule, {}, message="Add a -> b")
plot_graph(g.graph) | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
We create a new branch called "branch" | branch_commit = g.branch("branch")
print("Branches: ", g.branches())
print("Current branch '{}'".format(g.current_branch())) | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
Apply a rule that clones the node 'b' to the current vesion of the graph (branch 'branch') | pattern = NXGraph()
pattern.add_node("b")
rule = Rule.from_transform(pattern)
rule.inject_clone_node("b")
plot_rule(rule)
rhs_instance, commit_id = g.rewrite(rule, {"b": rhs_instance["b"]}, message="Clone b")
plot_graph(g.graph) | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
The rewrite method of VersionedGraph returns the RHS instance of the applied and the id of the newly created commit corresponding to this rewrite. | print("RHS instance", rhs_instance)
print("Commit ID: ", commit_id) | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
Switch back to the 'master' branch | g.switch_branch("master")
print(g.current_branch()) | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
Apply a rule that adds a loop form 'a' to itself, a new node 'c' and connects it with 'a' | pattern = NXGraph()
pattern.add_node("a")
rule = Rule.from_transform(pattern)
rule.inject_add_node("c")
rule.inject_add_edge("c", "a")
rule.inject_add_edge("a", "a")
rhs_instance, _ = g.rewrite(rule, {"a": "a"}, message="Add c and c->a")
plot_graph(g.graph) | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
Create a new branch 'dev' | g.branch("dev") | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
In this branch remove an edge from 'c' to 'a' and merge two nodes together | pattern = NXGraph()
pattern.add_node("c")
pattern.add_node("a")
pattern.add_edge("c", "a")
rule = Rule.from_transform(pattern)
rule.inject_remove_edge("c", "a")
rule.inject_merge_nodes(["c", "a"])
plot_rule(rule)
g.rewrite(rule, {"a": rhs_instance["a"], "c": rhs_instance["c"]}, message="Merge c and a")
plot_graph(g.gr... | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
Switch back to the 'master' branch. | g.switch_branch("master") | examples/Tutorial_graph_audit.ipynb | Kappa-Dev/ReGraph | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.