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
Variable Type & ConversionEvery variable has a type (int, float, string, list, etc) and some of them can be converted into certain types
#Finding out the type of a variable type(my_float) #printing the types of some other variables print(type(my_num), type(simple_dict), type(truth), type(mixed_list)) #Converting anything to string str(my_float) str(simple_dict) str(mixed_list) #converting string to number three = "3" int(three) float(three) #Converting ...
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Lists A versatile datatype that can be thought of as a collection of comma-seperated values. Each item in a list has an index. The indices start with 0. The items in a list doesn't need to be of the same type
#Defining some lists l1 = [1,2,3,4,5,6] l2 = ["a", "b", "c", "d"] l3 = list(range(2,50,2)) #Creates a list going from 2 up to and not including 50 in increments of 2 print(l3) #displaying l3 #Length of a list #The len command gives the size of the list i.e. the total number of items len(l1) len(l2)
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Accessing list items** List items can be accessed using their index. The first item has an index of 0, the next one has 1 and so on
#First item of l2 is "a" and third item of l1 is 3 print("First item of l2: {}".format(l2[0])) # l2[0] accesses the item at 0th index of l2 print("Third item of l1: {}".format(l1[2])) # l1[0] accesses the item at 2nd index of l1
First item of l2: a Third item of l1: 3
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Indexing in reverse** List items can be accessed in reversed order using negative indices. The last item canbe accessed with -1, second from last with -2 and so on
print("Last item of l3: {}".format(l3[-1])) print("Third to last item of l1: {}".format(l1[-3]))
Last item of l3: 48 Third to last item of l1: 4
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Slicing** Portions of a list can be chosen using some or all of 3 numbers - starting index, stopping index and increment The syntax is `list_name[start:stop:increment]`
#If I want 2,3,4 from list l1, I want to start from index 1 and end at index 3 #The stopping indes is not included so we choose 3+1=4 as stopping index l1[1:4] #In this example we chose items from idex 1 up to index 5, skipping an item every time (increment of 2) l1[1:6:2] #If we just indicate starting index, everythin...
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
List operations
#"adding" two lists results in concatenation l4 = l1 + l2 l4 #Multiplying a list by a scalar results in repetition ["hello"]*5 l2*3 [2]*7
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Some other popular list manipulation functions
#Appending to the end of an existing string l2.append("e") l2 #Insert an item at a particular index - list_name(index, value) l2.insert(2,"f") l2 #sorting a list l2.sort() l2 #removes item by index and returns the removed item l4.pop(3) #remove the item at index 3 l4 #remove item by matching value l4.remove("a") l4 #ma...
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
String Manipulation Strings are values enclosed in single quotes (' ') or double quotes (" ") These are characters or a series of characters and can be manipulated in very similar way to lists, though they have their own special functions
#Defining some strings str1 = "I hear Rafia is a harsh grader" str2 = "NO NEED TO SHOUT" str3 = "fine, no caps lock"
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Accessing & Slicing**
#Very similar to lists print(str1[:12]) #Takes the 1st 10 characters print(str1[0]) #Accesses the first character print(str2[-5:]) #Takes last 5 characters print(str3[6:13]) #Takes 6 through 9
I hear Rafia I SHOUT no caps
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Other popular string manipulation functions**
#Splitting a string based on a sperator - str_name.split(separator) print(str1.split(" ")) #separating based on space print(str2.split()) #If no argument is given to split, default separator is space print(str3.split(",")) #separating based on space #Changing case print(str2.lower()) #All lower case print(str3.upper())...
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Special Characters**
#\n makes a new line print("This is making \n a new line") #\t inserts a tab print("This just inserts \t a tab")
This is making a new line This just inserts a tab
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
If Statement Executing blockes of code based on whether or not a given condition is true The syntax is -```pythonif (condition): Do somthingelif (condition): Do some other thingelse: Do somet other thing``` Only one block will execute - the condition that returns true first You can use as many elif blocks...
if ("c" in l2): print("Yes c is in l2") l2.remove("c") print("But now it's removed. Here's the new list") print(l2) a = 5 #defining a variable if (a>10): print("a is greater than 10") else: print("a is less than 10") if (a>5): print("a is greater than 5") elif (a<5): print("a is less tha...
b = yes, c = 0
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
LoopsLoops are an essential tool in python that allows you to repeatedly excute a block of code given certain conditions or based on interating over a given list or array. There's two main types of loops in python - `For` and `While`. There's also `Do..While` loop in python by combinging the Do command and While comma...
#Looping a certain number of time for i in range(10): #iterating over a list going from 0 to 9 a = i*5 print("Multiply {} by 5 gives {}".format(i, a)) #Looping over a list for item in l4: str_item = str(item) print("{} - {}".format(str_item, type(str_item)))
1 - <class 'str'> 2 - <class 'str'> 3 - <class 'str'> 5 - <class 'str'> 6 - <class 'str'> b - <class 'str'> c - <class 'str'> d - <class 'str'>
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Loop Control Statements** You can control the execution of a loop using 3 statements - - `break` : This breaks out of a loop and moves on to the next segment of your code- `continue` : This skips any code below it (inside the loop) and moves on to the next iteration- `pass` : It's used when a statement is required s...
#l4 is a list that contains both integers and numbers l4
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
So if you try to add numbers to the string elements, you'll get an error. To avoid it when iterating over this list, you can insert a break statement in your loop so that your code breaks out of the loop when it encounters a string.
for i in l4: if type(i)==str: print("Encountered a string, breaking out of the loop") break tmp = i+10 print("Added 10 to list item {} to get {}".format(i, tmp))
Added 10 to list item 1 to get 11 Added 10 to list item 2 to get 12 Added 10 to list item 3 to get 13 Added 10 to list item 5 to get 15 Added 10 to list item 6 to get 16 Encountered a string, breaking out of the loop
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Demonstrating `continue` But now, with the `break` statement, it breaks out of the loop any time it encounters string element. If the next element after a string element is an integer, we're missing out on it. That is where the continue statment comes in. If you use `continue` instead of `break` then, instead of bre...
for i in l4: if type(i)==str: print("Encountered a string, moving on to the next element") continue tmp = i+10 print("Added 10 to list item {} to get {}".format(i, tmp))
Added 10 to list item 1 to get 11 Added 10 to list item 2 to get 12 Added 10 to list item 3 to get 13 Added 10 to list item 5 to get 15 Added 10 to list item 6 to get 16 Encountered a string, moving on to the next element Encountered a string, moving on to the next element Encountered a string, moving on to the next el...
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Demonstrating `pass` `pass` is more of a placeholder. If you start a loop, you are bound by syntax to write at least one statement inside it. If you don't want to write anything yet, you can use a `pass` statement to avoid getting an error
for i in l4: pass
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Popular functions related to loops** There's a lot of usefull functions in python that work well with loops e.g. (range, unpack(*), tuple, split etc.) But there are two very important ones that go hand-in-hand with loops - `zip` & `enumerate` - so these are the ones I'm discussing here.- `zip` : Used when you want to...
print(len(l1), len(l3)) for a, b in zip(l1, l3): print("list 1 item is {}, corresponding list 3 item is {}".format(a,b)) for i, (a,b) in enumerate(zip(l1,l3)): print("At index {}, list 1 item is {}, corresponding list 3 item is {}".format(i, a, b))
At index 0, list 1 item is 1, corresponding list 3 item is 2 At index 1, list 1 item is 2, corresponding list 3 item is 4 At index 2, list 1 item is 3, corresponding list 3 item is 6 At index 3, list 1 item is 4, corresponding list 3 item is 8 At index 4, list 1 item is 5, corresponding list 3 item is 10 At index 5, li...
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
While Loop While loops are usefull when you want to iterate a code block **until** a certain condition is satified. While loops often need a counter variable that increments as the loop goes on.```pythonwhile (condition): do something```
counter = 10 while counter>0: print("The counter is still positive and right now, it's {}".format(counter)) counter-= 1 #incrementing the counter, reducing it by 1 in every iteration
The counter is still positive and right now, it's 10 The counter is still positive and right now, it's 9 The counter is still positive and right now, it's 8 The counter is still positive and right now, it's 7 The counter is still positive and right now, it's 6 The counter is still positive and right now, it's 5 The cou...
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
`pass`, `break` and `continue` statements all work well with `while` loop. `zip` and `enumerate` doesn't usually pair with while since it doesn't iterate over list type objects Function In python, apart from using the built-in functions, you can define your own customized functions using the following syntax -```pyth...
#Defining the function def arithmatic_operations(num1, num2): """ A function to perform a series of arithmatic operations on num1 and num2 Returns the final result as an integer rounded up/down """ add = num1 + num2 mltply = add*num2 sbtrct = mltply - num2 divide = sbtrct/num2 result...
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**Setting default values** You can use default argument in you parameter list to set default values or optional arguments Default arguments are optional parameters for a function i.e. you can call the function without these parameters ```pythondef new_func(arg1, arg2, arg3=5): result = arg1 + arg2 + arg3 return...
#Defining the function def new_arith(num1, num2, convert=False): """ A new function function that can handle even string arguments """ if convert!=False: num1 = float(num1) num2 = float(num2) add = num1 + num2 mltply = add*num2 sbtrct = mltply - num2 divide = sb...
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Scope The variables in a program are not accessible by every part of the program. Based on accessibility, there are two types of variables - global variable and local variable. Global variables are variables that can be accessed by any part of the program. Example from this notebook would be `str1`, `str2`, `truth...
result mltply
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Miscellaneous Dictionary Dictionaries are another iterable data type that comes in comma separated, key-value pairs.
#Definging some dictionaries dict1 = {} #One way to define an empty dictionary dict2 = dict() #One way to define an empty dictionary or convert another data type into a dictionary ou_mascots = {"Name": "Boomer", "Species": "Horse", "Partner": "Sooner", "Represents": "Oklahoma Sooners"} dict3 = {1:"uno", 2:34, "three...
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Accessing elements
ou_mascots["Name"] ou_mascots.get("Partner")
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Updating Dictionary
#Adding new element dict1["new_element"] = 5113 dict1 #Deleting del dict3[1] #removes the entry with key 1 dict1.clear() #removes all entries del dict2 #deletes entire dictionary dict3 dict1 dict2
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Useful Dictionary Functions
ou_mascots.keys() #Returns keys ou_mascots.items() #Returns key-value pairs as tuples ou_mascots.values() #Returns values ou_mascots.pop("Species") #removes given key and returns value len(dict1)
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Tuples Tuples are another iterable and sequence data type. Almost everything disccussed in the list section can be applied to tuples and they work in the same way - operations, functions etc.
#Defining some tuples tup1 = (20,) #If your tuple has only one element, you still have to use a comma tup2 = (1,3,4,6,7) tup3 = ("a", "b", "c") tup4 = (5,6,7) #The key difference with lists, you can't change tuple items tup2[3] = 4 #You can use tuples to define deictionaries dict(zip(tup3, tup4))
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
List Comprehension List comprehension is a quick way to create a new list from an existing list (or any other iterable like tuples or dictionaries). The syntax is as follows -```pythonnew_list = [(x+5) for x in existing_list]```The above one line code is the same as writing the following lengthy code block:```pythonn...
print(l3) #We need a new list of numbers that are an even multiple of 5 #We already have a list of even numbers up to 48 - l3 #time to create the new list l5 = [2*i for i in l3] print(l5)
[4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96]
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Error Handling Sometimes we might have a code block, especially in a loop or a function that might not work for all kind of values. In that case, error hadnling is something to consider in order to avoid error and continue on with the rest of the program. Errors can be handled in many ways depending on your needs bu...
#inserting another string in l4 l4.insert(2, "a") l4 #let's try running the arithmatic_operations functions on the elements of l4 for item in l4: try: res = ariethmatic_operations(item,5) print("list item {}, result {}".format(item, res)) except: print("Could not perform arithmatic opera...
list item 1, result 5 list item 2, result 6 Could not perform arithmatic operations for list item a list item 3, result 7 list item 5, result 9 list item 6, result 10 Could not perform arithmatic operations for list item b Could not perform arithmatic operations for list item c Could not perform arithmatic operations f...
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Lambda Expression A quick way to define short anonymous functions - one liner functions. Handy when you keep repeating an expression and it's too small to define a formal function. ```pythonDefiningx = lambda arg : expressioncallingx(value)```This is equivalent to -```pythonDefiningdef x(arg): result = expressio...
#small function with 1 argument x = lambda a : a + 10 x(5) #small function with multiple arguments x = lambda a,b,c : ((a + 10)*b)/c x(5,10,2)
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Mapping Function `map` function is quick way to apply a function to many values using an iterable (lists, tuples etc). The function to apply can be a built in function, user defined function or even a lambda expression. In fact, mapping and lambda expression work really well together. The syntax is as follows : ```p...
dict3 result = map(type, dict3.values()) list(result)
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**applying the user-defined `arithmetic_operations` function to two lists**
print(l1, l3) result = map(ariethmatic_operations, l1, l3) #mapped up to the shorter of the two lists list(result)
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
**combining lambda expression and mapping function**
numbers1 = [1, 2, 3] numbers2 = [4, 5, 6] result = map(lambda x, y: x + y, numbers1, numbers2) list(result)
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
User Input Sometimes, it is necessary to take user input and you can do that in python using the `input` command. The `input` command returns the user input as a string so, always remember to convert the input to the data type you need. ```pythoninput("Your customized prompt goes here")```
inp = input("please input two integers seperated by comma") inp #let's apply the arithmetic_operation function to this user input a,b = inp.split(",") a ariethmatic_operations(int(a), int(b)) #Need to convert to integers since this one doesn't handle strings new_arith(a,b, convert=True)
_____no_output_____
MIT
.ipynb_checkpoints/Python Crash Course-checkpoint.ipynb
rafia37/DSA5113-TA-class-repo
Run all corpora
As.testSet() As.test(basic)
_____no_output_____
MIT
zz_test/100-slots.ipynb
sethbam9/tutorials
Run specific corpora
As.testSet("uruk") As.test(basic, refresh=True)
_____no_output_____
MIT
zz_test/100-slots.ipynb
sethbam9/tutorials
webgrabber für Listen von Wikipedia
# Gebäckliste import requests from bs4 import BeautifulSoup # man muss der liste einen letzten eintrag geben, weil sonst weitere listen unter der eigentlichen ausgelesen werden. def grab_list(url, last_item): # wenn wikipedia eine Tabelle anzeigt grabbed_list = [] r = requests.get(url) text = r.text so...
['Baik kut kyee kaik', 'Balchão', 'Bánh canh', 'Bisque (food)', 'Bún mắm', 'Bún riêu', 'Chowder', 'Cioppino', 'Crawfish pie', 'Curanto', 'Fideuà', 'Halabos', 'Hoe (dish)', 'Hoedeopbap', 'Kaeng som', 'Kedgeree', 'Maeuntang', 'Moules-frites', 'Namasu', 'New England clam bake', 'Paella', 'Paelya', 'Paila marina', 'Piapara...
MIT
webgrabber_wikilisten.ipynb
TechLabs-Dortmund/nutritional-value-determination
My first notebook
print ('my first notebook') 1 + 2 int(1 + 2) a = 3 print(a)
3
MIT
Labs/Lab1.ipynb
peralegh/480
Read Data from a file
import xlrd book = xlrd.open_workbook("Diamonds.xls") sheet = book.sheet_by_name("Diamonds") for row_index in range(1,5): # read the first 4 rows, skip the first row id_, weight, color,_,_,price = sheet.row_values(row_index) print(id_,weight,color,price)
1.0 0.3 D 1302.0 2.0 0.3 E 1510.0 3.0 0.3 G 1510.0 4.0 0.3 G 1260.0
MIT
Labs/Lab1.ipynb
peralegh/480
Question 1Given the following jumbled word, OBANWRI guess the correct English word.A. RANIBOWB. RAINBOWC. BOWRANID. ROBWANI
import random def shuffling(given): given = str(given) words = ['RAINBOW','RANIBOW','BOWRANI','ROBWANI'] shuffled = ''.join(random.sample(given,len(given))) if shuffled=='RAINBOW': return shuffled print("The correct option is: RAINBOW") else: #shuffling(given) print(...
BOIAWNR is incorrect The correct option is: RAINBOW
Apache-2.0
Day-1/Day1_assignment.ipynb
anjumrohra/LetsUpgrade_DataScience_Essentials
Question 2Write a program which prints “LETS UPGRADE”. (Please note that you have toprint in ALL CAPS as given)
string = "Lets upgrade" print(string.upper())
LETS UPGRADE
Apache-2.0
Day-1/Day1_assignment.ipynb
anjumrohra/LetsUpgrade_DataScience_Essentials
Question 3Write a program that takes Cost Price and Selling Price as input and displays whether the transaction is aProfit or a Loss or neither.INPUT FORMAT:1. The first line contains the cost price.2. The second line contains the selling price.OUTPUT FORMAT:1. Print "Profit" if the transaction is a profit or "Loss" i...
CP = float(input()) SP = float(input()) if CP<SP: print("Profit") elif CP>SP: print("Loss") else: print("Neither")
20 20 Neither
Apache-2.0
Day-1/Day1_assignment.ipynb
anjumrohra/LetsUpgrade_DataScience_Essentials
Question 4Write a program that takes an amount in Euros as input. You need to find its equivalent inRupees and display it. Assume 1 Euro equals Rs. 80.Please note that you are expected to stick to the given input and outputformat as in sample test cases. Please don't add any extra lines such as'Enter a number', etc.Yo...
Euro = float(input()) Rupees = Euro * 80 print(Rupees)
20 1600.0
Apache-2.0
Day-1/Day1_assignment.ipynb
anjumrohra/LetsUpgrade_DataScience_Essentials
IntroductionNow that I have removed the RNA/DNA node and we have fixed many pathways, I will re-visit the things that were raised in issue 37: 'Reaction reversibility'. There were reactions that we couldn't reverse or remove or they would kill the biomass. I will try to see if these problems have been resolved now. If...
import cameo import pandas as pd import cobra.io import escher from escher import Builder from cobra import Reaction model = cobra.io.read_sbml_model('../model/p-thermo.xml') model_e_coli = cameo.load_model('iML1515') model_b_sub = cameo.load_model('iYO844')
_____no_output_____
Apache-2.0
notebooks/28. Resolve issue 37-Reaction reversibility.ipynb
biosustain/p-thermo
__ALDD2x__should be irreversible, but doing so kills the biomass growth completely at this moment. It needs to be changed as we right now have an erroneous energy generating cycle going from aad_c --> ac_c (+atp) --> acald --> accoa_c -->aad_c.Apparently, unconciously i already fixed this problem in notebook 20. So thi...
model.reactions.NADK.bounds = (0,1000) model.reactions.ALAD_L.bounds = (-1000,0) model.optimize().objective_value cofactors = ['nad_c', 'nadh_c','', '', '', ''] with model: # model.add_boundary(model.metabolites.glc__D_c, type = 'sink', reaction_id = 'test') # model.add_boundary(model.metabolites.r5p_c , type ...
1.8496633304871162
Apache-2.0
notebooks/28. Resolve issue 37-Reaction reversibility.ipynb
biosustain/p-thermo
It seems that the NAD and NADH are the blocked metabolites for biomass generation. Now lets try to figure out where this problem lies. I think the problem lies in re-generating NAD. The model uses this reaction togehter with oth strange reactions to regenerate NAD, where normally in oxygen containing conditions I would...
model.add_reaction(Reaction(id='FADRx')) model.reactions.FADRx.name = 'Flavin reductase' model.reactions.FADRx.annotation = model_e_coli.reactions.FADRx.annotation model.reactions.FADRx.add_metabolites({ model.metabolites.fad_c:-1, model.metabolites.h_c: -1, model.metabolites.nadh_c:-1, model.metaboli...
_____no_output_____
Apache-2.0
notebooks/28. Resolve issue 37-Reaction reversibility.ipynb
biosustain/p-thermo
In looking at the above, I also observed some other reactions that probably should not looked at and modified.
model.reactions.MALQOR.id = 'MDH2' model.reactions.MDH2.bounds = (0,1000) model.metabolites.hexcoa_c.id = 'hxcoa_c' model.reactions.HEXOT.id = 'ACOAD2f' model.metabolites.dccoa_c.id = 'dcacoa_c' model.reactions.DECOT.id = 'ACOAD4f' #in the wrong direction and id model.reactions.GLYCDH_1.id = 'HPYRRx' model.reactions.HP...
_____no_output_____
Apache-2.0
notebooks/28. Resolve issue 37-Reaction reversibility.ipynb
biosustain/p-thermo
Even with the changes above we still do not restore growth... Supplying nmn_c restores growth, but supplying aspartate (beginning of the pathway) doesn't sovle the problem. so maybe the problem lies more with the NAD biosynthesis pathway than really the regeneration anymore?
model.metabolites.nicrnt_c.name = 'Nicotinate ribonucleotide' model.metabolites.ncam_c.name = 'Niacinamide' #wrong direction model.reactions.QULNS.bounds = (-1000,0) #this rescued biomass accumulation! #connected to aspartate model.optimize().objective_value #save&commit cobra.io.write_sbml_model(model,'../model/p-the...
_____no_output_____
Apache-2.0
notebooks/28. Resolve issue 37-Reaction reversibility.ipynb
biosustain/p-thermo
Flux is carried through the Still it is strange that flux is not carried through the ETC, but is through the ATP synthase as one would expect in the presence of oxygen. Therefore I will investigate where the extracellular protons come from. It seems all the extracellular protons come from the export of phosphate (pi_c)...
model.optimize()['ATPS4r'] model.metabolites.pi_c.summary()
_____no_output_____
Apache-2.0
notebooks/28. Resolve issue 37-Reaction reversibility.ipynb
biosustain/p-thermo
I also noticed that now most ATP comes from dGTP. The production of dGDP should just play a role in supplying nucleotides for biomass and so the flux it carries be low. I will check where the majority of the dGTP comes from.What is happening is the following: dgtp is converted dgdp and atp (rct ATDGDm). The dgdp then r...
#reaction to be removed model.remove_reactions(model.reactions.PYRPT)
C:\Users\vivmol\AppData\Local\Continuum\anaconda3\envs\g-thermo\lib\site-packages\cobra\core\model.py:716: UserWarning: need to pass in a list C:\Users\vivmol\AppData\Local\Continuum\anaconda3\envs\g-thermo\lib\site-packages\cobra\core\group.py:110: UserWarning: need to pass in a list
Apache-2.0
notebooks/28. Resolve issue 37-Reaction reversibility.ipynb
biosustain/p-thermo
Removing these reactions triggers normal ATP production via ETC and ATP synthase again. So this may be solved now.
model.metabolites.pi_c.summary() #save & commit cobra.io.write_sbml_model(model,'../model/p-thermo.xml')
_____no_output_____
Apache-2.0
notebooks/28. Resolve issue 37-Reaction reversibility.ipynb
biosustain/p-thermo
Градиентный бустинг своими руками**Внимание:** в тексте задания произошли изменения - поменялось число деревьев (теперь 50), правило изменения величины шага в задании 3 и добавился параметр `random_state` у решающего дерева. Правильные ответы не поменялись, но теперь их проще получить. Также исправлена опечатка в функ...
from sklearn import datasets, model_selection from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_squared_error import numpy as np boston = datasets.load_boston() X_train, X_test = boston.data[: 380, :], boston.data[381 :, :] y_train, y_test = boston.target[: 380], boston.target[381 :]
_____no_output_____
MIT
LearningOnMarkedData/week4/c02_w04_ex02.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
Задание 1Как вы уже знаете из лекций, **бустинг** - это метод построения композиций базовых алгоритмов с помощью последовательного добавления к текущей композиции нового алгоритма с некоторым коэффициентом. Градиентный бустинг обучает каждый новый алгоритм так, чтобы он приближал антиградиент ошибки по ответам компози...
def accent_l(z, y): '''result = list() for i in range(0, len(y)): result.append(-(y[i] - z[i])) ''' return -1.0*(z - y)
_____no_output_____
MIT
LearningOnMarkedData/week4/c02_w04_ex02.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
Задание 2Заведите массив для объектов `DecisionTreeRegressor` (будем их использовать в качестве базовых алгоритмов) и для вещественных чисел (это будут коэффициенты перед базовыми алгоритмами). В цикле от обучите последовательно 50 решающих деревьев с параметрами `max_depth=5` и `random_state=42` (остальные параметры ...
base_algorithms_list = list() coefficients_list = list() algorithm = DecisionTreeRegressor(max_depth=5, random_state=42) def gbm_predict(X): return [sum([coeff * algo.predict([x])[0] for algo, coeff in zip(base_algorithms_list, coefficients_list)]) for x in X] base_algorithms_list = list() coefficients_list = list...
5.448710743655589
MIT
LearningOnMarkedData/week4/c02_w04_ex02.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
Задание 3Вас может также беспокоить, что двигаясь с постоянным шагом, вблизи минимума ошибки ответы на обучающей выборке меняются слишком резко, перескакивая через минимум. Попробуйте уменьшать вес перед каждым алгоритмом с каждой следующей итерацией по формуле `0.9 / (1.0 + i)`, где `i` - номер итерации (от 0 до 49)....
base_algorithms_list = list() coefficients_list = list() b_0 = algorithm.fit(X_train, y_train) base_algorithms_list.append(b_0) coefficients_list.append(0.9) for i in range(1, 50): algorithm_i = DecisionTreeRegressor(max_depth=5, random_state=42) s_i = accent_l(gbm_predict(X_train), y_train) b_i = algorithm...
5.241288806316885
MIT
LearningOnMarkedData/week4/c02_w04_ex02.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
Задание 4Реализованный вами метод - градиентный бустинг над деревьями - очень популярен в машинном обучении. Он представлен как в самой библиотеке `sklearn`, так и в сторонней библиотеке `XGBoost`, которая имеет свой питоновский интерфейс. На практике `XGBoost` работает заметно лучше `GradientBoostingRegressor` из `sk...
from xgboost import XGBClassifier from sklearn.model_selection import cross_val_score from sklearn.ensemble import GradientBoostingRegressor %pylab inline n_trees = [1] + list(range(10, 105, 5)) X = boston.data y = boston.target estimator = GradientBoostingRegressor(learning_rate=0.1, max_depth=5, n_estimators=100) est...
_____no_output_____
MIT
LearningOnMarkedData/week4/c02_w04_ex02.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
Задание 5Сравните получаемое с помощью градиентного бустинга качество с качеством работы линейной регрессии. Для этого обучите `LinearRegression` из `sklearn.linear_model` (с параметрами по умолчанию) на обучающей выборке и оцените для прогнозов полученного алгоритма на тестовой выборке `RMSE`. Полученное качество - о...
from sklearn.linear_model import LinearRegression estimator = LinearRegression() estimator.fit(X_train, y_train) print(mean_squared_error(y_test, estimator.predict(X_test))**0.5)
7.87339775956158
MIT
LearningOnMarkedData/week4/c02_w04_ex02.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
HSV Color Space, Balloons Import resources and display image
import numpy as np import matplotlib.pyplot as plt import cv2 %matplotlib inline # Read in the image image = cv2.imread('images/water_balloons.jpg') # Change color to RGB (from BGR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image)
_____no_output_____
MIT
1_1_Image_Representation/5_1. HSV Color Space, Balloons.ipynb
m-emad/computer-vision-exercises
Plot color channels
# RGB channels r = image[:,:,0] g = image[:,:,1] b = image[:,:,2] f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,10)) ax1.set_title('Red') ax1.imshow(r, cmap='gray') ax2.set_title('Green') ax2.imshow(g, cmap='gray') ax3.set_title('Blue') ax3.imshow(b, cmap='gray') # Convert from RGB to HSV hsv = cv2.cvtColor(...
_____no_output_____
MIT
1_1_Image_Representation/5_1. HSV Color Space, Balloons.ipynb
m-emad/computer-vision-exercises
Define pink and hue selection thresholds
# Define our color selection criteria in HSV values lower_hue = np.array([150,0,0]) upper_hue = np.array([180,255,255]) # Define our color selection criteria in RGB values lower_pink = np.array([180,0,100]) upper_pink = np.array([255,255,230])
_____no_output_____
MIT
1_1_Image_Representation/5_1. HSV Color Space, Balloons.ipynb
m-emad/computer-vision-exercises
Mask the image
# Define the masked area in RGB space mask_rgb = cv2.inRange(image, lower_pink, upper_pink) # mask the image masked_image = np.copy(image) masked_image[mask_rgb==0] = [0,0,0] # Vizualize the mask plt.imshow(masked_image) # Now try HSV! # Define the masked area in HSV space mask_hsv = cv2.inRange(hsv, lower_hue, uppe...
_____no_output_____
MIT
1_1_Image_Representation/5_1. HSV Color Space, Balloons.ipynb
m-emad/computer-vision-exercises
Modeling and Simulation in PythonProject 1 exampleCopyright 2018 Allen DowneyLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)
# Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim library from modsim import * from pandas import read_html filename = ...
_____no_output_____
MIT
code/world_pop_transition_from_allendowney_github.ipynb
sdaitzman/ModSimPy
Trial 2: classification with learned graph filtersWe want to classify data by first extracting meaningful features from learned filters.
import time import numpy as np import scipy.sparse, scipy.sparse.linalg, scipy.spatial.distance from sklearn import datasets, linear_model import matplotlib.pyplot as plt %matplotlib inline import os import sys sys.path.append('..') from lib import graph
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Parameters Dataset* Two digits version of MNIST with N samples of each class.* Distinguishing 4 from 9 is the hardest.
def mnist(a, b, N): """Prepare data for binary classification of MNIST.""" folder = os.path.join('..', 'data') mnist = datasets.fetch_mldata('MNIST original', data_home=folder) assert N < min(sum(mnist.target==a), sum(mnist.target==b)) M = mnist.data.shape[1] X = np.empty((M, 2, N)) X[...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Regularized least-square Reference: sklearn ridge regression* With regularized data, the objective is the same with or without bias.
def test_sklearn(tauR): def L(w, b=0): return np.linalg.norm(X.T @ w + b - y)**2 + tauR * np.linalg.norm(w)**2 def dL(w): return 2 * X @ (X.T @ w - y) + 2 * tauR * w clf = linear_model.Ridge(alpha=tauR, fit_intercept=False) clf.fit(X.T, y) w = clf.coef_.T print('L = {}'.f...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Linear classifier
def test_optim(clf, X, y, ax=None): """Test optimization on full dataset.""" tstart = time.process_time() ret = clf.fit(X, y) print('Processing time: {}'.format(time.process_time()-tstart)) print('L = {}'.format(clf.L(*ret, y))) if hasattr(clf, 'dLc'): print('|dLc| = {}'.format(np.linalg...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Feature graph
t_start = time.process_time() z = graph.grid(int(np.sqrt(X.shape[0]))) dist, idx = graph.distance_sklearn_metrics(z, k=4) A = graph.adjacency(dist, idx) L = graph.laplacian(A, True) lmax = graph.lmax(L) print('Execution time: {:.2f}s'.format(time.process_time() - t_start))
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Lanczos basis
def lanczos(L, X, K): M, N = X.shape a = np.empty((K, N)) b = np.zeros((K, N)) V = np.empty((K, M, N)) V[0,...] = X / np.linalg.norm(X, axis=0) for k in range(K-1): W = L.dot(V[k,...]) a[k,:] = np.sum(W * V[k,...], axis=0) W = W - a[k,:] * V[k,...] - (b[k,:] * V[k-1,...] ...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Tests* Memory arrangement for fastest computations: largest dimensions on the outside, i.e. fastest varying indices.* The einsum seems to be efficient for three operands.
def test(): """Test the speed of filtering and weighting.""" def mult(impl=3): if impl is 0: Xb = Xt.view() Xb.shape = (K, M*N) XCb = Xb.T @ C # in MN x F XCb = XCb.T.reshape((F*M, N)) return (XCb.T @ w).squeeze() elif impl is 1: ...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
GFL classification without weights* The matrix is singular thus not invertible.
class gflc_noweights: def __init__(s, F, K, niter, algo='direct'): """Model hyper-parameters""" s.F = F s.K = K s.niter = niter if algo is 'direct': s.fit = s.direct elif algo is 'sgd': s.fit = s.sgd def L(s, Xt, y): #tmp = np...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
GFL classification with weights
class gflc_weights(): def __init__(s, F, K, tauR, niter, algo='direct'): """Model hyper-parameters""" s.F = F s.K = K s.tauR = tauR s.niter = niter if algo is 'direct': s.fit = s.direct elif algo is 'sgd': s.fit = s.sgd def L(s, X...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
GFL classification with splittingSolvers* Closed-form solution.* Stochastic gradient descent.
class gflc_split(): def __init__(s, F, K, tauR, tauF, niter, algo='direct'): """Model hyper-parameters""" s.F = F s.K = K s.tauR = tauR s.tauF = tauF s.niter = niter if algo is 'direct': s.fit = s.direct elif algo is 'sgd': s.f...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Filters visualizationObservations:* Filters learned with the splitting scheme have much smaller amplitudes.* Maybe the energy sometimes goes in W ?* Why are the filters so different ?
lamb, U = graph.fourier(L) print('Spectrum in [{:1.2e}, {:1.2e}]'.format(lamb[0], lamb[-1])) def plot_filters(C, spectrum=False): K, F = C.shape M, M = L.shape m = int(np.sqrt(M)) X = np.zeros((M,1)) X[int(m/2*(m+1))] = 1 # Kronecker Xt, q = lanczos_basis_eval(L, X, K) Z = np.einsum('kmn,kf...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Extracted features
def plot_features(C, x): K, F = C.shape m = int(np.sqrt(x.shape[0])) xt, q = lanczos_basis_eval(L, x, K) Z = np.einsum('kmn,kf->mnf', xt, C) fig, axes = plt.subplots(2,int(np.ceil(F/2)), figsize=(15,5)) for f in range(F): img = Z[:,0,f].reshape((m,m)) #im = axes.flat[f].imsh...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Performance w.r.t. hyper-parameters* F plays a big role. * Both for performance and training time. * Larger values lead to over-fitting !* Order $K \in [3,5]$ seems sufficient.* $\tau_R$ does not have much influence.
def scorer(clf, X, y): yest = clf.predict(X).round().squeeze() y = y.squeeze() yy = np.ones(len(y)) yy[yest < 0] = -1 nerrs = np.count_nonzero(y - yy) return 1 - nerrs / len(y) def perf(clf, nfolds=3): """Test training accuracy.""" N = X.shape[1] inds = np.arange(N) np.random.shu...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Classification* Greater is $F$, greater should $K$ be.
def cross_validation(clf, nfolds, nvalidations): M, N = X.shape scores = np.empty((nvalidations, nfolds)) for nval in range(nvalidations): inds = np.arange(N) np.random.shuffle(inds) inds.resize((nfolds, int(N/nfolds))) folds = np.arange(nfolds) for n in folds: ...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Sampled MNIST
Xfull = X def sample(X, p, seed=None): M, N = X.shape z = graph.grid(int(np.sqrt(M))) # Select random pixels. np.random.seed(seed) mask = np.arange(M) np.random.shuffle(mask) mask = mask[:int(p*M)] return z[mask,:], X[mask,:] X = Xfull z, X = sample(X, .5) dist, idx = graph.di...
_____no_output_____
MIT
trials/2_classification.ipynb
Gxqiang/cnn_graph
Housing Market Introduction:This time we will create our own dataset with fictional numbers to describe a house market. As we are going to create random data don't try to reason of the numbers. Step 1. Import the necessary libraries
import pandas as pd import numpy as np
_____no_output_____
BSD-3-Clause
05_Merge/Housing Market/Exercises.ipynb
LouisNodskov/pandas_exercises
Step 2. Create 3 differents Series, each of length 100, as follows: 1. The first a random number from 1 to 4 2. The second a random number from 1 to 33. The third a random number from 10,000 to 30,000
rand1 = pd.Series(np.random.randint(1, 5, 100)) rand2 = pd.Series(np.random.randint(1, 4, 100)) rand3 = pd.Series(np.random.randint(10000, 30001, 100)) print(rand1, rand2, rand3)
0 2 1 1 2 3 3 2 4 2 .. 95 3 96 4 97 3 98 2 99 2 Length: 100, dtype: int32 0 1 1 1 2 1 3 2 4 3 .. 95 2 96 1 97 3 98 3 99 2 Length: 100, dtype: int32 0 23816 1 22299 2 13516 3 25975 4 22916 ... 95 11050 96 16...
BSD-3-Clause
05_Merge/Housing Market/Exercises.ipynb
LouisNodskov/pandas_exercises
Step 3. Let's create a DataFrame by joinning the Series by column
df = pd.concat([rand1, rand2, rand3], axis = 1) df
_____no_output_____
BSD-3-Clause
05_Merge/Housing Market/Exercises.ipynb
LouisNodskov/pandas_exercises
Step 4. Change the name of the columns to bedrs, bathrs, price_sqr_meter
df.rename(columns = { 0: 'bedrs', 1: 'bathrs', 2: 'price_sqr_meter' }, inplace=True) df
_____no_output_____
BSD-3-Clause
05_Merge/Housing Market/Exercises.ipynb
LouisNodskov/pandas_exercises
Step 5. Create a one column DataFrame with the values of the 3 Series and assign it to 'bigcolumn'
bigcolumn = pd.DataFrame(pd.concat([rand1, rand2, rand3], axis = 0))
_____no_output_____
BSD-3-Clause
05_Merge/Housing Market/Exercises.ipynb
LouisNodskov/pandas_exercises
Step 6. Oops, it seems it is going only until index 99. Is it true?
len(bigcolumn)
_____no_output_____
BSD-3-Clause
05_Merge/Housing Market/Exercises.ipynb
LouisNodskov/pandas_exercises
Step 7. Reindex the DataFrame so it goes from 0 to 299
bigcolumn.reset_index(drop = True, inplace=True) bigcolumn
_____no_output_____
BSD-3-Clause
05_Merge/Housing Market/Exercises.ipynb
LouisNodskov/pandas_exercises
Import libraries
# generic tools import numpy as np import datetime # tools from sklearn from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import classification_report from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split # tools from tensorflow import tensorflow as tf fro...
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Download data, train-test split, binarize labels
data, labels = fetch_openml('mnist_784', version=1, return_X_y=True) # to data data = data.astype("float")/255.0 # split data (trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.2) # convert ...
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Define neural network architecture using ```tf.keras```
# define architecture 784x256x128x10 model = Sequential() model.add(Dense(256, input_shape=(784,), activation="sigmoid")) model.add(Dense(128, activation="sigmoid")) model.add(Dense(10, activation="softmax")) # generalisation of logistic regression for multiclass task
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Show summary of model architecture
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 256) 200960 ____________________________________...
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Visualise model layers
plot_model(model, show_shapes=True, show_layer_names=True)
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Compile model loss function, optimizer, and preferred metrics
# train model using SGD sgd = SGD(1e-2) model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Set ```tensorboard``` parameters - not compulsory!
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)
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Train model and save history
history = model.fit(trainX, trainY, validation_data=(testX,testY), epochs=100, batch_size=128, callbacks=[tensorboard_callback])
Epoch 1/100 438/438 [==============================] - 2s 4ms/step - loss: 2.3059 - accuracy: 0.1420 - val_loss: 2.2460 - val_accuracy: 0.3663 Epoch 2/100 438/438 [==============================] - 1s 3ms/step - loss: 2.2309 - accuracy: 0.3536 - val_loss: 2.1785 - val_accuracy: 0.4581 Epoch 3/100 438/438 [=============...
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Visualise using ```matplotlib```
plt.style.use("fivethirtyeight") plt.figure() plt.plot(np.arange(0, 100), history.history["loss"], label="train_loss") plt.plot(np.arange(0, 100), history.history["val_loss"], label="val_loss", linestyle=":") plt.plot(np.arange(0, 100), history.history["accuracy"], label="train_acc") plt.plot(np.arange(0, 100), history...
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Inspect using ```tensorboard```This won't run on JupyterHub!
%tensorboard --logdir logs/fit
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Classifier metrics
# evaluate network print("[INFO] evaluating network...") predictions = model.predict(testX, batch_size=128) print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=[str(x) for x in lb.classes_]))
_____no_output_____
MIT
notebooks/session8.ipynb
sofieditmer/cds-visual
Import Libraries
import sys !{sys.executable} -m pip install -r requirements.txt import numpy as np import matplotlib.pyplot as plt from analytics import SQLClient
_____no_output_____
MIT
analytics/analytics.ipynb
shawlu95/Grocery_Matter
Connect to MySQL database
username = "privateuser" password = "1234567" port = 7777 client = SQLClient(username, password, port) sql_tmp = """ SELECT id ,userID ,name ,type ,-priceCNY * count / 6.9 AS price ,count ,currency ,-priceCNY * count AS priceCNY ,time FR...
_____no_output_____
MIT
analytics/analytics.ipynb
shawlu95/Grocery_Matter
Analytics: Nov. 2018
start_dt = '2018-11-01' end_dt = '2018-12-01' df = client.query(sql_tmp.replace('$start_dt$', start_dt).replace("$end_dt$", end_dt)) df = df.groupby(['type']).sum() total = np.sum(df.price) df["pct"] = df.price / total df["category"] = client.categories df = df.sort_values("pct")[::-1] df labels = ["%s: $%.2f"%(df.cate...
_____no_output_____
MIT
analytics/analytics.ipynb
shawlu95/Grocery_Matter
Analytics: Year of 2018
start_dt = '2018-01-01' end_dt = '2018-12-01' df = client.query(sql_tmp.replace('$start_dt$', start_dt).replace("$end_dt$", end_dt)) df[df.type == 'COM'] df = df.groupby(['type']).sum() total = np.sum(df.price) df["pct"] = df.price / total df["category"] = client.categories df = df.sort_values("pct")[::-1] df labels = ...
_____no_output_____
MIT
analytics/analytics.ipynb
shawlu95/Grocery_Matter
Dependencies
import os import sys import cv2 import shutil import random import warnings import numpy as np import pandas as pd import seaborn as sns import multiprocessing as mp import matplotlib.pyplot as plt from tensorflow import set_random_seed from sklearn.utils import class_weight from sklearn.model_selection import train_te...
/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/conda/lib/python3.6/sit...
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection