markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The mass matrix should be the same as the trace of the 2nd shape integrals: | (shape_integral_2[0][0] + shape_integral_2[1][1] + shape_integral_2[2][2] - me).expand() | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Stiffness matrix
Differentiate the shape functions: | B = Matrix(np.zeros((4, 12)))
B[0, :] = S[0, :].diff(xi, 1) / l
B[1, :] = S[1, :].diff(xi, 2) / l**2
B[2, :] = S[2, :].diff(xi, 2) / l**2
B[3, :] = S[3, :].diff(xi, 1) / l
B.simplify()
B[:, :6]
B[:, 6:]
titles = ['x-defl', 'y-defl', 'z-defl', 'torsion']
for i in range(4):
sympy.plot(*([xx.subs(l, 2) for xx in B[... | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Define the stiffness distribution (linear): | EA1, EA2, EIy1, EIy2, EIz1, EIz2, GJ1, GJ2 = symbols('EA_1, EA_2, EIy_1, EIy_2, EIz_1, EIz_2, GJ_1, GJ_2')
EA = (1 - xi)*EA1 + xi*EA2
EIy = (1 - xi)*EIy1 + xi*EIy2
EIz = (1 - xi)*EIz1 + xi*EIz2
GJ = (1 - xi)*GJ1 + xi*GJ2
EA, EIy, EIz, GJ | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Note that $EI_y$ refers to the stiffness for bending in the $y$-direction, not about the $y$ axis.
Try and simplify results by using the average values where they come up | Ex, Ey, Ez, Gx = symbols('E_x, E_y, E_z, G_x')
def sym_ke():
# Note the order -- y deflections depend on EIz etc
E = Matrix(np.diag([EA, EIz, EIy, GJ]))
integrand = B.T * E * B
ke = integrand.applyfunc(
lambda xxx: l * sympy.integrate(xxx, (xi, 0, 1)).factor() #.subs((EA1+EA2), 2*Ex) #.expand()... | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Special case: uniform stiffness. | kem.subs({EA1: Ex, EA2: Ex, EIy1: Ey, EIy2: Ey, EIz1: Ez, EIz2: Ez}) | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
This is the same as Rao2004 p.326
Stress stiffening
Now derive the stress stiffening (e.g. centrifugal stiffening) matrix. Ref Cook1989.
Need the matrix $\boldsymbol{G}$ such that
$$
\begin{bmatrix} u_{,x} \ v_{,x} \ w_{,x} \ \end{bmatrix} = \boldsymbol{Gq}
$$ | # G = Matrix(np.zeros((3, 12)))
# G[0, :] = S[0, :].diff(xi, 1) / l
# G[1, :] = S[1, :].diff(xi, 1) / l
# G[2, :] = S[2, :].diff(xi, 1) / l
G = S[:3, :].diff(xi, 1) / l
G.simplify()
G[:, :6]
G[:, 6:]
def sym_ks_axial_force():
# Unit axial force (absorbing area from integral), block matrix 3 times
#smat3 = Mat... | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
This agrees with Cook1989, p.434, for the transverse directions.
Generalised forces
Define the force distribution (linear): | fx1, fx2, fy1, fy2, fz1, fz2 = symbols('f_x1, f_x2, f_y1, f_y2, f_z1, f_z2')
fx = (1 - xi)*fx1 + xi*fx2
fy = (1 - xi)*fy1 + xi*fy2
fz = (1 - xi)*fz1 + xi*fz2
f = Matrix([fx, fy, fz])
f
# Shape functions for applied force -- linear
SF = Matrix(np.zeros((3, 12)))
SF[0, 0 ] = x2 # x
SF[0, 6 ] = xi
S... | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
First shape integral for applied forces: | shape_integral_F1 = SF.applyfunc(
lambda xxx: l * sympy.integrate(xxx, (xi, 0, 1)).expand().simplify()
)
shape_integral_F1 | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Second shape integral for applied forces: | shape_integral_F2 = [
[l * (S[i, :].T * SF[j, :]).applyfunc(
lambda xxx: sympy.integrate(xxx, (xi, 0, 1)).expand().simplify())
for j in range(3)]
for i in range(3)
] | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
The generalised nodal forces are given by the trace of this (the other parts of it are used to find the moments on the whole body directly...): | F = shape_integral_F2[0][0] + shape_integral_F2[1][1] + shape_integral_F2[2][2] | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Special case -- constant force: | F * Matrix([fx1, fy1, fz1, 0, 0, 0, fx1, fy1, fz1, 0, 0, 0]) | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Another example -- a uniform distributed force in the z direction: | F * Matrix([0, 0, fz1, 0, 0, 0, 0, 0, fz1, 0, 0, 0]) / (l/12*fz1) | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Output
Write a Python file with functions to calculate all of these: | def numpy_array_str(expr):
return str(expr) \
.replace('Matrix([', 'array([\n') \
.replace('], [', '],\n[') \
.replace(']])', ']\n])')
def numpy_array_str_2x2(arr):
return ',\n'.join(['[{}]'.format(',\n'.join([numpy_array_str(arr[i][j])
... | theory/FE element matrices.ipynb | ricklupton/beamfe | mit |
Peak finding
Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should:
Properly handle local maxima at the endpoints of the input array.
Return a Numpy array of integer indices.
Handle any Python iterable as input. | def find_peaks(a):
"""Find the indices of the local maxima in a sequence."""
a = np.array(a)
s = np.sign(np.diff(a))
d = np.diff(s)
ind = [i for i in range(len(d)) if d[i] == 2]
if s[-1] == 1:
ind.append(len(a)-1)
return(np.array(ind))
p1 = find_peaks([2,0,1,0,2,0,1])
assert... | assignments/assignment07/AlgorithmsEx02.ipynb | aschaffn/phys202-2015-work | mit |
Here is a string with the first 10000 digits of $\pi$ (after the decimal). Write code to perform the following:
Convert that string to a Numpy array of integers.
Find the indices of the local maxima in the digits of $\pi$.
Use np.diff to find the distances between consequtive local maxima.
Visualize that distribution ... | from sympy import pi, N
pi_digits_str = str(N(pi, 10001))[2:]
pi_int = np.array(list(pi_digits_str), dtype="int")
pks = find_peaks(pi_int)
pks_diff = np.diff(pks)
plt.hist(pks_diff, bins = range(0,max(pks_diff)+1))
min(pks_diff), max(pks_diff)
pks
assert True # use this for grading the pi digits histogram | assignments/assignment07/AlgorithmsEx02.ipynb | aschaffn/phys202-2015-work | mit |
This is an iPython Notebook. You can write whatever Python code you like here - output like the print will be shown below the cell, and the final result is also shown (the result of a + 200).
Note - your Python code is running on a server I've set up (which has everything you need), not on your local machine.
Exercise ... | %matplotlib inline
import dlt
import numpy as np
import chainer as C | examples/Intro.ipynb | DouglasOrr/DeepLearnTute | mit |
Now we'll learn how to use these libraries to create deep learning functions (later, in the full tutorial, we'll use this to train a handwriting recognizer).
Here are two ways to create a numpy array: | a = np.array([1, 2, 3, 4, 5], dtype=np.int32)
print("a =", a)
print("a.shape =", a.shape)
print()
b = np.zeros((2, 3), dtype=np.float32)
print("b =", b)
print("b.shape =", b.shape) | examples/Intro.ipynb | DouglasOrr/DeepLearnTute | mit |
A np.array is a multidimensional array - a very flexible thing, it can be:
- 0-dimensional (a number, like 5)
- 1-dimensional (a vector, like a above)
- 2-dimensional (a matrix, like b above)
- N-dimensional (...)
It can also contain either whole numbers (np.int32) or real numbers (np.float32).
OK, I've done a bit ... | # EXERCISE
# 1. an array scalar containing the integer 5
# 2. a (10, 20) array of zeros
# 3. a (3, 3) array of different numbers (hint: use a list-of-lists)
| examples/Intro.ipynb | DouglasOrr/DeepLearnTute | mit |
Now we just need a few ways of working with these arrays - here are some examples of things that you can do: | x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
print("x =\n%s" % x)
print()
# Indexing
print("x[0, 1] =", x[0, 1]) # 0th row, 1st column
print("x[1, 1] =", x[1, 1]) # 1st row, 1st column
print()
# Slicing
print("x[0, :] =", x[0, :]) # 0th row, all columns
print("x[:, 2] =", x[:, 2]) # 2nd column, all rows
print... | examples/Intro.ipynb | DouglasOrr/DeepLearnTute | mit |
I won't explain all of this in detail, but have a play around with arrays, see what you can do with the above operations.
Exercise - try to use your numpy operations to find the following with M: | M = np.arange(900, dtype=np.float32).reshape(45, 20)
print(M.shape)
# EXERCISE
# 1. print out row number 0 (hint, it should be shape (20,))
# 2. print out row number 34
# 3. select column 15, print out the shape
# 4. select rows 30-40 inclusive, columns 5-8 inclusive, print out the shape (hint: should be (11, 4))
| examples/Intro.ipynb | DouglasOrr/DeepLearnTute | mit |
2. Chainer
We'll use numpy to get data in & out of Chainer, which is our deep learning library, but Chainer will do most of the data processing.
Here is how you get some data into Chainer, use a linear operation to change its shape, and get the result back out again: | a = C.Variable(np.zeros((10, 20), dtype=np.float32))
print("a.data.shape =", a.data.shape)
transformation = C.links.Linear(20, 30)
b = transformation(a)
print("b.data.shape =", b.data.shape)
c = C.functions.tanh(b)
print("c.data.shape =", c.data.shape) | examples/Intro.ipynb | DouglasOrr/DeepLearnTute | mit |
This may not seem particularly special, but this is the heart of a deep learning function. Take an input array, make various transformations that mess around with the shape, and produce an output array.
Some concepts:
- A Variable holds an array - this is some data going through the function
- A Link contains some pa... | # EXERCISE
# 1. Create an array, shape (2, 3) of various float numbers, put it in a variable
a = None # your array here
# 2. Print out tanh(a) (for the whole array)
# 3. Create a linear link of shape (3, 5) - this means it takes (N, 3) and produces (N, 5)
mylink = None # your link here
# 4. Use your link to transfor... | examples/Intro.ipynb | DouglasOrr/DeepLearnTute | mit |
If you can do all of this, you're ready to create a deep learning function.
In the last step, you may have noticed something interesting - the parameters inside the link change every time it is re-created. This is because deep learning functions start off random! Random functions don't sound too useful, so later we're ... | log = dlt.Log()
for i in range(100):
# The first argument "loss" says which plot to put the value on
# The second argument "train" gives it a name on that plot
# The third argument is the y-value
log.add("loss", "train", i)
log.add("loss", "valid", 2 * i)
log.show() | examples/Intro.ipynb | DouglasOrr/DeepLearnTute | mit |
Fitting Lines to Data
We'll cover very basic line fitting, largely ignoring the subtleties of the statistics in favor of showing you how to perform simple fits of models to data. | # These import commands set up the environment so we have access to numpy and pylab functions
import numpy as np
import pylab as pl
# Data Fitting
# First, we'll generate some fake data to use
x = np.linspace(0,10,50) # 50 x points from 0 to 10
# Remember, you can look at the help for linspace too:
# help(np.linspace... | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
y.size is the number of elements in y, just like len(y) or, in IDL, n_elements(y) | # We can add arrays in python just like in IDL
noisy_flux = y + noise
# We'll plot it too, but this time without any lines
# between the points, and we'll use black dots
# ('k' is a shortcut for 'black', '.' means 'point')
pl.clf() # clear the figure
pl.plot(x,noisy_flux,'k.')
# We need labels, of course
pl.xlabel("Tim... | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Now we're onto the fitting stage.
We're going to fit a function of the form
$$y = mx + b$$
which is the same as
$$f(x) = p[1]x + p[0]$$
to the data.
This is called "linear regression", but it is also a special case of a more
general concept: this is a first-order polynomial.
"First Order" means that the highest exponen... | # We'll use polyfit to find the values of the coefficients. The third
# parameter is the "order"
p = np.polyfit(x,noisy_flux,1)
# help(polyfit) if you want to find out more
# print our fit parameters. They are not exact because there's noise in the data!
# note that this is an array!
print p
print type(p) # you can ... | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Let's do the same thing with a noisier data set. I'm going to leave out most of the comments this time. | noisy_flux = y+noise*10
p = polyfit(x,noisy_flux,1)
print p
# plot it
pl.clf() # clear the figure
pl.plot(x,noisy_flux,'k.') # repeated from above
pl.plot(x,np.polyval(p,x),'r-',label="Best fit") # A red solid line
pl.plot(x,2.5*x+1.2,'b--',label="Input") # a blue dashed line showing the REAL line
pl.legend(loc='best'... | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Despite the noisy data, our fit is still pretty good! One last plotting trick, then we'll move on. | pl.clf() # clear the figure
pl.errorbar(x,noisy_flux,yerr=10,marker='.',color='k',linestyle='none') # errorbar requires some extras to look nice
pl.plot(x,np.polyval(p,x),'r-',label="Best fit") # A red solid line
pl.plot(x,2.5*x+1.2,'b--',label="Input") # a blue dashed line showing the REAL line
pl.legend(loc='best') #... | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Curve Fitting
We'll now move on to more complicated curves. What if the data looks more like a sine curve? We'll create "fake data" in basically the same way as above. | # this time we want our "independent variable" to be in radians
x = np.linspace(0,2*np.pi,50)
y = np.sin(x)
pl.clf()
pl.plot(x,y)
# We'll make it noisy again
noise = pl.randn(y.size)
noisy_flux = y + noise
pl.plot(x,noisy_flux,'k.') # no clear this time | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
That looks like kind of a mess. Let's see how well we can fit it.
The function we're trying to fit has the form:
$$f(x) = A * sin(x - B)$$
where $A$ is a "scale" parameter and $B$ is the side-to-side offset (or the "delay" if the x-axis is time). For our data, they are $A=1$ and $B=0$ respectively, because we made $y... | # curve_fit is the function we need for this, but it's in another package called scipy
from scipy.optimize import curve_fit
# we need to know what it does:
help(curve_fit) | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Look at the returns:
Returns
-------
popt : array
Optimal values for the parameters so that the sum of the squared error
of ``f(xdata, *popt) - ydata`` is minimized
pcov : 2d array
The estimated covariance of popt. The diagonals provide the variance
of the parameter estimate.
So the first set of retur... | def sinfunc(x,a,b):
return a*np.sin(x-b)
fitpars, covmat = curve_fit(sinfunc,x,noisy_flux)
# The diagonals of the covariance matrix are variances
# variance = standard deviation squared, so we'll take the square roots to get the standard devations!
# You can get the diagonals of a 2D array easily:
variances = covma... | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Again, this is pretty good despite the noisiness.
Fitting a Power Law
Power laws occur all the time in physis, so it's a good idea to learn how to use them.
What's a power law? Any function of the form:
$$f(t) = a t^b$$
where $x$ is your independent variable, $a$ is a scale parameter, and $b$ is the exponent (the powe... | t = np.linspace(0.1,10)
a = 1.5
b = 2.5
z = a*t**b
pl.clf()
pl.plot(t,z)
# Change the variables
# np.log is the natural log
y = np.log(z)
x = np.log(t)
pl.clf()
pl.plot(x,y)
pl.ylabel("log(z)")
pl.xlabel("log(t)") | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
It's a straight line. Now, for our "fake data", we'll add the noise before transforming from "linear" to "log" space | noisy_z = z + pl.randn(z.size)*10
pl.clf()
pl.plot(t,z)
pl.plot(t,noisy_z,'k.')
noisy_y = np.log(noisy_z)
pl.clf()
pl.plot(x,y)
pl.plot(x,noisy_y,'k.')
pl.ylabel("log(z)")
pl.xlabel("log(t)") | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Note how different this looks from the "noisy line" we plotted earlier. Power laws are much more sensitive to noise! In fact, there are some data points that don't even show up on this plot because you can't take the log of a negative number. Any points where the random noise was negative enough that the curve dropp... | print noisy_y
# try to polyfit a line
pars = np.polyfit(x,noisy_y,1)
print pars | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
In order to get around this problem, we need to mask the data. That means we have to tell the code to ignore all the data points where noisy_y is nan.
My favorite way to do this is to take advantage of a curious fact: $1=1$, but nan!=nan | print 1 == 1
print np.nan == np.nan | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
So if we find all the places were noisy_y != noisy_y, we can get rid of them. Or we can just use the places where noisy_y equals itself. | OK = noisy_y == noisy_y
print OK | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
This OK array is a "boolean mask". We can use it as an "index array", which is pretty neat. | print "There are %i OK values" % (OK.sum())
masked_noisy_y = noisy_y[OK]
masked_x = x[OK]
print "masked_noisy_y has length",len(masked_noisy_y)
# now polyfit again
pars = np.polyfit(masked_x,masked_noisy_y,1)
print pars
# cool, it worked. But the fit looks a little weird!
fitted_y = polyval(pars,x)
pl.plot(x, fitted... | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
The noise seems to have affected our fit. | # Convert bag to linear-space to see what it "really" looks like
fitted_z = np.exp(fitted_y)
pl.clf()
pl.plot(t,z)
pl.plot(t,noisy_z,'k.')
pl.plot(t,fitted_z,'r--')
pl.xlabel('t')
pl.ylabel('z') | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
That's pretty bad. A "least-squares" approach, as with curve_fit, is probably going to be the better choice. However, in the absence of noise (i.e., on your homework), this approach should work | def powerlaw(x,a,b):
return a*(x**b)
pars,covar = curve_fit(powerlaw,t,noisy_z)
pl.clf()
pl.plot(t,z)
pl.plot(t,noisy_z,'k.')
pl.plot(t,powerlaw(t,*pars),'r--')
pl.xlabel('t')
pl.ylabel('z') | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Tricks with Arrays
We need to cover a few syntactic things comparing IDL and python.
In IDL, if you wanted the maximum value in an array, you would do:
maxval = max(array, location_of_max)
In python, it's more straightforward:
location_of_max = array.argmax()
or
location_of_max = np.argmax(array)
Now, say we want to... | # sin(x) is already defined
def sin2x(x):
""" sin^2 of x """
return np.sin(x)**2
def sin3x(x):
""" sin^3 of x """
return np.sin(x)**3
def sincos(x):
""" sin(x)*cos(x) """
return np.sin(x)*np.cos(x)
list_of_functions = [np.sin, sin2x, sin3x, sincos]
# we want 0-2pi for these functions
t = np.lin... | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
Further info on IPython Notebooks
| Overview | link |
|--------------------------------------|------------------------------------------------------------------------------------|
| Blog of IPython creator ... | from IPython.display import YouTubeVideo
YouTubeVideo("xe_ATRmw0KM", width=600, height=400, theme="light", color="blue")
from IPython.display import YouTubeVideo
YouTubeVideo("zG8FYPFU9n4", width=600, height=400, theme="light", color="blue") | howto/00-intro_ipython.ipynb | vkuznet/rep | apache-2.0 |
1. I want to make sure my Plate ID is a string. Can't lose the leading zeroes! | df.dtypes #dtype: Data type for data or columns
print("The data type is",(type(df['Plate ID'][0]))) | homework 11/11-homework-data/.ipynb_checkpoints/zhao_shengying_homework 11-checkpoint.ipynb | sz2472/foundations-homework | mit |
2. I don't think anyone's car was built in 0AD. Discard the '0's as NaN. | df['Vehicle Year'] = df['Vehicle Year'].replace("0","NaN") #str.replace(old, new[, max])
df.head() | homework 11/11-homework-data/.ipynb_checkpoints/zhao_shengying_homework 11-checkpoint.ipynb | sz2472/foundations-homework | mit |
3. I want the dates to be dates! Read the read_csv documentation to find out how to make pandas automatically parse dates. | # Function to use for converting a sequence of string columns to an array of datetime instances: dateutil.parser.parser
type(df['Issue Date'][0])
def to_dates(date):
yourdate = dateutil.parser.parse(date)
return yourdate
df['Issue Date Converted'] = df['Issue Date'].apply(to_dates) #DataFrame.apply(func):fun... | homework 11/11-homework-data/.ipynb_checkpoints/zhao_shengying_homework 11-checkpoint.ipynb | sz2472/foundations-homework | mit |
4. "Date first observed" is a pretty weird column, but it seems like it has a date hiding inside. Using a function with .apply, transform the string (e.g. "20140324") into a Python date. Make the 0's show up as NaN. | df['Date First Observed'].tail()
import numpy as np #numpy object
def pydate(num):
num = str(num) #to work with dateutil.parser.parse():it has to be a string
print(num)
if num == "0":
print("replacing 0")
return np.NaN #if number==0,replace 0 with NaN
else:
print("parsing date")... | homework 11/11-homework-data/.ipynb_checkpoints/zhao_shengying_homework 11-checkpoint.ipynb | sz2472/foundations-homework | mit |
5. "Violation time" is... not a time. Make it a time. | df['Violation Time'].head()
type(df['Violation Time'][0])
def str_to_time(time_str):
s = str(time_str).replace("P"," PM").replace("A"," AM") #str(time_str) because str.replace()
x = s[:2] + ":" + s[2:]
return x
str_to_time("1239P")
df['Violation Time Converted'] = df['Violation Time'].apply(str_to_time)... | homework 11/11-homework-data/.ipynb_checkpoints/zhao_shengying_homework 11-checkpoint.ipynb | sz2472/foundations-homework | mit |
Load and check data | base = os.path.join('gsc-dsnn-2019-10-11-G-reproduce')
exps = [
os.path.join(base, exp) for exp in [
# 'gsc-Static',
'gsc-SET',
'gsc-WeightedMag',
]
]
paths = [os.path.expanduser("~/nta/results/{}".format(e)) for e in exps]
df = load_many(paths)
# replace hebbian prine
df['hebbian_prun... | projects/archive/dynamic_sparse/notebooks/mcaporale/2019-10-10-ExperimentAnalysis-GSCSparser.ipynb | mrcslws/nupic.research | agpl-3.0 |
## Analysis
Experiment Details | # Did any trials failed?
df[df["epochs"]<30]["epochs"].count()
# Removing failed or incomplete trials
df_origin = df.copy()
df = df_origin[df_origin["epochs"]>=30]
df.shape
# which ones failed?
# failed, or still ongoing?
df_origin['failed'] = df_origin["epochs"]<30
df_origin[df_origin['failed']]['epochs']
# helper... | projects/archive/dynamic_sparse/notebooks/mcaporale/2019-10-10-ExperimentAnalysis-GSCSparser.ipynb | mrcslws/nupic.research | agpl-3.0 |
Does improved weight pruning outperforms regular SET | agg(['model'])
agg(['on_perc'])
def model_name(row):
if row['model'] == 'DSNNWeightedMag':
return 'DSNN'
elif row['model'] == 'SET':
return 'SET'
elif row['model'] == 'SparseModel':
return 'Static'
assert False, "This should cover all cases. Got {} h - {} w - {}".fo... | projects/archive/dynamic_sparse/notebooks/mcaporale/2019-10-10-ExperimentAnalysis-GSCSparser.ipynb | mrcslws/nupic.research | agpl-3.0 |
Product of 4 consecutive numbers is always 1 less than a perfect square
<p>
<center>Shubhanshu Mishra (<a href="https://shubhanshu.com">shubhanshu.com</a>)</center>
 +1
consecutive_nums = np.stack([
np.roll(nums, -i)
for i in range(i_max)
], axis=1)[:-i_max+1]
n_prods = consecutive_nums.prod(axis=1)
df = pd.DataFrame(consecutive_nums, columns=[f"n{i+1}" for i in range(i_max)])
df["prod"] = n_prods
df["k"] = np.sqrt(n_prods+1).astype(int)
df[... | Slide Notebooks/Product of consecutive numbers.ipynb | napsternxg/ipython-notebooks | apache-2.0 |
Let us look at the right hand side of the equation first, i.e. $k^2 - 1$.
This can be rewritten as $\textbf{(k-1)*(k+1)}$
Now, this is where a hint lies.
What the right hand side means that it is a product of two integers ($k-1$ and $k+1$) which differ by 2.
We can see that this is the case:
$
\begin{equation}
(k+1) -... | df["k = n^2 + 3n + 1"] = (df["n1"]**2 + 3*df["n1"] + 1)
df
fig, ax = plt.subplots(1,3, figsize=(12, 6))
ax[0].plot("n1", "prod", "bo-", data=df)
ax[0].set_xlabel("n", fontsize=20)
ax[0].set_ylabel(f"$y = \prod_{{i=0}}^{{i={i_max}}} (n+i)$", fontsize=20)
ax[1].plot(df["k"], df["prod"], "ko-")
ax[1].set_xlabel("$k = \... | Slide Notebooks/Product of consecutive numbers.ipynb | napsternxg/ipython-notebooks | apache-2.0 |
More videos to come
<p>
<center>Shubhanshu Mishra (<a href="https://shubhanshu.com">shubhanshu.com</a>)</center>
 
... | fig, ax = plt.subplots(1,3, figsize=(12, 6))
fig.patch.set_facecolor('white')
ax[0].plot("n1", "prod", "bo-", data=df)
ax[0].set_xlabel("n", fontsize=20)
ax[0].set_ylabel(f"$y = \prod_{{i=0}}^{{i={i_max}}} (n+i)$", fontsize=20)
ax[1].plot(df["k"], df["prod"], "ko-")
ax[1].set_xlabel("$k = \sqrt{y + 1}$", fontsize=20... | Slide Notebooks/Product of consecutive numbers.ipynb | napsternxg/ipython-notebooks | apache-2.0 |
Related works
P. Erdรถs. J. L. Selfridge. "The product of consecutive integers is never a power." Illinois J. Math. 19 (2) 292 - 301, June 1975. https://doi.org/10.1215/ijm/1256050816
Visual Proof | nums = np.arange(10,10+4)
A = np.zeros((nums[0], nums[-1]))
A[:, nums[0]:] = 1
sns.heatmap(A, linewidth=2, cbar=False, vmin=0, vmax=4)
nums = np.arange(10,10+4)
A = np.zeros((nums[1], nums[2]))
A[:, nums[0]:] = 2
A[nums[0]:, :] = 3
A[nums[0]:, nums[0]:] = 1
sns.heatmap(A, linewidth=2, cbar=False, vmin=0, vmax=4)
imp... | Slide Notebooks/Product of consecutive numbers.ipynb | napsternxg/ipython-notebooks | apache-2.0 |
Server Local : Runing soun local area.
Program Python | # !/usr/bin/python2
import time
import BaseHTTPServer
import os
import random
import string
import requests
from urlparse import parse_qs, urlparse
HOST_NAME = '0.0.0.0'
PORT_NUMBER = 9999
# A variรกvel MP3_DIR serรก construida tendo como base o diretรณrio HOME do usuรกrio + Music/Campainha
# (e.g: /home/usuario/Music/... | dev/checkpoint/2017-05-25-estevesdouglas-compartilhando-notebook.ipynb | EstevesDouglas/UNICAMP-FEEC-IA369Z | gpl-3.0 |
Export database from dashaboard about device IoT
Arquivo csv | import numpy as np
import csv
with open('database.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print ', '.join(row) | dev/checkpoint/2017-05-25-estevesdouglas-compartilhando-notebook.ipynb | EstevesDouglas/UNICAMP-FEEC-IA369Z | gpl-3.0 |
Method
Conclusion | References | dev/checkpoint/2017-05-25-estevesdouglas-compartilhando-notebook.ipynb | EstevesDouglas/UNICAMP-FEEC-IA369Z | gpl-3.0 |
์๋ฃ ์๋ด: ์ฌ๊ธฐ์ ๋ค๋ฃจ๋ ๋ด์ฉ์ ์๋ ์ฌ์ดํธ์ ๋ด์ฉ์ ์ฐธ๊ณ ํ์ฌ ์์ฑ๋์์.
https://github.com/rouseguy/intro2stats
์๋ด์ฌํญ
์ค๋ ๋ค๋ฃจ๋ ๋ด์ฉ์ pandas ๋ชจ๋์ ์๊ฐ ์ ๋๋ก ์ดํดํ๊ณ ๋์ด๊ฐ ๊ฒ์ ๊ถ์ฅํ๋ค.
์๋ ๋ด์ฉ์ ์์
์ ์คํ๋ ๋์ํธ์ง์ ๋ด๊ธด ๋ฐ์ดํฐ๋ฅผ ๋ถ์ํ์ฌ ํ๊ท ๋ฑ์ ์ด๋ป๊ฒ ๊ตฌํ๋๊ฐ๋ฅผ ์๊ณ ์๋ค๋ฉด ์ด๋ ต์ง ์๊ฒ ์ดํดํ ์ ์๋ ๋ด์ฉ์ด๋ค. ์ฆ, ๋ํ์ด์ ์ด๋ ์ด์ ๋ํ ๊ธฐ์ด์ง์๊ณผ ์์
์ ๋ํ ๊ธฐ์ด์ง์์ ํ์ฉํ๋ฉด ๋ด์ฉ์ ๊ธฐ๋ณธ์ ์ผ๋ก ์ดํดํ ์ ์์ ๊ฒ์ด๋ค.
์ข ๋ ์์ธํ ์ค๋ช
์ด ์๊ตฌ๋๋ค๋ฉด ์๋ ์ฌ์ดํธ์ ์ค๋ช
์ ๋ฏธ๋ฆฌ ์ฝ์ผ๋ฉด ์ข๋ค(5.2... | import numpy as np
import pandas as pd
from datetime import datetime as dt
from scipy import stats | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
๋ฐ์ดํฐ ๋ถ๋ฌ์ค๊ธฐ ๋ฐ ์ฒ๋ฆฌ
์ค๋ ์ฌ์ฉํ ๋ฐ์ดํฐ๋ ๋ค์๊ณผ ๊ฐ๋ค.
๋ฏธ๊ตญ 51๊ฐ ์ฃผ(State)๋ณ ๋ด๋ฐฐ(์๋ฌผ) ๋๋งค๊ฐ๊ฒฉ ๋ฐ ํ๋งค์ผ์: Weed_price.csv
์๋ ๊ทธ๋ฆผ์ ๋ฏธ๊ตญ์ ์ฃผ๋ณ ๋ด๋ฐฐ(์๋ฌผ) ํ๋งค ๋ฐ์ดํฐ๋ฅผ ๋ด์ Weed_Price.csv ํ์ผ๋ฅผ ์์
๋ก ์ฝ์์ ๋์ ์ผ๋ถ๋ฅผ ๋ณด์ฌ์ค๋ค.
์ค์ ๋ฐ์ดํฐ๋์ 22899๊ฐ์ด๋ฉฐ, ์๋ ๊ทธ๋ฆผ์๋ 5๊ฐ์ ๋ฐ์ดํฐ๋ง์ ๋ณด์ฌ์ฃผ๊ณ ์๋ค.
* ์ฃผ์: 1๋ฒ์ค์ ํ
์ด๋ธ์ ์ด๋ณ ๋ชฉ๋ก(column names)์ ๋ด๊ณ ์๋ค.
* ์ด๋ณ ๋ชฉ๋ก: State, HighQ, HighQN, MedQ, MedQN, LowQ, LowQN, date
<p>
<tab... | prices_pd = pd.read_csv("data/Weed_Price.csv", parse_dates=[-1]) | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
read_csv ํจ์์ ๋ฆฌํด๊ฐ์ DataFrame ์ด๋ผ๋ ์๋ฃํ์ด๋ค. | type(prices_pd) | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
DataFrame ์๋ฃํ
์์ธํ ์ค๋ช
์ ๋ค์ ์๊ฐ์ ์ถ๊ฐ๋ ๊ฒ์. ์ฐ์ ์ ์๋ ์ฌ์ดํธ๋ฅผ ์ฐธ์กฐํ ์ ์๋ค๋ ์ ๋๋ง ์ธ๊ธํจ.
(5.2์ ๋ด์ฉ๊น์ง๋ฉด ์ถฉ๋ถํจ)
http://sinpong.tistory.com/category/Python%20for%20data%20analysis
DataFrame ์๋ฃํ๊ณผ ์์
์ ์คํ๋ ๋์ํธ ๋น๊ตํ๊ธฐ
๋ถ๋ฌ ๋ค์ธ Weed_Price.csv ํ์ผ์ ์์ ๋ค์ฏ ์ค์ ํ์ธํด๋ณด๋ฉด, ์์ ์์
ํ์ผ ๊ทธ๋ฆผ์์ ๋ณธ ๋ด์ฉ๊ณผ ์ผ์นํ๋ค.
๋ค๋ง, ํ๊ณผ ์ด์ ๋ชฉ๋ก์ด ์กฐ๊ธ ๋ค๋ฅผ ๋ฟ์ด๋ค.
* ์์
์์๋ ์ด ๋ชฉ๋ก์ด A, B, C, ..., H๋ก ๋์ด ์์ผ๋ฉฐ, ์์ค ํ์ผ์ ... | prices_pd.head() | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ธ์๋ฅผ ์ฃผ๋ฉด ์ํ๋ ๋งํผ ๋ณด์ฌ์ค๋ค. | prices_pd.head(10) | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
ํ์ผ์ด ๋งค์ฐ ๋ง์ ์์ ๋ฐ์ดํฐ๋ฅผ ํฌํจํ๊ณ ์์ ๊ฒฝ์ฐ, ๋งจ ๋ท์ชฝ ๋ถ๋ถ์ ํ์ธํ๊ณ ์ถ์ผ๋ฉด
tail ๋ฉ์๋๋ฅผ ํ์ฉํ๋ค. ์ฌ์ฉ๋ฒ์ head ๋ฉ์๋์ ๋์ผํ๋ค.
์๋ ๋ช
๋ น์ด๋ฅผ ํตํด Weed_Price.csv ํ์ผ์ 22899๊ฐ์ ๋ฐ์ดํฐ๊ฐ ์ ์ฅ๋์ด ์์์ ํ์ธํ ์ ์๋ค. | prices_pd.tail() | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
๊ฒฐ์ธก์น ์กด์ฌ ์ฌ๋ถ
์ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด LowQ ๋ชฉ๋ก์ NaN ์ด๋ผ๋ ๊ธฐํธ๊ฐ ํฌํจ๋์ด ์๋ค. NaN์ Not a Number, ์ฆ, ์ซ์๊ฐ ์๋๋ค๋ผ๋ ์๋ฏธ์ด๋ฉฐ, ๋ฐ์ดํฐ๊ฐ ์ ์ด๋ถํฐ ์กด์ฌํ์ง ์์๊ฑฐ๋ ๋๋ฝ๋์์์ ์๋ฏธํ๋ค.
DataFrame์ dtypes
DataFrame ์๋ฃํ์ dtypes ์์ฑ์ ์ด์ฉํ๋ฉด ์ด๋ณ ๋ชฉ๋ก์ ์ฌ์ฉ๋ ์๋ฃํ์ ํ์ธํ ์ ์๋ค.
Weed_Price.csv ํ์ผ์ ์ฝ์ด ๋ค์ธ prices_pd ๋ณ์์ ์ ์ฅ๋ DataFrame ๊ฐ์ ์ด๋ณ ๋ชฉ๋ก์ ์ฌ์ฉ๋ ์๋ฃํ์ ๋ณด์ฌ์ค๋ค.
์ฃผ์:
* numpy์ array ์๋ฃํ์ dtype ์์ฑ์ ํ๋์ ์๋ฃํ๋ง์ ๋ด๊ณ ... | prices_pd.dtypes | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ ๋ ฌ ๋ฐ ๊ฒฐ์ธก์น ์ฑ์ฐ๊ธฐ
์ ๋ ฌํ๊ธฐ
์ฃผ๋ณ๋ก, ๋ ์ง๋ณ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ๋ ฌํ๋ค. | prices_pd.sort_values(['State', 'date'], inplace=True) | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
๊ฒฐ์ธก์น ์ฑ์ฐ๊ธฐ
ํ๊ท ์ ๊ตฌํ๊ธฐ ์ํด์๋ ๊ฒฐ์ธก์น(๋๋ฝ๋ ๋ฐ์ดํฐ)๊ฐ ์์ด์ผ ํ๋ค.
์ฌ๊ธฐ์๋ ์ด์ ์ค์ ๋ฐ์ดํฐ๋ฅผ ์ด์ฉํ์ฌ ์ฑ์ฐ๋ ๋ฐฉ์(method='ffill')์ ์ด์ฉํ๋ค.
์ฃผ์: ์์ ์ ๋ ฌ์ ๋จผ์ ํ ์ด์ ๋, ๊ฒฐ์ธก์น๊ฐ ์์ ๊ฒฝ์ฐ ๊ฐ๋ฅํ๋ฉด ๋์ผํ ์ฃผ(State),
๋น์ทํ ์์ ์์ ๊ฑฐ๋๋ ๊ฐ๊ฒฉ์ ์ฌ์ฉํ๊ณ ์ ํจ์ด๋ค. | prices_pd.fillna(method='ffill', inplace=True) | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ ๋ ฌ๋ ๋ฐ์ดํฐ์ ์ฒซ ๋ถ๋ถ์ ์๋์ ๊ฐ์ด ์๋ผ๋ฐ๋ง(Alabama) ์ฃผ์ ๋ฐ์ดํฐ๋ง ๋ ์ง๋ณ๋ก ์์๋๋ก ๋ณด์ธ๋ค. | prices_pd.head() | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ ๋ ฌ๋ ๋ฐ์ดํฐ์ ๋ ๋ถ๋ถ์ ์๋์ ๊ฐ์ด ์๋ฐ(Wyoming) ์ฃผ์ ๋ฐ์ดํฐ๋ง ๋ ์ง๋ณ๋ก ์์๋๋ก ๋ณด์ธ๋ค.
์ด์ ๊ฒฐ์ธก์น๊ฐ ๋ ์ด์ ์กด์ฌํ์ง ์๋๋ค. | prices_pd.tail() | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
๋ฐ์ดํฐ ๋ถ์ํ๊ธฐ: ํ๊ท (Average)
์บ๋ฆฌํฌ๋์ ์ฃผ๋ฅผ ๋์์ผ๋กํด์ ๋ด๋ฐฐ(์๋ฌผ) ๋๋งค๊ฐ์ ํ๊ท (average)์ ๊ตฌํด๋ณธ๋ค.
ํ๊ท ๊ฐ(Mean)
ํ๊ท ๊ฐ = ๋ชจ๋ ๊ฐ๋ค์ ํฉ์ ๊ฐ๋ค์ ๊ฐ์๋ก ๋๋๊ธฐ
$X$: ๋ฐ์ดํฐ์ ํฌํจ๋ ๊ฐ๋ค์ ๋๋ณํ๋ ๋ณ์
$n$: ๋ฐ์ดํฐ์ ํฌํจ๋ ๊ฐ๋ค์ ๊ฐ์
$\Sigma\, X$: ๋ฐ์ดํฐ์ ํฌํจ๋ ๋ชจ๋ ๊ฐ๋ค์ ํฉ
$$\text{ํ๊ท ๊ฐ}(\mu) = \frac{\Sigma\, X}{n}$$
๋จผ์ ๋ง์คํฌ ์ธ๋ฑ์ค๋ฅผ ์ด์ฉํ์ฌ ์บ๋ฆฌํฌ๋์ ์ฃผ์ ๋ฐ์ดํฐ๋ง ์ถ์ถํด์ผ ํ๋ค. | california_pd = prices_pd[prices_pd.State == "California"].copy(True) | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์บ๋ฆฌํฌ๋์ ์ฃผ์์ ๊ฑฐ๋๋ ์ฒซ 5๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ํ์ธํด๋ณด์. | california_pd.head(20) | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
HighQ ์ด ๋ชฉ๋ก์ ์๋ ๊ฐ๋ค์ ์ดํฉ์ ๊ตฌํด๋ณด์.
์ฃผ์: sum() ๋ฉ์๋ ํ์ฉ์ ๊ธฐ์ตํ๋ค. | ca_sum = california_pd['HighQ'].sum()
ca_sum | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
HighQ ์ด ๋ชฉ๋ก์ ์๋ ๊ฐ๋ค์ ๊ฐ์๋ฅผ ํ์ธํด๋ณด์.
์ฃผ์: count() ๋ฉ์๋ ํ์ฉ์ ๊ธฐ์ตํ๋ค. | ca_count = california_pd['HighQ'].count()
ca_count | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ด์ ์บ๋ฆฌํฌ๋์ ์ฃผ์์ ๊ฑฐ๋๋ HighQ์ ๋ด๋ฐฐ๊ฐ๊ฒฉ์ ํ๊ท ๊ฐ์ ๊ตฌํ ์ ์๋ค. | # ์บ๋ฆฌํฌ๋์ ์ฃผ์์ ๊ฑฐ๋๋ ์ํ(HighQ) ๋ด๋ฐฐ(์๋ฌผ) ๋๋งค๊ฐ์ ํ๊ท ๊ฐ
ca_mean = ca_sum / ca_count
ca_mean | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ค์๊ฐ(Median)
์บ๋ฆฌํฌ๋์ ์ฃผ์์ ๊ฑฐ๋๋ HighQ์ ๋ด๋ฐฐ๊ฐ๊ฒฉ์ ์ค์๊ฐ์ ๊ตฌํ์.
์ค์๊ฐ = ๋ฐ์ดํฐ๋ฅผ ํฌ๊ธฐ ์์ผ๋ก ์ ๋ ฌํ์์ ๋ ๊ฐ์ฅ ๊ฐ์ด๋ฐ์ ์์นํ ์
๋ฐ์ดํฐ์ ํฌ๊ธฐ n์ด ํ์์ผ ๋: $\frac{n+1}{2}$๋ฒ ์งธ ์์นํ ๋ฐ์ดํฐ
๋ฐ์ดํฐ์ ํฌ๊ธฐ n์ด ์ง์์ผ ๋: $\frac{n}{2}$๋ฒ ์งธ์ $\frac{n}{2}+1$๋ฒ ์งธ์ ์์นํ ๋ฐ์ดํฐ๋ค์ ํ๊ท ๊ฐ
์ฌ๊ธฐ์๋ ๋ฐ์ดํฐ์ ํฌ๊ธฐ๊ฐ 449๋ก ํ์์ด๋ค. | ca_count | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
๋ฐ๋ผ์ ์ค์๊ฐ์ $\frac{\text{ca_count}-1}{2}$๋ฒ์งธ์ ์์นํ ๊ฐ์ด๋ค.
์ฃผ์: ์ธ๋ฑ์ค๋ 0๋ถํฐ ์ถ๋ฐํ๋ค. ๋ฐ๋ผ์ ์ค์๊ฐ์ด ํ๋ ์์ผ๋ก ๋น๊ฒจ์ง๋ค. | ca_highq_pd = california_pd.sort_values(['HighQ'])
ca_highq_pd.head() | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ธ๋ฑ์ค ๋ก์ผ์ด์
ํจ์์ธ iloc ํจ์๋ฅผ ํ์ฉํ๋ค.
์ฃผ์: iloc ๋ฉ์๋๋ ์ธ๋ฑ์ค ๋ฒํธ๋ฅผ ์ฌ์ฉํ๋ค.
์ ํ์์ ๋ณด์ฌ์ฃผ๋ ์ธ๋ฑ์ค ๋ฒํธ๋ Weed_Price.csv ํ์ผ์ ์ฒ์ ๋ถ๋ฌ์์ ๋ ์ฌ์ฉ๋ ์ธ๋ฑ์ค ๋ฒํธ์ด๋ค.
ํ์ง๋ง ca_high_pd ์์๋ ์ฐธ๊ณ ์ฌํญ์ผ๋ก ์ฌ์ฉ๋ ๋ฟ์ด๋ฉฐ, iloc ํจ์์ ์ธ์๋ก ๋ค์ด๊ฐ๋ ์ธ๋ฑ์ค๋ ๋ค์ 0๋ถํฐ ์ธ๋ ๊ฒ์ผ๋ก ์์ํ๋ค.
๋ฐ๋ผ์ ์๋ ์ฝ๋์ฒ๋ผ ๊ธฐ์กด์ ์ฐธ๊ณ ์ฉ ์ธ๋ฑ์ค๋ฅผ ์ฌ์ฉํ๋ฉด ์ณ์ ๋ต์ ๊ตฌํ ์ ์๋ค. | # ์บ๋ฆฌํฌ๋์์์ ๊ฑฐ๋๋ ์ํ(HighQ) ๋ด๋ฐฐ(์๋ฌผ) ๋๋งค๊ฐ์ ์ค์๊ฐ
ca_median = ca_highq_pd.HighQ.iloc[int((ca_count-1)/ 2)]
ca_median | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ต๋น๊ฐ(Mode)
์บ๋ฆฌํฌ๋์ ์ฃผ์์ ๊ฑฐ๋๋ HighQ์ ๋ด๋ฐฐ๊ฐ๊ฒฉ์ ์ต๋น๊ฐ์ ๊ตฌํ์.
์ต๋น๊ฐ = ๊ฐ์ฅ ์์ฃผ ๋ฐ์ํ ๋ฐ์ดํฐ
์ฃผ์: value_counts() ๋ฉ์๋ ํ์ฉ์ ๊ธฐ์ตํ๋ค. | # ์บ๋ฆฌํฌ๋์ ์ฃผ์์ ๊ฐ์ฅ ๋น๋ฒํ๊ฒ ๊ฑฐ๋๋ ์ํ(HighQ) ๋ด๋ฐฐ(์๋ฌผ)์ ๋๋งค๊ฐ
ca_mode = ca_highq_pd.HighQ.value_counts().index[0]
ca_mode | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ฐ์ต๋ฌธ์
์ฐ์ต
์ง๊ธ๊น์ง ๊ตฌํ ํ๊ท ๊ฐ, ์ค์๊ฐ, ์ต๋น๊ฐ์ ๊ตฌํ๋ ํจ์๊ฐ ์ด๋ฏธ DataFrame๊ณผ Series ์๋ฃํ์ ๋ฉ์๋๋ก ๊ตฌํ๋์ด ์๋ค.
์๋ ์ฝ๋๋ค์ ์คํํ๋ฉด์ ๊ฐ๊ฐ์ ์ฝ๋์ ์๋ฏธ๋ฅผ ํ์ธํ๋ผ. | california_pd.mean()
california_pd.mean().HighQ
california_pd.median()
california_pd.mode()
california_pd.mode().HighQ
california_pd.HighQ.mean()
california_pd.HighQ.median()
california_pd.HighQ.mode() | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
์ฐ์ต
์บ๋ฆฌํฌ๋์ ์ฃผ์์ 2013๋
, 2014๋
, 2015๋
์ ๊ฑฐ๋๋ HighQ์ ๋ด๋ฐฐ(์๋ฌผ) ๋๋งค๊ฐ๊ฒฉ์ ํ๊ท ์ ๊ฐ๊ฐ ๊ตฌํ๋ผ.
ํํธ: california_pd.iloc[0]['date'].year
๊ฒฌ๋ณธ๋ต์1
2014๋
์ ๊ฑฐ๋๋ ๋๋งค๊ฐ์ ํ๊ท ๊ฐ์ ์๋์ ๊ฐ์ด ๊ณ์ฐํ ์ ์๋ค.
sum ๋ณ์: 2014๋
๋์ ๊ฑฐ๋๋ ๋๋งค๊ฐ์ ์ดํฉ์ ๋ด๋๋ค.
count ๋ณ์: 2014๋
๋์ ๊ฑฐ๋ ํ์๋ฅผ ๋ด๋๋ค. | sum = 0
count = 0
for index in np.arange(len(california_pd)):
if california_pd.iloc[index]['date'].year == 2014:
sum += california_pd.iloc[index]['HighQ']
count += 1
sum/count | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
๊ฒฌ๋ณธ๋ต์2
์๋์ ๊ฐ์ ๋ฐฉ์์ ์ด์ฉํ์ฌ ์ธ๋ฑ์ค ์ ๋ณด๋ฅผ ๊ตฌํ์ฌ ์ฌ๋ผ์ด์ฑ ๊ธฐ๋ฅ์ ํ์ฉํ ์๋ ์๋ค.
์ฌ๋ผ์ด์ฑ์ ํ์ฉํ์ฌ ์ฐ๋๋ณ ํ๊ท ์ ๊ตฌํ๋ ๋ฐฉ์์ ๋ณธ๋ฌธ ๋ด์ฉ๊ณผ ๋์ผํ ๋ฐฉ์์ ๋ฐ๋ฅธ๋ค. | years = np.arange(2013, 2016)
year_starts = [0]
for yr in years:
for index in np.arange(year_starts[-1], len(california_pd)):
if california_pd.iloc[index]['date'].year == yr:
continue
else:
year_starts.append(index)
break
year_starts | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
year_starts์ ๋ด๊ธด ์ซ์๋ค์ ์๋ฏธ๋ ๋ค์๊ณผ ๊ฐ๋ค.
0๋ฒ์ค๋ถํฐ 2013๋
๋ ๊ฑฐ๋๊ฐ ํ์๋๋ค.
5๋ฒ์ค๋ถํฐ 2014๋
๋ ๊ฑฐ๋๊ฐ ํ์๋๋ค.
369๋ฒ์ค๋ถํฐ 2015๋
๋ ๊ฑฐ๋๊ฐ ํ์๋๋ค. | california_pd.iloc[4]
california_pd.iloc[5]
california_pd.iloc[368]
california_pd.iloc[369] | previous/y2017/W09-numpy-averages/GongSu21_Statistics_Averages.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
1. Importing the dependent time series data
In this codeblock a time series of groundwater levels is imported using the read_csv function of pandas. As pastas expects a pandas Series object, the data is squeezed. To check if you have the correct data type (a pandas Series object), you can use type(oseries) as shown bel... | # Import groundwater time seriesm and squeeze to Series object
gwdata = pd.read_csv('../data/head_nb1.csv', parse_dates=['date'],
index_col='date', squeeze=True)
print('The data type of the oseries is: %s' % type(gwdata))
# Plot the observed groundwater levels
gwdata.plot(style='.', figsize=(10, 4... | examples/notebooks/01_basic_model.ipynb | pastas/pastas | mit |
2. Import the independent time series
Two explanatory series are used: the precipitation and the potential evaporation. These need to be pandas Series objects, as for the observed heads.
Important characteristics of these time series are:
- All series are stored as pandas Series objects.
- The series may have irregular... | # Import observed precipitation series
precip = pd.read_csv('../data/rain_nb1.csv', parse_dates=['date'],
index_col='date', squeeze=True)
print('The data type of the precip series is: %s' % type(precip))
# Import observed evaporation series
evap = pd.read_csv('../data/evap_nb1.csv', parse_dates=['... | examples/notebooks/01_basic_model.ipynb | pastas/pastas | mit |
3. Create the time series model
In this code block the actual time series model is created. First, an instance of the Model class is created (named ml here). Second, the different components of the time series model are created and added to the model. The imported time series are automatically checked for missing value... | # Create a model object by passing it the observed series
ml = ps.Model(gwdata, name="GWL")
# Add the recharge data as explanatory variable
sm = ps.StressModel(recharge, ps.Gamma, name='recharge', settings="evap")
ml.add_stressmodel(sm) | examples/notebooks/01_basic_model.ipynb | pastas/pastas | mit |
4. Solve the model
The next step is to compute the optimal model parameters. The default solver uses a non-linear least squares method for the optimization. The python package scipy is used (info on scipy's least_squares solver can be found here). Some standard optimization statistics are reported along with the optim... | ml.solve() | examples/notebooks/01_basic_model.ipynb | pastas/pastas | mit |
5. Plot the results
The solution can be plotted after a solution has been obtained. | ml.plot() | examples/notebooks/01_basic_model.ipynb | pastas/pastas | mit |
6. Advanced plotting
There are many ways to further explore the time series model. pastas has some built-in functionalities that will provide the user with a quick overview of the model. The plots subpackage contains all the options. One of these is the method plots.results which provides a plot with more information. | ml.plots.results(figsize=(10, 6)) | examples/notebooks/01_basic_model.ipynb | pastas/pastas | mit |
7. Statistics
The stats subpackage includes a number of statistical functions that may applied to the model. One of them is the summary method, which gives a summary of the main statistics of the model. | ml.stats.summary() | examples/notebooks/01_basic_model.ipynb | pastas/pastas | mit |
8. Improvement: estimate evaporation factor
In the previous model, the recharge was estimated as precipitation minus potential evaporation. A better model is to estimate the actual evaporation as a factor (called the evaporation factor here) times the potential evaporation. First, new model is created (called ml2 here ... | # Create a model object by passing it the observed series
ml2 = ps.Model(gwdata)
# Add the recharge data as explanatory variable
ts1 = ps.RechargeModel(precip, evap, ps.Gamma, name='rainevap',
recharge=ps.rch.Linear(), settings=("prec", "evap"))
ml2.add_stressmodel(ts1)
# Solve the model
ml2.s... | examples/notebooks/01_basic_model.ipynb | pastas/pastas | mit |
First let us look at what the underdamped spectral density looks like: | def plot_spectral_density():
""" Plot the underdamped spectral density """
w = np.linspace(0, 5, 1000)
J = lam**2 * gamma * w / ((w0**2 - w**2)**2 + (gamma**2) * (w**2))
fig, axes = plt.subplots(1, 1, sharex=True, figsize=(8,8))
axes.plot(w, J, 'r', linewidth=2)
axes.set_xlabel(r'$\omega$',... | examples/heom/heom-1c-spin-bath-model-underdamped-sd.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
The correlation functions are now very oscillatory, because of the Lorentzian peak in the spectral density.
So next, let us plot the correlation functions themselves: | def Mk(t, k, gamma, w0, beta):
""" Calculate the Matsubara terms for a given t and k. """
Om = np.sqrt(w0**2 - (gamma / 2)**2)
Gamma = gamma / 2.
ek = 2 * pi * k / beta
return (
(-2 * lam**2 * gamma / beta) * ek * exp(-ek * abs(t))
/ (((Om + 1.0j * Gamma)**2 + ek**2) * ((Om - 1.... | examples/heom/heom-1c-spin-bath-model-underdamped-sd.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
It is useful to look at what the Matsubara contributions do to this spectral density. We see that they modify the real part around $t=0$: | def plot_matsubara_correlation_function_contributions():
""" Plot the underdamped correlation function. """
t = np.linspace(0, 20, 1000)
M_Nk3 = np.sum([Mk(t, k, gamma=gamma, w0=w0, beta=beta) for k in range(1, 2 + 1)], 0)
M_Nk5 = np.sum([Mk(t, k, gamma=gamma, w0=w0, beta=beta) for k in range(1, 100 + ... | examples/heom/heom-1c-spin-bath-model-underdamped-sd.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Solving for the dynamics as a function of time:
Next we calculate the exponents using the Matsubara decompositions. Here we split them into real and imaginary parts.
The HEOM code will optimize these, and reduce the number of exponents when real and imaginary parts have the same exponent. This is clearly the case for t... | ckAR, vkAR, ckAI, vkAI = underdamped_matsubara_params(lam=lam, gamma=gamma, T=T, nk=Nk) | examples/heom/heom-1c-spin-bath-model-underdamped-sd.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Having created the lists which specify the bath correlation functions, we create a BosonicBath from them and pass the bath to the HEOMSolver class.
The solver constructs the "right hand side" (RHS) determinining how the system and auxiliary density operators evolve in time. This can then be used to solve for dynamics o... | options = Options(nsteps=15000, store_states=True, rtol=1e-14, atol=1e-14)
with timer("RHS construction time"):
bath = BosonicBath(Q, ckAR, vkAR, ckAI, vkAI)
HEOMMats = HEOMSolver(Hsys, bath, NC, options=options)
with timer("ODE solver time"):
resultMats = HEOMMats.run(rho0, tlist)
plot_result_expect... | examples/heom/heom-1c-spin-bath-model-underdamped-sd.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
In practice, one would not perform this laborious expansion for the underdamped correlation function, because
QuTiP already has a class, UnderDampedBath, that can construct this bath for you. Nevertheless, knowing how
to perform this expansion will allow you to construct your own baths for other spectral densities.
Bel... | # Compare to built-in under-damped bath:
with timer("RHS construction time"):
bath = UnderDampedBath(Q, lam=lam, gamma=gamma, w0=w0, T=T, Nk=Nk)
HEOM_udbath = HEOMSolver(Hsys, bath, NC, options=options)
with timer("ODE solver time"):
result_udbath = HEOM_udbath.run(rho0, tlist) #normal 115
plot_result_e... | examples/heom/heom-1c-spin-bath-model-underdamped-sd.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
We can compare these results to those of the Bloch-Redfield solver in QuTiP: | UD = (
f" 2* {lam}**2 * {gamma} / ( {w0}**4 * {beta}) if (w==0) else"
f" 2* ({lam}**2 * {gamma} * w / (({w0}**2 - w**2)**2 + {gamma}**2 * w**2)) * ((1 / (exp(w * {beta}) - 1)) + 1)"
)
options = Options(nsteps=15000, store_states=True, rtol=1e-12, atol=1e-12)
with timer("ODE solver time"):
resultBR = brmes... | examples/heom/heom-1c-spin-bath-model-underdamped-sd.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Lastly, let us calculate the analytical steady-state result and compare all of the results:
The thermal state of a reaction coordinate (treating the environment as a single damped mode) should, at high temperatures and small gamma, tell us the steady-state: | dot_energy, dot_state = Hsys.eigenstates()
deltaE = dot_energy[1] - dot_energy[0]
gamma2 = gamma
wa = w0 # reaction coordinate frequency
g = lam / np.sqrt(2 * wa) # coupling
NRC = 10
Hsys_exp = tensor(qeye(NRC), Hsys)
Q_exp = tensor(qeye(NRC), Q)
a = tensor(destroy(NRC), qeye(2))
H0 = wa * a.dag() * a + Hsys_exp
... | examples/heom/heom-1c-spin-bath-model-underdamped-sd.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Hooray, we did it
Now we need to figure out how well it actually did | def get_test_detector_plane(row):
# Find location of nans, get the first one
# Then divide by 6 (6 values per detector plane)
plane = np.where(np.isnan(row.values))[0][0]/6
return int(plane)
def get_vals_at_plane(row, plane):
cols = [i + str(int(plane)) for i in ['x','y','px','py','pz']]
return... | jlab-ml-lunch-2/notebooks/01-Recommender-System.ipynb | BDannowitz/polymath-progression-blog | gpl-2.0 |
Make a recommender class, a la sklearn
Should have fit, predict methods | import logging
from jlab import COLS
from sklearn.preprocessing import StandardScaler
class DetectorRecommender(object):
def __init__(self, k=20):
self.logger = logging.getLogger(__name__)
self.k = k
self.planes = 27
self.kinematics = ["x", "y", "px", "py", "pz"]
... | jlab-ml-lunch-2/notebooks/01-Recommender-System.ipynb | BDannowitz/polymath-progression-blog | gpl-2.0 |
Tune the one hyperparameter we have | for k in range(5,15):
predictor = DetectorRecommender(k=k)
predictor.fit(X_train)
X_pred = predictor.predict(X_test)
print(k, mean_squared_error(X_true, X_pred)) | jlab-ml-lunch-2/notebooks/01-Recommender-System.ipynb | BDannowitz/polymath-progression-blog | gpl-2.0 |
Optimal performance at k=7 | predictor = DetectorRecommender(k=7)
predictor.fit(X_train)
X_pred = predictor.predict(X_test)
print(mean_squared_error(X_true, X_pred)) | jlab-ml-lunch-2/notebooks/01-Recommender-System.ipynb | BDannowitz/polymath-progression-blog | gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.