markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
To get asked dates binary list
import datetime true_false_female=[] for key in data_dose1.columns[:-1]: changed_key=key.split('.')[0].split('/') true_false_female.append(datetime.date(int(changed_key[2]),int(changed_key[1]),int(changed_key[0]))<datetime.date(2021,8,15)) true_false_female.append(False) true_false_male=[] for key in data...
_____no_output_____
MIT
Q7_Asgn1.nbconvert.ipynb
sunil-dhaka/india-covid19-cases-and-vaccination-analysis
Districts
districtids=[] stateids=[] ratio=[] count1=[] count2=[] for i in range(len(district_ids)): for j in range(data_dose1.shape[0]): if district_ids[i]==data_dose1['District'][j+1]: # why there is 'j+1 'in this line :: due to that NaN in first raw districtids.append(district_ids[i]) state...
_____no_output_____
MIT
Q7_Asgn1.nbconvert.ipynb
sunil-dhaka/india-covid19-cases-and-vaccination-analysis
States
ratio_df1=pd.DataFrame({'districtid':districtids,'covaxin':count2,'covishield':count1,'stateid':stateids}) unique_state_codes=np.array(np.unique(stateids)) stateid=[] ratio_state=[] covaxin_count=[] covishield_count=[] for i in range(len(unique_state_codes)): stateid.append(unique_state_codes[i]) foo_df=ratio_d...
_____no_output_____
MIT
Q7_Asgn1.nbconvert.ipynb
sunil-dhaka/india-covid19-cases-and-vaccination-analysis
Overall
# overall overall_df=pd.DataFrame({'overallid':['IN'], 'vaccinationratio':[np.round(sum(covishield_count)/sum(covaxin_count),3)]}) overall_df.to_csv('overall-vaccine-type-ratio.csv',index=False)
_____no_output_____
MIT
Q7_Asgn1.nbconvert.ipynb
sunil-dhaka/india-covid19-cases-and-vaccination-analysis
Downloading MEDLINE/PubMed Data and Posting to PostgreSQL Brandon L. Kramer - University of Virginia's Bicomplexity Institute This notebook detail the process of downloading all of [PubMed's MEDLINE data](https://www.nlm.nih.gov/databases/download/pubmed_medline.html) and posting it to a PostgresSQL database ([UV...
cd /scratch/kb7hp/pubmed_new wget --recursive --no-parent ftp://ftp.ncbi.nlm.nih.gov/pubmed/baseline/
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
Step 2: Download PubMedPortableSecond, we will clone [PubMedPortable package from GitHub](https://github.com/KerstenDoering/PubMedPortable).
cd /home/kb7hp/git/ git clone https://github.com/KerstenDoering/PubMedPortable.git cd PubMedPortable
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
Step 3: Populate Tables in PostgreSQL Database Go to the [PubMedPortable](https://github.com/KerstenDoering/PubMedPortable/wikibuild-up-a-relational-database-in-postgresql) protocol: - Skip the part on making a superuser named parser and use Rivanna login and pwd instead - Since `PubMedPortable` is written with the...
psql -U login -d sdad -h postgis1 CREATE SCHEMA pubmed_2021;
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
Then return to the Python terminal and run this to populate the new schema:
cd /home/kb7hp/git/PubMedPortable python PubMedDB.py -d pubmed_2021
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
Go back to the Rivanna PostgreSQL shell to check if that worked:
\dt pubmed_2021.*
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
Looks like it did so now we can start parsing. Step 4: Testing MEDLINE Data Upload We don't want to start dumping all 1062 files, so let's just start with one. We will create a pm_0001 folder and download just one of the .xml files from PubMed. Next, we had to debug the `PubMedParser.py` file by updating all of the `co...
cd /home/kb7hp/git/PubMedPortable/data mkdir pm_0001 cd pm_0001 wget ftp://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed21n0001.xml.gz cd /home/kb7hp/git/PubMedPortable/ python PubMedParser.py -i data/pm_0001/
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
It took about 8 minutes to run this one file. Step 5: Uploading the Rest of the MEDLINE Dataset to PostgreSQL Database in Batches Let's add the rest of the data to Postgres. Ideally, we would just dump the whole thing at once, but Rivanna limits the amount of data we can store locally (for some reason `PubMedPortable`...
# move all the .xml.gz files to their own folder cd /scratch/kb7hp/ mkdir pubmed_gz cd /scratch/kb7hp/pubmed_new/ftp.ncbi.nlm.nih.gov/pubmed/baseline/ mv *.gz /scratch/kb7hp/pubmed_gz # and copy 10 of those files to that new folder cd /scratch/kb7hp/pubmed_gz/ cp pubmed21n{0002..0011}.xml.gz /home/kb7hp/git/PubMedPor...
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
While I intially thought this process would take ~80 minutes, running these 10 files only look ~22 minutes because of the 4 cores that essentially cut the timing by a quarter. Thus, we spun an instance with 5 cores (1 extra as directed by the Rivanna admins) and ran the next ~90 files with this new allocation. When I c...
cd /scratch/kb7hp/pubmed_gz/ cp pubmed21n{0012..0100}.xml.gz /home/kb7hp/git/PubMedPortable/data/pm_0012_0100 cd /home/kb7hp/git/PubMedPortable/data/ python PubMedParser.py -i data/pm_0012_0100/ -c -p 4
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
And indeed it did! We have loaded the first 100 files and it took just over 3 hours (13:19:19-16:22:52). Batch 4 (0101-0500)Now, let's get a bit more ambitious. Given its now night time, we are can boost the allocation to 9 cores and try ~400 files. This should take around around 7 hours to complete (400 files * 8 min...
# first we will clean up the local directory cd /home/kb7hp/git/PubMedPortable/data/ rm -r pm_0001 rm -r pm_0002_0011 rm -r pm_0012_0100 # copy over our new files cd /scratch/kb7hp/pubmed_gz cp pubmed21n{0101..0500}.xml.gz /home/kb7hp/git/PubMedPortable/data/pm_0101_0500 # and then run the script for the next 400...
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
After parsing the pm_101_500 files, I woke up to a minor error, but it looks like the program continued running up through the very last citation of the last file. I checked the `pubmed_2021.tbl_abstract` table and had 6,388,959 entries while `pubmed_2021.tbl_medline_citation` had 13,095,000, which almost half of the 2...
cd /home/kb7hp/git/PubMedPortable/data rm -r pm_0101_0500 mkdir pm_0501_0750 cd /scratch/kb7hp/pubmed_gz cp pubmed21n{0501..0750}.xml.gz /home/kb7hp/git/PubMedPortable/data/pm_0501_0750 cd /home/kb7hp/git/PubMedPortable/ python PubMedParser.py -i data/pm_0501_0750/ -c -p 8
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
This took just over 4 hours (08:34:23-13:00:31) and worked flawlessly (no errors whatsoever). At this point, we have 12,158,748 abstracts in the `pubmed_2021.tbl_abstract` table. Batch 6 (0751-0900)While I thought this would be the last batch, I ran out of space again trying to dump 750-1062. Let's do up to 900 and do...
cd /home/kb7hp/git/PubMedPortable/data rm -r pm_0501_0750 mkdir pm_0751_0900 cd /scratch/kb7hp/pubmed_gz cp pubmed21n{0751..0900}.xml.gz /home/kb7hp/git/PubMedPortable/data/pm_0751_0900 cd /home/kb7hp/git/PubMedPortable/ python PubMedParser.py -i data/pm_0751_0900/ -c -p 8
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
That took __ hours and once again ran without errors. Batch 7 (0901-1062)We dumped the last batch with this code and we were done!
cd /home/kb7hp/git/PubMedPortable/data rm -r pm_0751_0900 mkdir pm_0901_1062 cd /scratch/kb7hp/pubmed_gz cp pubmed21n{0901..1062}.xml.gz /home/kb7hp/git/PubMedPortable/data/pm_0901_1062 cd /home/kb7hp/git/PubMedPortable/ python PubMedParser.py -i data/pm_0901_1062/ -c -p 8 # started this around 8:50am
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
On to the Next Step in Your Research ProjectOverall, this was a surprisingly easy process. A major kudos goes out to PubMedPortable for this fantastic package. Now, let's get to text mining! References Döring, K., Grüning, B. A., Telukunta, K. K., Thomas, P., & Günther, S. (2016). PubMedPortable: a framework for sup...
SELECT xml_file_name, COUNT(fk_pmid) FROM pubmed_2021.tbl_pmids_in_file GROUP BY xml_file_name; --- looks like there was some kind of problem parsing these files --- affected 0816, 0829, 0865, 0866, 0875, 0879, 0884, 0886, 0891 --- all of the rest were in the high 29,000s or at 30000 --- i think i parse 900:1062 an...
_____no_output_____
MIT
src/01_pubmed_db/.ipynb_checkpoints/02_pubmed_parser-checkpoint.ipynb
brandonleekramer/the-growth-of-diversity
Homework 2**Instructions:** Complete the notebook below. Download the completed notebook in HTML format. Upload assignment using Canvas.**Due:** Jan. 19 at **2pm**. Exercise: NumPy ArraysFollow the instructions in the following cells.
# Import numpy # Use the 'np.arange()' function to create a variable called 'numbers1' that stores the integers # 1 through (and including) 10 # Print the value of 'numbers1' # Use the 'np.arange()' function to create a variable called 'numbers2' that stores the numbers # 0 through (and including) 1 with a step i...
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
Exercise: Random NumbersFollow the instructions in the following cells.
# Set the seed of NumPy's random number generator to 126 # Create a variable called 'epsilon' that is an array containing 25 draws from # a normal distribution with mean 4 and standard deviation 2 # Print the value of epsilon # Print the mean of 'epsilon' # Print the standard deviation of 'epsilon'
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
Exercise: The Cobb-Douglas Production FunctionThe Cobb-Douglas production function can be written in per worker terms as : \begin{align} y & = A k^{\alpha}, \end{align}where $y$ denotes output per worker, $k$ denotes capital per worker, and $A$ denotes total factor productivity or technology. Part (a)On a single a...
# Import the pyplot module from Matplotlib as plt # Select the Matlplotlib style sheet to use (Optional) # Use the '%matplotlib inline' magic command to ensure that Matplotlib plots are displayed in the Notebook # Set capital share (alpha) # Create an array of capital values # Plot production function for each...
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
**Question**1. *Briefly* explain in words how increasing $A$ affects the shape of the production function. **Answer**1. Part (b)On a single axis: plot the Cobb-Douglas production for $\alpha$ = 0.1, 0.2, 0.3, 0.4, and 0.5 with $A$ = 1 and $k$ ranging from 0 to 10. Each line should have a different color. Your plot m...
# Set TFP (A) # Plot production function for each of the given values for alpha # Add x- and y-axis labels # Add a title to the plot # Create a legend # Add a grid
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
**Question**1. *Briefly* explain in words how increasing $\alpha$ affects the shape of the production function. **Answer**1. Exercise: The CardioidThe cardioid is a shape described by the parametric equations: \begin{align} x & = a(2\cos \theta - \cos 2\theta), \\ y & = a(2\sin \theta - \sin 2\theta). \end{align...
# Construct data for x and y # Plot y against x # Create x-axis label # Create y-axis label # Create title for plot # Add a grid to the plot
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
Exercise: Unconstrained optimizationConsider the quadratic function: \begin{align}f(x) & = -7x^2 + 930x + 30\end{align} You will use analytic (i.e., pencil and paper) and numerical methods to find the the value of $x$ that maximizes $f(x)$. Another name for $x$ that maximizes $f(x)$ is the *argument of the maxim...
# Use np.arange to create a variable called 'x' that is equal to the numbers 0 through 100 # with a spacing between numbers of 0.1 # Create a variable called 'f' that equals f(x) at each value of the array 'x' just defined # Use np.argmax to create a variable called xstar equal to the value of 'x' that maximizes t...
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
Part (c): EvaluationProvide answers to the follow questions in the next cell.**Questions**1. How did the choice of step size in the array `x` affect the accuracy of the computed results in the first two cells of Part (b)?2. What do you think is the drawback to decreasing the stepsize in `x`?3. In the previous cell, wh...
# Assign values to the constants alpha, beta, M, px, py # Create an array of x values # Create an array of utility values # Plot utility against x. # x- and y-axis labels # Title # Add grid
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
Part (b)The NumPy function `np.max()` returns the highest value in an array and `np.argmax()` returns the index of the highest value. Print the highest value and index of the highest value of `utility`.
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
Part (c)Use the index of the highest value of utility to find the value in `x` with the same index and store value in a new variable called `xstar`. Print the value of `xstar`.
# Create variable 'xstar' equal to value in 'x' that maximizes utility # Print value of 'xstar'
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
Part (d)Use the budget constraint to the find the implied utility-maximizing vaue of $y$ and store this in a variable called `ystar`. Print `ystar`.
# Create variable 'ystar' equal to value in 'y' that maximizes utility # Print value of 'xstar'
_____no_output_____
MIT
Homework Notebooks/Econ126_Winter2021_Homework_02_blank.ipynb
letsgoexploring/econ126
Use Spark to recommend mitigation for car rental company with `ibm-watson-machine-learning` This notebook contains steps and code to create a predictive model, and deploy it on WML. This notebook introduces commands for pipeline creation, model training, model persistance to Watson Machine Learning repository, model d...
api_key = 'PASTE YOUR PLATFORM API KEY HERE' location = 'PASTE YOUR INSTANCE LOCATION HERE' wml_credentials = { "apikey": api_key, "url": 'https://' + location + '.ml.cloud.ibm.com' }
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
Install and import the `ibm-watson-machine-learning` package**Note:** `ibm-watson-machine-learning` documentation can be found here.
!pip install -U ibm-watson-machine-learning from ibm_watson_machine_learning import APIClient client = APIClient(wml_credentials)
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
Working with spacesFirst of all, you need to create a space that will be used for your work. If you do not have space already created, you can use [Deployment Spaces Dashboard](https://dataplatform.cloud.ibm.com/ml-runtime/spaces?context=cpdaas) to create one.- Click New Deployment Space- Create an empty space- Select...
space_id = 'PASTE YOUR SPACE ID HERE'
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
You can use `list` method to print all existing spaces.
client.spaces.list(limit=10)
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
To be able to interact with all resources available in Watson Machine Learning, you need to set **space** which you will be using.
client.set.default_space(space_id)
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
**Note**: Please restart the kernel (Kernel -> Restart) Test Spark
try: from pyspark.sql import SparkSession except: print('Error: Spark runtime is missing. If you are using Watson Studio change the notebook runtime to Spark.') raise
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
2. Load and explore data In this section you will load the data as an Apache Spark DataFrame and perform a basic exploration. Read data into Spark DataFrame from DB2 database and show sample record. Load data
import os from wget import download sample_dir = 'spark_sample_model' if not os.path.isdir(sample_dir): os.mkdir(sample_dir) filename = os.path.join(sample_dir, 'car_rental_training_data.csv') if not os.path.isfile(filename): filename = download('https://github.com/IBM/watson-machine-learning-samples/raw/...
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
Explore data
df_data.printSchema()
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
As you can see, the data contains eleven fields. `Action` field is the one you would like to predict using feedback data in `Customer_Service` field.
print("Number of records: " + str(df_data.count()))
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
As you can see, the data set contains 243 records.
df_data.select('Business_area').groupBy('Business_area').count().show() df_data.select('Action').groupBy('Action').count().show(truncate=False)
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
3. Create an Apache Spark machine learning modelIn this section you will learn how to:- [3.1 Prepare data for training a model](prep)- [3.2 Create an Apache Spark machine learning pipeline](pipe)- [3.3 Train a model](train) 3.1 Prepare data for training a modelIn this subsection you will split your data into: train a...
train_data, test_data = df_data.randomSplit([0.8, 0.2], 24) print("Number of training records: " + str(train_data.count())) print("Number of testing records : " + str(test_data.count()))
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
3.2 Create the pipeline In this section you will create an Apache Spark machine learning pipeline and then train the model.
from pyspark.ml.feature import OneHotEncoder, StringIndexer, IndexToString, VectorAssembler, HashingTF, IDF, Tokenizer from pyspark.ml.classification import DecisionTreeClassifier from pyspark.ml.evaluation import MulticlassClassificationEvaluator from pyspark.ml import Pipeline, Model
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
In the following step, use the StringIndexer transformer to convert all the string fields to numeric ones.
string_indexer_gender = StringIndexer(inputCol="Gender", outputCol="gender_ix") string_indexer_customer_status = StringIndexer(inputCol="Customer_Status", outputCol="customer_status_ix") string_indexer_status = StringIndexer(inputCol="Status", outputCol="status_ix") string_indexer_owner = StringIndexer(inputCol="Car_Ow...
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
4. Persist model In this section you will learn how to store your pipeline and model in Watson Machine Learning repository by using python client libraries. **Note**: Apache® Spark 2.4 is required. Save training data in your Cloud Object Storage ibm-cos-sdk library allows Python developers to manage Cloud Object Stor...
import ibm_boto3 from ibm_botocore.client import Config
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
**Action**: Put credentials from Object Storage Service in Bluemix here.
cos_credentials = { "apikey": "***", "cos_hmac_keys": { "access_key_id": "***", "secret_access_key": "***" }, "endpoints": "***", "iam_apikey_description": "***", "iam_apik...
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
**Action**: Define the service endpoint we will use. **Tip**: You can find this information in Endpoints section of your Cloud Object Storage intance's dashbord.
service_endpoint = 'https://s3.us.cloud-object-storage.appdomain.cloud'
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
You also need IBM Cloud authorization endpoint to be able to create COS resource object.
auth_endpoint = 'https://iam.cloud.ibm.com/identity/token'
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
We create COS resource to be able to write data to Cloud Object Storage.
cos = ibm_boto3.resource('s3', ibm_api_key_id=cos_credentials['apikey'], ibm_service_instance_id=cos_credentials['resource_instance_id'], ibm_auth_endpoint=auth_endpoint, config=Config(signature_version='oauth'), ...
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
Now you will create bucket in COS and copy `training dataset` for model from **car_rental_training_data.csv**.
from uuid import uuid4 bucket_uid = str(uuid4()) score_filename = "car_rental_training_data.csv" buckets = ["car-rental-" + bucket_uid] for bucket in buckets: if not cos.Bucket(bucket) in cos.buckets.all(): print('Creating bucket "{}"...'.format(bucket)) try: cos.create_bucket(Bucket=b...
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
Create connections to a COS bucket
datasource_type = client.connections.get_datasource_type_uid_by_name('bluemixcloudobjectstorage') conn_meta_props= { client.connections.ConfigurationMetaNames.NAME: "COS connection - spark", client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: datasource_type, client.connections.ConfigurationMetaName...
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
**Note**: The above connection can be initialized alternatively with `api_key` and `resource_instance_id`. The above cell can be replaced with:```conn_meta_props= { client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ", client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: c...
connection_id = client.connections.get_uid(conn_details)
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
4.2 Save the pipeline and model
training_data_references = [ { "id":"car-rental-training", "type": "connection_asset", "connection": { "id": connection_id }, "location": { "bucket": bucket...
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
Get saved model metadata from Watson Machine Learning.
published_model_id = client.repository.get_model_uid(saved_model) print("Model Id: " + str(published_model_id))
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
**Model Id** can be used to retrive latest model version from Watson Machine Learning instance. Below you can see stored model details.
client.repository.get_model_details(published_model_id)
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
5. Deploy model in the IBM Cloud You can use following command to create online deployment in cloud.
deployment_details = client.deployments.create( published_model_id, meta_props={ client.deployments.ConfigurationMetaNames.NAME: "CARS4U - Action Recommendation model deployment", client.deployments.ConfigurationMetaNames.ONLINE: {} } ) deployment_details
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
6. Score
fields = ['ID', 'Gender', 'Status', 'Children', 'Age', 'Customer_Status','Car_Owner', 'Customer_Service', 'Business_Area', 'Satisfaction'] values = [3785, 'Male', 'S', 1, 17, 'Inactive', 'Yes', 'The car should have been brought to us instead of us trying to find it in the lot.', 'Product: Information', 0] import json ...
_____no_output_____
Apache-2.0
cloud/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to recommend mitigation for car rental company.ipynb
muthukumarbala07/watson-machine-learning-samples
Check If All Class 1 Bad Pixels Are Indeed Just Noisy Pixels---
quirks_store[classes_store == 1].shape fig = figure()#figsize=(6,6)) ax = fig.add_subplot(111) # ax.plot([nan,nan]) corrections = [] for cnow in np.where(classes_store == 1)[0]: # ax.lines.pop() ax.clear() ax.plot(quirks_store[cnow] - median(quirks_store[cnow])) ax.set_title('Entry:' + str(cnow) + '/ C...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Check If All Class 4 Bad Pixels Are Indeed Just CR Pixels---
quirks_store[classes_store == 4].shape
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
fig = figure()figsize=(6,6))ax = fig.add_subplot(111)CRs = np.where(classes_store == 4)[0]corrections = []for cnow in : ax.lines.pop() ax = fig.add_subplot(111) ax.plot((quirks_store[cnow] - min(quirks_store[cnow])) / (max(quirks_store[cnow]) - min(quirks_store[cnow])), lw=2) ax.set_title('Entry:' + str(...
np.where(classes_store == 6)[0]
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
classes_store[[140,260, 380]] = 2
plot(quirks_store[140]); plot(quirks_store[260]); plot(quirks_store[380]); ((quirks_store.T - np.min(quirks_store,axis=1)) / (np.max(quirks_store,axis=1) - np.min(quirks_store, axis=1))).shape ((quirks_store.T - np.min(quirks_store,axis=1)) / (np.max(quirks_store,axis=1) - np.min(quirks_store, axis=1))).T[classes_store...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
classNow = 5stepsize = 50fig = figure(figsize=(16,30))for k in range( np.sum(classes_store == classNow) // stepsize): quirksNow = quirk_store_norm[classes_store == classNow][k*stepsize:(k+1)*stepsize] upper = np.where(quirksNow[:,-1] > 0.5)[0] lower = np.where(quirksNow[:,-1] < 0.5)[0] classes_st...
fig = figure(figsize=(16,8)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.plot(quirk_store_norm[classes_store == 5].T, lw=1); ylims = ax1.get_ylim() xlims = ax1.get_xlim() xyNow = [np.min(xlims) + 0.5*diff(xlims), np.min(ylims) + 0.5*diff(ylims)] ax1.annotate(str(5), xyNow, fontsize=75) ax2.plot...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
classes_store_new = np.copy(classes_store)classes_store_new[(classes_store == 5)*(quirk_store_norm[:,-1] < 0.5)] = 6 classes_store_new[(classes_store == 5)*(quirk_store_norm[:,-1] >= 0.5)] = classes_store[(classes_store == 5)*(quirk_store_norm[:,-1] >= 0.5)]classes_store_new[classes_store_new == 6]np.savetxt('myclasse...
darks.shape darks_trnspsd = np.transpose(darks, axes=(1,2,0)) for irow in range(len(quirks_store)): quirk_pp = pp.scale(quirks_store[irow]) # print(std(quirk_pp), scale.mad(quirk_pp)) plot(quirk_pp, alpha=0.5)# - median(darks_trnspsd[icol,irow]))) # darks_scaled = pp.scale(darks,axis=0) darks.shape, darks...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
darks_flat = darks_trnspsd[darks_std < 2*darks_med_std]nNormals = len(darks_flat)nNormals
darks_norm_trnspsd = np.transpose(darks_norm, axes=(1,2,0)) darks_norm_flat = darks_norm_trnspsd[darks_std < 2*darks_med_std] darks_norm_flat.shape darks_norm_flat.shape[0]
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Simulate RTNs because the CV3 training data has None---
np.random.seed(42) saturation = 2**16 dynRange = 2**9 nSamps = 1000 nSig = 4.0 nFrames = darks_norm_flat.shape[1] rtn_syn = np.zeros((nSamps, nFrames)) rtn_classes = np.zeros(nSamps) maxRTNs = np.int(0.9*nFrames) maxWidth = 50 minWidth = 10 rtnCnt = 0 dark_inds = np.arange(darks_...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Remove Common Mode variations from frame to frame (time series)---Probably related to bias drifting
plot(darks_flat_med_axis0) quirks_store_smooth = np.copy(quirks_store) #/ darks_flat_med_axis0 rtn_syn_smooth = np.copy(rtn_syn) #/ darks_flat_med_axis0 darks_flat_sample_smooth = np.copy(darks_flat_sample) #/ darks_flat_med_axis0 print(quirks_store_smooth.shape, rtn_syn_smooth.shape, dark...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Random Forest Classification--- Load Sci-kit Learn Libraries
from sklearn.ensemble import RandomForestClassifier from sklearn.utils import shuffle from sklearn.cross_validation import train_test_split from sklearn.externals import joblib
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
darks_classes = np.zeros(darks_flat_sample_smooth.shape[0],dtype=int)rtn_classes = rtn_classes + 3samples_train_set = vstack([quirks_store_smooth, rtn_syn_smooth, darks_flat_sample_smooth])classes_train_set = vstack([classes_store[:,None], rtn_classes[:,None], darks_classes[:,None]])[:,0]
classes_store[np.where(classes_store > 3)] += 1 darks_classes = np.zeros(darks_flat_sample_smooth.shape[0],dtype=int) rtn_classes = rtn_classes + 3 samples_train_set = vstack([quirks_store, rtn_syn, darks_flat_sample]) classes_train_set = vstack([classes_store[:,None], rtn_classes[:,None], darks_classes[:,Non...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
sts_inds = np.arange(samples_train_set.shape[0])unsort_sts = np.random.choice(sts_inds, sts_inds.size, replace=False)
samples_train_set_resort = shuffle(np.copy(samples_train_set), random_state=42) classes_train_resort = shuffle(np.copy(classes_train_set), random_state=42)
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Rescaled all samples from 0 to 1
samples_train_set_resort.shape samples_train_set_resort_scaled = (( samples_train_set_resort.T - np.min(samples_train_set_resort,axis=1)) / \ (np.max(samples_train_set_resort,axis=1) - np.min(samples_train_set_resort,axis=1))).T samples_train_set_resort_scaled.shape plot(sample...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Establish Random Forest Classification- 1000 trees- OOB Score- Multiprocessing
rfc = RandomForestClassifier(n_estimators=1000, oob_score=True, n_jobs=-1, random_state=42, verbose=True)
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
rfc2 = RandomForestClassifier(n_estimators=1000, oob_score=True, n_jobs=-1, random_state=42, verbose=True)
Split Samples into 75% Train and 25% Test
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
X_train, X_test, Y_train, Y_test = train_test_split(samples_train_set_resort_scaled.T, classes_train_resort, test_size = 0.25, random_state=42) X_train.shape, X_test.shape, Y_train.shape, Y_test.shape
Shuffle Training Data Set
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
X_train, Y_train = shuffle(X_train, Y_train, random_state=42)
Train Classifier with `rfc.fit`
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
rfc.fit(X_train, Y_train)
rfc.fit(samples_train_set_resort_scaled, classes_train_resort)
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Score Classifier with Test Data Score
rfc.score(samples_train_set_resort_scaled, classes_train_resort)
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Score Classifier with Out-of-Bag Error
rfc.oob_score_
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Save Random Forest Classifier becuse 98% is AWESOME!
joblib.dump(rfc, 'trained_RF_Classifier/random_forest_classifier_trained_on_resorted_samples_train_set_RTN_CR_HP_Other_Norm.save') joblib.dump(dict(samples=samples_train_set_resort_scaled.T, classes=classes_train_resort), 'trained_RF_Classifier/RTN_CR_HP_Other_Norm_resorted_samples_train_set.save')
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
joblib.dump(rfc2, 'trained_RF_Classifier/random_forest_classifier_trained_full_set_on_resorted_samples_train_set_RTN_CR_HP_Other_Norm.save')
darks_reshaped.shape step = 0 skipsize = 100 chunkNow = arange(step*darks_reshaped.shape[0]//skipsize,min((step+1)*darks_reshaped.shape[0]//skipsize, darks_reshaped.shape[0])) darks_reshaped_chunk = darks_reshaped[chunkNow] darks_reshaped_chunk_smooth = darks_reshaped_chunk #/ darks_flat_med_axis0 darks_resh...
_____no_output_____
BSD-3-Clause
notebooks/RTN Classification - Active.ipynb
exowanderer/BadPixelDetector
Getting Geo-coordinates for WSJ CollegesHere we are going to use a couple of Python tools to make a database of the Latitude / Longitude locations for the different schools contained in the report. I'm doing this to compare the speed and accuracy of the included Power BI ArcGIS maps with a hard-coding the coordinates....
geodf.head() import pandas as pd wsj = pd.read_csv('wsj_data.csv') import os if os.path.exists('wsj_locs.csv'): geodf = pd.read_csv('wsj_locs.csv', index_col='loc_string') else: geodf = pd.DataFrame() geodf.index.name = 'loc_string' wsj.head()
_____no_output_____
Apache-2.0
Geocoding_Colleges.ipynb
stkbailey/WSJ_CollegeRankings2018
For each college, we're going to create a search string as if we were looking it up in Google Maps. It's important to include as much information as we have so that the location service doesn't get confused with institutions in other countries, for example.
overwrite_loc_string = None if overwrite_loc_string: wsj['loc_string'] = wsj.apply(lambda s: '{}, {}, USA'.format(s.college, s.city_state), axis=1) wsj.to_csv('wsj_data.csv', encoding='utf-8', index=None) print(wsj.loc_string[0:5]) def getCoords(search_string): '''Takes a search term, queries Google and re...
_____no_output_____
Apache-2.0
Geocoding_Colleges.ipynb
stkbailey/WSJ_CollegeRankings2018
Global Signals in Time Series DataBy Abigail Stevens Problem 1: Timmer and Koenig algorithm The algorithm outlined in Timmer & Koenig 1995 lets you define the shape of your power spectrum (a power law with some slope, a Lorentzian, a sum of a couple Lorentzians and a power law, etc.) then generate the random phases a...
n_bins = 8192 ## number of total frequency bins in a FT segment; same as number of time bins in the light curve dt = 1./16. # time resolution of the output light curve df = 1. / dt / n_bins
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
1a. Make an array of Fourier frequenciesYes you can do this with scipy, but the order of frequencies in a T&K power spectrum is different than what you'd get by default from a standard FFT of a light curve.You want the zero frequency to be in the middle (at index n_bins/2) of the frequency array. The positive frequenc...
#freq = fftpack.fftfreq(n_bins, d=df) freqs = np.arange(float(-n_bins/2)+1, float(n_bins/2)+1) * df pos_freq = freqs[np.where(freqs >= 0)] ## Positive should have 2 more than negative, ## because of the 0 freq and the nyquist freq neg_freq = freqs[np.where(freqs < 0)] nyquist = pos_freq[-1] len_pos = len(pos_freq)
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
1b. Define a Lorentzian function and power law function for the shape of the power spectrum
def lorentzian(v, v_0, gamma): """ Gives a Lorentzian centered on v_0 with a FWHM of gamma """ numerator = gamma / (np.pi * 2.0) denominator = (v - v_0) ** 2 + (1.0/2.0 * gamma) ** 2 L = numerator / denominator return L def powerlaw(v, beta): """Gives a powerlaw of (1/v)^-beta """ pl = np.z...
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
Now the T&K algorithm. I've transcribed the 'recipe' section of the T&K95 paper, which you will convert to lines of code. 1c. Choose a power spectrum $S(\nu)$. We will use a sum of one Lorentzians (a QPO with a centroid frequency of 0.5 Hz and a FWHM of 0.01 Hz), and a Poisson-noise power law. The QPO should be 100 ...
power_shape = 100 * lorentzian(pos_freq, 0.5, 0.01) + powerlaw(pos_freq, 0)
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
1d. For each Fourier frequency $\nu_i$ draw two gaussian-distributed random numbers, multiply them by $$\sqrt{\frac{1}{2}S(\nu_i)}$$ and use the result as the real and imaginary part of the Fourier transform $F$ of the desired data.In the case of an even number of data points, for reason of symmetry $F(\nu_{Nyquist})...
from numpy.random import randn np.random.seed(3) rand_r = np.random.standard_normal(len_pos) rand_i = np.random.standard_normal(len_pos-1) rand_i = np.append(rand_i, 0.0) # because the nyquist frequency should only have a real value ## Creating the real and imaginary values from the lists of random numbers and the fre...
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
1e. To obtain a real valued time series, choose the Fourier components for the negative frequencies according to $F(-\nu_i)=F*(\nu_i)$ where the asterisk denotes complex conjugation. Append to make one fourier transform array. Check that your T&K fourier transform has length `n_bins`. Again, for this algorithm, the ze...
FT_pos = r_values + i_values*1j FT_neg = np.conj(FT_pos[1:-1]) FT_neg = FT_neg[::-1] ## Need to flip direction of the negative frequency FT values so that they match up correctly FT = np.append(FT_pos, FT_neg)
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
1f. Obtain the time series by backward Fourier transformation of $F(\nu)$ from the frequency domain to the time domain.Note: I usually use `.real` after an iFFT to get rid of any lingering 1e-10 imaginary factors.
lc = fftpack.ifft(FT).real
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
Congratulations! 1g. Plot the power spectrum of your FT (only the positive frequencies) next to the light curve it makes. Remember: $$P(\nu_i)=|F(\nu_i)|^2$$
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12, 5)) ax1.loglog(pos_freq, np.abs(FT_pos)**2) ax2.plot(np.linspace(0, len(lc), len(lc)), lc) ax2.set_xlim(0, 200) fig.show()
/Users/rmorgan/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py:457: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure "matplotlib is currently using a non-GUI backend, "
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
You'll want to change the x scale of your light curve plot to be like 20 seconds in length, and only use the positive Fourier frequencies when plotting the power spectrum. Yay! 1h. Play around with your new-found simulation powers (haha, it's a pun!) Make more power spectra with different features -- try at least 5 or...
def gaussian(v, mean, std_dev): """ Gives a Gaussian with a mean of mean and a standard deviation of std_dev FWHM = 2 * np.sqrt(2 * np.log(2))*std_dev """ exp_numerator = -(v - mean)**2 exp_denominator = 2 * std_dev**2 G = np.exp(exp_numerator / exp_denominator) return G def powerlaw_ex...
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
2. More realistic simulation with T&KNow you're able to simulate the power spectrum of a single segment of a light curve. However, as you learned this morning, we usually use multiple (~50+) segments of a light curve, take the power spectrum of each segment, and average them together. 2a. Turn the code from 1d to 1e ...
fig, ax = plt.subplots(1,1, figsize=(8,5)) ax.plot(rb_freq, rb_pow, linewidth=2.0) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'Frequency (Hz)', fontproperties=font_prop) ax.tick_params(axis='x', labelsize=16, bottom=True, top=True, labelbottom=True, labeltop=False) ax.tick_params(axis='y',...
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
2f. Re-do 2b through the plot above but slightly changing the power spectrum shape in each segment. Maybe you change the centroid frequency of the QPO, or the normalizing factors between the two components, or the slope of the power-law. Bonus problems: 1. Use a different definition of the Lorentzian (below) to make ...
def lorentz_q(v, v_peak, q, rms): """ Form of the Lorentzian function defined in terms of peak frequency v_peak and quality factor q q = v_peak / fwhm with the integrated rms of the QPO as the normalizing factor. e.g. see Pottschmidt et al. 2003, A&A, 407, 1039 for more info """ f_re...
_____no_output_____
MIT
Session9/Day4/workbook_globalsignals.ipynb
rmorgan10/LSSTC-DSFP-Sessions
oneM2M - Access ControlThis notebook demonstrates how access control to resources can be done in oneM2M.- Create an &lt;ACP> resource with different credentials for a new originator- Create a second &lt;AE> resource with the new access controls policy- Succeed to add a &lt;Container> to the second &lg;AE> resource- Fa...
%run init.py
_____no_output_____
BSD-3-Clause
onem2m-05-accesscontrol.ipynb
lovele0107/oneM2M-jupyter
Create an &lt;ACP> ResourceAccess Control Policies are used to associate access control with credentials. They define the rules to for access control to resources. Each &lt;ACP> resource has two sections:- **pv (Privileges)** : The actual privileges defined by this policy.- **pvs (Self-Privileges)** : This defines the...
CREATE ( # CREATE request url, # Request Headers { 'X-M2M-Origin' : originator, # Set the originator 'X-M2M-RI' : '0', # Request identifier 'Accept' : 'application/json', # Response sha...
_____no_output_____
BSD-3-Clause
onem2m-05-accesscontrol.ipynb
lovele0107/oneM2M-jupyter
Create a second &lt;AE> Resource with the new &lt;ACP>We now create a new &lt;AE> resource that uses the just created &lt;ACP>.**This should succeed.**
CREATE ( # CREATE request url, # Request Headers { 'X-M2M-Origin' : 'C', # Set the originator 'X-M2M-RI' : '0', # Request identifier 'Accept' : 'application/json', # Response shal...
_____no_output_____
BSD-3-Clause
onem2m-05-accesscontrol.ipynb
lovele0107/oneM2M-jupyter
Try to Create &lt;Container> under the second &lt;AE> ResourceWe will update a &lt;Container> resource under the second &lt;AE> resource with the originator of *abc:xyz*. **This should work** since this originator is allowed to send CREATE requests.
CREATE ( # CREATE request url + '/Notebook-AE_2', # Request Headers { 'X-M2M-Origin' : "abcxyz", # Set the originator 'X-M2M-RI' : '0', # Request identifier 'Accept' : 'application/json', ...
_____no_output_____
BSD-3-Clause
onem2m-05-accesscontrol.ipynb
lovele0107/oneM2M-jupyter
Try to Update the second &lt;AE> ResourceNow we try to update the new &lt;AE> resource (add a *lbl* attribute) with the other originator, *abc:xyz*. **This should fail**, since the associated &lt;ACP> doesn't allow UPDATE requests.
UPDATE ( # UPDATE request url + '/Notebook-AE_2', # Request Headers { 'X-M2M-Origin' : 'abcxyz', # Set the originator 'X-M2M-RI' : '0', # Request identifier 'Accept' : 'application/json', ...
_____no_output_____
BSD-3-Clause
onem2m-05-accesscontrol.ipynb
lovele0107/oneM2M-jupyter
[View in Colaboratory](https://colab.research.google.com/github/JacksonIsaac/colab_notebooks/blob/master/kaggle_tgs_salt_identification.ipynb) Kaggle notebookFor *TGS Salt identification* competition:https://www.kaggle.com/c/tgs-salt-identification-challenge Setup kaggle and download dataset
!pip install kaggle ## Load Kaggle config JSON from googleapiclient.discovery import build import io, os from googleapiclient.http import MediaIoBaseDownload from google.colab import auth auth.authenticate_user() drive_service = build('drive', 'v3') results = drive_service.files().list( q="name = 'kaggle.json...
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Install Dependencies
!pip install -q imageio !pip install -q torch !pip install -q ipywidgets import os import numpy as np import imageio import matplotlib.pyplot as plt import pandas as pd import torch from torch.utils import data
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Create class for input dataset
class TGSSaltDataSet(data.Dataset): def __init__(self, root_path, file_list): self.root_path = root_path self.file_list = file_list def __len__(self): return len(self.file_list) def __getitem__(self, index): file_id = self.file_list[index] # Ima...
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Load dataset csv
train_mask = pd.read_csv('train.csv') depth = pd.read_csv('depths.csv') train_path = './' file_list = list(train_mask['id'].values) dataset = TGSSaltDataSet(train_path, file_list)
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Visualize dataset
def plot2x2array(image, mask): fig, axs = plt.subplots(1, 2) axs[0].imshow(image) axs[1].imshow(mask) axs[0].grid() axs[1].grid() axs[0].set_title('Image') axs[1].set_title('Mask') for i in range(5): image, mask = dataset[np.random.randint(0, len(dataset))] plot2x2array(ima...
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Convert RLE Mask to matrix
def rle_to_mask(rle_string, height, width): rows, cols = height, width try: rle_numbers = [int(numstr) for numstr in rle_string.split(' ')] rle_pairs = np.array(rle_numbers).reshape(-1, 2) img = np.zeros(rows * cols, dtype=np.uint8) for idx, length in rle_pairs: ...
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Create training mask
train_mask['mask'] = train_mask['rle_mask'].apply(lambda x: rle_to_mask(x, 101, 101)) train_mask['salt_proportion'] = train_mask['mask'].apply(lambda x: salt_proportion(x))
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks