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 |
|---|---|---|---|---|---|
Now that we have the dataset loaded, let's build a model.We will create training and test sets to evaluate the model's performance. In this case we will use the RandomSplitter(). DeepChem offers a number of other splitters such as the ScaffoldSplitter, which will divide the dataset by chemical scaffold or the ButinaSp... | splitter = dc.splits.RandomSplitter() | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
With the dataset split, we can train a model on the training set and test that model on the validation set. At this point we can define some metrics and evaluate the performance of our model. In this case our dataset is unbalanced, we have a small number of active compounds and a large number of inactive compounds. Giv... | metrics = [dc.metrics.Metric(dc.metrics.matthews_corrcoef, np.mean)] | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
In order to evaluate the performance of our moldel, we will perform 10 folds of cross valiation, where we train a model on the training set and validate on the validation set. | training_score_list = []
validation_score_list = []
transformers = []
cv_folds = 10
for i in tqdm(range(0,cv_folds)):
model = generate_graph_conv_model()
train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split(dataset)
model.fit(train_dataset)
train_scores = model.evaluate(train_dat... | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
To visualize the preformance of our models on the training and test data, we can make boxplots of the models' performance. | sns.boxplot(x=["training"]*cv_folds+["validation"]*cv_folds,y=training_score_list+validation_score_list); | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
It is also useful to visualize the result of our model. In order to do this, we will generate a set of predictions for a validation set. | pred = [x.flatten() for x in model.predict(valid_dataset)]
pred | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
**The results of predict on a GraphConv model are returned as a list of lists. Is this the intent? It doesn't seem consistent across models. RandomForest returns a list. For convenience, we will put our predicted results into a Pandas dataframe.** | pred_df = pd.DataFrame(pred,columns=["neg","pos"]) | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
We can easily add the activity class (1 = active, 0 = inactive) and the SMILES string for our predicted moleculesto the dataframe. __Is the moleculed id retained as part of the DeepChem dataset? I can't find it__ | pred_df["active"] = [int(x) for x in valid_dataset.y]
pred_df["SMILES"] = valid_dataset.ids
pred_df.head()
pred_df.sort_values("pos",ascending=False).head(25)
sns.boxplot(x=pred_df.active,y=pred_df.pos) | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
The performance of our model is very good, we can see a clear separation between the active and inactive compounds. It appears that only one of our active compounds receieved a low positive score. Let's look more closely. | false_negative_df = pred_df.query("active == 1 & pos < 0.5").copy()
PandasTools.AddMoleculeColumnToFrame(false_negative_df,"SMILES","Mol")
false_negative_df
false_positive_df = pred_df.query("active == 0 & pos > 0.5").copy()
PandasTools.AddMoleculeColumnToFrame(false_positive_df,"SMILES","Mol")
false_positive_df | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
Now that we've evaluated our model's performance we can retrain the model on the entire dataset and save it. | model.fit(dataset) | _____no_output_____ | MIT | Chapter11/chapter_11_02_erk2_graph_conv.ipynb | deepchem/DeepLearningLifeSciences |
Exercise 01 - Syntax, Variables and Numbers Welcome to your first set of Python coding problems! **Notebooks** are composed of blocks (called "cells") of text and code. Each of these is editable, though you'll mainly be editing the code cells to answer some questions.To get started, try running the code cell below (by... | print("You've successfully run some Python code")
print("Congratulations!") | _____no_output_____ | MIT | python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb | Quan030994/atom-assignments |
Try adding another line of code in the cell above and re-running it. Now let's get a little fancier: Add a new code cell by clicking on an existing code cell, hitting the `escape` key *(turn to command mode)*, and then hitting the `a` or `b` key. - The `a` key will add a cell above the current cell.- The `b` adds a c... | # Create a variable called color with an appropriate value on the line below
# (Remember, strings in Python must be enclosed in 'single' or "double" quotes)
color = 'blue' | _____no_output_____ | MIT | python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb | Quan030994/atom-assignments |
1. Simple Arithmetic OperationComplete the code below. In case it's helpful, here is the table of available arithmatic operations:| Operator | Name | Description ||--------------|----------------|--------------------------------------------------------|| ``a + b... | pi = 3.14159 # approximate
diameter = 3
# Create a variable called 'radius' equal to half the diameter
radius = 3/2
# Create a variable called 'area', using the formula for the area of a circle: pi times the radius squared
area = pi * radius**2
area | _____no_output_____ | MIT | python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb | Quan030994/atom-assignments |
**Results**:- Area = 7.0685775 2. Variable ReassignmentAdd code to the following cell to swap variables `a` and `b` (so that `a` refers to the object previously referred to by `b` and vice versa). | # If you're curious, these are examples of lists. We'll talk about
# them in depth a few lessons from now. For now, just know that they're
# yet another type of Python object, like int or float.
a = [1, 2, 3]
b = [3, 2, 1]
######################################################################
# Your code goes here. ... | a = [3, 2, 1]
b = [1, 2, 3]
| MIT | python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb | Quan030994/atom-assignments |
3. Order of Operationsa) Add parentheses to the following expression so that it evaluates to 1.*Hint*: Following its default "**PEMDAS**"-like rules for order of operations, Python will first divide 3 by 2, then subtract the result from 5. You need to add parentheses to force it to perform the subtraction first. | (5 - 3) // 2 | _____no_output_____ | MIT | python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb | Quan030994/atom-assignments |
Questions, like this one, marked a spicy pepper are a bit harder. Don't feel bad if you can't get these.b) 🌶️ Add parentheses to the following expression so that it evaluates to **0**. | 8 - (3 * 2) - (1 + 1) | _____no_output_____ | MIT | python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb | Quan030994/atom-assignments |
4. Your TurnAlice, Bob and Carol have agreed to pool their Halloween candies and split it evenly among themselves.For the sake of their friendship, any candies left over will be smashed. For example, if they collectivelybring home 91 candies, they'll take 30 each and smash 1.Write an arithmetic expression below to cal... | # Variables representing the number of candies collected by Alice, Bob, and Carol
alice_candies = 121
bob_candies = 77
carol_candies = 109
# Your code goes here! Replace the right-hand side of this assignment with an expression
candies_smash = (alice_candies + bob_candies + carol_candies) % 3
candies_smash
# involving... | _____no_output_____ | MIT | python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb | Quan030994/atom-assignments |
『本次練習內容』 運用這幾天所學觀念搭建一個CNN分類器 『本次練習目的』 熟悉CNN分類器搭建步驟與原理 學員們可以嘗試不同搭法,如使用不同的Maxpooling層,用GlobalAveragePooling取代Flatten等等 | from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import BatchNormalization
from keras.layers import Activation
import keras.utils
from keras... | Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 30, 30, 16) 448
__________________________________... | MIT | Day015_Cifar_HW.ipynb | semishen/DL-CVMarathon |
預測新圖片,輸入影像前處理要與訓練時相同 ((X-mean)/(std+1e-7) ):這裡的mean跟std是訓練集的 維度如下方示範 | index = 50
input_example = x_test[index].reshape(1,32,32,3)
# input_example.shape
input_example=(input_example-mean_train)/(std_train+1e-7)
print(classifier.predict(input_example))
print(y_test[index])
| _____no_output_____ | MIT | Day015_Cifar_HW.ipynb | semishen/DL-CVMarathon |
Transmission | %matplotlib inline
import numpy as np
np.seterr(divide='ignore') # Ignore divide by zero in log plots
from scipy import signal
import scipy.signal
from numpy.fft import fft, fftfreq
import matplotlib.pyplot as plt
#import skrf as rf # pip install scikit-rf if you want to run this one | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
First, let's set up a traditional, full-precision modulator and plot the spectrum of that as a baseline | def prbs(n=0, taps=[]):
state = [1]*n
shift = lambda s: [sum([s[i] for i in taps]) % 2] + s[0:-1]
out = []
for i in range(2**n - 1):
out.append(state[-1])
state = shift(state)
return out
prbs9 = lambda: prbs(n=9, taps=[4,8])
def make_carrier(freq=None, sample_rate=None, samples=None... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Now let's look at the FFT of this... | sample_rate = 6e9
modulated = modulate_gmsk(prbs9(), sample_rate=sample_rate)
fftm = np.abs(fft(modulated))
fftm = fftm/np.max(fftm)
fftbins = fftfreq(len(modulated), 1/sample_rate)
plt.figure(figsize=(10,6))
plt.plot(fftbins, 10*np.log10(fftm))
plt.gca().set_ylim(-40, 0) | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
This is clean (as one would expect), now let's see what happens if we reduce things to 1-bit of precision by just rounding The Naive Approach (Rounding) | sample_rate=5e9
modulates_5g = modulated = np.sign(modulate_gmsk(prbs9(), sample_rate=sample_rate))
fftm = np.abs(fft(modulated))
fftm = fftm/np.max(fftm)
fftbins = fftfreq(len(modulated), 1/sample_rate)
plt.figure(figsize=(10,6))
plt.plot(fftbins, 10*np.log10(fftm))
plt.gca().set_ylim(-40, 0)
plt.gca().set_xlim(0,... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
_Oof_ this is not pretty. What's happening here is that (I think) the aliases are mixing with each other to produce these interference paterns. In this case, it looks like the big subharmonics are spaced about 200Mhz which makes sense given the alias of 2.402ghz at 2.698ghz when sampling at 2.5ghz. | sample_rate = 6e9
modulated_6g = modulated = np.sign(modulate_gmsk(prbs9(), sample_rate=sample_rate))
fftm = np.abs(fft(modulated))
fftm = fftm/np.max(fftm)
fftbins = fftfreq(len(modulated), 1/sample_rate)
plt.figure(figsize=(10,6))
plt.plot(fftbins, 10*np.log10(fftm))
plt.gca().set_ylim(-40, 0)
plt.gca().set_xlim(... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Ok, in this case, the alias is at `3 + (3 - 2.402) = 3.6ghz`. The difference between this and 2.402ghz is about 1.2ghz, which looking at the next big peak, looks to be about 1.2ghz, so this makes sense. From this math, we can intuit that it's a good idea for the sample rate to be a whole number multiple of the carrier ... | sample_rate = 2.402e9*4
modulated_4x = modulated = np.sign(modulate_gmsk(prbs9(), sample_rate=sample_rate))
fftm = np.abs(fft(modulated))
fftm = fftm/np.max(fftm)
fftbins = fftfreq(len(modulated), 1/sample_rate)
plt.figure(figsize=(10,6))
plt.plot(fftbins, 10*np.log10(fftm))
plt.gca().set_ylim(-40, 0)
plt.gca().set... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
There a couple of challenges here, however:1. In order to get the clean(ish) spectrum, we have to clock the output frequency at a rate relative to the carrier frequency. If we only intended to use one frequency, this would be fine but Bluetooth (as an example) hops around frequency constantly by design. This might be d... | # pip install scikit-rf if you want to run this one
# Note: running this before we've plotted anything, borks matplotlib
import skrf as rf
filter2_4 = rf.Network('2_4ghzfilter.s2p')
filter2_4.s21.plot_s_db() | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Hey that's not too far off from data sheet (at least up to 4.4Ghz). To turn this into a filter, we can use the scipy-rf to compute an impulse response which we can then convolve with our input data to see what the filtered output would be: | ts, ms = filter2_4.s21.impulse_response()
impulse_response = ms[list(ts).index(0):]
impulse_response = impulse_response/np.max(impulse_response)
tstep = ts[1] - ts[0]
print("Timestep {} seconds, frequency {:e} hz".format(tstep, 1/tstep))
plt.plot(impulse_response)
plt.gca().set_xlim(0, 300) | Timestep 3.2641464908425124e-11 seconds, frequency 3.063588e+10 hz
| Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
This is great and all but the impulse response is sampled at north of 30ghz (!). Our output serdes runs at around 6ghz so let's resample this to that rate | # Truncate the impulse response so we can get relatively close to 6ghz
trunc = impulse_response[:-4]
size = int((tstep*(len(trunc) - 1))/(1/6e9) + 1)
print(size)
impulse_response_6g = scipy.signal.resample(impulse_response, size)
plt.plot(impulse_response_6g)
plt.gca().set_xlim(0, 50) | 274
| Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Not quite as pretty, but it's what we need. Let's verify that this does "the thing" by filtering our 6ghz signal: | sample_rate=6e9
fftm = np.abs(fft(np.convolve(modulated_6g, impulse_response_6g, mode="same")))
fftm = fftm/np.max(fftm)
fftbins = fftfreq(len(fftm), 1/sample_rate)
plt.figure(figsize=(10,6))
plt.plot(fftbins, 10*np.log10(fftm))
plt.grid(b=True)
plt.gca().set_ylim(-40, 0)
plt.gca().set_xlim(0, 3e9) | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
This looks better, but the passband for my filter is still super wide (hundreds of MHz, not surprising for a 50c filter, I should look at B39242B9413K610 which is a $1 surface acoustic wave filter). We see some nontrivial imaging up to -12db, which is... not great.What to do? Delta Sigma ModulationA way around this is... | def pwm2(sig, k=1.0):
z1 = 0.0
z2 = 0.0
out = np.zeros((len(sig,)))
for i in range(len(sig)):
v = sig[i] - (k*z1 + z2)
out[i] = np.sign(v)
z2 = z1
z1 = v - out[i]
return out | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
To be clear, `pwm2` is replacing `np.sign` | sample_rate = 6e9
modulated = modulate_gmsk(prbs9(), sample_rate=sample_rate)
modulatedsd5 = modulated = pwm2(modulated, k=-2.0*np.cos(2.0*np.pi*2.402e9/sample_rate))
fftm = np.abs(fft(np.sign(modulated)))
fftm = fftm/np.max(fftm)
fftbins = fftfreq(len(modulated), 1/sample_rate)
plt.figure(figsize=(10,6))
plt.plot(... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Now let's filter this with our output filter | fftm = np.abs(fft(np.convolve(modulatedsd5, impulse_response_6g, mode="same")))
fftm = fftm/np.max(fftm)
fftbins = fftfreq(len(fftm), 1/sample_rate)
plt.figure(figsize=(10,6))
plt.plot(fftbins, 10*np.log10(fftm))
plt.grid(b=True)
plt.gca().set_ylim(-40, 0)
plt.gca().set_xlim(0, 3e9)
plt.title("Filtered Second Order D... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
This is better in the immediate vicinity of our signal. You'll notice on the wikipedia page that we can use increasing filter orders to increase the steepness of the valley around our signal of interest.On one hand this is good, but because our filter is not very good (tm) this actually results in higher peaks than we'... | from pydsm.ir import impulse_response
from pydsm.delsig import synthesizeNTF, simulateDSM, evalTF
from pydsm.delsig import dbv, dbp
from pydsm.NTFdesign import quantization_noise_gain
from pydsm.NTFdesign.legacy import q0_from_filter_ir
from pydsm.NTFdesign.weighting import ntf_fir_from_q0
H_inf = 1.6 # This is out of ... |
Calling CVXOPT ...
pcost dcost gap pres dres k/t
0: 1.3378e-17 -1.0000e+00 2e+02 8e+00 1e+01 1e+00
1: -3.2534e-02 4.5237e-02 1e+01 1e+00 2e+00 4e-01
2: 1.6301e-01 1.5136e-01 2e+00 3e-01 3e-01 5e-02
3: 1.3047e-01 1.2416e-01 5e-01 9e-02 1e-01 2e-02
4: 1.3111e-01 1.275... | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Let's see how well we did. Anecdotally, this is not a _great_ solution (likely constrained by the low oversampling) but I'd wager this is because the oversampling rate is super low. | # Take the frequency response
samples = filter2_4.s21.s_db[:,0,0]
# Normalize the samples
ff = filter2_4.f/6e9
# Compute frequency response data
resp_opti = evalTF(ntf_opti, np.exp(1j*2*np.pi*ff))
# Plot the output filter,
plt.figure()
plt.plot(ff*6e9, dbv(resp_opti), 'r', label="Optimal NTF")
plt.plot(ff*6e9, sampl... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Ok, so it's not amazing but definitely an improvement. But now that we've got this monstrous 49 coefficient NTF, how do we modulate with it?Fortunately we have the pydsm to the rescue! | sample_rate = 6e9
modulated = modulate_gmsk(prbs9(), sample_rate=sample_rate)
xx_opti = simulateDSM(modulated, ntf_opti)
fftm = np.abs(fft(np.convolve(xx_opti[0], impulse_response_6g, mode="same")))
fftm = fftm/np.max(fftm)
fftbins = fftfreq(len(fftm), 1/sample_rate)
plt.figure(figsize=(10,6))
plt.plot(fftbins, 10*np... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Ok, so we've basically "filled in the valley" with the peaks from eithe sides. We've cut the max spurs down by about 3db. Not amazing, but not bad!After looking around at SAW filters I realized how impressive they can be in this frequency rance, so I tried to order one (CBPFS-2441) and try with that. Unfortunately, the... | import csv
from scipy.interpolate import interp1d
traced = np.array([(float(f), float(d)) for f,d in csv.reader(open('saw_filter_traced.csv'))])
# Interpolate to 600 equally spaced points (this means 1200 total, so 1200 * 5MHz -> 6GHz sampling rate)
x = traced[:,0]
y = -1*traced[:,1]
f = interp1d(x, y)
x = np.array(n... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Let's look at the impulse respponse quickly | impulse = np.fft.ifft(y_orig)
impulse_trunc = impulse[:300]
plt.plot(np.real(impulse_trunc)) | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
**Update:** The filter finally arrived and I can characterize it, as shown below...(the remaining code uses the measured filter response rather than the one trace from the image) | sawfilter = rf.Network('crysteksawfilter.s2p')
sawfilter.s21.plot_s_db()
filter2_4.s21.plot_s_db()
ts, ms = sawfilter.s21.impulse_response()
impulse_response = ms[list(ts).index(0):]
impulse_response = impulse_response/np.max(impulse_response)
tstep = ts[1] - ts[0]
print("Timestep {} seconds, frequency {:e} hz".format(... | Timestep 4.283537554093063e-11 seconds, frequency 2.334519e+10 hz
| Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Wow that is a fair bit sharper. | H_inf = 1.5
q0 = q0_from_filter_ir(49, np.real(impulse_response_6g))
ntf_opti = ntf_fir_from_q0(q0, H_inf=H_inf)
# Take the frequency response
#samples = 10*np.log10(y)
# Normalize the samples
#ff = x*1e6/6e9
# Take the frequency response
samples = sawfilter.s21.s_db[:,0,0]
# Normalize the samples
ff = sawfilter.f/6e9... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Wow, the baseline noise level has dropped by almost 10db! Impressive! Symbol DictionariesNow that we've figured out how much noise we can stifle with this setup, we can begin to design our transmitter.Now you may notice that the above noise transfer function filter is... quite expensive, clocking in at 51 coefficients... | carrier_freq = 2.402e9
sample_rate = 6e9
symbol_rate = 1e6
samples_per_symbol = int(sample_rate/symbol_rate)
# Used to test that we've mapped things correctly.
# Note that this returns the phase angle, not the output bits
def demodulate_gmsk(sig, phase_offset=0):
I = make_carrier(freq=carrier_freq, sample_rate=sam... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
With these established, let's concatenate a few symbols together, demodulate to phase angle and make sure things look nice and smooth | def sim(out):
carrier=2.402e9
I = make_carrier(freq=carrier, sample_rate=sample_rate, samples=len(out), phase=0)
Q = make_carrier(freq=carrier, sample_rate=sample_rate, samples=len(out), phase=np.pi/2)
sos = signal.butter(2, symbol_rate, 'low', fs=sample_rate, output='sos')
rx_baseband = signal.sosfilt(sos... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Now, in order to synthesize this, we need a bit more logic to map between a bit stream and its respective symbols.Note that there is additional state (i.e. the current phase offset) that factors into the symbol encoding beyond just the symbol value itself, which makes things a bit more complicate than most other forms ... | idx = {
'000': 0,
'111': 1,
'001': 2,
'011': 3,
'010': 4,
'101': 5,
'110': 6,
'100': 7
}
start_q = [
[3, 2, 3, 2, 2, 3, 2, 3],
[0, 3, 0, 3, 3, 0, 3, 0],
[1, 0, 1, 0, 0, 1, 0, 1],
[2, 1, 2, 1, 1, 2, 1, 2]
]
def encode(bitstream):
out = np.zeros((len(bitstream)*samples_per_symbol,))
q = 0
... | [22, 21, 20, 21, 20, 21, 20, 21, 20, 23, 10, 12, 13, 12, 15, 2, 4, 7, 24, 16, 8, 2, 4, 7, 26, 27, 6, 5, 3, 9, 22, 21, 20, 23, 8, 2, 3, 9, 22, 23, 8, 0, 24, 18, 19, 25, 6, 7, 26, 28, 29, 27, 1, 14, 15, 2, 4, 7, 24, 18, 19, 30, 31, 16, 8, 2, 3, 14, 15, 2, 3, 9, 17, 30, 31, 18, 19, 25, 6, 5, 3, 14, 15, 2, 3, 14, 13, 12, 1... | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
As a reminder, the dictionary is really just one bit of precision: | dictionary[0][:100] | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Let's demodulate the encoded bits to check that things make sense (note that the filtering will delay the output a bit in time, but it demodulates correctly) | def demodulate_gmsk(sig):
carrier_freq=2.402e9
I = make_carrier(freq=carrier_freq, sample_rate=sample_rate, samples=len(sig), phase=0)
Q = make_carrier(freq=carrier_freq, sample_rate=sample_rate, samples=len(sig), phase=np.pi/2)
# Mix down to (complex) baseband
down = sig*I + 1j*sig*Q
# Create... | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
The library used to generate the NTF filter uses a copyleft license, so rather than integrate that into the code, we save out the resulting symbol waveforms and use those directly. | np.save('../data/gmsk_2402e6_6e9.npy', dictionary) | _____no_output_____ | Apache-2.0 | research/Transmission.ipynb | goran-mahovlic/onebitbt |
Pre-processing pipeline for spikeglx sessions, zebra finchBird z_w12m7_20- For every run in the session: - Load the recordings - Extract wav chan with micrhopohone and make a wav chan with the nidq syn signal - Get the sync events for the nidq sync channel - Do bout detection In another notebook, bout detection is cu... | %matplotlib inline
import os
import glob
import logging
import pickle
import numpy as np
import pandas as pd
from scipy.io import wavfile
from scipy import signal
import traceback
import warnings
from matplotlib import pyplot as plt
from importlib import reload
logger = logging.getLogger()
handler = logging.StreamHan... | 2021-10-19 11:58:34,081 root INFO all modules loaded
| MIT | notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb | zekearneodo/ceciestunepipe |
Session parameters and raw files list all the sessions for this bird | bird = 'z_w12m7_20'
all_bird_sess = et.list_sessions(bird)
logger.info('all sessions for bird are {}'.format(all_bird_sess)) | 2021-10-19 11:58:35,383 root INFO all sessions for bird are ['2020-11-04', '2020-11-05', '2020-11-06']
| MIT | notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb | zekearneodo/ceciestunepipe |
set up bird and sessions parametersthis will define:- locations of files (for the bird)- signals and channels to look for in the metadata of the files and in the rig.json parameter file: Note that this have to exist in all of the sessions that will be processed- 'sess' is unimportant here, but it comes handy if there ... | reload(et)
# for one example session
sess_par = {'bird': 'z_w12m7_20',
'sess': '2020-11-04',
'probes': ['probe_0'], #probes of interest
'mic_list': ['microphone_0'], #list of mics of interest, by signal name in rig.json
'sort': 4, #label for this sort instance
}
... | _____no_output_____ | MIT | notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb | zekearneodo/ceciestunepipe |
list all the epochs in a session, to check that it is finding what it has to find | sess_epochs = et.list_sgl_epochs(sess_par)
sess_epochs | 2021-10-19 11:58:37,438 ceciestunepipe.file.bcistructure INFO {'folders': {'bird': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20', 'raw': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04', 'sglx': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04/sglx', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04'... | MIT | notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb | zekearneodo/ceciestunepipe |
define pre-processing steps for each epoch and for the session | def preprocess_run(sess_par, exp_struct, epoch):
# get the recordings
logger.info('PREPROCESSING sess {} | epoch {}'.format(sess_par['sess'], epoch))
logger.info('getting extractors')
sgl_exp_struct = et.sgl_struct(sess_par, epoch)
run_recs_dict, run_meta_files, files_pd, rig_dict = pre.load_sglx_re... | _____no_output_____ | MIT | notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb | zekearneodo/ceciestunepipe |
Process multiple sessions | sess_list = all_bird_sess
# fist implant, right hemisphere
sess_list = ['2020-11-04', '2020-11-05', '2020-11-06']
all_sess_dict = {}
for one_sess in sess_list[:]:
sess_par['sess'] = one_sess
preprocess_session(sess_par)
sess_par
# Search bouts | _____no_output_____ | MIT | notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb | zekearneodo/ceciestunepipe |
search bouts for those sessions | from ceciestunepipe.util.sound import boutsearch as bs
from ceciestunepipe.util import wavutil as wu
from joblib import Parallel, delayed
import pickle
import sys
reload(bs)
def sess_file_id(f_path):
n = int(os.path.split(f_path)[1].split('-')[-1].split('.wav')[0])
return n
def get_all_day_bouts(sess_par: di... | _____no_output_____ | MIT | notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb | zekearneodo/ceciestunepipe |
debug debug search_bout | ## look for a single file
sess = sess_list[0]
exp_struct = et.get_exp_struct(sess_par['bird'], sess, ephys_software='sglx')
source_folder = exp_struct['folders']['derived']
wav_path_list = et.get_sgl_files_epochs(source_folder, file_filter='*wav_mic.wav')
wav_path_list.sort()
logger.info('Found {} files'.format(len(wa... | 2021-09-22 15:13:45,924 ceciestunepipe.util.sound.boutsearch INFO Getting bouts for long file /mnt/sphere/speech_bci/derived_data/s_b1253_21/2021-06-14/sglx/0712_g0/wav_mic.wav
| MIT | notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb | zekearneodo/ceciestunepipe |
Telescopes: Tutorial 5This notebook will build on the previous tutorials, showing more features of the `PsrSigSim`. Details will be given for new features, while other features have been discussed in the previous tutorial notebook. This notebook shows the details of different telescopes currently included in the `PsrS... | # import some useful packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# import the pulsar signal simulator
import psrsigsim as pss | _____no_output_____ | MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
The Folded SignalHere we will use the same `Signal` definitions that have been used in the previous tutorials. We will again simulate a 20-minute-long observation total, with subintegrations of 1 minute. The other simulation parameters will be 64 frequency channels each 12.5 MHz wide (for 800 MHz bandwidth).We will s... | # Define our signal variables.
f0 = 1500 # center observing frequecy in MHz
bw = 800.0 # observation MHz
Nf = 64 # number of frequency channels
# We define the pulse period early here so we can similarly define the frequency
period = 0.00457 # pulsar period in seconds for J1713+0747
f_samp = (1.0/period)*2048*10**-6 # ... | Warning: specified sample rate 0.4481400437636761 MHz < Nyquist frequency 1600.0 MHz
| MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
The Pulsar and ProfilesNow we will load the pulse profile as in Tutorial 3 and initialize a single `Pulsar` object. | # First we load the data array
path = 'psrsigsim/data/J1713+0747_profile.npy'
J1713_dataprof = np.load(path)
# Now we define the data profile
J1713_prof = pss.pulsar.DataProfile(J1713_dataprof)
# Define the values needed for the puslar
Smean = 0.009 # The mean flux of the pulsar, J1713+0747 at 1400 MHz from the ATNF p... | _____no_output_____ | MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
The ISMHere we define the `ISM` class used to disperse the simulated pulses. | # Define the dispersion measure
dm = 15.921200 # pc cm^-3
# And define the ISM object, note that this class takes no initial arguements
ism_sim = pss.ism.ISM() | _____no_output_____ | MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
Defining TelescopesHere we will show how to use the two predefined telescopes, Green Bank and Arecibo, and the systems accociated with them. We will also show how to define a `telescope` from scratch, so that any current or future telescopes and systems can be simulated. Predefined TelescopesWe start off by showing t... | # Define the Green Bank Telescope
tscope_GBT = pss.telescope.telescope.GBT()
# Define the Arecibo Telescope
tscope_AO = pss.telescope.telescope.Arecibo() | _____no_output_____ | MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
Each telescope is made up of one or more `systems` consisting of a `Reciever` and a `Backend`. For the predefined telescopes, the systems for the `GBT` are the L-band-GUPPI system or the 800 MHz-GUPPI system. For `Arecibo` these are the 430 MHz-PUPPI system or the L-band-PUPPI system. One can check to see what these sy... | # Information about the GBT systems
print(tscope_GBT.systems)
# We can also find out information about a receiver that has been defined here
rcvr_LGUP = tscope_GBT.systems['Lband_GUPPI'][0]
print(rcvr_LGUP.bandwidth, rcvr_LGUP.fcent, rcvr_LGUP.name) | {'820_GUPPI': (Receiver(820), Backend(GUPPI)), 'Lband_GUPPI': (Receiver(Lband), Backend(GUPPI)), '800_GASP': (Receiver(800), Backend(GASP)), 'Lband_GASP': (Receiver(Lband), Backend(GASP))}
800.0 MHz 1400.0 MHz Lband
| MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
Defining a new systemOne can also add a new system to one of these existing telescopes, similarly to what will be done when define a new telescope from scratch. Here we will add the 350 MHz receiver with the GUPPI backend to the Green Bank Telescope.First we define a new `Receiver` and `Backend` object. The `Receiver`... | # First we define a new receiver
rcvr_350 = pss.telescope.receiver.Receiver(fcent=350, bandwidth=100, name="350")
# And then we want to use the GUPPI backend
guppi = pss.telescope.backend.Backend(samprate=3.125, name="GUPPI")
# Now we add the new system. This needs just the receiver, backend, and a name
tscope_GBT.add_... | (Receiver(350), Backend(GUPPI))
| MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
Defining a new telescopeWe can also define a new telescope from scratch. In addition to needing the `Receiver` and `Backend` objects to define at least one system, the `telescope` also needs the aperture size in meters, the total area in meters^2, the system temperature in kelvin, and a name. Here we will define a sma... | # We first need to define the telescope parameters
aperture = 3.0 # meters
area = (0.5*aperture)**2*np.pi # meters^2
Tsys = 250.0 # kelvin, note this is not a realistic system temperature for a backyard telescope
name = "Backyard_Telescope"
# Now we can define the telescope
tscope_bkyd = pss.telescope.Telescope(apertur... | _____no_output_____ | MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
Now similarly to defining a new system before, we must add a system to our new telescope by defining a receiver and a backend. Since this just represents a little telescope, the system won't be comparable to the previously defined telescope. | rcvr_bkyd = pss.telescope.receiver.Receiver(fcent=1400, bandwidth=20, name="Lband")
backend_bkyd = pss.telescope.backend.Backend(samprate=0.25, name="Laptop") # Note this is not a realistic sampling rate
# Add the system to our telecope
tscope_bkyd.add_system(name="bkyd", receiver=rcvr_bkyd, backend=backend_bkyd)
# An... | {'bkyd': (Receiver(Lband), Backend(Laptop))}
| MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
Observing with different telescopesNow that we have three different telescopes, we can observe our simulated pulsar with all three and compare the sensitivity of each telescope for the same initial `Signal` and `Pulsar`. Since the radiometer noise from the telescope is added directly to the signal though, we will need... | # We define three new, similar, signals, one for each telescope
signal_1713_AO = pss.signal.FilterBankSignal(fcent = f0, bandwidth = bw, Nsubband=Nf, sample_rate = f_samp,
sublen = sublen, fold = True)
# Our backyard telescope will need slightly different parameters to be comparab... | WARNING: AstropyDeprecationWarning: The truth value of a Quantity is ambiguous. In the future this will raise a ValueError. [astropy.units.quantity]
| MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
Now we can look at the simulated data and compare the sensitivity of the different telescopes. We first plot the observation from the GBT, then Arecibo, and then our newly defined backyard telescope. | # We first plot the first two pulses in frequency-time space to show the undispersed pulses
time = np.linspace(0, obslen, len(signal_1713_GBT.data[0,:]))
# Since we know there are 2048 bins per pulse period, we can index the appropriate amount
plt.plot(time[:4096], signal_1713_GBT.data[0,:4096], label = signal_1713_GB... | _____no_output_____ | MIT | docs/_static/notebooks/telescopes_tutorial_5.ipynb | LBJ-Wade/PsrSigSim |
!pip3 install -U pywebio
# !pip install -U https://github.com/solrz/PyWebIO/archive/dev.zip
!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip
!wget https://raw.githubusercontent.com/solrz/pywebio-example/main/hello_world.py
!pip3 install nest-asyncio
import ran... | 請拖曳網址到新視窗來打開App(每次網址都會更新喔!):
https://950ebb9c7872.ngrok.io
Listen on 0.0.0.0:7606
| MIT | Eatago.ipynb | ifsunnyace/eatago-1 | |
FCLA/FNLA Fast.ai Numerical/Computational Linear Algebra Lecture 3: New Perspectives on NMF, Randomized SVDNotes / In-Class QuestionsWNixalo - 2018/2/8 Question on section: [Truncated SVD](http://nbviewer.jupyter.org/github/fastai/numerical-linear-algebra/blob/master/nbs/2.%20Topic%20Modeling%20with%20NMF%20and%20SVD.... | import torch
import numpy as np
Q = np.eye(3)
print(Q)
print(Q.T)
print(Q @ Q.T)
# construct I matrix
Q = torch.eye(3)
# torch matrix multip
# torch.mm(Q, Q.transpose)
Q @ torch.t(Q) | _____no_output_____ | MIT | FACLA/L3-notes.ipynb | WNoxchi/Kawkasos |
So if A is *approx equal* to Q•Q.T•A .. but *not* equal.. then Q is **not** the identity, but is very close to it. Oh, right. Q: m x r, **not** m x m... If both the columns and rows of Q had been orthonormal, then it would have been the Identity, but only the columns (r) are orthonormal.Q is a tall, skinny matrix. ---A... | import numpy as np
from sklearn.datasets import fetch_20newsgroups
from sklearn import decomposition
from scipy import linalg
import matplotlib.pyplot as plt
%matplotlib inline
np.set_printoptions(suppress=True)
categories = ['alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space']
remove = ('headers', 'foo... | _____no_output_____ | MIT | FACLA/L3-notes.ipynb | WNoxchi/Kawkasos |
Randomized SVD method: | def randomized_svd(M, n_components, n_oversamples=10, n_iter=4):
# number of random columns we're going to create is the number of
# columns we want + number of oversamples (extra buffer)
n_random = n_components + n_oversamples
Q = randomized_range_finder(M, n_random, n_iter)
# proje... | _____no_output_____ | MIT | FACLA/L3-notes.ipynb | WNoxchi/Kawkasos |
Computational Complexity for a M`x`N matrix in SVD is $M^2N+N^3$, so Randomized (Truncated?) SVD is a *massive* improvement. ---2018/3/7Write a loop to calculate the error of your decomposition as your vary the of topics. Plot the results. | # 1. how do I calculate decomposition error?:
# I guess I'll use MSE?
# # NumPy: # https://stackoverflow.com/questions/16774849/mean-squared-error-in-numpy
# def MSEnp(A,B):
# if type(A) == np.ndarray and type(B) == np.ndarray:
# return ((A - B) ** 2).mean()
# else:
# return np.square((A - B... | _____no_output_____ | MIT | FACLA/L3-notes.ipynb | WNoxchi/Kawkasos |
USDA Unemployment | import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
Data US Unemployment data by countyEconomic Research Service U.S. Department of Agriculture link: Notes - Year 2020, Median Household Income (2019), & '% of State Median HH Income had 78 Nan Values that are all from Puerto Rico.- I am going to drop all rows from Puerto Rico, Puerto Rico does not show up in any of ... | stats_master_list = ['Vermont',
'Mississippi',
'Maine',
'Montana',
'Washington',
'District of Columbia',
'Texas',
'Alabama',
'Michigan',
'Maryland',
'Rhode Island',
'South Dakota',
'Nebraska',
'Virginia',
'Florida',
'Utah',
'Louisiana',
'Missouri',
'Massachusetts',
'South Carolina',
'Pennsylvania',
... | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
File managment | files = os.listdir("../data_raw/USDA_gov-unemplyment/")
# remove mac file
files.remove('.DS_Store')
#files | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
Example of the csv files | # random peek
df = pd.read_excel('../data_raw/USDA_gov-unemplyment/UnemploymentReport (14).xlsx', skiprows=2)
df.shape
df.head()
df.tail() | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
Create master DataFrame | # Concat
# create master file
master_df = pd.DataFrame(columns = columns)
state_name_list = []
# LOOP
for file in files:
# read excel file
_df = pd.read_excel('../data_raw/USDA_gov-unemplyment/'+file, skiprows=2)
# read state_name
state_name = _df.iloc[0,1]
# DROP
#drop row 0
_df.drop... | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
Dataframe clean up | # reset Index
master_df.reset_index(drop = True, inplace = True )
master_df.columns
# Rename columns
master_df.rename(columns = {'FIPS ':'FIPS'}, inplace = True)
# shape
master_df.shape
master_df.head() | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
Remove rows with all nan's | master_df.isna().sum()
master_df[ master_df['FIPS'].isnull()].head()
nan_rows = master_df[ master_df['FIPS'].isnull()].index
nan_rows
len(nan_rows)
# remove rows with all Nans
master_df.drop(nan_rows, inplace = True)
master_df.isna().sum()
master_df[ master_df['2020'].isnull()].iloc[20:25,:] | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
- There are 78 rows that do have nans for 2020, - all of the Remaing rows with nan's are form Puerto Rico- I am going to remove the Nans from Puerto Rico because the other USDA data sets do not have Puerto Rico | master_df[ master_df['state'] == 'Puerto Rico' ].index
# Drop all Rows with state as Puerto Rico
index_names = master_df[ master_df['state'] == 'Puerto Rico' ].index
master_df.drop(index_names, inplace = True)
master_df.drop([], inplace = True )
master_df.isna().sum()
master_df.shape | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
Sanity Check | # unique Count of stats
master_df['state'].nunique()
len(state_name_list)
# checks if there are duplicates in state list
checkIfDuplicates_3(state_name_list)
master_df['state'].nunique() | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
Write to CSV | master_df.to_csv('../data/USDA/USDA_unemployment.csv', index=False)
master_df.shape | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
EDA | master_df.shape
master_df.head(2)
plt.figure(figsize = (17, 17))
sns.scatterplot(data = master_df, x = '2020', y = "Median Household Income (2019)", hue = 'state');
plt.xlabel("% of unemployment")
plt.title("% of Unemployment by Household Median income 2019")
set(master_df['FIPS']) | _____no_output_____ | MIT | code/USDA notebooks /EDA_for_USDA_unemployment.ipynb | STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit- |
Manually filled pop.xlsx | pop=pd.read_excel('pop.xlsx')
dta['summer']=pop['summer']
dta['winter']=pop['winter']
dta.to_excel('alldata.xlsx')
dta.set_index('name').T.to_json('antarctica.json')
v = cesiumpy.Viewer(animation=False, baseLayerPicker=True, fullscreenButton=True,
geocoder=False, homeButton=False, infoBox=True, sceneMode... | _____no_output_____ | MIT | antarctica/parser.ipynb | csaladenes/tsne |
_Lambda School Data Science_ This sprint, your project is about water pumps in Tanzania. Can you predict which water pumps are faulty? Confusion Matrix Objectives- get and interpret the confusion matrix for classification models- use classification metrics: precision, recall- understand the relationships between precis... | # !pip install category_encoders matplotlib==3.1.0 | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
Review: Load data, fit model | %matplotlib inline
import category_encoders as ce
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.impute import SimpleImputer
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeli... | Validation Accuracy 0.8140409527789386
| MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
Get and interpret the confusion matrix for classification models[Scikit-Learn User Guide — Confusion Matrix](https://scikit-learn.org/stable/modules/model_evaluation.htmlconfusion-matrix) | from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_val, y_pred)
cm
sns.heatmap?
y_val.unique()
sns.heatmap(cm, cmap='viridis', annot=True, fmt='d')
columns=[f'Predicted "{c}"' for c in y_val.unique()]
columns
index_names =[f'Actual "{c}"' for c in y_val.unique()]
index_names
df = pd.DataFrame(cm, colu... | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
How many correct predictions were made? | 7005 + 332 + 4351
sum(y_val == y_pred) | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
How many total predictions were made? | len(y_val)
cm.sum() | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
What was the classification accuracy? | 11688/14358
sum(y_val == y_pred)/len(y_val) | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
Use classification metrics: precision, recall[Scikit-Learn User Guide — Classification Report](https://scikit-learn.org/stable/modules/model_evaluation.htmlclassification-report) | from sklearn.metrics import classification_report
print(classification_report(y_val, y_pred)) | precision recall f1-score support
functional 0.81 0.90 0.85 7798
functional needs repair 0.58 0.32 0.41 1043
non functional 0.85 0.79 0.82 5517
micro avg 0.81 0.81 0.81 ... | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
Wikipedia, [Precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall)> Both precision and recall are based on an understanding and measure of relevance.> Suppose a computer program for recognizing dogs in photographs identifies 8 dogs in a picture containing 12 dogs and some cats. Of the 8 identified a... | plot_confusion_matrix(y_val, y_pred) | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
How many correct predictions of "non functional"? | correct_predictions_nonfunctional = 4351 | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
How many total predictions of "non functional"? | total_predictions_nonfunctional = 622 + 156 + 4351
total_predictions_nonfunctional | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
What's the precision for "non functional"? | correct_predictions_nonfunctional/total_predictions_nonfunctional | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
How many actual "non functional" waterpumps? | actual_nonfunctional = 1098 + 68 + 4351
actual_nonfunctional | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
What's the recall for "non functional"? | correct_predictions_nonfunctional/actual_nonfunctional
(0.81+0.58+0.85)/3
print(classification_report(y_val, y_pred))
classification_report(y_val, y_pred, output_dict=True)['non functional']['precision'] | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
Understand the relationships between precision, recall, thresholds, and predicted probabilities. Understand how Precision@K can help make decisions and allocate budgets Imagine this scenario...Suppose there are over 14,000 waterpumps that you _do_ have some information about, but you _don't_ know whether they are cur... | len(test) | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
**You have the time and resources to go to just 2,000 waterpumps for proactive maintenance.** You want to predict, which 2,000 are most likely non-functional or in need of repair, to help you triage and prioritize your waterpump inspections.You have historical inspection data for over 59,000 other waterpumps, which you... | len(train) + len(val) | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
You have historical inspection data for over 59,000 other waterpumps, which you'll use to fit your predictive model.Based on this historical data, if you randomly chose waterpumps to inspect, then about 46% of the waterpumps would need repairs, and 54% would not need repairs. | y_train.value_counts(normalize=True) | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
**Can you do better than random at prioritizing inspections?** In this scenario, we should define our target differently. We want to identify which waterpumps are non-functional _or_ are functional but needs repair: | y_train = y_train != 'functional'
y_val = y_val != 'functional'
y_train.value_counts(normalize=True) | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
We already made our validation set the same size as our test set. | len(val) == len(test) | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
We can refit our model, using the redefined target.Then make predictions for the validation set. | pipeline.fit(X_train, y_train)
y_pred = pipeline.predict(X_val)
y_pred_proba = pipeline.predict_proba(X_val)
y_pred_proba | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
And look at the confusion matrix: | y_pred_proba[:,1]
confusion_matrix(y_val, y_pred)
ax = sns.distplot(y_pred_proba[:,1], kde=False)
ax.axvline(0.5, color='r')
y_pred = y_pred_proba[:,1] > 0.6
pd.Series(y_pred).value_counts() | _____no_output_____ | MIT | module3-confusion-matrix/confusion_matrix.ipynb | alex000kim/DS-Unit-2-Tree-Ensembles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.