markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Променливи
Променливата е име,с което се асоциира дадена стойност.
Валидни имена на променливи
Името на променлива може да съдържа главни и малки букви, цифри и символът _.
Името на променлива трябва да започва с буква или _.
За имена на променливи не може да се използват служебни думи от Python.
Препоръки за именува... | c = 10 # number of coins - прекалени късо
number_of_coins = 10 # прекалино детайлно име
coinsCount = 10 # ОК, но за Java
coins_count = 10 # OK
# Задаването на стойност на променлива се нарича `присвояване`
count = 1
# Когато Python срещне променлива в израз, той я заменя със стойността и
print(count + 1)
# Промен... | week2/Expressions, variables and errors.ipynb | YAtOff/python0-reloaded | mit |
Какво трябва да напишем, за да увеличим стойността на count с 1 (приемете, че не знаем каква е стойността на count)? | count = 1
count = count + 1
print(count) | week2/Expressions, variables and errors.ipynb | YAtOff/python0-reloaded | mit |
Грешки | my var = 1
price = 1
print(pirce) | week2/Expressions, variables and errors.ipynb | YAtOff/python0-reloaded | mit |
Names scores
Problem 22
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name... | from euler import timer, Seq
def score(s):
return s >> Seq.map(lambda x: ord(x) - 64) >> Seq.sum
def p022():
return (
open('data/p022.txt').read().split(',')
>> Seq.map(lambda x: x.strip('"'))
>> Seq.sort
>> Seq.mapi(lambda (i,x): score(x)*(i+1))
>> Seq.sum)
timer... | euler_021_030.ipynb | mndrake/PythonEuler | mit |
Non-abundant sums
Problem 23
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be $1 + 2 + 4 + 7 + 14 = 28$, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper diviso... | from euler import FactorInteger, Seq, timer
from operator import mul
def divisor_sum(n):
return (
FactorInteger(n)
>> Seq.map(lambda (p,a): (p**(a+1) - 1)/(p-1))
>> Seq.reduce(mul)
) - n
def p023():
max_n = 28123
abundants = range(12, max_n+1) >> Seq.filter(lambda n: n < ... | euler_021_030.ipynb | mndrake/PythonEuler | mit |
Lexicographic permutations
Problem 24
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 ... | from math import factorial
from euler import timer
def p024():
numbers = range(10)
def loop(remainder, acc):
k = len(numbers) - 1
if k==0:
return acc + str(numbers[0])
else:
next = numbers[remainder / factorial(k)]
numbers.remove(next)
re... | euler_021_030.ipynb | mndrake/PythonEuler | mit |
1000-digit Fibonacci number
Problem 25
The Fibonacci sequence is defined by the recurrence relation:
$F_n = F_{n−1} + F_{n−2}$, where $F_1 = 1$ and $F_2 = 1$.
Hence the first 12 terms will be:
$F_1 = 1$
$F_2 = 1$
$F_3 = 2$
$F_4 = 3$
$F_5 = 5$
$F_6 = 8$
$F_7 = 13$
$F_8 = 21$
$F_9 = 34$
$F_{10} = 55$
$F_{11} = 89$
$F_{12... | from math import log10
from euler import timer, Seq
def p025():
return (
Seq.unfold(lambda (a,b):(b, (b,a+b)), (0,1))
>> Seq.findIndex(lambda x: log10(x) > 999)
) + 1
timer(p025) | euler_021_030.ipynb | mndrake/PythonEuler | mit |
Reciprocal cycles
Problem 26
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..... | from euler import timer, Seq
def cycle(denom):
if denom==2 or denom==5:
return 0
elif denom%2==0:
return cycle(denom/2)
elif denom%5==0:
return cycle(denom/5)
else:
return (
Seq.initInfinite(lambda x: x+1)
>> Seq.map (lambda x: 10 ** x - 1)
... | euler_021_030.ipynb | mndrake/PythonEuler | mit |
Quadratic primes
Problem 27
Euler discovered the remarkable quadratic formula:
$n^2 + n + 41$
It turns out that the formula will produce $40$ primes for the consecutive values $n = 0$ to $39$. However, when $n = 40$, $40^2 + 40 + 41 = 40(40 + 1) + 41$ is divisible by $41$, and certainly when $n = 41$, $41^2 + 41 + 41... | from euler import is_prime, Seq, timer, primes
def primes_generated(x):
a,b = x
return (
Seq.initInfinite(lambda n: n*n + a*n + b)
>> Seq.takeWhile(is_prime)
>> Seq.length)
def p027():
primes_1000 = (primes()
>> Seq.takeWhile(lambda x: x<1000)
... | euler_021_030.ipynb | mndrake/PythonEuler | mit |
Number spiral diagonals
Problem 28
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
<font color='red'>21</font> 22 23 24 <font color='red'>25</font>
20 <font color='red'>07</font> 08 <font color='red'>09</font> 10
19 06 <font color='red'>01</font> 02 11... | from euler import timer
def p028():
n = 1001
def collect(depth, start, acc):
if (depth > n/2):
return acc
else:
return collect(depth+1, start+8*depth, acc+4*start+20*depth)
return collect(1,1,1)
timer(p028) | euler_021_030.ipynb | mndrake/PythonEuler | mit |
Distinct powers
Problem 29
Consider all integer combinations of $a^b$ for $2 ≤ a ≤ 5$ and $2 ≤ b ≤ 5$:
$2^2=4$, $2^3=8$, $2^4=16$, $2^5=32$
$3^2=9$, $3^3=27$, $3^4=81$, $3^5=243$
$4^2=16$, $4^3=64$, $4^4=256$, $4^5=1024$
$5^2=25$, $5^3=125$, $5^4=625$, $5^5=3125$
If they are then placed in numerical order, with any r... | from euler import timer
def p029():
return (set(a **b for a in range(2,101) for b in range(2,101))
>> Seq.length)
timer(p029) | euler_021_030.ipynb | mndrake/PythonEuler | mit |
Digit fifth powers
Problem 30
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
$1634 = 1^4 + 6^4 + 3^4 + 4^4$
$8208 = 8^4 + 2^4 + 0^4 + 8^4$
$9474 = 9^4 + 4^4 + 7^4 + 4^4$
As $1 = 1^4$ is not a sum it is not included.
The sum of these numbers is $1634 + 8208 +... | from euler import timer
def p030():
def is_sum(n):
return (
str(n)
>> Seq.map(lambda x: int(x) ** 5)
>> Seq.sum
) == n
max_n = (
((Seq.unfold(lambda x: (x, x+1), 1)
>> Seq.find(lambda x: 10 ** x - 1 > x * 9 ** 5)
) - 1) * 9 ** 5)
... | euler_021_030.ipynb | mndrake/PythonEuler | mit |
Set up inline matplotlib | %matplotlib inline
rcParams['figure.figsize'] = 5, 4
sb.set_style('whitegrid') | Community_identity.ipynb | HNoorazar/PyOpinionGame | gpl-3.0 |
Setting Up Game Parameters | config = og_cfg.staticParameters()
path = '/Users/hn/Documents/GitHub/PyOpinionGame/' # path to the 'staticParameters.cfg'
staticParameters = path + 'staticParameters.cfg'
config.readFromFile(staticParameters) # Read static parameters
config.threshold = 0.0001
config.Kthreshold = 0.00001
config.startingseed = 10
con... | Community_identity.ipynb | HNoorazar/PyOpinionGame | gpl-3.0 |
Set up the state of the system
State of the system includes:
Weight Matrix (Matrix of the coupling wieghts between topic)
Initial Opinions of agents
Adjacency matrix of the network
This is just initialization of the state, later we update some elements of it. | # These are the default matrices for the state of the system:
# If you want to change them, you can generate a new one in the following cell
default_weights = og_coupling.weights_no_coupling(config.popSize, config.ntopics)
default_initialOpinions = og_opinions.initialize_opinions(config.popSize, config.ntopics)
default... | Community_identity.ipynb | HNoorazar/PyOpinionGame | gpl-3.0 |
User Defined States and parameters Can go in the following cell: | numberOfCommunities = 3
communityPopSize = 25
config.popSize = numberOfCommunities * communityPopSize
# List of upper bound probability of interaction between communities
uppBound_list = [0.0]
# List of uniqueness Strength parameter
individStrength = [0.0]
config.learning_rate = 0.1
config.iterationMax = 10000
ta... | Community_identity.ipynb | HNoorazar/PyOpinionGame | gpl-3.0 |
Plot the experiment done above: | time, population_size, no_of_topics = evolution = all_experiments_history['experiment1'].shape
evolution = all_experiments_history['experiment1'].reshape(time, population_size)
fig = plt.figure()
plt.plot(evolution)
plt.xlabel('Time')
plt.ylabel('Opinionds')
plt.title('Evolution of Opinions')
fig.set_size_inches(10,5)... | Community_identity.ipynb | HNoorazar/PyOpinionGame | gpl-3.0 |
Skew Uniqueness Tendency Driver:
I observed when having tendency for uniqueness is drawn from normal distribution, we do not get an interesting result. For example, initial intuition was that uniqueness for tendency would delay stabilization of the network, however, it did not. So, here we draw uniqueness tendencies fr... | state = og_state.WorldState(adj=default_adj,
couplingWeights=default_weights,
initialOpinions=default_initialOpinions,
initialHistorySize=100,
historyGrowthScale=2)
state.validate()
#
# load configuratio... | Community_identity.ipynb | HNoorazar/PyOpinionGame | gpl-3.0 |
Initiate State | # These are the default matrices for the state of the system:
# If you want to change them, you can generate a new one in the following cell
default_weights = og_coupling.weights_no_coupling(config.popSize, config.ntopics)
default_initialOpinions = og_opinions.initialize_opinions(config.popSize, config.ntopics)
default... | Community_identity.ipynb | HNoorazar/PyOpinionGame | gpl-3.0 |
In this example we will optimize the 2D Six-Hump Camel function (available in GPyOpt). We will assume that exact evaluations of the function are observed. The explicit form of the function is:
$$f(x_1,x_2) =4x_1^2 – 2.1x_1^4 + x_1^6/3 + x_1x_2 – 4x_2^2 + 4x_2^4$$ | func = GPyOpt.objective_examples.experiments2d.sixhumpcamel() | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
Imagine that we were optimizing the function in the intervals $(-1,1)\times (-1.5,1.5)$. As usual, we can defined this box constraints as: | space =[{'name': 'var_1', 'type': 'continuous', 'domain': (-1,1)},
{'name': 'var_2', 'type': 'continuous', 'domain': (-1.5,1.5)}] | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
This will be an standard case of optimizing the function in an hypercube. However in this case we are going to study how to solve optimization problems with arbitrary constraints. In particular, we consider the problem of finding the minimum of the function in the region defined by
$$-x_2 - .5 + |x_1| -\sqrt{1-x_1^2} \... | constraints = [{'name': 'constr_1', 'constraint': '-x[:,1] -.5 + abs(x[:,0]) - np.sqrt(1-x[:,0]**2)'},
{'name': 'constr_2', 'constraint': 'x[:,1] +.5 - abs(x[:,0]) - np.sqrt(1-x[:,0]**2)'}] | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
And create the feasible region od the problem by writting: | feasible_region = GPyOpt.Design_space(space = space, constraints = constraints) | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
Now, let's have a look to what we have. Let's make a plot of the feasible region and the function with the original box-constraints. Note that the function .indicator_constrains(X) takes value 1 if we are in the feasible region and 0 otherwise. | ## Grid of points to make the plots
grid = 400
bounds = feasible_region.get_continuous_bounds()
X1 = np.linspace(bounds[0][0], bounds[0][1], grid)
X2 = np.linspace(bounds[1][0], bounds[1][1], grid)
x1, x2 = np.meshgrid(X1, X2)
X = np.hstack((x1.reshape(grid*grid,1),x2.reshape(grid*grid,1)))
## Check the points in the ... | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
The Six-Hump Camel function has two global minima. However, with the constraints that we are using, only one of the two is a valid one. We can see this by overlapping the two previous plots. | plt.figure(figsize=(6.5,6))
OB = plt.contourf(X1, X2, func.f(X).reshape(grid,grid),100,alpha=1)
IN = plt.contourf(X1, X2, masked_ind ,100, cmap= plt.cm.bone, alpha=.5,origin ='lower')
plt.text(-0.25,0,'FEASIBLE',size=20,color='white')
plt.text(-0.3,1.1,'INFEASIBLE',size=20,color='white')
plt.plot(np.array(func.min)[:,0... | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
We will use the modular iterface to solve this problem. We start by generating an random inital design of 5 points to start the optimization. We just need to do: | # --- CHOOSE the intial design
from numpy.random import seed # fixed seed
seed(123456)
initial_design = GPyOpt.experiment_design.initial_design('random', feasible_region, 10) | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
Importantly, the points are always generated within the feasible region as we can check here: | plt.figure(figsize=(6.5,6))
OB = plt.contourf(X1, X2, func.f(X).reshape(grid,grid),100,alpha=1)
IN = plt.contourf(X1, X2, masked_ind ,100, cmap= plt.cm.bone, alpha=.5,origin ='lower')
plt.text(-0.25,0,'FEASIBLE',size=20,color='white')
plt.text(-0.3,1.1,'INFEASIBLE',size=20,color='white')
plt.plot(np.array(func.min)[:,0... | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
Now, we choose the rest of the objects that we need to run the optimization. We will use a Gaussian Process with parameters fitted using MLE and the Expected improvement. We use the default BFGS optimizer of the acquisition. Evaluations of the function are done sequentially. | # --- CHOOSE the objective
objective = GPyOpt.core.task.SingleObjective(func.f)
# --- CHOOSE the model type
model = GPyOpt.models.GPModel(exact_feval=True,optimize_restarts=10,verbose=False)
# --- CHOOSE the acquisition optimizer
aquisition_optimizer = GPyOpt.optimization.AcquisitionOptimizer(feasible_region)
# --- ... | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
Next, we create the BO object to run the optimization. | # BO object
bo = GPyOpt.methods.ModularBayesianOptimization(model, feasible_region, objective, acquisition, evaluator, initial_design) | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
We first run the optimization for 5 steps and check how the results looks. | # --- Stop conditions
max_time = None
max_iter = 5
tolerance = 1e-8 # distance between two consecutive observations
# Run the optimization
bo.run_optimization(max_iter = max_iter, max_time = max_time, eps = tolerance, verbosity=False)
bo.plot_acquisition() | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
See how the optimization is only done within the feasible region, out of it the value of the acquisition is zero, so no evaluation is selected in that region. We run 20 more iterations to see the acquisition and convergence. | # Run the optimization
max_iter = 25
bo.run_optimization(max_iter = max_iter, max_time = max_time, eps = tolerance, verbosity=False)
bo.plot_acquisition()
bo.plot_convergence()
# Best found value
np.round(bo.x_opt,2)
# True min
np.round(func.min[0],2) | manual/GPyOpt_constrained_optimization.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
Now we build something more complicated to show where indexing can get tricky ... | import numpy as np
import pandas as pd
m3d=np.random.rand(3,4,5)
m3d
# how does Pandas arrange the data?
n3d=m3d.reshape(4,3,5)
n3d | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Notice which numbers moved where. This would seem to indicate that in shape(a,b,c):
- a is like the object's depth (how many groupings of rows/columns are there?)
- b is like the object's rows per grouping (how many rows in each subgroup)
- c is like the object's columns
What if the object had 4 dimensions? | o3d=np.random.rand(2,3,4,5)
o3d | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Just analyzing how the numbers are arranged, we see that in shape(a,b,c,d), it just added the new extra dimensional layer to the front of the list so that now:
- a = larger hyper grouping (2 of them)
- b = first subgroup within (3 of them)
- c = rows within these groupings (4 of them)
- d = columns within these groupin... | # some simple arrays:
simp1=np.array([[1,2,3,4,5]])
simp2=np.array([[10,9,8,7,6]])
simp3=[11,12,13]
# a dictionary
dfrm1 = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'population': [1.5, 1.7, 3.6, 2.4, 2.9]}
# convert dictionary to DataFrame
dfrm1 = p... | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Now let's access other stuff in the list ... | crazyList[1] # this is the second object of the list (Python like many languages starts indicies at 0)
# this is the full output of m3d
crazyList[0] # after the above demo, no surprises here ... simp1 was the first object we added to the list | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
In the tests that follow ... anything that does not work is wrapped in exception handling (that displays the error) so this notebook can be run from start to finish ... Note that it is not good practice to use a catch all for all errors. In real coding errors should be handled individually by type.
How do we access the... | try: # not this way ...
crazyList[0][1]
except Exception as ex:
print("%s%s %s" %(type(ex), ":", ex))
# let's look at what we built: all the objects are here but are no longer named so we need to get indices right
crazyList
# note that both of these get the same data, but also note the diffe... | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Sub element 4 is a simple list nested within caryList: crazyList [ ... [content at index position 4] ...] | print(crazyList[4])
crazyList[4][1] # get 2nd element in the list within a list at position 4 (object 4 in the list) | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
So what about the array? The array was originally built in "simp1" and then added to crazyList. Its source looks like this: | print(type(simp1))
print(simp1.shape)
print(simp1)
print(simp1[0]) # note that the first two give us the same thing (whole array)
simp1[0][1] | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Note the [] versus the [[]] ... our "simple arrays" were copied from an example, but are actually nested objects of 1 list of 5 elements forming the first object inside the array. A true simple array would like this: | trueSimp1=np.array([10,9,8,7,6])
print(trueSimp1.shape) # note: output shows that Python thinks this is 5 rows, 1 column
trueSimp1 | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Let's add the true simple array to our crazy object and then create working examples of accessing everything ... | crazyList.append(trueSimp1) # append mutates so this changes the original list
crazyList # Warning! if you re-run this cell, you will keep adding more copies of the last object
# to the end of this object. To be consistent with content in this NB
... | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Looking at just that first element again: | crazyList[0] # first array to change | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
remember that this object if it were not in a list would be accessed like so: | simp1[0][1] # second element inside it | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
... so inside crazyList ? The answer is that the list is one level deep and the elements are yet another level in: | crazyList[0]
crazyList[0][0][1] | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
<a id="mutation" name="mutation"></a>
Sidebar: Mutation and Related Concerns
Try this test and you will see it does not work:
crazyList2 = crazyList.append(trueSimp1)
What it did: crazyList got an element appended to the end and crazyList2 came out the other side empty. This is because append() returns None and oper... | aList = [1,2,3]
bList = aList
print(aList)
print(bList) | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Note how the second is really a reference to the first so changing one changes the other: | aList[0] = 0
bList[1] = 1
bList.append(4)
print(aList)
print(bList) | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
For a simple list ... we can fix that by simply using list() during our attempt to create the copy: | bList = list(aList)
bList[0] = 999
aList[1] = 998
print(aList)
print(bList)
bList.append(19)
print(aList)
print(bList) | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Mutation is avoided. Now we can change our two objects independantly. However, with complex objects like crazyList, this does not work.
The following will illustrate the problem and later, options to get around it are presented. | crazyList2 = list(crazyList)
crazyList2 | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Now we make some changes: | len(crazyList2)-1 # this is the position of the object we want to change
crazyList2[7][1] = 13 # this will change element 2 of last object in crazyList2 | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Now we'll look at just the last object in both "crazyLists" showing what changed: | print(crazyList[7])
print(crazyList2[7]) | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
The "13" replaced the value at this location in both crazyList and crazyList2. We are not dealing with true copies but rather references to the same data as further illustrated here: | crazyList[7][1] = 9 # change on of them again and both change
print(crazyList[7])
print(crazyList2[7]) | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
So ... how to make a copy that does not mutate? (we can change one without changing the other)?<br/>
Let's look at some things that don't work first ... | crazyList3 = crazyList[:] # according to online topics ... this was supposed to work for the reason outlined below
# it probably works with some complex objects but does not work with this one
# some topics online indicate this should have worked because:
# * the problem is avoided by... | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Python is hard to fool ... At first, I considered that we might now have two lists, but w/ just element 7 passed in by reference and so it mutates. But this shows our whole lists are still mutating: | print("before:")
print(crazyList[4])
print(crazyList3[4])
crazyList3[4][0] = 14
print("after:")
print(crazyList[4])
print(crazyList3[4]) # try other tests of other elements and you will get same results | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
deepcopy() comes from the copy library and the commands are documented at Python.org. For this situation, this solution seems to work for when mutation is undesirable: | import copy
crazyList4 = copy.deepcopy(crazyList)
print("before:")
print(crazyList[4])
print(crazyList4[4])
crazyList4[4][0] = 15
print("")
print("after:")
print(crazyList[4])
print(crazyList4[4]) | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Should even deepcopy() not work, this topic online may prove helpful in these situations: Stack Overflow: When Deep Copy is not Enough.
<a id="indexing" name="indexing"></a>
Finding The Index of a Value
Suppose we didn't know how to find the element but we knew the value we were looking for? How to get its index? | print(stupidList)
print(stupidList[1].index(5)) # this works on lists
# but for nested lists, you would need to loop through each sublist and handle the error that
# gets thrown each time it does not find the answer
for element in stupidList:
try:
test_i = element.index(5)
except E... | PY_Basics/TMWP_PY_CrazyList_Indexing_and_Related_Experiments.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Getting the data ready for work
If the data is in GSLIB format you can use the function pygslib.gslib.read_gslib_file(filename) to import the data into a Pandas DataFrame. | #get the data in gslib format into a pandas Dataframe
mydata= pygslib.gslib.read_gslib_file('../datasets/cluster.dat')
# This is a 2D file, in this GSLIB version we require 3D data and drillhole name or domain code
# so, we are adding constant elevation = 0 and a dummy BHID = 1
mydata['Zlocation']=0.
mydata['bhid']... | doc/source/Ipython_templates/gamv3D.ipynb | opengeostat/pygslib | mit |
This code creates a CP model container that allows the use of constraints that are specific to constraint programming or to
scheduling.
Declarations of decision variables
Variable declarations define the type of each variable in the model. For example, to create a variable that equals the amount of material shipped fro... | masonry = mdl0.interval_var(size=35)
carpentry = mdl0.interval_var(size=15)
plumbing = mdl0.interval_var(size=40)
ceiling = mdl0.interval_var(size=15)
roofing = mdl0.interval_var(size=5)
painting = mdl0.interval_var(size=10)
windows = mdl0.interval_var(size=5)
facade = mdl0.interval_var(size=10)
garden = mdl0.interval_... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Here, the special constraint end_before_start() ensures that one interval variable ends before the other starts.
If one of the interval variables is not present, the constraint is automatically satisfied.
Calling the solve | # Solve the model
print("\nSolving model....")
msol0 = mdl0.solve(TimeLimit=10)
print("done") | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Displaying the solution
The interval variables and precedence constraints completely describe this simple problem.
Print statements display the solution, after values have been assigned to the start and end of each of the interval variables in the model. | if msol0:
var_sol = msol0.get_var_solution(masonry)
print("Masonry : {}..{}".format(var_sol.get_start(), var_sol.get_end()))
var_sol = msol0.get_var_solution(carpentry)
print("Carpentry : {}..{}".format(var_sol.get_start(), var_sol.get_end()))
var_sol = msol0.get_var_solution(plumbing)
print("Pl... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
To understand the solution found by CP Optimizer to this satisfiability scheduling problem, consider the line:
<code>Masonry : 0..35</code>
The interval variable representing the masonry task, which has size 35, has been assigned the interval [0,35).
Masonry starts at time 0 and ends at the time point 35.
Graphical vi... | import docplex.cp.utils_visu as visu
import matplotlib.pyplot as plt
%matplotlib inline
#Change the plot size
from pylab import rcParams
rcParams['figure.figsize'] = 15, 3
if msol0:
wt = msol0.get_var_solution(masonry)
visu.interval(wt, 'lightblue', 'masonry')
wt = msol0.get_var_solution(carpentry) ... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Solving a problem consists of finding a value for each decision variable so that all constraints are satisfied.
It is not always know beforehand whether there is a solution that satisfies all the constraints of the problem.
In some cases, there may be no solution. In other cases, there may be many solutions to a prob... | # Solve the model
print("\nSolving model....")
msol1 = mdl1.solve(TimeLimit=20)
print("done")
if msol1:
print("Cost will be " + str(msol1.get_objective_values()[0]))
var_sol = msol1.get_var_solution(masonry)
print("Masonry : {}..{}".format(var_sol.get_start(), var_sol.get_end()))
var_sol = msol1.g... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Graphical display of the same result is available with: | import docplex.cp.utils_visu as visu
import matplotlib.pyplot as plt
%matplotlib inline
#Change the plot size
from pylab import rcParams
rcParams['figure.figsize'] = 15, 3
if msol1:
wt = msol1.get_var_solution(masonry)
visu.interval(wt, 'lightblue', 'masonry')
wt = msol1.get_var_solution(carpentry) ... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Step 7: Create the transition times
Transition times can be modeled using tuples with three elements.
The first element is the interval variable type of one task, the second is the interval variable type of the other task and the third element of the tuple is the transition time from the first to the second.
An integ... | transitionTimes = transition_matrix([[int(abs(i - j)) for j in Houses] for i in Houses]) | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Step 11: Solve the model
The search for an optimal solution in this problem can potentiality take a long time. A fail limit can be placed on the solve process to limit the search process.
The search stops when the fail limit is reached, even if optimality of the current best solution is not guaranteed.
The code for l... | # Solve the model
print("\nSolving model....")
msol2 = mdl2.solve(FailLimit=30000)
print("done")
if msol2:
print("Cost will be " + str(msol2.get_objective_values()[0]))
else:
print("No solution found")
# Viewing the results of sequencing problems in a Gantt chart
# (double click on the gantt to see details)
i... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Chapter 4. Adding calendars to the house building problem
This chapter introduces calendars into the house building problem, a problem of scheduling the tasks involved in building multiple houses in such a manner that minimizes the overall completion date of the houses.
There are two workers, each of whom must perform ... | import sys
from docplex.cp.model import *
mdl3 = CpoModel()
NbHouses = 5;
WorkerNames = ["Joe", "Jim" ]
TaskNames = ["masonry","carpentry","plumbing","ceiling","roofing","painting","windows","facade","garden","moving"]
Duration = [35,15,40,15,5,10,5,10,5,5]
Worker = {"masonry":"Joe","carpentry":"Joe","plumbing":... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Step 9: Solve the model
The search for an optimal solution in this problem could potentiality take a long time, so a fail limit has been placed on the solve process.
The search will stop when the fail limit is reached, even if optimality of the current best solution is not guaranteed.
The code for limiting the solve ... | # Solve the model
print("\nSolving model....")
msol3 = mdl3.solve(FailLimit=30000)
print("done")
if msol3:
print("Cost will be " + str( msol3.get_objective_values()[0] )) # Allocate tasks to workers
tasks = {w : [] for w in WorkerNames}
for k,v in Worker.items():
tasks[v].append(k)
types = ... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Chapter 5. Using cumulative functions in the house building problem
Some tasks must necessarily take place before other tasks, and each task has a predefined duration.
Moreover, there are three workers, and each task requires any one of the three workers.
A worker can be assigned to at most one task at a time.
In ad... | NbWorkers = 3
NbHouses = 5
TaskNames = {"masonry","carpentry","plumbing",
"ceiling","roofing","painting",
"windows","facade","garden","moving"}
Duration = [35, 15, 40, 15, 5, 10, 5, 10, 5, 5]
ReleaseDate = [31, 0, 90, 120, 90]
Precedences = [("masonry", "carpentry"), ("masonry", "plumbin... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Step 10: Solve the model
The search for an optimal solution in this problem could potentiality take a long time, so a fail limit has been placed on the solve process.
The search will stop when the fail limit is reached, even if optimality of the current best solution is not guaranteed.
The code for limiting the solve... | # Solve the model
print("\nSolving model....")
msol4 = mdl4.solve(FailLimit=30000)
print("done")
if msol4:
print("Cost will be " + str( msol4.get_objective_values()[0] ))
import docplex.cp.utils_visu as visu
import matplotlib.pyplot as plt
%matplotlib inline
#Change the plot size
from pylab im... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Step 9: Solve the model
The search for an optimal solution in this problem could potentiality take a long time, so a fail limit has been placed on the solve process. The search will stop when the fail limit is reached, even if optimality of the current best solution is not guaranteed. | # Solve the model
print("\nSolving model....")
msol5 = mdl5.solve(FailLimit=30000)
print("done")
if msol5:
print("Cost will be "+str( msol5.get_objective_values()[0] ))
worker_idx = {w : i for i,w in enumerate(Workers)}
worker_tasks = [[] for w in range(nbWorkers)] # Tasks assigned to a given worker
... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Step 5: Create the transition times
The transition time from a dirty state to a clean state is the same for all houses.
As in the example Chapter 3, “Adding workers and transition times to the house building problem”, a tupleset ttime is created to represent the transition time between cleanliness states. | Index = {s : i for i,s in enumerate(AllStates)}
ttvalues = [[0, 0], [0, 0]]
ttvalues[Index["dirty"]][Index["clean"]] = 1
ttime = transition_matrix(ttvalues, name='TTime') | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Step 9: Solve the model
The search for an optimal solution in this problem could potentiality take a long time, so a fail limit has been placed on the solve process. The search will stop when the fail limit is reached, even if optimality of the current best solution is not guaranteed.
The code for limiting the solve p... | # Solve the model
print("\nSolving model....")
msol6 = mdl6.solve(FailLimit=30000)
print("done")
if msol6:
print("Cost will be " + str( msol6.get_objective_values()[0] ))
import docplex.cp.utils_visu as visu
import matplotlib.pyplot as plt
%matplotlib inline
#Change the plot size
from pylab im... | examples/cp/jupyter/scheduling_tuto.ipynb | IBMDecisionOptimization/docplex-examples | apache-2.0 |
Type a., then press tab to see attributes:
Alternatively, use the dir(a) command to see the attributes (ignore everything starting with __): | dir(a) | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
Imagine we want to find out what the append attribute is: use help(a.append) or a.append? to learn more about an attribute: | help(a.append) | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
Let's try this: | print(a)
a.append("New element")
print(a) | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
Comments
Anything following a # sign is considered a comment (to the end of the line) | d = 20e-9 # distance in metres | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
Importing libraries
The core Python commands can be extened through importing additonal libraries.
import syntax 1 | import math
math.sin(0) | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
import syntax 2 | import math as m
m.sin(0) | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
Functions
A function is defined in Python using the def keyword. For example, the greet function accepts two input arguments, and concatenates them to become a greeting: | def greet(greeting, name):
"""Optional documentation string, inclosed in tripple quotes.
Can extend over mutliple lines."""
print(greeting + " " + name)
greet("Hello", "World")
greet("Bonjour", "tout le monde") | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
In above examples, the input argument to the function has been identified by the order of the arguments.
In general, we prefer another way of passing the input arguments as
- this provides additional clarity and
- the order of the arguments stops to matter. | greet(greeting="Hello", name="World")
greet(name="World", greeting="Hello") | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
Note that the names of the input arguments can be displayed intermittently if you type greet( and then press SHIFT+TAB (the cursor needs to be just to the right of the opening paranthesis).
A loop | def say_hello(name): # function
print("Hello " + name)
# main program starts here
names = ["Landau", "Lifshitz", "Gilbert"]
for name in names:
say_hello(name=name) | workshops/Durham/reference/basics-python.ipynb | joommf/tutorial | bsd-3-clause |
Link Prediction
The idea of link prediction was first proposed by Liben-Nowell and Kleinberg in 2004 as the following question:
"Given a snapshot of a social network, can we infer which new interactions among its members are likely to occur in the near future?"
It's an inticing idea and has led to many interesting de... | preds_jc = nx.jaccard_coefficient(GA)
pred_jc_dict = {}
for u, v, p in preds_jc:
pred_jc_dict[(u,v)] = p
sorted(pred_jc_dict.items(), key=lambda x:x[1], reverse=True)[:10]
extra_attrs = {'finn':('Finn Dandridge','M','S'),
'olivia':('Olivia Harper','F','S'),
'steve':('Steve Murphy','M','S'),
'torres':('Callie ... | notebooks/5. Link Prediction.ipynb | rtidatascience/connected-nx-tutorial | mit |
Preferential Attachment
The preferential attachement methods mirrors the “rich get richer” -- nodes with more connections will be the ones to be more likely to get future connections.
Essentially, the measure is the product of a node pairs degrees:
$$ PA = |\Gamma(u)| \bullet |\Gamma(v)|$$
where $\Gamma(u)$ denotes t... | preds_pa = nx.preferential_attachment(GA)
pred_pa_dict = {}
for u, v, p in preds_pa:
pred_pa_dict[(u,v)] = p
sorted(pred_pa_dict.items(), key=lambda x:x[1], reverse=True)[:10] | notebooks/5. Link Prediction.ipynb | rtidatascience/connected-nx-tutorial | mit |
So far we have imported a dataset from a CSV file into a Pandas DataFrame using the read_csv() function. Then we displayed the data, first as a table, and secondly as a historgram.
Questions About the Data
There are a near infinite number of questions we could possibly ask about this data. But to get started, here ar... | # Calculate the length of each employee's title and add to the DataFrame
white_house['LengthOfTitle'] = white_house['Position Title'].apply(len)
white_house.head()
# Plot the length of employee title versus salary to look for correlation
plt.plot(white_house['LengthOfTitle'], white_house['Salary'])
plt.title('How does... | dataquest/JupyterNotebook/Basics.ipynb | tleonhardt/CodingPlayground | mit |
Uh ok, maybe I was wrong about visuallizing being great for detecting correlation ;-)
It looks like there may be a weak positive correlation. But it is really hard to tell.
Maybe we should just numerically calculate the correlation.
Also, it looks like there are some low salary outliers. Should we check to make sure... | # Get the values in Pay Basis and figure out how many unique ones there are
types_of_pay_basis = set(white_house['Pay Basis'])
types_of_pay_basis | dataquest/JupyterNotebook/Basics.ipynb | tleonhardt/CodingPlayground | mit |
Ok, only one pay basis, annually. So that wasn't an issue. | # Compute pairwise correlation of columns, excluding NA/null values
correlations = white_house.corr()
correlations
# Linear Regression using ordinary least squares
import statsmodels.api as sm
model = sm.OLS(white_house['Salary'], white_house['LengthOfTitle'])
residuals = model.fit()
print(residuals.summary()) | dataquest/JupyterNotebook/Basics.ipynb | tleonhardt/CodingPlayground | mit |
So yea, there is a real positive correlation between length of employee title and salary!
How much does the White House pay in total salary? | total_salary = sum(white_house['Salary'])
total_salary | dataquest/JupyterNotebook/Basics.ipynb | tleonhardt/CodingPlayground | mit |
The white house pays about $40 Million per year in total salary.
Who are the highest and lowest paid staffers? | highest_paid = white_house[white_house['Salary'] == max(white_house['Salary'])]
highest_paid
lowest_paid = white_house[white_house['Salary'] == min(white_house['Salary'])]
lowest_paid | dataquest/JupyterNotebook/Basics.ipynb | tleonhardt/CodingPlayground | mit |
この結果から古典的最小二乗法による推定式をまとめると、
[供給関数]
$\hat Q_{i} = 4.8581 + 1.5094 P_{i} - 1.5202 E_{i} $
[需要関数]
$\hat Q_{i} = 16.6747 - 0.9088 P_{i} - 1.0369 A_{i}$
となる。
しかし、説明変数Pと誤差の間に関係があるため、同時方程式バイアスが生じてしまいます。
そこで、以下では同時方程式体系の推定法として代表的な二段階最小二乗法を用いて推定し直します。 | # 外生変数設定
inst = data[[ 'A', 'E']].as_matrix()
inst = sm.add_constant(inst)
# 2SLSの実行(Two Stage Least Squares: 二段階最小二乗法)
model1 = IV2SLS(Y, X1, inst)
model2 = IV2SLS(Y, X2, inst)
result1 = model1.fit()
result2 = model2.fit()
print(result1.summary())
print(result2.summary()) | SimultaneousEquation.ipynb | ogaway/Econometrics | gpl-3.0 |
Preliminary Report
Read the following results/report. While you are reading it, think about if the conclusions are correct, incorrect, misleading or unfounded. Think about what you would change or what additional analyses you would perform.
A. Initial observations based on the plot above
+ Overall, rate of readmissions... | clean_hospital_read_df.head()
clean_hospital_read_df.info()
hospital_dropna_df = clean_hospital_read_df[np.isfinite(clean_hospital_read_df['Excess Readmission Ratio'])]
hospital_dropna_df.info() | Reduce Hospital Readmissions Using EDA/sliderule_dsi_inferential_statistics_exercise_3.ipynb | llclave/Springboard-Mini-Projects | mit |
A. Do you agree with the above analysis and recommendations? Why or why not?
The analysis seems to base its conclusion on one scatterplot. I cannot agree with the above analysis and recommendations because there is not enough evidence to support it. Further investigation and statistical analysis should be completed to ... | number_of_discharges = hospital_dropna_df['Number of Discharges']
excess_readmission_ratio = hospital_dropna_df['Excess Readmission Ratio']
pearson_r = np.corrcoef(number_of_discharges, excess_readmission_ratio)[0, 1]
print('The Pearson correlation of the sample is', pearson_r)
permutation_replicates = np.empty(100... | Reduce Hospital Readmissions Using EDA/sliderule_dsi_inferential_statistics_exercise_3.ipynb | llclave/Springboard-Mini-Projects | mit |
The p value was calculated to be extremely small above. This means our null hypothesis ($H_0$) should be rejected and the alternate hypothesis is more likely. There is a statistically significant negtive correlation between number of discharges and readmission rates. However the correlation is small as shown by the pea... | import seaborn as sns
sns.set()
plt.scatter(number_of_discharges, excess_readmission_ratio, alpha=0.5)
slope, intercept = np.polyfit(number_of_discharges, excess_readmission_ratio, 1)
x = np.array([0, max(number_of_discharges)])
y = slope * x + intercept
plt.plot(x, y)
plt.xlabel('Number of discharges')
plt.ylabel... | Reduce Hospital Readmissions Using EDA/sliderule_dsi_inferential_statistics_exercise_3.ipynb | llclave/Springboard-Mini-Projects | mit |
<a id='ll'>2.3 Which data to use?</a>
Here i am combining all the 3 data so as to collect the data of all files and removing 1st jan which is an outlier
Here i have removed the data of 1st Jan because it was new year, and as we can see the number of stockouts were too high so we should remove it from our current anal... | pre_stock.groupby(by='dt')['stockout'].sum().sort_values(ascending=False)
%matplotlib inline
import matplotlib.pyplot as plt
pre_stock.groupby(by='dt')['stockout'].sum().plot(figsize=(10,4))
plt.xticks(rotation=40)
plt.annotate("1St Jan",xy=(1,8000))
order['created_at']=pd.to_datetime(order.created_at)
order['comple... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<a id='god'>3. Feature Engineering</a>
<a id='ot'>3.1 Drivers Engaged</a>
Here i am calculating how many drivers are engaged in given train-test combination of times. This would give us average engagement of a driver at particular time interval.
** Note: this would take 5-6 hours. | df = order.loc[(order.state=='COMPLETE')&(order.created_at.dt.day>29)].reset_index()
df.head()
df2 = order_test.loc[(order_test.state=='COMPLETE')&(order_test.created_at.dt.day>29)].reset_index()
order_test.loc[(order_test.state=='COMPLETE')&(order_test.created_at.dt.day>25)].reset_index().shape
from tqdm import tq... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
i saved a backup here(train_driver.csv which contains driver engaged) | train.head()
train=pd.read_csv('train_driver.csv')
test =pd.read_csv('test/post_stockout_test_candidate.csv')
train.head()
train.head() | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<a id='ot2'>3.2 Backbone of my Analysis(Feature Engineering)</a>
Making Aggregate features like
Concat the train and test and make features like<br>
1) Stockout on day of week<br>
2)stockout in the hour of a day<br>
3)stockout in the hour of second<br>
4)stockout in the hour of every day of week<br>
5)stockout in the... |
#train.head()
def upd(train,pre_stock):
train = train.merge(pd.DataFrame(alldata_out.groupby(by=['weekday'])['stockout'].sum()).reset_index(),on='weekday',how='left',suffixes=('','_week'))
train = train.merge(pd.DataFrame(alldata_out.groupby(by=['hour'])['stockout'].sum()).reset_index(),on='hour',how='left',su... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
Processing date | from datetime import datetime
import datetime
def dat1(X):
return(datetime.datetime.strptime(X, "%d%b%Y:%H:%M:%S"))
tm=train.time_stamp_utc.apply(dat1)
tm2=test.time_stamp_utc.apply(dat1)
train =upd(train,pre_stock)
train.head()
test =upd(test,pre_stock_test)
test= test.merge(pd.DataFrame(alldata_out.groupby(by... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<a id='ot3'>3.3 Exploring hidden hints and making features.</a>
This is the minute stockout history on every day-of-week basis | import seaborn as sns
%matplotlib inline
import matplotlib.pyplot as plt
plt.figure(figsize=(20,5))
sns.heatmap(pre_stock.pivot_table(index='weekday',columns='minute',values='stockout',aggfunc=sum),linecolor='black')
min_graph=pre_stock.pivot_table(index='weekday',columns='minute',values='stockout',aggfunc=sum)
min_gr... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
This is the one of the most shocking observation here, as you can see there is very high probability of getting a stockout during between 11-25 and 41-55 seconds of every minute. | plt.figure(figsize=(20,5))
sns.heatmap(pre_stock.pivot_table(index='weekday',columns='second',values='stockout',aggfunc=sum),linecolor='black') | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
you can see that is somewhat perfect normal | plt.figure(figsize=(20,5))
sec_graph.loc[1].plot() | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
Inference:
So we can infer that there could be two possible case:<br>
1)As stockout starts occuring the Zomato's iternal system may alert the Part time driver.<br>
2)The data-organisers may have generated the random time samples where it was not uniform but somewhat normal.
Using the Above fact lets discover a new fe... | a=[]
for i in train.second:
if i<15:
a.append(i)
elif i<30:
a.append(30-i)
elif i<45:
a.append(i-30)
else:
a.append(60-i)
train['sec_fun']=a
a=[]
for i in test.second:
if i<15:
a.append(i)
elif i<30:
a.append(30-i)
elif i<45:
a.append(... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<a id='ot4'>3.4 Making Features using order file.</a>
Using the order file , Let's try to calculate the total number of orders and aggregate features | order_comp=order.loc[order.state=='COMPLETE']
order_comp_test=order_test.loc[order.state=='COMPLETE'] | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.