markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Here I create the code that will perform a specified iteration scheme, with the option of specifying a value for $\omega$.
def space_iterate(method,A,b,resid,**optional): '''Uses sparse matrices''' if ('w' in optional): #print 'w found, it is ', optional['w'] w = optional['w'] else: #print 'no w found, assumed to be 1.17 if needed.' w = 1.17 #w = 1.02 n = max(A.get_shape...
Corlett_Assign3.ipynb
bcorlett/Notebooks_Modelling
mit
The following code will initialize the $[A]$ and $[b]$ matrices according to the inputs, and depending on which code I call, as they use Neumann + Dirichlet and Dirichlet-only boundary conditions, respectively.
def neumann_stable(n,v,u0,Z_f,Z_c,K): #Create Neumann + Dirichlet boundary conditions, yielding matrices A + b A=zeros((3,n)) # For solving for 'n+1' solution for item in range(1,n+1): #Start from bed and work to surface #j-1 if item>1: A[0,item-2]=+(K[item-1]/((Z_f[item]-Z_f[it...
Corlett_Assign3.ipynb
bcorlett/Notebooks_Modelling
mit
1. Sensitivity of the System to Boundary Conditions Note that the spectral radius changes as the boundary conditions change, but not when the values change. The spectral radius is not influenced by boundary condition values per say, but it is influenced by the type of boundary conditions present within the system. This...
#Initialize a comparison n=20 #n must be greater than 6 for my SOR code to work - the issue lies with calculating eigenvalues. K=0.3 v=0.5 u0=0. u1=1. #[A,b]=dirichlet(n,v,u0,u1,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1])) #[A,b]=neumann_stable(n,v,u1,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T...
Corlett_Assign3.ipynb
bcorlett/Notebooks_Modelling
mit
Variations in boundary condition values:
print 'Variations under changing boundary values, using Dirichlet boundary conditions:' print '\n Conditions with u_surface = 1: ' [A,b]=dirichlet(n,v,u0,1,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1])); [Q,I,S]=space_iterate('sor',A,b,1); print '\n\n Conditions with u_surface = 2: ' [A,b]=dirichlet(...
Corlett_Assign3.ipynb
bcorlett/Notebooks_Modelling
mit
Variations in the boundary condition itself:
print 'Variations under changing boundary conditions | Dirichlet v Neumann + Dirichlet:' print '\n\n Conditions with Neumann + Dirichlet: ' [A,b]=neumann_stable(n,v,1,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1])); [Q,I,S]=space_iterate('sor',A,b,1); print '\n\n Conditions with Dirichlet: ' [A,b]=dir...
Corlett_Assign3.ipynb
bcorlett/Notebooks_Modelling
mit
2. Sensitivity of the solution to $\nu$ The convergence of the system is sensitive to the value of $\nu$, as $\nu$ will change the values on the diagonal of the matrix $[A]$, changing the determinate of $[B]$ in the process of calculating its inverse, and thus the spectral radius ($\rho$).
[A,b]=dirichlet(n,0.5,1,0,matrix(arange(0,n+2)).T,matrix(arange(0,n+2)).T,K*ones([n+1,1])) [Q,I,S]=space_iterate('jacobi',A,b,1) [Q,I,S]=space_iterate('gaussseidel',A,b,1) [Q,I,S]=space_iterate('sor',A,b,1) nu=[1.0e3,1.0e2,1.0e1,9.0,8.0,7.0,6.0,5.0,4.0,3.0,2.0,1.0e0,.9,.8,.7,.6,.5,.4,.3,.2,1.0e-1,1.0e-2,1.0e-3] ...
Corlett_Assign3.ipynb
bcorlett/Notebooks_Modelling
mit
Reviewing the effect of $\nu$ After plotting these values, it became apparent that further investigation of the SOR factor was needed. After testing the matrices with varying values for this factor, it appears that the factor can be chosen specifically for given conditions to maximize the code's efficiency. The downsid...
K=1. v=1. u0=0. u1=1. N=(arange(0,20)+1)*10 #fig, axs = plt.subplots(1,2) #,ax=axs[1] plt.figure(figsize=(20,5)) plt.subplot(121) for R in range(0,size(N)): #Varies the value of n [A,b]=dirichlet(N[R],v,1,0,matrix(arange(0,N[R]+2)).T,matrix(arange(0,N[R]+2)).T,K*ones([N[R]+1,1])) [Q,Is,Ss]=space_iterate...
Corlett_Assign3.ipynb
bcorlett/Notebooks_Modelling
mit
If you are using Vertex AI Workbench, your environment already meets all the requirements to run this notebook. You can skip this step.
! pip install google-cloud-aiplatform ! pip install fsspec ! pip install gcsfs
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Set your project ID If you don't know your project ID, you may be able to get your project ID using gcloud.
import os PROJECT_ID = "" # Get your Google Cloud project ID from gcloud if not os.getenv("IS_TESTING"): shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID: ", PROJECT_ID)
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Otherwise, set your project ID here.
if PROJECT_ID == "" or PROJECT_ID is None: PROJECT_ID = "[your-project-id]" # @param {type:"string"} %env GOOGLE_CLOUD_PROJECT PROJECT_ID print("Project ID: ", PROJECT_ID)
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Authenticate your Google Cloud account If you are using Vertex AI Workbench managed notebooks or user-managed notebooks, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, foll...
import os import sys # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. # The Google Cloud Notebook product has specific requirements...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Import required libraries and define constants
import os import random from typing import Dict, List, Optional, Sequence, Tuple, Union import matplotlib.pyplot as plt import pandas as pd from google.cloud import aiplatform, storage from wordcloud import STOPWORDS, WordCloud LOCATION = "us-central1" BUCKET_NAME = "{your_bucket_name}"
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Load the data <a name="section-5"></a>
phrases = pd.read_csv( "gs://vertex_ai_managed_services_demo/sentiment_analysis/stanfordSentimentTreebank/dictionary.txt", sep="|", ) phrases.columns = ["text", "phrase ids"] scores = pd.read_csv( "gs://vertex_ai_managed_services_demo/sentiment_analysis/stanfordSentimentTreebank/sentiment_labels.txt", s...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
The data itself doesn't contain any feature names and thus needs its columns to be renamed. dictionary.txt contains all phrases and their IDs, separated by a vertical line |. sentiment_labels.txt contains all phrase ids and the corresponding sentiment scores, separated by a vertical line. Four classes are created by ma...
VERYNEGATIVE = 0 NEGATIVE = 1 POSITIVE = 2 VERYPOSITIVE = 3 bins = [0, 0.25, 0.5, 0.75, 1] labels = [VERYNEGATIVE, NEGATIVE, POSITIVE, VERYPOSITIVE] df["label"] = pd.cut(df["sentiment values"], bins=bins, labels=labels) print(df.head())
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Prepare the training data <a name="section-6"></a> To train a sentiment analysis model, you provide representative samples of the type of content you want AutoML Natural Language to analyze, each labeled with a value indicating how positive the sentiment is within the content. The sentiment score is an integer ranging ...
subset_data = df[df["label"].isin([VERYNEGATIVE, VERYPOSITIVE])].reset_index(drop=True) subset_data.head() subset_data["label"] = subset_data["label"].apply(lambda x: 1 if x == 3 else 0) subset_data["ml_use"] = "" subset_data["sentimentMax"] = 1 subset_data = subset_data[["ml_use", "text", "label", "sentimentMax"]] pr...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create an import csv
FILE_NAME = "sentiment_data.csv" subset_data.to_csv(FILE_NAME, index=False) # Upload the saved model file to Cloud Storage BLOB_PATH = "sentiment_analysis/" BLOB_NAME = os.path.join(BLOB_PATH, FILE_NAME) bucket = storage.Client().bucket(BUCKET_NAME) blob = bucket.blob(BLOB_NAME) blob.upload_from_filename(FILE_NAME)
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a dataset in Vertex AI <a name="section-7"></a> The following code uses the Vertex AI SDK for Python to both create a dataset and import data.
def import_data_text_sentiment_analysis( project: str, location: str, display_name: str, src_uris: Union[str, List[str]], sync: bool = True, ): aiplatform.init(project=project, location=location) ds = aiplatform.TextDataset.create( display_name=display_name, gcs_source=src_u...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Train the model using Vertex AI <a name="section-8"></a> The following code uses the Vertex AI SDK for Python to train the model on the above created dataset. You can get the dataset id from the Dataset section of Vertex AI in the console or from the resource name in the dataset object created above. You can specify ho...
def create_training_pipeline_text_sentiment_analysis( project: str, location: str, display_name: str, dataset_id: str, model_display_name: Optional[str] = None, sentiment_max: int = 10, training_fraction_split: float = 0.8, validation_fraction_split: float = 0.1, test_fraction_split:...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Deploy the model to the endpoint <a name="section-9"></a> Create the endpoint
def create_endpoint( project: str, display_name: str, location: str, ): aiplatform.init(project=project, location=location) endpoint = aiplatform.Endpoint.create( display_name=display_name, project=project, location=location, ) print(endpoint.display_name) print...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Deploy the model The following code uses the Vertex AI SDK for Python to deploy the model to a endpoint. You can get the model id from the models section of Vertex AI in the console
def deploy_model_with_automatic_resources( project, location, model_name: str, endpoint: Optional[aiplatform.Endpoint] = None, deployed_model_display_name: Optional[str] = None, traffic_percentage: Optional[int] = 0, traffic_split: Optional[Dict[str, int]] = None, min_replica_count: int ...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Prediction <a name="section-10"></a> After deploying the model to an endpoint use the Vertex AI API to request an online prediction. Filter the data that you haven't used for the training and pick longer reviews to test the model.
def predict_text_sentiment_analysis_sample(endpoint, content): print(content) response = endpoint.predict(instances=[{"content": content}], parameters={}) for prediction_ in response.predictions: print(prediction_) test_data_pos = df[df["label"].isin([POSITIVE])].reset_index(drop=True) test_data_n...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Here is the prediction results on the positive samples. The model did a good job on predicting positive sentiment for positive reviews. The first and last review predictions are false negatives.
for review in test_data_pos[0:10]: predict_text_sentiment_analysis_sample(endpoint, review)
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Here is the prediction results on the negative reviews. Out of 10 reviews below 7 negative reviews are correctly predicted with negative sentiment
for review in test_data_neg[0:10]: predict_text_sentiment_analysis_sample(endpoint, review)
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Review visualization <a name="section-11"></a> Visualize the positive and negative reviews in the data.
data_pos = df[df["label"].isin([VERYPOSITIVE])].reset_index(drop=True) data_neg = df[df["label"].isin([VERYNEGATIVE])].reset_index(drop=True) data_neg = data_neg.text.values data_pos = data_pos.text.values
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create the word cloud by removing the common words to highlight the words representing positive and negative samples.
# Python program to generate WordCloud def plot_word_cloud(data, common_words): comment_words = "" stopwords = set(STOPWORDS) for val in data: tokens = val.split() for i in range(len(tokens)): tokens[i] = tokens[i].lower() for each in common_words: if ...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Plot a word cloud of negative reviews.
plot_word_cloud( data_neg, [ "movie", "film", "story", "audience", "director", "watch", "seem", "world", "one", "make", "way", "character", "much", "time", "even", "take", "s",...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Plot a word cloud of positive reviews.
plot_word_cloud( data_pos, [ "movie", "film", "story", "audience", "director", "watch", "seem", "world", "one", "make", "way", "character", "much", "time", "even", "take", "s",...
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Clean up <a name="section-12"></a> Undeploy the model from the endpoint.
DEPLOYED_MODEL_ID = "" endpoint.undeploy(deployed_model_id=DEPLOYED_MODEL_ID)
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Delete the endpoint.
endpoint.delete()
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Delete the dataset.
dataset.delete()
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Delete the model.
model.delete()
notebooks/community/managed_notebooks/sentiment_analysis/Sentiment_Analysis.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Project 1: Quick Theory Validation
from collections import Counter import numpy as np positive_counts = Counter() negative_counts = Counter() total_counts = Counter() for i in range(len(reviews)): if(labels[i] == 'POSITIVE'): for word in reviews[i].split(" "): positive_counts[word] += 1 total_counts[word] += 1 e...
tutorials/sentiment_network/Sentiment Classification - Project 1 Solution.ipynb
xpharry/Udacity-DLFoudation
mit
The raw recordings from Green Bank Telescope can be downladed from the Breakthrough Listen Open Data Archive. Here we are using this recording, which was made on 2015-12-30 00:00:00. You can find an analysis of this recording in the breakthrough Github repository. The raw recordings are in GUPPI format. Below we have a...
class GuppiFile(): """A class to read data from a file in GUPPI format""" # we only support 8bit files def __init__(self, filename, header_len, blocsize, npol, nchan, centre_freq, chan_bw): self.f = open(filename, 'rb') self.header_len = header_len self.blocsize = blocsize se...
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
To run the code below, make sure that you have downloaded the GUPPI file and placed it in the same folder as this notebook. This opens the GUPPI file with the correct parameters.
guppi = GuppiFile('blc3_guppi_57386_VOYAGER1_0004.0000.raw', header_len = 0x1900, blocsize = 132251648, npol = 2, nchan = 64, centre_freq = 8493.75e6, chan_bw = 2.9296875e6) voyager_freq = 8420.2164537e6 voyager_chan = guppi.get_channel(voyager_fr...
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Now we read the first 50 blocks of the file, compute an FFT around the frequency of the Voyager 1 signal and show the power spectrums for both polarizations. Note that the Voyager 1 signal is left circularly polarized, so all the signal is in the first plot. The carrier and data sidebands are visible.
signal = np.concatenate([guppi.read_block_from_channel(x, voyager_chan) for x in range(50)], axis = 1) nsamples = signal.shape[1] # Amplitude balance between channels (to be used later) amplitude_balance = np.sqrt(np.sum(np.abs(signal)**2, axis = 1))[::-1] hz_per_bin = guppi.chan_bw / nsamples centre_bin = nsamples /...
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Note that the two polarization channels have different gain. The noise floor in the left channel is around 110dB, while the noise floor in the right channel is around 100dB. To compensate for this, we multiply each channel by the average power of the other channel. This ensures that both channels have the same power.
corrected_fft = np.array(np.diag(amplitude_balance) * np.mat(fft)) del fft
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Now we select a frequency range of 10Hz about the Voyager carrier. We will compute the Stokes parameters using this frequency range as a signal in the frequency domain.
width = 10 selection = np.logical_and(voyager_freq - width/2 <= frequencies, frequencies <= voyager_freq + width/2) plt.title('Voyager 1 carrier (left is LCP, green is RCP)') plt.xlabel('Frequency (Hz)') plt.ylabel('Power (dB)') plt.plot(frequencies[selection], 20 * np.log10(np.abs(corrected_fft)[0,...][selection])) pl...
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
The class below computes the Stokes parameters of a signal in (LCP, RCP) polarization. The signal can be in the time domain or in the frequency domain.
StokesParameters = collections.namedtuple('StokesParameters', ['I', 'Q', 'U', 'V']) def compute_stokes_LR(x): """Compute stokes parameters of signal in time or frequency domain in dual (LCP,RCP) polarization""" def combine_powers(x, coeffs): return np.dot(np.sum(np.abs(x)**2, axis = 1), coeffs) def...
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
We use the class above to compute the Stokes parameters of the Voyager 1 carrier. We expect to obtain parameters matching those of a LCP signal (V positive and near I, Q and U small).
stokes = compute_stokes_LR(corrected_fft[...,selection]) stokes
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Now we can compute Ip, the polarized intensity, and the polarization degree. We see that the signal is highly polarized.
Ip = np.sqrt(stokes.V**2 + stokes.Q**2 + stokes.U**2) polarization_degree = Ip/stokes.I polarization_degree
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Finally, we compute L, the complex intensity of linear polarization and show the degree of linear polarization (which is small, as expected) and the angle of the linear polarization.
L = stokes.Q + 1j*stokes.U (np.abs(L)/Ip, np.angle(L)/2*180/np.pi)
VoyagerGBT.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
A. The semantic connections: keywords Based on a first iterative search on "open science", the term frequently occurs in connection with: open access open data reproducible research data sharing reproducibility big data collaboration metadata meta-analysis research data Here it is reasonable to conclude that "open sc...
# General libraries %matplotlib inline import pandas as pd import warnings warnings.simplefilter(action = "ignore", category = FutureWarning) # Supress some meaningless warnings. #from tabulate import tabulate from collections import Counter import seaborn as sns import numpy as np from itertools import combinations i...
openscienceliterature.ipynb
christopherkullenberg/openscienceliterature
mit
A. Web of Science - Recursion 1. Search details Date: 20170121, General Search. Search string: TS="open science" Result: 544 Records. Important note on parsing the WoS tsv files Delete the column BJ since it is erronneous. The separator is tab, and there is no delimiter.
#fel data , error_bad_lines=False df = pd.read_csv('.data/WoS549recs20170121.tsv', sep="\t", encoding='utf-8') # Input: web of science tsv file, utf-8 encoding. df.head(3) # Print this for explanation of WoS columns woskeyfile = open('woskeys.txt') woskeys = woskeyfile.read() #print(woskeys) dfTC = df.sort('TC', as...
openscienceliterature.ipynb
christopherkullenberg/openscienceliterature
mit
Keyword analysis
# Read all keywords into a list. allkeywords = [] for keyword in df.DE: k = str(keyword) keywordsperarticle = k.split('; ') for word in keywordsperarticle: allkeywords.append(word.lower()) # make all lower case for better string matching. print("Total number of keywords: " + str(len(allke...
openscienceliterature.ipynb
christopherkullenberg/openscienceliterature
mit
Journal analysis
# To get only journal articles, select df.SO[df['PT'] == 'J'] for journal in Counter(frequentjournals(df.SO[df['PT'] == 'J'] )).most_common(10): print(journal)
openscienceliterature.ipynb
christopherkullenberg/openscienceliterature
mit
Scopus - Recursive search: Iteration 1 Search date: 20170120 (TITLE-ABS-KEY" Search string: "open science" Records: 769
df2 = pd.read_csv('.data/scopusRecursionOne769recs20170120.csv', encoding="utf-8") # Print this for Scopus column names #for header in list(df2.columns.values): # print(header) #df2['Document Type'] df2TC = df2.sort('Cited by', ascending=False) # Order dataframe by times cited df2TC.tail(3) # NOTE: there is a cry...
openscienceliterature.ipynb
christopherkullenberg/openscienceliterature
mit
Journal analysis
# For journal articles only: df2['Source title'][df2['Document Type'] == 'Article'] for journal in Counter(frequentjournals(df2['Source title'][df2['Document Type'] == 'Article'])).most_common(10): print(journal)
openscienceliterature.ipynb
christopherkullenberg/openscienceliterature
mit
C. Scopus Recursive search: Iteration 2 Scopus Search date: 20170120 (TITLE-ABS-KEY) Note: Scopus will not include Author Keywords when exporting this large ammount of data. Search string: Included: "open science" OR "data sharing" OR "open data" OR "open science grid" Excluded * "open access" - Too broad, gets around...
df3 = pd.read_csv('.data/scopusRecursionTwo14146recs20170120.csv') df3.tail(3) # Verify all data is there. # Create a time series of the publications. Some data cleaning is needed: df3dropna = df3.Year.dropna() # Drop empty values in years df3years = pd.DataFrame(df3dropna.astype(int)) # Convert existing years to i...
openscienceliterature.ipynb
christopherkullenberg/openscienceliterature
mit
Journal analysis
for journal in Counter(frequentjournals(df3['Source title'][df3['Document Type'] == "Article"])).most_common(10): print(journal) WoSyears = [] for year in df.PY.dropna(): if year > 1990.0: WoSyears.append(int(year)) #print(sorted(WoSyears)) Scopusyears = [] for year in df2['Year'].dr...
openscienceliterature.ipynb
christopherkullenberg/openscienceliterature
mit
Gradient Edge Detection Because edges correspond to locations in images where the brightness undergoes a sharp change, a naive idea would be to differentiate the image and look for places where the magnitude of the derivative is large. For many simple cases with regular geometry topologies, this simple method could wor...
psource(gradient_edge_detector)
notebooks/chapter24/Image Edge Detection.ipynb
Chipe1/aima-python
mit
Example Now let's try the detector for real case pictures. First, we will show the original picture before edge detection: <img src="images/stapler.png" width="500"/> We will use matplotlib to read the image as a numpy ndarray:
import matplotlib.pyplot as plt import numpy as np import matplotlib.image as mpimg im =mpimg.imread('images/stapler.png') print("image height:", len(im)) print("image width:", len(im[0]))
notebooks/chapter24/Image Edge Detection.ipynb
Chipe1/aima-python
mit
The code shows we get an image with a size of $787*590$. gaussian_derivative_edge_detector can extract images in both x and y direction and then put them together in a ndarray:
edges = gradient_edge_detector(im) print("image height:", len(edges)) print("image width:", len(edges[0]))
notebooks/chapter24/Image Edge Detection.ipynb
Chipe1/aima-python
mit
The edges are in the same shape of the original image. Now we will try print out the image, we implemented a show_edges function to do this:
show_edges(edges)
notebooks/chapter24/Image Edge Detection.ipynb
Chipe1/aima-python
mit
We can see that the edges are extracted well. We can use the result of this simple algorithm as a baseline and compare the results of other algorithms to it. Derivative of Gaussian When considering the situation when there is strong noise in an image, the ups and downs of the noise will induce strong peaks in the gradi...
x_filter = scipy.signal.convolve2d(gaussian_filter, np.asarray([[1, -1]]), 'same') y_filter = scipy.signal.convolve2d(gaussian_filter, np.asarray([[1], [-1]]), 'same')
notebooks/chapter24/Image Edge Detection.ipynb
Chipe1/aima-python
mit
Then both of the filters are applied to the input image to extract the x and y direction edges. For detailed implementation, please view by:
psource(gaussian_derivative_edge_detector)
notebooks/chapter24/Image Edge Detection.ipynb
Chipe1/aima-python
mit
Example Now let's try again on the stapler image and plot the extracted edges:
e = gaussian_derivative_edge_detector(im) show_edges(e)
notebooks/chapter24/Image Edge Detection.ipynb
Chipe1/aima-python
mit
We can see that the extracted edges are more similar to the original one. The resulting edges are depending on the initial Gaussian kernel size and how it is initialized. Laplacian Edge Detector Laplacian is somewhat different from the methods we have discussed so far. Unlike the above kernels which are only using the ...
e = laplacian_edge_detector(im) show_edges(e)
notebooks/chapter24/Image Edge Detection.ipynb
Chipe1/aima-python
mit
コピュラ入門 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/probability/examples/Gaussian_Copula"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tenso...
import numpy as np import matplotlib.pyplot as plt import tensorflow.compat.v2 as tf tf.enable_v2_behavior() import tensorflow_probability as tfp tfd = tfp.distributions tfb = tfp.bijectors
site/ja/probability/examples/Gaussian_Copula.ipynb
tensorflow/docs-l10n
apache-2.0
[copula](https://en.wikipedia.org/wiki/Copula_(probability_theory%29)とは、ランダム変数間の依存関係を捉えるための古典的な手法です。より正式には、コピュラは、マージナリゼーションによって $U_i \sim \text{Uniform}(0, 1)$ が得られる多変量分布 $C(U_1, U_2, ...., U_n)$ です。 コピュラを使用すると任意の周辺分布を持つ多変量分布を作成できるため、コピュラは非常に興味深い関数と言えます。以下にそのレシピを示します。 確率積分変換を使って、任意の連続分布 R.V. $X$ を一様分布 $F_X(X)$ に変換します。...
class GaussianCopulaTriL(tfd.TransformedDistribution): """Takes a location, and lower triangular matrix for the Cholesky factor.""" def __init__(self, loc, scale_tril): super(GaussianCopulaTriL, self).__init__( distribution=tfd.MultivariateNormalTriL( loc=loc, scale_tril=scale_tr...
site/ja/probability/examples/Gaussian_Copula.ipynb
tensorflow/docs-l10n
apache-2.0
しかし、このようなモデルの力は、確率積分変換を使用して任意の R.V. にコピュラを使用するところにあります。こうすることで、任意の周辺分布を指定し、コピュラを使って接合することができます。 次のモデルから開始します。 $$\begin{align} X &amp;\sim \text{Kumaraswamy}(a, b) \ Y &amp;\sim \text{Gumbel}(\mu, \beta) \end{align}$$ そして、コピュラを使って、二変量 R.V. $Z$ を取得します。これには、周辺分布の Kumaraswamy と Gumbel があります。 まず、これらの 2 つの R.V. で生成された分布をプロット...
a = 2.0 b = 2.0 gloc = 0. gscale = 1. x = tfd.Kumaraswamy(a, b) y = tfd.Gumbel(loc=gloc, scale=gscale) # Plot the distributions, assuming independence x_axis_interval = np.linspace(0.01, 0.99, num=200, dtype=np.float32) y_axis_interval = np.linspace(-2., 3., num=200, dtype=np.float32) x_grid, y_grid = np.meshgrid(x_a...
site/ja/probability/examples/Gaussian_Copula.ipynb
tensorflow/docs-l10n
apache-2.0
異なる周辺分布を使用した同時分布 次に、ガウスコピュラを使用して分布を接合し、それをプロットします。ここでも、TransformedDistribution を適切な Bijector に適用して、目的の周辺分布を取得します。 具体的には、さまざまなベクトルで異なるバイジェクターを適用(全単射変換のままです)する Blockwise バイジェクターを使用します。 これで、必要としているコピュラを定義できるようになりました。ターゲットとなる周辺分布のリスト(バイジェクターとしてエンコード)があれば、コピュラを使用し、指定された周辺分布を持つ新しい分布を簡単に構築できます。
class WarpedGaussianCopula(tfd.TransformedDistribution): """Application of a Gaussian Copula on a list of target marginals. This implements an application of a Gaussian Copula. Given [x_0, ... x_n] which are distributed marginally (with CDF) [F_0, ... F_n], `GaussianCopula` represents an application of the Cop...
site/ja/probability/examples/Gaussian_Copula.ipynb
tensorflow/docs-l10n
apache-2.0
最後に、このガウスコピュラを実際に使用してみましょう。バリアンス 1 に対応する $\begin{bmatrix}1 &amp; 0\rho &amp; \sqrt{(1-\rho^2)}\end{bmatrix}$ のコレスキー、そして多変量正規分布の相関 $\rho$ を使用します。 いくつかのケースを見てみましょう。
# Create our coordinates: coordinates = np.concatenate( [x_grid[..., np.newaxis], y_grid[..., np.newaxis]], -1) def create_gaussian_copula(correlation): # Use Gaussian Copula to add dependence. return WarpedGaussianCopula( loc=[0., 0.], scale_tril=[[1., 0.], [correlation, tf.sqrt(1. - correlation...
site/ja/probability/examples/Gaussian_Copula.ipynb
tensorflow/docs-l10n
apache-2.0
最後に、実際に求めていた周辺分布を実際に取得することを確認しましょう。
def kumaraswamy_pdf(x): return tfd.Kumaraswamy(a, b).prob(np.float32(x)) def gumbel_pdf(x): return tfd.Gumbel(gloc, gscale).prob(np.float32(x)) copula_samples = [] for copula in copulas: copula_samples.append(copula.sample(10000)) plot_rows = len(correlations) plot_cols = 2 # for 2 densities [kumarswamy...
site/ja/probability/examples/Gaussian_Copula.ipynb
tensorflow/docs-l10n
apache-2.0
Upload Activity results Workflow activities are (optionally) uniquely labeled by the Workflow Definition. This label allows clients to upload metadata and files to activities by label. In this example, we create a new XX activity within an existing workflow.
# TODO source, destination metadata = {'custom_attributes': {'my-attribute': 1}} resources = {'resource-label': '/Users/barry/Desktop/Ovation Demo Files/results.txt'} workflow_id = input('Workflow ID: ') activity_label = input('Activity label: ')
examples/lab/workflow-activity-upload.ipynb
physion/ovation-python
gpl-3.0
For illustration, we view the Workflow, showing links.activity_label.related, the URL where create_activity will POST the new Activity data
workflow = s.get(s.path('workflows', workflow_id)) pprint(workflow.workflow)
examples/lab/workflow-activity-upload.ipynb
physion/ovation-python
gpl-3.0
Now, let's create the activity.
activity = workflows.create_activity(s, workflow_id, activity_label, data=metadata, resources=resources, progress=tqdm)
examples/lab/workflow-activity-upload.ipynb
physion/ovation-python
gpl-3.0
Numerical Methods for Initial Value Problems We now turn towards time dependent PDEs. Before moving to the full PDEs we will explore numerical methods for systems of ODEs that are initial value problems of the general form $$ \frac{\text{d} \vec{u}}{\text{d}t} = \vec{f}(t, \vec{u}) ~~~~ \vec{u}(0) = \vec{u}_0 $$ w...
t = numpy.linspace(0.0, 1.6e3, 100) c_0 = 1.0 decay_constant = numpy.log(2.0) / 1600.0 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(t, 1.0 * numpy.exp(-decay_constant * t)) axes.set_title("Radioactive Decay with $t_{1/2} = 1600$ years") axes.set_xlabel('t (years)') axes.set_ylabel('$c$') axes.set_ylim...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Examples: Complex radioactive decay (or chemical system). Chain of decays from one species to another. $$\begin{aligned} \frac{\text{d} c_1}{\text{d}t} &= -\lambda_1 c_1 \ \frac{\text{d} c_2}{\text{d}t} &= \lambda_1 c_1 - \lambda_2 c_2 \ \frac{\text{d} c_2}{\text{d}t} &= \lambda_2 c_3 - \lambda_3 c_3 \end...
import scipy.integrate as integrate def f(t, u, mu=5): return numpy.array([u[1], mu * (1.0 - u[0]**2) * u[1] - u[0]]) t = numpy.linspace(0.0, 100, 1000) u = numpy.empty((2, t.shape[0])) u[:, 0] = [0.1, 0.0] integrator = integrate.ode(f) integrator.set_integrator("dopri5") integrator.set_initial_value(u[:, 0]) f...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Examples: Heat Equation Let's try to construct a system of ODEs that represents the heat equation $$ u_t = u_{xx}. $$ If we discretize the right hand side with second order, centered differences with $m$ points we would have $$ \frac{\text{d}}{\text{d} t} U_i(t) = \frac{U_{i+1}(t) - 2 U_i(t) + U_{i-1}(t)}{\Del...
t = numpy.linspace(0.0, 1.6e3, 100) c_0 = 1.0 decay_constant = numpy.log(2.0) / 1600.0 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(t, c_0 * numpy.exp(-decay_constant * t), label="True Solution") # Plot Euler step dt = 1e3 u_np = c_0 + dt * (-decay_constant * c_0) axes.plot((0.0, dt), (c_0, u_np), 'k'...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
A similar method can be derived if we consider instead using the second order accurate central difference: $$\frac{U^{n+1} - U^{n-1}}{2\Delta t} = f(t_{n}, U^{n})$$ this method is known as the midpoint or leap-frog method. Note that the way we have written this method requires a previous function evaluation and techni...
t = numpy.linspace(0.0, 1.6e3, 100) c_0 = 1.0 decay_constant = numpy.log(2.0) / 1600.0 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(t, c_0 * numpy.exp(-decay_constant * t), label="True Solution") # Plot Euler step dt = 1e3 u_np = c_0 + dt * (-decay_constant * c_0 * numpy.exp(-decay_constant * dt / 2.0...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Similar to forward Euler is the backward Euler method which, as you may have guessed, evaluates the function $f$ at the updated time so that $$ U^{n+1} = U^n + \Delta t f(t_{n+1}, U^{n+1}). $$ Schemes where the function $f$ is evaluated at the unknown time are called implicit methods.
t = numpy.linspace(0.0, 1.6e3, 100) c_0 = 1.0 decay_constant = numpy.log(2.0) / 1600.0 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(t, c_0 * numpy.exp(-decay_constant * t), label="True Solution") # Plot Euler step dt = 1e3 u_np = c_0 + dt * (-decay_constant * c_0 * numpy.exp(-decay_constant * dt)) axe...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Another simple implicit method is based on integration using the trapezoidal method. The scheme is $$ \frac{U^{n+1} - U^{n}}{\Delta t} = \frac{1}{2} (f(U^n) + f(U^{n+1})) $$
c_0 = 1.0 decay_constant = numpy.log(2.0) / 1600.0 t_exact = numpy.linspace(0.0, 1.6e3, 100) u_exact = c_0 * numpy.exp(-decay_constant * t_exact) # Implement trapezoidal method t = numpy.linspace(0.0, 1.6e3, 10) delta_t = t[1] - t[0] u = numpy.empty(t.shape) u[0] = c_0 integration_constant = (1.0 - decay_constant * de...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Error Analysis Truncation Errors We can define truncation errors the same as we did before where we insert the true solution of the ODE into the difference equation and use Taylor series expansions. $$ \tau^n = \frac{1}{\Delta t} [U^{n+1} - u(t + \Delta t)] $$ Similarly if we know $$ \lim_{\Delta t \rightarrow ...
# Compare accuracy between Euler and Leap-Frog f = lambda t, u: -u u_exact = lambda t: numpy.exp(-t) u_0 = 1.0 t_f = 10.0 num_steps = [2**n for n in xrange(4,10)] delta_t = numpy.empty(len(num_steps)) error_euler = numpy.empty(len(num_steps)) error_trap = numpy.empty(len(num_steps)) error_leapfrog = numpy.empty(len(nu...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
One-Step Errors There is another definition of local truncation error sometimes used in ODE numerical methods called the one-step error which is slightly different than our local truncation error definition. Our definition uses the direct discretization of the derivatives to find the LTE where as this alternative base...
# Implement and compare the two-stage and 4-stage Runge-Kutta methods f = lambda t, u: -u t_exact = numpy.linspace(0.0, 10.0, 100) u_exact = numpy.exp(-t_exact) N = 50 t = numpy.linspace(0, 10.0, N) delta_t = t[1] - t[0] U_2 = numpy.empty(t.shape) U_4 = numpy.empty(t.shape) U_2[0] = 1.0 U_4[0] = 1.0 for (n, t_n) in ...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Linear Multi-Step Methods Multi-step methods (as introduced via the leap-frog method) are ODE methods that require multiple time step evaluations to work. Some of the advanatages of using a multi-step method rather than one-step method included Taylor series methods require differentiating the given equation which ca...
# Use 2-step Adams-Bashforth to compute solution f = lambda t, u: -u t_exact = numpy.linspace(0.0, 10.0, 100) u_exact = numpy.exp(-t_exact) N = 100 t = numpy.linspace(0, 10.0, N) delta_t = t[1] - t[0] U = numpy.empty(t.shape) # Use RK-2 to start the method U[0] = 1.0 U[1] = U[0] + 0.5 * delta_t * f(t[0], U[0]) U[1] ...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Adams-Moulton Methods The Adams-Moulton methods are the implicit versions of the Adams-Bashforth methods. Since this gives one additional parameter to use $\beta_r$ these methods are generally one order of accuracy greater than their counterparts. $$\begin{aligned} &\text{1-step:}& &U^{n+1} = U^n &+& \frac{\Delta t}{...
# Use 2-step Adams-Moulton to compute solution # u' = - decay u decay_constant = 1.0 f = lambda t, u: -decay_constant * u t_exact = numpy.linspace(0.0, 10.0, 100) u_exact = numpy.exp(-t_exact) N = 20 t = numpy.linspace(0, 10.0, N) delta_t = t[1] - t[0] U = numpy.empty(t.shape) U[0] = 1.0 U[1] = U[0] + 0.5 * delta_t *...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Truncation Error for Multi-Step Methods We can again find the truncation error in general for linear multi-step methods: $$\begin{aligned} \tau^n &= \frac{1}{\Delta t} \left [\sum^r_{j=0} \alpha_j u(t_{n+j}) - \Delta t \sum^r_{j=0} \beta_j f(t_{n+j}, u(t_{n+j})) \right ] \end{aligned}$$ Using the general expansion ...
# Compare accuracy between RK-2, AB-2 and AM-2 f = lambda t, u: -u u_exact = lambda t: numpy.exp(-t) t_f = 10.0 num_steps = [2**n for n in xrange(4,10)] delta_t = numpy.empty(len(num_steps)) error_rk = numpy.empty(len(num_steps)) error_ab = numpy.empty(len(num_steps)) error_am = numpy.empty(len(num_steps)) for (i, N)...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
Predictor-Corrector Methods One way to simplify the Adams-Moulton methods so that implicit evaluations are not needed is by estimating the required implicit function evaluations with an explicit method. These are often called predictor-corrector methods as the explicit method provides a prediction of what the solution...
# One-step Adams-Bashforth-Moulton f = lambda t, u: -u t_exact = numpy.linspace(0.0, 10.0, 100) u_exact = numpy.exp(-t_exact) N = 100 t = numpy.linspace(0, 10.0, N) delta_t = t[1] - t[0] U = numpy.empty(t.shape) U[0] = 1.0 for n in xrange(t.shape[0] - 1): U[n+1] = U[n] + delta_t * f(t[n], U[n]) U[n+1] = U[n]...
07_ivp.ipynb
eramirem/numerical-methods-pdes
cc0-1.0
TPU detection
try: # detect TPUs tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect() # TPU detection strategy = tf.distribute.TPUStrategy(tpu) except ValueError: # detect GPUs strategy = tf.distribute.MirroredStrategy() # for GPU or multi-GPU machines #strategy = tf.distribute.get_strategy() # default s...
courses/fast-and-lean-data-science/07_Keras_Flowers_TPU_playground.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Configuration
GCS_PATTERN = 'gs://flowers-public/tfrecords-jpeg-192x192-2/*.tfrec' IMAGE_SIZE = [192, 192] if tpu: BATCH_SIZE = 16*strategy.num_replicas_in_sync # A TPU has 8 cores so this will be 128 else: BATCH_SIZE = 32 # On Colab/GPU, a higher batch size does not help and sometimes does not fit on the GPU (OOM) VALIDATIO...
courses/fast-and-lean-data-science/07_Keras_Flowers_TPU_playground.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Read images and labels from TFRecords
def read_tfrecord(example): features = { "image": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring "class": tf.io.FixedLenFeature([], tf.int64), # shape [] means scalar "one_hot_class": tf.io.VarLenFeature(tf.float32), } example = tf.io.parse_single_example(example...
courses/fast-and-lean-data-science/07_Keras_Flowers_TPU_playground.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
training and validation datasets
def get_batched_dataset(filenames, train=False): dataset = load_dataset(filenames) dataset = dataset.cache() # This dataset fits in RAM if train: # Best practices for Keras: # Training dataset: repeat then batch # Evaluation dataset: do not repeat dataset = dataset.repeat() dataset = dataset.bat...
courses/fast-and-lean-data-science/07_Keras_Flowers_TPU_playground.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Model [WORK REQUIRED] train the model as it is, with a single convolutional layer Accuracy 40%... Not great. add additional convolutional layers interleaved with max-pooling layers. Try also adding a second dense layer. For example:<br/> conv 3x3, 16 filters, relu<br/> conv 3x3, 30 filters, relu<br/> max pool 2x2<br/>...
with strategy.scope(): # this line is all that is needed to run on TPU (or multi-GPU, ...) model = tf.keras.Sequential([ ### tf.keras.layers.InputLayer(input_shape=[*IMAGE_SIZE, 3]), tf.keras.layers.Conv2D(kernel_size=3, filters=20, padding='same', activation='relu'), # # YOUR LAYERS H...
courses/fast-and-lean-data-science/07_Keras_Flowers_TPU_playground.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Training
EPOCHS = 20 history = model.fit(training_dataset, steps_per_epoch=steps_per_epoch, epochs=EPOCHS, validation_data=validation_dataset) print(history.history.keys()) display_training_curves(history.history['accuracy'], history.history['val_accuracy'], 'accuracy', 211) display_training_curves(history...
courses/fast-and-lean-data-science/07_Keras_Flowers_TPU_playground.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Predictions
# randomize the input so that you can execute multiple times to change results permutation = np.random.permutation(160) some_flowers, some_labels = (some_flowers[permutation], some_labels[permutation]) predictions = model.predict(some_flowers, batch_size=16) evaluations = model.evaluate(some_flowers, some_labels, batc...
courses/fast-and-lean-data-science/07_Keras_Flowers_TPU_playground.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Load some double-well data
trjs = load_doublewell(random_state=0)['trajectories'] plt.hist(np.concatenate(trjs), bins=50, log=True) plt.ylabel('Frequency') plt.show()
examples/bayesian-msm.ipynb
liyigerry/msm_test
apache-2.0
We'll discretize the space using 10 states And the build one MSM using the MLE transition matrix estimator, and one with the Bayesian estimator
clusterer = NDGrid(n_bins_per_feature=10) mle_msm = MarkovStateModel(lag_time=100) b_msm = BayesianMarkovStateModel(lag_time=100, n_samples=10000, n_steps=1000) states = clusterer.fit_transform(trjs) with timing('running mcmc'): b_msm.fit(states) mle_msm.fit(states) plt.subplot(2, 1, 1) plt.plot(b_msm.all_transm...
examples/bayesian-msm.ipynb
liyigerry/msm_test
apache-2.0
Now lets try using 50 states The MCMC sampling is a lot harder to converge
clusterer = NDGrid(n_bins_per_feature=50) mle_msm = MarkovStateModel(lag_time=100) b_msm = BayesianMarkovStateModel(lag_time=100, n_samples=1000, n_steps=100000) states = clusterer.fit_transform(trjs) with timing('running mcmc (50 states)'): b_msm.fit(states) mle_msm.fit(states) plt.plot(b_msm.all_timescales_[:,...
examples/bayesian-msm.ipynb
liyigerry/msm_test
apache-2.0
Introduction to Visualization: Density Estimation and Data Exploration Version 0.1 There are many flavors of data analysis that fall under the "visualization" umbrella in astronomy. Today, by way of example, we will focus on 2 basic problems. By AA Miller 16 September 2017
import numpy as np import matplotlib.pyplot as plt %matplotlib inline
Sessions/Session07/Day0/TooBriefVisualization.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 1) Density Estimation Starting with 2MASS and SDSS and extending through LSST, we are firmly in an era where data and large statistical samples are cheap. With this explosion in data volume comes a problem: we do not know the underlying probability density function (PDF) of the random variables measured via our...
from sklearn.datasets import load_linnerud linnerud = load_linnerud() chinups = linnerud.data[:,0]
Sessions/Session07/Day0/TooBriefVisualization.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
1) Where are most billionaires from?
recent['countrycode'].value_counts().head() #df['animal'].value_counts()
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
2) How many of them are from Switzerland?
Swiss_billionaires = recent[recent['countrycode'] == 'CHE'] Swiss_billionaires.count().head(1)
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
3) Display all of the Swiss billionaires, starting with the richest.
Swiss_billionaires = recent[recent['countrycode'] == 'CHE'] Swiss_billionaires_sorted = Swiss_billionaires.sort_values(by='networthusbillion', ascending=False) Swiss_billionaires_sorted
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
4) How many of the richest Swiss are female, and how many are male?
female_Swiss_billionaires = Swiss_billionaires[Swiss_billionaires['gender'] == 'female'].count().head(1) female_Swiss_billionaires male_Swiss_billionaire = Swiss_billionaires[Swiss_billionaires['gender'] == 'male'].count().head(1) male_Swiss_billionaire
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
So that is 8 female Swiss billionaires and 14 male ones. 5) How is their wealth distributed? How many billions do super rich men and women have in Switzerland compared to women?
female_Swiss_billionaires_list = Swiss_billionaires[Swiss_billionaires['gender'] == 'female'] female_mean = female_Swiss_billionaires_list['networthusbillion'].mean() print(female_mean) #print("Swiss female billionaire's average wealth:", female_Swiss_billionaire['networthusbillion'].mean()) #print("Swiss male billion...
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
6) Do more Swiss women or more men inherit their fortunes?
#df[(df['animal'] == 'cat') & (df['inches'] > 12)] male_Swiss_billionaires_list[male_Swiss_billionaires_list['selfmade'] == 'inherited'].count().head(1) inherited = male_Swiss_billionaires_list[male_Swiss_billionaires_list['selfmade'] == 'inherited'].count().head(1) print("So out of 14 male Swiss billionaires 9 of them...
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
7) Display the only Swiss female billionaire who is a self made woman?
recent[(recent['gender'] == 'female') & (recent['selfmade'] == 'self-made') & (recent['countrycode'] == 'CHE')]
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
8) Display the richest woman in the world
recent[(recent['gender'] == 'female')].sort_values(by='networthusbillion', ascending=False)
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
9) Who is the richest self made woman? And how many women are selfmade?
recent[(recent['gender'] == 'female') & (recent['selfmade'] == 'self-made')].sort_values(by='networthusbillion', ascending=False)
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit
Interesting. Chan Laiwa, the richest self made woman in the world is from China. She is also above 70. The second on the list, Gayle Cook, is even over 80. 10. Lets compare that to the richest self made men. How much have they made?
recent[(recent['gender'] == 'male') & (recent['selfmade'] == 'self-made')].sort_values(by='networthusbillion', ascending=False)
07/RichPeople_Pandas_Homework_7_Skinner.ipynb
barjacks/foundations-homework
mit