markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We're going to extract images of representing the bins in the spike | a = np.apply_along_axis(lambda x:x[4]/x[3], 1, data_thresholded)
spike = a[np.logical_and(a <= 0.0015, a >= 0.0012)]
n, bins, _ = plt.hist(spike, 2000)
bin_max = np.where(n == n.max())
bin_width = bins[1]-bins[0]
syn_normalized[:,3] = syn_normalized[:,3]/(64**3)
spike = syn_normalized[np.logical_and(syn_normalized[:,3]... | code/Spike Imaging.ipynb | Upward-Spiral-Science/team1 | apache-2.0 |
<img src='spike0_0.bmp' style="width: 800px;"/>
Distributions of Synapses across x, y, z in spike | %matplotlib inline
unique_x = np.unique(spike_thres[:,0])
unique_y = np.unique(spike_thres[:,1])
unique_z = np.unique(spike_thres[:,2])
x_sum = [0] * len(unique_x)
for i in range(len(unique_x)):
x_sum[i] = sum(spike_thres[spike_thres[:,0]==unique_x[i]][:,4])
y_sum = [0] * len(unique_y)
for i in range(len(uniq... | code/Spike Imaging.ipynb | Upward-Spiral-Science/team1 | apache-2.0 |
Source alignment
The aim of this tutorial is to show how to visually assess that the data
are well aligned in space for computing the forward solution. | import os.path as op
import mne
from mne.datasets import sample
print(__doc__) | 0.15/_downloads/plot_source_alignment.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Set parameters | data_path = sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
tr_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(raw_fname) | 0.15/_downloads/plot_source_alignment.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
:func:mne.viz.plot_alignment is a very useful function for inspecting
the surface alignment before source analysis. If the subjects_dir and
subject parameters are provided, the function automatically looks for the
Freesurfer surfaces from the subject's folder. Here we use trans=None, which
(incorrectly!) equates the MR... | mne.viz.plot_alignment(raw.info, trans=None, subject='sample',
subjects_dir=subjects_dir, surfaces=['head', 'brain']) | 0.15/_downloads/plot_source_alignment.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
It is quite clear that things are not well aligned for estimating the
sources. We need to provide the function with a transformation that aligns
the MRI with the MEG data. Here we use a precomputed matrix, but you can try
creating it yourself using :func:mne.gui.coregistration.
Aligning the data using GUI
Uncomment the... | # mne.gui.coregistration(subject='sample', subjects_dir=subjects_dir)
trans = mne.read_trans(tr_fname)
src = mne.read_source_spaces(op.join(data_path, 'MEG', 'sample',
'sample_audvis-meg-oct-6-meg-inv.fif'))
mne.viz.plot_alignment(raw.info, trans=trans, subject='sample', src=src,
... | 0.15/_downloads/plot_source_alignment.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
The previous is possible if you have the surfaces available from Freesurfer.
The function automatically searches for the correct surfaces from the
provided subjects_dir. Otherwise it is possible to use the sphere
conductor model. It is passed through bem parameter.
<div class="alert alert-info"><h4>Note</h4><p>``bem`` ... | sphere = mne.make_sphere_model(info=raw.info, r0='auto', head_radius='auto')
mne.viz.plot_alignment(raw.info, subject='sample', eeg='projected',
meg='helmet', bem=sphere, dig=True,
surfaces=['brain', 'inner_skull', 'outer_skull',
'outer_skin... | 0.15/_downloads/plot_source_alignment.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Convert that astropy.time.Time back to a localized datetime, arriving back at the original datetime (only this one is localized): | localized_datetime = obs.astropy_time_to_datetime(astropy_time)
print('datetime:', localized_datetime)
print('new datetime equivalent to original naive datetime?:',
local_naive_datetime == localized_datetime.replace(tzinfo=None)) | timezones.ipynb | bmorris3/gsoc2015 | mit |
Let's say the Subaru observer is remotely observing from the East Coast. Let's convert their local time (Eastern) to an astropy time. Since this datetime is localized, datetime_to_astropy_time will use the datetime's timezone (rather than assuming self.timezone): | east_coast_datetime = pytz.timezone('US/Eastern').localize(datetime.datetime(2015, 7, 14, 6))
east_coast_astropy_time = obs.datetime_to_astropy_time(east_coast_datetime)
print('Convert local East Coast time to UTC:', east_coast_astropy_time)
print('Equivalent to original astropy time?:', east_coast_astropy_time == astr... | timezones.ipynb | bmorris3/gsoc2015 | mit |
Warning
How you construct your localized timezone is important! Don't initialize datetimes with
the tzinfo kwarg. Here's an example of when it doesn't work. These two times should be equal, but are not. See pytz documentation for discussion. | tzinfo_kwarg = datetime.datetime(2015, 7, 14, 6, tzinfo=pytz.timezone('US/Eastern'))
localized = pytz.timezone('US/Eastern').localize(datetime.datetime(2015, 7, 14, 6))
print('with tz assigned in kwarg:', tzinfo_kwarg)
print('with localization by tz.localize(dt):', localized) | timezones.ipynb | bmorris3/gsoc2015 | mit |
After reading the "PyDIP basics" notebook, you should be familiar with the concepts of scalar images and color images. We remind the reader that an image can have any number of values associated to each pixel. An image with a single value per pixel is a scalar image. Multiple values can be arranged in one or two dimens... | img = dip.ImageRead('../trui.ics')
img.Show() | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
We can compute its gradient, which is a vector image: | g = dip.Gradient(img)
g.Show() | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
The vector image is displayed by showing the first vector component in the red channel, and the second one in the green channel. g has two components: | print(g.TensorElements())
print(g.TensorShape()) | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
Multiplying a vector with its transposed leads to a symmetric matrix: | S = g @ dip.Transpose(g)
print("Tensor size:", S.TensorSizes())
print("Tensor shape:", S.TensorShape())
print("Tensor elements:", S.TensorElements()) | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
Note how the 2x2 symmetric matrix stores only 3 elements per pixel. Because of the symmetry, the [0,1] and the [1,0] elements are identical, and need not be both stored. See the documentation for details on how the individual elements are stored.
Local averaging of this matrix image (i.e. applying a low-pass filter) le... | S = dip.Gauss(S, [5])
S.Show() | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
We can still display this tensor image, because it has only 3 tensor elements, which can be mapped to the three RGB channels of the display.
The structure tensor is one of the more important applications for the concept of the tensor image. In this documentation page there are some example applications of the structure... | eigenvalues, eigenvectors = dip.EigenDecomposition(S)
print(eigenvalues.TensorShape())
print(eigenvectors.TensorShape()) | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
The eigendecomposition is such that S * eigenvectors == eigenvectors * eigenvalues. eigenvectors is a full 2x2 matrix, and hence has 4 tensor elements. These are stored in column-major order. The first column is the eigenvector that corresponds to the first eigenvalue. Eigenvalues are sorted in descending order, and he... | v1 = eigenvectors.TensorColumn(0)
angle = dip.Angle(v1)
angle.Show('orientation') | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
Note that extracting a column from the tensor yields a vector image, and that this vector image shares data with the column-major matrix image. Transposing a matrix is a cheap operation that just changes the storage order of the matrix, without a need to copy or reorder the data: | tmp = dip.Transpose(eigenvectors)
print(tmp.TensorShape())
print(tmp.SharesData(eigenvectors)) | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
A second important matrix image is the Hessian matrix, which contains all second order derivatives. Just like the strucutre tensor, it is a symmetric 2x2 matrix: | H = dip.Hessian(img)
print("Tensor size:", S.TensorSizes())
print("Tensor shape:", S.TensorShape())
print("Tensor elements:", S.TensorElements())
H.Show() | examples/python/tensor_images.ipynb | DIPlib/diplib | apache-2.0 |
Settings | ALG = 'SLM'
random_state = 100
if ALG == 'GLM':
lenscale = gamma(2, scale=50)
regularizer = gamma(2, scale=10)
var = gamma(2, scale=50)
nbases = 8192
nsamples = 10
batch_size = 10
maxiter = int(1e6)
updater = Adam()
elif ALG == 'SLM':
lenscale = gamma(1, scale=50)
regularizer =... | demos/sarcos_demo.ipynb | NICTA/revrand | apache-2.0 |
Load the data | gpml_sarcos = fetch_gpml_sarcos_data()
X_train = gpml_sarcos.train.data
y_train = gpml_sarcos.train.targets
X_test = gpml_sarcos.test.data
y_test = gpml_sarcos.test.targets
Ntrain, D = X_train.shape
print("Training data shape = {}".format(X_train.shape))
print("Testing data shape = {}".format(X_test.shape))
| demos/sarcos_demo.ipynb | NICTA/revrand | apache-2.0 |
Transform targets and inputs
As per GPML p23 | # Targets
ymean = y_train.mean()
y_train -= ymean
y_test -= ymean
# Inputs
Xscaler = StandardScaler()
Xscaler.fit(X_train)
X_train = Xscaler.transform(X_train)
X_test = Xscaler.transform(X_test) | demos/sarcos_demo.ipynb | NICTA/revrand | apache-2.0 |
Initialise the algorithms | regularizer_init = Parameter(regularizer, Positive())
lenscale_init = Parameter(lenscale, Positive(), shape=(D,))
base = RandomRBF(nbases=nbases,
Xdim=D,
lenscale=lenscale_init,
random_state=random_state,
regularizer=regularizer_init
)
... | demos/sarcos_demo.ipynb | NICTA/revrand | apache-2.0 |
Train the algorithms | rnd = np.random.RandomState(random_state)
if ALG == 'GLM':
alg.fit(X_train, y_train)
else:
t_ind = rnd.choice(Ntrain, size=m, replace=False)
alg.fit(X_train[t_ind], y_train[t_ind])
| demos/sarcos_demo.ipynb | NICTA/revrand | apache-2.0 |
Predict and score | if ALG == 'GLM':
Ey, Vf = alg.predict_moments(X_test)
Vy = Vf + alg.like_hypers_
Sy = np.sqrt(Vy)
elif ALG == 'GP':
Ey, Sy = alg.predict(X_test, return_std=True)
Vy = Sy**2
else:
Ey, Vy = alg.predict_moments(X_test)
Sy = np.sqrt(Vy)
print("SMSE = {}".format(smse(y_test, Ey)))
print("MSL... | demos/sarcos_demo.ipynb | NICTA/revrand | apache-2.0 |
Using MNIST dataset
Loading pickled MNIST dataset | # Load the dataset
f = gzip.open('data/mnist.pkl.gz', 'rb')
train_set, valid_set, test_set = cPickle.load(f)
f.close()
def shared_dataset(data_xy):
""" Function that loads the dataset into shared variables
The reason we store our dataset in shared variables is to allow
Theano to copy it into the GPU memor... | projects/digit_recognition/digit_recognition.ipynb | FlorentSilve/Udacity_ML_nanodegree | mit |
Question 1
What approach did you take in coming up with a solution to this problem?
Answer:
Question 2
What does your final architecture look like? (Type of model, layers, sizes, connectivity, etc.)
Answer:
Question 3
How did you train your model? How did you generate your synthetic dataset? Include examples of images... |
### Your code implementation goes here.
### Feel free to use as many code cells as needed.
| projects/digit_recognition/digit_recognition.ipynb | FlorentSilve/Udacity_ML_nanodegree | mit |
Question 4
Describe how you set up the training and testing data for your model. How does the model perform on a realistic dataset?
Answer:
Question 5
What changes did you have to make, if any, to achieve "good" results? Were there any options you explored that made the results worse?
Answer:
Question 6
What were your ... |
### Your code implementation goes here.
### Feel free to use as many code cells as needed.
| projects/digit_recognition/digit_recognition.ipynb | FlorentSilve/Udacity_ML_nanodegree | mit |
Question 7
Choose five candidate images of numbers you took from around you and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult?
Answer:
Question 8
Is your model able to perform equally well on captured pictures or a live camera stream when compare... |
### Your code implementation goes here.
### Feel free to use as many code cells as needed.
| projects/digit_recognition/digit_recognition.ipynb | FlorentSilve/Udacity_ML_nanodegree | mit |
Question 10
How well does your model localize numbers on the testing set from the realistic dataset? Do your classification results change at all with localization included?
Answer:
Question 11
Test the localization function on the images you captured in Step 3. Does the model accurately calculate a bounding box for th... |
### Your optional code implementation goes here.
### Feel free to use as many code cells as needed.
| projects/digit_recognition/digit_recognition.ipynb | FlorentSilve/Udacity_ML_nanodegree | mit |
회귀: 자동차 연비 예측하기
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/r1/tutorials/keras/basic_regression.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />구글 코랩(Colab)에서 실행하기</a>
... | # 산점도 행렬을 그리기 위해 seaborn 패키지를 설치합니다
!pip install seaborn
import pathlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import tensorflow.compat.v1 as tf
from tensorflow import keras
from tensorflow.keras import layers
print(tf.__version__) | site/ko/r1/tutorials/keras/basic_regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
정규화된 데이터를 사용하여 모델을 훈련합니다.
주의: 여기에서 입력 데이터를 정규화하기 위해 사용한 통계치(평균과 표준편차)는 원-핫 인코딩과 마찬가지로 모델에 주입되는 모든 데이터에 적용되어야 합니다. 여기에는 테스트 세트는 물론 모델이 실전에 투입되어 얻은 라이브 데이터도 포함됩니다.
모델
모델 만들기
모델을 구성해 보죠. 여기에서는 두 개의 완전 연결(densely connected) 은닉층으로 Sequential 모델을 만들겠습니다. 출력 층은 하나의 연속적인 값을 반환합니다. 나중에 두 번째 모델을 만들기 쉽도록 build_model 함수로 모델 구성 단계를... | def build_model():
model = keras.Sequential([
layers.Dense(64, activation=tf.nn.relu, input_shape=[9]),
layers.Dense(64, activation=tf.nn.relu),
layers.Dense(1)
])
optimizer = tf.keras.optimizers.RMSprop(0.001)
model.compile(loss='mean_squared_error',
optimizer=optimizer,
... | site/ko/r1/tutorials/keras/basic_regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
history 객체에 저장된 통계치를 사용해 모델의 훈련 과정을 시각화해 보죠. | hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
hist.tail()
import matplotlib.pyplot as plt
def plot_history(history):
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
plt.figure(figsize=(8,12))
plt.subplot(2,1,1)
plt.xlabel('Epoch')
plt.ylabel('Mean Abs Error [MPG]'... | site/ko/r1/tutorials/keras/basic_regression.ipynb | tensorflow/docs-l10n | apache-2.0 |
Generate Input Files
First we need to define materials that will be used in the problem. We will create three materials for the fuel, water, and cladding of the fuel pin. | # 1.6 enriched fuel
fuel = openmc.Material(name='1.6% Fuel')
fuel.set_density('g/cm3', 10.31341)
fuel.add_nuclide('U235', 3.7503e-4)
fuel.add_nuclide('U238', 2.2625e-2)
fuel.add_nuclide('O16', 4.6007e-2)
# borated water
water = openmc.Material(name='Borated Water')
water.set_density('g/cm3', 0.740582)
water.add_nuclid... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
With our three materials, we can now create a materials file object that can be exported to an actual XML file. | # Instantiate a Materials collection
materials_file = openmc.Materials([fuel, water, zircaloy])
# Export to "materials.xml"
materials_file.export_to_xml() | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Now let's move on to the geometry. This problem will be a square array of fuel pins for which we can use OpenMC's lattice/universe feature. The basic universe will have three regions for the fuel, the clad, and the surrounding coolant. The first step is to create the bounding surfaces for fuel and clad, as well as the ... | # Create cylinders for the fuel and clad
fuel_outer_radius = openmc.ZCylinder(x0=0.0, y0=0.0, R=0.39218)
clad_outer_radius = openmc.ZCylinder(x0=0.0, y0=0.0, R=0.45720)
# Create boundary planes to surround the geometry
# Use both reflective and vacuum boundaries to make life interesting
min_x = openmc.XPlane(x0=-10.71... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
With the surfaces defined, we can now construct a fuel pin cell from cells that are defined by intersections of half-spaces created by the surfaces. | # Create fuel Cell
fuel_cell = openmc.Cell(name='1.6% Fuel', fill=fuel,
region=-fuel_outer_radius)
# Create a clad Cell
clad_cell = openmc.Cell(name='1.6% Clad', fill=zircaloy)
clad_cell.region = +fuel_outer_radius & -clad_outer_radius
# Create a moderator Cell
moderator_cell = openmc.Cell(nam... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Using the pin cell universe, we can construct a 17x17 rectangular lattice with a 1.26 cm pitch. | # Create fuel assembly Lattice
assembly = openmc.RectLattice(name='1.6% Fuel - 0BA')
assembly.pitch = (1.26, 1.26)
assembly.lower_left = [-1.26 * 17. / 2.0] * 2
assembly.universes = [[pin_cell_universe] * 17] * 17 | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
OpenMC requires that there is a "root" universe. Let us create a root cell that is filled by the pin cell universe and then assign it to the root universe. | # Create root Cell
root_cell = openmc.Cell(name='root cell', fill=assembly)
# Add boundary planes
root_cell.region = +min_x & -max_x & +min_y & -max_y & +min_z & -max_z
# Create root Universe
root_universe = openmc.Universe(name='root universe')
root_universe.add_cell(root_cell) | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
We now must create a geometry that is assigned a root universe and export it to XML. | # Create Geometry and export to "geometry.xml"
geometry = openmc.Geometry(root_universe)
geometry.export_to_xml() | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
With the geometry and materials finished, we now just need to define simulation parameters. In this case, we will use 5 inactive batches and 15 minimum active batches each with 2500 particles. We also tell OpenMC to turn tally triggers on, which means it will keep running until some criterion on the uncertainty of tall... | # OpenMC simulation parameters
min_batches = 20
max_batches = 200
inactive = 5
particles = 2500
# Instantiate a Settings object
settings = openmc.Settings()
settings.batches = min_batches
settings.inactive = inactive
settings.particles = particles
settings.output = {'tallies': False}
settings.trigger_active = True
set... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Let us also create a plot file that we can use to verify that our pin cell geometry was created successfully. | # Instantiate a Plot
plot = openmc.Plot(plot_id=1)
plot.filename = 'materials-xy'
plot.origin = [0, 0, 0]
plot.width = [21.5, 21.5]
plot.pixels = [250, 250]
plot.color_by = 'material'
# Instantiate a Plots collection and export to "plots.xml"
plot_file = openmc.Plots([plot])
plot_file.export_to_xml() | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
As we can see from the plot, we have a nice array of pin cells with fuel, cladding, and water! Before we run our simulation, we need to tell the code what we want to tally. The following code shows how to create a variety of tallies. | # Instantiate an empty Tallies object
tallies = openmc.Tallies() | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Instantiate a fission rate mesh Tally | # Instantiate a tally Mesh
mesh = openmc.Mesh(mesh_id=1)
mesh.type = 'regular'
mesh.dimension = [17, 17]
mesh.lower_left = [-10.71, -10.71]
mesh.width = [1.26, 1.26]
# Instantiate tally Filter
mesh_filter = openmc.MeshFilter(mesh)
# Instantiate energy Filter
energy_filter = openmc.EnergyFilter([0, 0.625, 20.0e6])
# ... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Instantiate a cell Tally with nuclides | # Instantiate tally Filter
cell_filter = openmc.CellFilter(fuel_cell)
# Instantiate the tally
tally = openmc.Tally(name='cell tally')
tally.filters = [cell_filter]
tally.scores = ['scatter']
tally.nuclides = ['U235', 'U238']
# Add mesh and tally to Tallies
tallies.append(tally) | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Create a "distribcell" Tally. The distribcell filter allows us to tally multiple repeated instances of the same cell throughout the geometry. | # Instantiate tally Filter
distribcell_filter = openmc.DistribcellFilter(moderator_cell)
# Instantiate tally Trigger for kicks
trigger = openmc.Trigger(trigger_type='std_dev', threshold=5e-5)
trigger.scores = ['absorption']
# Instantiate the Tally
tally = openmc.Tally(name='distribcell tally')
tally.filters = [distri... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Now we a have a complete set of inputs, so we can go ahead and run our simulation. | # Remove old HDF5 (summary, statepoint) files
!rm statepoint.*
# Run OpenMC!
openmc.run() | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Tally Data Processing | # We do not know how many batches were needed to satisfy the
# tally trigger(s), so find the statepoint file(s)
statepoints = glob.glob('statepoint.*.h5')
# Load the last statepoint file
sp = openmc.StatePoint(statepoints[-1]) | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Analyze the mesh fission rate tally | # Find the mesh tally with the StatePoint API
tally = sp.get_tally(name='mesh tally')
# Print a little info about the mesh tally to the screen
print(tally) | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Use the new Tally data retrieval API with pure NumPy | # Get the relative error for the thermal fission reaction
# rates in the four corner pins
data = tally.get_values(scores=['fission'],
filters=[openmc.MeshFilter, openmc.EnergyFilter], \
filter_bins=[((1,1),(1,17), (17,1), (17,17)), \
... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Analyze the cell+nuclides scatter-y2 rate tally | # Find the cell Tally with the StatePoint API
tally = sp.get_tally(name='cell tally')
# Print a little info about the cell tally to the screen
print(tally)
# Get a pandas dataframe for the cell tally data
df = tally.get_pandas_dataframe()
# Print the first twenty rows in the dataframe
df.head(20) | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Use the new Tally data retrieval API with pure NumPy | # Get the standard deviations the total scattering rate
data = tally.get_values(scores=['scatter'],
nuclides=['U238', 'U235'], value='std_dev')
print(data) | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Analyze the distribcell tally | # Find the distribcell Tally with the StatePoint API
tally = sp.get_tally(name='distribcell tally')
# Print a little info about the distribcell tally to the screen
print(tally) | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Use the new Tally data retrieval API with pure NumPy | # Get the relative error for the scattering reaction rates in
# the first 10 distribcell instances
data = tally.get_values(scores=['scatter'], filters=[openmc.DistribcellFilter],
filter_bins=[tuple(range(10))], value='rel_err')
print(data) | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Print the distribcell tally dataframe | # Get a pandas dataframe for the distribcell tally data
df = tally.get_pandas_dataframe(nuclides=False)
# Print the last twenty rows in the dataframe
df.tail(20)
# Show summary statistics for absorption distribcell tally data
absorption = df[df['score'] == 'absorption']
absorption[['mean', 'std. dev.']].dropna().desc... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Perform a statistical test comparing the tally sample distributions for two categories of fuel pins. | # Extract tally data from pins in the pins divided along y=-x diagonal
multi_index = ('level 2', 'lat',)
lower = df[df[multi_index + ('x',)] + df[multi_index + ('y',)] < 16]
upper = df[df[multi_index + ('x',)] + df[multi_index + ('y',)] > 16]
lower = lower[lower['score'] == 'absorption']
upper = upper[upper['score'] =... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Note that the symmetry implied by the y=-x diagonal ensures that the two sampling distributions are identical. Indeed, as illustrated by the test above, for any reasonable significance level (e.g., $\alpha$=0.05) one would not reject the null hypothesis that the two sampling distributions are identical.
Next, perform t... | # Extract tally data from pins in the pins divided along y=x diagonal
multi_index = ('level 2', 'lat',)
lower = df[df[multi_index + ('x',)] > df[multi_index + ('y',)]]
upper = df[df[multi_index + ('x',)] < df[multi_index + ('y',)]]
lower = lower[lower['score'] == 'absorption']
upper = upper[upper['score'] == 'absorptio... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
Note that the asymmetry implied by the y=x diagonal ensures that the two sampling distributions are not identical. Indeed, as illustrated by the test above, for any reasonable significance level (e.g., $\alpha$=0.05) one would reject the null hypothesis that the two sampling distributions are identical. | # Extract the scatter tally data from pandas
scatter = df[df['score'] == 'scatter']
scatter['rel. err.'] = scatter['std. dev.'] / scatter['mean']
# Show a scatter plot of the mean vs. the std. dev.
scatter.plot(kind='scatter', x='mean', y='rel. err.', title='Scattering Rates')
# Plot a histogram and kernel density e... | examples/jupyter/pandas-dataframes.ipynb | johnnyliu27/openmc | mit |
It's interesting to note that these perfect predictions are actually lucky shots: $|U_i|$ is always very small, meaning that very few users have rated the target item. This implies that the set of neighbors is very small (see the actual_k field)... And, it just happens that all the ratings from the neighbors are the sa... | # Now, let's look at the prediction with the biggest error
worst_predictions | examples/notebooks/KNNBasic_analysis.ipynb | charmoniumQ/Surprise | bsd-3-clause |
Let's focus first on the last two predictions. Well, we can't do much about them. We should have predicted $5$, but the only available neighbor had a rating of $1$, so we were screwed. The only way to avoid this kind of errors would be to increase the min_k parameter, but it would actually worsen the accuracy (see note... | from collections import Counter
import matplotlib.pyplot as plt
import matplotlib
%matplotlib notebook
matplotlib.style.use('ggplot')
counter = Counter([r for (_, r) in trainset.ir[trainset.to_inner_iid('302')]])
pd.DataFrame.from_dict(counter, orient='index').plot(kind='bar', legend=False)
plt.xlabel('Rating value')... | examples/notebooks/KNNBasic_analysis.ipynb | charmoniumQ/Surprise | bsd-3-clause |
POSTGAP Report
This notebook was automatically generated as a summary of POSTGAP output.
Setup
Note that for command line usage (python reporter.py <filename>) the following will work just fine. However, to edit the template, temporarily change the following to import helpers. | from reports import helpers
helpers.calc_run_str()
# pg = pd.read_csv(filename, sep='\t', na_values=['None'])
pg = helpers.load_file(filename) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Headline
Q: How many rows and columns? | print(pg.shape) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Q: How many unique target-disease associations? | helpers.calc_g2d_pair_counts(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Q: What is the distribution of unique diseases per gene? And vice versa? | helpers.calc_pairwise_degree_dist(pg, 'gene_id', 'disease_efo_id', 'Gene', 'Disease') | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Identifiers
Q: How many unique values appear for each identifier? | helpers.calc_id_field_counts(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Q: What is the maximum number of rows for a given fixed identifier? | helpers.calc_id_field_max_rows(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Identifier pairs
Q: How many unique identifier pairs appear? | helpers.calc_id_field_pair_counts(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Gene-LD SNP associations
Q: What is the distribution of each association subscore (VEP, GTEx, etc.)? | helpers.calc_g2v_field_hists(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Q: What is the distribution of unique LD SNPs per gene? And vice versa? | helpers.calc_pairwise_degree_dist(pg, 'gene_id', 'ld_snp_rsID', 'Gene', 'LD SNP') | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Q: What is the overlap between presence of association subscores? | helpers.calc_g2v_field_overlap(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Q: What is the joint distribution between association subscore pairs (ie. how correlated are they)? | helpers.calc_g2v_field_cross_dists(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
LD SNP-GWAS SNP associations
Q: What is the distribution of r2? | helpers.calc_dist_r2(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Q: What is the distribution of unique GWAS SNPs per LD SNP? And vice versa? | helpers.calc_pairwise_degree_dist(pg, 'ld_snp_rsID', 'gwas_snp', 'LD SNP', 'GWAS SNP') | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
GWAS SNP-Disease associations
Q: What are the distributions of (gwas_pvalue, gwas_beta, gwas_odds_ratio)? | helpers.calc_v2d_field_hists(pg) | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
Q: What is the distribution of unique diseases per GWAS SNP? And vice versa? | helpers.calc_pairwise_degree_dist(pg, 'gwas_snp', 'disease_efo_id', 'GWAS SNP', 'Disease') | tests/reports/template.ipynb | Ensembl/cttv024 | apache-2.0 |
PrettyTensor version: | pt.__version__ | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The MNIST data-set has now been loaded and consists of 70,000 images and associated labels (i.e. classifications of the images). The data-set is split into 3 mutually exclusive sub-sets, but we will make random training-sets further below. | print("Size of:")
print("- Training-set:\t\t{}".format(len(data.train.labels)))
print("- Test-set:\t\t{}".format(len(data.test.labels)))
print("- Validation-set:\t{}".format(len(data.validation.labels))) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Class numbers
The class-labels are One-Hot encoded, which means that each label is a vector with 10 elements, all of which are zero except for one element. The index of this one element is the class-number, that is, the digit shown in the associated image. We also need the class-numbers as integers for the test- and va... | data.test.cls = np.argmax(data.test.labels, axis=1)
data.validation.cls = np.argmax(data.validation.labels, axis=1) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function for creating random training-sets
We will train 5 neural networks on different training-sets that are selected at random. First we combine the original training- and validation-sets into one big set. This is done for both the images and the labels. | combined_images = np.concatenate([data.train.images, data.validation.images], axis=0)
combined_labels = np.concatenate([data.train.labels, data.validation.labels], axis=0) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Check that the shape of the combined arrays is correct. | print(combined_images.shape)
print(combined_labels.shape) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Size of the combined data-set. | combined_size = len(combined_images)
combined_size | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Define the size of the training-set used for each neural network. You can try and change this. | train_size = int(0.8 * combined_size)
train_size | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
We do not use a validation-set during training, but this would be the size. | validation_size = combined_size - train_size
validation_size | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function for splitting the combined data-set into a random training- and validation-set. | def random_training_set():
# Create a randomized index into the full / combined training-set.
idx = np.random.permutation(combined_size)
# Split the random index into training- and validation-sets.
idx_train = idx[0:train_size]
idx_validation = idx[train_size:]
# Select the images and labels f... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function for plotting images
Function used to plot 9 images in a 3x3 grid, and writing the true and predicted classes below each image. | def plot_images(images, # Images to plot, 2-d array.
cls_true, # True class-no for images.
ensemble_cls_pred=None, # Ensemble predicted class-no.
best_cls_pred=None): # Best-net predicted class-no.
assert len(images) == len(cls_tr... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
TensorFlow Graph
The entire purpose of TensorFlow is to have a so-called computational graph that can be executed much more efficiently than if the same calculations were to be performed directly in Python. TensorFlow can be more efficient than NumPy because TensorFlow knows the entire computation graph that must be ex... | x = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='x') | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Now that we have wrapped the input image in a Pretty Tensor object, we can add the convolutional and fully-connected layers in just a few lines of source-code.
Note that pt.defaults_scope(activation_fn=tf.nn.relu) makes activation_fn=tf.nn.relu an argument for each of the layers constructed inside the with-block, so th... | with pt.defaults_scope(activation_fn=tf.nn.relu):
y_pred, loss = x_pretty.\
conv2d(kernel=5, depth=16, name='layer_conv1').\
max_pool(kernel=2, stride=2).\
conv2d(kernel=5, depth=36, name='layer_conv2').\
max_pool(kernel=2, stride=2).\
flatten().\
fully_connected(size... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Saver
In order to save the variables of the neural network, we now create a Saver-object which is used for storing and retrieving all the variables of the TensorFlow graph. Nothing is actually saved at this point, which will be done further below.
Note that if you have more than 100 neural networks in the ensemble then... | saver = tf.train.Saver(max_to_keep=100) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
This is the directory used for saving and retrieving the data. | save_dir = 'checkpoints/' | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
This function returns the save-path for the data-file with the given network number. | def get_save_path(net_number):
return save_dir + 'network' + str(net_number) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Initialize variables
The variables for weights and biases must be initialized before we start optimizing them. We make a simple wrapper-function for this, because we will call it several times below. | def init_variables():
session.run(tf.initialize_all_variables()) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function to create a random training batch.
There are thousands of images in the training-set. It takes a long time to calculate the gradient of the model using all these images. We therefore only use a small batch of images in each iteration of the optimizer.
If your computer crashes or becomes very slow becaus... | train_batch_size = 64 | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Function for selecting a random training-batch of the given size. | def random_batch(x_train, y_train):
# Total number of images in the training-set.
num_images = len(x_train)
# Create a random index into the training-set.
idx = np.random.choice(num_images,
size=train_batch_size,
replace=False)
# Use the random... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-function to perform optimization iterations
Function for performing a number of optimization iterations so as to gradually improve the variables of the network layers. In each iteration, a new batch of data is selected from the training-set and then TensorFlow executes the optimizer using those training samples.... | def optimize(num_iterations, x_train, y_train):
# Start-time used for printing time-usage below.
start_time = time.time()
for i in range(num_iterations):
# Get a batch of training examples.
# x_batch now holds a batch of images and
# y_true_batch are the true labels for those image... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Create ensemble of neural networks
Number of neural networks in the ensemble. | num_networks = 5 | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Number of optimization iterations for each neural network. | num_iterations = 10000 | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Create the ensemble of neural networks. All networks use the same TensorFlow graph that was defined above. For each neural network the TensorFlow weights and variables are initialized to random values and then optimized. The variables are then saved to disk so they can be reloaded later.
You may want to skip this compu... | if True:
# For each of the neural networks.
for i in range(num_networks):
print("Neural network: {0}".format(i))
# Create a random training-set. Ignore the validation-set.
x_train, y_train, _, _ = random_training_set()
# Initialize the variables of the TensorFlow graph.
... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-functions for calculating and predicting classifications
This function calculates the predicted labels of images, that is, for each image it calculates a vector of length 10 indicating which of the 10 classes the image is.
The calculation is done in batches because it might use too much RAM otherwise. If your co... | # Split the data-set in batches of this size to limit RAM usage.
batch_size = 256
def predict_labels(images):
# Number of images.
num_images = len(images)
# Allocate an array for the predicted labels which
# will be calculated in batches and filled into this array.
pred_labels = np.zeros(shape=(nu... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Calculate a boolean array whether the predicted classes for the images are correct. | def correct_prediction(images, labels, cls_true):
# Calculate the predicted labels.
pred_labels = predict_labels(images=images)
# Calculate the predicted class-number for each image.
cls_pred = np.argmax(pred_labels, axis=1)
# Create a boolean array whether each image is correctly classified.
... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Calculate a boolean array whether the images in the test-set are classified correctly. | def test_correct():
return correct_prediction(images = data.test.images,
labels = data.test.labels,
cls_true = data.test.cls) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.