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 |
|---|---|---|---|---|---|
再次对固化的因子进行回测检验 | # set signal shift
sig_shift = 1 | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
确认因子转换为信号的逻辑 | signal = np.sign(factor) | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
确认回测结果 | (df['return'] * signal.shift(sig_shift)).cumsum().describe()
(df['return'] * signal.shift(sig_shift)).cumsum().plot(figsize=(16,9))
data = pd.DataFrame([factor.shift(sig_shift), base_return]).T
data.columns = ['factor', 'return']
fig = plt.figure(figsize=(16,9))
sns.scatterplot(data=data, x='factor', y='return')
data =... | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
----------------- CAUTION! YOU ARE ABOUT TO CONSOLIDATE A FACTOR FUNCTION AND ITS DATA. ENTER FOLLOWING STEPS WITH CAUTION! ------------------------- consolidate factor | cf.record_source(factor_tmom_xxx_1200) | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
set instrument name: | instrument = 'IF' | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
save factor to parquet | factor_df = pd.DataFrame(factor)
factor_df.columns=['factor']
factor_df
factor_fp = root_path + f"/factor/{instrument}/"
# os.mkdir(factor_fp)
cf.save_factor(factor_df, factor_fp, factor_name) | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
save signal to parquet | signal_df = pd.DataFrame(signal)
signal_df.columns=['signal']
signal_df
signal_fp = root_path + f"/signal/{instrument}"
# os.mkdir(signal_fp)
cf.save_signal(signal_df, signal_fp, factor_name) | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
from google.colab import drive
drive.mount('/gdrive')
%cd /gdrive/'My Drive'/
%tensorflow_version 1.x
# import libraries
import json
import math
from tqdm import tqdm, tqdm_notebook
import gc
import warnings
import os
import cv2
from PIL import Image
import pandas as pd
import scipy
import matplotlib.pyplot as plt
... | _____no_output_____ | MIT | notebooks/12.Testing_3_all.ipynb | muhdlaziem/DR | |
[View in Colaboratory](https://colab.research.google.com/github/DillipKS/MLCC_assignments/blob/master/feature_sets.ipynb) Copyright 2017 Google LLC. | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the L... | _____no_output_____ | Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
Feature Sets **Learning Objective:** Create a minimal set of features that performs just as well as a more complex feature set So far, we've thrown all of our features into the model. Models with fewer features use fewer resources and are easier to maintain. Let's see if we can build a model on a minimal set of housin... | from __future__ import print_function
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging... | Training examples summary:
| Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
Task 1: Develop a Good Feature Set**What's the best performance you can get with just 2 or 3 features?**A **correlation matrix** shows pairwise correlations, both for each feature compared to the target and for each feature compared to other features.Here, correlation is defined as the [Pearson correlation coefficient... | correlation_dataframe = training_examples.copy()
correlation_dataframe["target"] = training_targets["median_house_value"]
correlation_dataframe.corr() | _____no_output_____ | Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
Features that have strong positive or negative correlations with the target will add information to our model. We can use the correlation matrix to find such strongly correlated features.We'd also like to have features that aren't so strongly correlated with each other, so that they add independent information.Use this... | def construct_feature_columns(input_features):
"""Construct the TensorFlow Feature Columns.
Args:
input_features: The names of the numerical input features to use.
Returns:
A set of feature columns
"""
return set([tf.feature_column.numeric_column(my_feature)
for my_feature in input_fea... | _____no_output_____ | Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
Spend 5 minutes searching for a good set of features and training parameters. Then check the solution to see what we chose. Don't forget that different features may require different learning parameters. | #
# Your code here: add your features of choice as a list of quoted strings.
#
minimal_features = ["median_income", "rooms_per_person"]
assert minimal_features, "You must select at least one feature!"
minimal_training_examples = training_examples[minimal_features]
minimal_validation_examples = validation_examples[min... | Training model...
RMSE (on training data):
period 00 : 204.30
period 01 : 172.09
period 02 : 142.18
period 03 : 115.27
period 04 : 94.83
period 05 : 85.87
period 06 : 84.60
period 07 : 84.73
period 08 : 84.56
period 09 : 84.51
Model training finished.
| Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
SolutionClick below for a solution. | minimal_features = [
"median_income",
"latitude",
]
minimal_training_examples = training_examples[minimal_features]
minimal_validation_examples = validation_examples[minimal_features]
_ = train_model(
learning_rate=0.01,
steps=500,
batch_size=5,
training_examples=minimal_training_examples,
tra... | _____no_output_____ | Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
Task 2: Make Better Use of LatitudePlotting `latitude` vs. `median_house_value` shows that there really isn't a linear relationship there.Instead, there are a couple of peaks, which roughly correspond to Los Angeles and San Francisco. | plt.scatter(training_examples["latitude"], training_targets["median_house_value"]) | _____no_output_____ | Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
**Try creating some synthetic features that do a better job with latitude.**For example, you could have a feature that maps `latitude` to a value of `|latitude - 38|`, and call this `distance_from_san_francisco`.Or you could break the space into 10 different buckets. `latitude_32_to_33`, `latitude_33_to_34`, etc., eac... | # YOUR CODE HERE: Train on a new data set that includes synthetic features based on latitude.
train_lat_bins = [0,0,0,0,0,0,0,0,0,0] #bins for a unit latitude range
for lat in training_examples["latitude"]:
if int(lat)==32: train_lat_bins[0]+=1
elif int(lat)==33: train_lat_bins[1]+=1
elif int(lat)==34:... | _____no_output_____ | Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
SolutionClick below for a solution. Aside from `latitude`, we'll also keep `median_income`, to compare with the previous results.We decided to bucketize the latitude. This is fairly straightforward in Pandas using `Series.apply`. | LATITUDE_RANGES = zip(range(32, 44), range(33, 45))
def select_and_transform_features(source_df):
selected_examples = pd.DataFrame()
selected_examples["median_income"] = source_df["median_income"]
for r in LATITUDE_RANGES:
selected_examples["latitude_%d_to_%d" % r] = source_df["latitude"].apply(
lambda... | Training model...
RMSE (on training data):
period 00 : 207.06
period 01 : 177.35
period 02 : 149.11
period 03 : 123.33
period 04 : 101.95
period 05 : 88.18
period 06 : 84.82
period 07 : 84.22
period 08 : 83.85
period 09 : 83.69
Model training finished.
| Apache-2.0 | feature_sets.ipynb | DillipKS/MLCC_assignments |
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. | # Dependencies and Setup
import pandas as pd
# File to Load (Remember to Change These)
HeroesOfPymoli = "Resources/purchase_data.csv"
# Read Purchasing File and store into Pandas data frame
HoP_df = pd.read_csv(HeroesOfPymoli)
HoP_df.head() | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Player Count * Display the total number of players | Player_Count = HoP_df["SN"].nunique()
Player_Count
data = {'Total Players':[Player_Count]}
PC_df = pd.DataFrame(data)
PC_df | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Purchasing Analysis (Total) * Run basic calculations to obtain number of unique items, average price, etc.* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame | # Number of Unique Items
U_Items_Count = HoP_df["Item ID"].nunique()
U_Items_Count
#Average Price
Average_Price = HoP_df["Price"].mean()
Average_Price
#Total Number of Purchases
Number_P = HoP_df["Purchase ID"].count()
Number_P
#Total Revenue
T_Revenue= Number_P * Average_Price
T_Revenue
PAdata = {'Number of Unique It... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Gender Demographics * Percentage and Count of Male Players* Percentage and Count of Female Players* Percentage and Count of Other / Non-Disclosed | #Count of Players
G_Players_df = HoP_df.loc[1:, ["SN","Gender","Price","Purchase ID"]]
GP=G_Players_df.drop_duplicates()
GP
Gender_Count=GP['Gender'].value_counts()
Gender_Count
Percent_of_Players= (Gender_Count / Player_Count)*100
Percent_of_Players
GAdata = {'Total Count':[Gender_Count], 'Percentage of Players':[Perc... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Purchasing Analysis (Gender) * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame | # Purchase analysis
Purchase_Analysis_df = HoP_df.loc[ 1:,["Gender","Price",]]
Purchase_Analysis_df
PA_Count = Purchase_Analysis_df['Gender'].value_counts()
PA_Count
#AVG purchase price per member
Avg_Purchase_Price = HoP_df.loc[ 1:,["Price"]]
Avg_Purchase_Price.mean() | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Age Demographics * Establish bins for ages* Categorize the existing players using the age bins. Hint: use pd.cut()* Calculate the numbers and percentages by age group* Create a summary data frame to hold the results* Optional: round the percentage column to two decimal points* Display Age Demographics Table | Age_df = HoP_df.loc[1:, ["SN","Age"]]
AG=Age_df.drop_duplicates()
AgeD=pd.DataFrame(AG)
AgeD
#Establish Bins
bins= [0,10,15,20,25,30,35,40,100]
group_names = ["<10","10-14","15-19","20-24","25-29","30-34","35-39","40+"]
AgeD["age ranges"] = pd.cut(AgeD["Age"], bins, labels=group_names)
AgeD.head()
#Total Counts
Tota... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Purchasing Analysis (Age) * Bin the purchase_data data frame by age* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary d... | PurchaseAnalysis_df = HoP_df.loc[1:, ["SN","Age","Price","Purchase ID"]]
PurchaseAnalysis_df
P_Analysis=PurchaseAnalysis_df.drop_duplicates()
PurchaseAS=pd.DataFrame(PurchaseAnalysis_df)
PurchaseAS
#Establish Bins
bins= [0,10,15,20,25,30,35,40,100]
group_names = ["<10","10-14","15-19","20-24","25-29","30-34","35-39","... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Top Spenders * Run basic calculations to obtain the results in the table below* Create a summary data frame to hold the results* Sort the total purchase value column in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the summary data frame | T_Spenders_df = HoP_df.loc[1:, ["SN","Price"]]
T_Spenders_df
#Cant figure this out
T_Spenders1_df = T_Spenders_df.()
T_Spenders1_df | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Most Popular Items * Retrieve the Item ID, Item Name, and Item Price columns* Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value* Create a summary data frame to hold the results* Sort the purchase count column in descending order* Optional: give the disp... | PopItems_df = HoP_df.loc[1:, ["Item Name","Price","Item ID"]]
PopItems_df
#???
PopItems1_df = PopItems_df.groupby(by="Item Name")
PopItems1_df | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.HW.ipynb | cmills39/pandas-challenge |
Population Segmentation with SageMakerIn this notebook, we'll employ two, unsupervised learning algorithms to do **population segmentation**. Population segmentation aims to find natural groupings in population data that reveal some feature-level similarities between different regions in the US.Using **principal compo... | # data managing and display libs
import pandas as pd
import numpy as np
import os
import io
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
# sagemaker libraries
import boto3
import sagemaker | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Loading the Data from Amazon S3This particular dataset is already in an Amazon S3 bucket; you can load the data by pointing to this bucket and getting a data file by name. > You can interact with S3 using a `boto3` client. | # boto3 client to get S3 data
s3_client = boto3.client('s3')
bucket_name='aws-sagemaker-census-segmentation' | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Take a look at the contents of this bucket; get a list of objects that are contained within the bucket and print out the names of the objects. You should see that there is one file, 'Census_Data_for_SageMaker.csv'. | # get a list of objects in the bucket
obj_list=s3_client.list_objects(Bucket=bucket_name)
# print object(s)in S3 bucket
files=[]
for contents in obj_list['Contents']:
files.append(contents['Key'])
print(files)
# there is one file --> one key
file_name=files[0]
print(file_name) | Census_Data_for_SageMaker.csv
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Retrieve the data file from the bucket with a call to `client.get_object()`. | # get an S3 object by passing in the bucket and file name
data_object = s3_client.get_object(Bucket=bucket_name, Key=file_name)
# what info does the object contain?
display(data_object)
# information is in the "Body" of the object
data_body = data_object["Body"].read()
print('Data type: ', type(data_body)) | Data type: <class 'bytes'>
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
This is a `bytes` datatype, which you can read it in using [io.BytesIO(file)](https://docs.python.org/3/library/io.htmlbinary-i-o). | # read in bytes data
data_stream = io.BytesIO(data_body)
# create a dataframe
counties_df = pd.read_csv(data_stream, header=0, delimiter=",")
counties_df.head() | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Exploratory Data Analysis (EDA)Now that we've loaded in the data, it is time to clean it up, explore it, and pre-process it. Data exploration is one of the most important parts of the machine learning workflow because it allows you to notice any initial patterns in data distribution and features that may inform how yo... | # print out stats about data
print('Original data stats:\n', counties_df.shape)
# drop any incomplete rows of data, and create a new df
clean_counties_df = counties_df.dropna()
print('Cleaned data stats:\n', clean_counties_df.shape) | Original data stats:
(3220, 37)
Cleaned data stats:
(3218, 37)
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Create a new DataFrame, indexed by 'State-County'Eventually, you'll want to feed these features into a machine learning model. Machine learning models need numerical data to learn from and not categorical data like strings (State, County). So, you'll reformat this data such that it is indexed by region and you'll also... | # index data by 'State-County'
clean_counties_df.index = clean_counties_df['State'] + '-' + clean_counties_df['County']
# drop the old State and County columns, and the CensusId column
# clean df should be modified or created anew
clean_counties_df = clean_counties_df.drop(['State', 'County', 'CensusId'], axis=1)
clean... | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Now, what features do you have to work with? | # features
features_list = clean_counties_df.columns.values
print('Features: \n', features_list) | Features:
['TotalPop' 'Men' 'Women' 'Hispanic' 'White' 'Black' 'Native' 'Asian'
'Pacific' 'Citizen' 'Income' 'IncomeErr' 'IncomePerCap' 'IncomePerCapErr'
'Poverty' 'ChildPoverty' 'Professional' 'Service' 'Office' 'Construction'
'Production' 'Drive' 'Carpool' 'Transit' 'Walk' 'OtherTransp'
'WorkAtHome' 'MeanCommut... | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Visualizing the DataIn general, you can see that features come in a variety of ranges, mostly percentages from 0-100, and counts that are integer values in a large range. Let's visualize the data in some of our feature columns and see what the distribution, over all counties, looks like.The below cell displays **histo... | # transportation (to work)
transport_list = ['Drive', 'Carpool', 'Transit', 'Walk', 'OtherTransp']
n_bins = 30 # can decrease to get a wider bin (or vice versa)
for column_name in transport_list:
ax=plt.subplots(figsize=(6,3))
# get data by column_name and display a histogram
ax = plt.hist(clean_counties_d... | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
EXERCISE: Create histograms of your ownCommute transportation method is just one category of features. If you take a look at the 34 features, you can see data on profession, race, income, and more. Display a set of histograms that interest you! | # create a list of features that you want to compare or examine
my_list = ['Hispanic', 'White', 'Black', 'Native', 'Asian']
n_bins = 50
# histogram creation code is similar to above
for column_name in my_list:
ax=plt.subplots(figsize=(6,3))
# get data by column_name and display a histogram
ax = plt.hist(cl... | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Normalize the dataYou need to standardize the scale of the numerical columns in order to consistently compare the values of different features. You can use a [MinMaxScaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html) to transform the numerical values so that they all fall... | # scale numerical features into a normalized range, 0-1
# store them in this dataframe
from sklearn.preprocessing import MinMaxScaler
min_max = MinMaxScaler()
counties_scaled = pd.DataFrame(min_max.fit_transform(clean_counties_df))
counties_scaled.columns = clean_counties_df.columns
counties_scaled.index = clean_cou... | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
--- Data ModelingNow, the data is ready to be fed into a machine learning model!Each data point has 34 features, which means the data is 34-dimensional. Clustering algorithms rely on finding clusters in n-dimensional feature space. For higher dimensions, an algorithm like k-means has a difficult time figuring out which... | from sagemaker import get_execution_role
session = sagemaker.Session() # store the current SageMaker session
# get IAM role
role = get_execution_role()
print(role)
# get default bucket
bucket_name = session.default_bucket()
print(bucket_name)
print() | sagemaker-us-east-1-204421427803
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Define a PCA ModelTo create a PCA model, I'll use the built-in SageMaker resource. A SageMaker estimator requires a number of parameters to be specified; these define the type of training instance to use and the model hyperparameters. A PCA model requires the following constructor arguments:* role: The IAM role, which... | # define location to store model artifacts
prefix = 'counties'
output_path='s3://{}/{}/'.format(bucket_name, prefix)
print('Training artifacts will be uploaded to: {}'.format(output_path))
# define a PCA model
from sagemaker import PCA
# this is current features - 1
# you'll select only a portion of these to use, la... | train_instance_count has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
train_instance_type has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Convert data into a RecordSet formatNext, prepare the data for a built-in model by converting the DataFrame to a numpy array of float values.The *record_set* function in the SageMaker PCA model converts a numpy array into a **RecordSet** format that is the required format for the training input data. This is a require... | # convert df to np array
train_data_np = counties_scaled.values.astype('float32')
# convert to RecordSet format
formatted_train_data = pca_SM.record_set(train_data_np) | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Train the modelCall the fit function on the PCA model, passing in our formatted, training data. This spins up a training instance to perform the training job.Note that it takes the longest to launch the specified training instance; the fitting itself doesn't take much time. | %%time
# train the PCA mode on the formatted data
pca_SM.fit(formatted_train_data) | Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Accessing the PCA Model AttributesAfter the model is trained, we can access the underlying model parameters. Unzip the Model DetailsNow that the training job is complete, you can find the job under **Jobs** in the **Training** subsection in the Amazon SageMaker console. You can find the job name listed in the traini... | # Get the name of the training job, it's suggested that you copy-paste
# from the notebook or from a specific job in the AWS console
training_job_name='pca-2021-04-21-10-18-40-888'
# where the model is saved, by default
model_key = os.path.join(prefix, training_job_name, 'output/model.tar.gz')
print(model_key)
# dow... | counties/pca-2021-04-21-10-18-40-888/output/model.tar.gz
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
MXNet ArrayMany of the Amazon SageMaker algorithms use MXNet for computational speed, including PCA, and so the model artifacts are stored as an array. After the model is unzipped and decompressed, we can load the array using MXNet.You can take a look at the MXNet [documentation, here](https://aws.amazon.com/mxnet/). | import mxnet as mx
# loading the unzipped artifacts
pca_model_params = mx.ndarray.load('model_algo-1')
# what are the params
print(pca_model_params) | {'s':
[1.7896362e-02 3.0864021e-02 3.2130770e-02 3.5486195e-02 9.4831578e-02
1.2699370e-01 4.0288666e-01 1.4084760e+00 1.5100485e+00 1.5957943e+00
1.7783760e+00 2.1662524e+00 2.2966361e+00 2.3856051e+00 2.6954880e+00
2.8067985e+00 3.0175958e+00 3.3952675e+00 3.5731301e+00 3.6966958e+00
4.1890211e+00 4.3457499e+00 ... | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
PCA Model AttributesThree types of model attributes are contained within the PCA model.* **mean**: The mean that was subtracted from a component in order to center it.* **v**: The makeup of the principal components; (same as ‘components_’ in an sklearn PCA model).* **s**: The singular values of the components for the ... | # get selected params
s=pd.DataFrame(pca_model_params['s'].asnumpy())
v=pd.DataFrame(pca_model_params['v'].asnumpy()) | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Data VarianceOur current PCA model creates 33 principal components, but when we create new dimensionality-reduced training data, we'll only select a few, top n components to use. To decide how many top components to include, it's helpful to look at how much **data variance** the components capture. For our original, h... | # looking at top 5 components
n_principal_components = 5
start_idx = N_COMPONENTS - n_principal_components # 33-n
# print a selection of s
print(s.iloc[start_idx:, :]) | 0
28 7.991313
29 10.180052
30 11.718245
31 13.035975
32 19.592180
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Calculate the explained varianceIn creating new training data, you'll want to choose the top n principal components that account for at least 80% data variance. Complete a function, `explained_variance` that takes in the entire array `s` and a number of top principal components to consider. Then return the approximate... | # Calculate the explained variance for the top n principal components
# you may assume you have access to the global var N_COMPONENTS
def explained_variance(s, n_top_components):
'''Calculates the approx. data variance that n_top_components captures.
:param s: A dataframe of singular values for top component... | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Test CellTest out your own code by seeing how it responds to different inputs; does it return a reasonable value for the single, top component? What about for the top 5 components? | # test cell
n_top_components = 8 # select a value for the number of top components
# calculate the explained variance
exp_variance = explained_variance(s, n_top_components)
print('Explained variance: ', exp_variance) | Explained variance: 0.83158576
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
As an example, you should see that the top principal component accounts for about 32% of our data variance! Next, you may be wondering what makes up this (and other components); what linear combination of features make these components so influential in describing the spread of our data?Below, let's take a look at our ... | # features
features_list = counties_scaled.columns.values
print('Features: \n', features_list) | Features:
['TotalPop' 'Men' 'Women' 'Hispanic' 'White' 'Black' 'Native' 'Asian'
'Pacific' 'Citizen' 'Income' 'IncomeErr' 'IncomePerCap' 'IncomePerCapErr'
'Poverty' 'ChildPoverty' 'Professional' 'Service' 'Office' 'Construction'
'Production' 'Drive' 'Carpool' 'Transit' 'Walk' 'OtherTransp'
'WorkAtHome' 'MeanCommut... | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Component MakeupWe can now examine the makeup of each PCA component based on **the weightings of the original features that are included in the component**. The following code shows the feature-level makeup of the first component.Note that the components are again ordered from smallest to largest and so I am getting t... | import seaborn as sns
def display_component(v, features_list, component_num, n_weights=10):
# get index of component (last row - component_num)
row_idx = N_COMPONENTS-component_num
# get the list of weights from a row in v, dataframe
v_1_row = v.iloc[:, row_idx]
v_1 = np.squeeze(v_1_row.value... | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Deploying the PCA ModelWe can now deploy this model and use it to make "predictions". Instead of seeing what happens with some test data, we'll actually want to pass our training data into the deployed endpoint to create principal components for each data point. Run the cell below to deploy/host this model on an insta... | %%time
# this takes a little while, around 7mins
pca_predictor = pca_SM.deploy(initial_instance_count=1,
instance_type='ml.t2.medium') | Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
We can pass the original, numpy dataset to the model and transform the data using the model we created. Then we can take the largest n components to reduce the dimensionality of our data. | # pass np train data to the PCA model
train_pca = pca_predictor.predict(train_data_np)
# check out the first item in the produced training features
data_idx = 0
print(train_pca[data_idx]) | label {
key: "projection"
value {
float32_tensor {
values: 0.0002009272575378418
values: 0.0002455431967973709
values: -0.0005782842636108398
values: -0.0007815659046173096
values: -0.00041911262087523937
values: -0.0005133943632245064
values: -0.0011316537857055664
... | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Create a transformed DataFrameFor each of our data points, get the top n component values from the list of component data points, returned by our predictor above, and put those into a new DataFrame.You should end up with a DataFrame that looks something like the following:``` c_1 c_2 c_... | # create dimensionality-reduced data
def create_transformed_df(train_pca, counties_scaled, n_top_components):
''' Return a dataframe of data points with component features.
The dataframe should be indexed by State-County and contain component values.
:param train_pca: A list of pca training data, r... | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Now we can create a dataset where each county is described by the top n principle components that we analyzed earlier. Each of these components is a linear combination of the original feature space. We can interpret each of these components by analyzing the makeup of the component, shown previously. Define the `top_n` ... | ## Specify top n
top_n = 8
# call your function and create a new dataframe
counties_transformed = create_transformed_df(train_pca, counties_scaled, n_top_components=top_n)
## TODO: Add descriptive column names
cols = ['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7', 'col_8']
counties_transformed.columns... | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Delete the Endpoint!Now that we've deployed the mode and created our new, transformed training data, we no longer need the PCA endpoint.As a clean up step, you should always delete your endpoints after you are done using them (and if you do not plan to deploy them to a website, for example). | # delete predictor endpoint
session.delete_endpoint(pca_predictor.endpoint) | The endpoint attribute has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
--- Population Segmentation Now, you’ll use the unsupervised clustering algorithm, k-means, to segment counties using their PCA attributes, which are in the transformed DataFrame we just created. K-means is a clustering algorithm that identifies clusters of similar data points based on their component makeup. Since we ... | # define a KMeans estimator
from sagemaker import KMeans
n_clusters = 7
kmeans_est = KMeans(role=role,
sagemaker_session=session,
instance_count=1,
instance_type='ml.c4.xlarge',
output_path=output_path,
k=n_clusters) | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Create formatted, k-means training dataJust as before, you should convert the `counties_transformed` df into a numpy array and then into a RecordSet. This is the required format for passing training data into a `KMeans` model. | # convert the transformed dataframe into record_set data
training_data_np = counties_transformed.values.astype('float32')
training_data = kmeans_est.record_set(training_data_np) | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Train the k-means modelPass in the formatted training data and train the k-means model. | %%time
# train kmeans
kmeans_est.fit(training_data) | Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Deploy the k-means modelDeploy the trained model to create a `kmeans_predictor`. | %%time
# deploy the model to create a predictor
kmeans_predictor = kmeans_est.deploy(initial_instance_count=1, instance_type='ml.t2.medium') | Defaulting to the only supported framework/algorithm version: 1. Ignoring framework/algorithm version: 1.
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Pass in the training data and assign predicted cluster labelsAfter deploying the model, you can pass in the k-means training data, as a numpy array, and get resultant, predicted cluster labels for each data point. | # get the predicted clusters for all the kmeans training data
cluster_info = kmeans_predictor.predict(training_data_np) | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Exploring the resultant clustersThe resulting predictions should give you information about the cluster that each data point belongs to.You should be able to answer the **question**: which cluster does a given data point belong to? | # print cluster info for first data point
data_idx = 0
print('County is: ', counties_transformed.index[data_idx])
print()
print(cluster_info[data_idx]) | County is: Alabama-Autauga
label {
key: "closest_cluster"
value {
float32_tensor {
values: 4.0
}
}
}
label {
key: "distance_to_cluster"
value {
float32_tensor {
values: 0.3278287351131439
}
}
}
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Visualize the distribution of data over clustersGet the cluster labels for each of our data points (counties) and visualize the distribution of points over each cluster. | # get all cluster labels
cluster_labels = [c.label['closest_cluster'].float32_tensor.values[0] for c in cluster_info]
# count up the points in each cluster
cluster_df = pd.DataFrame(cluster_labels)[0].value_counts()
print(cluster_df) | 4.0 978
1.0 775
2.0 423
6.0 354
5.0 322
0.0 260
3.0 106
Name: 0, dtype: int64
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Now, you may be wondering, what do each of these clusters tell us about these data points? To improve explainability, we need to access the underlying model to get the cluster centers. These centers will help describe which features characterize each cluster. Delete the Endpoint!Now that you've deployed the k-means mo... | # delete kmeans endpoint
session.delete_endpoint(kmeans_predictor.endpoint) | The endpoint attribute has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
| MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
--- Model Attributes & ExplainabilityExplaining the result of the modeling is an important step in making use of our analysis. By combining PCA and k-means, and the information contained in the model attributes within a SageMaker trained model, you can learn about a population and remark on some patterns you've found, ... | # download and unzip the kmeans model file
# use the name model_algo-1
training_job_name='kmeans-2021-04-21-14-23-50-011'
model_key = os.path.join(prefix, training_job_name, 'output/model.tar.gz')
print(model_key)
boto3.resource('s3').Bucket(bucket_name).download_file(model_key, 'model.tar.gz')
os.system('tar -zxvf m... | [
[[ 2.58064777e-01 -1.65894613e-01 -1.04465716e-01 -1.35486513e-01
1.03924178e-01 -1.08686484e-01 -8.16875845e-02 -2.35025808e-02]
[-2.51183987e-01 -2.47022919e-02 -2.59090755e-02 -3.94684374e-02
-1.28233312e-02 -2.87618302e-02 7.08517572e-03 -2.10537948e-02]
[ 3.26939464e-01 2.11919174e-01 4.73352224e-02 2... | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
There is only 1 set of model parameters contained within the k-means model: the cluster centroid locations in PCA-transformed, component space.* **centroids**: The location of the centers of each cluster in component space, identified by the k-means algorithm. | # get all the centroids
cluster_centroids=pd.DataFrame(kmeans_model_params[0].asnumpy())
cluster_centroids.columns=counties_transformed.columns
display(cluster_centroids) | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Visualizing Centroids in Component SpaceYou can't visualize 7-dimensional centroids in space, but you can plot a heatmap of the centroids and their location in the transformed feature space. This gives you insight into what characteristics define each cluster. Often with unsupervised learning, results are hard to inte... | # generate a heatmap in component space, using the seaborn library
plt.figure(figsize = (12,9))
ax = sns.heatmap(cluster_centroids.T, cmap = 'YlGnBu')
ax.set_xlabel("Cluster")
plt.yticks(fontsize = 16)
plt.xticks(fontsize = 16)
ax.set_title("Attribute Value by Centroid")
plt.show() | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
If you've forgotten what each component corresponds to at an original-feature-level, that's okay! You can use the previously defined `display_component` function to see the feature-level makeup. | # what do each of these components mean again?
# let's use the display function, from above
component_num=7
display_component(v, counties_scaled.columns.values, component_num=component_num) | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
Natural GroupingsYou can also map the cluster labels back to each individual county and examine which counties are naturally grouped together. | # add a 'labels' column to the dataframe
counties_transformed['labels']=list(map(int, cluster_labels))
# sort by cluster label 0-6
sorted_counties = counties_transformed.sort_values('labels', ascending=True)
# view some pts in cluster 0
sorted_counties.head(20) | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
You can also examine one of the clusters in more detail, like cluster 1, for example. A quick glance at the location of the centroid in component space (the heatmap) tells us that it has the highest value for the `comp_6` attribute. You can now see which counties fit that description. | # get all counties with label == 1
cluster=counties_transformed[counties_transformed['labels']==1]
cluster.head() | _____no_output_____ | MIT | Pop_Segmentation.ipynb | ahmed14-cell/population-segmentation |
**Dependencies** | !pip install -U -q sentence-transformers
!git clone https://github.com/desaibhargav/VR.git | [K |████████████████████████████████| 71kB 9.4MB/s
[K |████████████████████████████████| 1.8MB 29.8MB/s
[K |████████████████████████████████| 1.2MB 56.2MB/s
[K |████████████████████████████████| 2.9MB 55.3MB/s
[K |████████████████████████████████| 890kB 50.5MB/s
[?25h Building wheel for ... | MIT | notebooks/Semantic_Search.ipynb | KewalMishra/VR |
**Imports** | import pandas as pd
import numpy as np
import torch
import time
from typing import Generator
from sentence_transformers import SentenceTransformer, CrossEncoder, util
from VR.backend.chunker import Chunker | _____no_output_____ | MIT | notebooks/Semantic_Search.ipynb | KewalMishra/VR |
**Dataset** | # load scrapped data (using youtube_client.py)
dataset = pd.read_pickle('VR/datasets/youtube_scrapped.pickle')
# split transcripts of videos to smaller blocks or chunks (using chunker.py)
chunked = Chunker(chunk_by='length', expected_threshold=100, min_tolerable_threshold=75).get_chunks(dataset)
# finally, create dat... | Average length of block: 107.33691183188671, Standard Deviation: 12.755147492715611
| MIT | notebooks/Semantic_Search.ipynb | KewalMishra/VR |
**Semantic Search**---The idea is to compute embeddings of the query (entered by user) and use cosine similarity to find the `top_k` most similar blocks. Blocks are nothing but the entire video transcript (big string) split into fixed length strings (small strings, ~100 words). ---The reason for such a design choice w... | # request to enable GPU
if not torch.cuda.is_available():
print("Warning: No GPU found. Please add GPU to your notebook")
# load model (to encode the dataset)
bi_encoder = SentenceTransformer('paraphrase-distilroberta-base-v1')
# number of blocks we want to retrieve with the bi-encoder
top_k = 200
# the bi-en... | _____no_output_____ | MIT | notebooks/Semantic_Search.ipynb | KewalMishra/VR |
**Try some queries!** | query = "I feel lost in life. I feel like there is no purpose of living. How should I deal with this?"
search(query)
query = "I just recently became a parent and I am feeling very nervous. What is the best way to bring up a child?"
search(query)
query = "I had a divorce. I feel like a failure. How should I handle this ... | Input query: How to be confident while making big decisions in life?
Results (after 2.63 seconds):
0.984 somebody says “I am doing this.” somebody says “I am doing this.” So one thing that all of you should do before you make big decisions in your life is, withdraw from these pressures of peers, professors, parents, e... | MIT | notebooks/Semantic_Search.ipynb | KewalMishra/VR |
**Semantic Search x Auxiliary Features**This section is under active development. ---This purpose of this section is to explore two primary frontiers:1. Just semantic search yields satisfactory results, but comes at the cost of compute power. The bottleneck for compute power is the cross-encoder step. This section exp... | _____no_output_____ | MIT | notebooks/Semantic_Search.ipynb | KewalMishra/VR | |
Think Bayes: Chapter 7This notebook presents code and exercises from Think Bayes, second edition.Copyright 2016 Allen B. DowneyMIT License: https://opensource.org/licenses/MIT | from __future__ import print_function, division
% matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import math
import numpy as np
from thinkbayes2 import Pmf, Cdf, Suite, Joint
import thinkplot | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Warm-up exercises **Exercise:** Suppose that goal scoring in hockey is well modeled by a Poisson process, and that the long-run goal-scoring rate of theBoston Bruins against the Vancouver Canucks is 2.9 goals per game.In their next game, what is the probabilitythat the Bruins score exactly 3 goals? Plot the PMF of `k... | # Solution goes here
# Solution goes here
# Solution goes here | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
**Exercise:** Assuming again that the goal scoring rate is 2.9, what is the probability of scoring a total of 9 goals in three games? Answer this question two ways:1. Compute the distribution of goals scored in one game and then add it to itself twice to find the distribution of goals scored in 3 games.2. Use the P... | # Solution goes here
# Solution goes here | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
**Exercise:** Suppose that the long-run goal-scoring rate of theCanucks against the Bruins is 2.6 goals per game. Plot the distributionof `t`, the time until the Canucks score their first goal.In their next game, what is the probability that the Canucks scoreduring the first period (that is, the first third of the gam... | # Solution goes here
# Solution goes here
# Solution goes here | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
**Exercise:** Assuming again that the goal scoring rate is 2.8, what is the probability that the Canucks get shut out (that is, don't score for an entire game)? Answer this question two ways, using the CDF of the exponential distribution and the PMF of the Poisson distribution. | # Solution goes here
# Solution goes here | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
The Boston Bruins problemThe `Hockey` suite contains hypotheses about the goal scoring rate for one team against the other. The prior is Gaussian, with mean and variance based on previous games in the league.The Likelihood function takes as data the number of goals scored in a game. | from thinkbayes2 import MakeNormalPmf
from thinkbayes2 import EvalPoissonPmf
class Hockey(Suite):
"""Represents hypotheses about the scoring rate for a team."""
def __init__(self, label=None):
"""Initializes the Hockey object.
label: string
"""
mu = 2.8
sigma = 0.3
... | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Now we can initialize a suite for each team: | suite1 = Hockey('bruins')
suite2 = Hockey('canucks') | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Here's what the priors look like: | thinkplot.PrePlot(num=2)
thinkplot.Pdf(suite1)
thinkplot.Pdf(suite2)
thinkplot.Config(xlabel='Goals per game',
ylabel='Probability') | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
And we can update each suite with the scores from the first 4 games. | suite1.UpdateSet([0, 2, 8, 4])
suite2.UpdateSet([1, 3, 1, 0])
thinkplot.PrePlot(num=2)
thinkplot.Pdf(suite1)
thinkplot.Pdf(suite2)
thinkplot.Config(xlabel='Goals per game',
ylabel='Probability')
suite1.Mean(), suite2.Mean() | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
To predict the number of goals scored in the next game we can compute, for each hypothetical value of $\lambda$, a Poisson distribution of goals scored, then make a weighted mixture of Poissons: | from thinkbayes2 import MakeMixture
from thinkbayes2 import MakePoissonPmf
def MakeGoalPmf(suite, high=10):
"""Makes the distribution of goals scored, given distribution of lam.
suite: distribution of goal-scoring rate
high: upper bound
returns: Pmf of goals per game
"""
metapmf = Pmf()
... | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Here's what the results look like. | goal_dist1 = MakeGoalPmf(suite1)
goal_dist2 = MakeGoalPmf(suite2)
thinkplot.PrePlot(num=2)
thinkplot.Pmf(goal_dist1)
thinkplot.Pmf(goal_dist2)
thinkplot.Config(xlabel='Goals',
ylabel='Probability',
xlim=[-0.7, 11.5])
goal_dist1.Mean(), goal_dist2.Mean() | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Now we can compute the probability that the Bruins win, lose, or tie in regulation time. | diff = goal_dist1 - goal_dist2
p_win = diff.ProbGreater(0)
p_loss = diff.ProbLess(0)
p_tie = diff.Prob(0)
print('Prob win, loss, tie:', p_win, p_loss, p_tie) | Prob win, loss, tie: 0.4579997823117246 0.37029032604107404 0.1717098916472006
| MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
If the game goes into overtime, we have to compute the distribution of `t`, the time until the first goal, for each team. For each hypothetical value of $\lambda$, the distribution of `t` is exponential, so the predictive distribution is a mixture of exponentials. | from thinkbayes2 import MakeExponentialPmf
def MakeGoalTimePmf(suite):
"""Makes the distribution of time til first goal.
suite: distribution of goal-scoring rate
returns: Pmf of goals per game
"""
metapmf = Pmf()
for lam, prob in suite.Items():
pmf = MakeExponentialPmf(lam, high=2.5,... | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Here's what the predictive distributions for `t` look like. | time_dist1 = MakeGoalTimePmf(suite1)
time_dist2 = MakeGoalTimePmf(suite2)
thinkplot.PrePlot(num=2)
thinkplot.Pmf(time_dist1)
thinkplot.Pmf(time_dist2)
thinkplot.Config(xlabel='Games until goal',
ylabel='Probability')
time_dist1.Mean(), time_dist2.Mean() | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
In overtime the first team to score wins, so the probability of winning is the probability of generating a smaller value of `t`: | p_win_in_overtime = time_dist1.ProbLess(time_dist2)
p_adjust = time_dist1.ProbEqual(time_dist2)
p_win_in_overtime += p_adjust / 2
print('p_win_in_overtime', p_win_in_overtime) | p_win_in_overtime 0.5241451046185259
| MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Finally, we can compute the overall chance that the Bruins win, either in regulation or overtime. | p_win_overall = p_win + p_tie * p_win_in_overtime
print('p_win_overall', p_win_overall) | p_win_overall 0.5480006814331824
| MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Exercises **Exercise:** To make the model of overtime more correct, we could update both suites with 0 goals in one game, before computing the predictive distribution of `t`. Make this change and see what effect it has on the results. | # Solution goes here | _____no_output_____ | MIT | code/chap07-all-exercises.ipynb | JeffreyMinucci/ThinkBayes2 |
Adsorbed Phases on Graphene | import numpy as np
import matplotlib.pyplot as plt
from graphenetools import gt
import re,glob,os,sys
from scipy.signal import argrelextrema
import dgutils.colors as colortools
import dgutils.pypov as pypov
from collections import defaultdict
import importlib
from PIL import Image,ImageOps
from vapory import *
π = np.... | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
Setting the colors | blue = colortools.hex_to_rgb('#0073CD')
grey = colortools.hex_to_rgb('#a7a7a7')
brown = colortools.hex_to_rgb('#e9b68c')
brown = colortools.hex_to_rgb('#926f34')
green = colortools.hex_to_rgb('#15A05E')
red = colortools.hex_to_rgb('#8c0a07') | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
Construct the graphene lattice, $\sqrt{3}\times\sqrt{3}$ adsorbant and bonds | # lattice vectors
aₒ = 1.42
a = (aₒ/2)*np.array([[np.sqrt(3),-np.sqrt(3)],[3,3]])
#√3 x √3
θ = π/6
R = np.array([[np.cos(θ),-np.sin(θ)],[np.sin(θ),np.cos(θ)]])
α = np.matmul(R,np.sqrt(3)*a)
# basis vectors
b = aₒ*np.array([[np.sqrt(3)/2,0],[1/2,1]])
# Box size
L = [8,8]
import sympy
sympy.init_printing(use_unicode=T... | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
The Lattice | C_positions = []
G_centers = []
hex_centers = []
for n1 in range(-12,12):
for n2 in range(-12,12):
G_centers.append(n1*α[:,0] + n2*α[:,1])
C_positions.append(n1*a[:,0] + n2*a[:,1] + b[:,0])
C_positions.append(n1*a[:,0] + n2*a[:,1] + b[:,1])
hex_centers.append(n1*a[:,0] + n2*a[:,1])
... | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
Visualizing the Lattice Vectors | fig,ax = plt.subplots()
#ax.scatter(He_positions[:,0],He_positions[:,1], s=8, color='b')
ax.annotate("",
xy=(a[0,0], a[1,0]), xycoords='data',
xytext=(0, 0), textcoords='data',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3",ec='k'),
)... | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
The Bonds | bonds = np.empty([0,4])
fig,ax = plt.subplots()
NG = len(C_positions)
for i in range(NG):
ri = C_positions[i]
for j in range(i,NG):
rj = C_positions[j]
d = np.linalg.norm(ri-rj)
if d > 0.1 and d < (aₒ+0.1):
ax.plot([ri[0],rj[0]],[ri[1],rj[1]],'-', zorder=-1, lw=0.5,color=gre... | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
Create a graphic of the dual triangular lattice | dual_bonds = np.empty([0,4])
NA = len(hex_centers)
for i in range(NA):
ri = hex_centers[i]
for j in range(i,NA):
rj = hex_centers[j]
d = np.linalg.norm(ri-rj)
if d > 0.1 and d < (np.sqrt(3)*aₒ+0.1):
dual_bonds = np.vstack((dual_bonds,[ri[0],rj[0],ri[1],rj[1]])) | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
Images of Adsorbed Phases Setting the colors and sizes for some objects | col_C = Texture(Finish('ambient','0.2','diffuse','0.8'),Pigment('color',brown,'transmit',0.0))
col_bond = Texture(Finish('phong','0.2'),Pigment('color',brown,'transmit',0.0))
col_He = Texture(Finish('phong','0.9','phong_size',400),Pigment('color',green,'transmit',0.0))
col_He_link = Texture(Finish('phong','0.9','phong_... | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
C1/3 Solid Generate the graphene lattice | sphere = [Sphere([x[i],0, y[i]], r_C, col_C) for i in range(len(x))]
cylinder = [Cylinder([x1[i],0.0,y1[i]],[x2[i],0.0,y2[i]], 0.075,col_bond) for i in range(len(x1))]
sphere.extend([Sphere([cr[0],1.1, cr[1]], r_He, col_He) for cr in He_positions]) | _____no_output_____ | MIT | src/graphene_adsorbed_phases.ipynb | DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.