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> ![Twitter Follow](https://img.shields.io/twitter/follow/TheShubhanshu?style=social) ![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/...
i_max = 4 nums = np.arange(0, 50)+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> ![Twitter Follow](https://img.shields.io/twitter/follow/TheShubhanshu?style=social) ![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCZpSoW1pm0jk-jUaGwVWzLA?style=social) ...
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