markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
This OptimizationRecord object has many different fields attached to it so that all quantities involved in the computation can be explored. For this example, let us pull the final molecule (optimized structure) and inspect the physical dimensions.
Note: if the status does not say COMPLETE, these fields will not be avai... | final_mol = proc.get_final_molecule()
print(final_mol.measure([0, 1]))
print(final_mol.measure([1, 0, 2]))
final_mol | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
This water molecule has bond length and angle dimensions much closer to expected values. We can also plot the optimization history to see how each step in the geometry optimization affected the results. Though the chart is not too impressive for this simple molecule, it is hopefully illuminating and is available for an... | proc.show_history() | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
Collections
Submitting individual procedures or single quantum chemistry tasks is not typically done as it becomes hard to track individual tasks. To help resolve this, Collections are different ways of organizing standard computations so that many tasks can be referenced in a more human-friendly way. In this particula... | ds = ptl.collections.ReactionDataset("My IE Dataset", ds_type="ie", client=client, default_program="psi4") | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
We can construct a water dimer that has fragments used in the intermolecular computation with the -- divider. A single water molecule with ghost atoms can be extracted like so: | water_dimer = ptl.Molecule.from_data("""
O 0.000000 0.000000 0.000000
H 0.758602 0.000000 0.504284
H 0.260455 0.000000 -0.872893
--
O 3.000000 0.500000 0.000000
H 3.758602 0.500000 0.504284
H 3.260455 0.500000 -0.872893
""")
water_dimer.get_fragment(0, 1) | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
Many molecular entries can be added to this dataset where each is entry is a given intermolecular complex that is given a unique name. In addition, the add_ie_rxn method to can automatically fragment molecules. | ds.add_ie_rxn("water dimer", water_dimer)
ds.add_ie_rxn("helium dimer", """
He 0 0 -3
--
He 0 0 3
""") | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
Once the Collection is created it can be saved to the server so that it can always be retrived at a future date | ds.save() | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
The client can list all Collections currently on the server and retrive collections to be manipulated: | client.list_collections()
ds = client.get_collection("ReactionDataset", "My IE Dataset")
ds | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
Computing with collections
Computational methods can be applied to all of the reactions in the dataset with just a few simple lines: | ds.compute("B3LYP-D3", "def2-SVP") | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
By default this collection evaluates the non-counterpoise corrected interaction energy which typically requires three computations per entry (the complex and each monomer). In this case we compute the B3LYP and -D3 additive correction separately, nominally 12 total computations. However the collection is smart enough t... | ds.compute("PBE-D3", "def2-SVP") | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
A list of all methods that have been computed for this dataset can also be shown: | ds.list_values() | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
The above only shows what has been computed and does not pull this data from the server to your computer. To do so, the get_history command can be used: | print(f"DataFrame units: {ds.units}")
ds.get_values() | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
You can also visualize results and more! | ds.visualize(["B3LYP-D3", "PBE-D3"], "def2-SVP", bench="B3LYP/def2-svp", kind="violin") | docs/qcfractal/source/quickstart.ipynb | psi4/DatenQM | bsd-3-clause |
Importing a data set
This next cell may take a little while to run if it's grabbing a pretty big data set. The cell label to the left will look like "In [*]" while it's still thinking and "In [2]" when it's finished. | # Combined land and ocean temperature averages (LOTI: Land Ocean Temperature Index)
data1 = pd.read_csv('http://github.com/adamlamee/CODINGinK12-data/raw/master/LOTI.csv', header=1).replace(to_replace="***", value=np.NaN)
data_LOTI = data1.apply(lambda x: pd.to_numeric(x, errors='ignore'))
# Only land temperature aver... | GlobalTemp.ipynb | merryjman/astronomy | gpl-3.0 |
We can view the first few rows of the file we just imported. | # The .head(n) command displays the first n rows of the file.
data_LAND.head(5) | GlobalTemp.ipynb | merryjman/astronomy | gpl-3.0 |
Plotting the data | x1 = data_LOTI.Year
y1 = data_LOTI.JanDec
# plt.plot() makes a line graph, by default
fig = plt.figure(figsize=(10, 5))
plt.plot(x1, y1)
plt.title('Average land an docean temperature readings')
plt.xlabel('Year')
plt.ylabel('Percent temp change')
x2 = data_LAND.Year
y2 = data_LAND.JanDec
# plt.plot() makes a line gr... | GlobalTemp.ipynb | merryjman/astronomy | gpl-3.0 |
Edit and re-plot
If you like Randall Monroe's webcomic XKCD as much as I do, you can make your plots look like his hand-drawn ones. Thanks to Jake VanderPlas for sorting that out. | plt.xkcd()
fig = plt.figure(figsize=(10, 5))
plt.plot(x1, y1)
# to make normal plots again
mpl.rcParams.update(inline_rc) | GlobalTemp.ipynb | merryjman/astronomy | gpl-3.0 |
Demultiplexers
\begin{definition}\label{def:MUX}
A Demultiplexer, typically referred to as a DEMUX, is a Digital(or analog) switching unit that takes one input channel to be streamed to a single output channel from many via a control input. For single input DEMUXs with $2^n$ outputs, there are then $n$ input selection ... | x, s, y0, y1=symbols('x, s, y_0, y_1')
y12_0Eq=Eq(y0, ~s&x)
y12_1Eq=Eq(y1, s&x)
y12_0Eq, y12_1Eq
T0=TruthTabelGenrator(y12_0Eq)
T1=TruthTabelGenrator(y12_1Eq)
T10=pd.merge(T1, T0, how='left')
T10
y12_0EqN=lambdify([s, x], y12_0Eq.rhs, dummify=False)
y12_1EqN=lambdify([s, x], y12_1Eq.rhs, dummify=False)
SystmaticVals=... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Module | @block
def DEMUX1_2_Combo(x, s, y0, y1):
"""
1:2 DEMUX written in full combo
Inputs:
x(bool): input feed
s(bool): channel select
Outputs:
y0(bool): ouput channel 0
y1(bool): ouput channel 1
"""
@always_comb
def logic():
y0.next= not s and x
... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | TestLen=10
SystmaticVals=list(itertools.product([0,1], repeat=2))
xTVs=np.array([i[1] for i in SystmaticVals]).astype(int)
np.random.seed(15)
xTVs=np.append(xTVs, np.random.randint(0,2, TestLen)).astype(int)
sTVs=np.array([i[0] for i in SystmaticVals]).astype(int)
#the random genrator must have a differint seed bewee... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Conversion | DUT.convert()
VerilogTextReader('DEMUX1_2_Combo'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_2_Combo_RTL.png}}
\caption{\label{fig:D12CRTL} DEMUX1_2_Combo RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_2_Combo_SYN.png}}
\caption{\label{fig:D12CSYN} DEMUX1_2_Combo Synthesized Schemati... | #create BitVectors
xTVs=intbv(int(''.join(xTVs.astype(str)), 2))[TestLen:]
sTVs=intbv(int(''.join(sTVs.astype(str)), 2))[TestLen:]
xTVs, bin(xTVs), sTVs, bin(sTVs)
@block
def DEMUX1_2_Combo_TBV():
"""
myHDL -> testbench for module `DEMUX1_2_Combo`
"""
x=Signal(bool(0))
s=Signal(bool(0))
y0=S... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
PYNQ-Z1 Deployment
Board Circuit
\begin{figure}
\centerline{\includegraphics[width=5cm]{DEMUX12PYNQZ1Circ.png}}
\caption{\label{fig:D12Circ} 1:2 DEMUX PYNQ-Z1 (Non SoC) conceptualized circuit}
\end{figure}
Board Constraints | ConstraintXDCTextReader('DEMUX1_2'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Video of Deployment
DEMUX1_2_Combo on PYNQ-Z1 (YouTube)
1 Channel Input:4 Channel Output demultiplexer in Gate Level Logic
Sympy Expression | x, s0, s1, y0, y1, y2, y3=symbols('x, s0, s1, y0, y1, y2, y3')
y14_0Eq=Eq(y0, ~s0&~s1&x)
y14_1Eq=Eq(y1, s0&~s1&x)
y14_2Eq=Eq(y2, ~s0&s1&x)
y14_3Eq=Eq(y3, s0&s1&x)
y14_0Eq, y14_1Eq, y14_2Eq, y14_3Eq
T0=TruthTabelGenrator(y14_0Eq)
T1=TruthTabelGenrator(y14_1Eq)
T2=TruthTabelGenrator(y14_2Eq)
T3=TruthTabelGenrator(y14_3E... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Module | @block
def DEMUX1_4_Combo(x, s0, s1, y0, y1, y2, y3):
"""
1:4 DEMUX written in full combo
Inputs:
x(bool): input feed
s0(bool): channel select 0
s1(bool): channel select 1
Outputs:
y0(bool): ouput channel 0
y1(bool): ouput channel 1
y2(bool): ouput chann... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | TestLen=10
SystmaticVals=list(itertools.product([0,1], repeat=3))
xTVs=np.array([i[2] for i in SystmaticVals]).astype(int)
np.random.seed(15)
xTVs=np.append(xTVs, np.random.randint(0,2, TestLen)).astype(int)
s0TVs=np.array([i[1] for i in SystmaticVals]).astype(int)
#the random genrator must have a differint seed bewe... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Conversion | DUT.convert()
VerilogTextReader('DEMUX1_4_Combo'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_4_Combo_RTL.png}}
\caption{\label{fig:D14CRTL} DEMUX1_4_Combo RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_4_Combo_SYN.png}}
\caption{\label{fig:D14CSYN} DEMUX1_4_Combo Synthesized Schemati... | #create BitVectors
xTVs=intbv(int(''.join(xTVs.astype(str)), 2))[TestLen:]
s0TVs=intbv(int(''.join(s0TVs.astype(str)), 2))[TestLen:]
s1TVs=intbv(int(''.join(s1TVs.astype(str)), 2))[TestLen:]
xTVs, bin(xTVs), s0TVs, bin(s0TVs), s1TVs, bin(s1TVs)
@block
def DEMUX1_4_Combo_TBV():
"""
myHDL -> testbench for mod... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
PYNQ-Z1 Deployment
Board Circuit
\begin{figure}
\centerline{\includegraphics[width=5cm]{DEMUX14PYNQZ1Circ.png}}
\caption{\label{fig:D14Circ} 1:4 DEMUX PYNQ-Z1 (Non SoC) conceptualized circuit}
\end{figure}
Board Constraints | ConstraintXDCTextReader('DEMUX1_4'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Video of Deployment
DEMUX1_4_Combo on PYNQ-Z1 (YouTube)
1 Channel Input:4 Channel Output demultiplexer via DEMUX Stacking
myHDL Module | @block
def DEMUX1_4_DMS(x, s0, s1, y0, y1, y2, y3):
"""
1:4 DEMUX via DEMUX Stacking
Inputs:
x(bool): input feed
s0(bool): channel select 0
s1(bool): channel select 1
Outputs:
y0(bool): ouput channel 0
y1(bool): ouput channel 1
y2(bool): ouput channel 2
... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | TestLen=10
SystmaticVals=list(itertools.product([0,1], repeat=3))
xTVs=np.array([i[2] for i in SystmaticVals]).astype(int)
np.random.seed(15)
xTVs=np.append(xTVs, np.random.randint(0,2, TestLen)).astype(int)
s0TVs=np.array([i[1] for i in SystmaticVals]).astype(int)
#the random genrator must have a differint seed bewe... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Conversion | DUT.convert()
VerilogTextReader('DEMUX1_4_DMS'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_4_DMS_RTL.png}}
\caption{\label{fig:D14DMSRTL} DEMUX1_4_DMS RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_4_DMS_SYN.png}}
\caption{\label{fig:D14DMSSYN} DEMUX1_4_DMS Synthesized Schematic; X... | #create BitVectors
xTVs=intbv(int(''.join(xTVs.astype(str)), 2))[TestLen:]
s0TVs=intbv(int(''.join(s0TVs.astype(str)), 2))[TestLen:]
s1TVs=intbv(int(''.join(s1TVs.astype(str)), 2))[TestLen:]
xTVs, bin(xTVs), s0TVs, bin(s0TVs), s1TVs, bin(s1TVs)
@block
def DEMUX1_4_DMS_TBV():
"""
myHDL -> testbench for modul... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
PYNQ-Z1 Deployment
Board Circuit
See Board Circuit for "1 Channel Input:4 Channel Output demultiplexer in Gate Level Logic"
Board Constraint
uses same 'DEMUX1_4.xdc' as "# 1 Channel Input:4 Channel Output demultiplexer in Gate Level Logic"
Video of Deployment
DEMUX1_4_DMS on PYNQ-Z1 (YouTube)
1:2 DEMUX via Behavioral I... | @block
def DEMUX1_2_B(x, s, y0, y1):
"""
1:2 DMUX in behavioral
Inputs:
x(bool): input feed
s(bool): channel select
Outputs:
y0(bool): ouput channel 0
y1(bool): ouput channel 1
"""
@always_comb
def logic():
if s==0:
#take note that sin... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | TestLen=10
SystmaticVals=list(itertools.product([0,1], repeat=2))
xTVs=np.array([i[1] for i in SystmaticVals]).astype(int)
np.random.seed(15)
xTVs=np.append(xTVs, np.random.randint(0,2, TestLen)).astype(int)
sTVs=np.array([i[0] for i in SystmaticVals]).astype(int)
#the random genrator must have a differint seed bewee... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Conversion | DUT.convert()
VerilogTextReader('DEMUX1_2_B'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_2_B_RTL.png}}
\caption{\label{fig:D12BRTL} DEMUX1_2_B RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_2_B_SYN.png}}
\caption{\label{fig:D12BSYN} DEMUX1_2_B Synthesized Schematic; Xilinx Vivado... | #create BitVectors
xTVs=intbv(int(''.join(xTVs.astype(str)), 2))[TestLen:]
sTVs=intbv(int(''.join(sTVs.astype(str)), 2))[TestLen:]
xTVs, bin(xTVs), sTVs, bin(sTVs)
@block
def DEMUX1_2_B_TBV():
"""
myHDL -> testbench for module `DEMUX1_2_B`
"""
x=Signal(bool(0))
s=Signal(bool(0))
y0=Signal(bo... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
PYNQ-Z1 Deployment
Board Circuit
See Board Circuit for "1 Channel Input: 2 Channel Output demultiplexer in Gate Level Logic"
Board Constraint
uses same 'DEMUX1_2.xdc' as "1 Channel Input: 2 Channel Output demultiplexer in Gate Level Logic"
Video of Deployment
DEMUX1_2_B on PYNQ-Z1 (YouTube)
1:4 DEMUX via Behavioral if-... | @block
def DEMUX1_4_B(x, s0, s1, y0, y1, y2, y3):
"""
1:4 DEMUX written via behaviorial
Inputs:
x(bool): input feed
s0(bool): channel select 0
s1(bool): channel select 1
Outputs:
y0(bool): ouput channel 0
y1(bool): ouput channel 1
y2(bool): ouput channel... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | TestLen=10
SystmaticVals=list(itertools.product([0,1], repeat=3))
xTVs=np.array([i[2] for i in SystmaticVals]).astype(int)
np.random.seed(15)
xTVs=np.append(xTVs, np.random.randint(0,2, TestLen)).astype(int)
s0TVs=np.array([i[1] for i in SystmaticVals]).astype(int)
#the random genrator must have a differint seed bewe... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Conversion | DUT.convert()
VerilogTextReader('DEMUX1_4_B'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_4_B_RTL.png}}
\caption{\label{fig:D14BRTL} DEMUX1_4_B RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_4_B_SYN.png}}
\caption{\label{fig:D14BSYN} DEMUX1_4_B Synthesized Schematic; Xilinx Vivado... | #create BitVectors
xTVs=intbv(int(''.join(xTVs.astype(str)), 2))[TestLen:]
s0TVs=intbv(int(''.join(s0TVs.astype(str)), 2))[TestLen:]
s1TVs=intbv(int(''.join(s1TVs.astype(str)), 2))[TestLen:]
xTVs, bin(xTVs), s0TVs, bin(s0TVs), s1TVs, bin(s1TVs)
@block
def DEMUX1_4_B_TBV():
"""
myHDL -> testbench for module ... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
PYNQ-Z1 Deployment
Board Circuit
See Board Circuit for "1 Channel Input:4 Channel Output demultiplexer in Gate Level Logic"
Board Constraint
uses same 'DEMUX1_4.xdc' as "# 1 Channel Input:4 Channel Output demultiplexer in Gate Level Logic"
Video of Deployment
DEMUX1_4_B on PYNQ-Z1 (YouTube)
Demultiplexer 1:4 Behavioral... | @block
def DEMUX1_4_BV(x, S, Y):
"""
1:4 DEMUX written via behaviorial with
bit vectors
Inputs:
x(bool): input feed
S(2bit vector): channel select bitvector;
min=0, max=3
Outputs:
Y(4bit vector): ouput channel bitvector;
values min=0, max=15; allow... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | xTVs=np.array([0,1])
xTVs=np.append(xTVs, np.random.randint(0,2,6)).astype(int)
TestLen=len(xTVs)
np.random.seed(12)
STVs=np.arange(0,4)
STVs=np.append(STVs, np.random.randint(0,4, 5))
TestLen, xTVs, STVs
Peeker.clear()
x=Signal(bool(0)); Peeker(x, 'x')
S=Signal(intbv(0)[2:]); Peeker(S, 'S')
Y=Signal(intbv(0)[4:]); P... | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Conversion | DUT.convert()
VerilogTextReader('DEMUX1_4_BV'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_4_BV_RTL.png}}
\caption{\label{fig:D14BVRTL} DEMUX1_4_BV RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{DEMUX1_4_BV_SYN.png}}
\caption{\label{fig:D14BVSYN} DEMUX1_4_BV Synthesized Schematic; Xilinx ... | ConstraintXDCTextReader('DEMUX1_4_BV'); | myHDL_DigLogicFundamentals/myHDL_Combinational/Demultiplexers(DEMUX).ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Regex Filtering
Another approach is to use the regular expressions while dealing with special patterns of noise. We have explained regular expressions in detail in one of our previous article. Following python code removes a regex pattern from the input text: | import re
def _remove_regex(input_text, regex_pattern):
urls = re.finditer(regex_pattern, input_text)
for i in urls:
input_text = re.sub(i.group().strip(), '', input_text)
return input_text
regex_pattern = "#[\w]*"
_remove_regex("remove this #FloridaBlue from tweet text", regex_pattern) | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
Normalization
Another type of textual noise is about the multiple representations exhibited by single word.
For example – “play”, “player”, “played”, “plays” and “playing” are the different variations of the word – “play”, Though they mean different but contextually all are similar. The step converts all the disparitie... | from nltk.stem.wordnet import WordNetLemmatizer
lem = WordNetLemmatizer()
from nltk.stem.porter import PorterStemmer
stem = PorterStemmer()
word = "multiplying"
lem.lemmatize(word, "v")
stem.stem(word) | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
Standardization
Text data often contains words or phrases which are not present in any standard lexical dictionaries. These pieces are not recognized by search engines and models.
Some of the examples are – acronyms, hashtags with attached words, and colloquial slangs. With the help of regular expressions and manually ... | translation_dict = {'rt':'Retweet', 'dm':'direct message', "awsm" : "awesome", "luv" :"love"} | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
Parsing
Syntactical parsing involves the analysis of words in the sentence for grammar and their arrangement in a manner that shows the relationships among the words. Dependency Grammar and Part of Speech tags are the important attributes of text syntactics.
Dependency Trees – Sentences are composed of some words sewed... | import nltk
from nltk import sent_tokenize, word_tokenize
from IPython.display import Image
nltk.download()
sentences = sent_tokenize("Our mission is to help people and communities achieve better health declares our purpose " \
"as a company and it serves as the standard against which we wei... | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
Part of speech tagging
Apart from the grammar relations, every word in a sentence is also associated with a part of speech (pos) tag (nouns, verbs, adjectives, adverbs etc). The pos tags defines the usage and function of a word in the sentence. Here is a list of all possible pos-tags defined by Pennsylvania university.... | from nltk import pos_tag
#this is a Classifier, given a token assign a class
#pos_tag Already defined in the library. We can train our own.
tags = pos_tag(tokens)
text = "I am using Data Science Experience at Florida Blue for Natural Language Processing"
tokens = word_tokenize(text)
print pos_tag(tokens)
# Let's a... | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
Part of Speech tagging is used for many important purposes in NLP:
Word Sense Disambiguation
Some language words have multiple meanings according to their usage. For example, in the two sentences below:
I. “Please book my flight for Delhi”
II. “I am going to read this book in the flight”
“Book” is used with different c... | from nltk.corpus import wordnet as wn #loading wordnet module
wn.synsets('human')
wn.synsets('human')[0].definition
wn.synsets('human')[1].definition
human = wn.synsets('Human',pos=wn.NOUN)[0]
human
human.hypernyms()
human.hyponyms()
bike = wn.synsets('bicycle')[0]
bike
girl = wn.synsets('girl')[1]
girl
bike... | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
Chunks
Chunking is the process of collecting patterns of Part of Speech together, representing some meaning. Analysis of a sentence which identifies the constituents (noun groups - "[The red tree] grows near the river", verbs, verb groups, etc.)
Our goal is detect into digital text, thing like "where are different ent... | from nltk import word_tokenize,pos_tag
from nltk.chunk import RegexpParser
chunker = RegexpParser(r'''
NP:
{<DT><NN.*><.*>*<NN.*>}
}<VB.*>{
''')
print tags
print chunker.parse(tags) | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
Entity Recognition - Chunking
Part of chunking. We look for chunks of Part Of Speech. The goal is to detect entities: Person, Location, Time, etc. I will use here the library ne_chunker. But we can train our own models, or provide grammar rules as before. | from nltk.chunk import ne_chunk
sentence = "Daryl A. is the head of the coworking place Commoncode Corp. from where many people work in Melbourne, Australia."
pos_tags = pos_tag(word_tokenize(sentence))
pos_tags
from IPython.display import display
display(pos_tags) | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
Sentiment Analyisis
Is a phrase expresing a positive opinion? a negative opinion? how can we measure that? We will decompose sentences into their smaller units: tokens, and we will measure how probable they distribute on positive/negative sentences along the text.
<h2> Lets Classify Text! </h2> | #We will use movie reviews, already separated as positive and negative. Specially interest are those bigrams,
#that are in positive or negative sentences (pair of words (word1, word2) that appear consecutives.)
from nltk.corpus import movie_reviews
import nltk.classify.util
from nltk.classify import NaiveBayesClassif... | NLP Overview.ipynb | krondor/nlp-dsx-pot | gpl-3.0 |
<span id="Shallow_Water_Bathymetry_import">Import Dependencies and Connect to the Data Cube ▴</span> | from datacube.utils.aws import configure_s3_access
configure_s3_access(requester_pays=True)
import datacube
dc = datacube.Datacube() | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_plat_prod">Choose the Platform and Product ▴</span> | #List the products available on this server/device
dc.list_products()
#create a list of the desired platforms
platform = 'LANDSAT_8'
product = 'ls8_level1_usgs' | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_define_extents">Define the Extents of the Analysis ▴</span>
Region bounds | # East Coast of Australia
lat_subsect = (-31.7, -32.2)
lon_subsect = (152.4, 152.9)
print('''
Latitude:\t{0}\t\tRange:\t{2} degrees
Longitude:\t{1}\t\tRange:\t{3} degrees
'''.format(lat_subsect,
lon_subsect,
max(lat_subsect)-min(lat_subsect),
max(lon_subsect)-min(lon_subsect))) | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
Display | from utils.data_cube_utilities.dc_display_map import display_map
display_map(latitude = lat_subsect,longitude = lon_subsect) | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_retrieve_data">Retrieve the Data ▴</span>
Load and integrate datasets | %%time
ds = dc.load(lat = lat_subsect,
lon = lon_subsect,
platform = platform,
product = product,
output_crs = "EPSG:32756",
measurements = ["red","blue","green","nir","quality"],
resolution = (-30,30))
ds | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
Preview the Data | from utils.data_cube_utilities.dc_rgb import rgb
rgb(ds.isel(time=6), x_coord='x', y_coord='y')
plt.show() | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_bathymetry">Calculate the Bathymetry and NDWI Indices ▴</span>
The bathymetry function is located at the top of this notebook. | # Create Bathemtry Index column
ds["bathymetry"] = bathymetry_index(ds)
from utils.data_cube_utilities.dc_water_classifier import NDWI
# (green - nir) / (green + nir)
ds["ndwi"] = NDWI(ds, band_pair=1) | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<hr>
Preview Combined Dataset | ds | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_export_unmasked">Export Unmasked GeoTIFF ▴</span> | import os
from utils.data_cube_utilities.import_export import export_xarray_to_multiple_geotiffs
unmasked_dir = "geotiffs/landsat8/unmasked"
if not os.path.exists(unmasked_dir):
os.makedirs(unmasked_dir)
export_xarray_to_multiple_geotiffs(ds, unmasked_dir + "/unmasked.tif",
x_coo... | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_mask">Mask the Dataset Using the Quality Column and NDWI ▴</span> | # preview values
np.unique(ds["quality"]) | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
Use NDWI to Mask Out Land
The threshold can be tuned if need be to better fit the RGB image above. <br>
Unfortunately our existing WOFS algorithm is designed to work with Surface Reflectance (SR) and does not work with this data yet but with a few modifications it could be made to do so. We will approximate the WOFs ... | # Tunable threshold for masking the land out
threshold = .05
water = (ds.ndwi>threshold).values
#preview one time slice to determine the effectiveness of the NDWI masking
rgb(ds.where(water).isel(time=6), x_coord='x', y_coord='y')
plt.show()
from utils.data_cube_utilities.dc_mosaic import ls8_oli_unpack_qa
clear_xar... | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_vis_func">Create a Visualization Function ▴</span>
Visualize the distribution of the bathymetry index for the water pixels | plt.figure(figsize=[15,5])
#Visualize the distribution of the remaining data
sns.boxplot(ds['bathymetry'])
plt.show() | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<b>Interpretation: </b> We can see that most of the values fall within a very short range. We can scale our plot's cmap limits to fit the specific quantile ranges for the bathymetry index so we can achieve better contrast from our plots. | #set the quantile range in either direction from the median value
def get_quantile_range(col, quantile_range = .25):
low = ds[col].quantile(.5 - quantile_range,["time","y","x"]).values
high = ds[col].quantile(.5 + quantile_range,["time","y","x"]).values
return low,high
#Custom function for a color mapping ... | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_bath_vis">Visualize the Bathymetry ▴</span> | mean_value_visual(ds, "bathymetry", cmap="GnBu") | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
<span id="Shallow_Water_Bathymetry_bath_vis_better">Visualize the Bathymetry With Adjusted Contrast ▴</span>
If we clamp the range of the plot using different quantile ranges we can see relative differences in higher contrast. | # create range using the 10th and 90th quantile
low, high = get_quantile_range("bathymetry", .40)
custom = custom_color_mapper(val_range=(low,high),
colors=["darkred","red","orange","yellow","green",
"blue","darkblue","black"])
mean_value_visual(ds, "... | notebooks/water/bathymetry/Shallow_Water_Bathymetry.ipynb | ceos-seo/data_cube_notebooks | apache-2.0 |
Read dog breed information | # source1: web
df_breed = pd.read_csv("breed_nick_names.txt",names=['breed_info'])
df_breed.head()
df_breed.shape
breeds_info = df_breed['breed_info'].values
breed_dict = {}
for breed in breeds_info:
temp = breed.lower()
temp = re.findall('\d.\s+(\D*)', temp)[0]
temp = temp.strip().split('=')
breed_d... | NLP/nlp eda.ipynb | sadahanu/Capstone | mit |
for poodles:create each type of poodle a separate look up item and delete the original poodle one.
to add: american bulldog, merge with bulldog here
to add: bull mastiff = bullmstiffs
to add english springer = 'english springer spaniels'
german shorhaired = 'german shorthaired pointers'
german shepherd = 'german s... | # poodles:
for breed in not_found_breed:
if breed.endswith('poodle') or breed=='wheaten terrier':
breed_dict[breed] = set(breed.split())|set([snowball.stem(w) for w in breed.split()])
breed_dict.pop('poodle', None)
# bullmastiff
if 'bull mastiff' in not_found_breed:
breed_dict['bull mastiff'] = bre... | NLP/nlp eda.ipynb | sadahanu/Capstone | mit |
Save intermediate import dictionaries and results | save_data = df_extract.to_csv(index=False)
s3_res = boto3.resource('s3')
s3_res.Bucket('dogfaces').put_object(Key='reviews/extract_breed_review.csv', Body=save_data)
# save breed_lookup
# save breed_dict
with open('breed_lookup.pickle', 'wb') as handle:
pickle.dump(breed_lookup, handle, protocol=pickle.HIGHEST_PRO... | NLP/nlp eda.ipynb | sadahanu/Capstone | mit |
Get breed scores | # generate a data frame, review_id, toy_id, breed
len(df_extract['review_id'].unique()) | NLP/nlp eda.ipynb | sadahanu/Capstone | mit |
.. _tut_inverse_mne_dspm:
Source localization with MNE/dSPM/sLORETA
The aim of this tutorials is to teach you how to compute and apply a linear
inverse method such as MNE/dSPM/sLORETA on evoked/raw/epochs data. | import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import (make_inverse_operator, apply_inverse,
write_inverse_operator) | 0.12/_downloads/plot_mne_dspm_source_localization.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Process MEG data | data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
event_id = dict(aud_r=1) # event trigger and conditions
tmin = -0.2 # start of each epoch (200ms before the trigger)
tmax = ... | 0.12/_downloads/plot_mne_dspm_source_localization.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Compute regularized noise covariance
For more details see :ref:tut_compute_covariance. | noise_cov = mne.compute_covariance(
epochs, tmax=0., method=['shrunk', 'empirical'])
fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info) | 0.12/_downloads/plot_mne_dspm_source_localization.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Here we use peak getter to move visualization to the time point of the peak
and draw a marker at the maximum peak vertex. | vertno_max, time_idx = stc.get_peak(hemi='rh', time_as_index=True)
subjects_dir = data_path + '/subjects'
brain = stc.plot(surface='inflated', hemi='rh', subjects_dir=subjects_dir)
brain.set_data_time_index(time_idx)
brain.add_foci(vertno_max, coords_as_verts=True, hemi='rh', color='blue',
scale_factor... | 0.12/_downloads/plot_mne_dspm_source_localization.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Morph data to average brain | stc_fsaverage = stc.morph(subject_to='fsaverage', subjects_dir=subjects_dir)
brain_fsaverage = stc_fsaverage.plot(surface='inflated', hemi='rh',
subjects_dir=subjects_dir)
brain_fsaverage.set_data_time_index(time_idx)
brain_fsaverage.scale_data_colormap(fmin=8, fmid=12, fmax=15, tr... | 0.12/_downloads/plot_mne_dspm_source_localization.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Vertex AI Training and Serving with TFX and Vertex Pipelines
<div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/tfx/tutorials/tfx/gcp/vertex_pipelines_vertex_training">
<img src="https://www.tensorflow.org/images/tf_logo_32px.png"... | # Use the latest version of pip.
!pip install --upgrade pip
!pip install --upgrade "tfx[kfp]<2" | site/en-snapshot/tfx/tutorials/tfx/gcp/vertex_pipelines_vertex_training.ipynb | tensorflow/docs-l10n | apache-2.0 |
Write a pipeline definition
We will define a function to create a TFX pipeline. It has the same three
Components as in
Simple TFX Pipeline Tutorial,
but we use a Trainer and Pusher component in the GCP extension module.
tfx.extensions.google_cloud_ai_platform.Trainer behaves like a regular
Trainer, but it just moves th... | def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str,
module_file: str, endpoint_name: str, project_id: str,
region: str, use_gpu: bool) -> tfx.dsl.Pipeline:
"""Implements the penguin pipeline with TFX."""
# Brings data into the pipeline or otherwise ... | site/en-snapshot/tfx/tutorials/tfx/gcp/vertex_pipelines_vertex_training.ipynb | tensorflow/docs-l10n | apache-2.0 |
Run the pipeline on Vertex Pipelines.
We will use Vertex Pipelines to run the pipeline as we did in
Simple TFX Pipeline for Vertex Pipelines Tutorial. | # docs_infra: no_execute
import os
PIPELINE_DEFINITION_FILE = PIPELINE_NAME + '_pipeline.json'
runner = tfx.orchestration.experimental.KubeflowV2DagRunner(
config=tfx.orchestration.experimental.KubeflowV2DagRunnerConfig(),
output_filename=PIPELINE_DEFINITION_FILE)
_ = runner.run(
_create_pipeline(
... | site/en-snapshot/tfx/tutorials/tfx/gcp/vertex_pipelines_vertex_training.ipynb | tensorflow/docs-l10n | apache-2.0 |
The generated definition file can be submitted using Google Cloud aiplatform
client in google-cloud-aiplatform package. | # docs_infra: no_execute
from google.cloud import aiplatform
from google.cloud.aiplatform import pipeline_jobs
import logging
logging.getLogger().setLevel(logging.INFO)
aiplatform.init(project=GOOGLE_CLOUD_PROJECT, location=GOOGLE_CLOUD_REGION)
job = pipeline_jobs.PipelineJob(template_path=PIPELINE_DEFINITION_FILE,
... | site/en-snapshot/tfx/tutorials/tfx/gcp/vertex_pipelines_vertex_training.ipynb | tensorflow/docs-l10n | apache-2.0 |
Now you can visit the link in the output above or visit 'Vertex AI > Pipelines'
in Google Cloud Console to see the
progress.
Test with a prediction request
Once the pipeline completes, you will find a deployed model at the one of the
endpoints in 'Vertex AI > Endpoints'. We need to know the id of the endpoint to
send a... | ENDPOINT_ID='' # <--- ENTER THIS
if not ENDPOINT_ID:
from absl import logging
logging.error('Please set the endpoint id.') | site/en-snapshot/tfx/tutorials/tfx/gcp/vertex_pipelines_vertex_training.ipynb | tensorflow/docs-l10n | apache-2.0 |
We use the same aiplatform client to send a request to the endpoint. We will
send a prediction request for Penguin species classification. The input is the four features that we used, and the model will return three values, because our
model outputs one value for each species.
For example, the following specific exampl... | # docs_infra: no_execute
import numpy as np
# The AI Platform services require regional API endpoints.
client_options = {
'api_endpoint': GOOGLE_CLOUD_REGION + '-aiplatform.googleapis.com'
}
# Initialize client that will be used to create and send requests.
client = aiplatform.gapic.PredictionServiceClient(cli... | site/en-snapshot/tfx/tutorials/tfx/gcp/vertex_pipelines_vertex_training.ipynb | tensorflow/docs-l10n | apache-2.0 |
For detailed information about online prediction, please visit the
Endpoints page in
Google Cloud Console. you can find a guide on sending sample requests and
links to more resources.
Run the pipeline using a GPU
Vertex AI supports training using various machine types including support for
GPUs. See
Machine spec refere... | # docs_infra: no_execute
runner.run(
_create_pipeline(
pipeline_name=PIPELINE_NAME,
pipeline_root=PIPELINE_ROOT,
data_root=DATA_ROOT,
module_file=os.path.join(MODULE_ROOT, _trainer_module_file),
endpoint_name=ENDPOINT_NAME,
project_id=GOOGLE_CLOUD_PROJECT,
reg... | site/en-snapshot/tfx/tutorials/tfx/gcp/vertex_pipelines_vertex_training.ipynb | tensorflow/docs-l10n | apache-2.0 |
Tiramisu / Camvid
Tiramisu is a fully-convolutional neural network based on DenseNet architecture. It was designed as a state-of-the-art approach to semantic image segmentation.
We're going to use the same dataset they did, CamVid.
CamVid is a dataset of images from a video. It has ~ 600 images, so it's quite small, an... | PATH = '/data/datasets/SegNet-Tutorial/CamVid/'
frames_path = PATH+'all/'
labels_path = PATH+'allannot/'
PATH = '/data/datasets/camvid/' | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
The images in CamVid come with labels defining the segments of the input image. We're going to load both the images and the labels. | frames_path = PATH+'701_StillsRaw_full/'
labels_path = PATH+'LabeledApproved_full/'
fnames = glob.glob(frames_path+'*.png')
lnames = [labels_path+os.path.basename(fn)[:-4]+'_L.png' for fn in fnames]
img_sz = (480,360) | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
Standardize | imgs-=0.4
imgs/=0.3
n,r,c,ch = imgs.shape | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
Convert labels
The following loads, parses, and converts the segment labels we need for targets.
In particular we're looking to make the segmented targets into integers for classification purposes. | def parse_code(l):
a,b = l.strip().split("\t")
return tuple(int(o) for o in a.split(' ')), b
label_codes,label_names = zip(*[
parse_code(l) for l in open(PATH+"label_colors.txt")])
label_codes,label_names = list(label_codes),list(label_names) | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
Each segment / category is indicated by a particular color. The following maps each unique pixel to it's category. | list(zip(label_codes,label_names))[:5] | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
Test set
Next we load test set, set training/test images and labels. | fn_test = set(o.strip() for o in open(PATH+'test.txt','r'))
is_test = np.array([o.split('/')[-1] in fn_test for o in fnames])
trn = imgs[is_test==False]
trn_labels = labels_int[is_test==False]
test = imgs[is_test]
test_labels = labels_int[is_test]
trn.shape,test_labels.shape
rnd_trn = len(trn_labels)
rnd_test = len(... | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
The Tiramisu
Now that we've prepared our data, we're ready to introduce the Tiramisu.
Conventional CNN's for image segmentation are very similar to the kind we looked at for style transfer. Recall that it involved convolutions with downsampling (stride 2, pooling) to increase the receptive field, followed by upsampling... | def relu(x): return Activation('relu')(x)
def dropout(x, p): return Dropout(p)(x) if p else x
def bn(x): return BatchNormalization(mode=2, axis=-1)(x)
def relu_bn(x): return relu(bn(x))
def concat(xs): return merge(xs, mode='concat', concat_axis=-1)
def conv(x, nf, sz, wd, p, stride=1):
x = Convolution2D(nf, sz, ... | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
This is the downsampling transition.
In the original paper, downsampling consists of 1x1 convolution followed by max pooling. However we've found a stride 2 1x1 convolution to give better results. | def transition_dn(x, p, wd):
# x = conv_relu_bn(x, x.get_shape().as_list()[-1], sz=1, p=p, wd=wd)
# return MaxPooling2D(strides=(2, 2))(x)
return conv_relu_bn(x, x.get_shape().as_list()[-1], sz=1, p=p, wd=wd, stride=2) | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
This is the upsampling transition. We use a deconvolution layer. | def transition_up(added, wd=0):
x = concat(added)
_,r,c,ch = x.get_shape().as_list()
return Deconvolution2D(ch, 3, 3, (None,r*2,c*2,ch), init='he_uniform',
border_mode='same', subsample=(2,2), W_regularizer=l2(wd))(x)
# x = UpSampling2D()(x)
# return conv(x, ch, 2, wd, 0) | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
Finally we put together the entire network. | def create_tiramisu(nb_classes, img_input, nb_dense_block=6,
growth_rate=16, nb_filter=48, nb_layers_per_block=5, p=None, wd=0):
if type(nb_layers_per_block) is list or type(nb_layers_per_block) is tuple:
nb_layers = list(nb_layers_per_block)
else: nb_layers = [nb_layers_per_block] * nb_dense_... | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
Train
Now we can train.
These architectures can take quite some time to train. | limit_mem()
input_shape = (224,224,3)
img_input = Input(shape=input_shape)
x = create_tiramisu(12, img_input, nb_layers_per_block=[4,5,7,10,12,15], p=0.2, wd=1e-4)
model = Model(img_input, x)
gen = segm_generator(trn, trn_labels, 3, train=True)
gen_test = segm_generator(test, test_labels, 3, train=False)
model.c... | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
View results
Let's take a look at some of the results we achieved. | colors = [(128, 128, 128), (128, 0, 0), (192, 192, 128), (128, 64, 128), (0, 0, 192),
(128, 128, 0), (192, 128, 128), (64, 64, 128), (64, 0, 128), (64, 64, 0),
(0, 128, 192), (0, 0, 0)]
names = ['sky', 'building', 'column_pole', 'road', 'sidewalk', 'tree',
'sign', 'fence', 'car', 'ped... | data_science/courses/deeplearning2/tiramisu-keras.ipynb | jmhsi/justin_tinker | apache-2.0 |
Can you plot the distribution of protein sizes in the data/proteome.faa file? | %matplotlib inline
import matplotlib.pyplot as plt
sizes = []
for seq in SeqIO.parse('../data/proteome.faa', 'fasta'):
sizes.append(len(seq))
plt.hist(sizes, bins=100)
plt.xlabel('protein size')
plt.ylabel('count'); | notebooks/[6a]-Exercises-solutions.ipynb | mgalardini/2017_python_course | gpl-2.0 |
Can you count the number of CDS sequences in the data/ecoli.gbk file? | counter = 0
for seq in SeqIO.parse('../data/ecoli.gbk', 'genbank'):
for feat in seq.features:
if feat.type == 'CDS':
counter += 1
counter | notebooks/[6a]-Exercises-solutions.ipynb | mgalardini/2017_python_course | gpl-2.0 |
Can you compute the average root-to-tip distance in the data/tree.nwk file? | from Bio import Phylo
tree = Phylo.read('../data/tree.nwk', 'newick')
distances = []
for node in tree.get_terminals():
distances.append(tree.distance(tree.root, node))
sum(distances)/float(len(distances)) | notebooks/[6a]-Exercises-solutions.ipynb | mgalardini/2017_python_course | gpl-2.0 |
Networkx
Can you read the yeast protein interaction network in data/yeast.gml? Can you plot the degree distribution of the proteins contained in the graph? | import networkx as nx
graph = nx.read_gml('../data/yeast.gml')
plt.hist(nx.degree(graph).values(), bins=20)
plt.xlabel('degree')
plt.ylabel('count'); | notebooks/[6a]-Exercises-solutions.ipynb | mgalardini/2017_python_course | gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.