markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
The issue here is the finality of a probability of zero. Out of the three 15-letter words, it turns out that "nongovernmental" is in the dictionary, but if it hadn't been, if somehow our corpus of words had missed it, then the probability of that whole phrase would have been zero. It seems that is too strict; there m... | def pdist_additive_smoothed(counter, c=1):
"""The probability of word, given evidence from the counter.
Add c to the count for each item, plus the 'unknown' item."""
N = sum(counter.values()) # Amount of evidence
Nplus = N + c * (len(counter) + 1) # Evidence plus fake observations
return la... | _____no_output_____ | MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
But now there's a problem ... we now have previously-unseen words with non-zero probabilities. And maybe 10-12 is about right for words that are observed in text: that is, if I'm *reading* a new text, the probability that the next word is unknown might be around 10-12. But if I'm *manufacturing* 20-letter sequences a... | segment.cache.clear()
segment('thisisatestofsegmentationofalongsequenceofwords') | _____no_output_____ | MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
There are two problems: First, we don't have a clear model of the unknown words. We just say "unknown" butwe don't distinguish likely unknown from unlikely unknown. For example, is a 8-character unknown more likely than a 20-character unknown?Second, we don't take into account evidence from *parts* of the unknown.... | singletons = (w for w in COUNTS if COUNTS[w] == 1)
lengths = map(len, singletons)
Counter(lengths).most_common()
1357 / sum(COUNTS.values())
hist(lengths, bins=len(set(lengths)));
def pdist_good_turing_hack(counter, onecounter, base=1/26., prior=1e-8):
"""The probability of word, given evidence from the counter.
... | _____no_output_____ | MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
That was somewhat unsatisfactory. We really had to crank up the prior, specifically because the process of running `segment` generates so many non-word candidates (and also because there will be fewer unknowns with respect to the billion-word `WORDS1` than with respect to the million-word `WORDS`). It would be better... | print P1w('francisco')
print P1w('individuals') | 7.73314623661e-05
7.72494966889e-05
| MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
They have similar unigram probabilities but differ in their freedom to be the second word of a bigram: | print [bigram for bigram in COUNTS2 if bigram.endswith('francisco')]
print [bigram for bigram in COUNTS2 if bigram.endswith('individuals')] | ['are individuals', 'other individuals', 'on individuals', 'infected individuals', 'in individuals', 'where individuals', 'or individuals', 'which individuals', 'to individuals', 'both individuals', 'help individuals', 'more individuals', 'interested individuals', 'from individuals', '<S> individuals', 'income individu... | MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
Intuitively, words that appear in many bigrams before are more likely to appear in a new, previously unseen bigram. In *Kneser-Ney* smoothing (Reinhard Kneser, Hermann Ney) we multiply the bigram counts by this ratio. But I won't implement that here, because The Count never covered it.(10) One More Task: Secret Codes=... | def rot(msg, n=13):
"Encode a message with a rotation (Caesar) cipher."
return encode(msg, alphabet[n:]+alphabet[:n])
def encode(msg, key):
"Encode a message with a substitution cipher."
table = string.maketrans(upperlower(alphabet), upperlower(key))
return msg.translate(table)
def upperlower... | _____no_output_____ | MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
Now decoding is easy: try all 26 candidates, and find the one with the maximum Pwords: | def decode_rot(secret):
"Decode a secret message that has been encoded with a rotation cipher."
candidates = [rot(secret, i) for i in range(len(alphabet))]
return max(candidates, key=lambda msg: Pwords(tokens(msg)))
msg = 'Who knows the answer?'
secret = rot(msg, 17)
print(secret)
print(decode_rot(secret)) | Nyf befnj kyv rejnvi?
Who knows the answer?
| MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
Let's make it a tiny bit harder. When the secret message contains separate words, it is too easy to decode by guessing that the one-letter words are most likely "I" or "a". So what if the encode routine mushed all the letters together: | def encode(msg, key):
"Encode a message with a substitution cipher; remove non-letters."
msg = cat(tokens(msg)) ## Change here
table = string.maketrans(upperlower(alphabet), upperlower(key))
return msg.translate(table) | _____no_output_____ | MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
Now we can decode by segmenting. We change candidates to be a list of segmentations, and still choose the candidate with the best Pwords: | def decode_rot(secret):
"""Decode a secret message that has been encoded with a rotation cipher,
and which has had all the non-letters squeezed out."""
candidates = [segment(rot(secret, i)) for i in range(len(alphabet))]
return max(candidates, key=lambda msg: Pwords(msg))
msg = 'Who knows the answer thi... | -123 p ah d g h p l max t g l p x km a bl mb f x t gr h g x un x e ex k
-133 q b i eh i q m n by u hm q y l n b cm n c g y u h s i h y vo y ff y l
-128 r c j f i jr no c z v in r z mo c d nod h z v it j i z w p z g g z m
-115 sd k g j k so p da w j os an p de op e i a w j u k j ax q ah h an
-144 t el h k l t p q e b x ... | MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
What about a general substitution cipher? The problem is that there are 26! substitution ciphers, and we can't enumerate all of them. We would need to search through this space. Initially make some guess at a substitution, then swap two letters; if that looks better keep going, if not try something else. This appro... | correct('cpgratulations') | _____no_output_____ | MIT | ipynb/How to Do Things with Words.ipynb | mikiec84/pytudes |
Experimenting with smaller action spacesHere we look at the board (states) that all evolve from an initial board. We're going to train on all board snapshots of a series of heuristically played games. | def new_initial_state(heuristics):
board = GomokuBoard(heuristics, N=15, disp_width=8)
policy = HeuristicGomokuPolicy(style = 2, bias=.5, topn=5,
threat_search=ThreatSearch(2,2))
board.set(H,8).set('G',6).set(G,8).set(F,8).set(H,9).set(H,10)
return board, policy
... | _____no_output_____ | Apache-2.0 | GomokuData.ipynb | smurve/DeepGomoku |
Plausibility check | index = np.argmax(values[3])
r, c = np.divmod(index,17)
pos=gt.m2b((r, c), 17)
print(r,c,pos, values[3][r][c])
from wgomoku import create_samples_and_qvalues
def data_from_game(board, policy, heuristics):
"""
Careful: This function rolls back the board
"""
s,v = create_samples_and_qvalues(board, heu... | _____no_output_____ | Apache-2.0 | GomokuData.ipynb | smurve/DeepGomoku |
Yet another plausibility check | sample_no = 30
index = np.argmax(data[1][sample_no])
r, c = np.divmod(index,17)
pos=gt.m2b((r, c), 17)
print(r,c,pos)
print("Value of the suggested pos:")
print(data[1][sample_no][r][c])
print("Value to the right of the suggested pos:")
print(data[1][sample_no][r][c+1]) | _____no_output_____ | Apache-2.0 | GomokuData.ipynb | smurve/DeepGomoku |
Save the results for later training | np.save("samples.npy", data[0])
np.save("values.npy", data[1])
samples = np.load("samples.npy")
values = np.load("values.npy")
samples.shape, values.shape
np.rollaxis(samples[0], 2, 0)
np.rollaxis(values[0], 2, 0)
np.rollaxis(samples[0], 2, 0)[0] + 2*np.rollaxis(samples[0], 2, 0)[1] | _____no_output_____ | Apache-2.0 | GomokuData.ipynb | smurve/DeepGomoku |
Randomized Benchmarking IntroductionOne of the main challenges in building a quantum information processor is the non-scalability of completelycharacterizing the noise affecting a quantum system via process tomography. In addition, process tomography is sensitive to noise in the pre- and post rotation gates plus the ... | #Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
#Import the RB Functions
import qiskit.ignis.verification.randomized_benchmarking as rb
#Import Qiskit classes
import qiskit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.pr... | _____no_output_____ | Apache-2.0 | content/ch-quantum-hardware/randomized-benchmarking.ipynb | NunoEdgarGFlowHub/qiskit-textbook |
Step 1: Generate RB sequencesThe RB sequences consist of random Clifford elements chosen uniformly from the Clifford group on $n$-qubits, including a computed reversal element,that should return the qubits to the initial state.More precisely, for each length $m$, we choose $K_m$ RB sequences. Each such sequence contai... | #Generate RB circuits (2Q RB)
#number of qubits
nQ=2
rb_opts = {}
#Number of Cliffords in the sequence
rb_opts['length_vector'] = [1, 10, 20, 50, 75, 100, 125, 150, 175, 200]
#Number of seeds (random sequences)
rb_opts['nseeds'] = 5
#Default pattern
rb_opts['rb_pattern'] = [[0,1]]
rb_circs, xdata = rb.randomized_be... | Making the n=2 Clifford Table
| Apache-2.0 | content/ch-quantum-hardware/randomized-benchmarking.ipynb | NunoEdgarGFlowHub/qiskit-textbook |
As an example, we print the circuit corresponding to the first RB sequence | print(rb_circs[0][0]) | βββββββββββββββ β βββββββββββββββββ βββ Β»
qr_0: |0>βββββββββββββββ βββ€ H ββ€ S ββ€ Z βββββ€ Z ββ€ Sdg ββ€ H ββββ ββββββββ€MββββββΒ»
βββββββββββββββ΄βββββββ€βββββ€βββββ€ β βββββ€βββββββ€βββββ€βββ΄βββββββββ₯ββββββΒ»
qr_1: |0>β€ Sdg ββ€ H ββ€ X ββ€ H ββ€ S ββ€ Z βββββ€ Z ββ€ Sdg ββ€ H ββ€ X ββ€ H βββ«ββ€ S... | Apache-2.0 | content/ch-quantum-hardware/randomized-benchmarking.ipynb | NunoEdgarGFlowHub/qiskit-textbook |
One can verify that the Unitary representing each RB circuit should be the identity (with a global phase). We simulate this using Aer unitary simulator. | # Create a new circuit without the measurement
qregs = rb_circs[0][-1].qregs
cregs = rb_circs[0][-1].cregs
qc = qiskit.QuantumCircuit(*qregs, *cregs)
for i in rb_circs[0][-1][0:-nQ]:
qc.data.append(i)
# The Unitary is an identity (with a global phase)
backend = qiskit.Aer.get_backend('unitary_simulator')
basis_gate... | [[ 0.+1.j -0.+0.j -0.+0.j -0.+0.j]
[-0.+0.j 0.+1.j -0.-0.j 0.+0.j]
[ 0.-0.j 0.+0.j 0.+1.j -0.+0.j]
[-0.-0.j 0.-0.j 0.-0.j 0.+1.j]]
| Apache-2.0 | content/ch-quantum-hardware/randomized-benchmarking.ipynb | NunoEdgarGFlowHub/qiskit-textbook |
Step 2: Execute the RB sequences (with some noise)We can execute the RB sequences either using Qiskit Aer Simulator (with some noise model) or using IBMQ provider, and obtain a list of results.By assumption each operation $C_{i_j}$ is allowed to have some error, represented by $\Lambda_{i_j,j}$, and each sequence can ... | # Run on a noisy simulator
noise_model = NoiseModel()
# Depolarizing_error
dp = 0.005
noise_model.add_all_qubit_quantum_error(depolarizing_error(dp, 1), ['u1', 'u2', 'u3'])
noise_model.add_all_qubit_quantum_error(depolarizing_error(2*dp, 2), 'cx')
backend = qiskit.Aer.get_backend('qasm_simulator') | _____no_output_____ | Apache-2.0 | content/ch-quantum-hardware/randomized-benchmarking.ipynb | NunoEdgarGFlowHub/qiskit-textbook |
Step 3: Get statistics about the survival probabilitiesFor each of the $K_m$ sequences the survival probability $Tr[E_\psi \textit{S}_{\textbf{i}_\textbf{m}}(\rho_\psi)]$is measured. Here $\rho_\psi$ is the initial state taking into account preparation errors and $E_\psi$ is thePOVM element that takes into account mea... | # Create the RB fitter
backend = qiskit.Aer.get_backend('qasm_simulator')
basis_gates = ['u1','u2','u3','cx']
shots = 200
qobj_list = []
rb_fit = rb.RBFitter(None, xdata, rb_opts['rb_pattern'])
for rb_seed,rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
new_rb_circ_seed = qiskit.compile... | Compiling seed 0
| Apache-2.0 | content/ch-quantum-hardware/randomized-benchmarking.ipynb | NunoEdgarGFlowHub/qiskit-textbook |
Plot the results | plt.figure(figsize=(8, 6))
ax = plt.subplot(1, 1, 1)
# Plot the essence by calling plot_rb_data
rb_fit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False)
# Add title and label
ax.set_title('%d Qubit RB'%(nQ), fontsize=18)
plt.show() | _____no_output_____ | Apache-2.0 | content/ch-quantum-hardware/randomized-benchmarking.ipynb | NunoEdgarGFlowHub/qiskit-textbook |
The intuition behind RBThe depolarizing quantum channel has a parameter $\alpha$, and works like this: with probability $\alpha$, the state remains the same as before; with probability $1-\alpha$, the state becomes the totally mixed state, namely:$$\rho_f = \alpha \rho_i + \frac{1-\alpha}{2^n} * \mathbf{I}$$Suppose th... | #Count the number of single and 2Q gates in the 2Q Cliffords
gates_per_cliff = rb.rb_utils.gates_per_clifford(qobj_list, xdata[0],basis_gates, rb_opts['rb_pattern'][0])
for i in range(len(basis_gates)):
print("Number of %s gates per Clifford: %f"%(basis_gates[i],
np.... | _____no_output_____ | Apache-2.0 | content/ch-quantum-hardware/randomized-benchmarking.ipynb | NunoEdgarGFlowHub/qiskit-textbook |
Homework for week 4 Functions 1. Convert String Number to IntegerCreate a function that can take something like ```"$5,356"``` or ```"$250,000"``` or even ```"$10.75"``` and covert into integers like return ```5356```, ```250000``` and ```11``` respectively. | ## build function here
## call the function on "$5,356"
## Did you get 5356?
## call the function on "$10.75"
## Did you get 11?
## Use map() to run your function on the following list
## save result in a list called updated_list
my_amounts = ["$12.24", "$4,576.33", "$23,629.01"] | _____no_output_____ | MIT | homework/homework-for-week-4-BLANKS.ipynb | jchapamalacara/fall21-students-practical-python |
3. What if we encounter a list that has a mix of numbers as strings and integers and floats? | ## Run this cell
more_amounts = [960, "$12.24", "$4,576.33", "$23,629.01", 23.656]
## tweaked the function here to handle all situations
## run it on more_amounts using map()
| _____no_output_____ | MIT | homework/homework-for-week-4-BLANKS.ipynb | jchapamalacara/fall21-students-practical-python |
Compare the outer envelope stellar mass and SDSS redMaPPer clusters DSigma profiles of HSC massive galaxies | # DeltaSigma profiles of HSC massive galaxies
topn_massive = pickle.load(open(os.path.join(res_dir, 'topn_galaxies_sum.pkl'), 'rb'))
# DeltaSigma profiles of redMaPPer and CAMIRA clusters
topn_cluster = pickle.load(open(os.path.join(res_dir, 'topn_clusters_cen_sum.pkl'), 'rb'))
# For clusters, but using both central ... | _____no_output_____ | MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
DSigma profiles of mock galaxies | sim_dsig = Table.read(os.path.join(sim_dir, 'sim_merge_all_dsig.fits')) | _____no_output_____ | MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Halo mass distributions | sim_mhalo = Table.read(os.path.join(sim_dir, 'sim_merge_mhalo_hist.fits')) | _____no_output_____ | MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Pre-compute lensing results for HSC galaxies | # Pre-compute
s16a_precompute = os.path.join(data_dir, 'topn_public_s16a_medium_precompute.hdf5')
hsc_pre = Table.read(s16a_precompute, path='hsc_extra')
red_sdss = Table.read(s16a_precompute, path='redm_sdss')
red_hsc = Table.read(s16a_precompute, path='redm_hsc') | _____no_output_____ | MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Pre-compute lensing results for randoms | # Lensing data using medium photo-z quality cut
s16a_lensing = os.path.join(data_dir, 's16a_weak_lensing_medium.hdf5')
# Random
s16a_rand = Table.read(s16a_lensing, path='random') | _____no_output_____ | MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Pre-defined number density bins | topn_bins = Table.read(os.path.join(bin_dir, 'topn_bins.fits')) | _____no_output_____ | MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Compute the DSigma profiles of SDSS redMaPPer clusters- 0.2 < z < 0.38 clusters | plt.scatter(red_sdss['z_best'], red_sdss['lambda_cluster_redm'], s=5, alpha=0.3)
mask_sdss_1 = (red_sdss['z_best'] >= 0.19) & (red_sdss['z_best'] <= 0.35)
print(mask_sdss_1.sum())
sdss_bin_1 = Table(copy.deepcopy(topn_bins[0]))
sdss_bin_1['n_obj'] = mask_sdss_1.sum()
sdss_bin_1['rank_low'] = 1
sdss_bin_1['rank_upp'] ... |
# Using column: lambda_cluster_redm
# Bin 1: 0 - 54
# Dealing with Bin: 1
| MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Compute the DSigma profiles of HSC redMaPPer clusters | plt.scatter(red_hsc['z_best'], red_hsc['lambda'], s=5, alpha=0.3)
mask_hsc_1 = (red_hsc['z_best'] >= 0.19) & (red_hsc['z_best'] <= 0.35)
redm_hsc_dsig_1 = wlensing.gather_topn_dsigma_profiles(
red_hsc, s16a_rand, sdss_bin_1, 'lambda',
mask=mask_hsc_1, n_rand=100000, n_boot=200, verbose=True)
print(np.min(red... |
# Using column: lambda
# Bin 1: 0 - 54
14.115065
# Dealing with Bin: 1
| MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Compute the DSigma profiles of HSC massive galaxies | # S18A bright star mask
bsm_s18a = hsc_pre['flag'] > 0
# General mask for HSC galaxies
mask_mout_1 = (
(hsc_pre['c82_100'] <= 18.) & (hsc_pre['logm_100'] - hsc_pre['logm_50'] <= 0.2) & (hsc_pre['logm_50_100'] > 0) &
bsm_s18a & (hsc_pre['z'] >= 0.19) & (hsc_pre['z'] <= 0.35)
)
mask_mout_2 = (
(hsc_pre['c82... |
# Using column: logm_50_100
# Bin 1: 0 - 54
# Dealing with Bin: 1
| MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Making a figure for the paper | def compare_sdss_redm_profiles(
dsig_ref, dsig_cmp, sim_dsig, sig_type='bt', compare_to_model=True,
label_ref=r'$\rm Ref$', label_cmp=r'$\rm Test$',
sub_ref=r'{\rm Ref}', sub_cmp=r'{\rm Test}',
cmap_list=None, color_bins=None,
marker_ref='o', msize_ref=180,
marker_cmp='P', msize_cmp=180,
s... | _____no_output_____ | MIT | notebooks/figure/figF1.ipynb | mattkwiecien/jianbing |
Pre-procesamiento de datosTodos los datos operados por un algoritmo de inteligencia artificial deben ser numΓ©ricos en una forma especΓfica. Debido a que la mayorΓa de datos se encuentran en un formato diferente, que no puede ser utilizado en un algoritmo, estos deben ser convertidos a un formato adecuado. Esta tarea s... | import pandas as pd
from sklearn.preprocessing import LabelEncoder
# Leer los datos del archivo CSV original
df = pd.read_csv('telco.csv')
df.info()
# Revisar la composiciΓ³n de datos en el DataFrame
df.head() | _____no_output_____ | MIT | clase4/4-1_preprocessing.ipynb | jinchuika/umg-ai |
ObjetivoAplicaremos pre-procesamiento de datos para realizar una predicciΓ³n en la columna `MonthlyCharges`, intentando predecir los pagos mensuales de un cliente. Para ello, seleccionamos las columnas que puedan servir como caracterΓsticas (`X`) y nuestra variable objetivo (`y`). | # Elegir las columnas a utilizar
columnas_importantes = [
'gender',
'Partner',
'Dependents',
'SeniorCitizen',
'PhoneService',
'MultipleLines',
'InternetService',
'MonthlyCharges'
]
# Nuevo DataFrame con las columnas seleccionadas
df_limpio = df[columnas_importantes]
# Revisamos una mues... | _____no_output_____ | MIT | clase4/4-1_preprocessing.ipynb | jinchuika/umg-ai |
Como podemos observar, la mayorΓa de columnas con datos categΓ³ricos se encuentran en formato de texto. Si deseamos utilizar esos datos en un algoritmo de inteligencia artificial, necesitamos convertirlos en representaciones numΓ©ricas. Para ello, realizaremos una tarea de pre-procesamiento utilizando un codificador de t... | # Crear el encoder para la columna gender
gender_encoder = LabelEncoder()
# "Aprender" los datos para el encoder.
# Este proceso reconoce las diferentes categorΓas en los datos.
# Para cada categorΓa, asignarΓ‘ un nΓΊmero iniciando desde 0
gender_encoder.fit(df_limpio['gender'])
# Podemos transformar los datos original... | _____no_output_____ | MIT | clase4/4-1_preprocessing.ipynb | jinchuika/umg-ai |
Una forma mΓ‘s eficienteYa que necesitamos un codificador para cada columna, crearemos una estructura de datos que permita almacenar un codificador distinto para cada columna. | # Empezamos revisando la de columnas del DataFrame
for columna in df_limpio.columns:
print(columna) | gender
Partner
Dependents
SeniorCitizen
PhoneService
MultipleLines
InternetService
MonthlyCharges
| MIT | clase4/4-1_preprocessing.ipynb | jinchuika/umg-ai |
Ya que no todas las columnas necesitan ser codificadas (`SeniorCitizen` ya se encuentra codificada y `MonthlyCharges` no es un dato de tipo categΓ³rico), incluiremos ΓΊnicamente las columnas con datos categΓ³ricos que necesitan ser codificados. | # Creamos un nuevo DataFrame que tendrΓ‘ los datos convertidos
df_final = pd.DataFrame()
# En un diccionario, almacenamos un codificador por cada columna
encoders = {
'gender': LabelEncoder(),
'Partner': LabelEncoder(),
'Dependents': LabelEncoder(),
'PhoneService': LabelEncoder(),
'MultipleLines': L... | _____no_output_____ | MIT | clase4/4-1_preprocessing.ipynb | jinchuika/umg-ai |
*Data Science Unit 4 Sprint 3 Assignment 2* Convolutional Neural Networks (CNNs) Assignment- Part 1: Pre-Trained Model- Part 2: Custom CNN Model- Part 3: CNN with Data AugmentationYou will apply three different CNN models to a binary image classification model using Keras. Classify images of Mountains (`./data/mounta... | import numpy as np
import os
from skimage import color, io
from sklearn.model_selection import train_test_split
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
from tens... | _____no_output_____ | MIT | module2-convolutional-neural-networks/LS_DS_432_Convolution_Neural_Networks_Assignment.ipynb | j-m-d-h/DS-Unit-4-Sprint-3-Deep-Learning |
Instatiate Model | for layer in resnet.layers:
layer.trainable = False
x = resnet.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(1, activation='sigmoid')(x)
model = Model(resnet.input, predictions)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) | _____no_output_____ | MIT | module2-convolutional-neural-networks/LS_DS_432_Convolution_Neural_Networks_Assignment.ipynb | j-m-d-h/DS-Unit-4-Sprint-3-Deep-Learning |
Fit Model | model.fit(pics_train, labels_train, validation_data=(pics_test, labels_test), epochs=4)
model.predict(pics[206]) | _____no_output_____ | MIT | module2-convolutional-neural-networks/LS_DS_432_Convolution_Neural_Networks_Assignment.ipynb | j-m-d-h/DS-Unit-4-Sprint-3-Deep-Learning |
Custom CNN ModelIn this step, write and train your own convolutional neural network using Keras. You can use any architecture that suits you as long as it has at least one convolutional and one pooling layer at the beginning of the network - you can add more if you want. | Train on 561 samples, validate on 141 samples
Epoch 1/5
561/561 [==============================] - 18s 32ms/sample - loss: 0.2667 - accuracy: 0.9073 - val_loss: 0.1186 - val_accuracy: 0.9858
Epoch 2/5
561/561 [==============================] - 18s 32ms/sample - loss: 0.2046 - accuracy: 0.9073 - val_loss: 0.3342 - val_a... | MIT | module2-convolutional-neural-networks/LS_DS_432_Convolution_Neural_Networks_Assignment.ipynb | j-m-d-h/DS-Unit-4-Sprint-3-Deep-Learning | |
Custom CNN Model with Image Manipulations *This a stretch goal, and it's relatively difficult*To simulate an increase in a sample of image, you can apply image manipulation techniques: cropping, rotation, stretching, etc. Luckily Keras has some handy functions for us to apply these techniques to our mountain and fores... | # State Code for Image Manipulation Here | _____no_output_____ | MIT | module2-convolutional-neural-networks/LS_DS_432_Convolution_Neural_Networks_Assignment.ipynb | j-m-d-h/DS-Unit-4-Sprint-3-Deep-Learning |
Set Up | # imports and juppyter environment settings
%run -i settings.py
# setup environment variables
%run -i setup.py
# To auto-reload modules in jupyter notebook (so that changes in files *.py doesn't require manual reloading):
# for auto-reloading external modules
# see http://stackoverflow.com/questions/1907993/autoreload-... | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
Summary Statistics | # In this example, the data frame is described and [βobjectβ] is passed to include parameter
# to see description of object series. [.20, .40, .60, .80] is passed to percentile parameter
# to view the respective percentile of Numeric series.
# see: https://www.geeksforgeeks.org/python-pandas-dataframe-describe-method/... | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
Data Cleaning | # number of na values in each column
df.isna().sum() | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
For our study, 'personId', 'offense_date', 'final_disposition', 'fips', 'race', 'gender', 'charge', 'fips_area' are mandatory columns.So removing all records where these field values are missing will be removed | df.dropna(axis=0, subset=['final_disposition'], inplace=True)
df.dropna(axis=0, subset=['race'], inplace=True)
df.isna().sum()
# for the moment we consider case_class as important field, so we will impute missing value 'unknown'
df['ammended_charge'].fillna('unknown', inplace=True)
df.isna().sum()
duplicate_records = p... | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
Our dataset has 974935 duplicate records, so we purge these records from our dataset | #drop duplicate records
df = df.drop_duplicates(['person_id', 'offense_date', 'final_disposition', 'fips', 'race', 'gender', 'charge', 'ammended_charge'])
len(df) | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
df * We can see that hearing_date, fips, gender, charge_type and person_id do not have any missing data, however we need to address the missing data for other columns. | df.isna().sum() | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
Per our domain expert if ammended_charge is reduced to **'DWI'** then the case is a candidate for expungement. | dwi_ammended_charge_df = df [df.ammended_charge.str.contains('DWI') == True]
len(dwi_ammended_charge_df) | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
Our aim is to derive the cadidate cases for expungement based on hearing_results, let us examine the uniuqe values for hearing_result | # top 15 hearing results
hearing_result_counts = df['final_disposition'].value_counts()
subset = hearing_result_counts[:15]
sns.barplot(y=subset.index, x=subset.values)
# to 15 hearing results by gender
df_result_bygendger = df.groupby(['final_disposition', 'gender'])\
.size()\
... | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
Preprocessing Data Adding fips_area name column | #load fips code table
fips_file = 'reference-data/va-fips-codes.csv'
fips_df = pd.read_csv(fips_file)
fips_df = fips_df[['CountyFIPSCode', 'GUName']]
fips_df
#add fips_GUName
df = pd.merge(df,fips_df,left_on='fips', right_on='CountyFIPSCode', how='left')\
.drop(columns=['CountyFIPSCode'], axis=1)\
.rename(colu... | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
Identifying the candidates for case expungement Assumptions maded based on domain expert input:1. If the final_disposition is any the following values 'Dismissed','Noile Prosequi','Not Guilty', 'Withdrawn', 'Not Found', 'No Indictment Presented', 'No Longer Under Advisement', 'Not True Bill' then the case is candidate... | cand_list =['Dismissed','Noile Prosequi','Not Guilty', 'Withdrawn', 'Not Found', 'No Indictment Presented', 'No Longer Under Advisement', 'Not True Bill']
df['candidate'] = [1 if x in cand_list else 0 for x in df['final_disposition']]
df
df.groupby(['candidate']).count().head()
df.groupby(['candidate','race','gender'])... | _____no_output_____ | MIT | va_circuit_court_eda.ipynb | mh4ey/va-case-expungement |
Implementing ResNet in PyTorchToday we are going to implement the famous ResNet from Kaiming He et al. (Microsoft Research). It won the 1st place on the ILSVRC 2015 classification task.The original paper can be read from [here ](https://arxiv.org/abs/1512.03385) and it is very easy to follow, additional material can b... | class Conv2dAuto(nn.Conv2d):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.padding = (self.kernel_size[0] // 2, self.kernel_size[1] // 2) # dynamic add padding based on the kernel_size
conv3x3 = partial(Conv2dAuto, kernel_size=3, bias=False)
con... | Conv2dAuto(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
| MIT | ResNet.ipynb | harshithbelagur/ResNet |
Residual BlockTo make clean code is mandatory to think about the main building block of each application, or of the network in our case. The residual block takes an input with `in_channels`, applies some blocks of convolutional layers to reduce it to `out_channels` and sum it up to the original input. If their sizes m... | class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.in_channels, self.out_channels = in_channels, out_channels
self.blocks = nn.Identity()
self.shortcut = nn.Identity()
def forward(self, x):
residual = x
... | _____no_output_____ | MIT | ResNet.ipynb | harshithbelagur/ResNet |
Let's test it with a dummy vector with one one, we should get a vector with two | dummy = torch.ones((1, 1, 1, 1))
block = ResidualBlock(1, 64)
block(dummy) | _____no_output_____ | MIT | ResNet.ipynb | harshithbelagur/ResNet |
In ResNet each block has a expansion parameter in order to increase the `out_channels`. Also, the identity is defined as a Convolution followed by an Activation layer, this is referred as `shortcut`. Then, we can just extend `ResidualBlock` and defined the `shortcut` function. | from collections import OrderedDict
class ResNetResidualBlock(ResidualBlock):
def __init__(self, in_channels, out_channels, expansion=1, downsampling=1, conv=conv3x3, *args, **kwargs):
super().__init__(in_channels, out_channels)
self.expansion, self.downsampling, self.conv = expansion, downsampling... | _____no_output_____ | MIT | ResNet.ipynb | harshithbelagur/ResNet |
Basic BlockA basic ResNet block is composed by two layers of `3x3` convs/batchnorm/relu. In the picture, the lines represnet the residual operation. The dotted line means that the shortcut was applied to match the input and the output dimension. Let's first create an handy function to ... | from collections import OrderedDict
def conv_bn(in_channels, out_channels, conv, *args, **kwargs):
return nn.Sequential(OrderedDict({'conv': conv(in_channels, out_channels, *args, **kwargs),
'bn': nn.BatchNorm2d(out_channels) }))
conv_bn(3, 3, nn.Conv2d, kernel_size=3)
class ResNetBasicBl... | ResNetBasicBlock(
(blocks): Sequential(
(0): Sequential(
(conv): Conv2dAuto(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
(1): ReLU()
(2): Sequential(
(conv): Conv2dAuto(6... | MIT | ResNet.ipynb | harshithbelagur/ResNet |
BottleNeckTo increase the network deepths but to decrese the number of parameters, the Authors defined a BottleNeck block that "The three layers are 1x1, 3x3, and 1x1 convolutions, where the 1Γ1 layers are responsible for reducing and then increasing (restoring) dimensions, leaving the 3Γ3 layer a bottleneck with smal... | class ResNetBottleNeckBlock(ResNetResidualBlock):
expansion = 4
def __init__(self, in_channels, out_channels, activation=nn.ReLU, *args, **kwargs):
super().__init__(in_channels, out_channels, expansion=4, *args, **kwargs)
self.blocks = nn.Sequential(
conv_bn(self.in_channels, self.out... | ResNetBottleNeckBlock(
(blocks): Sequential(
(0): Sequential(
(conv): Conv2dAuto(32, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
(1): ReLU()
(2): Sequential(
(conv): Conv2dAuto(64, 64, kern... | MIT | ResNet.ipynb | harshithbelagur/ResNet |
LayerA ResNet's layer is composed by blocks stacked one after the other. We can easily defined it by just stuck `n` blocks one after the other, just remember that the first convolution block has a stide of two since "We perform downsampling directly by convolutional layers that have a ... | class ResNetLayer(nn.Module):
def __init__(self, in_channels, out_channels, block=ResNetBasicBlock, n=1, *args, **kwargs):
super().__init__()
# 'We perform downsampling directly by convolutional layers that have a stride of 2.'
downsampling = 2 if in_channels != out_channels else 1
... | _____no_output_____ | MIT | ResNet.ipynb | harshithbelagur/ResNet |
EncoderSimilarly, the encoder is composed by multiple layer at increasing features size. | class ResNetEncoder(nn.Module):
"""
ResNet encoder composed by increasing different layers with increasing features.
"""
def __init__(self, in_channels=3, blocks_sizes=[64, 128, 256, 512], deepths=[2,2,2,2],
activation=nn.ReLU, block=ResNetBasicBlock, *args,**kwargs):
super()._... | _____no_output_____ | MIT | ResNet.ipynb | harshithbelagur/ResNet |
DecoderThe decoder is the last piece we need to create the full network. It is a fully connected layer that maps the features learned by the network to their respective classes. Easily, we can defined it as: | class ResnetDecoder(nn.Module):
"""
This class represents the tail of ResNet. It performs a global pooling and maps the output to the
correct class by using a fully connected layer.
"""
def __init__(self, in_features, n_classes):
super().__init__()
self.avg = nn.AdaptiveAvgPool2d((1,... | _____no_output_____ | MIT | ResNet.ipynb | harshithbelagur/ResNet |
ResNetFinal, we can put all the pieces together and create the final model. | class ResNet(nn.Module):
def __init__(self, in_channels, n_classes, *args, **kwargs):
super().__init__()
self.encoder = ResNetEncoder(in_channels, *args, **kwargs)
self.decoder = ResnetDecoder(self.encoder.blocks[-1].blocks[-1].expanded_channels, n_classes)
def forward(self... | _____no_output_____ | MIT | ResNet.ipynb | harshithbelagur/ResNet |
We can now defined the five models proposed by the Authors, `resnet18,34,50,101,152` | def resnet18(in_channels, n_classes):
return ResNet(in_channels, n_classes, block=ResNetBasicBlock, deepths=[2, 2, 2, 2])
def resnet34(in_channels, n_classes):
return ResNet(in_channels, n_classes, block=ResNetBasicBlock, deepths=[3, 4, 6, 3])
def resnet50(in_channels, n_classes):
return ResNet(in_channel... | ----------------------------------------------------------------
Layer (type) Output Shape Param #
================================================================
Conv2d-1 [-1, 64, 112, 112] 9,408
BatchNorm2d-2 [-1, 64, 112, 112] 12... | MIT | ResNet.ipynb | harshithbelagur/ResNet |
Our modeling approach- We fully characterize the existence of a 1-round protocol by a Mixed Integer Linear Program. | from sage.all import *
import itertools
import random
from sage.sat.solvers.satsolver import SAT
from sage.sat.solvers.cryptominisat import CryptoMiniSat
from sage.misc.temporary_file import atomic_write
import copy
import time
solver = SAT(solver="LP")
solver.add_clause((-1,2))
solver.add_clause((1,3))
solution = solv... | finding a solution for l= 3
generating constraints ...
a_set = [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
[1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 ... | MIT | 3-eq-ILP-lab-mini-suf-submatrices.ipynb | anpc/perfect-reductions |
Evaluate, optimize, and fit a classifier BackgroundBefore we can begin making crop/non-crop predictions, we first need to evaluate, optimize, and fit a classifier. Because we are working with spatial data, and because the size of our training dataset is relatively small (by machine learning standards), we need to im... | # from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
import os
import joblib
import numpy as np
import pandas as pd
from joblib import dump
from pprint import pprint
import matplotlib.pyplot as plt
from odc.io.cgroups import get_cpu_quota
from sklearn.model_selection import GridSearchCV, S... | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
Analysis Parameters* `training_data`: Name and location of the training data `.txt` file output from runnning `1_Extract_training_data.ipynb`* `coordinate_data`: Name and location of the coordinate data `.txt` file output from runnning `1_Extract_training_data.ipynb`* `Classifier`: This parameter refers to the scikit-... | training_data = "results/training_data/sahel_training_data_20211110.txt"
Classifier = RandomForestClassifier
metric = 'balanced_accuracy'
output_suffix = '20211110' | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
K-Fold Cross Validation Parameters* `inner_cv_splits` : Number of cross-validation splits to do on the inner loop, e.g. `5`* `outer_cv_splits` : Number of cross-validation splits to do on the outer loop, e.g. `5`* `test_size` : This will determine what fraction of the dataset will be set aside as the testing dataset. ... | inner_cv_splits = 5
outer_cv_splits = 5
test_size = 0.20
| _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
Automatically find the number of cpus | ncpus=round(get_cpu_quota())
print('ncpus = '+str(ncpus)) | ncpus = 15
| Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
Import training and coordinate data | # load the data
model_input = np.loadtxt(training_data)
# coordinates = np.loadtxt(coordinate_data)
# load the column_names
with open(training_data, 'r') as file:
header = file.readline()
column_names = header.split()[1:]
# Extract relevant indices from training data
model_col_indices = [column_names.index(v... | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
Evaluating the classifierNow that we're happy with the spatial clustering, we can evaluate the classifier via _nested_, K-fold cross-validation.The k-fold cross-validation procedure is used to estimate the performance of machine learning models when making predictions on data not used during training. However, when th... | # Create the parameter grid
param_grid = {
'max_features': ['auto', 'log2', None],
'n_estimators': [150,200,250,300,350,400],
'criterion':['gini', 'entropy']
} | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
Now we will conduct the nested CV using the SKCV function. This will take a while to run depending on the number of inner and outer cv splits | outer_cv = KFold(n_splits=outer_cv_splits, shuffle=True,
random_state=0)
# lists to store results of CV testing
acc = []
f1 = []
roc_auc = []
i = 1
for train_index, test_index in outer_cv.split(X, y):
print(f"Working on {i}/{outer_cv_splits} outer cv split", end='\r')
model = Classifier... | Working on 5/5 outer cv split
| Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
The results of our model evaluation | print("=== Nested K-Fold Cross-Validation Scores ===")
print("Mean balanced accuracy: "+ str(round(np.mean(acc), 2)))
print("Std balanced accuracy: "+ str(round(np.std(acc), 2)))
print('\n')
print("Mean F1: "+ str(round(np.mean(f1), 2)))
print("Std F1: "+ str(round(np.std(f1), 2)))
print('\n')
print("Mean roc_auc: "+ s... | === Nested K-Fold Cross-Validation Scores ===
Mean balanced accuracy: 0.82
Std balanced accuracy: 0.01
Mean F1: 0.77
Std F1: 0.01
Mean roc_auc: 0.916
Std roc_auc: 0.01
| Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
These scores represent a robust estimate of the accuracy of our classifier. However, because we are using only a subset of data to fit and optimize the models, it is reasonable to expect these scores are an under-estimate of the final model's accuracy. Also, the _map_ accuracy will differ from the accuracies reported ... | #generate n_splits of train-test_split
rs = ShuffleSplit(n_splits=outer_cv_splits, test_size=test_size, random_state=0)
# #instatiate a gridsearchCV
clf = GridSearchCV(Classifier(),
param_grid,
scoring=metric,
verbose=1,
cv=rs.split(X, y),
... | Fitting 5 folds for each of 36 candidates, totalling 180 fits
The most accurate combination of tested parameters is:
{'criterion': 'entropy', 'max_features': None, 'n_estimators': 250}
The balanced_accuracy score using these parameters is:
0.82
| Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
Fit a modelUsing the best parameters from our hyperparmeter optmization search, we now fit our model on all the data to give the best possible model. | #create a new model
# new_model = Classifier(**clf.best_params_, random_state=1)
new_model = Classifier(**{'criterion': 'entropy', 'max_features': None, 'n_estimators': 200}, random_state=1)
new_model.fit(X, y) | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
Save the modelRunning this cell will export the classifier as a binary`.joblib` file. This will allow for importing the model in the subsequent script, `4_Predict.ipynb` | model_filename = 'results/sahel_ml_model_'+output_suffix+'.joblib'
dump(new_model, model_filename) | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/3_Train_fit_evaluate_classifier.ipynb | digitalearthafrica/crop-mask |
Loading resultsResults have the format: {conf:table_of_results},where **conf** represents the experimental setting and is the tuple (0-remove_stopwords, 1-remove_punctuation, 2-termsim_metric, 3-normalization, 4-termsim_th, 5-synsets_taken, 6-wscheme, 7-sim_metric) There is ... | #experiments = pickle.load(open("./Results/results_20170620_complex_normalization.pickle", 'rb'))
experiments = pickle.load(open("./Results/results_20170830_normalization_4termsimTh_Rada_Stevenson_Softcosine.pickle", 'rb'))
len(experiments)
# res = (threshold, accuracy, f_measure, precision, recall)
max([(conf, res[0][... | [[0.7 0.74092247 0.81886792 0.77575561 0.86705412]
[0.7 0.74092247 0.81886792 0.77575561 0.86705412]
[0.7 0.74018646 0.81875749 0.77411003 0.86887032]]
[[False True 'lin' 'lemma' 'lemma' 'bnc_ic_2007' False 0.5 'all' 'binary'
'mihalcea']
[False True 'lin' 'lemma' 'lemma' 'bnc_ic_2007' False 0... | MIT | SoftCosine_Results_Analysis.ipynb | CubasMike/wordnet_paraphrase |
Getting some resultsIn this cell we get the best results for each text similarity metric and 3-top best wordnet metrics | my_results = []
for text_metric in ["mihalcea", "softcosine", "stevenson"]:
for wordnet_metric in ["path", "lch", "wup", "res", "jcn", "lin"]:
print("------------------------------------------------------")
print(text_metric, wordnet_metric)
res, conf = extract_best_results(experiments,
... | _____no_output_____ | MIT | SoftCosine_Results_Analysis.ipynb | CubasMike/wordnet_paraphrase |
Saving results to latex table format 0. Removing stopwords flag : [True, False]1. Removing punctuation flag : [True, False]2. Wordnet similarity metrics : ["path", "lch", "wup", "res", "jcn", "lin"]3. Features extracted to compute similarity : ["token", "lemma", "stem", "lemmapos"]4. Features used to extract s... | ic_map = {None: "", "bnc_ic_2007": "bnc07", "bnc_ic_2000": "bnc00", "semcor_ic":"semcor", "brown_ic":"brown"}
ss_map = {"first":"1", "all":"n"}
ws_map = {"tf":"tf", "binary":"bin"}
with open("latex_out.txt", "w") as fid:
for row in res:
line = "{0} & {1} & {3} & {9} & {4} & {8} & {2} & {5} & {6} & {7:.2f} &... | _____no_output_____ | MIT | SoftCosine_Results_Analysis.ipynb | CubasMike/wordnet_paraphrase |
Analyzing test scores | test_scores = pickle.load(open("./Results/test_results_20180504.pickle","rb"))
test_scores
ic_map = {None: "", "bnc_ic_2007": "bnc07", "bnc_ic_2000": "bnc00", "semcor_ic":"semcor", "brown_ic":"brown"}
ss_map = {"first":"1", "all":"n"}
ws_map = {"tf":"tf", "binary":"bin"}
new_scores = []
for old_row in res:
conf = t... | _____no_output_____ | MIT | SoftCosine_Results_Analysis.ipynb | CubasMike/wordnet_paraphrase |
Other example with chest information Training Prepare function to calculate feature vector from 3D to [1D x number_of_features] | def localization_fv2(data3d, voxelsize_mm): # scale
fv = []
# f0 = scipy.ndimage.filters.gaussian_filter(data3d, sigma=3).reshape(-1, 1)
#f1 = scipy.ndimage.filters.gaussian_filter(data3dr, sigma=1).reshape(-1, 1) - f0
#f2 = scipy.ndimage.filters.gaussian_filter(data3dr, sigma=5).... | /Users/mjirik/miniconda/lib/python2.7/site-packages/numpy/core/numeric.py:190: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
a = empty(shape, dtype, order)
/Users/mjirik/miniconda/lib/python2.7/site-packages/skimage/morphology/misc.py:122: UserWarnin... | MIT | examples/liver_localization_training_with_chest.ipynb | mjirik/bodynavigation |
Testing | one = list(imtools.datasets.sliver_reader("*019.mhd", read_seg=True))[0]
numeric_label, vs_mm, oname, orig_data, rname, ref_data = one
fit = ol.predict(orig_data, voxelsize_mm=vs_mm)
plt.figure(figsize=(15,10))
sed3.show_slices(orig_data, fit, slice_step=20, axis=1, flipV=True)
import lisa.volumetry_evaluation
lisa.vol... | _____no_output_____ | MIT | examples/liver_localization_training_with_chest.ipynb | mjirik/bodynavigation |
Fitting the parameters | from scipy import optimize
from scipy import integrate
ydata = np.array(df_analyse.Germany[35:]) #90
time = np.arange(len(ydata))
I0 = ydata[0]
S0 = 1000000
R0 = 0
beta
print(I0)
def SIR_model_fit(SIR, time, beta, gamma):
S,I,R = SIR
dS = -beta * S * I/N0
dI = beta * S * I/N0 - gamma * I
dR = gam... | _____no_output_____ | MIT | notebooks/SIR_modeling/.ipynb_checkpoints/0_SIR_modeling_intro-checkpoint.ipynb | ebinzacharias/ads_COVID-19 |
Dynamic Beta | t_initial = 25
t_intro_measures = 14
t_hold = 21
t_relax = 21
beta_max = 0.4
beta_min = 0.11
gamma = 0.1
pd_beta = np.concatenate((np.array(t_initial*[beta_max]),
np.linspace(beta_max, beta_min, t_intro_measures),
np.array(t_hold * [beta_min]),
... | _____no_output_____ | MIT | notebooks/SIR_modeling/.ipynb_checkpoints/0_SIR_modeling_intro-checkpoint.ipynb | ebinzacharias/ads_COVID-19 |
Imports | import json
import re
import string
import scipy
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm_notebook as tqdm
from nltk.sentiment.util import mark_negation
from nltk import wordpunct_tokenize
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.snowball... | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Constants | train_path = 'data/train.json'
dev_path = 'data/dev.json'
translator = str.maketrans("","", string.punctuation)
# stemmer = SnowballStemmer("english", ignore_stopwords=True) | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Function Defs | def read_file(path):
data_X = []
data_Y = []
with open(path, 'r') as data_file:
line = data_file.readline()
while line:
data = json.loads(line)
data_X.append(data['review'])
data_Y.append(data['ratings'])
line = data_file.readline()
return ... | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
* Try Removeding whole numbers* Try seperating number and text* Try replacing 000ps by ooops* Try removing repeated characters like sssslllleeeepppp. Baseline | # all_5 = list(5*np.ones([len(Y_dev),]))
# get_metrics_from_pred(all_5,Y_dev) | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Trying Multinomial Naive Bayes | # model = MultinomialNB()
# model.fit(X_train_counts,Y_train)
# get_metrics(model,X_dev_counts,Y_dev)
# get_metrics_using_probs(model,X_dev_counts,Y_dev) | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Trying Logistic Regression | model = LogisticRegression(verbose=1,n_jobs=7,solver='sag',multi_class='ovr')
model.fit(X_train_counts,Y_train)
get_metrics(model,X_dev_counts,Y_dev)
get_metrics_using_probs(model,X_dev_counts,Y_dev)
# model = LogisticRegression(verbose=1,n_jobs=7,class_weight='balanced',multi_class='ovr',solver='liblinear')
# model.fi... | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Linear Regression | # model = LinearRegression(n_jobs=7)
# model.fit(X_train_counts,Y_train)
# get_metrics(model,X_dev_counts,Y_dev) | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
SGD Classifier | # model = SGDClassifier(n_jobs=7,verbose=True)
# model.fit(X_train_counts,Y_train)
# get_metrics(model,X_dev_counts,Y_dev) | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
ElasticNet | # model = ElasticNet()
# model.fit(X_train_counts,Y_train)
# get_metrics(model,X_dev_counts,Y_dev) | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
GradientBoostingClassifier | # model = GradientBoostingClassifier(verbose=True)
# model.fit(X_train_counts,Y_train)
# get_metrics(model,X_dev_counts,Y_dev) | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Complicated Model ( Tree with two branches 1-3 and 4-5) | indices = np.where(list(map(lambda x:x>3,Y_train)))[0]
X_train_counts_4_5 = X_train_counts[indices]
Y_train_4_5 = [Y_train[j] for j in indices]
indices = np.where(list(map(lambda x:x<=3,Y_train)))[0]
X_train_counts_1_3 = X_train_counts[indices]
Y_train_1_3 = [Y_train[j] for j in indices]
Y_modified = list(map(lambda x... | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Another Try (Tree with negative ,neutral and positive review) | indices = np.where(list(map(lambda x:x>3,Y_train)))[0]
X_train_counts_4_5 = X_train_counts[indices]
Y_train_4_5 = [Y_train[j] for j in indices]
indices = np.where(list(map(lambda x:x<3,Y_train)))[0]
X_train_counts_1_2 = X_train_counts[indices]
Y_train_1_2 = [Y_train[j] for j in indices]
indices = np.where(list(map(la... | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Voting Classifier (With simple ovr logistive regression and multinomial naive bayes) | # m1 = LogisticRegression(verbose=1,n_jobs=7,solver='sag',multi_class='ovr')
# m2 = MultinomialNB()
# model = VotingClassifier(estimators=[('lr', m1),('gnb', m2)],voting='soft')
# model.fit(X_train_counts,Y_train)
# get_metrics(model,X_dev_counts,Y_dev)
# get_metrics_using_probs(mo... | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Binary Logistics Everywhere (Tree with base classified as neutral or 1-3&4-5) | indices = np.where(list(map(lambda x: x!=3,Y_train)))[0]
X_train_counts_p_n = X_train_counts[indices]
Y_train_p_n = [1 if Y_train[j]>3 else 0 for j in indices]
indices = np.where(list(map(lambda x:x>3,Y_train)))[0]
X_train_counts_4_5 = X_train_counts[indices]
Y_train_4_5 = [Y_train[j] for j in indices]
indices = np.w... | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Another Try (Full tree leaning towards 1) | indices = np.where(list(map(lambda x: x<=3,Y_train)))[0]
X_train_counts_12_3 = X_train_counts[indices]
Y_train_12_3 = [1 if Y_train[j]==3 else 0 for j in indices]
indices = np.where(list(map(lambda x:x>3,Y_train)))[0]
X_train_counts_4_5 = X_train_counts[indices]
Y_train_4_5 = [Y_train[j] for j in indices]
indices = n... | _____no_output_____ | MIT | A1_part_1/Non Pipelined Tester.ipynb | ankurshaswat/COL772 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.