markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
We'll need to download our DAGMC geometry and unstructured mesh files. We'll be retrieving those using the function and URLs below.
from IPython.display import display, clear_output import urllib.request manifold_geom_url = 'https://tinyurl.com/rp7grox' # 99 MB manifold_mesh_url = 'https://tinyurl.com/wojemuh' # 5.4 MB def download(url, filename): """ Helper function for retrieving dagmc models """ def progress_hook(count, bl...
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
The model we'll be looking at in this example is a steel piping manifold:
Image("./images/manifold-cad.png", width=800)
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
This is a nice example of a model which would be extremely difficult to model using CSG. To get started, we'll need two files: 1. the DAGMC gometry file on which we'll track particles and 2. a tetrahedral mesh of the piping structure on which we'll score tallies To start, let's create the materials we'll need for...
air = openmc.Material(name='air') air.set_density('g/cc', 0.001205) air.add_element('N', 0.784431) air.add_element('O', 0.210748) air.add_element('Ar',0.0046) steel = openmc.Material(name='steel') steel.set_density('g/cc', 8.0) steel.add_element('Si', 0.010048) steel.add_element('S', 0.00023) steel.add_element('Fe', 0...
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
Now let's download the geometry and mesh files. (This may take some time.)
# get the manifold DAGMC geometry file download(manifold_geom_url, 'dagmc.h5m') # get the manifold tet mesh download(manifold_mesh_url, 'manifold.h5m')
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
Next we'll create a 5 MeV neutron point source at the entrance the single pipe on the low side of the model with
src_pnt = openmc.stats.Point(xyz=(0.0, 0.0, 0.0)) src_energy = openmc.stats.Discrete(x=[5.e+06], p=[1.0]) source = openmc.Source(space=src_pnt, energy=src_energy) settings = openmc.Settings() settings.source = source settings.run_mode = "fixed source" settings.batches = 10 settings.particles = 100
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
And we'll indicate that we're using a CAD-based geometry.
settings.dagmc = True settings.export_to_xml()
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
We'll run a few particles through this geometry to make sure everything is working properly.
openmc.run()
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
Now let's setup the unstructured mesh tally. We'll do this the same way we did in the previous notebook.
unstructured_mesh = openmc.UnstructuredMesh("manifold.h5m") mesh_filter = openmc.MeshFilter(unstructured_mesh) tally = openmc.Tally() tally.filters = [mesh_filter] tally.scores = ['flux'] tally.estimator = 'tracklength' tallies = openmc.Tallies([tally]) tallies.export_to_xml() settings.batches = 200 settings.partic...
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
Again we should see that tally_1.200.vtk file which we can use to visualize our results in VisIt, ParaView, or another tool of your choice that supports VTK files.
!ls *.vtk Image("./images/manifold_flux.png", width="800")
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
For the purpose of this example, we haven't run enough particles to score in all of the tet elements, but we indeed see larger flux values near the source location at the bottom of the model. Visualization with statepoint data It was mentioned in the previous unstructured mesh example that the centroids and volumes of ...
# energy filter with bins from 0 to 1 MeV and 1 MeV to 5 MeV energy_filter = openmc.EnergyFilter((0.0, 1.e+06, 5.e+06)) tally.filters = [mesh_filter, energy_filter] print(tally) print(energy_filter) tallies.export_to_xml() !cat tallies.xml openmc.run(output=False)
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
Noice the warning at the end of the output above indicating that the .vtk file we used before isn't written in this case. Let's open up this statepoint file and get the information we need to create the point cloud data instead. NOTE: You will need the Python vtk module installed to run this part of the notebook.
with openmc.StatePoint("statepoint.200.h5") as sp: tally = sp.tallies[1] umesh = sp.meshes[1] centroids = umesh.centroids mesh_vols = umesh.volumes thermal_flux = tally.get_values(scores=['flux'], filters=[openmc.EnergyFilter], ...
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
We should now see our new flux file in the directory. It can be used to visualize the results in the same way as our other .vtk files.
!ls *.vtk Image("./images/manifold_pnt_cld.png", width=800)
examples/jupyter/unstructured-mesh-part-ii.ipynb
paulromano/openmc
mit
Recap from last week We looked at the basics of Object Oriented Programming, or OOP, last week. If you couldn't make it, don't be concerned because the content from last week won't affect what we will be looking at today. ``` class Human(object): def init(self,name,age,height): self.name = name sel...
# Creating an array of all zeroes np.zeros((3,4),int) print('a. np.zeros((2,2))') a = np.zeros((2,2),int) print(a) print('b. np.ones((1,2))') b = np.ones((1,2)) print(b) print('c. np.full((2,2), 7)') c = np.full((2,2), 7) # Create a constant array print(c) print('d...
lesson6.ipynb
trsherborne/learn-python
mit
In general you can follow the format below for declaring most NumPy arrays np.format(shape, fill_value, dtype) Where shape is declared as a tuple like (3,4) and dtype is the type of the data which is constant across the array but doesn't have to be a number Try replacing int in the declaration of array a with str
# You can also declare NumPy arrays using standard Python # Lists (and Lists of Lists) l1 = [1,2,3,4] l2 = [5,6,7,8] l3 = [9,10,11,12] l = [l1,l2,l3] print(l) l_array = np.array(l) #print(l_array)
lesson6.ipynb
trsherborne/learn-python
mit
Indexing a NumPy array
# For a list of lists we would use the [][] notation upper_left_val = l[0][0] print(upper_left_val) print() # We use a single [] with np and seperate dimensions by , upper_left_val_np = l_array[0,0] print(upper_left_val_np) print() # You can also slice arrays as so print(l_array[0:2,1:3]) print() # And use the shape...
lesson6.ipynb
trsherborne/learn-python
mit
Array mathematics
# Declare two example arrays x = np.array([[1,2],[3,4]], dtype=np.float64) y = np.array([[5,6],[7,8]], dtype=np.float64) # By default, operations are element wise in NumPy # Addition, two options print(x+y) #print(np.add(x,y)) print() # Subtraction print(x-y) #print(np.subtract(x,y)) print() # Product print(x*y) #p...
lesson6.ipynb
trsherborne/learn-python
mit
Challenge Declare a 5 by 5 array of any numbers you want using one of the above methods we've discussed. Then read this NumPy documentation, when you are ready print the mean, standard deviation, minimum and maximum of your array
# TO DO # You can declare an array of random numbers or start with a list of lists # Check your array is the right size by printing the .shape attribute # Print the mean # Print the standard deviation # Print the minimum # Print the maximum # END TODO
lesson6.ipynb
trsherborne/learn-python
mit
Pandas Pandas is a data manipulation package that we've glimpsed before. If you know R, then the Pandas Dataframe type will be very familiar, if not you can think of a Dataframe is a spreadsheet like object which can be manipulated and interfaced with much easier than lists of dictionaries (or dictionaries of lists!). ...
# Pandas DataFrames can be initialised using Numpy objects or # or with native Python objects. # Using Numpy df1 = pd.DataFrame(np.random.randn(3,4),columns=list('ABCD')) print(df1) # Or with a dictionary of list vales my_dict = { 'A':[1,2,3,4], 'B':['2016-12-25','2015-12-25','2014-12-25','2013-12-25'], '...
lesson6.ipynb
trsherborne/learn-python
mit
Selecting elements
# Use [] indexing and a column name to grab columns df2['C'] # Use [] and row values to grab rows df2[1:3] # Or use .loc to retrieve specific values like the 0th row df2.loc[0] # Or use loc and a condition df2.loc[df2['E']==True]
lesson6.ipynb
trsherborne/learn-python
mit
Revisiting what we did on the first day
# Choose a stock ticker = 'DRYS' # Choose a start date in US format MM/DD/YYYY stock_start = '10/2/2014' # Choose an end date in US format MM/DD/YYYY stock_end = '28/11/2016' # Retrieve the Data from Google's Finance Database stock = web.DataReader(ticker,data_source='google', start = stock_sta...
lesson6.ipynb
trsherborne/learn-python
mit
The code below is usually set in the PlanarAverage.py file; you don't need to edit it
if os.path.isfile('LOCPOT'): print('LOCPOT already exists') else: os.system('bunzip2 LOCPOT.bz2') vasp_pot, NGX, NGY, NGZ, Lattice = md.read_vasp_density(input_file) vector_a,vector_b,vector_c,av,bv,cv = md.matrix_2_abc(Lattice) resolution_x = vector_a/NGX resolution_y = vector_b/NGY resolution_z = vector_c/NG...
tutorials/HeteroJunction/HeteroJunction.ipynb
WMD-group/MacroDensity
mit
The code below will prompt you to say which axis you want to average along
## POTENTIAL planar = md.planar_average(grid_pot, NGX, NGY, NGZ) ## MACROSCOPIC AVERAGE macro = md.macroscopic_average(planar, lattice_vector/2, resolution_z)
tutorials/HeteroJunction/HeteroJunction.ipynb
WMD-group/MacroDensity
mit
Now we can plot the results
fig, ax1 = plt.subplots(1, 1, sharex=True) textsize = 22 mpl.rcParams['xtick.labelsize'] = textsize mpl.rcParams['ytick.labelsize'] = textsize mpl.rcParams['figure.figsize'] = (15, 8) ax1.plot(planar,label="Planar",lw=3) ax1.plot(macro,label="Macroscopic",lw=3) ax1.set_ylabel('V/V', fontsize=22) ax1.set_xlabel('Grid...
tutorials/HeteroJunction/HeteroJunction.ipynb
WMD-group/MacroDensity
mit
Get $\Delta V$ From inspection of the macroscopic average, saved in planar.dat we can find that the value of $V$ at each plateau is 2.64 V and -2.61 V. So the step $\Delta V$ is 5.25 V The offset Applying the equation from earlier, the VBO is 1.07 - 2.28 + 5.25 = 4.04 eV Procedure (ii) In this procedure we can take in...
extrema = md.vasp_tools.get_band_extrema('OUTCAR_ZnO_av') print(extrema) extrema = md.vasp_tools.get_band_extrema('OUTCAR_ZnS_av') print(extrema)
tutorials/HeteroJunction/HeteroJunction.ipynb
WMD-group/MacroDensity
mit
The deformation potential To account for the effect of strain on the band positions we need to know the deformation potential $\alpha$. In this case the values for $\alpha$ of ZnO and ZnS (and many other systems) are available Phys. Rev. B 73, 245206. $\alpha_{ZnO} = 0.48$ $\alpha_{ZnS} = 0.83$ The equation we now use ...
input_file = 'LOCPOT' lattice_vector = 3.6 output_file = 'planar.dat' vasp_pot, NGX, NGY, NGZ, Lattice = md.read_vasp_density(input_file) vector_a,vector_b,vector_c,av,bv,cv = md.matrix_2_abc(Lattice) resolution_x = vector_a/NGX resolution_y = vector_b/NGY resolution_z = vector_c/NGZ grid_pot, electrons = md.density_2...
tutorials/HeteroJunction/HeteroJunction.ipynb
WMD-group/MacroDensity
mit
As before the value of $\Delta V$ is 5.25 V. Volume change By comparing the average to the equilibrium POSCARs we can get the values of $\partial\ln V = \frac{\Delta V}{V_{av}}$
dlnVa = (47.55 - 61.04) / 61.04 # ZnO dlnVb = (76.88 - 61.04) / 61.04 # ZnS VBO_natural = (-2.464 + 0.48 * dlnVa ) - (4.8288 + 0.83 * dlnVb) + 5.25 print 'Natural offset: %3.1f eV' % (VBO_natural)
tutorials/HeteroJunction/HeteroJunction.ipynb
WMD-group/MacroDensity
mit
If you want help with coding there is in addition to the example code, some hints within each section and a function reference list.
# Let us now load the simulated data sim_data = read_root('Data/PhaseSpaceSimulation.root')
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
<div align="justify">Now that you can access the data, you can use a number of functions which can help you analyse it. You can find these functions in the libraries at the top of the page. Try to make a table of some of the information within your data file so that you can get a feel of the typical values for data in ...
# make a table of the data variables here
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Hints Creating a table - Use your head() - remember to look at the example analysis to see how this was done there. Invariant mass reconstruction Aims: Plot a histogram of the momentum of one of the kaon candidates Calculate the energy of each of the kaon candidates Plot the invariant masses of the B<sup>+</sup> or B<...
# make a histogram of the H1_PX variable here
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Momentum is a vector quantity, it has x,y, and z components. Try calculating the magnitude of the momentum of the first kaon candidate and plotting a histogram of this, you'll need the H1_PX, H1_PY and H1_PZ variables.
# calculate a variable for the magnitude of the momentum of the first kaon # plot a histogram of this variable
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Hints Histogram plotting - You can use the hist() function. The parameters bins(n) and range(x,y) allow youto plot n bins over the range x to y. Vector Magnitude The square magnitude of a magnitude of a vector is given by the sum of the square of its of its components in the x,y and z directions: $p^2 = p_x^2+p_y^2+p_z...
# calculate the energy of the first kaon # plot a histogram of this variable
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Hints Energy calculation - Use the magnitude of momentum variable you calculated above and the known invariant mass of the kaon to work out the energy of the first hadron. Calculate the energy squared, and then the energy and plot this. Kaon mass - you can find the kaon mass on wikipedia or in physics textbooks. There ...
# calculate variables for the energy of the other two kaons
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Adding features of the $B$ meson In this analysis we are looking for B<sup>+</sup> or B<sup>-</sup> mesons (see B meson) that have decayed into the three charged kaons. Energy is a conserved quantities. This means that you can use the energy of the three 'daughter' kaons, which you have calculated above, to calculate t...
# calculate the energy of the B meson # calculate the momentum components of the B meson # and the magnitude of the momentum of the B meson # calculate the B meson invariant mass # plot the B meson invariant mass in a histogram
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
You should have a graph that sharply peaks at the mass of the B<sup>+</sup> meson. The mass of the B<sup>+</sup> and B<sup>-</sup> meson are the same. Check that the peak of your graph is at the known mass of the B meson. Congratulations! Recall that you have made this plot for simulated data. How might you expect the ...
# Make your preselection here, this line applies no preselection preselection = ""
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
This next line of code just loads the real data into a new DataFrame, this may take a few minutes. It also applies the preselection that you have created if you called it preselection.
real_data = read_root(['Data/B2HHH_MagnetDown.root', 'Data/B2HHH_MagnetUp.root'], where=preselection)
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Make histograms of the probability of a final state particle being a kaon or a pion. These will help guide you on suitable probability values at which to cut. You can also consider more sophisticated options like 2-D plots of kaon and pion probabilities or different values of the cuts for the different final state part...
# plot the probability that a final state particle is a kaon # plot the probability that a final state particle is a pion
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Now calculate the invariant mass of the B meson for the real data and plot a histogram of this. Compare it with the one you drew for the simulation data. Can you explain the differences you observe?
# draw a histogram for the B meson mass in the real data
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Experiment with the cuts and see the impact of harsher or more lenient cuts on the invariant mass plot. You should select a set of cuts which makes the signal most prominent with respect to the background. Once you have finalised the selection on particle identification also make cuts on the reconstructed particle mass...
preselection = "H1_ProbPi < 0.5 & H2_ProbPi < 0.5 & H3_ProbPi < 0.5 & H1_ProbK > 0.5 & H2_ProbK > 0.5 & H3_ProbK > 0.5 & !H1_isMuon & !H2_isMuon & !H3_isMuon"
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Searching for global matter anti-matter differences In this section you will start to study matter antimatter differences (CP Violation). Here 'global' means that you are looking for differences across all ranges of energy and momentum (the kinematics) of the kaons into which the charge B mesons have decayed. Later we ...
# make a variable for the charge of the B mesons
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Now count the numbers of events of each of the two types (N<sup>+</sup> and N<sup>-</sup>). Also calculate the difference between these two numbers.
# make variables for the numbers of positive and negative B mesons
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
In order to calculate the Asymmetry, you can make use of the formula: (note you may need to run this box in order to see the image) <img src="Images/AsymmetryEq.png" width="200" />
# calculate the value of the asymmetry, by using the formula above, and then print it
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Hint Differentiating between N+ and N- Charge is a conserved quantity. The charge of the $B$ meson is equal to the sum of the charges of the particles into which it decays. You can use len(real_data.query('B_Charge == charge')) to count the number of mesons, where B_Charge is the variable you created and charge is 1 o...
# calculate the statistical significance of your result and print it
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Congratulations! You have performed your first search for a matter anti-matter difference. Here you have only considered the statistical uncertainty. Your measurement will also have other sources of uncertainty known as systematic uncertainties which you have not considered at this stage. Dalitz plots and two body reso...
# calculate the invariant masses for each possible hadron pair combination # plot the invariant mass for one of these combinations # make a Dalitz plot with labelled axes for the simulation data
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Hints Calculating invariant mass - Use the same technique as you did above for the B meson, but now applying it to two-body invariant masses rather than three. Plotting the Dalitz plot - You can use a scatter plot from matplotlib to plot a Dalitz plotm, see the example analysis. Remember to use the square of each two-b...
# calculate the invariant masses for each possible hadron pair combination in the real data # make a Dalitz plot for the real data (with your preselection cuts applied)
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
<div align="justify">While drawing the Dalitz plot for the real data, label the axes accordingly. Compare the Dalitz plots of the real data with the one for the simulation. What are the most striking differences? </div> Ordering Dalitz variables You can make a further improvement to allow you to observe the resonanc...
# make a new Dalitz plot with a mass ordering of the axes
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Hint Ordered Dalitz plot - You can find the maximum of the mass of R<sup>0</sup><sub>Low</sub> vs R<sup>0</sup><sub>High</sub> elementwise on one axis, and the minimum of on the other. You can use numpy.min(a,b) and numpy.max(a,b) to perform elementwise comparisons between two arrays a and b and return one array filled...
# plot a binned Dalitz Plot # use colorbar() to make a legend for your plot at the side
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Two body resonances You can now use your Dalitz plot to identify the intermediate resonances that you see in your plots. The resonances will have shown up as bands of higher density of points on the plots. You can use the particle data group tables of mesons to identify which particles these correspond to. The tables g...
# make a Dalitz plot for the B+ events # make a Dalitz plot for the B- events # Make a plot showing the asymmetry between these two Daltz plots # i.e. calculate the asymmetry between each bin of the B+ and B- Dalitz plots and show the result in another 2D plot
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Observing a large asymmetry in some regions of the plot does not necessarily mean you have observed CP violation. If there are very few events in that region of the plot the uncertainty on that large asymmetry may be large. Hence, the value may still be compatible with zero. You can calculate the statistical uncertaint...
# Make a plot showing the uncertainty on the asymmetry # Make a plot showing the statistical significance of the asymmetry
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
Observing CP violation From your studies of the asymmetry plot, and the plot of its significance, you will be able to identify regions in the Dalitz plots that show indications of sizeable and significant CP Violation. You may find you have several consecutive bins with significant positive, or negative, asymmetries. Y...
# Make a plot showing the invariant mass of the B+ meson particles # using events from a region of the Dalitz plot showing sizeable CP asymmetries # Make a plot showing the invariant mass of the B- meson particles using events from the same region
LHCb_Open_Data_Project.ipynb
lhcb/opendata-project
gpl-2.0
I'll write another function to grab batches out of the arrays made by split data. Here each batch will be a sliding window on these arrays with size batch_size X num_steps. For example, if we want our network to train on a sequence of 100 characters, num_steps = 100. For the next batch, we'll shift this window the next...
def get_batch(arrs, num_steps): batch_size, slice_size = arrs[0].shape n_batches = int(slice_size/num_steps) for b in range(n_batches): yield [x[:, b*num_steps: (b+1)*num_steps] for x in arrs] def build_rnn(num_classes, batch_size=50, num_steps=50, lstm_size=128, num_layers=2, le...
tensorboard/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb
mdiaz236/DeepLearningFoundations
mit
Основными структурами данных в Pandas являются классы Series и DataFrame. Первый из них представляет собой одномерный индексированный массив данных некоторого фиксированного типа. Второй - это двухмерная структура данных, представляющая собой таблицу, каждый столбец которой содержит данные одного типа. Можно представля...
salaries = pd.Series([400, 300, 200, 250], index = ['Andrew', 'Bob', 'Charles', 'Ann']) print(salaries) salaries[salaries > 250]
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Индексирование возможно в виде s.Name или s['Name'].
print(salaries.Andrew == salaries['Andrew']) salaries['Carl'] = np.nan salaries.fillna(salaries.median(), inplace=True) salaries
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Series поддерживает пропуски в данных.
salaries.c = np.nan # Series can contain missing values print(salaries)
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Объекты Series похожи на ndarray и могут быть переданы в качестве аргументов большинству функций из Numpy.
print('Second element of salaries is', salaries[1], '\n') # Smart indexing print(salaries[:3], '\n') print('There are', len(salaries[salaries > 0]), 'positive elements in salaries\n') # Series obects can be the arguments for Numpy functions print(np.exp(salaries))
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
DataFrame Создание и изменение Перейдём к рассмотрению объектов типа DataFrame. Такой объект можно создать из массива numpy, указав названия строк и столбцов.
df1 = pd.DataFrame(np.random.randn(5, 3), index=['o1', 'o2', 'o3', 'o4', 'o5'], columns=['f1', 'f2', 'f3']) df1
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Альтернативным способом является создание DataFrame из словаря numpy массивов или списков.
df2 = pd.DataFrame({'A': np.random.random(5), 'B': ['a', 'b', 'c', 'd', 'e'], 'C': np.arange(5) > 2}) df2
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Обращение к элементам (или целым кускам фрейма):
print('The element in position 3, B is', df2.at[3, 'B'], '\n') print(df2.loc[[1, 4], ['A', 'B']])
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Изменение элементов и добавление новых:
df2.at[2, 'B'] = 'f' df2 df2.loc[5] = [3.1415, 'c', False] df2 df1.columns = ['A', 'B', 'C'] df3 = df1.append(df2) df3
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Обработка пропущенных значений
df1.at['o2', 'A'] = np.nan df1.at['o4', 'C'] = np.nan df1
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Булева маска для пропущенных значений (True - там, где был пропуск, иначе - False):
pd.isnull(df1)
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Можно удалить все строки, где есть хотя бы один пропуск.
df1.dropna(how='any')
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Пропуски можно заменить каким-то значением.
df1.fillna(0)
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Пример первичного анализа данных с Pandas Чтение из файла и первичный анализ Однако на практике DataFrame, с которым нам предстоит работать, необходимо считать из некоторого файла. Рассмотрим работу с DataFrame на примере следующего набора данных. Для каждрого опрошенного имеется следующая информация: заработная плата ...
df = pd.read_csv('../data/beauty.csv', sep = ';')
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Посмотрим на размер данных и названия признаков.
print(df.shape) print(df.columns.values) df.head(10)
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
При работе с большими объёмами данных бывает удобно посмотреть только на небольшие части фрейма (например, начало).
df.head(4)
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Метод describe показывает основные статистические характеристики данных по каждому признаку: число непропущенных значений, среднее, стандартное отклонение, диапазон, медиану, 0.25 и 0.75 квартили.
df.describe()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
DataFrame можно отсортировать по значению какого-нибудь из признаков. В нашем случае, например, по размеру заработной платы.
df.sort_values(by='wage', ascending = False).head() df.sort_values(by=['female', 'wage'], ascending=[True, False]).head()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Индексация и извлечение данных DataFrame можно индексировать по-разному. В связи с этим рассмотрим различные способы индексации и извлечения нужных нам данных из DataFrame на примере простых вопросов. Для извлечения отдельного столбца можно использовать конструкцию вида DataFrame['Name']. Воспользуемся этим для ответа ...
df['goodhlth'].mean()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Очень удобной является логическая индексация DataFrame по одному столбцу. Выглядит она следующим образом: df[P(df['Name'])], где P - это некоторое логическое условие, проверяемое для каждого элемента столбца Name. Итогом такой индексации является DataFrame, состоящий только из строк, удовлетворяющих условию P по столбц...
df[df['female'] == 1].head() df[(df['goodhlth'] == 1) & (df['female'] == 1)].head() df[(df['female'] == 0)]['wage'].mean() - \ df[(df['female'] == 1)]['wage'].mean()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Какова максимальная заработная плата среди мужчин, имеющих членство в профсоюзе, и с опытом работы до 10 лет?
df[(df['female'] == 0) & (df['union'] == 1) & (df['exper'] < 10)]['wage'].max()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Применение функции к каждому столбцу:
df.apply(np.mean)
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Группирование данных в зависимости от значения признака looks и подсчет среднего значения по каждому столбцу в каждой группе.
df['looks'].describe() g = df.groupby('looks') for (i, sub_df) in g: print(sub_df['wage'].mean(), sub_df['looks'].mean())
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Обращение к конкретной группе:
d1 = g.get_group(1) d1
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Визуализация в Pandas Метод scatter_matrix позволяет визуализировать попарные зависимости между признаками (а также распределение каждого признака на диагонали). Проделаем это для небинарных признаков.
pd.scatter_matrix(df[['wage', 'exper', 'educ', 'looks']], figsize=(15, 15), diagonal='kde') plt.show()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Для каждого признака можно построить отдельную гистограмму:
df['looks'].hist()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Или сразу для всех:
df.hist(color = 'k', bins = 30, figsize=(15,10)) plt.show()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Полезным также является график типа box plot ("ящик с усами"). Он позволяет компактно визуализировать основные характеристики (медиану, нижний и верхний квартили, минимальное и максимальное значение, выбросы) распределения признаков.
df.boxplot(column='exper', by='looks') plt.show()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Можно сделать это, сгруппировав данные по какому-либо другому признаку:
df.boxplot(column='exper', by=['female', 'black'], figsize=(10,10)) plt.show()
numpy_and_pandas/part1_pandas_intro.ipynb
andreyf/machine-learning-examples
gpl-3.0
Subsampling Words that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ i...
## Your code here # My solution was not using Counter thus was extremely slow. here it is: # def freq(word,corpus): # return corpus.count(word)/len(corpus) # # def prob(word,freqs,th): # return 1-np.sqrt(th/freqs[word]) # # freqs = {word:freq(word,int_words) for word in int_words} # p_drop = {word: prob(word,fr...
embeddings/Skip-Gram_word2vec.ipynb
guyk1971/deep-learning
mit
Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to grab all the words in a window around that word, with size $C$. From Mikolov et al.: "Since the more distant words are usually l...
def get_target(words, idx, window_size=5): ''' Get a list of words in a window around an index. ''' # Your code here # get random number in the range (1,window_size) - this will be the number of words we'll take R=random.randint(1,window_size) # what about warping arond ? do we want to allow it...
embeddings/Skip-Gram_word2vec.ipynb
guyk1971/deep-learning
mit
Building the graph From Chris McCormick's blog, we can see the general structure of our network. The input words are passed in as integers. This will go into a hidden layer of linear units, then into a softmax layer. We'll use the softmax layer to make a prediction like normal. The idea here is to train the hidden lay...
train_graph = tf.Graph() with train_graph.as_default(): inputs = tf.placeholder(dtype=tf.int32,shape=[None], name='inputs') labels = tf.placeholder(dtype=tf.int32,shape=[None,None],name='labels') # ??? To make things work later, you'll need to set the second dimension of labels to None or 1.
embeddings/Skip-Gram_word2vec.ipynb
guyk1971/deep-learning
mit
Validation This code is from Thushan Ganegedara's implementation. Here we're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them. It's a nice way to check that our embedding table is grouping together words with similar semantic meanings.
with train_graph.as_default(): # Question : why do we need this context ? ## From Thushan Ganegedara's implementation valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # pick 8 samples from (0,100) and (1000,1100) each ranges. lower id implies more frequent valid_...
embeddings/Skip-Gram_word2vec.ipynb
guyk1971/deep-learning
mit
get viewshed suffix (for filenames)
def getViewshedSuffix(): if use_viewshed: viewshed_suffix = '_viewshed' else: viewshed_suffix = '' return viewshed_suffix naturalness_area_table_filename = "/home/ubuntu/naturalness_areas_{0}m{1}.csv".format(radius, getViewshedSuffix())
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
Import statements
import numpy as np import pandas import pyprind
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
GRASS import statements
import grass.script as gscript from grass.pygrass.vector.geometry import Point from grass.pygrass.vector import Vector from grass.pygrass.vector import VectorTopo from grass.pygrass.vector.table import DBlinks
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
Function declarations connect to attribute table
def connectToAttributeTable(map): vector = VectorTopo(map) vector.open(mode='r') dblinks = DBlinks(vector.c_mapinfo) link = dblinks[0] return link.table()
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
extract point from vector map
def extractPoint(input, ID, output): where = 'ID = {0}'.format(ID) type = 'point' gscript.read_command('v.extract', input=input, where=where, output=output, type=type, overwrite=Tr...
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
create buffer around point
def bufferPoint(input, output, radius): gscript.read_command('v.buffer', input=input, output=output, type='point', distance=radius, overwrite=True)
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
convert viewshed from raster to vector map
def vectorizeViewshed(input, ID, output): type = 'area' column = 'visible' gscript.read_command('r.to.vect', input=input, output=output, type=type, column=column, overwrite=True)
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
overlay a vector map on an underlying vector map using 'and' selection operator
def overlay(overlay, underlay, output): operator='and' gscript.read_command('v.overlay', ainput=overlay, binput=underlay, operator=operator, output=output, overwrite=True)
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
add area column to vector map
def calculateAreas(map): #add new area column gscript.read_command('v.db.addcolumn', map=map, columns="area_square_meters DOUBLE PRECISION") #compute area and insert into area column gscript.read_command('v.to.db', map=...
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
create table showing total area by landcover type
def getNaturalnessAreaByValue(map): #get area data table = connectToAttributeTable(map=map) table.filters.select() columns = table.columns.names() cursor = table.execute() result = np.array(cursor.fetchall()) cursor.close() data = pandas.DataFrame(result, columns=columns).set_index('cat'...
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
Utility functions export vector map to a shapefile
def exportVectorToShapefile(map, output): gscript.read_command('v.out.ogr', input=map, format='ESRI_Shapefile', output=output, flags='e', overwrite=True)
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
get info about a vector map
def getVectorMapInfo(map): return gscript.read_command('v.info', map=map)
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
Compute landcover areas connect to 'sample_points' attribute table
point_table = connectToAttributeTable(map=sample_points) point_table.filters.select() columns = point_table.columns.names() cursor = point_table.execute() result = np.array(cursor.fetchall()) cursor.close() point_data = pandas.DataFrame(result, columns=columns).set_index('cat')
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
loop through sample points
with Vector(sample_points, mode='r') as points: #setup progress bar progress_bar = pyprind.ProgBar(points.n_lines, bar_char='█', title='Naturalness analysis progress', monitor=True, stream=1, width=50) #iterate through points for point in points: #get point ID (SiteID) ...
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
Export naturalness area table create table with naturalness areas by type for each point
#create table index_start = 0 ''' set the first index number, allowing easier insertion into a database table that already contains area calculations with other parameters (i.e radius and use_viewshed)''' columns = ['ID', 'SiteID', 'IncludedArea'] columns = columns + [ str(n) for n in range(1,n_types+1) ] ...
Compute naturalness areas.ipynb
jacobdein/alpine-soundscapes
mit
토큰 생성(tokenizing) 문서를 분석하기 위해서는 우선 긴 문자열을 분석을 위한 작은 단위로 나누어야 한다. 이 문자열 단위를 토큰(token)이라고 한다.
from nltk.tokenize import word_tokenize word_tokenize(emma_raw[50:100]) from nltk.tokenize import RegexpTokenizer t = RegexpTokenizer("[\w]+") t.tokenize(emma_raw[50:100]) from nltk.tokenize import sent_tokenize print(sent_tokenize(emma_raw[:1000])[3])
19. 문서 전처리/02. NLTK 자연어 처리 패키지 소개.ipynb
zzsza/Datascience_School
mit
형태소 분석 형태소 분석이란 어근, 접두사/접미사, 품사(POS, part-of-speech) 등 다양한 언어적 속성의 구조를 파악하는 작업이다. 구체적으로는 다음과 같은 작업으로 나뉜다. stemming (어근 추출) lemmatizing (원형 복원) POS tagging (품사 태깅) ### Stemming and lemmatizing
from nltk.stem import PorterStemmer st = PorterStemmer() st.stem("eating") from nltk.stem import LancasterStemmer st = LancasterStemmer() st.stem("shopping") from nltk.stem import RegexpStemmer st = RegexpStemmer("ing") st.stem("cooking") from nltk.stem import WordNetLemmatizer lm = WordNetLemmatizer() print(lm.lemm...
19. 문서 전처리/02. NLTK 자연어 처리 패키지 소개.ipynb
zzsza/Datascience_School
mit
POS tagging POS(part-of-speech)는 품사를 말한다. Part-of-Speech Tagset https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.htm http://www.ibm.com/support/knowledgecenter/ko/SS5RWK_3.5.0/com.ibm.discovery.es.ta.doc/iiysspostagset.htm
from nltk.tag import pos_tag tagged_list = pos_tag(word_tokenize(emma_raw[:100])) tagged_list from nltk.tag import untag untag(tagged_list)
19. 문서 전처리/02. NLTK 자연어 처리 패키지 소개.ipynb
zzsza/Datascience_School
mit