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 |
|---|---|---|---|---|---|
How does it perform on a different distribution? | n = 1000
X, y = datasets.make_circles(n_samples=n, shuffle=True, noise=0.05, random_state=None, factor = 0.4)
plt.scatter(X[:,0], X[:,1])
# k-means fails
km = KMeans(n_clusters = 2)
km.fit(X)
plt.scatter(X[:,0], X[:,1], c = km.predict(X)) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
By adjusting the distance parameter `epsilon`, we can find a way to cluster the two circular blobs. We do run into singularity issues for some values of `epsilon`, but otherwise the results are plotted below. | fig, axs = plt.subplots(11, figsize=(8,50))
for i in range(3,11):
epsilon = i/10
try:
axs[i].scatter(X[:,0], X[:,1], c = spectral_clustering(X,epsilon))
axs[i].set_title(label = "epsilon = " + str(epsilon))
except:
print("Error when epsilon = ", epsilon) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Topic: Challenge Set 1 (MTA Subway Turnstile Data - Subject: Explore MTA turnstile dataDate: 09/29/2018Name: Brenner Heintz | import pandas as pd
import numpy as np
import random
import itertools
import calendar
import datetime as dt
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
%matplotlib inline
%xmode
import matplotlib.style as style
style.use('fivethirtyeight')
sns.set_context('notebook', font_sca... | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
Downloaded data from: http://web.mta.info/developers/turnstile.htmlDownloaded 3 weeks of data:Saturday, September 22, 2018Saturday, September 15, 2018Saturday, September 08, 2018Documentation at: http://web.mta.info/developers/resources/nyct/turnstile/ts_Field_Description.txtMap of the MTA system: http://web.mta.info/m... | df1 = pd.read_csv('http://web.mta.info/developers/data/nyct/turnstile/turnstile_180908.txt')
df2 = pd.read_csv('http://web.mta.info/developers/data/nyct/turnstile/turnstile_180915.txt')
df3 = pd.read_csv('http://web.mta.info/developers/data/nyct/turnstile/turnstile_180922.txt')
frames = [df1, df2, df3]
df = pd.concat(f... | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 2**"Let's turn this into a time series. Create a new column that specifies the date and time of each entry." | df['DATE'] = pd.to_datetime(df['DATE'], format='%m/%d/%Y')
# df['DATETIME'] = pd.to_datetime(df.DATE + ' ' + df.TIME, format='%m/%d/%Y') | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 3**These counts are for every n hours. (What is n?) We want total daily entries. | df['STATION_KEY'] = df['C/A'] + ' ' + df['UNIT'] + ' ' + df['STATION']
df['EXITS'] = df['EXITS ']
df.drop('EXITS ', axis=1, inplace=True)
# Reset index because index was duplicated on all 3 origin... | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 4**Now plot the daily time series for a turnstile. | x = df.groupby(['STATION_KEY', 'SCP','DATE'])['ENTRY_DIFFS'].sum()
x = pd.DataFrame(x)
x.reset_index(inplace=True)
x.head(2)
x_values = x[(x['SCP']=='02-00-00') & (x['STATION_KEY']=='A002 R051 59 ST')]['DATE']
y_values = x[(x['SCP']=='02-00-00') & (x['STATION_KEY']=='A002 R051 59 ST')]['ENTRY_DIFFS']
y_values = y_value... | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 5**We want to combine the numbers together -- for each ControlArea/UNIT/STATION combo, for each day, add the counts from each turnstile belonging to that combo. | df.head(3)
df['UNIT'].nunique()
df.groupby(['C/A', 'UNIT', 'SCP', 'DATE']).sum() | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 6**Similarly, combine everything in each station, and come up with a time series of [(date1, count1),(date2,count2),...] type of time series for each STATION, by adding up all the turnstiles in a station. | station_df = df.groupby(['STATION', 'DATE']).sum()
station_df.reset_index(inplace=True) | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 7**Plot the time series (either daily or your preferred level of granularity) for a station. | x_values = station_df[station_df['STATION'] == '1 AV']['DATE']
y_values = station_df[station_df['STATION'] == '1 AV']['TOTAL']
y_values = y_values.astype(int)
fig, ax = plt.subplots()
fig.set_size_inches(8,4)
fig.autofmt_xdate()
ax.xaxis.set_major_locator(mdates.WeekdayLocator())
ax.xaxis.set_major_formatter(mdates.D... | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 8**Select a station and find the total daily counts for this station. Then plot those daily counts for each week separately.To clarify: if I have 10 weeks of data on the 28th st 6 station, I will add 10 lines to the same figure (e.g. running plt.plot(week_count_list) once for each week). Each plot will have... | fig, ax = plt.subplots()
fig.set_size_inches(8,4)
fig.autofmt_xdate()
ax.xaxis.set_major_locator(mdates.WeekdayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b. %d'))
ax.set_xlabel('Date')
ax.set_ylabel('Daily Entries')
ax.set_title('Daily Turnstile Entries (First Ave Station)')
plt.plot(x_values[:8... | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 9**Over multiple weeks, sum total ridership for each station and sort them, so you can find out the stations with the highest traffic during the time you investigate | total_ridership_counts = df.groupby('STATION').sum()
total_ridership_counts.reset_index(inplace=True)
total_ridership_counts.head(3) | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
**Challenge 10**Make a single list of these total ridership values and plot it withplt.hist(total_ridership_counts) | y_vals = total_ridership_counts['TOTAL']
fig, ax = plt.subplots()
fig.set_size_inches(8,4)
ax.set_xlabel('Entries')
ax.set_ylabel('Number of Stations')
ax.set_title('Histogram of Total Entries')
ax.set_xlim(0,3000000)
plt.ticklabel_format(style='plain', axis='x')
plt.hist(y_vals, bins=30); | _____no_output_____ | MIT | weekly_challenges/challenge_set_1_heintz.ipynb | athena15/metis |
Notebook 1: Homology matrix generation from genome sequencesIn this notebook, I will be applying the notebooks accompanying the paper by Norsigian et al., 2020. (doi:10.1038/s41596-019-0254-3.) I will apply this for the P. thermo model we've been working on and the M10EXG strain that we used to validate our model with... | #import packages needed
import pandas as pd
from glob import glob
from Bio import Entrez, SeqIO
import sys
import cobra
import decimal | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
__NOTE__ to be able to import the Entrez and SeqIO, I need to change the folder name from 'bio' to 'Bio' and then it'll work. C:\Users\vivmol\AppData\Local\Continuum\anaconda3\envs\g-thermo\Lib\site-packagesSo be careful whenever i install Biopython again that this needs to be fixed. Here I will be working with strains... | # Load the information on the five strains we will be working with in this tutorial
StrainsOfInterest=pd.read_excel('Strain Information.xlsx')
StrainsOfInterest
#The Reference Genome is as Described in the Base Reconstruction; here the reference is
referenceStrainID='NCIMB11955'
targetStrainIDs=list(StrainsOfInterest[... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
1. Download genome annotations (GenBank files) to generate fasta files Dowload genomes from NCBIDownload the genome annotations (GenBank files) from NCBI for strains of interest. | # define a function to download the annotated genebank files from NCBI
def dl_genome(id, folder='genomes'): # be sure get CORRECT ID
files=glob('%s/*.gb'%folder)
out_file = '%s/%s.gb'%(folder, id)
if out_file in files:
print (out_file, 'already downloaded')
return
else:
print ('... | downloading CP016622.1 from NCBI
| Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Examine the Downloaded Strains | # define a function to gather information of the downloaded strains from the GenBank files
def get_strain_info(folder='genomes'):
files = glob('%s/*.gb'%folder)
strain_info = []
for file in files:
handle = open(file)
record = SeqIO.read(handle, "genbank")
for f in recor... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Generate FASTA files for both Protein and Nucleotide PipelinesFrom the GenBank file, we can extract sequence and annoation information to generate fasta files for the protein and nucleotide analyses. The resulting fasta files will then be used in step 2 as input for BLAST | # define a function to parse the Genbank file to generate fasta files for both protein and nucleotide sequences
def parse_genome(id, type='prot', in_folder='genomes', out_folder='prots', overwrite=1):
in_file = '%s/%s.gb'%(in_folder, id)
out_file='%s/%s.fa'%(out_folder, id)
files =glob('%s/*.fa'%out_folder... | parsing NCIMB11955
parsing NCIMB11955
| Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
2. Perform BLAST to find homologous proteins in strains of interest Make BLAST DB for each of the target strains for both Protein and Nucleotide PipelinesIn this tutorial, we will run both BLASTp for proteins and BLSATn for nucleotides. BLASTp will be used as the main approach to identify homologous proteins in refer... | # Define a function to make blast database for either protein of nucleotide
def make_blast_db(id,folder='prots',db_type='prot'):
import os
out_file ='%s/%s.fa.pin'%(folder, id)
files =glob('%s/*.fa.pin'%folder)
if out_file in files:
print (id, 'already has a blast db')
return
... | making blast db with following command line...
makeblastdb -in prots/2501416905.fa -dbtype prot
making blast db with following command line...
makeblastdb -in prots/NCIMB11955.fa -dbtype prot
| Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Define functions to run protein BLAST and get sequence lengths- BLASTp will be the main approach used here to identify homologous proteins between strains - Aside from sequence similarity, we also want to ensure the coverage of sequence mapping is sufficient. Therefore, we need to identiy the sequence length for each ... | # define a function to run BLASTp
def run_blastp(seq,db,in_folder='prots', out_folder='bbh', out=None,outfmt=6,evalue=0.001,threads=1):
import os
if out==None:
out='%s/%s_vs_%s.txt'%(out_folder, seq, db)
print(out)
files =glob('%s/*.txt'%out_folder)
if out in files:
print (s... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
3. Use Bi-Directional BLASTp Best Hits to create gene presence/absence matrix Obtain Bi-Directional BLASTp Best HitsFrom the above BLASTp results, we can obtain Bi-Directional BLASTp Best Hits to identify homologous proteins. Note beside gene similarity score, the coverage of alignment is also used to filter mapping ... | # define a function to get Bi-Directional BLASTp Best Hits
def get_bbh(query, subject, in_folder='bbh'):
#Utilize the defined protein BLAST function
run_blastp(query, subject)
run_blastp(subject, query)
query_lengths = get_gene_lens(query, in_folder='prots')
subject_lengths = get_gene_... | bbh/NCIMB11955_vs_2501416905.txt
blasting NCIMB11955 vs 2501416905
running blastp with following command line...
blastp -db prots/2501416905.fa -query prots/NCIMB11955.fa -out bbh/NCIMB11955_vs_2501416905.txt -evalue 0.001 -outfmt 6 -num_threads 1
bbh/2501416905_vs_NCIMB11955.txt
blasting 2501416905 vs NCIMB11955
runni... | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Parse the BLAST Results into one Homology Matrix of the Reconstruction GenesFor the homology matrix, want to find, for each gene in the reference annotation, is there one in the other strains. And then later filter this down to metabolic genes. | #Load all the BLAST files between the reference strain and target strains
blast_files=glob('%s/*_parsed.csv'%'bbh')
for blast in blast_files:
bbh=pd.read_csv(blast)
print (blast,bbh.shape) | bbh\NCIMB11955_vs_2501416905_parsed.csv (3520, 16)
| Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
In this section of the notebook, I will deviate from the published tutorial. In the tutorial, they map the orthologous genes onto the curated model of the reference genome. In reality, we are curious as to how homologous the genomes are to one another, and how many metabolic genes the different strains have in common. ... | #import all the csv files
compare = pd.read_csv('bbh/NCIMB11955_vs_2501416905_parsed.csv')
#filter out all other columns that i won't use later
compare = compare[['gene', 'PID']]
#list of all ORFs found in the reference genome
with open('prots/NCIMB11955.fa') as fasta_file: # Will close handle cleanly
NCIMB_ids = ... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now that we have a dataframe that compares the PID scores for each gene in the reference genome to the other strains, we can start to 'sum up' what percentage of the genes in the reference have a matched gene in the strain. For this, we will set a threshold of 80% sequence identity between genes to be counted as a true... | columns = list(comparison)
for i in columns: #iterate through the columns
if i in 'NCIMB11955': # skip reference column
continue
else:
#now go through each row in this column
common_genes = []
for index,row in comparison.iterrows():
value = row[i]
if v... | M10EXG : 88.9967637540453
| Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Try the same as above, but use the E-value as the threshold instead. | #import all the csv files
compare = pd.read_csv('bbh/NCIMB11955_vs_2501416905_parsed.csv')
#filter out all other columns that i won't use later
compare_eval = compare[['gene', 'eVal']]
#make dataframe for first comparison, and then add on the rest
comparison_eval = pd.DataFrame({'gene': NCIMB_ids})
comparison_eval = p... | M10EXG : 94.47141316073355
| Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now that we have done the above, we can start to look at the overlap between the strains, so that we can create a venn diagram of total ORFs that are unique to each strain but also ovelap. __Approach__- Import the fasta files in the prots folder: this is a list of all the ORFs in each strain. - make a list, per strain,... | #import total strain lists, for each strain
with open('prots/2501416905.fa') as fasta_file: # Will close handle cleanly
M10EXG_ids = []
for seq_record in SeqIO.parse(fasta_file, 'fasta'): # (generator)
M10EXG_ids.append(seq_record.id) | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Next is to make a dataframe for the comparison of the reference (here NCIMB11955) to the other strain. The list should then contain the gene names of the reference organism, as well as the strain being mapped against. | compare_eval
ol_reference = [] #the overlapping genes, with the reference strain ID
ol_strain =[] #the overlapping genes, with the reference strain ID
for index,row in compare.iterrows():
value = row['eVal']
if value > 1E-5: #selected threshold level
continue #we don't want to save these anywhere ... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
In the example above, you then see which 3498 genes of the target strain match the reference strain.We can then see how many genes each strain has by themselves and from that make the venndiagram. | len(NCIMB_ids) | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
So NCIMB has 259 unique ORFs. In the above, we had NCIMB as the reference strain. TO find how many true unique genes there are in M10EXG, we would need to repeat the above analysis but now with M10EXG as reference strain. That will be done below. | StrainsOfInterest=pd.read_excel('Strain InformationB.xlsx')
StrainsOfInterest
#switch reference and target here
referenceStrainID='2501416905'
targetStrainIDs=list(StrainsOfInterest['NCBI ID'])
for strain in targetStrainIDs:
get_bbh(referenceStrainID,strain, in_folder='bbh') | bbh/2501416905_vs_NCIMB11955.txt
blasting 2501416905 vs NCIMB11955
running blastp with following command line...
blastp -db prots/NCIMB11955.fa -query prots/2501416905.fa -out bbh/2501416905_vs_NCIMB11955.txt -evalue 0.001 -outfmt 6 -num_threads 1
bbh/NCIMB11955_vs_2501416905.txt
blasting NCIMB11955 vs 2501416905
runni... | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now import this file and make it into a dataframe so we can find the unique genes. | #import all the csv files
compare = pd.read_csv('bbh/2501416905_vs_NCIMB11955_parsed.csv')
#filter out all other columns that i won't use later
compare_eval = compare[['gene', 'eVal', 'subject']]
strains = ['M10EXG', 'eVal', 'NCIMB11955']
compare_eval.columns = strains | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now that we have done the above, we can slook at the overlap from M10EXg to the NCIMB strain. __Approach__- make a list, per strain, of all genes for that strain that fit the comparison threshold (for this use Eval < 1E-5 for now) i.e. all the genes that these two strains have in common | ol_reference = [] #the overlapping genes, with the reference strain ID
ol_strain =[] #the overlapping genes, with the reference strain ID
for index,row in compare_eval.iterrows():
value = row['eVal']
if value > 1E-5: #selected threshold level
continue #we don't want to save these anywhere
... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
There are 5 genes less mapped as overlap, but this is within the error range. | len(M10EXG_ids) | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
So we would have 234 unique genes in M10EXG. So overall, we have 3498 genes that overlap, 259 unique in NCIMB and 234 unique in M10EXG. This very closely matches the results of the KBASE pipeline we did, which is good. Filter for metabolic genesNow that we know the overlap in the total protein, we want to find out wh... | genes = []
EC = []
x = 0
for seq_record in SeqIO.parse("genomes/NCIMB11955.gb", "genbank"):
for f in seq_record.features:
if f.type=='CDS':
if 'locus_tag' in f.qualifiers.keys():
locus = f.qualifiers['locus_tag'][0]
elif 'gene' in f.qualifiers.keys():
... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now I'll do the same for the M10EXG genome/annotation. | genes = []
EC = []
x = 0
for seq_record in SeqIO.parse("genomes/2501416905.gb", "genbank"):
for f in seq_record.features:
if f.type=='CDS':
if 'locus_tag' in f.qualifiers.keys():
locus = f.qualifiers['locus_tag'][0]
elif 'gene' in f.qualifiers.keys():
... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
So, this shows we have 1424 metabolic genes in the reference strain and 1417 in the M10EXG strain. Note, there are ofcourse many hypothetical proteins annotated in the genome. Those are ignored. Now, I will have to filter the list of BBH based on just the genes that are metabolic. Approach:- NCIMB_M10EXG_OL has all the... | NCIMB = []
M10EXG = []
for row, index in NCIMB_M10EXG_OL.iterrows():
ref_gene = index['NCIMB11955']
try:
NCIMB_met.loc[NCIMB_met["Gene"] == ref_gene,'EC'].values[0] #if it is a metaoblic gene this will give a hit
NCIMB.append(index['NCIMB11955'])
M10EXG.append(index['M10EXG'])
except... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
So we have 1384 metabolic genes that overlap. That means there are 40 genes unique to NCIMB, and for M10EXG we need to check how many are still unmatched. Finally, I will make a list of the unique metabolic genes, that can be supplied in supplementary, and given a short look through if anything unexpected appears.Appro... | genes = []
ECs =[]
for row, index in NCIMB_met.iterrows():
gene = index['Gene']
try:
OL_metabolic.loc[OL_metabolic["NCIMB11955"] == gene,'M10EXG'].values[0] #If the gene is in the overlap dataframe it will give an output
continue
except IndexError: #i.e. if the gene doesn't have an overlap i... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now we know that for NCIMB, there are 40 unique metabolic genes and 1384 overlapping genes. I will do the same as above but for the M10EXG strain to find how many are unique in that strain when that is used as reference sequence. | M10EXG = []
NCIMB = []
for row, index in M10EXG_NCIMB_OL.iterrows():
ref_gene = index['M10EXG']
try:
M10EXG_met.loc[M10EXG_met["Gene"] == ref_gene,'EC'].values[0] #if it is a metaoblic gene this will give a hit
M10EXG.append(index['M10EXG'])
NCIMB.append(index['NCIMB'])
except IndexE... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Again here there is a difference of a few genes, but falls within an error range if you consider the size of the total metabolic gene set. So this is fine. Next, we will make a dataframe of the metabolic genes that are unique to M10EXG. | genes = []
ECs =[]
for row, index in M10EXG_met.iterrows():
gene = index['Gene']
try:
OL_metabolic_M10EXG.loc[OL_metabolic_M10EXG["M10EXG"] == gene,'NCIMB11955'].values[0] #If the gene is in the overlap dataframe it will give an output
continue
except IndexError: #i.e. if the gene doesn't ha... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
So we have 29 unique genes in M10EXG, and 40 in our strain. Now we have two dataframes, one for each strain, with the unique metabolic genes, we can try to find a bit more information about them. I will try to get a name for the reaction, as well as what pathway they are a part of. First I will prepare a dataframe fro... | df = pd.read_csv('http://rest.kegg.jp/link/ec/pathway', header=None, sep = '\t')
df.columns = ['Pathway', 'EC'] #rename the columns
#remove all 'path:' and 'rn:'
df['Pathway'] = df['Pathway'].str.replace(r'path:ec', '')
df['EC'] = df['EC'].str.replace(r'ec:', '')
#remove the rows with 'path_map' to prevent duplication
... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now I can map the EC code from the unique metabolic reaction lists to these pathway classes. | pathway =[]
for index, row in NCIMB_unique.iterrows():
ec = row['EC']
types =[]
found = df.loc[df["EC"] == ec]
for indexa, rowa in found.iterrows() :
types.append(rowa['Name'])
pathway.append(types)
NCIMB_unique['Pathway'] = pathway
pathway =[]
for index, row in M10EXG_unique.iterrows():
... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now I'll also add a column which looks at the KO of the ec codes recognized so that we get a bit more information about which reactions are unique in each strain.First I will prepare a dataframe that contains the EC codes linked to the KO ontology terms for these annotations. That we can use to map the unique reactions... | df = pd.read_csv('http://rest.kegg.jp/link/ec/ko', header=None, sep = '\t')
df.columns = ['KO', 'EC'] #rename the columns
#remove all 'ko:' and 'ec:'
df['KO'] = df['KO'].str.replace(r'ko:', '')
df['EC'] = df['EC'].str.replace(r'ec:', '')
#now import the list of KO terms with more meaningful description
ko = pd.read_csv... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now we can map the EC code to a KO term. | ko_term =[]
for index, row in NCIMB_unique.iterrows():
ec = row['EC']
types =[]
found = df.loc[df["EC"] == ec]
for indexa, rowa in found.iterrows() :
types.append(rowa['Name'])
ko_term.append(types)
NCIMB_unique['KO'] = ko_term
ko_term =[]
for index, row in M10EXG_unique.iterrows():
ec ... | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
Now I will export these two tables and need to some some manual inspection of them. | M10EXG_unique.to_csv('M10EXG_unique.csv')
NCIMB_unique.to_csv('NCIMB_unique.csv') | _____no_output_____ | Apache-2.0 | notebooks/Genome comparison/55. Execute Sequence Comparison to Generate Homology Matrix -new.ipynb | biosustain/p-thermo |
IntroductionIn this exercise you'll apply more advanced encodings to encode the categorical variables ito improve your classifier model. The encodings you will implement are:- Count Encoding- Target Encoding- Leave-one-out Encoding- CatBoost Encoding- Feature embedding with SVD You'll refit the classifier after each e... | import numpy as np
import pandas as pd
from sklearn import preprocessing, metrics
import lightgbm as lgb
# Set up code checking
# This can take a few seconds, thanks for your patience
from learntools.core import binder
binder.bind(globals())
from learntools.feature_engineering.ex2 import *
clicks = pd.read_parquet('.... | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
Here I'll define a couple functions to help test the new encodings. | def get_data_splits(dataframe, valid_fraction=0.1):
""" Splits a dataframe into train, validation, and test sets. First, orders by
the column 'click_time'. Set the size of the validation and test sets with
the valid_fraction keyword argument.
"""
dataframe = dataframe.sort_values('click_ti... | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
Run this cell to get a baseline score. If your encodings do better than this, you can keep them. | print("Baseline model")
train, valid, test = get_data_splits(clicks)
_ = train_model(train, valid) | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
1) Categorical encodings and leakageThese encodings are all based on statistics calculated from the dataset like counts and means. Considering this, what data should you be using to calculate the encodings?Uncomment the following line after you've decided your answer. | q_1.solution() | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
2) Count encodingsHere, encode the categorical features `['ip', 'app', 'device', 'os', 'channel']` using the count of each value in the data set. Using `CountEncoder` from the `category_encoders` library, fit the encoding using the categorical feature columns defined in `cat_features`. Then apply the encodings to the ... | import category_encoders as ce
cat_features = ['ip', 'app', 'device', 'os', 'channel']
train, valid, test = get_data_splits(clicks)
# Create the count encoder
count_enc = ____
# Learn encoding from the training set
____
# Apply encoding to the train and validation sets as new columns
# Make sure to add `_count` as ... | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
Count encoding improved our model's score! 3) Why is count encoding effective?At first glance, it could be surprising that Count Encoding helps make accurate models. Why do you think is count encoding is a good idea, or how does it improve the model score?Uncomment the following line after you've decided your answer. | q_3.solution() | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
4) Target encodingHere you'll try some supervised encodings that use the labels (the targets) to transform categorical features. The first one is target encoding. Create the target encoder from the `category_encoders` library. Then, learn the encodings from the training dataset, apply the encodings to all the datasets... | cat_features = ['ip', 'app', 'device', 'os', 'channel']
train, valid, test = get_data_splits(clicks)
# Create the target encoder. You can find this easily by using tab completion.
# Start typing ce. the press Tab to bring up a list of classes and functions.
target_enc = ____
# Learn encoding from the training set. Us... | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
5) Try removing IP encodingTry leaving `ip` out of the encoded features and retrain the model with target encoding again. You should find that the score increases and is above the baseline score! Why do you think the score is below baseline when we encode the IP address but above baseline when we don't?Uncomment the f... | # q_5.solution() | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
6) CatBoost EncodingThe CatBoost encoder is supposed to working well with the LightGBM model. Encode the categorical features with `CatBoostEncoder` and train the model on the encoded data again. | train, valid, test = get_data_splits(clicks)
# Create the CatBoost encoder
cb_enc = ____
# Learn encoding from the training set
____
# Apply encoding to the train and validation sets as new columns
# Make sure to add `_cb` as a suffix to the new columns
train_encoded = ____
valid_encoded = ____
q_6.check()
# Uncomme... | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
The CatBoost encodings work the best, so we'll keep those. | encoded = cb_enc.transform(clicks[cat_features])
for col in encoded:
clicks.insert(len(clicks.columns), col + '_cb', encoded[col]) | _____no_output_____ | Apache-2.0 | notebooks/feature_engineering/raw/ex2.ipynb | dansbecker/learntools |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
Eager execution basics Run in Google Colab View source on GitHub This is an introductory tutorial for using TensorFlow. It will cover:* Importing required packages* Creating and using Tensors* Using GPU acceleration* Datasets Import TensorFlowTo get started, import the `tensorflow` module and enable ea... | from __future__ import absolute_import, division, print_function, unicode_literals
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
import tensorflow.compat.v1 as tf
| _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
TensorsA Tensor is a multi-dimensional array. Similar to NumPy `ndarray` objects, `Tensor` objects have a data type and a shape. Additionally, Tensors can reside in accelerator (like GPU) memory. TensorFlow offers a rich library of operations ([tf.add](https://www.tensorflow.org/api_docs/python/tf/add), [tf.matmul](ht... | print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.square(5))
print(tf.reduce_sum([1, 2, 3]))
print(tf.encode_base64("hello world"))
# Operator overloading is also supported
print(tf.square(2) + tf.square(3)) | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
Each Tensor has a shape and a datatype | x = tf.matmul([[1]], [[2, 3]])
print(x.shape)
print(x.dtype) | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
The most obvious differences between NumPy arrays and TensorFlow Tensors are:1. Tensors can be backed by accelerator memory (like GPU, TPU).2. Tensors are immutable. NumPy CompatibilityConversion between TensorFlow Tensors and NumPy ndarrays is quite simple as:* TensorFlow operations automatically convert NumPy ndarra... | import numpy as np
ndarray = np.ones([3, 3])
print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray, 42)
print(tensor)
print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor, 1))
print("The .numpy() method explicitly conver... | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
GPU accelerationMany TensorFlow operations can be accelerated by using the GPU for computation. Without any annotations, TensorFlow automatically decides whether to use the GPU or CPU for an operation (and copies the tensor between CPU and GPU memory if necessary). Tensors produced by an operation are typically backed... | x = tf.random.uniform([3, 3])
print("Is there a GPU available: "),
print(tf.test.is_gpu_available())
print("Is the Tensor on GPU #0: "),
print(x.device.endswith('GPU:0')) | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
Device NamesThe `Tensor.device` property provides a fully qualified string name of the device hosting the contents of the tensor. This name encodes many details, such as an identifier of the network address of the host on which this program is executing and the device within that host. This is required for distributed... | import time
def time_matmul(x):
start = time.time()
for loop in range(10):
tf.matmul(x, x)
result = time.time()-start
print("10 loops: {:0.2f}ms".format(1000*result))
# Force execution on CPU
print("On CPU:")
with tf.device("CPU:0"):
x = tf.random_uniform([1000, 1000])
assert x.device.endswith("CPU... | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
DatasetsThis section demonstrates the use of the [`tf.data.Dataset` API](https://www.tensorflow.org/r1/guide/datasets) to build pipelines to feed data to your model. It covers:* Creating a `Dataset`.* Iteration over a `Dataset` with eager execution enabled.We recommend using the `Dataset`s API for building performant,... | ds_tensors = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])
# Create a CSV file
import tempfile
_, filename = tempfile.mkstemp()
with open(filename, 'w') as f:
f.write("""Line 1
Line 2
Line 3
""")
ds_file = tf.data.TextLineDataset(filename) | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
Apply transformationsUse the transformations functions like [`map`](https://www.tensorflow.org/api_docs/python/tf/data/Datasetmap), [`batch`](https://www.tensorflow.org/api_docs/python/tf/data/Datasetbatch), [`shuffle`](https://www.tensorflow.org/api_docs/python/tf/data/Datasetshuffle) etc. to apply transformations to... | ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2) | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
IterateWhen eager execution is enabled `Dataset` objects support iteration.If you're familiar with the use of `Dataset`s in TensorFlow graphs, note that there is no need for calls to `Dataset.make_one_shot_iterator()` or `get_next()` calls. | print('Elements of ds_tensors:')
for x in ds_tensors:
print(x)
print('\nElements in ds_file:')
for x in ds_file:
print(x) | _____no_output_____ | Apache-2.0 | site/en/r1/tutorials/eager/eager_basics.ipynb | atharva1503/docs |
use cpu because the following computation need a lot of memory | device = 'cpu'
train_features, train_labels = train_features.to(device), train_labels.to(device)
num_train_data = train_labels.shape[0]
num_class = torch.max(train_labels) + 1
torch.manual_seed(args.rng_seed)
torch.cuda.manual_seed_all(args.rng_seed)
perm = torch.randperm(num_train_data).to(device)
print(perm) | tensor([36044, 49165, 37807, ..., 42128, 15898, 31476])
| MIT | notebooks/knn.ipynb | Bhaskers-Blu-Org2/metric-transfer.pytorch |
soft label | fig = plt.figure(dpi=200)
for num_labeled_data in [50, 100, 250, 500, 1000, 2000, 4000, 8000]:
index_labeled = []
index_unlabeled = []
data_per_class = num_labeled_data // args.num_class
for c in range(10):
indexes_c = perm[train_labels[perm] == c]
index_labeled.append(indexes_c[:data_pe... | tensor([24681, 42151, 48978, 41040, 36909, 8628, 24936, 35926, 15934, 8801,
36293, 28026, 3814, 34981, 21135, 16904, 20152, 3486, 11894, 29780,
23932, 33744, 41766, 42979, 49518, 11341, 6091, 48161, 36335, 29858,
36044, 25569, 46340, 8832, 38677, 37807, 4480, 18517, 8409, 15769,
... | MIT | notebooks/knn.ipynb | Bhaskers-Blu-Org2/metric-transfer.pytorch |
IntroductionThe aim of this project is to conduct a sentiment analysis using python and twitter's API. The topic in my case is Expo 2020.**What is Expo 2020?**> Initiated in London 1851. It is a global gathering aimed to find solutions to challenges imposed by the current times. Aims to create enriching and immersive... | import tweepy
import pandas as pd
import numpy as np
import configparser
import matplotlib.pyplot as plt
import random | _____no_output_____ | MIT | tweets-collection.ipynb | dalalbinhumaid/expo-2020-sentiment-analysis |
1. Configuration and Authentication ---This is the setup part and API authentication. Prior to using the API it is necessary to create a developer account, the account grants you two levels of access. A user level and an application/project level. I will be using **configparser** to ensure my API keys are not visible.... | # read the file from 'config.ini'
config = configparser.ConfigParser()
config.read('config.ini')
# API Variables
CONSUMER_KEY = config['twitter']['CONSUMER_KEY']
CONSUMER_SECRET = config['twitter']['CONSUMER_SECRET']
ACCESS_TOKEN = config['twitter']['ACCESS_TOKEN']
ACCESS_TOKEN_SECRET = config['twitter']['ACCESS_TOKE... | _____no_output_____ | MIT | tweets-collection.ipynb | dalalbinhumaid/expo-2020-sentiment-analysis |
2. Data Collection---After setting up the credentials and authenticating the project. I can start extracting data using **tweepy's** API. The aim is to search different terms and different hashtags in order to collect as much entries as the API allows for. There are many limitations since I have the `Elevated Access`.... | def extract_tweets():
tweets = [] # main data frame
data = [] # temporary data frame
columns_header = ['ID', 'Tweet', 'Timestamp', 'Likes', 'Retweets', 'Length']
search_terms = ['@expo2020dubai -filter:retweets',
'#expo2020 -filter:retweets',
'#اكسبو -filter:retw... | _____no_output_____ | MIT | tweets-collection.ipynb | dalalbinhumaid/expo-2020-sentiment-analysis |
3. Preliminary Data Exploration | display(tweets.head())
display(tweets.tail())
print('total of collected tweets is ', len(tweets))
tweets.info()
| <class 'pandas.core.frame.DataFrame'>
Int64Index: 706 entries, 0 to 705
Data columns (total 6 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ID 706 non-null int64
1 Tweet 706 non-null object
2 Tim... | MIT | tweets-collection.ipynb | dalalbinhumaid/expo-2020-sentiment-analysis |
4. Data Visualization | plt.plot(tweets['Timestamp'], tweets['Likes'])
plt.gcf().autofmt_xdate()
plt.show()
plt.scatter(tweets['Length'], tweets['Likes'], color='pink')
plt.show()
# tweets1 = pd.read_csv('tweets1.csv')
# tweets2 = pd.read_csv('tweets3.csv')
# tweets3 = pd.read_csv('tweets327.csv')
# tweets4 = pd.read_csv('tweets1439.csv')
# ... | _____no_output_____ | MIT | tweets-collection.ipynb | dalalbinhumaid/expo-2020-sentiment-analysis |
Plotly | import plotly.graph_objects as go
import dash
import dash_core_components as dcc
import dash_html_components as html
country_list = df_plot[1:].columns
fig = go.Figure()
for each in country_list:
fig.add_trace(go.Scatter(
x = df_plot.date,
y = df_plot[each],
mode = 'markers+lines',
... | Dash is running on http://127.0.0.1:8050/
Dash is running on http://127.0.0.1:8050/
Dash is running on http://127.0.0.1:8050/
Dash is running on http://127.0.0.1:8050/
Dash is running on http://127.0.0.1:8050/
Dash is running on http://127.0.0.1:8050/
Dash is running on http://127.0.0.1:8050/
Dash is running on ... | FTL | notebooks/EDA.ipynb | simran-grewal/COVID-19-Data-Analysis |
Copyright 2019 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Get started with TensorBoard View on TensorFlow.org Run in Google Colab View source on GitHub In machine learning, to improve something you often need to be able to measure it. TensorBoard is a tool for providing the measurements and visualizations needed during the machine learning workflow. It e... | # Load the TensorBoard notebook extension
%load_ext tensorboard
import tensorflow as tf
import datetime
# Clear any logs from previous runs
!rm -rf ./logs/ | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Using the [MNIST](https://en.wikipedia.org/wiki/MNIST_database) dataset as the example, normalize the data and write a function that creates a simple Keras model for classifying the images into 10 classes. | mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
def create_model():
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.... | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
| Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Using TensorBoard with Keras Model.fit() When training with Keras's [Model.fit()](https://www.tensorflow.org/api_docs/python/tf/keras/models/Modelfit), adding the `tf.keras.callbacks.TensorBoard` callback ensures that logs are created and stored. Additionally, enable histogram computation every epoch with `histogram_f... | model = create_model()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
model.fit(... | Train on 60000 samples, validate on 10000 samples
Epoch 1/5
60000/60000 [==============================] - 15s 246us/sample - loss: 0.2217 - accuracy: 0.9343 - val_loss: 0.1019 - val_accuracy: 0.9685
Epoch 2/5
60000/60000 [==============================] - 14s 229us/sample - loss: 0.0975 - accuracy: 0.9698 - val_loss: ... | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Start TensorBoard through the command line or within a notebook experience. The two interfaces are generally the same. In notebooks, use the `%tensorboard` line magic. On the command line, run the same command without "%". | %tensorboard --logdir logs/fit | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
A brief overview of the dashboards shown (tabs in top navigation bar):* The **Scalars** dashboard shows how the loss and metrics change with every epoch. You can use it to also track training speed, learning rate, and other scalar values.* The **Graphs** dashboard helps you visualize your model. In this case, the Kera... | train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))
train_dataset = train_dataset.shuffle(60000).batch(64)
test_dataset = test_dataset.batch(64) | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
The training code follows the [advanced quickstart](https://www.tensorflow.org/tutorials/quickstart/advanced) tutorial, but shows how to log metrics to TensorBoard. Choose loss and optimizer: | loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam() | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Create stateful metrics that can be used to accumulate values during training and logged at any point: | # Define our metrics
train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32)
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy('train_accuracy')
test_loss = tf.keras.metrics.Mean('test_loss', dtype=tf.float32)
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy('test_accuracy') | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Define the training and test functions: | def train_step(model, optimizer, x_train, y_train):
with tf.GradientTape() as tape:
predictions = model(x_train, training=True)
loss = loss_object(y_train, predictions)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_loss(los... | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Set up summary writers to write the summaries to disk in a different logs directory: | current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
train_log_dir = 'logs/gradient_tape/' + current_time + '/train'
test_log_dir = 'logs/gradient_tape/' + current_time + '/test'
train_summary_writer = tf.summary.create_file_writer(train_log_dir)
test_summary_writer = tf.summary.create_file_writer(test_log_... | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Start training. Use `tf.summary.scalar()` to log metrics (loss and accuracy) during training/testing within the scope of the summary writers to write the summaries to disk. You have control over which metrics to log and how often to do it. Other `tf.summary` functions enable logging other types of data. | model = create_model() # reset our model
EPOCHS = 5
for epoch in range(EPOCHS):
for (x_train, y_train) in train_dataset:
train_step(model, optimizer, x_train, y_train)
with train_summary_writer.as_default():
tf.summary.scalar('loss', train_loss.result(), step=epoch)
tf.summary.scalar('accuracy', train... | Epoch 1, Loss: 0.24321186542510986, Accuracy: 92.84333801269531, Test Loss: 0.13006582856178284, Test Accuracy: 95.9000015258789
Epoch 2, Loss: 0.10446818172931671, Accuracy: 96.84833526611328, Test Loss: 0.08867532759904861, Test Accuracy: 97.1199951171875
Epoch 3, Loss: 0.07096975296735764, Accuracy: 97.8016662597656... | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Open TensorBoard again, this time pointing it at the new log directory. We could have also started TensorBoard to monitor training while it progresses. | %tensorboard --logdir logs/gradient_tape | _____no_output_____ | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
That's it! You have now seen how to use TensorBoard both through the Keras callback and through `tf.summary` for more custom scenarios. TensorBoard.dev: Host and share your ML experiment results[TensorBoard.dev](https://tensorboard.dev) is a free public service that enables you to upload your TensorBoard logs and ge... | !tensorboard dev upload \
--logdir logs/fit \
--name "(optional) My latest experiment" \
--description "(optional) Simple comparison of several hyperparameters" \
--one_shot | 2020-12-17 00:52:27.342972: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
***** TensorBoard Uploader *****
This will upload your TensorBoard logs to https://tensorboard.dev/ from
the following directory:
logs/fit
This TensorBoard will be visibl... | Apache-2.0 | Copy_of_get_started.ipynb | dlminvestments/cloudml-template |
Commonly Available Datasets MNIST DatasetDataset of 70,000 Handwritten Digits (28X28 Images)Original Dataset : http://yann.lecun.com/exdb/mnist/ | from sklearn.datasets import load_digits
import matplotlib.pyplot as plt
mnist = load_digits()
X = mnist.data
Y = mnist.target
print(X.shape)
print(Y.shape)
example = X[42]
print(Y[42])
img = example.reshape((8,8))
print(img)
plt.imshow(img,cmap="gray")
plt.show() | _____no_output_____ | MIT | ml_repo/2. Working with Libraries/Some Common Datasets (Updated).ipynb | sachinpr0001/data_science |
Boston DatasetHousing Prices Dataset | from sklearn.datasets import load_boston
boston = load_boston()
X = boston.data
Y = boston.target
print(X.shape)
print(Y.shape) | (506,)
| MIT | ml_repo/2. Working with Libraries/Some Common Datasets (Updated).ipynb | sachinpr0001/data_science |
Loading & Visualising MNIST Dataset using Pandas & Matplotlib | import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("../Datasets/MNIST-2/mnist_train.csv")
df.shape
df.head(n=3)
print(type(df))
data = df.values
np.random.shuffle(data)
print(type(data))
print(data.shape)
X = data[ : ,1: ]
Y = data[ : ,0]
print(X.shape,Y.shape)
## Try to visualise one image
def drawI... | (33600, 784) (33600,)
(8400, 784) (8400,)
| MIT | ml_repo/2. Working with Libraries/Some Common Datasets (Updated).ipynb | sachinpr0001/data_science |
Python fundamentalsA quick introduction to the [Python programming language](https://www.python.org/) and [Jupyter notebooks](https://jupyter.org/). ([We're using Python 3, not Python 2](https://pythonclock.org/).) Basic data types and the print() function | # variable assignment
# https://www.digitalocean.com/community/tutorials/how-to-use-variables-in-python-3
# strings -- enclose in single or double quotes, just make sure they match
my_name = 'Cody'
# numbers
int_num = 6
float_num = 6.4
# the print function
print(8)
print('Hello!')
print(my_name)
print(int_num)
print... | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
Basic mathYou can do [basic math](https://www.digitalocean.com/community/tutorials/how-to-do-math-in-python-3-with-operators) with Python. (You can also do [more advanced math](https://docs.python.org/3/library/math.html).) | # addition
add_eq = 4 + 2
# subtraction
sub_eq = 4 - 2
# multiplication
mult_eq = 4 * 2
# division
div_eq = 4 / 2
# etc. | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
ListsA comma-separated collection of items between square brackets: `[]`. Python keeps track of the order of things inside a list. | # create a list: name, hometown, age
# an item's position in the list is the key thing
cody = ['Cody', 'Midvale, WY', 32]
# create another list of mixed data
my_list = [1, 2, 3, 'hello', True, ['a', 'b', 'c']]
# use len() to get the number of items in the list
my_list_count = len(my_list)
print('There are', my_list_... | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
DictionariesA data structure that maps _keys_ to _values_ inside curly brackets: `{}`. Items in the dictionary are separated by commas. Python does not keep track of the order of items in a dictionary; if you need to keep track of insertion order, use an [OrderedDict](https://docs.python.org/3/library/collections.html... | my_dict = {'name': 'Cody', 'title': 'Training director', 'organization': 'IRE'}
# Access items in a dictionary using square brackets and the key (typically a string)
my_name = my_dict['name']
print(my_name)
# You can also use the `get()` method to retrieve values
# you can optionally provide a second argument as the ... | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
Commenting your codePython skips lines that begin with a hashtag -- these lines are used to write comments to help explain the code to others (and to your future self).Multi-line comments are enclosed between triple quotes: """ """ | # this is a one-line comment
"""
This is a
multi-line comment
~~~
""" | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
Comparison operatorsWhen you want to [compare values](https://docs.python.org/3/reference/expressions.htmlvalue-comparisons), you can use these symbols:- `<` means less than- `>` means greater than- `==` means equal- `>=` means greater than or equal- `<=` means less than or equal- `!=` means not equal | 4 > 6
'Hello!' == 'Hello!'
(2 + 2) != (4 * 2)
100.2 >= 100 | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
String functionsPython has a number of built-in methods to work with strings. They're useful if, say, you're using Python to clean data. Here are a few of them: _strip()_Call `strip()` on a string to remove whitespace from either side. It's like using the `=TRIM()` function in Excel. | whitespace_str = ' hello! '
print(whitespace_str.strip()) | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
_upper()_ and _lower()_Call `.upper()` on a string to make the characters uppercase. Call `.lower()` on a string to make the characters lowercase. This can be useful when testing strings for equality. | my_name = 'Cody'
my_name_upper = my_name.upper()
print(my_name_upper)
my_name_lower = my_name.lower()
print(my_name_lower) | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
_replace()_Use `.replace()` to substitute bits of text. | company = 'Bausch & Lomb'
company_no_ampersand = company.replace('&', 'and')
print(company_no_ampersand) | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
_split()_Use `.split()` to split a string on some delimiter. If you don't specify a delimiter, it uses a single space as the default. | date = '6/4/2011'
date_split = date.split('/')
print(date_split) | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
_zfill()_Among other things, you can use `.zfill()` to add zero padding -- for instance, if you're working with ZIP code data that was saved as a number somewhere and you've lost the leading zeroes for that handful of ZIP codes that begin with 0._Note: `.zfill()` is a string method, so if you want to apply it to a num... | mangled_zip = '2301'
fixed_zip = mangled_zip.zfill(5)
print(fixed_zip)
num_zip = 2301
fixed_num_zip = str(num_zip).zfill(5)
print(fixed_num_zip) | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
_slicing_Like lists, strings are _iterables_, so you can use slicing to grab chunks. | my_string = 'supercalifragilisticexpialidocious'
chunk = my_string[9:20]
print(chunk) | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
_startswith()_, _endswith()_ and _in_If you need to test whether a string starts with a series of characters, use `.startswith()`. If you need to test whether a string ends with a series of characters, use `.endswith()`. If you need to test whether a string is part of another string -- or a list of strings -- use `.in... | str_to_test = 'hello'
print(str_to_test.startswith('hel'))
print(str_to_test.endswith('lo'))
print('el' in str_to_test)
print(str_to_test in ['hi', 'whatsup', 'salutations', 'hello']) | _____no_output_____ | MIT | completed/00. Python Fundamentals (Part 1).ipynb | cjwinchester/cfj-2017 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.