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 |
|---|---|---|---|---|---|
1. Model | model = RNNClassifier() | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
2. Criterion & Loss | criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
for epoch in tqdm(range(1, 1 + 1)):
train(model, 'cpu', train_loader, optimizer, epoch, criterion)
test(model, 'cpu', test_loader, criterion) | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Save a trained model | import pickle
def save_object(obj, filename):
with open(filename, 'wb') as output: # Overwrites any existing file.
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
save_object(model, 'name-classifier.pkl') | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
Experiment Notes 1. Linear layer either one layer or two layers. No impact on confusion matrix. It still blindly guess `Russian`. Solve it by `ImbalancedDatasetSampler` Scratch Note | weight = torch.tensor([3, 1, 1], dtype=torch.float)
loss = nn.CrossEntropyLoss(weight=weight)
Y = torch.tensor([2, 0, 1], dtype=torch.long)
y_pred1 = torch.tensor([
[.1 ,.2, .9],
[1.1, .1, .2],
[0.2, 2.1, .1]
])
y_pred2 = torch.tensor([
[0.8, .2, .3],
[.2, .3, .5],
[.2, .2, .1],
])
l1 = loss(y_p... | _____no_output_____ | MIT | lessons/lesson13_RNN_classification.ipynb | elcolie/practice-pytorch |
**Welcome To Penajam Project**script created by **[Penajam Euy](https://www.facebook.com/balibeach69/)**Cara pakai (*How to use*)1. Cek Core2. Start Mining3. Paste script dibawah ke browser console (***Ctrl+Shift+i - Console***)```async function eternalMode() { let url = 'https://raw.githubusercontent.com/liebedevil/... | #@title **1. Cek Core**
#@markdown Berfungsi untuk melihat spesifikasi
!lscpu
#@title **2. Start Mining**
#@markdown ▶ *Isi nama worker di kolom Name*
#@markdown ▶ *Wallet sesuaikan dengan koin yang akan dimining, penulisan koin dengan huruf kapital* (Ex: VRSC, RTM, DOGE, LTC)
#@markdown ▶ *Level di isi jumlah cor... | _____no_output_____ | MIT | rvn_Zerg.ipynb | rogg13/pCol |
时间复杂度nlogn | li = [2,1,4,3,5,6,7,9,8]
len(li)-1
quick_sort(li,0,len(li)-1)
li = [5,2,1,4,3,6,7,9,8]
len(li)-1
quick_sort(li,0,len(li)-1)
import random
random.shuffle(li)
li
# 内部实现语言为c
li.sort()
li | _____no_output_____ | MIT | jupyter/quick_sort.ipynb | lishulong16/sklearn_demo |
ovr-svm | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import gc
import nltk
import os
import re
import pickle
import sklearn
import sys
import string
from sklearn.metrics import f1_score, precision_score, recall_score,average_precision_score
from sklearn.model_selection import cross_val_score, GridSea... | _____no_output_____ | MIT | social-tags/notebooks/movielens-imdb/ovr-svm.ipynb | queirozfcom/auto-tagger |
Set the path to directory containing code of this case | new_path = r'/home/users/suihong/3-Cond_wellfacies-upload/'
sys.path.append(new_path) | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
Set the path to data directory; this directory includes two datasets: "trainingdata" and "testdata" | data_dir_test = '/scratch/users/suihong/DataSets(MultiChannels_Version4_Consistency)/' | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
Set path to trained network | # 19200 means totally 19200 thousand training images (facies models) used for the training
network_dir = '/scratch/users/suihong/ProGAN_MultiChannel_Reusults_ConditionedtoMultiConditions_TF/099-pgan-cond-Well-sinuosity-2gpu/'
network_name = 'network-snapshot-025920.pkl' | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
1. Fetch dataset | # Initialize TensorFlow session.
tf.InteractiveSession()
import dataset
# tfrecord_dir='TestData' to fetch test dataset, if tfrecord_dir='TrainingData' to fetch training dataset
# labeltypes: 0 for 'channelorientation', 1 for 'mudproportion', 2 for 'channelwidth', 3 for 'channelsinuosity'
# well_enlarge: if True, well... | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
Global features are kept and inputted into Networks with the scale of -1 to 1. To recover the global features into its original scales, use the below transformation functions. | # index in label_test[:,0], e.g., "0" here, needs to be adjusted according to the setting of "labeltypes = [3]" in previous "dataset.load_dataset(..)" function
#orit_test = (label_test[:,0]/2+0.5)*168-84
back_ratio_test = (label_test[:,0]/2+0.5)*0.8037109375+0.167724609375
width_test = (label_test[:,1]/2+0.5)*0.8+2.7
... | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
2. Import pre-trained Network | # Initialize TensorFlow session.
tf.InteractiveSession()
# Import networks.
with open(network_dir+network_name, 'rb') as file:
G, D, Gs = pickle.load(file) | /share/software/user/open/py-tensorflow/1.12.0_py36/lib/python3.6/site-packages/tensorflow/python/client/session.py:1702: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other... | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
3. Evaluation of the imported pretrained Generator 3.1 Fetch 300 inputs from Test dataset | # Sample 300 global features, probability maps, and well facies data
faciesmodels_real = image_test[:3000]
labels_inspect = label_test[:3000]
proborder = np.arange(3000) * 8 + np.random.RandomState(32).randint(0, 8, size=3000)
wellfacies_inspect_init = wellfacies_test[proborder]
wellfacies_points_inspect = np.where(we... | (3000, 4)
(3000, 2, 64, 64)
| MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
Create masks to only output visualize well facies against white background | ### Enlarge areas of well points for displaying ###
wellfacies_onechannel = wellfacies_inspect[:,0:1]+wellfacies_inspect[:,1:2]
wellfacies_onechannel_mask = np.ma.masked_where(wellfacies_onechannel == 0, wellfacies_onechannel)
cmap_well = plt.cm.viridis # Can be any colormap that you want after the cm '.
cmap_well.s... | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
3.2 General visual assessment Visual assessment on realism, diversity, conditioning to global features, conditioning to well facies data * (1) Input corresponding global features with well data into trained Generator Second column corresponds to ground truth for well facies data and global features. | print(Gs.input_shapes)
fig, ax = plt.subplots(8, 16, sharex='col', sharey='row')
fig.set_size_inches(25, 12.5, forward=True)
images_plt_average = np.zeros((8,1,64,64))
for i in range (8):
ax[i, 0].imshow(wellfacies_onechannel_mask[i,0], cmap=cmap_well, vmax = 2.15)
ax[i, 1].imshow(faciesmodels_real[i,0,:,... | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
3.3 Evaluation of Generator's conditioning ability to global features 3.3.1 Visual assessment by comparing to corresponding ground truth facies models. * Generate facies models with increasing input sinuosity index ** Choose appropriate increasing global features from test data. ** These chosen global featu... | amwv_ratio_no = 4
amwv_ratio_test_max = np.max(amwv_ratio_test)
amwv_ratio_test_min = np.min(amwv_ratio_test)
plot_img_no = np.empty((amwv_ratio_no), dtype = np.int)
for j in range(amwv_ratio_no):
for r in range(amwv_ratio_test.shape[0]):
if amwv_ratio_test[r] >= (amwv_ratio_test_max - amwv_ratio_test_min) ... | [ 6 2 18 0]
| MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
Simulate with the above chosen appropriate global features | # This cell is only used for evaluation of conditioning to sinuosity when the GAN is only conditioning to sinuosity and well facies data
fig, ax = plt.subplots(4, 16, sharex='col', sharey='row')
fig.set_size_inches(24, 6, forward=True)
images_plt_average = np.zeros((4,1,64,64))
images_plt_variance = np.zeros((4,1,64,6... | [ 6 2 18 0]
[0.07 0.22999999 0.38016528 0.55 ]
| MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
3.3.2 Quantitative assessment by comparing to corresponding ground truth facies models. * Assess channel sinuosity Second quantitative evaluation method in paper. 1) With input global features from test dataset, generate a number of facies model realizations; 2) Use image process toolbox in Matlab to measure the chan... | latents_plt = np.random.RandomState(99).randn(300, Gs.input_shapes[0][1])
labels_plt = label_test[:300, 3:4]
wellfacies_plt = wellfacies_inspect[:300]
# Run the generator to produce a set of images.
images_plt = Gs.run(latents_plt, labels_plt,wellfacies_plt)
images_plt = np.where(images_plt< -0.3, -1, images_plt)
imag... | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
Box plot | # statistics of generated facies models with differnt input sinuosity
atodlen1=[1.11889313640155,1.09077787644318,1.12165645035333,1.09007474127227,1.13424798563159,1.13978293428402,1.11589740130591,1.08779763348608,1.10422031446294,1.17915902056786,1.02510382912376,1.17754080734206,1.10875489964738,1.18006034468054,1.... | _____no_output_____ | MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
3.4 Evaluation of Generator's conditioning ability to input well data **Well points accuracy evaluation** | def get_random_well_facies_data(images_num):
well_points = np.zeros([images_num, 1, 64, 64], dtype = int)
for i in range(images_num):
well_points_num = np.random.RandomState(3*i).choice(np.arange(8, 16), 1) # Random choose the expected total number of well points
xs = np.random.choice(64, well_... | 0.9952981406283394
0.9785766691122524
| MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
4. Evaluation of the imported pretrained Discriminator as a global feature recognizer Assess D with Test data | plt_data_no = 500
a = np.arange(plt_data_no)
np.random.shuffle(a)
test_img_no = a[:plt_data_no]
_, features = D.run(image_test[test_img_no]/127.5-1)
# orit_test = (label_test[:,0]/2+0.5)*168-84
# back_ratio_test = (label_test[:,1]/2+0.5)*0.8037109375+0.167724609375
# width_test = (label_test[:,2]/2+0.5)*0.8+2.7
# amwv_... | y=0.830203x+(0.089593)
| MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
Assess D with Simulated data*(1) Randomly Select global features data | print(plt_data_no)
# Generate latent vectors.
latents_plt = np.random.randn(plt_data_no, Gs.input_shapes[0][1]) # 1000 random latents *Gs.input_shapes[0][1:]=[None, 128] [None, 4]
labels_plt = labels_inspect[:plt_data_no, 2:3]
wellfacies_plt = wellfacies_inspect[:plt_data_no]
# Run the generator to produce a set of ... | y=0.820349x+(0.097468)
| MIT | Code/1_conditioning_to_well_facies_alone_or_with_global_features/Analyses_of_Trained_Generator-Sinuosity-WellEnlarg.ipynb | SCRFpublic/GeoModeling_Conditional_ProGAN |
Lec9 `17/10/17` Examples Box and Pointer ExamplesTrivial examples of scheme representation, box and pointer diagram, and printed representation. HOP Examples ```scheme (define f (multiplier 3))(f 5) ; 15(f 3) ; 9```Type of multiplier: Number -> (Number -> Number)Type of f: Number -> Number | (define (multiplier n)
(lambda (x) (* x n)))
(define f (multiplier 3))
(f 5)
(define (repeated f n)
(lambda (x)
(if (= n 0)
x
(f ((repeated f (- n 1)) x))
)))
(define (mul a b)
((repeated (lambda (x) (+ x a)) b) 0))
(mul 3 4)
(define (exp a b)
((repeated (lambda (x) (* x a)) b) 1))
... | _____no_output_____ | Apache-2.0 | Lectures/Lec9.ipynb | Kausta/Comp200LN |
Rational Numbers Interface```scheme(make-rat n d) ; Rational Number Object(numer obj) ; n(denom obj) ; d``` | (define (+rat x y) ; x, y are rational numbers
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (*rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y)))) | _____no_output_____ | Apache-2.0 | Lectures/Lec9.ipynb | Kausta/Comp200LN |
Implementation 1- Cons - Car- Cdr Implementation 2- List- Car- Cadr | (define (make-rat x y) (cons x y))
(define (numer x) (car x))
(define (denom x) (cdr x))
(define a (make-rat 1 2))
(define b (make-rat 1 4))
(define c (+rat a b))
(display (numer c)) (newline)
(display (denom c)) | 6
8 | Apache-2.0 | Lectures/Lec9.ipynb | Kausta/Comp200LN |
Simplification | (define (gcd a b)
(if (= a 0)
b
(gcd (% b a) a)))
(define (make-rat x y)
(cons (/ x (gcd x y))
(/ y (gcd x y))))
(define c (+rat a b))
(display (numer c)) (newline)
(display (denom c))
(define (make-rat x y) (cons x y))
(define (numer x) (/ (car x) (gcd (car x) (cdr x))))
(define (denom x) (/ ... | 3
4 | Apache-2.0 | Lectures/Lec9.ipynb | Kausta/Comp200LN |
Gaussian feedforward -- analysisRo JeffersonLast updated 2021-05-26This is the companion notebook to "Gaussian_Feedforward.ipynb", and is designed to read and perform analysis on data generated by that notebook and stored in HDF5 format.**The user must specify** the `PATH_TO_DATA` (where the HDF5 files to be read are ... | # Numpy, scipy, and plotting:
import numpy as np
from scipy.stats import norm # Gaussian fitting
import scipy.integrate as integrate # integration
import matplotlib.pyplot as plt # plotting
import seaborn as sns; sns.set() # nicer plotting
import pandas as pd # dataframe for use with ... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
Import HDF5 dataSpecify the path to the .hdf5 files containing the accuracies and hooks, and define functions to load the data as dictionaries: | PATH_TO_DATA = '/full/path/to/HDF5/data/'
PATH_TO_OUTPUT = '/full/path/where/plots/are/to/be/saved/'
# read file of accuracies, return dataset as dictionary:
def read_accuracies(file_name):
with h5py.File(PATH_TO_DATA + file_name, 'r') as file:
# cast elements as np.array, else returns closed file datasets... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
So, for example, we can read in files and extract the hyperparameters as follows: | accs, hooks, paras = load_data('acc-150-30.hdf5', 'e14-hooks-150-30.hdf5', 'e14-para-150-30.hdf5')
depth = hooks['depth'].item()
var_w = hooks['var_weight'].item()
var_b = hooks['var_bias'].item() | Successfully loaded network with the following parameters:
Depth = 30
var_w = 1.5
var_b = 0.05
Hook keys:
dict_keys(['depth', 'in-0', 'in-1', 'in-10', 'in-11', 'in-12', 'in-13', 'in-14', 'in-15', 'in-16', 'in-17', 'in-18', 'in-19', 'in-2', 'in-20', 'in-21', 'in-22', 'in-23', 'in-24', 'in-25', 'in-26', 'in-27', 'in-28'... | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
Analysis functionsHere we'll define some useful functions for analyzing the results. To begin, let's write a simple function that returns the distribution of pre-/post-activations (i.e., inputs/outputs) for each layer, to see whether they remain Gaussian. | # return mean and variance for the layer, and optionally plot:
def view_layer(key, plot=False, truncate=1000):
layer = hooks[key][-truncate:] # use last `truncate` samples, else excessive size
sns.distplot(layer, fit=norm)
if not plot: plt.close() # optionally suppress figure
mean, std = norm.fit(la... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
Let's look at a few layers: | # current dataset corresponds to `wide` network option, so should remain Gaussian until the last couple layers:
view_layer('in-0', True)
view_layer('in-15', True)
view_layer('in-27', True)
view_layer('in-29', True) # only 10 neurons, don't expect Gaussian | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
Of chief importance is the fixed-point $q^*$. We can find the approximate value with the following process: first, we numerically evaluate the integral expression for $q^{\ell+1}$ as a function of $q^{\ell}$ for a grid of points. We can optionally use this to plot $q^{\ell+1}$ and the unit slope, but all we really need... | # recursive expression for the variances, eq. (14) in my blog:
def next_q(q, var_w=1, var_b=0):
integral = integrate.quad(lambda z: np.exp(-z**2/2)*np.tanh(np.sqrt(q)*z)**2, -np.inf, np.inf)[0]/np.sqrt(2*np.pi)
return var_w*integral + var_b
# compute q* given variances, and optionally plot q^{l+1} vs. q^l:
def... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
For example, for the case above, we have: | qstar = find_qstar(var_w, var_b, plot=True)
print(qstar) | 0.4174806682136245
| MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
Similarly, we would like to find the fixed point $\rho^*$, which is found by numerically solving a similar recursion relation, and then applying the flip-interpolation strategy above: | # recursive expression for the Pearson correlation coefficient, eq. (23) in my blog:
def next_rho(rho, qstar, var_w=1, var_b=0):
sq = np.sqrt(qstar)
bound = np.inf # integration bound (should be np.inf)
integral = integrate.dblquad(lambda x, y: np.exp(-x**2/2)*np.exp(-y**2/2)*np.tanh(sq*x)*np.tanh(sq*... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
For example, for the $q^*$ value and associated variances above, we have: | rhostar = find_rhostar(qstar, var_w, var_b, True)
print(rhostar) | 1
| MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
With these values in hand, we can compute the theoretical correlation length, given by eq. (27) in my blog (which is eq. (9) in Schoenholz et al.): | # correlation length (for the Pearson correlation coefficient):
def correlation_length(rhostar, qstar, var_w=1):
sq = np.sqrt(qstar)
bound = 100 # integration bound (should be np.inf, but that causes overflow errors)
integral = integrate.dblquad(lambda x, y: np.exp(-x**2/2)*np.exp(-y**2/2)*(1/np.cosh(... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
Probing fall-offTheoretically, we should be able to train deeper networks at criticality, and they should all fall-off based on the correlation length. To see how our networks behave, we'll write a function that reads-in a grid-worth of accuracy data (optionally plotting the individual accuracies), and another that us... | # automatically read and plot accuracies from a series of files **with the same variances**:
def read_and_plot_accs(base, start, stop, step, plot=True, write=False):
# file names in format acc-{base}-{dd}.hdf5
filenames = ['acc-{}-{}.hdf5'.format(base, dd) for dd in range(start, stop, step)]
#print('Re... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
How does this compare with the theoretical value of the correlation length? We can easily compute this using the $q^*$, $\rho^*$, and `correlation_length` functions above: | # same range of var_w values as above, for given var_b:
test_w = np.arange(1.0, 2.86, 0.05)
test_b = 0.05
qstar_test = [find_qstar(ww, test_b, False) for ww in test_w]
#print('q* = ', qstar_test)
rhostar_test = [find_rhostar(qq, ww, test_b, False) for qq, ww in zip(qstar_test, test_w)]
#print('\nrho* = {}\n'.format(r... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
In principle this should never be negative, but the numerics are such that the integral can be greater than 1 near the critical point, which makes $\xi<0$. Since we can't plot infinity, let's just replace this with double the largest positive value for visualization purposes: | neg_index = np.where(np.array(xi_vals) < 0)[0].item() # get index of negative value
xis = np.copy(xi_vals)
xis[neg_index] = 2*max(xi_vals)
xi_df = pd.DataFrame({'var_w': test_w, 'xi': xis})
xi_plot = sns.lineplot('var_w', 'xi', data=xi_df, marker='o');
xi_plot.set_ylim(0,100); | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
This is fine, but it would be nice to overlay the theoretical curve on the grid: | # re-create and overlay above two plots:
def overlay_falloff(base_list, start, stop, step, write=False):
# ************ load and process data for scatterplot: ************
# read accuracies, with plot suppressed:
acc_list, dep_list, w_list, b_list = [], [], [], []
for base in base_list:
acc... | _____no_output_____ | MIT | Gaussian_Feedforward_Analysis.ipynb | ro-jefferson/entropy_dnn |
pyAllegro: WebApi Import package and setup credentials | from pyAllegro.api import AllegroRestApi
```
RestApi = AllegroRestApi()
#RestApi = AllegroRestApi(config_file_dir='/Users/xszpo/.allegroApiConfig')
RestApi.credentials_set(
appName='<credentials from allegro>',
clientId='<credentials from allegro>',
clientSecred='<credentials from allegro>',
... | _____no_output_____ | MIT | tutorial_RestApi.ipynb | xSzpo/pyAllegro |
Get token | RestApi = AllegroRestApi()
RestApi.get_token() | _____no_output_____ | MIT | tutorial_RestApi.ipynb | xSzpo/pyAllegro |
```RestApi.get_token()server_address: ('localhost', 8000)Waiting for response with access_code from Allegro.pl (user authorization in progress)...Got an authorize code```During this process you will be redirected to allegro login page and you will be ask for access to your allegro account. Token that you'll receive i... | from pyAllegro.api import AllegroRestApi
RestApi = AllegroRestApi() | _____no_output_____ | MIT | tutorial_RestApi.ipynb | xSzpo/pyAllegro |
You cann use all ```GET``` methods listed [here](https://developer.allegro.pl/documentation/) with ```RestApi.resource_get(resource_name='...',params={...})``` Some examples User ratings summary | status_code, json_data = RestApi.resource_get(
resource_name='/users/{userId}/ratings-summary'.format(
**{'userId': 11791190}),
params={}
) | _____no_output_____ | MIT | tutorial_RestApi.ipynb | xSzpo/pyAllegro |
In response you will recive ```response.status_code``` and ```json``` with data | status_code
json_data | _____no_output_____ | MIT | tutorial_RestApi.ipynb | xSzpo/pyAllegro |
offers listing - allegro search | status_code, json_data = RestApi.resource_get(
resource_name='/offers/listing',
params={'phrase': 'Dell Inspiron 7347 i5-4210U/8GB/256/Win8 FHD Dotyk',
'limit' : 1}
)
json_data | _____no_output_____ | MIT | tutorial_RestApi.ipynb | xSzpo/pyAllegro |
Analysis of Price/Rating and Price/Action; applying match function in Excel and data plotting with Sklearn library | # Load S%P 500 constituent data
kmdata = pd.read_csv('/Users/algend/Desktop/Project_3_Code/StockFinder_Dashboard_Re/static/csv/Financials_2.csv')
kmdata.head(505) | _____no_output_____ | FSFAP | static/python/.ipynb_checkpoints/kmeans_trial-checkpoint.ipynb | ALGEND/stockfinder.github.io |
Best(Rating) vs Buy(Action) and/or Better(Rating) vs Sell(Action) and/or Good(Rating) vs Hold(Action) are displaying a numerical value direct match or relative data pertained to the accounts P/R and P/A tested mathematical ratios. | # Create Array of Samples "X1" for Price/Earnings/Rating(P/R) vs. Price/Earnings/Action(P/A)
X1_df = kmdata.loc[:, kmdata.columns.intersection(['PE/R', 'PE/A'])]
X1 = X1_df.values
#X1
plt.scatter(X1[:, 0], X1[:,1])
plt.show() | _____no_output_____ | FSFAP | static/python/.ipynb_checkpoints/kmeans_trial-checkpoint.ipynb | ALGEND/stockfinder.github.io |
K-Means clustering is a fast, robust, and simple algorithm that gives reliable results when data sets are distinct or well separated from each other in a linear fashion. https://brilliant.org/wiki/k-means-clustering/ | # Use n_clusters=5 as the k value
kmeans = KMeans(n_clusters=4)
# Fit the model to the data
kmeans.fit(X1)
# Predict the clusters
predicted_clusters = kmeans.predict(X1)
plt.scatter(X1[:, 0], X1[:, 1], c=predicted_clusters, s=50, cmap='viridis')
plt.xlabel('P/E/Rating')
plt.ylabel('P/E/Action')
plt.show() | _____no_output_____ | FSFAP | static/python/.ipynb_checkpoints/kmeans_trial-checkpoint.ipynb | ALGEND/stockfinder.github.io |
Deep Learning=============Assignment 2------------Previously in `1_notmnist.ipynb`, we created a pickle with formatted datasets for training, development and testing on the [notMNIST dataset](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html).The goal of this assignment is to progressively train deeper and m... | # These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range | _____no_output_____ | MIT | tensorflow/udacity/2_fullyconnected.ipynb | saarthakbhola/DeepLearning_Work |
First reload the data we generated in `1_notmnist.ipynb`. | pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
save = pickle.load(f)
train_dataset = save['train_dataset']
train_labels = save['train_labels']
valid_dataset = save['valid_dataset']
valid_labels = save['valid_labels']
test_dataset = save['test_dataset']
test_labels = save['test_labels'... | Training set (200000, 28, 28) (200000,)
Validation set (10000, 28, 28) (10000,)
Test set (18724, 28, 28) (18724,)
| MIT | tensorflow/udacity/2_fullyconnected.ipynb | saarthakbhola/DeepLearning_Work |
Reformat into a shape that's more adapted to the models we're going to train:- data as a flat matrix,- labels as float 1-hot encodings. | image_size = 28
num_labels = 10
def reformat(dataset, labels):
dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
# Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
return dataset, labels
train_dataset, train_l... | Training set (200000, 784) (200000, 10)
Validation set (10000, 784) (10000, 10)
Test set (18724, 784) (18724, 10)
| MIT | tensorflow/udacity/2_fullyconnected.ipynb | saarthakbhola/DeepLearning_Work |
We're first going to train a multinomial logistic regression using simple gradient descent.TensorFlow works like this:* First you describe the computation that you want to see performed: what the inputs, the variables, and the operations look like. These get created as nodes over a computation graph. This description i... | # With gradient descent training, even this much data is prohibitive.
# Subset the training data for faster turnaround.
train_subset = 10000
graph = tf.Graph()
with graph.as_default():
# Input data.
# Load the training, validation and test data into constants that are
# attached to the graph.
tf_train_dataset... | _____no_output_____ | MIT | tensorflow/udacity/2_fullyconnected.ipynb | saarthakbhola/DeepLearning_Work |
Let's run this computation and iterate: | num_steps = 801
def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
/ predictions.shape[0])
with tf.Session(graph=graph) as session:
# This is a one-time operation which ensures the parameters get initialized as
# we described in the graph: rand... | Initialized
Loss at step 0 : 17.2939
Training accuracy: 10.8%
Validation accuracy: 13.8%
Loss at step 100 : 2.26903
Training accuracy: 72.3%
Validation accuracy: 71.6%
Loss at step 200 : 1.84895
Training accuracy: 74.9%
Validation accuracy: 73.9%
Loss at step 300 : 1.60701
Training accuracy: 76.0%
Validation accuracy: ... | MIT | tensorflow/udacity/2_fullyconnected.ipynb | saarthakbhola/DeepLearning_Work |
Let's now switch to stochastic gradient descent training instead, which is much faster.The graph will be similar, except that instead of holding all the training data into a constant node, we create a `Placeholder` node which will be fed actual data at every call of `session.run()`. | batch_size = 128
graph = tf.Graph()
with graph.as_default():
# Input data. For the training data, we use a placeholder that will be fed
# at run time with a training minibatch.
tf_train_dataset = tf.placeholder(tf.float32,
shape=(batch_size, image_size * image_size))
tf_tra... | _____no_output_____ | MIT | tensorflow/udacity/2_fullyconnected.ipynb | saarthakbhola/DeepLearning_Work |
Let's run it: | num_steps = 3001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().run()
print("Initialized")
for step in range(num_steps):
# Pick an offset within the training data, which has been randomized.
# Note: we could use better randomization across epochs.
offset = (step * batch_si... | Initialized
Minibatch loss at step 0 : 16.8091
Minibatch accuracy: 12.5%
Validation accuracy: 14.0%
Minibatch loss at step 500 : 1.75256
Minibatch accuracy: 77.3%
Validation accuracy: 75.0%
Minibatch loss at step 1000 : 1.32283
Minibatch accuracy: 77.3%
Validation accuracy: 76.6%
Minibatch loss at step 1500 : 0.944533
... | MIT | tensorflow/udacity/2_fullyconnected.ipynb | saarthakbhola/DeepLearning_Work |
CLUSTERING Comparisons Clustering is a type of **Unsupervised Machine Learning**, which can determine relationships of unlabeled data. DBSCAN stands for Density-Based Spatial Clustering of Applications with Noise.This notebook will show one approach to prepare data for exploration of DBScan, Agglomerative and ... | import pandas as pd
import csv
import os
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib
from sklearn.cluster import DBSCAN
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import normalize
from sklearn.decomposition import ... | _____no_output_____ | MIT | ML/Clustering comparison Summarized Data.ipynb | georgetown-analytics/acquisitioners |
Preparing DataUse pandas to prepare data for machine learning. | #Reading in summarized feature set
file_name = os.path.join(os.getcwd(), "summary_out_Text2.csv")
df = pd.read_csv(file_name,skipinitialspace=True) | _____no_output_____ | MIT | ML/Clustering comparison Summarized Data.ipynb | georgetown-analytics/acquisitioners |
Look at the structure of the data. | df.head()
df.columns
df.shape | _____no_output_____ | MIT | ML/Clustering comparison Summarized Data.ipynb | georgetown-analytics/acquisitioners |
Select columns that will be used as features for Machine Learning. | #load two features
x = df[['dollars_obligated','MaxTxYear']]
| _____no_output_____ | MIT | ML/Clustering comparison Summarized Data.ipynb | georgetown-analytics/acquisitioners |
Dealing with missing values can be done by removing rows with missing data.... | #check number of rows
print ("original number of rows: %d" % (len(x.index)))
#see the nan rows
x[x.isna().any(axis=1)]
#remove rows
x1 = x.dropna()
print ("new number of rows: %d" % (len(x1.index)))
## confirm that there are no null values
x1.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 207714 entries, 0 to 207713
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 dollars_obligated 207714 non-null float64
1 MaxTxYear 207714 non-null int64
dtypes: float6... | MIT | ML/Clustering comparison Summarized Data.ipynb | georgetown-analytics/acquisitioners |
To see variance of features: boxplot (from Seaborn) can be used with the MinMaxscaler (from scikit-learn) to visualize this. | scaler = StandardScaler()
X_scaled = scaler.fit_transform(x1)
fmX = pd.DataFrame(X_scaled)
ax = sns.boxplot(data=fmX)
ax
#look at the box plot of the unscaled data
ax = sns.boxplot(data=x1)
#scatter plot the first 2 columns
plt.figure(figsize=(10,10))
plt.scatter(fmX[0],fmX[1],s=15,color='grey')
plt.title('Dataset',f... | _____no_output_____ | MIT | ML/Clustering comparison Summarized Data.ipynb | georgetown-analytics/acquisitioners |
Since g2 data from measurements are saved in .spe files so we import an external library to read such files to get data in numpy arrays. | # import libraries we need
%pylab inline
import sys
sys.path.append('./py_programs/')
from tensorflow import keras
from sdt_reader import sdtfile
from py_programs import sdt
file = sdtfile.SdtFile('./sdt_data/Antibunching_Rh110_DPC.sdt')
file.block_measure_info
# read data files
t1, y1 = sdt.read('./sdt_data/Antibunchi... | _____no_output_____ | MIT | midterm.ipynb | ubsuny/g2-coral |
We need to manually set the dip as the zero time delay. And also normalize the g2 signal to its maximum. | # normalize g2 values and zero the time delay
t1_norm, y1_norm = sdt.normalize(t1,y1)
t2_norm, y2_norm = sdt.normalize(t2,y2)
# take a look at the data
plt.figure(1)
plt.title('Antibunching_Rh110_DPC')
plt.xlabel(r'$\tau$(ns)')
plt.ylabel(r'$g^{(2)}$') # un-normalized
plt.plot(t1_norm,y1_norm)
plt.figure(2)
plt.titl... | _____no_output_____ | MIT | midterm.ipynb | ubsuny/g2-coral |
MachineLearning Part To avoid tensorflow occupying all CPUs or GPU in a computer we need to set processing units which tensorflow has access to use. | # this is to limit the GPU and CPUs being occupied by tensorflow
from implementations import tf_setCPU
# create training sequences
#time_step = 2
train = sdt.create_train(y1_norm,time_step)
#train2x, train2y = sdt.create_train(y1,time_step
train1 = train1.reshape(train1.shape[0],train1.shape[1],1)
train2 = sdt.create_t... | _____no_output_____ | MIT | midterm.ipynb | ubsuny/g2-coral |
Here I create a [1D CNN](https://keras.io/api/layers/convolution_layers/convolution1d/). | # create a training model
kernelsize = 7
model = keras.Sequential()
model.add(keras.layers.Input(shape=(train1.shape[1],train1.shape[2])))
model.add(keras.layers.Conv1D(filters=32, kernel_size=kernelsize, padding="same", strides=1, activation="relu")) #,input_shape=(train1.shape[0],train1.shape[1],1)
model.add(keras.la... | _____no_output_____ | MIT | midterm.ipynb | ubsuny/g2-coral |
!pip install sentence_transformers
ls
cd '/content/drive/My Drive/sbert/sentence-transformers'
!pip install transformers
import torch
import numpy as np
import pandas as pd
from sentence_transformers import SentenceTransformer
import scipy.spatial
from torch.utils.data import DataLoader
import time
pwd
df =pd.read_csv... | _____no_output_____ | Apache-2.0 | QuoraSentenceSimilarity.ipynb | subham1/sentence-transformers | |
Text properties and layoutControlling properties of text and its layout with Matplotlib.The :class:`matplotlib.text.Text` instances have a variety ofproperties which can be configured via keyword arguments to the textcommands (e.g., :func:`~matplotlib.pyplot.title`,:func:`~matplotlib.pyplot.xlabel` and :func:`~matplo... | import matplotlib.pyplot as plt
import matplotlib.patches as patches
# build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
# axes coordinates are 0,0 is bottom left and 1,1 is upper right
p = pat... | _____no_output_____ | Unlicense | python/learn/matplotlib/tutorials_jupyter/text/text_props.ipynb | flyingwjw/Documentation |
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.  ... | import logging
import os
import csv
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets
import pkg_resources
import azureml.core
from azureml.core.experiment import Experiment
from azureml.core.workspace import Workspace
from azureml.train.automl import AutoMLConfi... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Initialize WorkspaceInitialize a workspace object from persisted configuration. Make sure the config file is present at .\config.json | ws = Workspace.from_config()
print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\n') | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Create an Azure ML experimentLet's create an experiment named "automl-classification" and a folder to hold the training scripts. The script runs will be recorded under the experiment in Azure.The best practice is to use separate folders for scripts and its dependent files for each step and specify that folder as the `... | # Choose a name for the run history container in the workspace.
experiment_name = 'automlstep-classification'
project_folder = './project'
experiment = Experiment(ws, experiment_name)
experiment | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Create or Attach an AmlCompute clusterYou will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecturecompute-target) for your AutoML run. In this tutorial, you get the default `AmlCompute` as your training compute resource. | # Choose a name for your cluster.
amlcompute_cluster_name = "cpu-cluster"
found = False
# Check if this compute target already exists in the workspace.
cts = ws.compute_targets
if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':
found = True
print('Found existing compute ta... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Data | # The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.
example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'
dataset = Dataset.Tabular.from_delimited_files(example_data)
dataset.to_pandas_dataframe().describe()
dataset.take(5).to_p... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Review the Dataset ResultYou can peek the result of a TabularDataset at any range using `skip(i)` and `take(j).to_pandas_dataframe()`. Doing so evaluates only `j` records for all the steps in the TabularDataset, which makes it fast even against large datasets.`TabularDataset` objects are composed of a list of transfor... | X = dataset.drop_columns(columns=['Primary Type', 'FBI Code'])
y = dataset.keep_columns(columns=['Primary Type'], validate=True)
print('X and y are ready!') | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
TrainThis creates a general AutoML settings object. | automl_settings = {
"iteration_timeout_minutes" : 5,
"iterations" : 2,
"primary_metric" : 'AUC_weighted',
"preprocess" : True,
"verbosity" : logging.INFO
}
automl_config = AutoMLConfig(task = 'classification',
debug_log = 'automl_errors.log',
... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
You can define outputs for the AutoMLStep using TrainingOutput. | from azureml.pipeline.core import PipelineData, TrainingOutput
ds = ws.get_default_datastore()
metrics_output_name = 'metrics_output'
best_model_output_name = 'best_model_output'
metrics_data = PipelineData(name='metrics_data',
datastore=ds,
pipeline_output_name=m... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Create an AutoMLStep. | automl_step = AutoMLStep(
name='automl_module',
automl_config=automl_config,
outputs=[metrics_data, model_data],
allow_reuse=True)
from azureml.pipeline.core import Pipeline
pipeline = Pipeline(
description="pipeline_with_automlstep",
workspace=ws,
steps=[automl_step])
pipeline_run = exp... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Examine Results Retrieve the metrics of all child runsOutputs of above run can be used as inputs of other steps in pipeline. In this tutorial, we will examine the outputs by retrieve output data and running some tests. | metrics_output = pipeline_run.get_pipeline_output(metrics_output_name)
num_file_downloaded = metrics_output.download('.', show_progress=True)
import json
with open(metrics_output._path_on_datastore) as f:
metrics_output_result = f.read()
deserialized_metrics_output = json.loads(metrics_output_result)
df = pd.... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Retrieve the Best Model | best_model_output = pipeline_run.get_pipeline_output(best_model_output_name)
num_file_downloaded = best_model_output.download('.', show_progress=True)
import pickle
with open(best_model_output._path_on_datastore, "rb" ) as f:
best_model = pickle.load(f)
best_model | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Test the Model Load Test DataFor the test data, it should have the same preparation step as the train data. Otherwise it might get failed at the preprocessing step. | dataset = Dataset.Tabular.from_delimited_files(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv')
df_test = dataset_test.to_pandas_dataframe()
df_test = df_test[pd.notnull(df['Primary Type'])]
y_test = df_test[['Primary Type']]
X_test = df_test.drop(['Primary Type', 'FBI Code'], axis=1) | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
Testing Our Best Fitted ModelWe will use confusion matrix to see how our model works. | from pandas_ml import ConfusionMatrix
ypred = best_model.predict(X_test)
cm = ConfusionMatrix(y_test['Primary Type'], ypred)
print(cm)
cm.plot() | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb | tmccrmck/MachineLearningNotebooks |
The Least Common Multiple (LCM) of two integers can be found by figuring out their prime factors. | # For example let's take integers a and b
a=6
b=10
print("factors of a:",f.prime_factors_list(a))
print("factors of b:",f.prime_factors_list(b))
# Notice that if the two numbers have common factors these will be present in the lcm only once
lcm=f.lcm(a,b)
print("lcm({},{})={}".format(a, b, lcm))
print("and its prime ... | All factors, except the last: [7, 3] would form a number 21.
All factors, except the first: [3, 2] would form a number 6.
| Unlicense | number_theory/lcm.ipynb | EvgeniiaVak/brilliant-python-math |
Breast-Cancer Classification | #WOHOO already Version 2 I learned How to explore Data | _____no_output_____ | MIT | version2/breast-cancer classification.ipynb | zahrael97/BreastCancer_Classsification |
Library | # Import Dependencies
%matplotlib inline
# Start Python Imports
import math, time, random, datetime
# Data Manipulation
import numpy as np
import pandas as pd
# Visualization
import matplotlib.pyplot as plt
import missingno
import seaborn as sns
plt.style.use('seaborn-whitegrid')
# Preprocessing
from sklearn.prepr... | _____no_output_____ | MIT | version2/breast-cancer classification.ipynb | zahrael97/BreastCancer_Classsification |
Exploring the dataset | dataset = pd.read_csv('data.csv')
dataset.drop('Unnamed: 32', inplace=True, axis=1)
dataset.head()
# Plot graphic of missing values
missingno.matrix(dataset, figsize = (30,10))
dataset.columns
print(dataset.shape)
dataset.describe()
dataset.isnull().sum()
X = dataset.iloc[:, 2:].values
y = dataset.iloc[:, 1:2].values | _____no_output_____ | MIT | version2/breast-cancer classification.ipynb | zahrael97/BreastCancer_Classsification |
spliting the dataset | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2)
#categorical values
from sklearn.preprocessing import LabelEncoder
label_y = LabelEncoder()
y_train = label_y.fit_transform(y_train)
y_test = label_y.transform(y_test) | _____no_output_____ | MIT | version2/breast-cancer classification.ipynb | zahrael97/BreastCancer_Classsification |
Method 1 Fitting the model and analysing | #fitting
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(n_jobs= -1)
classifier.fit(X_train, y_train)
#predicting
y_pred = classifier.predict(X_test)
#confusion matrix
from sklearn.metrics import confusion_matrix
confusion_matrix(y_test, y_pred)
# classification analysis
from sklearn... | 0.9495652173913044 0.029335408199644544
| MIT | version2/breast-cancer classification.ipynb | zahrael97/BreastCancer_Classsification |
Method 2 Function that runs the requested algorithm and returns the accuracy metrics | def fit_ml_algo(algo, X_train, y_train, cv):
# One Pass
model = algo.fit(X_train, y_train)
acc = round(model.score(X_train, y_train) * 100, 2)
# Cross Validation
train_pred = model_selection.cross_val_predict(algo,
X_train,
... | Accuracy: 95.38
Accuracy CV 10-Fold: 94.95
Running Time: 0:00:00.078176
| MIT | version2/breast-cancer classification.ipynb | zahrael97/BreastCancer_Classsification |
Loading Raw Data | import tensorflow as tf
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train[:, 0:27, 0:27]
x_test = x_test[:, 0:27, 0:27]
x_train_flatten = x_train.reshape(x_train.shape[0], x_train.shape[1]*x_train.shape[2])/255.0
x_test_flatten = x_test.reshape(x_test.shape[0], x_test.shape[... | (980, 729)
(1135, 729)
(1032, 729)
(1010, 729)
(982, 729)
(892, 729)
(958, 729)
(1028, 729)
(974, 729)
(1009, 729)
| MIT | PennyLane/Data Reuploading Classifier/Conv + DRC Keras MNIST (best).ipynb | Graciaira/quantum_image_classifier |
Selecting the datasetOutput: X_train, Y_train, X_test, Y_test | X_train = np.concatenate((x_train_list[0][:200, :], x_train_list[1][:200, :]), axis=0)
Y_train = np.zeros((X_train.shape[0],), dtype=int)
Y_train[200:] += 1
X_train.shape, Y_train.shape
X_test = np.concatenate((x_test_list[0][:500, :], x_test_list[1][:500, :]), axis=0)
Y_test = np.zeros((X_test.shape[0],), dtype=int)
... | _____no_output_____ | MIT | PennyLane/Data Reuploading Classifier/Conv + DRC Keras MNIST (best).ipynb | Graciaira/quantum_image_classifier |
Dataset Preprocessing | X_train = X_train.reshape(X_train.shape[0], 27, 27, 1)
X_test = X_test.reshape(X_test.shape[0], 27, 27, 1)
X_train.shape, X_test.shape | _____no_output_____ | MIT | PennyLane/Data Reuploading Classifier/Conv + DRC Keras MNIST (best).ipynb | Graciaira/quantum_image_classifier |
Quantum | import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import AdamOptimizer, GradientDescentOptimizer
qml.enable_tape()
from tensorflow.keras.utils import to_categorical
# Set a random seed
np.random.seed(2020)
# Define output labels as quantum state vectors
def density_matrix(state):
... | _____no_output_____ | MIT | PennyLane/Data Reuploading Classifier/Conv + DRC Keras MNIST (best).ipynb | Graciaira/quantum_image_classifier |
Given a number N find the sum of all the even valued terms in the fibonacci sequence less than or equal to N. Try generating only even fibonacci numbers instead of iterating over all Fibonacci numbers. | n=int(input())
a,b=1,1
sum=0
while a<=n:
if a%2==0:
sum+=a
a,b=b,a+b
print(sum) | 4
2
| MIT | Lecture 2 Conditionals loops and Functions/Practice/Even Fibonacci Numbers-checkpoint.ipynb | Paraskk/Data-Science-and-Machine-Leaning- |
Dependencies | # !pip install --quiet efficientnet
!pip install --quiet image-classifiers
import warnings, json, re, glob, math
from scripts_step_lr_schedulers import *
from melanoma_utility_scripts import *
from kaggle_datasets import KaggleDatasets
from sklearn.model_selection import KFold
import tensorflow.keras.layers as L
import... | _____no_output_____ | MIT | Model backlog/Train/31-melanoma-5fold-resnet18-cosine-decay-wr.ipynb | dimitreOliveira/melanoma-classification |
TPU configuration | strategy, tpu = set_up_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync)
AUTO = tf.data.experimental.AUTOTUNE | REPLICAS: 1
| MIT | Model backlog/Train/31-melanoma-5fold-resnet18-cosine-decay-wr.ipynb | dimitreOliveira/melanoma-classification |
Model parameters | dataset_path = 'melanoma-256x256'
config = {
"HEIGHT": 256,
"WIDTH": 256,
"CHANNELS": 3,
"BATCH_SIZE": 64,
"EPOCHS": 20,
"LEARNING_RATE": 3e-4,
"ES_PATIENCE": 5,
"N_FOLDS": 5,
"BASE_MODEL_PATH": 'imagenet',
"DATASET_PATH": dataset_path
}
with open('config.json', 'w') as json_file:
json.dump(j... | _____no_output_____ | MIT | Model backlog/Train/31-melanoma-5fold-resnet18-cosine-decay-wr.ipynb | dimitreOliveira/melanoma-classification |
Load data | database_base_path = '/kaggle/input/siim-isic-melanoma-classification/'
k_fold = pd.read_csv(database_base_path + 'train.csv')
test = pd.read_csv(database_base_path + 'test.csv')
print('Train samples: %d' % len(k_fold))
display(k_fold.head())
print(f'Test samples: {len(test)}')
display(test.head())
GCS_PATH = KaggleD... | Train samples: 33126
| MIT | Model backlog/Train/31-melanoma-5fold-resnet18-cosine-decay-wr.ipynb | dimitreOliveira/melanoma-classification |
Augmentations | def data_augment(image, label):
p_spatial = tf.random.uniform([1], minval=0, maxval=1, dtype='float32')
p_spatial2 = tf.random.uniform([1], minval=0, maxval=1, dtype='float32')
p_rotate = tf.random.uniform([1], minval=0, maxval=1, dtype='float32')
p_crop = tf.random.uniform([1], minval=0, maxval=1, dtyp... | _____no_output_____ | MIT | Model backlog/Train/31-melanoma-5fold-resnet18-cosine-decay-wr.ipynb | dimitreOliveira/melanoma-classification |
Auxiliary functions | # Datasets utility functions
def read_labeled_tfrecord(example, height=config['HEIGHT'], width=config['WIDTH'], channels=config['CHANNELS']):
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
image = decode_image(example['image'], height, width, channels)
label = tf.cast(example['target'],... | _____no_output_____ | MIT | Model backlog/Train/31-melanoma-5fold-resnet18-cosine-decay-wr.ipynb | dimitreOliveira/melanoma-classification |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.