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
๋ฏธ์ง€์ˆ˜์˜ ๊ฐฏ์ˆ˜์™€ ์ •๋ฐฉํ–‰๋ ฌ์˜ ๊ณ„์ˆ˜๊ฐ€ ๊ฐ™๋‹ค๋Š” ๊ฒƒ์€ ์ด ์„ ํ˜• ์—ฐ๋ฆฝ ๋ฐฉ์ •์‹์˜ ํ•ด๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๋œป์ด๋‹ค.The number of unknowns and the rank of the matrix are the same; we can find a root of this system of linear equations. ์šฐ๋ณ€์„ ์ค€๋น„ํ•ด ๋ณด์ž.Let's prepare for the right side.
vector = py.matrix([[0, 0, 0, 0, 0, 100, 0, 0]]).T
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp
ํŒŒ์ด์ฌ์˜ ํ™•์žฅ ๊ธฐ๋Šฅ ๊ฐ€์šด๋ฐ ํ•˜๋‚˜์ธ NumPy ์˜ ์„ ํ˜• ๋Œ€์ˆ˜ ๊ธฐ๋Šฅ `solve()` ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋ฅผ ๊ตฌํ•ด ๋ณด์ž.Using `solve()` of linear algebra subpackage of `NumPy`, a Python package, let's find a solution.
sol = nl.solve(matrix, vector) sol
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp
![Triangular Truss](triangular_truss.svg) Final Bell๋งˆ์ง€๋ง‰ ์ข…
# stackoverfow.com/a/24634221 import os os.system("printf '\a'");
_____no_output_____
BSD-3-Clause
60_linear_algebra_2/015_System_Linear_Eq_Four_Node_Truss.ipynb
cv2316eca19a/nmisp
![](../graphics/solutions-microsoft-logo-small.png) Python for Data Professionals 02 Programming Basics Course Outline 1 - Overview and Course Setup 2 - Programming Basics (This section) 2.1 - Getting help 2.2 Code Syntax and Structure 2.3 Variables 2.4 Operations and Functions 3 Working with Data 4 De...
# Try it:
_____no_output_____
MIT
PythonForDataProfessionals/Python for Data Professionals/notebooks/.ipynb_checkpoints/02 Programming Basics-checkpoint.ipynb
fratei/sqlworkshops
2.2 Code Syntax and StructureLet's cover a few basics about how Python code is written. (For a full discussion, check out the [Style Guide for Python, called PEP 8](https://www.python.org/dev/peps/pep-0008/) ) Let's use the "Zen of Python" rules from Tim Peters for this course: Beautiful is better than ugly. Expl...
# Try it:
_____no_output_____
MIT
PythonForDataProfessionals/Python for Data Professionals/notebooks/.ipynb_checkpoints/02 Programming Basics-checkpoint.ipynb
fratei/sqlworkshops
2.4 Operations and FunctionsPython has the following operators: Arithmetic Operators Comparison (Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity OperatorsYou have the standard operators and functions from most every language. Here are som...
# Try it:
_____no_output_____
MIT
PythonForDataProfessionals/Python for Data Professionals/notebooks/.ipynb_checkpoints/02 Programming Basics-checkpoint.ipynb
fratei/sqlworkshops
Activity - Programming basicsOpen the **02_ProgrammingBasics.py** file and run the code you see there. The exercises will be marked out using comments:` - Section Number`
# 02_ProgrammingBasics.py # Purpose: General Programming exercises for Python # Author: Buck Woody # Credits and Sources: Inline # Last Updated: 27 June 2018 # 2.1 Getting Help help() help(str) # <TODO> - Write code to find help on help # 2.2 Code Syntax and Structure # <TODO> - Python uses spaces to indicate code...
_____no_output_____
MIT
PythonForDataProfessionals/Python for Data Professionals/notebooks/.ipynb_checkpoints/02 Programming Basics-checkpoint.ipynb
fratei/sqlworkshops
Manual Jupyter Notebook:https://athena.brynmawr.edu/jupyter/hub/dblank/public/Jupyter%20Notebook%20Users%20Manual.ipynb Jupyter Notebook Users ManualThis page describes the functionality of the [Jupyter](http://jupyter.org) electronic document system. Jupyter documents are called "notebooks" and can be seen as many th...
2 + 3
_____no_output_____
MIT
Data Science Academy/Python Fundamentos/Cap01/JupyterNotebook-ManualUsuario.ipynb
tobraga/Cursos
2.1.1.2 Cell Tabbing Cell tabbing allows you to look at the input and output components of a cell separately. It also allows you to hide either component behind the other, which can be usefull when creating visualizations of data. Below is an example of a tabbed Code Cell:
2+3
_____no_output_____
MIT
Data Science Academy/Python Fundamentos/Cap01/JupyterNotebook-ManualUsuario.ipynb
tobraga/Cursos
2.1.1.3 Column Configuration Like the row configuration, the column layout option allows you to look at both the input and the output components at once. In the column layout, however, the two components appear beside one another, with the input on the left and the output on the right. Below is an example of a Code Ce...
2+3
_____no_output_____
MIT
Data Science Academy/Python Fundamentos/Cap01/JupyterNotebook-ManualUsuario.ipynb
tobraga/Cursos
**Assignment 1 Day 3**
n = int(input("Enter the altitude")) if n<=1000 : print("Safe to land") elif n<=5000 and n>1000 : print("Bring Down to 1000") else : print("Turn Around")
_____no_output_____
Apache-2.0
Day_3_Assignment.ipynb
ratikeshbajpai/Letsupgrade-Python
Recommendations with IBMIn this notebook, you will be putting your recommendation skills to use on real data from the IBM Watson Studio platform. You may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your code p...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import project_tests as t import pickle from matplotlib.pyplot import figure %matplotlib inline df = pd.read_csv('data/user-item-interactions.csv') df_content = pd.read_csv('data/articles_community.csv') del df['Unnamed: 0'] del df_content['Unname...
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
Part I : Exploratory Data AnalysisUse the dictionary and cells below to provide some insight into the descriptive statistics of the data.`1.` What is the distribution of how many articles a user interacts with in the dataset? Provide a visual and descriptive statistics to assist with giving a look at the number of ti...
# Count interactions per user, sorted interactions = df.groupby('email').count().drop(['title'],axis=1) interactions.columns = ['nb_articles'] interactions_sorted = interactions.sort_values(['nb_articles']) interactions_sorted.head() interactions_sorted.describe() #plt.figure(figsize=(10,30)) plt.style.use('ggplot') i...
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`2.` Explore and remove duplicate articles from the **df_content** dataframe.
row_per_article = df_content.groupby('article_id').count() duplicates = row_per_article[row_per_article['doc_full_name'] > 1].index df_content[df_content['article_id'].isin(duplicates)].sort_values('article_id') # Remove any rows that have the same article_id - only keep the first df_content_no_duplicates = df_content....
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`3.` Use the cells below to find:**a.** The number of unique articles that have an interaction with a user. **b.** The number of unique articles in the dataset (whether they have any interactions or not).**c.** The number of unique users in the dataset. (excluding null values) **d.** The number of user-article interac...
# Articles with an interaction len(df['article_id'].unique()) # Total articles len(df_content_no_duplicates['article_id'].unique()) # Unique users len(df[df['email'].isnull() == False]['email'].unique()) # Unique interactions len(df) unique_articles = 714 # The number of unique articles that have at least one interacti...
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`4.` Use the cells below to find the most viewed **article_id**, as well as how often it was viewed. After talking to the company leaders, the `email_mapper` function was deemed a reasonable way to map users to ids. There were a small number of null values, and it was found that all of these null values likely belong...
df.groupby('article_id').count().sort_values(by='email',ascending = False).head(1) most_viewed_article_id = str(1429.0) # The most viewed article in the dataset as a string with one value following the decimal max_views = 937 # The most viewed article in the dataset was viewed how many times? ## No need to change the ...
It looks like you have everything right here! Nice job!
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
Part II: Rank-Based RecommendationsUnlike in the earlier lessons, we don't actually have ratings for whether a user liked an article or not. We only know that a user has interacted with an article. In these cases, the popularity of an article can really only be based on how often an article was interacted with.`1.` ...
def get_top_articles(n, df=df): ''' INPUT: n - (int) the number of top articles to return df - (pandas dataframe) df as defined at the top of the notebook OUTPUT: top_articles - (list) A list of the top 'n' article titles ''' top_articles = list(df.groupby('title').count().so...
Your top_5 looks like the solution list! Nice job. Your top_10 looks like the solution list! Nice job. Your top_20 looks like the solution list! Nice job.
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
Part III: User-User Based Collaborative Filtering`1.` Use the function below to reformat the **df** dataframe to be shaped with users as the rows and articles as the columns. * Each **user** should only appear in each **row** once.* Each **article** should only show up in one **column**. * **If a user has interacted...
# create the user-article matrix with 1's and 0's def create_user_item_matrix(df): ''' INPUT: df - pandas dataframe with article_id, title, user_id columns OUTPUT: user_item - user item matrix Description: Return a matrix with user ids as rows and article ids on the columns with ...
You have passed our quick tests! Please proceed!
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`2.` Complete the function below which should take a user_id and provide an ordered list of the most similar users to that user (from most similar to least similar). The returned result should not contain the provided user_id, as we know that each user is similar to him/herself. Because the results for each user here ...
def find_similar_users(user_id, user_item=user_item): ''' INPUT: user_id - (int) a user_id user_item - (pandas dataframe) matrix of users by articles: 1's when a user has interacted with an article, 0 otherwise OUTPUT: similar_users - (list) an ordered list where the closes...
The 10 most similar users to user 1 are: [3933, 23, 3782, 203, 4459, 3870, 131, 4201, 46, 5041] The 5 most similar users to user 3933 are: [1, 23, 3782, 203, 4459] The 3 most similar users to user 46 are: [4201, 3782, 23]
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`3.` Now that you have a function that provides the most similar users to each user, you will want to use these users to find articles you can recommend. Complete the functions below to return the articles you would recommend to each user.
def get_article_names(article_ids, df=df): ''' INPUT: article_ids - (list) a list of article ids df - (pandas dataframe) df as defined at the top of the notebook OUTPUT: article_names - (list) a list of article names associated with the list of article ids (this is iden...
If this is all you see, you passed all of our tests! Nice job!
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`4.` Now we are going to improve the consistency of the **user_user_recs** function from above. * Instead of arbitrarily choosing when we obtain users who are all the same closeness to a given user - choose the users that have the most total article interactions before choosing those with fewer article interactions.* ...
def get_top_sorted_users(user_id, df=df, user_item=user_item): ''' INPUT: user_id - (int) df - (pandas dataframe) df as defined at the top of the notebook user_item - (pandas dataframe) matrix of users by articles: 1's when a user has interacted with an article, 0 otherwise ...
The top 10 recommendations for user 20 are the following article ids: ['1024.0', '1085.0', '109.0', '1150.0', '1151.0', '1152.0', '1153.0', '1154.0', '1157.0', '1160.0'] The top 10 recommendations for user 20 are the following article names: ['airbnb data for analytics: washington d.c. listings', 'analyze accident rep...
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`5.` Use your functions from above to correctly fill in the solutions to the dictionary below. Then test your dictionary against the solution. Provide the code you need to answer each following the comments below.
### Tests with a dictionary of results user1_most_sim = get_top_sorted_users(1).iloc[1].name #Find the user that is most similar to user 1 user131_10th_sim = get_top_sorted_users(131).iloc[10].name #Find the 10th most similar user to user 131 ## Dictionary Test Here sol_5_dict = { 'The user that is most similar to...
This all looks good! Nice job!
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`6.` If we were given a new user, which of the above functions would you be able to use to make recommendations? Explain. Can you think of a better way we might make recommendations? Use the cell below to explain a better method for new users. We would provide the top articles for all the users. `7.` Using your exis...
new_user = '0.0' # What would your recommendations be for this new user '0.0'? As a new user, they have no observed articles. # Provide a list of the top 10 article ids you would give to new_user_recs = get_top_article_ids(10) assert set(new_user_recs) == set(['1314.0','1429.0','1293.0','1427.0','1162.0','1364.0','1...
That's right! Nice job!
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
Part IV: Content Based Recommendations (EXTRA - NOT REQUIRED)Another method we might use to make recommendations is to perform a ranking of the highest ranked articles associated with some term. You might consider content to be the **doc_body**, **doc_description**, or **doc_full_name**. There isn't one way to creat...
def make_content_recs(): ''' INPUT: OUTPUT: '''
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`2.` Now that you have put together your content-based recommendation system, use the cell below to write a summary explaining how your content based recommender works. Do you see any possible improvements that could be made to your function? Is there anything novel about your content based recommender? This part is ...
# make recommendations for a brand new user # make a recommendations for a user who only has interacted with article id '1427.0'
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
Part V: Matrix FactorizationIn this part of the notebook, you will build use matrix factorization to make article recommendations to the users on the IBM Watson Studio platform.`1.` You should have already created a **user_item** matrix above in **question 1** of **Part III** above. This first question here will just...
# Load the matrix here user_item_matrix = pd.read_pickle('user_item_matrix.p') # quick look at the matrix user_item_matrix.head()
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`2.` In this situation, you can use Singular Value Decomposition from [numpy](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.svd.html) on the user-item matrix. Use the cell to perform SVD, and explain why this is different than in the lesson.
# Perform SVD on the User-Item Matrix Here u, s, vt = np.linalg.svd(user_item_matrix) s.shape, u.shape, vt.shape # Change the dimensions of u, s, and vt as necessary # update the shape of u and store in u_new u_new = u[:, :len(s)] # update the shape of s and store in s_new s_new = np.zeros((len(s), len(s))) s_new[:len...
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
There are no null values in the matrix since we are not using ratings, but whether the user has seen an article or not. Therefore it is enough for us to use SVD, we do not need to use funkSVD which needs to be used when handling null values. `3.` Now for the tricky part, how do we choose the number of latent features t...
num_latent_feats = np.arange(10,700+10,20) sum_errs = [] for k in num_latent_feats: # restructure with k latent features s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :] # take dot product user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new)) # compute error for each p...
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`4.` From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in ...
df_train = df.head(40000) df_test = df.tail(5993) def create_test_and_train_user_item(df_train, df_test): ''' INPUT: df_train - training dataframe df_test - test dataframe OUTPUT: user_item_train - a user-item matrix of the training dataframe (unique users for each r...
Awesome job! That's right! All of the test movies are in the training data, but there are only 20 test users that were also in the training set. All of the other users that are in the test set we have no data on. Therefore, we cannot make predictions for these users using SVD.
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
Please note that I had to modify 'articles' to 'movies' otherwise the function would not get the right result. However, we are talking about articles here, not movies. `5.` Now use the **user_item_train** dataset from above to find U, S, and V transpose using SVD. Then find the subset of rows in the **user_item_test** ...
# fit SVD on the user_item_train matrix u_train, s_train, vt_train = np.linalg.svd(user_item_train)# fit svd similar to above then use the cells below s_train.shape, u_train.shape, vt_train.shape # Find users to predict in test matrix users_to_predict = np.intersect1d(test_idx, user_item_train.index.tolist(), assume_un...
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
`6.` Use the cell below to comment on the results you found in the previous question. Given the circumstances of your results, discuss what you might do to determine if the recommendations you make with any of the above recommendation systems are an improvement to how users currently find articles? When using SVD on t...
from subprocess import call call(['python', '-m', 'nbconvert', 'Recommendations_with_IBM.ipynb'])
_____no_output_____
IBM-pibs
Recommendations_with_IBM.ipynb
julie-data/recommendations-ibm-watson
0.0. IMPORTS
import inflection import math import datetime import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from IPython.core.display import HTML from IPython.display import Image
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
0.1. Helper Functions
def load_csv(path): df = pd.read_csv(path, low_memory=False) return df def rename_columns(df, old_columns): snakecase = lambda x: inflection.underscore(x) cols_new = list(map(snakecase, old_columns)) print(f"Old columns: {df.columns.to_list()}") # Rename df.columns = cols_new ...
Populating the interactive namespace from numpy and matplotlib
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
0.2. Path Definition
# path home_path = 'C:\\Users\\sindolfo\\rossmann-stores-sales\\' raw_data_path = 'data\\raw\\' interim_data_path = 'data\\interim\\' figures = 'reports\\figures\\'
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
0.3. Loading Data
## Historical data including Sales df_sales_raw = load_csv(home_path+raw_data_path+'train.csv') ## Supplemental information about the stores df_store_raw = load_csv(home_path+raw_data_path+'store.csv') # Merge df_raw = pd.merge(df_sales_raw, df_store_raw, how='left', on='Store')
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.0. DATA DESCRIPTION
df1 = df_raw.copy() df1.to_csv(home_path+interim_data_path+'df1.csv')
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
Data fields Most of the fields are self-explanatory. The followingย are descriptions for those that aren't.- **Id** - an Id that represents a (Store, Date) duple within the test set- **Store** -ย a unique Id for each store- **Sales** - the turnover for any given day (this is what you are predicting)- **Customers** - the...
cols_old = [ 'Store', 'DayOfWeek', 'Date', 'Sales', 'Customers', 'Open', 'Promo', 'StateHoliday', 'SchoolHoliday', 'StoreType', 'Assortment', 'CompetitionDistance', 'CompetitionOpenSinceMonth', 'CompetitionOpenSinceYear', 'Promo2', 'Promo2SinceWeek', 'Promo2SinceYear', 'PromoInterval' ] df1 = renam...
Old columns: ['Store', 'DayOfWeek', 'Date', 'Sales', 'Customers', 'Open', 'Promo', 'StateHoliday', 'SchoolHoliday', 'StoreType', 'Assortment', 'CompetitionDistance', 'CompetitionOpenSinceMonth', 'CompetitionOpenSinceYear', 'Promo2', 'Promo2SinceWeek', 'Promo2SinceYear', 'PromoInterval'] New columns: ['store', 'day_of_...
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.2. Data Dimensions
show_dimensions(df1)
Number of Rows: 1017209 Number of Columns: 18 Shape: (1017209, 18)
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.3. Data Types
show_data_types(df1) ## Date is a object type. This is wrong. In the section "Types Changes" others chages is made. df1['date'] = pd.to_datetime(df1['date'])
store int64 day_of_week int64 date object sales int64 customers int64 open int64 promo int64 state_holiday object ...
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.4. Check NA
check_na(df1) ## Columns with NA vales ## competition_distance 2642 ## competition_open_since_month 323348 ## competition_open_since_year 323348 ## promo2_since_week 508031 ## promo2_since_year 508031 ## promo_interval 508031
store 0 day_of_week 0 date 0 sales 0 customers 0 open 0 promo 0 state_holiday 0 school_h...
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.5. Fillout NA
# competition_distance: distance in meters to the nearest competitor store # # Assumption: if there is a row that is NA in this column, # it is because there is no close competitor. # The way I used to represent this is to put # a number much larger than the maximum value # of the competition_distance variable. # ...
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.6. Type Changes
df1['competition_open_since_month'] = df1['competition_open_since_month'].astype('int64') df1['competition_open_since_year'] = df1['competition_open_since_year'].astype('int64') df1['promo2_since_week'] = df1['promo2_since_week'].astype('int64') df1['promo2_since_year'] = df1['promo2_since_year'].astype('int64')
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.7. Descriptive Statistical
num_attributes = df1.select_dtypes(include=['int64', 'float64']) cat_attributes = df1.select_dtypes(exclude=['int64', 'float64', 'datetime64[ns]'])
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.7.1 Numerical Attributes
show_descriptive_statistical(num_attributes) sns.displot(df1['sales'])
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
1.7.2 Categorical Attributes
cat_attributes.apply(lambda x: x.unique().shape[0]) aux1 = df1[(df1['state_holiday'] != '0') & (df1['sales'] > 0)] plt.subplot(1, 3, 1) sns.boxplot(x='state_holiday', y='sales', data=aux1) plt.subplot(1, 3, 2) sns.boxplot(x='store_type', y='sales', data=aux1) plt.subplot(1, 3, 3) sns.boxplot(x='assortment', y='sales...
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
2.0. FEATURE ENGINEERING
df2 = df1.copy() df2.to_csv(home_path+interim_data_path+'df2.csv')
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
2.1. Hypothesis Mind Map
Image(home_path+figures+'mind-map-hypothesis.png')
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
2.2 Creating hypotheses 2.2.1 Store Hypotheses **1.** Stores with larger staff should sell more.**2.** Stores with more inventory should sell more.**3.** Stores with close competitors should sell less.**4.** Stores with a larger assortment should sell more.**5.** Stores with more employees should sell more.**6.** Sto...
# year df2['year'] = df2['date'].dt.year # month df2['month'] = df2['date'].dt.month # day df2['day'] = df2['date'].dt.day # week of year df2['week_of_year'] = df2['date'].dt.isocalendar().week # year week df2['year_week'] = df2['date'].dt.strftime('%Y-%W') # competition since # I have competition measured in mont...
_____no_output_____
FSFAP
notebooks/c0.2-sg-feature-engineering.ipynb
sindolfoGomes/rossmann-stores-sales
.tg {border-collapse:collapse;border-spacing:0;}.tg td{border-color:white;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px; overflow:hidden;padding:10px 5px;word-break:normal;}.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px; f...
import numpy as np import pandas as pd import glob import os import tifffile as tf from importlib import reload import warnings warnings.filterwarnings( "ignore") import matplotlib.pyplot as plt %matplotlib inline import citrus_utils as vitaminC
_____no_output_____
MIT
jupyter/09_ellipsoid_fruit_fitting.ipynb
amezqui3/vitaminC_morphology
Define the appropriate base/root name and label name- This is where having consistent file naming pays off
tissue_src = '../data/tissue/' oil_src = '../data/oil/' bnames = [os.path.split(x)[-1] for x in sorted(glob.glob(oil_src + 'WR*'))] for i in range(len(bnames)): print(i, '\t', bnames[i]) bname = bnames[0] L = 3 lname = 'L{:02d}'.format(L) rotateby = [2,1,0]
_____no_output_____
MIT
jupyter/09_ellipsoid_fruit_fitting.ipynb
amezqui3/vitaminC_morphology
Load voxel-size data- The micron size of each voxel depends on the scanning parameters
voxel_filename = '../data/citrus_voxel_size.csv' voxel_size = pd.read_csv(voxel_filename) voxsize = (voxel_size.loc[voxel_size.ID == bname, 'voxel_size_microns'].values)[0] print('Each voxel is of side', voxsize, 'microns')
Each voxel is of side 57.5 microns
MIT
jupyter/09_ellipsoid_fruit_fitting.ipynb
amezqui3/vitaminC_morphology
Load oil gland centers and align based on spine- From the previous step, retrieve the `vh` rotation matrix to align the fruit- The point cloud is made to have mean zero and it is scaled according to its voxel size- The scale now should be in cm- Plot 2D projections of the oil glands to make sure the fruit is standing ...
savefig= False filename = tissue_src + bname + '/' + lname + '/' + bname + '_' + lname + '_vh_alignment.csv' vh = np.loadtxt(filename, delimiter = ',') print(vh) oil_dst = oil_src + bname + '/' + lname + '/' filename = oil_dst + bname + '_' + lname + '_glands.csv' glands = np.loadtxt(filename, delimiter=',', dtype=floa...
_____no_output_____
MIT
jupyter/09_ellipsoid_fruit_fitting.ipynb
amezqui3/vitaminC_morphology
Compute the general conic parametersHere we follow the algorithm laid out by [Li and Griffiths (2004)](https://doi.org/10.1109/GMAP.2004.1290055). A general quadratic surface is defined by the equation$$\eqalignno{ & ax^{2}+by^{2}+cz^{2}+2fxy+2gyz+2hzy\ \ \ \ \ \ \ \ \ &\hbox{(1)}\cr &+2px+2qy+2rz+d=0.}$$Let $$\rho = ...
np.vstack(tuple(ell_params.values())).shape bbox = (np.max(glands, axis=0) - np.min(glands, axis=0))*.5 guess = np.argsort(np.argsort(bbox)) print(bbox) print(guess[rotateby]) bbox[rotateby] datapoints = glands.T filename = oil_src + bname + '/' + lname + '/' + bname + '_' + lname + '_vox_v_ell.csv' ell_v_params, flag...
_____no_output_____
MIT
jupyter/09_ellipsoid_fruit_fitting.ipynb
amezqui3/vitaminC_morphology
Project the oil gland centers to the best-fit ellipsoid- The oil gland point cloud is translated to the center of the best-fit ellipsoid.- Projection will be **geocentric**: trace a ray from the origin to the oil gland and see where it intercepts the ellipsoid.Additionally, we can compute these projection in terms of ...
footpoints = 'geocentric' _, xyz = vitaminC.get_footpoints(datapoints, ell_params, footpoints) rho = vitaminC.ell_rho(ell_params['axes']) print(rho) eglands = xyz - ell_params['center'].reshape(-1,1) eglands = eglands[rotateby] cglands = datapoints - ell_params['center'].reshape(-1,1) cglands = cglands[rotateby] egl...
_____no_output_____
MIT
jupyter/09_ellipsoid_fruit_fitting.ipynb
amezqui3/vitaminC_morphology
Plot the best-fit ellipsoid sphere and the gland projections- Visual sanity check
domain_lon = [-np.pi, np.pi] domain_lat = [-.5*np.pi, 0.5*np.pi] lonN = 25 latN = 25 longitude = np.linspace(*domain_lon, lonN) latitude = np.linspace(*domain_lat, latN) shape_lon, shape_lat = np.meshgrid(longitude, latitude) lonlat = np.vstack((np.ravel(shape_lon), np.ravel(shape_lat))) ecoords = vitaminC.ellipsoid...
_____no_output_____
MIT
jupyter/09_ellipsoid_fruit_fitting.ipynb
amezqui3/vitaminC_morphology
LAB 4c: Create Keras Wide and Deep model.**Learning Objectives**1. Set CSV Columns, label column, and column defaults1. Make dataset of features and label from CSV files1. Create input layers for raw features1. Create feature columns for inputs1. Create wide layer, deep dense hidden layers, and output layer1. Create ...
import datetime import os import shutil import matplotlib.pyplot as plt import numpy as np import tensorflow as tf print(tf.__version__)
2.1.1
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Verify CSV files existIn the seventh lab of this series [4a_sample_babyweight](../solutions/4a_sample_babyweight.ipynb), we sampled from BigQuery our train, eval, and test CSV files. Verify that they exist, otherwise go back to that lab and create them.
%%bash ls *.csv %%bash head -5 *.csv
==> eval.csv <== 6.3118345610599995,Unknown,35,Single(1),38 5.43659938092,Unknown,21,Multiple(2+),35 7.43839671988,Unknown,20,Single(1),40 6.37576861704,Unknown,27,Multiple(2+),34 7.62358501996,True,30,Single(1),38 ==> test.csv <== 6.9996768185,Unknown,20,Single(1),39 6.9996768185,Unknown,26,Single(1),37 7.93443680938...
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Create Keras model Lab Task 1: Set CSV Columns, label column, and column defaults.Now that we have verified that our CSV files exist, we need to set a few things that we will be using in our input function.* `CSV_COLUMNS` are going to be our header names of our columns. Make sure that they are in the same order as in...
# Determine CSV, label, and key columns # TODO: Create list of string column headers, make sure order matches. CSV_COLUMNS = ["weight_pounds", "is_male", "mother_age", "plurality", "gestation_weeks"] # TODO: Add string name for label column LABEL_COLUMN = "weight_pounds" # Set default values for each CSV column as a ...
_____no_output_____
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Lab Task 2: Make dataset of features and label from CSV files.Next, we will write an input_fn to read the data. Since we are reading from CSV files we can save ourself from trying to recreate the wheel and can use `tf.data.experimental.make_csv_dataset`. This will create a CSV dataset object. However we will need to d...
def features_and_labels(row_data): """Splits features and labels from feature dictionary. Args: row_data: Dictionary of CSV column names and tensor values. Returns: Dictionary of feature tensors and label tensor. """ label = row_data.pop(LABEL_COLUMN) return row_data, label # ...
_____no_output_____
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Lab Task 3: Create input layers for raw features.We'll need to get the data read in by our input function to our model function, but just how do we go about connecting the dots? We can use Keras input layers [(tf.Keras.layers.Input)](https://www.tensorflow.org/api_docs/python/tf/keras/Input) by defining:* shape: A sha...
def create_input_layers(): """Creates dictionary of input layers for each feature. Returns: Dictionary of `tf.Keras.layers.Input` layers for each feature. """ # TODO: Create dictionary of tf.keras.layers.Input for each dense feature deep_inputs = { colname: tf.keras.layers.Input( ...
_____no_output_____
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Lab Task 4: Create feature columns for inputs.Next, define the feature columns. `mother_age` and `gestation_weeks` should be numeric. The others, `is_male` and `plurality`, should be categorical. Remember, only dense feature columns can be inputs to a DNN.
def categorical_fc(name, values): """Helper function to wrap categorical feature by indicator column. Args: name: str, name of feature. values: list, list of strings of categorical values. Returns: Categorical and indicator column of categorical feature. """ cat_column = tf....
_____no_output_____
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Lab Task 5: Create wide and deep model and output layer.So we've figured out how to get our inputs ready for machine learning but now we need to connect them to our desired output. Our model architecture is what links the two together. We need to create a wide and deep model now. The wide side will just be a linear re...
def get_model_outputs(wide_inputs, deep_inputs, dnn_hidden_units): """Creates model architecture and returns outputs. Args: wide_inputs: Dense tensor used as inputs to wide side of model. deep_inputs: Dense tensor used as inputs to deep side of model. dnn_hidden_units: List of integers ...
_____no_output_____
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Lab Task 6: Create custom evaluation metric.We want to make sure that we have some useful way to measure model performance for us. Since this is regression, we would like to know the RMSE of the model on our evaluation dataset, however, this does not exist as a standard evaluation metric, so we'll have to create our o...
def rmse(y_true, y_pred): """Calculates RMSE evaluation metric. Args: y_true: tensor, true labels. y_pred: tensor, predicted labels. Returns: Tensor with value of RMSE between true and predicted labels. """ # TODO: Calculate RMSE from true and predicted labels return tf....
_____no_output_____
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Lab Task 7: Build wide and deep model tying all of the pieces together.Excellent! We've assembled all of the pieces, now we just need to tie them all together into a Keras Model. This is NOT a simple feedforward model with no branching, side inputs, etc. so we can't use Keras' Sequential Model API. We're instead going...
def build_wide_deep_model(dnn_hidden_units=[64, 32], nembeds=3): """Builds wide and deep model using Keras Functional API. Returns: `tf.keras.models.Model` object. """ # Create input layers inputs = create_input_layers() # Create feature columns wide_fc, deep_fc = create_feature_co...
Here is our wide and deep architecture so far: Model: "model_1" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to =========================================================...
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
We can visualize the wide and deep network using the Keras plot_model utility.
tf.keras.utils.plot_model( model=model, to_file="wd_model.png", show_shapes=False, rankdir="LR")
_____no_output_____
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Run and evaluate model Lab Task 8: Train and evaluate.We've built our Keras model using our inputs from our CSV files and the architecture we designed. Let's now run our model by training our model parameters and periodically running an evaluation to track how well we are doing on outside data as training goes on. We...
TRAIN_BATCH_SIZE = 32 NUM_TRAIN_EXAMPLES = 10000 * 5 # training dataset repeats, it'll wrap around NUM_EVALS = 5 # how many times to evaluate # Enough to get a reasonable sample, but not so much that it slows down NUM_EVAL_EXAMPLES = 10000 # TODO: Load training dataset trainds = load_dataset( pattern="train*", ...
Train for 312 steps, validate for 10 steps Epoch 1/5 312/312 [==============================] - 5s 15ms/step - loss: 1.8696 - mse: 1.8696 - rmse: 1.2285 - val_loss: 1.2763 - val_mse: 1.2763 - val_rmse: 1.1294 Epoch 2/5 312/312 [==============================] - 3s 8ms/step - loss: 1.1673 - mse: 1.1673 - rmse: 1.0681 - ...
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Visualize loss curve
# Plot nrows = 1 ncols = 2 fig = plt.figure(figsize=(10, 5)) for idx, key in enumerate(["loss", "rmse"]): ax = fig.add_subplot(nrows, ncols, idx+1) plt.plot(history.history[key]) plt.plot(history.history["val_{}".format(key)]) plt.title("model {}".format(key)) plt.ylabel(key) plt.xlabel("epoch"...
_____no_output_____
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
Save the model
OUTPUT_DIR = "babyweight_trained_wd" shutil.rmtree(OUTPUT_DIR, ignore_errors=True) EXPORT_PATH = os.path.join( OUTPUT_DIR, datetime.datetime.now().strftime("%Y%m%d%H%M%S")) tf.saved_model.save( obj=model, export_dir=EXPORT_PATH) # with default serving function print("Exported trained model to {}".format(EXPORT...
assets saved_model.pb variables
Apache-2.0
notebooks/end-to-end-structured/labs/.ipynb_checkpoints/4c_keras_wide_and_deep_babyweight-checkpoint.ipynb
jfesteban/Google-ASL
__________________________
import numpy as np labels = np.load("data/frame_labels_avenue.npy") labels = np.reshape(labels,labels.shape[1]) noll = 0 ett = 0 for x in Y_test: if x == 0: noll += 1 else: ett +=1 print("Noll: ",noll) print("Ett: ",ett) from sklearn.model_selection import train_test_split X_train, X_test, Y_tra...
_____no_output_____
MIT
experiemnt1.ipynb
evinus/My-appproch-One
Neural Network ExampleBuild a 2-hidden layers fully connected neural network (a.k.a multilayer perceptron) with TensorFlow.- Author: Aymeric Damien- Project: https://github.com/aymericdamien/TensorFlow-Examples/ Neural Network Overview MNIST Dataset OverviewThis example is using MNIST handwritten digits. The dataset ...
from __future__ import print_function # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) import tensorflow as tf # Parameters learning_rate = 0.1 num_steps = 500 batch_size = 128 display_step = 100 # Network Parameters n_hidden...
Step 1, Minibatch Loss= 13208.1406, Training Accuracy= 0.266 Step 100, Minibatch Loss= 462.8610, Training Accuracy= 0.867 Step 200, Minibatch Loss= 232.8298, Training Accuracy= 0.844 Step 300, Minibatch Loss= 85.2141, Training Accuracy= 0.891 Step 400, Minibatch Loss= 38.0552, Training Accuracy= 0.883 Step 500, Minibat...
MIT
TensorFlow-Examples/notebooks/3_NeuralNetworks/neural_network_raw.ipynb
elitej13/project-neural-ersatz
T81-558: Applications of Deep Neural Networks**Module 10: Time Series in Keras*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class websi...
try: %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False
_____no_output_____
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
Part 10.3: Text Generation with LSTMRecurrent neural networks are also known for their ability to generate text. As a result, the output of the neural network can be free-form text. In this section, we will see how to train an LSTM can on a textual document, such as classic literature, and learn to output new text ...
from tensorflow.keras.callbacks import LambdaCallback from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.utils import get_file import numpy as np import random import sys ...
_____no_output_____
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
For this simple example, we will train the neural network on the classic children's book [Treasure Island](https://en.wikipedia.org/wiki/Treasure_Island). We begin by loading this text into a Python string and displaying the first 1,000 characters.
r = requests.get("https://data.heatonresearch.com/data/t81-558/text/"\ "treasure_island.txt") raw_text = r.text print(raw_text[0:1000])
รฏยปยฟThe Project Gutenberg EBook of Treasure Island, by Robert Louis Stevenson This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gu...
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
We will extract all unique characters from the text and sort them. This technique allows us to assign a unique ID to each character. Because we sorted the characters, these IDs should remain the same. If we add new characters to the original text, then the IDs would change. We build two dictionaries. The first **c...
processed_text = raw_text.lower() processed_text = re.sub(r'[^\x00-\x7f]',r'', processed_text) print('corpus length:', len(processed_text)) chars = sorted(list(set(processed_text))) print('total chars:', len(chars)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumer...
corpus length: 397400 total chars: 60
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
We are now ready to build the actual sequences. Just like previous neural networks, there will be an $x$ and $y$. However, for the LSTM, $x$ and $y$ will both be sequences. The $x$ input will specify the sequences where $y$ are the expected output. The following code generates all possible sequences.
# cut the text in semi-redundant sequences of maxlen characters maxlen = 40 step = 3 sentences = [] next_chars = [] for i in range(0, len(processed_text) - maxlen, step): sentences.append(processed_text[i: i + maxlen]) next_chars.append(processed_text[i + maxlen]) print('nb sequences:', len(sentences)) sentence...
_____no_output_____
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
The dummy variables for $y$ are shown below.
y[0:10]
_____no_output_____
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
Next, we create the neural network. This neural network's primary feature is the LSTM layer, which allows the sequences to be processed.
# build the model: a single LSTM print('Build model...') model = Sequential() model.add(LSTM(128, input_shape=(maxlen, len(chars)))) model.add(Dense(len(chars), activation='softmax')) optimizer = RMSprop(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer) model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= lstm (LSTM) (None, 128) 96768 ____________________________________...
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
The LSTM will produce new text character by character. We will need to sample the correct letter from the LSTM predictions each time. The **sample** function accepts the following two parameters:* **preds** - The output neurons.* **temperature** - 1.0 is the most conservative, 0.0 is the most confident (willing to ma...
def sample(preds, temperature=1.0): # helper function to sample an index from a probability array preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return...
_____no_output_____
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
Keras calls the following function at the end of each training Epoch. The code generates sample text generations that visually demonstrate the neural network better at text generation. As the neural network trains, the generations should look more realistic.
def on_epoch_end(epoch, _): # Function invoked at end of each epoch. Prints generated text. print("******************************************************") print('----- Generating text after Epoch: %d' % epoch) start_index = random.randint(0, len(processed_text) - maxlen - 1) for temperature in [0....
_____no_output_____
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
We are now ready to train. It can take up to an hour to train this network, depending on how fast your computer is. If you have a GPU available, please make sure to use it.
# Ignore useless W0819 warnings generated by TensorFlow 2.0. Hopefully can remove this ignore in the future. # See https://github.com/tensorflow/tensorflow/issues/31308 import logging, os logging.disable(logging.WARNING) os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # Fit the model print_callback = LambdaCallback(on_epoch...
Train on 132454 samples Epoch 1/60 128/132454 [..............................] - ETA: 35:39****************************************************** ----- Generating text after Epoch: 0 ----- temperature: 0.2 ----- Generating with seed: "im shouting. but you may suppose i pa" im shouting. but you may suppose i pa
Apache-2.0
t81_558_class_10_3_text_generation.ipynb
tenyi257/t81_558_deep_learning
Define a couple of helper functions
def get_within_between_distances(map_df, dm, col): filtered_dm, filtered_map = filter_dm_and_map(dm, map_df) groups = [] distances = [] map_dict = filtered_map[col].to_dict() for id_1, id_2 in itertools.combinations(filtered_map.index.tolist(), 2): row = [] if map_dict[id_1] == map_d...
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Load mapping file and munge it-----------------
home = '/home/office-microbe-files' map_fp = join(home, 'master_map_150908.txt') sample_md = pd.read_csv(map_fp, sep='\t', index_col=0, dtype=str) sample_md = sample_md[sample_md['16SITS'] == 'ITS'] sample_md = sample_md[sample_md['OfficeSample'] == 'yes'] replicate_ids = '''F2F.2.Ce.021 F2F.2.Ce.022 F2F.3.Ce.021 F2F.3...
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Load alpha diversity----------------------
alpha_div_fp = '/home/johnchase/office-project/office-microbes/notebooks/UNITE-analysis/core_div/core_div_open/arare_max999/alpha_div_collated/observed_species.txt' alpha_div = pd.read_csv(alpha_div_fp, sep='\t', index_col=0) alpha_div = alpha_div.T.drop(['sequences per sample', 'iteration']) alpha_cols = [e for e in a...
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
add alpha diversity to map-------------
sample_md = pd.concat([sample_md, alpha_div], axis=1, join='inner') sample_md['MeanAlpha'] = sample_md[alpha_cols].mean(axis=1)
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Filter the samples so that only corrosponding row 2, 3 samples are included-----------------------------------------------------------
sample_md['NoRow'] = sample_md['Description'].apply(lambda x: x[:3] + x[5:]) row_df = sample_md[sample_md.duplicated('NoRow', keep=False)].copy() row_df['SampleType'] = 'All Row 2/3 Pairs (n={0})'.format(int(len(row_df)/2)) plot_row_df = row_df[['Row', 'MeanAlpha', 'SampleType']] sample_md_wall = row_df[row_df['Plate...
(5.8449136803810715, 1.7233641180780523e-08) row 2 mean: 176.48000000000002, row 1 mean: 123.44017094017092
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Beta Diversity! Create beta diversity boxplots of within and bewteen distances for row. It may not make a lot of sense doing this for all samples as the location and or city affect may drown out the row affect Load the distance matrix----------------------
dm = skbio.DistanceMatrix.read(join(home, '/home/johnchase/office-project/office-microbes/notebooks/UNITE-analysis/core_div/core_div_open/bdiv_even999/binary_jaccard_dm.txt'))
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Run permanova and recored within between values on various categories----------------------All of these will be based on the row 2, 3 paired samples, though they may be filtered to avoind confounding variables Row distances
filt_map = row_df[(row_df['City'] == 'flagstaff') & (row_df['Run'] == '2')] filt_dm, filt_map = filter_dm_and_map(dm, filt_map) row_dists = get_within_between_distances(filt_map, filt_dm, 'Row') row_dists['Category'] = 'Row (n=198)' permanova(filt_dm, filt_map, column='Row', permutations=999)
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Plate locationWe can use the same samples for this as the previous test
plate_dists = get_within_between_distances(filt_map, filt_dm, 'PlateLocation') plate_dists['Category'] = 'Plate Location (n=198)' permanova(filt_dm, filt_map, column='PlateLocation', permutations=999)
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Run
filt_map = row_df[(row_df['City'] == 'flagstaff')] filt_dm, filt_map = filter_dm_and_map(dm, filt_map) run_dists = get_within_between_distances(filt_map, filt_dm, 'Run') run_dists['Category'] = 'Run (n=357)' permanova(filt_dm, filt_map, column='Run', permutations=999)
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Material
filt_map = row_df[(row_df['City'] == 'flagstaff') & (row_df['Run'] == '2')] filt_dm, filt_map = filter_dm_and_map(dm, filt_map) material_dists = get_within_between_distances(filt_map, filt_dm, 'Material') material_dists['Category'] = 'Material (n=198)' permanova(filt_dm, filt_map, column='Material', permutations=999)...
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Row Distances
filt_map = row_df[(row_df['City'] == 'flagstaff') & (row_df['Run'] == '2')] filt_dm, filt_map = filter_dm_and_map(dm, filt_map) row_dists = get_within_between_distances(filt_map, filt_dm, 'Row') row_dists['Category'] = 'Row (n=198)' permanova(filt_dm, filt_map, column='Row', permutations=999)
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Plate Location
plate_dists = get_within_between_distances(filt_map, filt_dm, 'PlateLocation') plate_dists['Category'] = 'Plate Location (n=198)' permanova(filt_dm, filt_map, column='PlateLocation', permutations=999)
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Run
filt_map = row_df[(row_df['City'] == 'flagstaff')] filt_dm, filt_map = filter_dm_and_map(dm, filt_map) run_dists = get_within_between_distances(filt_map, filt_dm, 'Run') run_dists['Category'] = 'Run (n=357)' permanova(filt_dm, filt_map, column='Run', permutations=999)
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Material
filt_map = row_df[(row_df['City'] == 'flagstaff') & (row_df['Run'] == '2')] filt_dm, filt_map = filter_dm_and_map(dm, filt_map) material_dists = get_within_between_distances(filt_map, filt_dm, 'Material') material_dists['Category'] = 'Material (n=198)' permanova(filt_dm, filt_map, column='Material', permutations=999)...
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
ANCOM-----
table_fp = join(home, 'core_div_out/table_even1000.txt') table = pd.read_csv(table_fp, sep='\t', skiprows=1, index_col=0).T table.index = table.index.astype(str) table_ancom = table.loc[:, table[:3].sum(axis=0) > 0] table_ancom = pd.DataFrame(multiplicative_replacement(table_ancom), index=table_ancom.index, columns=tab...
_____no_output_____
BSD-3-Clause
Final/Figure-3/figure-3-its.ipynb
gregcaporaso/office-microbes
Training with Chainer[VGG](https://arxiv.org/pdf/1409.1556v6.pdf) is an architecture for deep convolution networks. In this example, we train a convolutional network to perform image classification using the CIFAR-10 dataset. CIFAR-10 consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. The...
# Setup from sagemaker import get_execution_role import sagemaker sagemaker_session = sagemaker.Session() # This role retrieves the SageMaker-compatible role used by this Notebook Instance. role = get_execution_role()
_____no_output_____
Apache-2.0
sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb
can-sun/amazon-sagemaker-examples
Downloading training and test dataWe use helper functions provided by `chainer` to download and preprocess the CIFAR10 data.
import chainer from chainer.datasets import get_cifar10 train, test = get_cifar10()
_____no_output_____
Apache-2.0
sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb
can-sun/amazon-sagemaker-examples
Uploading the dataWe save the preprocessed data to the local filesystem, and then use the `sagemaker.Session.upload_data` function to upload our datasets to an S3 location. The return value `inputs` identifies the S3 location, which we will use when we start the Training Job.
import os import shutil import numpy as np train_data = [element[0] for element in train] train_labels = [element[1] for element in train] test_data = [element[0] for element in test] test_labels = [element[1] for element in test] try: os.makedirs("/tmp/data/train_cifar") os.makedirs("/tmp/data/test_cifar"...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb
can-sun/amazon-sagemaker-examples
Writing the Chainer script to run on Amazon SageMaker TrainingWe need to provide a training script that can run on the SageMaker platform. The training script is very similar to a training script you might run outside of SageMaker, but you can access useful properties about the training environment through various env...
!pygmentize 'src/chainer_cifar_vgg_single_machine.py'
_____no_output_____
Apache-2.0
sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb
can-sun/amazon-sagemaker-examples
Running the training script on SageMakerTo train a model with a Chainer script, we construct a ```Chainer``` estimator using the [sagemaker-python-sdk](https://github.com/aws/sagemaker-python-sdk). We pass in an `entry_point`, the name of a script that contains a couple of functions with certain signatures (`train` an...
from sagemaker.chainer.estimator import Chainer chainer_estimator = Chainer( entry_point="chainer_cifar_vgg_single_machine.py", source_dir="src", role=role, sagemaker_session=sagemaker_session, train_instance_count=1, train_instance_type="ml.p2.xlarge", hyperparameters={"epochs": 50, "batch...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb
can-sun/amazon-sagemaker-examples