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 |
|---|---|---|---|---|---|
Test: | df_twit['rating_dinominator'].value_counts().sort_index() | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
8.Some of data are duplicates. Define: Remove the duplicated rows. Code: | df_twit = df_twit.drop_duplicates() | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
Test: | df_twit.duplicated().sum() | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
Tidiness 1.'doggo', 'floofer', 'pupper', 'puppo' must be merged to 'stage' column Define:All these needs to be merged together into one column for better visualization. Code: | df_twit['stage'] = df_twit[['doggo', 'floofer', 'pupper', 'puppo']].max(axis=1)
df_twit.stage = df_twit.stage.astype('category')
df_twit.drop(['doggo', 'floofer', 'pupper', 'puppo'], axis=1, inplace=True) | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
Test: | df_twit.stage.value_counts() | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
2."breed" column should be added in df_twit table; its values based on p1_conf and p1_dog columns of df_img (image predictions) table 3.retweet_count and favorite_count columns from status_df (tweet status) table should be joined with df_twit table Code: | df_twit['breed'] = 'None'
df_twit['retweet_count'] = 0
df_twit['favorite_count'] = 0
df_twit.columns
df_twit.favorite_count
status_df.drop(['display_text_range'],axis=1,inplace=True)
status_df
df_merge = pd.merge(df_twit, status_df, on='tweet_id')
df_merge.head()
df_merge.drop(['retweet_count_x','favorite_count_x'],axi... | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
Test: | df = pd.read_csv('twitter_archive_master.csv')
df.head()
df.stage.value_counts() | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
Analysis: | df.info()
import seaborn as sns | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 2328 entries, 0 to 2327
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 tweet_id 2328 non-null int64
1 timestamp 2328 non-null object
2 source ... | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
Analysis of the largest tweet based on th year | pd.DatetimeIndex(df['timestamp']).year.value_counts().plot(kind='bar'); | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
1.Here we can see that year 2016 had the highest number of tweets followed by 2015 and 2017 | df.source.value_counts().plot(kind='barh'); | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
2.Most of the tweets have come from mobile devices through the twitter app. | df['rating_numerator'].value_counts().sort_index().plot(kind='bar') | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
3.Highest ratings is 12 that is more than 500 tweets. Lowest being 15. | names = df.drop(df[df['name'] == 'None'].index)
names.name.value_counts().iloc[:10].plot(kind='barh') | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
4.Charlie is the highest used name for dogs . | df_img.p1.value_counts().iloc[:10].plot(kind='barh') | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
5.Golden retriever is the highest breed that came up in tweets followed by labrador. | retweet = df.retweet_count.mean()
fav = df.favorite_count.mean()
fav
retweet | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree |
6.Mean retweet count is 3181 and favored count is 8122 | _____no_output_____ | MIT | Twitter analysis/.ipynb_checkpoints/wrangle_act-checkpoint.ipynb | Siddharth1698/Data-Analyst-Nanodegree | |
Word2Vec (gensim) Based on [Dive Into NLTK, Part X: Play with Word2Vec Models based on NLTK Corpus by TextMiner](http://textminingonline.com/dive-into-nltk-part-x-play-with-word2vec-models-based-on-nltk-corpus) 1. Exploring the `gutenburg` corpus Project Gutenberg (PG) is a volunteer effort to digitize and archive cu... | from nltk.corpus import gutenberg
gutenberg.readme().replace('\n', ' ')
gutenberg.fileids()
bible_kjv_sents = gutenberg.sents('bible-kjv.txt')
len(bible_kjv_sents) | _____no_output_____ | MIT | 8-2-Word2vec-(gensim).ipynb | abalvet/hands-on-nltk-tutorial |
2. Implementing Word2Vec | from string import punctuation
discard_punctuation_and_lowercased_sents = [[word.lower() for word in sent if word not in punctuation and word.isalpha()]
for sent in bible_kjv_sents]
discard_punctuation_and_lowercased_sents[3]
from gensim.models import Word2Vec
bible_kjv_wo... | _____no_output_____ | MIT | 8-2-Word2vec-(gensim).ipynb | abalvet/hands-on-nltk-tutorial |
EDA Imports | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt | _____no_output_____ | CC0-1.0 | scratch/EDA.ipynb | pezpet/capstone |
Data | data = pd.read_csv('./data/merged_data.csv')
data.drop(columns='Unnamed: 0', inplace=True)
data.head() | _____no_output_____ | CC0-1.0 | scratch/EDA.ipynb | pezpet/capstone |
Pairplot | plt.figure(figsize=(8, 12))
sns.pairplot(
data=data[
[
"wave_height",
"dominant_period",
"avg_period",
"water_temp",
"dominant_wave_direction_sin",
"dominant_wave_direction_cos",
"wind_speed",
"gust_speed",
... | _____no_output_____ | CC0-1.0 | scratch/EDA.ipynb | pezpet/capstone |
AutoAggregator for Merging External TablesIn many situations your data may be stored in several tables. Let's see how `AutoConverter` can take care of it. After you perform conversion you can proceed with `AutoLearn` as usual.Sometimes not all the data is stored in one table. For example you can have some user informa... | import os
import sys
sys.path.append('../')
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
from learnit import AutoConverter, AutoLearn, Evaluate
warnings.filterwarnings('ignore')
dirpath = "data/kaggle-kkbox-churn-prediction-challenge-1k/"
df_main = pd.read_csv(os.path.join(dirpath, 'members_tr... | Using TensorFlow backend.
| Apache-2.0 | notebooks/03_auto_aggregation.ipynb | suhara/learnit |
You need to predict churn of the users and you have twotables:1) users table. This table consists of users, some information about them and, most importantly the target values (labels for prediction). The latter suggests that this should be the main table for the purpose of `AutoConverter`. This table also contains ID ... | df_main.head() | _____no_output_____ | Apache-2.0 | notebooks/03_auto_aggregation.ipynb | suhara/learnit |
2) user_transactions table: this table consists of separate transaction records. Each user, represented by User_ID, can have multiple transactions. In order to get a single feature matrix for our learning algorithm, we will need to group this information by User_ID before we merge user table with user_transactions tabl... | df_sub.head()
df_sub2.head() | _____no_output_____ | Apache-2.0 | notebooks/03_auto_aggregation.ipynb | suhara/learnit |
Let's take care about both of the tables. For that we will create `AutoConverter` object as usual. We are also creating `subtables` dictionary that tells the system how to link the secondary tables to the main one. For each secondary table this dictionary contains its name, the variable that contains the table (`df_sub... | ac = AutoConverter(target='is_churn')
"""subtables = {'second_table': {'table': df_sub,
'link_key': 'msno',
'group_key': 'msno'}}"""
subtables = {'transactions': {'table': df_sub,
'link_key': 'msno',
'group_key':... | (898, 302)
| Apache-2.0 | notebooks/03_auto_aggregation.ipynb | suhara/learnit |
As we can see now we have features from the main table and the ones from the secondary table. Printing out feature names also gives us understanding about how well the system has extracted the features. Now we can train the model using `AutoLearn` the same way as we did before. | print(X.shape)
al = AutoLearn(level=2)
al.learn(X, y)
info, metrics = al.display(tab=False)
info.head()
metrics.head()
#Visualize train/test performance with error bars (standard deviation)
metrics.plot(kind="bar", rot=0) | _____no_output_____ | Apache-2.0 | notebooks/03_auto_aggregation.ipynb | suhara/learnit |
It is usual for the predictive models to achieve better results on *training set* than on *test_set*. This happens because the model can see the data in the *training set* and take it into account and can not see the data from the *test set*. This difference, however should not be too big. For example if the model achi... | # Feature Importance calculation with Evaluate
e = Evaluate(ac=ac, alearn=al)
col_imp_df = e.calculate_column_importance()
pd.DataFrame(col_imp_df["roc_auc"])
# Will be implemented as a function. Don't worry!
col_imp_df["roc_auc"].sort_values().plot(kind="barh") | _____no_output_____ | Apache-2.0 | notebooks/03_auto_aggregation.ipynb | suhara/learnit |
Assignment 1 Part II - machine reading knowledge graph instance closure In this part of the Assignment I you will learn about applying logical closure over a knowledge graph creating using predications extracted using machine reading.This notebook is broken into 3 parts. First, you will learn about the rule programmin... | seed_pmid_L = [27569062,24283439,22098123,21062266,20518782,17184278,15096145,10333626,7917994,1619641,1842204,22946697,3789005,3712393,4697981,15490149,15490149,11078563,22837569,19047498,16825433,12522802,12494447,12239713,8725790,9147900,8867662,7917994,1358488,1867292,2063896,1915501,2596507,2596506,2596505,3265306... | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
The next two cells obtain PMIDs for articles cited in the PMIDs you chose and also articles that cite the PMIDs you chose. Both cells uses the eutils API with my email and API key. There is only a very tiny difference in the eutils call. Note: the call returns an error if it cannot retrieve citations for a given PMID.... | cited_in_pmids = {}
for pmid in seed_pmid_L:
print("INFO: pmid {}".format(pmid))
e = entrezpy.elink.elinker.Elinker('bioinf2071-course-notebook',
'rdb20@pitt.edu',
'2f8f82da766ed382a93ccb66e19b07a4ef09')
try:
analyzer = e.in... | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
The next cells connect to an instance of SemMedDB running on the same server as this notebook. Below is query for predications extracted from the articles in the set of PMIDS you picked, citing artcles, and articles cited by. **NOTE:** The cell that runs the actual semmeddb query will likely run for more than 2 hours... | import MySQLdb
cnx = MySQLdb.connect(user='semmeddb', passwd='semmeddb',
host='127.0.0.1',
db='semmeddb')
cursor = cnx.cursor()
## We store the PMIDs list in a table on the database
import os
cursor.execute('''DROP TABLE IF EXISTS t_pmids_{};'''.format(os.g... | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
The next cells give some summary information about the predications extracted from the cells above. Take a look at some of the predications and answer the questions that follow. | import random
sampleIdxL = random.sample(range(0,len(data)), 100)
## Obtain predication score data
scoreData = []
for idx in sampleIdxL:
cursor.execute('''SELECT * FROM PREDICATION_AUX WHERE PREDICATION_ID = {};'''.format(data[idx][0]))
scoreRec = cursor.fetchall()
scoreData.append(scoreRec[0])
## Obtain t... | subject_entities: 2137
subject_types: 95
predicate_types: 45
object_entities: 1738
object_types: 91
| Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
E4 - Answer the following questions (NOTE: you can read more about SemMedDB and how it was built here - https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3509487/): 1. Did you find any predications that make sense to you? Are they what you would expect for the domain of discourse you chose? List a few of them and explain ... | ## Set up the CLIPS environment
import clips
env = clips.Environment()
MIN_PREDICATION_BELIEF = 0.8
MIN_TRANSITIVE_BELIEF = 0.6 # chosen because it retains most depth 1 transitive inferences over semmed
## NOTE: This clears test-inference.ntriples each time this cell is ran
## This accomplishes that
f = open("test... | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
We set the rules up first. Look at the code and comments and then answer the questions below. | ## First, we clear the working memory of the rule engine. This removes all Working Memory Elements and resets the
## inference algorithm
env.clear()
env.reset()
## We will be writing the triples to RDF. This file is opened by the rule enginein append mode
env.eval('(open "test-inference.ntriples" writeFile "a")')
... | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
**E5** - Questions about the closure rules:1. What happens to working memory when the RHS of the rule (the 'assert' statement) triggers?ANSWER: 2. The reasoner will run the rules over data in working memory (loaded by the cells below) using 'forward chaining'. Describe what that actually means. ANSWER:3. What has to be... | originalTriplesF = open('original-triples.ntriples','w')
resourceD = {}
resourceDinv = {}
rcnt = 0
fctStrD = {}
semTypeD = {}
labelsD = {}
[PREDICATION_ID,SENTENCE_ID,INDEX,PMID,SUBJECT_SOURCE,SUBJECT_CUI,SUBJECT_NAME,SUBJECT_TYPE,SUBJECT_SCORE,PREDICATE,OBJECT_SOURCE,OBJECT_CUI,OBJECT_NAME,OBJECT_TYPE,OBJECT_SCORE,B... | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
This shows how many predications were loaded into working memory from the original set of predications after filtering out predicate types that we don't want in the knowledge graph | len(fctStrD.keys()) | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
The next cell shows how the data loaded into working memory is formatted | i = 0
for fact in env.facts():
print(fact)
if i == 20:
break
i += 1 | (initial-fact)
(oav (object r0) (attribute part_of) (value r1) (predNS RO) (inferred No) (belief 0.8))
(oav (object r2) (attribute associated_with) (value r3) (predNS RO) (inferred No) (belief 0.8))
(oav (object r0) (attribute causes) (value r3) (predNS RO) (inferred No) (belief 0.8))
(oav (object r2) (attribute associ... | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
The next cell runs the inference algorithm over the predications loaded into working memory. The count that is printed is the number of inferrences from the reasoner | env.run()
env.eval("close(writeFile)") | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
The next cells wrap normalize the identifiers and format original and inferred predications and while translating the newly extracted knowledge statements to RDF The reason for this step is that we plan to integrate the knowledge extracted from the literature in SemMedDB with a much larger ontology-based knowledge gr... | # predicate to RO mapping
predMapD = {
'affects':'RO_0002211',
'associated_with':'RO_0002610',
'augments':'augments',
'causes':'RO_0002501',
'coexists_with':'RO_0002490',
'complicates':'complicates',
'disrupts':'disrupts',
'inhibits':'RO_0002212',
'interacts_with':'RO_0002434',
... | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
Running SPARQL over the original and inferred triples | ## We load the original extracted predicates (filtered as above) into an
## in-memory triple store. Notice that we load RO as well.
import rdflib
## The SPARQL query just pulls up to 100 predications and
## the human readable labels. The output
g = rdflib.Graph()
g.parse("original-triples-RO-mapped.ntriples", forma... | Triple count after loading original and inferred-transitive-and-symmetric.ntriples: 7234
TRIPLE:
Acid Phosphatase
negatively regulates
CRK protein, human|CRK
http://umls.org/st/#aapp
http://umls.org/st/#aapp
http://dikb.org/cfc#C0001109
http://purl.obolibrary.org/obo/RO_0002212
http://dikb.org/cfc#C1451465
TRIPLE:
... | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
**E6** - Use the next cells to write a SPARQL queries that count the number of distinct CUIs used for subject and object roles in the merged graph. Also, shown how the counts for subject and objects break down by semantic type. The basic structure of the queries are set up for you. | # Count distinct subject CUIs
qres = g.query("""
SELECT ?s_type (count(distinct ?s) AS ?count)
WHERE {{
?s ?p ?o.
?s rdf:type ?s_type.
}}
group by ?s_type
""")
for row in qres:
print("\n\nRESULT:\n{}".format('\n'.join([str(x) for x in row])))
# Count subject CUI grouped by semantic type
qres = g.query("""
S... |
RESULT:
http://purl.obolibrary.org/obo/RO_0002561
is symmetric relational form of process class
4
4
RESULT:
http://purl.obolibrary.org/obo/IAO_0000424
expand expression to
22
22
RESULT:
http://purl.obolibrary.org/obo/RO_0002211
regulates
278
292
RESULT:
http://www.geneontology.org/formats/oboInOwl#hasBroadSynon... | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
There are many interesting patterns that we can apply to the extracted knowledge. I will discuss examples in class. This first query is simple example that looks for a simple causal chain involving clinically relevant entities | qres = g.query("""
SELECT ?s_lab ?p_lab ?o_lab ?p_lab ?d_lab ?s ?o ?d
WHERE {{
?s rdf:type ?s_semType.FILTER(?s_semType != <http://umls.org/st/#bacs> && ?s_semType != <http://umls.org/st/#bhvr> && ?s_semType != <http://umls.org/st/#dora> && ?s_semType != <http://umls.org/st/#food> && ?s_semType != <http://umls.org/s... |
TRIPLE:
STAT3 gene|STAT3
causes or contributes to condition
Pathogenesis
causes or contributes to condition
Tumor Initiation
http://dikb.org/cfc#C1367307
http://dikb.org/cfc#C0699748
http://dikb.org/cfc#C0598935
TRIPLE:
STAT3 gene|STAT3
causes or contributes to condition
Pathogenesis
causes or contributes to condit... | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
This next query looks for a pattern typical of statistical confounders where there is a common cause to a disorder and a disease where the disorder is also causally related to the disease |
qres = g.query("""
SELECT ?s_lab ?p_lab ?o_lab ?s_lab ?p_lab ?d_lab ?o_lab ?p_lab ?d_lab ?s ?o ?d
WHERE {{
?s rdf:type ?s_semType.FILTER(?s_semType != <http://umls.org/st/#bacs> && ?s_semType != <http://umls.org/st/#bhvr> && ?s_semType != <http://umls.org/st/#dora> && ?s_semType != <http://umls.org/st/#food> && ?s_... |
TRIPLE:
STAT3 gene|STAT3
causes or contributes to condition
Pathogenesis
STAT3 gene|STAT3
causes or contributes to condition
Malignant Neoplasms
Pathogenesis
causes or contributes to condition
Malignant Neoplasms
http://dikb.org/cfc#C1367307
http://dikb.org/cfc#C0699748
http://dikb.org/cfc#C0006826
TRIPLE:
BRAF gen... | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
The above 2 queries only use the 'causes or contributes to condition' predicate type (RO_0003302) but there are several other predicate types that could be used to create patterns (see the RO predicates in your graph from one of the queries above). **E7** - Use the next cell block to write a query that uses a differen... | qres = g.query("""
SELECT *
WHERE {{
?s rdf:type ?s_semType.FILTER(?s_semType != <http://umls.org/st/#bacs> && ?s_semType != <http://umls.org/st/#bhvr> && ?s_semType != <http://umls.org/st/#dora> && ?s_semType != <http://umls.org/st/#food> && ?s_semType != <http://umls.org/st/#hops> && ?s_semType != <http://umls.org... |
TRIPLE:
PTPN11 gene|PTPN11
Orthologous Gene
interacts with
Ubiquinone
http://dikb.org/cfc#C0041536
http://umls.org/st/#gngm
http://dikb.org/cfc#C1335280
http://umls.org/st/#gngm
http://dikb.org/cfc#C1335144
TRIPLE:
MAP Kinase Gene
Neurofibromatosis Type 1 Protein
interacts with
Mitogen-Activated Protein Kinases
htt... | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
This final cell sets things up for the next part of the assignment (to be assigned next week). It creates mapping files that will be needed to work that crosses the extracted triples to OBO entity identifiers in PheKnowLator | ## create a file with triples to map the UMLS CUIs to the target ontologies used in the Pheknowlator KG ()
all_cui_to_codeD = {}
umls_mapped_cnt = 0
reach_mapped_cnt = 0
bioportal_mapped_cnt = 0
# start by loading all GO and HPO UMLS CUIs
# ex: C2247561|GO|GO:0034023|"5-(carboxyamino)imidazole ribonucleotide mutase ac... | _____no_output_____ | Apache-2.0 | assignment-1-part-2-KG/.ipynb_checkpoints/assignment-1-part-2-machine-reading-kg-checkpoint.ipynb | dbmi-pitt/bioinf-2071-knowledge-graph |
Import wiki dataset | imdb = keras.datasets.imdb
(train_data, train_label),(test_data,test_label) = imdb.load_data(num_words=10000) | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/imdb.npz
17465344/17464789 [==============================] - 3s 0us/step
| Apache-2.0 | tf/.ipynb_checkpoints/Text Classification-checkpoint.ipynb | rishuatgithub/MLPy |
The argument num_words=10000 keeps the top 10,000 most frequently occurring words in the training data. The rare words are discarded to keep the size of the data manageable. | print("Train data shape:",train_data.shape)
print("Test data shape:",test_data.shape)
print("Train label :",len(train_label))
print("First Imdb review: ",train_data[0]) ## review data for the first review
## notice the difference in length of 2 reviews
print("length of first and second review:",len(train_data[0])," "... | Train data shape: (25000,)
Test data shape: (25000,)
Train label : 25000
First Imdb review: [1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 2, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 2, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, ... | Apache-2.0 | tf/.ipynb_checkpoints/Text Classification-checkpoint.ipynb | rishuatgithub/MLPy |
Convert integers to String from the dictonary of words | ## A dictionary mapping of a word to a integer index
word_index = imdb.get_word_index()
## The first indices are reserved
word_index["<PAD>"] = 0
word_index["<START>"] = 1
word_index["<UNK>"] = 2 ## unknown
word_index["<UNUSED>"] = 3
word_index = {k:(v+3) for k,v in word_index.items()}
reverse_word_index = dict([(val... | _____no_output_____ | Apache-2.0 | tf/.ipynb_checkpoints/Text Classification-checkpoint.ipynb | rishuatgithub/MLPy |
Preparing the data we can pad the arrays so they all have the same length, then create an integer tensor of shape max_length * num_reviews. We can use an embedding layer capable of handling this shape as the first layer in our network. Since the movie reviews must be the same length, we will use the pad_sequences f... | train_data = keras.preprocessing.sequence.pad_sequences(train_data,
value = word_index["<PAD>"],
padding='post',
maxlen = 256)
test_data = keras.preproce... | [ 1 14 22 16 43 530 973 1622 1385 65 458 4468 66 3941
4 173 36 256 5 25 100 43 838 112 50 670 2 9
35 480 284 5 150 4 172 112 167 2 336 385 39 4
172 4536 1111 17 546 38 13 447 4 192 50 16 6 147
2025 19 14 22 4 1920 4613 ... | Apache-2.0 | tf/.ipynb_checkpoints/Text Classification-checkpoint.ipynb | rishuatgithub/MLPy |
Building the model | # input shape is the vocabulary count used in the reviews i.e. word count = 10,000
vocab_size = 10000
model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation = tf.nn.relu))
model.add(keras.layers.Dense(1,... | _____no_output_____ | Apache-2.0 | tf/.ipynb_checkpoints/Text Classification-checkpoint.ipynb | rishuatgithub/MLPy |
Training the model | history = model.fit(partial_x_train,
partial_y_train,
epochs=40,
batch_size=512,
validation_data=(x_val, y_val),
verbose=1) | Train on 15000 samples, validate on 10000 samples
WARNING:tensorflow:From /anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Epoch 1/40
15000/... | Apache-2.0 | tf/.ipynb_checkpoints/Text Classification-checkpoint.ipynb | rishuatgithub/MLPy |
Evaluate the model | results = model.evaluate(test_data, test_label)
print(results) | 25000/25000 [==============================] - 1s 29us/sample - loss: 0.3339 - acc: 0.8714
[0.33389624541282653, 0.8714]
| Apache-2.0 | tf/.ipynb_checkpoints/Text Classification-checkpoint.ipynb | rishuatgithub/MLPy |
Create a graph of accuracy over time | history_dict = history.history
history_dict.keys()
import matplotlib.pyplot as plt
acc = history_dict['acc']
val_acc = history_dict['val_acc']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epochs = range(1, len(acc) + 1)
# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')
... | _____no_output_____ | Apache-2.0 | tf/.ipynb_checkpoints/Text Classification-checkpoint.ipynb | rishuatgithub/MLPy |
[SOC-88] Practice with Visualizations Professor David Harding Table of Contents[Introduction](intro)[Using Tables with Bigger Data](1)- [Question 1: Who is Represented?](q1)- [Question 2: Differences by Race](q2)- [Question 3: Minimum Sentence Lengths](q3)- [Question 4: Sentence Lengths across Different Sentence Types... | # Data library
from datascience import *
import numpy as np
# Plotting libraries
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
Great! Let's explore the different ways we can use Tables to create data visualizations. Using Tables with Bigger Data Let's explore some ways to manage bigger data and break it down into something we can visualize.First, we need some big data. Here, we'll use some data from Professor Harding's own research about the ... | sentencing = Table().read_table("harding_new.csv")
sentencing | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
Question 1: Who is represented? Cool, now we have data. Let's see if we can figure out the following questions:- Who is represented in this dataset? Groups or individuals?- What does each row of the table represent? And, how many people are represented in this dataset?Write in the cell below any code that you would ne... | # write any code here | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
When starting to analyze your data, it is good to think about how many unique values exist in your dataset. The following code checks how many unique values there are in each column of your table. A way to understand what these numbers mean is if there are 140,267 unique values and there are 140,267 rows in our table, ... | for i in sentencing.labels:
print('Number of unique values in column',i,":", len(np.unique(sentencing.column(i)))) | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
For columns with low numbers of unique values, it is useful to try to group them and determine which plot is best to plot the differences between the groups. Let's try with `race_cat` first, and then for other variables. To group by the `race_cat` column, we use the `table.group()` function. We will define this new tab... | race_categories = sentencing.group('race_cat')
race_categories | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
Question 2: Differences by Race Let's represent this data to see the disparities between races. We have one categorical variable and one numerical variable. Here is an example plot: | race_categories.barh('race_cat', width=15) | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
Now, it is your turn! Improve this bar chart with the methods from the first notebook. Then, describe why you choose to add or not add certain features to the chart. Think about fonts, colors, titles, clear labeling, avoiding too much "ink". Be prepared to explain your design choices below! | # your code here | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
**Desribe the features you choose.** What does your plot argue? What is the main point? What is the general message of the plot? *Type your answer here* One thing to consider when grouping by race is that the data we have is for all individuals sentenced in Michigan between 2003 and 2006. This is the race breakdown for... | races = ['Black', 'Other', 'White']
counts = [1412742, 559649, 7966053]
percent = [14.2, 5.3, 80.5]
race_census = Table().with_columns('Race', races, 'Count', counts, 'Percent', percent)
race_census | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
The table `race_full` below contains both the sentencing counts and the census counts, along with the percentage of the population sentenced for each race. We will use this to show the differences in race for the individuals sentenced. | race_sentencing = race_categories.where('race_cat', are.not_equal_to('Race Unknown'))
race_full = race_sentencing.with_column('census_count', race_census['Count']).relabeled('count', 'sentencing_count')
race_full = race_full.with_column('sentenced_pct', race_full['sentencing_count']/race_full['census_count']*100)
race_... | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
**Question:** What do you notice that is different about this plot than the plot you created with the sentencing counts? What does this tell us about context and population size when creating visualizations? *Type your answer here* Question 3: Minimum Sentence Lengths Now, let's investigate the distribution of `cum_m... | plt.hist(sentencing.column('cum_min_length_months'))
plt.xlabel("Minimum Length (Months)")
plt.ylabel("Number of occurrences"); | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
**3a.** How could we find the outliers in our dataset? Let's define outliers as months where the number of occurrences are below 200. What is the largest minimum length that has over 200 occurrences? To start, we've grouped the occurrences of `cum_min_length_months`. Build off of the existing code to find the largest n... | sentencing.group('cum_min_length_months')... | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
**3b.** We've plotted the original data with new bins to compare this distribution to one without outliers. Plot the same data below with bins widths of 20, but filter out minimum sentence lengths over 180 months. Make sure to contain the bin from 160 to 180. Hint: *Use the `bins` argument of histograms to display only... | # Do not change the code in this cell!
plt.hist(sentencing.column('cum_min_length_months'), bins=np.arange(0, 1200,20))
plt.xlabel("Minimum Length (Months)")
plt.ylabel("Number of occurrences")
plt.title('Distribution of Minimum Sentence Lengths');
# your code here | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
Question 4: Sentence Lengths across Different Sentence Types To compare the different types of sentences and their lengths, we will have to filter tables so that they only contain one sentencing type and then create a histogram of the lengths within that table. You will need to make 4 different tables for the differ... | jail_only = sentencing.where('sent_type', 'Jail Only')
plt.hist(jail_only.column('cum_min_length_months'));
# your code below
jail_prob = sentencing.where('sent_type', 'Jail with Probation')
plt.hist(jail_prob.column('cum_min_length_months'));
# your code below
prison = sentencing.where('sent_type', 'Prison')
plt.hist(... | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
**Desribe the features you choose below.** Think about the choices you made regarding fonts, colors, titles, clear labeling. Why did you choose what you did? How does this help your plot give a message? What is the type of message this plot gives? *Type your answer here* **4b.** What do we learn from these graphs? Whic... | # write any code used to help answer the question here | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
[Bonus] Sentence Lengths across different Races Another thing we can compare is the length of sentences based on race. Here we've plotted the distribution of sentence lengths for white and black individuals. | white_sentence_lengths = sentencing.where('race_cat', 'White')
black_sentence_lengths = sentencing.where('race_cat', 'Black')
fig = plt.figure(figsize=(15,8))
ax = fig.add_subplot(221)
plt.hist(white_sentence_lengths.column('cum_min_length_months'), bins=np.arange(0,200,12), density=True)
plt.ylim(0, 0.04)
ax.set(ti... | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
Bonus Challenge Question How would you improve upon this data visualization of two side by side histograms comparing sentence length between races? *Type your answer here* One possible way to visualize the length of sentence for different races is with a superimposed kernel density estimate plot. Below, we've generate... | import seaborn as sns
sns.kdeplot(white_sentence_lengths.column('cum_min_length_months'), gridsize=1000, label = 'White')
sns.kdeplot(black_sentence_lengths.column('cum_min_length_months'), gridsize=1000, label = 'Black')
plt.xlim(0,150)
plt.title('Length of Sentence by Race')
plt.xlabel('Months')
plt.ylabel('Percent'... | _____no_output_____ | BSD-3-Clause | Lab_2/Practice_with_Visualizations.ipynb | ds-modules/SOC-88-SP21 |
Finding the nearest sentences about *cat* | import numpy as np
import re
from scipy.spatial import distance | _____no_output_____ | BSD-2-Clause | ya.learning/1c2w Nearest sentences.ipynb | aosorgin/ml-notebooks |
Reading sentences from file and place them to dict and listWe use the following structure to store words:```struct Word { Index int, Count int}dict{\: @Word}``` | class Words:
def __init__(self):
self._words = dict()
def add(self, word):
if word in self._words:
self._words[word]['count'] += 1
else:
self._words[word] = {'index': len(self._words), 'count': 1}
def index(self, word):
if word in self._words... | _____no_output_____ | BSD-2-Clause | ya.learning/1c2w Nearest sentences.ipynb | aosorgin/ml-notebooks |
Reading sentances from file | allWords = Words()
listOfSentenceFeatures = []
with open('data/1c2s_sentences.txt', 'r') as f:
for sentence in f.readlines():
sentenceWords = Words()
words = np.array([x.lower() for x in re.split('[^A-Za-z]', sentence.strip())])
words = words[words != '']
for word in words:
... | _____no_output_____ | BSD-2-Clause | ya.learning/1c2w Nearest sentences.ipynb | aosorgin/ml-notebooks |
Construct matrix of sentance features | features = np.zeros((len(listOfSentenceFeatures), len(listOfSentenceFeatures[-1])))
for enu, row in enumerate(listOfSentenceFeatures):
features[enu, :len(row)] += row | _____no_output_____ | BSD-2-Clause | ya.learning/1c2w Nearest sentences.ipynb | aosorgin/ml-notebooks |
Calculating cosine distance for all sentences from the first one | distances = dict()
for num, row in enumerate(features[1:]):
distances[distance.cosine(features[0], row)] = num + 1
print [(distances[key], key) for key in sorted(distances.keys())] | [(6, 0.7327387580875756), (4, 0.7770887149698589), (21, 0.8250364469440588), (10, 0.8328165362273942), (12, 0.8396432548525454), (16, 0.8406361854220809), (20, 0.8427572744917122), (2, 0.8644738145642124), (13, 0.8703592552895671), (14, 0.8740118423302576), (11, 0.8804771390665607), (8, 0.8842724875284311), (19, 0.8885... | BSD-2-Clause | ya.learning/1c2w Nearest sentences.ipynb | aosorgin/ml-notebooks |
Writing results to file | with open('data/1c2s_result1.txt', 'w') as f:
f.write(' '.join((str(distances[key]) for key in sorted(distances.keys()))))
!cat data/1c2s_result1.txt
!cat data/1c2s_sentences.txt | In comparison to dogs, cats have not undergone major changes during the domestication process.
As cat simply catenates streams of bytes, it can be also used to concatenate binary files, where it will just concatenate sequence of bytes.
A common interactive use of cat for a single file is to output the content of a fi... | BSD-2-Clause | ya.learning/1c2w Nearest sentences.ipynb | aosorgin/ml-notebooks |
Mini-batch Stochastic Gradient Descent In each iteration, the gradient descent uses the entire training data set to compute the gradient, so it is sometimes referred to as batch gradient descent. Stochastic gradient descent (SGD) only randomly select one example in each iteration to compute the gradient. Just like in ... | import sys
sys.path.insert(0, '..')
%matplotlib inline
import d2l
import torch
import torch.nn as nn
import numpy as np
import time
def get_data():
data = np.genfromtxt('../data/airfoil_self_noise.dat', delimiter='\t')
data = (data - data.mean(axis=0)) / data.std(axis=0)
return torch.Tensor(data[:1500, :-1]... | _____no_output_____ | Apache-2.0 | Ch12_Optimization_Algorithms/Mini-batch_Stochastic_Gradient_Descent.ipynb | jasson31/d2l-pytorch |
Implementation from Scratch We have already implemented the mini-batch SGD algorithm in the chapter linear cratch. We have made its input parameters more generic here, so that we can conveniently use the same input for the other optimization algorithms introduced later in this chapter. Specifically, we add the status ... | def sgd(params, states, hyperparams,batch_size):
for p in params:
print('p:',p.grad)
p.data.sub_(hyperparams['lr'] * p.grad)
p.grad.data.zero_() | _____no_output_____ | Apache-2.0 | Ch12_Optimization_Algorithms/Mini-batch_Stochastic_Gradient_Descent.ipynb | jasson31/d2l-pytorch |
Next, we are going to implement a generic training function to facilitate the use of the other optimization algorithms introduced later in this chapter. It initializes a linear regression model and can then be used to train the model with the mini-batch SGD and other algorithms introduced in subsequent sections. | def train(trainer_fn, states, hyperparams, features, labels,batch_size=10, num_epochs=2):
# Initialize model parameters
net, loss = d2l.linreg, d2l.squared_loss
w = torch.ones(()).new_empty((features.shape[1], 1),requires_grad=True)
b= torch.zeros((1,),requires_grad=True)
l= torch.zeros((1500,1... | _____no_output_____ | Apache-2.0 | Ch12_Optimization_Algorithms/Mini-batch_Stochastic_Gradient_Descent.ipynb | jasson31/d2l-pytorch |
When the batch size equals 1500 (the total number of examples), we use gradient descent for optimization. The model parameters will be iterated only once for each epoch of the gradient descent. As we can see, the downward trend of the value of the objective function (training loss) flattened out after 6 iterations. | def train_sgd(lr, batch_size, num_epochs=2):
return train(sgd, None, {'lr': lr}, features, labels, batch_size, num_epochs)
gd_res = train_sgd(1, 1500,4)
| p: None
| Apache-2.0 | Ch12_Optimization_Algorithms/Mini-batch_Stochastic_Gradient_Descent.ipynb | jasson31/d2l-pytorch |
When the batch size equals 1, we use SGD for optimization. In order to simplify the implementation, we did not self-decay the learning rate. Instead, we simply used a small constant for the learning rate in the (mini-batch) SGD experiment. In SGD, the independent variable (model parameter) is updated whenever an exampl... | sgd_res = train_sgd(0.005, 1) | p: None
| Apache-2.0 | Ch12_Optimization_Algorithms/Mini-batch_Stochastic_Gradient_Descent.ipynb | jasson31/d2l-pytorch |
When the batch size equals 100, we use mini-batch SGD for optimization. The time required for one epoch is between the time needed for gradient descent and SGD to complete the same epoch. | mini1_res = train_sgd(.4, 100) | loss: 0.246469, 0.086600 sec per epoch
| Apache-2.0 | Ch12_Optimization_Algorithms/Mini-batch_Stochastic_Gradient_Descent.ipynb | jasson31/d2l-pytorch |
Reduce the batch size to 10, the time for each epoch increases because the workload for each batch is less efficient to execute. | mini2_res = train_sgd(.05, 10) | loss: 0.243249, 0.310116 sec per epoch
| Apache-2.0 | Ch12_Optimization_Algorithms/Mini-batch_Stochastic_Gradient_Descent.ipynb | jasson31/d2l-pytorch |
Finally, we compare the time versus loss for the preview four experiments. As can be seen, despite SGD converges faster than GD in terms of number of examples processed, it uses more time to reach the same loss than GD because that computing gradient example by example is not efficient. Mini-batch SGD is able to trade-... | d2l.set_figsize([6, 3])
for res in [gd_res, sgd_res, mini1_res, mini2_res]:
d2l.plt.plot(res[0], res[1])
d2l.plt.xlabel('time (sec)')
d2l.plt.ylabel('loss')
d2l.plt.xscale('log')
d2l.plt.xlim([1e-3, 1])
d2l.plt.legend(['gd', 'sgd', 'batch size=100', 'batch size=10']); | _____no_output_____ | Apache-2.0 | Ch12_Optimization_Algorithms/Mini-batch_Stochastic_Gradient_Descent.ipynb | jasson31/d2l-pytorch |
IPython Utilities Utilities to help work with ipython/jupyter environment. To import from [`fastai.utils.ipython`](/utils.ipython.htmlutils.ipython) do: | from fastai.gen_doc.nbdoc import *
from fastai.utils.ipython import * | _____no_output_____ | Apache-2.0 | docs_src/utils.ipython.ipynb | mogwai/fastai |
Workarounds to the leaky ipython traceback on exceptionipython has a feature where it stores tb with all the `locals()` tied in, whichprevents `gc.collect()` from freeing those variables and leading to a leakage.Therefore we cleanse the tb before handing it over to ipython. The 2 ways of doing it are by either using t... | show_doc(gpu_mem_restore) | _____no_output_____ | Apache-2.0 | docs_src/utils.ipython.ipynb | mogwai/fastai |
[`gpu_mem_restore`](/utils.ipython.htmlgpu_mem_restore) is a decorator to be used with any functions that interact with CUDA (top-level is fine)* under non-ipython environment it doesn't do anything.* under ipython currently it strips tb by default only for the "CUDA out of memory" exception.The env var `FASTAI_TB_CLEA... | show_doc(gpu_mem_restore_ctx, title_level=4) | _____no_output_____ | Apache-2.0 | docs_src/utils.ipython.ipynb | mogwai/fastai |
if function decorator is not a good option, you can use a context manager instead. For example:```with gpu_mem_restore_ctx(): learn.fit_one_cycle(1,1e-2)```This particular one will clear tb on any exception. | from fastai.gen_doc.nbdoc import *
from fastai.utils.ipython import * | _____no_output_____ | Apache-2.0 | docs_src/utils.ipython.ipynb | mogwai/fastai |
Brainstorm tutorial datasetsHere we compute the evoked from raw for the Brainstormtutorial dataset. For comparison, see [1]_ and: http://neuroimage.usc.edu/brainstorm/Tutorials/MedianNerveCtfReferences----------.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM. Brainstorm: A User-Friendly Application... | # Authors: Mainak Jas <mainak.jas@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets.brainstorm import bst_raw
print(__doc__)
tmin, tmax, event_id = -0.1, 0.3, 2 # take right-hand somato
reject = dict(mag=4e-12, eog=250e-6)
data_path = bst_raw.data_path()
raw_fname ... | _____no_output_____ | BSD-3-Clause | 0.15/_downloads/plot_brainstorm_data.ipynb | drammock/mne-tools.github.io |
Scalar and vector> Marcos Duarte > Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/)) > Federal University of ABC, Brazil Python handles very well all mathematical operations with numeric scalars and vectors and you can use [Sympy](http://sympy.org) for similar stuff but with abs... | import math
a = 2
b = 3
print('a =', a, ', b =', b)
print('a + b =', a + b)
print('a - b =', a - b)
print('a * b =', a * b)
print('a / b =', a / b)
print('a ** b =', a ** b)
print('sqrt(b) =', math.sqrt(b)) | a = 2 , b = 3
a + b = 5
a - b = -1
a * b = 6
a / b = 0.6666666666666666
a ** b = 8
sqrt(b) = 1.7320508075688772
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
If you have a set of numbers, or an array, it is probably better to use Numpy; it will be faster for large data sets, and combined with Scipy, has many more mathematical funcions. | import numpy as np
a = 2
b = [3, 4, 5, 6, 7, 8]
b = np.array(b)
print('a =', a, ', b =', b)
print('a + b =', a + b)
print('a - b =', a - b)
print('a * b =', a * b)
print('a / b =', a / b)
print('a ** b =', a ** b)
print('np.sqrt(b) =', np.sqrt(b)) # use numpy functions for numpy arrays | a = 2 , b = [3 4 5 6 7 8]
a + b = [ 5 6 7 8 9 10]
a - b = [-1 -2 -3 -4 -5 -6]
a * b = [ 6 8 10 12 14 16]
a / b = [ 0.66666667 0.5 0.4 0.33333333 0.28571429 0.25 ]
a ** b = [ 8 16 32 64 128 256]
np.sqrt(b) = [ 1.73205081 2. 2.23606798 2.44948974 2.64575131 2.82842712]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Numpy performs the arithmetic operations of the single number in `a` with all the numbers of the array `b`. This is called broadcasting in computer science. Even if you have two arrays (but they must have the same size), Numpy handles for you: | a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print('a =', a, ', b =', b)
print('a + b =', a + b)
print('a - b =', a - b)
print('a * b =', a * b)
print('a / b =', a / b)
print('a ** b =', a ** b) | a = [1 2 3] , b = [4 5 6]
a + b = [5 7 9]
a - b = [-3 -3 -3]
a * b = [ 4 10 18]
a / b = [ 0.25 0.4 0.5 ]
a ** b = [ 1 32 729]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Vector>A **vector** is a quantity with magnitude (or length) and direction expressed numerically as an ordered list of values according to a coordinate reference system. For example, position, force, and torque are physical quantities defined by vectors.For instance, consider the position of a point in space represen... | a = np.array([1, 3, 2])
print('a =', a) | a = [1 3 2]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Exactly like the arrays in the last example for scalars, so all operations we performed will result in the same values, of course. However, as we are now dealing with vectors, now some of the operations don't make sense. For example, for vectors there are no multiplication, division, power, and square root in the wa... | a = np.array([1, 2, 3])
np.linalg.norm(a) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Or we can use the definition and compute directly: | np.sqrt(np.sum(a*a)) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Then, the versor for the vector $ \overrightarrow{\mathbf{a}} = (1, 2, 3) $ is: | a = np.array([1, 2, 3])
u = a/np.linalg.norm(a)
print('u =', u) | u = [ 0.26726124 0.53452248 0.80178373]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
And we can verify its magnitude is indeed 1: | np.linalg.norm(u) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
But the representation of a vector as a tuple of values is only valid for a vector with its origin coinciding with the origin $ (0, 0, 0) $ of the coordinate system we adopted.For instance, consider the following vector: Figure. A vector in space.Such a vector cannot be represented by $ (b_x, b_y, b_z) $ because this ... | a = np.array([[1, 2, 3], [1, 1, 1]])
b = np.array([[4, 5, 6], [7, 8, 9]])
print('a =', a, '\nb =', b)
print('a + b =', a + b)
print('a - b =', a - b) | a = [[1 2 3]
[1 1 1]]
b = [[4 5 6]
[7 8 9]]
a + b = [[ 5 7 9]
[ 8 9 10]]
a - b = [[-3 -3 -3]
[-6 -7 -8]]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Numpy can handle a N-dimensional array with the size limited by the available memory in your computer.And we can perform operations on each vector, for example, calculate the norm of each one. First let's check the shape of the variable `a` using the method `shape` or the function `numpy.shape`: | print(a.shape)
print(np.shape(a)) | (2, 3)
(2, 3)
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
This means the variable `a` has 2 rows and 3 columns. We have to tell the function `numpy.norm` to calculate the norm for each vector, i.e., to operate through the columns of the variable `a` using the paraneter `axis`: | np.linalg.norm(a, axis=1) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Dot productDot product (or scalar product or inner product) between two vectors is a mathematical operation algebraically defined as the sum of the products of the corresponding components (maginitudes in each direction) of the two vectors. The result of the dot product is a single number (a scalar). The dot product ... | from IPython.display import IFrame
IFrame('https://faraday.physics.utoronto.ca/PVB/Harrison/Flash/Vectors/DotProduct/DotProduct.html',
width='100%', height=400) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
The Numpy function for the dot product is `numpy.dot`: | a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print('a =', a, '\nb =', b)
print('np.dot(a, b) =', np.dot(a, b)) | a = [1 2 3]
b = [4 5 6]
np.dot(a, b) = 32
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Or we can use the definition and compute directly: | np.sum(a*b) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.