markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Download PUMS for household records for a PUMA
h_pums = c.download_household_pums("06", puma10=puma10, puma00=puma00) h_pums.head(5)
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
Now the job is to categorize acs and pums into the same categories - we start with the household acs data
h_acs_cat = cat.categorize(h_acs, { ("households", "total"): "B11001_001E", ("children", "yes"): "B11001_002E", ("children", "no"): "B11001_001E - B11001_002E", ("income", "lt35"): "B19001_002E + B19001_003E + B19001_004E + " "B19001_005E + B19001_006E + B19001_007E", ("incom...
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
And the same for ACS population - the output of the categorization is the MARGINALS for each variable category
p_acs_cat = cat.categorize(p_acs, { ("population", "total"): "B01001_001E", ("age", "19 and under"): "B01001_003E + B01001_004E + B01001_005E + " "B01001_006E + B01001_007E + B01001_027E + " "B01001_028E + B01001_029E + B01001_030E + " ...
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
To get the marginals a series for one geography do this
p_acs_cat.iloc[0].transpose()
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
Now categorize the PUMS population data into the same categories
def age_cat(r): if r.AGEP <= 19: return "19 and under" elif r.AGEP <= 35: return "20 to 35" elif r.AGEP <= 60: return "35 to 60" return "above 60" def race_cat(r): if r.RAC1P == 1: return "white" elif r.RAC1P == 2: return "black" elif r.RAC1P == 6: return "asian" return "other" def sex...
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
Do the same for households - the output of this step is the JOINT DISTRIBUTIONS for the cross product of all possible categories
def cars_cat(r): if r.VEH == 0: return "none" elif r.VEH == 1: return "one" return "two or more" def children_cat(r): if r.NOC > 0: return "yes" return "no" def income_cat(r): if r.FINCP > 100000: return "gt100" elif r.FINCP > 35000: return "gt35-lt100" return "lt35" def workers_cat(r...
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
With marginals (aggregate, from ACS) and joint distribution (disaggregate, from PUMS) we're ready for some synthesis
"TBD"
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
Versió 1.0 Utilitzeu el codi de l'exemple anterior del bucle while: només heu d'afegir que, després del xoc, el robot vaja cap enrere, gire una mica (cap al vostre costat preferit), i pare.
while ___: ___ ___
task/navigation.ipynb
ecervera/mindstorms-nb
mit
Versió 2.0 Se suposa que la maniobra del robot li permet evitar l'obstacle, i per tant tornar a anar cap avant. Com ho podem programar? Cal repetir tot el bloc d'instruccions del comportament, incloent el bucle. Cap problema, els llenguatges de programació permeten posar un bucle dins d'un altre, el que s'anomena bucle...
for ___: while ___: ___ ___
task/navigation.ipynb
ecervera/mindstorms-nb
mit
Versió 3.0 <img src="img/interrupt.png" align="right"> I si en lloc de repetir 5, 10 o 20 vegades, volem que el robot continue fins que el parem nosaltres? Ho podem fer amb un bucle infinit, i indicarem al programa que pare amb el botó interrupt kernel. En Python, un bucle infinit s'escriu així: python while True: ...
try: while True: while ___: ___ ___ except KeyboardInterrupt: stop()
task/navigation.ipynb
ecervera/mindstorms-nb
mit
La funció random és com llançar un dau, però en compte de donar una valor d'1 a 6, dóna un número real entre 0 i 1. Aleshores, el robot pot utilitzar eixe valor per a decidir si gira a esquerra o dreta. Com? Doncs si el valor és major que 0.5, gira a un costat, i si no, cap a l'altre. Aleshores, girarà a l'atzar, amb u...
try: while True: while ___: ___ if ___: ___ else: ___ except KeyboardInterrupt: stop()
task/navigation.ipynb
ecervera/mindstorms-nb
mit
Recapitulem Tot el que hem vist en aquest exercici: bucles anidats excepcions números aleatoris No està malament, quasi hem vist el temari d'un primer curs de programació, i això només amb un sensor! Passem a vore doncs el següent sensor. Abans de continuar, desconnecteu el robot:
disconnect() next_notebook('sound')
task/navigation.ipynb
ecervera/mindstorms-nb
mit
Set up your Google Cloud project
PROJECT_ID = "<your-project>" # replace with your project ID if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ...
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you. Americas: us-central1 Europe: europe-west4 Asia Pacific: asia-east1 You may not use a multi-regional bu...
REGION = "us-central1"
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create a Cloud Storage bucket When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions. Set the name of your Cloud Storage bucket below. Bucket names must be globally ...
BUCKET_NAME = "gs://<your-bucket>" # replace bucket name if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]": BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Set up variables Next, set up some variables used in this notebook. Import libraries and define constants
import google.cloud.aiplatform as aip
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Set pre-built containers Set the pre-built Docker container image for training and prediction. For the latest list, see Pre-built containers for training. For the latest list, see Pre-built containers for prediction.
TRAIN_VERSION = "xgboost-cpu.1-1" DEPLOY_VERSION = "xgboost-cpu.1-1" TRAIN_IMAGE = "gcr.io/cloud-aiplatform/training/{}:latest".format(TRAIN_VERSION) DEPLOY_IMAGE = "gcr.io/cloud-aiplatform/prediction/{}:latest".format(DEPLOY_VERSION)
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Set machine type Next, set the machine type to use for training and prediction. Set the variables TRAIN_COMPUTE and DEPLOY_COMPUTE to configure the compute resources for the VMs you will use for for training and prediction. machine type n1-standard: 3.75GB of memory per vCPU. n1-highmem: 6.5GB of memory per vCPU n1-h...
import os if os.getenv("IS_TESTING_TRAIN_MACHINE"): MACHINE_TYPE = os.getenv("IS_TESTING_TRAIN_MACHINE") else: MACHINE_TYPE = "n1-standard" VCPU = "4" TRAIN_COMPUTE = MACHINE_TYPE + "-" + VCPU print("Train machine type", TRAIN_COMPUTE) if os.getenv("IS_TESTING_DEPLOY_MACHINE"): MACHINE_TYPE = os.getenv("...
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Examine the training package Package layout Before you start the training, you will look at how a Python package is assembled for a custom training job. When unarchived, the package contains the following directory/file layout. PKG-INFO README.md setup.cfg setup.py trainer __init__.py task.py The files setup.cfg and ...
# Make folder for Python training script ! rm -rf custom ! mkdir custom # Add package information ! touch custom/README.md setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0" ! echo "$setup_cfg" > custom/setup.cfg setup_py = "import setuptools\n\nsetuptools.setup(\n\n install_requires=[\n\n 'tensorflow...
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Store training script on your Cloud Storage bucket Next, you package the training folder into a compressed tar ball, and then store it in your Cloud Storage bucket.
! rm -f custom.tar custom.tar.gz ! tar cvf custom.tar custom ! gzip custom.tar ! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_iris.tar.gz
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Train a model (training.create-python-pre-built-container) Create and run custom training job To train a custom model, you perform two steps: 1) create a custom training job, and 2) run the job. Create custom training job A custom training job is created with the CustomTrainingJob class, with the following parameters: ...
# constructs a Custom Training Job using a Python script job = # TODO: Your code goes here print(job)
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Run the custom training job Next, you run the custom job to start the training job by invoking the method run, with the following parameters: replica_count: The number of compute instances for training (replica_count = 1 is single node training). machine_type: The machine type for the compute instances. base_output_di...
MODEL_DIR = "{}/{}".format(BUCKET_NAME, TIMESTAMP) job.run( replica_count=1, machine_type=TRAIN_COMPUTE, base_output_dir=MODEL_DIR, sync=True ) MODEL_DIR = MODEL_DIR + "/model" model_path_to_deploy = MODEL_DIR
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
The custom training job will take some time to complete. Upload the model (general.import-model) Next, upload your model to a Model resource using Model.upload() method, with the following parameters: display_name: The human readable name for the Model resource. artifact_uri: The Cloud Storage location of the trained ...
model = # TODO: Your code goes here model.wait()
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Make batch predictions (predictions.batch-prediction) Make test items You will use synthetic data as a test data items. Don't be concerned that we are using synthetic data -- we just want to demonstrate how to make a prediction.
INSTANCES = [[1.4, 1.3, 5.1, 2.8], [1.5, 1.2, 4.7, 2.4]]
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Make the batch input file Now make a batch input file, which you will store in your local Cloud Storage bucket. Each instance in the prediction request is a list of the form: [ [ content_1], [content_2] ] content: The feature values of the test item as a list.
import tensorflow as tf gcs_input_uri = BUCKET_NAME + "/" + "test.jsonl" with tf.io.gfile.GFile(gcs_input_uri, "w") as f: for i in INSTANCES: f.write(str(i) + "\n") ! gsutil cat $gcs_input_uri
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Make the batch prediction request Now that your Model resource is trained, you can make a batch prediction by invoking the batch_predict() method, with the following parameters: job_display_name: The human readable name for the batch prediction job. gcs_source: A list of one or more batch request input files. gcs_dest...
MIN_NODES = 1 MAX_NODES = 1 batch_predict_job = # TODO: Your code goes here ( job_display_name="iris_" + TIMESTAMP, gcs_source=gcs_input_uri, gcs_destination_prefix=BUCKET_NAME, instances_format="jsonl", predictions_format="jsonl", model_parameters=None, machine_type=DEPLOY_COMPUTE, sta...
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Batch prediction request will take 25-30 mins to complete. Get the predictions Next, get the results from the completed batch prediction job. The results are written to the Cloud Storage output bucket you specified in the batch prediction request. You call the method iter_outputs() to get a list of each Cloud Storage f...
import json bp_iter_outputs = batch_predict_job.iter_outputs() prediction_results = list() for blob in bp_iter_outputs: if blob.name.split("/")[-1].startswith("prediction"): prediction_results.append(blob.name) tags = list() for prediction_result in prediction_results: gfile_name = f"gs://{bp_iter_ou...
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Make online predictions (predictions.deploy-model-api) Deploy the model Next, deploy your model for online prediction. To deploy the model, you invoke the deploy method, with the following parameters: deployed_model_display_name: A human readable name for the deployed model. traffic_split: Percent of traffic at the en...
DEPLOYED_NAME = "iris-" + TIMESTAMP TRAFFIC_SPLIT = {"0": 100} MIN_NODES = 1 MAX_NODES = 1 endpoint = # TODO: Your code goes here
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Model deployment will take some time to complete. Make test item (predictions.online-prediction-automl) You will use synthetic data as a test data item. Don't be concerned that we are using synthetic data -- we just want to demonstrate how to make a prediction.
INSTANCE = [1.4, 1.3, 5.1, 2.8]
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Make the prediction Now that your Model resource is deployed to an Endpoint resource, you can do online predictions by sending prediction requests to the Endpoint resource. Request The format of each instance is: [feature_list] Since the predict() method can take multiple items (instances), send your single test item ...
instances_list = [INSTANCE] prediction = endpoint.predict(instances_list) print(prediction)
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/labs/sdk_custom_xgboost.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
QUESTIONS: What do these scores tell you? Are they too high or too low you think? If it's 1.0, what does that mean? What does the graph look like for this decision tree? i.e. what are the "questions" and "decisions" for this tree... Note: You need both Graphviz app and the python package graphviz (It's worth it f...
from sklearn.tree import export_graphviz import graphviz # Let's rerun the decision tree classifier from sklearn import tree t = tree.DecisionTreeClassifier(max_depth = 4, criterion = 'entropy', class_weight = 'balanced', ...
04.Supervised Learning.ipynb
karthikrangarajan/intro-to-sklearn
bsd-3-clause
From Decision Tree to Random Forest
from sklearn.datasets import load_iris import pandas as pd import numpy as np iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3) from sklearn.ensemble import RandomForestClassifier forest = RandomForestClassifier(max_depth=4, ...
04.Supervised Learning.ipynb
karthikrangarajan/intro-to-sklearn
bsd-3-clause
1. Basic data files Pandas provide various data analysis tools. We will load two trajectory table files using Pandas library.
# read data and convert timestamps data_dir = '../data/' photo_table = os.path.join(data_dir, 'trajectory_photos.csv') traj_table = os.path.join(data_dir, 'trajectory_stats.csv') traj = pd.read_csv(photo_table, delimiter=',', parse_dates=[3], skipinitialspace=True) traj_stats = pd.read_csv(traj_table, delimiter=',', pa...
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
1.1. Contents of trajectory table The first table is from trajectory-photos.csv file. Here's five sample entries from the trajectory table. Each entry of trajectory table corresponds to single photo/video. The table consists of following attributes(columns): Trajectory_ID: trajectory ID of entry (multiple entries belo...
traj.head()
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
1.2. Contents of trajectory statistics table The second table is about statistics for each trajectory. Each entry of this table corresponds to single trajectory. This table consists of following attributes(columns): Trajectory_ID: Unique trajectory ID User_ID: User ID #Photo: Number of photos in the trajectory Start_T...
traj_stats.head()
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
2. Basic Statistics 2.1. Number of users, trajectories, and average trajectories per user
num_user = traj_stats['User_ID'].unique().size num_traj = traj_stats['Trajectory_ID'].unique().size avg_traj_per_user = num_traj/num_user print('# users :', num_user) print('# trajectories :', num_traj) print('Average trajectories per user :', avg_traj_per_user)
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
2.2. Min/Max/Median/Mean of each attribute
basic_stats = pd.DataFrame([traj_stats.min(), traj_stats.max(), traj_stats.median(), traj_stats.mean()], \ index=['min','max', 'median', 'mean']) basic_stats.drop('Start_Time', axis=1, inplace=True) basic_stats.drop('Trajectory_ID', axis=1, inplace=True) basic_stats.drop('User_ID', axis=1, in...
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
2.3 Number of Photos by year Here's the bar chart that plots the number of photos taken by each year.
yeardict = dict() for i in traj.index: dt = traj.ix[i]['Timestamp'] if dt.year not in yeardict: yeardict[dt.year] = 1 else: yeardict[dt.year] += 1 plt.figure(figsize=[9, 5]) plt.xlabel('Year') plt.ylabel('#Photos') X = list(sorted(yeardict.keys())) Y = [yeardict[x] for x in X] plt.bar(X, Y, width=1)
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
3. Distributions 3.1. Bar chart: Accuracy of photos The original dataset provide the accuracy of geo-tag for each photo. Accuracy of 16 is the most accurate and the accuracy of 1 is the least accurate. (The default accuracy is set to 16 by Flickr when the user does not provide any accuracy information about photo.) Her...
print("Number and % of points at max accuracy (16)", len(traj[traj['Accuracy']==16]), \ 1.*len(traj[traj['Accuracy']==16])/len(traj)) print("Number and % of points at accuracy >=12", len(traj[traj['Accuracy']>=11]), \ 1.*len(traj[traj['Accuracy']>=11])/len(traj)) ax1 = plt.figure(figsize=[10,3]).add_subplo...
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
3.2. Histogram: Travel time
ax1 = plt.figure(figsize=[10,3]).add_subplot(111) traj_stats.hist(column='Total_Time(min)', bins=50, ax=ax1)
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
3.3. Histogram: Distances of trajectory
ax1 = plt.figure(figsize=[10,3]).add_subplot(111) traj_stats.hist(column='Travel_Distance(km)', bins=50, ax=ax1)
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
3.4. Histogram: Average Speed
ax1 = plt.figure(figsize=[10,3]).add_subplot(111) traj_stats.hist(column='Average_Speed(km/h)', bins=50, ax=ax1)
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
4. Trajectory Visualization KML file is a useful tool to visualize trajectories on commercial map services such as Google Map. In this section, we provide how to generate KML files for visualize trajectories on the map of Melbourne. 4.1. Generating KML files with trajectory ID We implemented KML file generator in traj...
import traj_visualise # for visualization on map
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
traj_visualise.gen_kml function takes list of trajectories as an input and generate KML files for the list of trajectories. python def gen_kml(fname, traj_data, traj_stats, traj_id_list, traj_name_list=None) fname: output file path traj_data: Trajectory table traj_stats: Trajectory stat table traj_id_list: List of tra...
mostphoto_idx = traj_stats['#Photo'].idxmax() mostphoto_traj_id = traj_stats.ix[mostphoto_idx].Trajectory_ID output_file = '../data/most_photos.kml' traj_visualise.gen_kml(output_file, traj, traj_stats, [mostphoto_traj_id], ['The most number of photos']) traj_stats.ix[mostphoto_idx]
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
Trajectory with the longest travel time: Link to Google Map <img src="./img/longest_time.png" style="width: 600px;"/>
time_idx = traj_stats['Total_Time(min)'].idxmax() time_traj_id = traj_stats.ix[time_idx].Trajectory_ID output_file = '../data/longest_time.kml' traj_visualise.gen_kml(output_file, traj, traj_stats, [time_traj_id], ['The longest travel time']) traj_stats.ix[time_idx]
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
Longest travel distance: Link to Google Map <img src="./img/longest_distance.png" style="width: 600px;"/>
longest_idx = traj_stats['Travel_Distance(km)'].idxmax() longest_traj_id = traj_stats.ix[longest_idx].Trajectory_ID output_file = '../data/longest.kml' traj_visualise.gen_kml(output_file, traj, traj_stats, [longest_traj_id], ['longest_traj']) traj_stats.ix[longest_idx]
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
Fastest trajectory: Link to Google Map <img src="./img/fastest_speed.png" style="width: 600px;"/>
fastest_idx = traj_stats['Average_Speed(km/h)'].idxmax() fastest_traj_id = traj_stats.ix[fastest_idx].Trajectory_ID output_file = '../data/fastest.kml' traj_visualise.gen_kml(output_file, traj, traj_stats, [fastest_traj_id], ['fastest_traj']) traj_stats.ix[fastest_idx]
src/flickr_analysis.ipynb
cdawei/flickr-photo
gpl-2.0
Connect Python to MongoDB
client = MongoClient('mongodb://localhost:27017/')
The Airbnb Scoop/Source Code/2. Data Preparation Part 1 (Listings).ipynb
chloeyangu/BigDataAnalytics
mit
Retrieve from Database Database named as "airbnb"
db = client.airbnb
The Airbnb Scoop/Source Code/2. Data Preparation Part 1 (Listings).ipynb
chloeyangu/BigDataAnalytics
mit
Retrieve Tables from Database
listings = db.listings_new attractions = db.attractions
The Airbnb Scoop/Source Code/2. Data Preparation Part 1 (Listings).ipynb
chloeyangu/BigDataAnalytics
mit
Store data in a pandas dataframe for further analysis
import pandas as pd listings_df = pd.DataFrame(list(db.listings_new.find())) listings_df.head() listings_df.columns.values
The Airbnb Scoop/Source Code/2. Data Preparation Part 1 (Listings).ipynb
chloeyangu/BigDataAnalytics
mit
Convert numeric variables
listings_df = listings_df.convert_objects(convert_numeric=True) listings_df['price'] = listings_df['price'].str[1:] listings_df['price'] = listings_df.price.replace(',', '',regex=True) listings_df['price'] = listings_df.price.astype(float).fillna(0.0) listings_df['extra_people'] = listings_df['extra_people'].str[1:] ...
The Airbnb Scoop/Source Code/2. Data Preparation Part 1 (Listings).ipynb
chloeyangu/BigDataAnalytics
mit
Convert Amenities to Dummy Variables
listings_df['amenities_split'] = listings_df["amenities"].apply(lambda x: x[1:-1].split(',')) #Get unique amenities unique_amenities = list(set(x for l in listings_df["amenities_split"] for x in l)) unique_amenities = unique_amenities[0:2] + unique_amenities[3:] unique_amenities num_col = len(unique_amenities) #numbe...
The Airbnb Scoop/Source Code/2. Data Preparation Part 1 (Listings).ipynb
chloeyangu/BigDataAnalytics
mit
Combine Attractions Data
attractions = pd.DataFrame(list(db.attractions.find())) attractions.head() #Calculate distance between 2 lat long points #Returns distance in km def distance(lat1, long1, lat2, long2): from math import sin, cos, sqrt, atan2, radians # approximate radius of earth in km R = 6373.0 lat1 = radians(lat1)...
The Airbnb Scoop/Source Code/2. Data Preparation Part 1 (Listings).ipynb
chloeyangu/BigDataAnalytics
mit
Data Loading and Preprocessing
# Loads the training and test data sets (X_train, y_train), (X_test, y_test) = mnist.load_data() first_image = X_train[0, :, :] # To interpret the values as a 28x28 image, we need to reshape # the numpy array, which is one dimensional. plt.imshow(first_image, cmap=plt.cm.Greys); num_classes = len(np.unique(y_train))...
notebooks/04_deep_multilayer_perceptron.ipynb
ramhiser/Keras-Tutorials
mit
Multilayer Perceptron In this example, we increase the depth of the network to have two hidden layers. We also apply dropout, which is a regularization technique that randomly drops a percentage of the nodes (neurons) in the network.
model = Sequential() model.add(Dense(512, activation='relu', input_shape=(input_dim,))) model.add(Dropout(0.3)) model.add(Dense(512, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes, activation='softmax'))
notebooks/04_deep_multilayer_perceptron.ipynb
ramhiser/Keras-Tutorials
mit
Different Ways to Summarize Model
model.summary() SVG(model_to_dot(model, show_shapes=True).create(prog='dot', format='svg')) import json json.loads(model.to_json())
notebooks/04_deep_multilayer_perceptron.ipynb
ramhiser/Keras-Tutorials
mit
Train Classifier
# Trains the model, iterating on the training data in batches of 32 in 3 epochs. # Using the Adam optimizer. model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=32, epochs=3, verbose=1)
notebooks/04_deep_multilayer_perceptron.ipynb
ramhiser/Keras-Tutorials
mit
Model Evaluation
# Test accuracy is ~98%. model.evaluate(X_test, y_test)
notebooks/04_deep_multilayer_perceptron.ipynb
ramhiser/Keras-Tutorials
mit
Predicting a Couple of Held-Out Images
first_test_image = X_test[0, :] plt.imshow(first_test_image.reshape(28, 28), cmap=plt.cm.Greys); second_test_image = X_test[1, :] plt.imshow(second_test_image.reshape(28, 28), cmap=plt.cm.Greys); model.predict_classes(X_test[[0, 1], :])
notebooks/04_deep_multilayer_perceptron.ipynb
ramhiser/Keras-Tutorials
mit
1) Set up input data for PSA using MDAnalysis
from MDAnalysis import Universe from MDAnalysis.analysis.psa import PSAnalysis from pair_id import PairID
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
Initialize lists for the methods on which to perform PSA. PSA will be performed for four different simulations methods with three runs for each: DIMS, FRODA, rTMD-F, and rTMD-S. Also initialize a PSAIdentifier object to keep track of the data corresponding to comparisons between pairs of simulations.
method_names = ['DIMS', 'FRODA', 'GOdMD', 'MDdMD', 'rTMD-F', 'rTMD-S', 'ANMP', 'iENM', 'MAP', 'MENM-SD', 'MENM-SP', 'Morph', 'LinInt'] labels = [] # Heat map labels simulations = [] # List of simulation topology/trajectory filename pairs universes = [] # List of MDAnalysis Universes repr...
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
For each method, get the topology and each of three total trajectories (per method). Each simulation is represented as a (topology, trajectory) pair of file names, which is appended to a master list of simulations.
for method in method_names: # Note: DIMS uses the PSF topology format topname = 'top.psf' if 'DIMS' in method or 'TMD' in method else 'top.pdb' pathname = 'fitted_psa.dcd' method_dir = 'methods/{}'.format(method) if method is not 'LinInt': for run in xrange(1, 4): # 3 runs per method ...
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
Generate a list of universes from the list of simulations.
for sim in simulations: universes.append(Universe(*sim))
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
2) Compute and plot all-pairs distances using PSA Initialize a PSA comparison from the universe list using a C$_\alpha$ trajectory representation, then generate PSA Paths from the universes.
psa_short = PSAnalysis(universes, path_select='name CA', labels=labels) psa_short.generate_paths()
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
Computing mutual distances using Hausdorff and (discrete) Fréchet path metrics Hausdorff: compute the Hausdorff distances between all unique pairs of Paths and store the distance matrix.
psa_short.run(metric='hausdorff') hausdorff_distances = psa_short.get_pairwise_distances()
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
Plot clustered heat maps using Ward hierarchical clustering. The first heat map is plotted with the corresponding dendrogram and is fully labeled by the method names; the second heat map is annotated by the Hausdorff distances.
psa_short.plot(filename='dh_ward_psa-short.pdf', linkage='ward'); psa_short.plot_annotated_heatmap(filename='dh_ward_psa-short_annot.pdf', linkage='ward');
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
Fréchet: compute the (discrete) Fréchet distances between all unique pairs of Paths and store the distance matrix.
psa_short.run(metric='discrete_frechet') frechet_distances = psa_short.get_pairwise_distances()
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
As above, plot heat maps for (discrete) Fréchet distances.
psa_short.plot(filename='df_ward_psa-short.pdf', linkage='ward'); psa_short.plot_annotated_heatmap(filename='df_ward_psa-short_annot.pdf', linkage='ward');
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
3) Extract specific data from PSA Get the Simulation IDs and PSA ID for the second DIMS simulation (DIMS 2) and third rTMD-F simulation (rTMD-F 3).
identifier = PairID() for name in method_names: run_ids = [1] if 'LinInt' in name else [1,2,3] identifier.add_sim(name, run_ids) sid1 = identifier.get_sim_id('DIMS 2') sid2 = identifier.get_sim_id('rTMD-F 3') pid = identifier.get_pair_id('DIMS 2', 'rTMD-F 3')
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
Use the Simulation IDs to locate Hausdorff and (discrete) Fréchet distances DIMS 2/rTMD-F 3 comparison:
print hausdorff_distances[sid1,sid2] print frechet_distances[sid1,sid2]
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
Use the Pair ID when the distances are in the form of a distance vector (see scipy.spatial.distance.squareform)
from scipy.spatial.distance import squareform hausdorff_vectorform = squareform(hausdorff_distances) frechet_vectorform = squareform(frechet_distances) print hausdorff_vectorform[pid] print frechet_vectorform[pid]
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
Check that data obtained from the distance matrix is the same as that accessed from the distance vector
print hausdorff_distances[sid1,sid2] == hausdorff_vectorform[pid] print frechet_distances[sid1,sid2] == frechet_vectorform[pid]
psa_short.ipynb
Becksteinlab/PSAnalysisTutorial
gpl-3.0
We need a binary file from NASA called SPICE kernel to compute the position and velocities of the planets. Astropy downloads it for us:
from astropy.coordinates import solar_system_ephemeris solar_system_ephemeris.set("jpl")
docs/source/examples/Going to Mars with Python using poliastro.ipynb
Juanlu001/poliastro
mit
The initial data was gathered from Wikipedia: the date of the launch was on November 26, 2011 at 15:02 UTC and landing was on August 6, 2012 at 05:17 UTC. We compute then the time of flight, which is exactly what it sounds.
# Initial data date_launch = time.Time("2011-11-26 15:02", scale="utc").tdb date_arrival = time.Time("2012-08-06 05:17", scale="utc").tdb
docs/source/examples/Going to Mars with Python using poliastro.ipynb
Juanlu001/poliastro
mit
To compute the transfer orbit, we have the useful function lambert : according to a theorem with the same name, the transfer orbit between two points in space only depends on those two points and the time it takes to go from one to the other. We could make use of the raw algorithms available in poliastro.iod for solvin...
earth = Ephem.from_body(Earth, time_range(date_launch, end=date_arrival)) mars = Ephem.from_body(Mars, time_range(date_launch, end=date_arrival)) # Solve for departure and target orbits ss_earth = Orbit.from_ephem(Sun, earth, date_launch) ss_mars = Orbit.from_ephem(Sun, mars, date_arrival)
docs/source/examples/Going to Mars with Python using poliastro.ipynb
Juanlu001/poliastro
mit
We can now solve for the maneuver that will take us from Earth to Mars. After solving it, we just need to apply it to the departure orbit to solve for the transfer one.
# Solve for the transfer maneuver man_lambert = Maneuver.lambert(ss_earth, ss_mars) # Get the transfer and final orbits ss_trans, ss_target = ss_earth.apply_maneuver(man_lambert, intermediate=True)
docs/source/examples/Going to Mars with Python using poliastro.ipynb
Juanlu001/poliastro
mit
Let's plot this transfer orbit in 3D!
from poliastro.plotting import OrbitPlotter3D plotter = OrbitPlotter3D() plotter.set_attractor(Sun) plotter.plot_ephem(earth, date_launch, label="Earth at launch position") plotter.plot_ephem(mars, date_arrival, label="Mars at arrival position") plotter.plot_trajectory( ss_trans.sample(max_anomaly=180 * u.deg), c...
docs/source/examples/Going to Mars with Python using poliastro.ipynb
Juanlu001/poliastro
mit
Not bad! Let's celebrate with some music!
from IPython.display import YouTubeVideo YouTubeVideo('zSgiXGELjbc')
docs/source/examples/Going to Mars with Python using poliastro.ipynb
Juanlu001/poliastro
mit
Dataset We are using the Cryptocurrency Historical Prices dataset from Kaggle.
data_dir = '../../input' # Check what files our dataset contain print('Our dataset contains the following files: \n') print(check_output(["ls", data_dir]).decode("utf8"))
waterfall_checkpoint/demo/Demo.ipynb
ninoxcello/mscs710-project
mit
Bitcoin We will explore the bitcoin data for the purpose of a demo.
# Reading in bitcoin price file bitcoin_price = pd.read_csv('{}/bitcoin_price.csv'.format(data_dir), parse_dates=['Date'], index_col=0) bitcoin_price.dtypes # Lets look at the first 10 rows bitcoin_price.head(10) bitcoin_price.tail(10) print('Date of newest data: {}'.format(bitcoin_price.index[0])) print('Date of ol...
waterfall_checkpoint/demo/Demo.ipynb
ninoxcello/mscs710-project
mit
Helper Function
#helper functions to read in the .v and .vhd generated files into python def VerilogTextReader(loc, printresult=True): with open(f'{loc}.v', 'r') as vText: VerilogText=vText.read() if printresult: print(f'***Verilog modual from {loc}.v***\n\n', VerilogText) return VerilogText def VHDLTextR...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
Architecture Setup
BitWidth=16 #the max in excluded in intbv MaxV=int(2**(BitWidth-1)); MinV=-int(2**(BitWidth-1)) a=intbv(0)[BitWidth:]; a=a.signed() len(a), a.min, MinV, a.max, MaxV
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
$\Delta$ Difference Section <img src='DiffSect.png'> The Delta ($\Delta$) section takes in the input Digital word $x(n)$ signal and subtracts from the input word the feedback word which is $$\Delta(n)=x(n)-\begin{cases} 2^{W}-1, & \text{if}\ y(n)=1 \ 0, & \text{if}\ y(n)=0 \end{cases}$$ where $y(n)$ is ...
x1N=np.random.randint(MinV, MaxV, 20) x2N=np.random.randint(MinV, MaxV, 20) ResultsDiff=pd.DataFrame(columns=['x1', 'x2', 'yN']) ResultsDiff['x1']=x1N; ResultsDiff['x2']=x2N ResultsDiff['yN']=x1N-x2N ResultsDiff=ResultsDiff[ResultsDiff['yN']>=MinV] ResultsDiff=ResultsDiff[ResultsDiff['yN']<=MaxV] ResultsDiff.reset_ind...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL Implementation
@block def Difference(x1, x2, y): """ Prototype Delta Section such that `x1` is th input word, `x2` is the Feedback word and `y` is the ouput to the Sigma Section Inputs: x1 (2's): The From x2 (2's): the suptraction amount Outputs: y (2's): x1-x2 """ @always_comb ...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL Testing
Peeker.clear() x1=Signal(modbv(0, min=MinV, max=MaxV)); Peeker(x1, 'x1') x2=Signal(modbv(0, min=MinV, max=MaxV)); Peeker(x2, 'x2') y=Signal(modbv(0, min=MinV, max=MaxV)); Peeker(y, 'y') DUT=Difference(x1, x2, y) def Difference_TB(): for i, Row in ResultsDiff.iterrows(): x1.next=int(Row['x1']); x2.next=int...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL to Verilog
if Comp: DUT.convert() VerilogTextReader('Difference')
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
Comparator <img src='Comparator.png'> The Comparator section performers the same actions as would a Analog Computer does. It takes a input and compares that values to a reference where if the input is greater then the reference then the output is 1 else 0. Thus the Comparator performs a 1Bit quantization of the result ...
xN=np.random.randint(MinV, MaxV, 20) Ref=np.random.randint(MinV, MaxV, 20) ResultsComp=pd.DataFrame(columns=['x', 'Ref', 'yN']) ResultsComp['x']=x1N; ResultsComp['Ref']=Ref for i , Row in ResultsComp.iterrows(): ResultsComp['yN'].loc[i]=int(Row['x']>Row['Ref']) ResultsComp
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL Implementation
@block def Comparator(x, Ref, y): """ Prototype Comparator section used to convert word to binary ouput Inputs: x (2's): Input Word Ref (2's): Reference to compare too Outputs: y(bool): Outcome of Comparison; True if Input (`x`) is Greater Than the Reference, ...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL Testing
Peeker.clear() x=Signal(intbv(0, min=MinV, max=MaxV)); Peeker(x, 'x') Ref=Signal(intbv(0, min=MinV, max=MaxV)); Peeker(Ref, 'Ref') y=Signal(bool(0)); Peeker(y, 'y') DUT=Comparator(x, Ref, y) def Comparator_TB(): for i, Row in ResultsComp.iterrows(): x.next=int(Row['x']); Ref.next=int(Row['Ref']) y...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL to Verilog
if Comp: DUT.convert() VerilogTextReader('Comparator')
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
Rail To Rail Digital Scaler <img src='RailToRail.png'> The Rail to Rail Digital Scaler is part of the feedback loop of the $\Delta\Sigma$ DAC where it takes the 1Bit output and converts it to digital word that is feed to the Difference ($\Delta$) Section. Is is called a Rail to Rail since the output range is to constr...
x=np.random.randint(0, 2, 20) PRail=MaxV-1; NRail=MinV+1 DigitalRailScaleComp=pd.DataFrame(columns=['x', 'yN']) DigitalRailScaleComp['x']=x DigitalRailScaleComp['yN']=[PRail if i is 1 else NRail for i in DigitalRailScaleComp['x']] DigitalRailScaleComp
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL Implementation
@block def DigitalRailScaler(x, y, PRail, NRail): """ Prototype RailToRailDigital Scaler Inputs: x (bool): Binary Bit input select scaling Ouputs: y (2's): the Rail ouput word will be Positive Rail value if `x` is the else will be Negative Rail value Parms: PRail (in...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL Testing
Peeker.clear() x=Signal(bool(0)); Peeker(x, 'x') y=Signal(intbv(0, min=MinV, max=MaxV)); Peeker(y, 'y') DUT=DigitalRailScaler(x, y, PRail, NRail) def DigitalRailScaler_TB(): for i, Row in DigitalRailScaleComp.iterrows(): x.next=int(Row['x']) yield (delay(1)) raise StopSimulation sim=Simula...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL to Verilog
if Comp: DUT.convert() VerilogTextReader('DigitalRailScaler')
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
$\Sigma$ Integrator <img src='Integrator.png'> The Integrator ($\Sigma$) section is not a true integrator in the calculus since but instead acts as a accumulator of of the error from the $\Delta$ sections feedback. Where then the accumulated error is feed to the Comparator to convert to a binary value. In the discrete...
x=np.arange(-11, 13+1) y=[] for i, xi in enumerate(x): if i==0: y.append(0) else: y.append(y[-1]+xi) IntegratorComp=pd.DataFrame(columns=['x', 'yN']) IntegratorComp['x']=x; IntegratorComp['yN']=y IntegratorComp
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL Implementation
@block def Integrator(x, y, clk, rst): ''' Prototype Simple Integrator/ Accumultor for the Sigma Section Inputs: x (2's): the x(n) data in feed ------------------------ clk(bool): clock feed rst(bool): reset feed Outputs: ...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL Testing
Peeker.clear() x=Signal(intbv(0, min=MinV, max=MaxV)); Peeker(x, 'x') y=Signal(intbv(0, min=MinV, max=MaxV)); Peeker(y, 'y') clk, rst=[Signal(bool(0)) for _ in range(2)] Peeker(clk, 'clk'); Peeker(rst, 'rst') DUT=Integrator(x, y, clk, rst) def Integrator_TB(): @always(delay(1)) ## delay in nano seconds ...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
myHDL to Verilog
if Comp: DUT.convert() VerilogTextReader('Integrator')
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause
1Bit $\Delta\Sigma$-DAC <img src='DAC.png'> The final topology of the 1Bit $\Delta\Sigma$-DAC is shown in it's block diagram where the section that where developed above are are stitched via the following The Delta Section, which consists the DAC input and the feedback subtraction after the binary output is converted ...
TestData=pd.DataFrame(columns=['Ref', 'QRef']) refvals = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] # Generate the actual DAC codes based on the DAC resolution dac_codes = list() for value in refvals: dac_code = int(value * 2**(BitWidth-2)) if dac_code == 2**BitWidth: dac_code = 2**BitW...
myHDL_DigitalSignalandSystems/DigitalAnalog_AnalogDigital/DACDeltaSigma1Bit.ipynb
PyLCARS/PythonUberHDL
bsd-3-clause