markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
b. Data pipeline input function
def parse_label_column(label_string_tensor): table = tf.contrib.lookup.index_table_from_tensor(tf.constant(TARGET_LABELS)) return table.lookup(label_string_tensor) def csv_input_fn(files_name_pattern, mode=tf.estimator.ModeKeys.EVAL, skip_header_lines=0, num_epochs=None, ...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
3. Define Feature Columns
def extend_feature_columns(feature_columns, hparams): num_buckets = hparams.num_buckets embedding_size = hparams.embedding_size buckets = np.linspace(-3, 3, num_buckets).tolist() alpha_X_beta = tf.feature_column.crossed_column( [feature_columns['alpha'], feature_columns['beta']], 4) ...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
4. Define Model Function
def get_input_layer_feature_columns(hparams): feature_columns = list(get_feature_columns(hparams).values()) dense_columns = list( filter(lambda column: isinstance(column, feature_column._NumericColumn) | isinstance(column, feature_column._EmbeddingColumn), ...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
6. Run Experiment a. Define experiment function
def generate_experiment_fn(**experiment_args): def _experiment_fn(run_config, hparams): train_input_fn = lambda: csv_input_fn( TRAIN_DATA_FILES_PATTERN, mode = tf.estimator.ModeKeys.TRAIN, num_epochs=hparams.num_epochs, batch_size=hparams.batch_size ...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
b. Set HParam and RunConfig
TRAIN_SIZE = 12000 NUM_EPOCHS = 1 #1000 BATCH_SIZE = 500 NUM_EVAL = 1 #10 CHECKPOINT_STEPS = int((TRAIN_SIZE/BATCH_SIZE) * (NUM_EPOCHS/NUM_EVAL)) hparams = tf.contrib.training.HParams( num_epochs = NUM_EPOCHS, batch_size = BATCH_SIZE, hidden_units=[16, 12, 8], num_buckets = 6, embedding_size = 3, ...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
c. Define JSON serving function
def json_serving_input_fn(): receiver_tensor = {} for feature_name in FEATURE_NAMES: dtype = tf.float32 if feature_name in NUMERIC_FEATURE_NAMES else tf.string receiver_tensor[feature_name] = tf.placeholder(shape=[None], dtype=dtype) if PROCESS_FEATURES: features = process_fea...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
d. Run the Experiment via learn_runner
if not RESUME_TRAINING: print("Removing previous artifacts...") shutil.rmtree(model_dir, ignore_errors=True) else: print("Resuming training...") tf.logging.set_verbosity(tf.logging.INFO) time_start = datetime.utcnow() print("Experiment started at {}".format(time_start.strftime("%H:%M:%S"))) print("......
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
6. Evaluate the Model
TRAIN_SIZE = 12000 VALID_SIZE = 3000 TEST_SIZE = 5000 train_input_fn = lambda: csv_input_fn(files_name_pattern= TRAIN_DATA_FILES_PATTERN, mode= tf.estimator.ModeKeys.EVAL, batch_size= TRAIN_SIZE) valid_input_fn = lambda: csv_input_fn(files_na...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
7. Prediction
import itertools predict_input_fn = lambda: csv_input_fn(files_name_pattern= TEST_DATA_FILES_PATTERN, mode= tf.estimator.ModeKeys.PREDICT, batch_size= 5) predictions = list(itertools.islice(estimator.predict(input_fn=predict_input_fn),5)) p...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
Serving Exported Model
import os export_dir = model_dir +"/export/Servo/" saved_model_dir = export_dir + "/" + os.listdir(path=export_dir)[-1] print(saved_model_dir) print("") predictor_fn = tf.contrib.predictor.from_saved_model( export_dir = saved_model_dir, signature_def_key="prediction" ) output = predictor_fn( { ...
02_Classification/04.0 - TF Classification Model - Custom Estimator + Experiment + Dataset + CSV.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
1.2 Calculate Actual Profit
df_sales = df_sales.assign(Actual_Profit = df_sales['Price']*df_sales['Profit']) # adds new col df_sales.head()
notebooks/notebook.ipynb
craigrshenton/home
mit
1.3 Load data from 'Calories' worksheet and plot
# find path to your Concessions.xlsx df_cals = pandas.read_excel(open('C:/Users/craigrshenton/Desktop/Dropbox/excel_data_sci/ch01_complete/Concessions.xlsx','rb'), sheetname=1) df_cals = df_cals.iloc[0:14, 0:2] # take data from 'Calories' worksheet df_cals.head() df_cals = df_cals.set_index('Item') # index df by ite...
notebooks/notebook.ipynb
craigrshenton/home
mit
1.4 add calorie data to sales worksheet
df_sales = df_sales.assign(Calories=df_sales['Item'].map(df_cals['Calories'])) # map num calories from df_cals per item in df_sales (==Vlookup) df_sales.head()
notebooks/notebook.ipynb
craigrshenton/home
mit
1.5 pivot table: number of sales per item
pivot = pandas.pivot_table(df_sales, index=["Item"], values=["Price"], aggfunc=len) # len == 'count of price' pivot.columns = ['Count'] # renames col pivot.index.name = None # removes intex title which is not needed pivot
notebooks/notebook.ipynb
craigrshenton/home
mit
1.6 pivot table: revenue per item / category
# revenue = price * number of sales pivot = pandas.pivot_table(df_sales, index=["Item"], values=["Price"], columns=["Category"], aggfunc=np.sum, fill_value='') pivot.index.name = None pivot.columns = pivot.columns.get_level_values(1) # sets cols to product categories pivot # set up decision variables items = df_cals.i...
notebooks/notebook.ipynb
craigrshenton/home
mit
Check that we are using the GPU:
from tensorflow.python.client import device_lib def get_available_gpus(): local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU'] get_available_gpus() import tensorflow as tf # Creates a graph. with tf.device('/gpu:0'): a = tf.constant...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Model Model definition
from keras.applications.vgg16 import VGG16 # create the base pre-trained model base_model = VGG16(weights='imagenet', include_top=False)
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Base Model arquitecture We have the following model arquitecture:
base_model.summary()
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Complete model with FCN Classifier on top
from keras.layers import Dense, Dropout, GlobalAveragePooling2D # add a global spatial average pooling layer x = base_model.output x = GlobalAveragePooling2D()(x) # let's add a fully-connected layer x = Dense(64, activation='relu')(x) x = Dropout(0.3)(x) # and a logistic layer predictions = Dense(2, activation='so...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Set the non trainable layers We are going to set all the vgg16 layers as non trainables:
TRAINABLE_LAST_LAYERS = 0 assert TRAINABLE_LAST_LAYERS >= 0 # first: train only the top layers (which were randomly initialized) # i.e. freeze all convolutional InceptionV3 layers if TRAINABLE_LAST_LAYERS == 0: for layer in base_model.layers: layer.trainable = False print(len(base_model.layers)) else:...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Training the top layer Keras callbacks
from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard # Early stop in case of getting worse early_stop = EarlyStopping(monitor = 'val_loss', patience = 3, verbose = 0) #TensorBoard # run tensorboard with tensorboard --logdir=/full_path_to_your_logs #tensorboard_path = TENSORBOARD_DIRECTORY...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Model optimizer
OPTIMIZER_LEARNING_RATE = 1e-2 OPTIMIZER_DECAY = 1e-4 OPTIMIZER_MOMENTUM = 0.89 OPTIMIZER_NESTEROV_ENABLED = False from keras.optimizers import SGD optimizer = SGD(lr=OPTIMIZER_LEARNING_RATE, decay=OPTIMIZER_DECAY, momentum=OPTIMIZER_MOMENTUM, nesterov=OPTIMIZER_NESTEROV_ENABLED)
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Model compilation
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=["accuracy"])
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Model Training Train data generator
from keras.preprocessing.image import ImageDataGenerator ## train generator with shuffle but no data augmentation train_datagen = ImageDataGenerator(rescale = 1./255, shear_range=0.2, zoom_range=0.2, horizontal_fli...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Validation data generator
from keras.preprocessing.image import ImageDataGenerator ## train generator with shuffle but no data augmentation validation_datagen = ImageDataGenerator(rescale = 1./255) valid_batch_generator = validation_datagen.flow_from_directory(VALID_DIRECTORY, target_size = I...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Model fitting
# fine-tune the model hist = model.fit_generator( train_batch_generator, steps_per_epoch=NUMBER_TRAIN_SAMPLES/BATCH_SIZE, epochs=NUMBER_EPOCHS, # epochs: Integer, total number of iterations on the data. validation_data=valid_batch_generator, validation_steps=NUMBER_VALIDATION_SA...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Filenames and labels Save and load classes and filenames:
(val_classes, trn_classes, val_labels, trn_labels, val_filenames, filenames, test_filenames) = get_all_classes() import pickle file = PRECOMPUTED_DIRECTORY + '/classes_and_filenames.dat' # Saving the objects: with open(file, 'wb') as file: # Python 2: open(..., 'w') pickle.dump([val_classes, trn_classes, v...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Keras callbacks We are going to define two callbacks that are going to be called in the training. EarlyStopping to stop the training if its not getting better. And a tensorboard callback to log information to be used by tensorboard.
from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard # Early stop in case of getting worse early_stop = EarlyStopping(monitor = 'val_loss', patience = 3, verbose = 0) #TensorBoard # run tensorboard with tensorboard --logdir=/full_path_to_your_logs tensorboard_path = TENSORBOARD_DIRECTORY ...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Model Optimizer
OPTIMIZER_LEARNING_RATE = 1e-2 OPTIMIZER_DECAY = 1e-4 # LearningRate = LearningRate * 1/(1 + decay * epoch) OPTIMIZER_MOMENTUM = 0.89 OPTIMIZER_NESTEROV_ENABLED = False from keras.optimizers import SGD optimizer = SGD(lr=OPTIMIZER_LEARNING_RATE, decay=OPTIMIZER_DECAY, momentum=OPTIMIZER_MOMENTU...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Compile the model
model.compile(loss='categorical_crossentropy', optimizer=optimizer, \ metrics=["accuracy"])
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Training Train data generator
from keras.preprocessing.image import ImageDataGenerator ## train generator with shuffle but no data augmentation train_datagen = ImageDataGenerator(rescale = 1./255) train_batch_generator = train_datagen.flow_from_directory(TRAIN_DIRECTORY, target_size = IMAGE_SIZE,...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Training plots
import matplotlib.pyplot as plt # summarize history for accuracy plt.figure(figsize=(15, 5)) plt.subplot(1, 2, 1) plt.plot(hist.history['acc']); plt.plot(hist.history['val_acc']); plt.title('model accuracy'); plt.ylabel('accuracy'); plt.xlabel('epoch'); plt.legend(['train', 'valid'], loc='upper left'); # summarize hi...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Plot a few examples Evaluate the model
############ # load weights ############ model_save_path = WEIGHTS_DIRECTORY + 'vgg16_pretrained_v2.h5' print("Loading weights from: {}".format(model_save_path)) model.load_weights(model_save_path) from keras.preprocessing.image import ImageDataGenerator ## train generator with shuffle but no data augmentation valida...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Test the model
from keras.preprocessing.image import ImageDataGenerator ## train generator with shuffle but no data augmentation test_datagen = ImageDataGenerator(rescale = 1./255) test_batch_generator = test_datagen.flow_from_directory( TEST_DIRECTORY, target_size = I...
notebooks/03 - VGG16 pre-trained model.ipynb
gabrielrezzonico/dogsandcats
mit
Read Input data
counts, featuredata=read10X('Data/')
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Shape of dataset: Genes, Cells
counts.shape plotQC(counts)
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Normalize data Since number of genes and transcipts detected is directly dependent on read depth, library size normalization is essential. This function will normalize gene expression based on total transcripts detected in each cell, multiply with a constant and log transform.
cpt=normalize(counts)
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Feature Selection One of the most important steps in single cell RNA seq processing, is selecting genes that describe most of the biological variance. However, this is confounded by the high levels of technical noise associated with single cell RNA-seq data. This jupyter notebook contains 2 functions to enable feature...
top1000=overdispersion(cpt,1000)
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Dimensionality reduction After gene selection, the high dimensionality of single cell RNA-seq data is commnly reduced to cluster similar cells together. This jupyter notebook contains 2 functions for dimensionality reduction: 1. PCA 2. tSNE - for the purposes of the demonstration, we will use tSNE and reduce data to ...
tsnedata=runTSNE(cpt,top1000) tsnedata=pd.read_csv('')
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Visualization Visualization is an important part of an single cell experiment. Exploring data with genes of interest helps validate clustering as wells begins the process of identifying the cell type of each cluster Lets take a look at our dimensionality reduction by plotting cells.
plt.scatter(tsnedata['V2'],tsnedata['V3'],s=5)
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Visualization Visualization is an important part of an single cell experiment. Exploring data with genes of interest helps validate clustering as wells begins the process of identifying the cell type of each cluster Lets take a look at our dimensionality reduction by plotting cells, but this time color each cell by the...
plotTSNE(cpt,tsnedata,'Snap25',featuredata,'V2','V3')
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Cluster identification After dimensionality reduction, clusters are identified using a variety of approaches. We will use a simple algorithm called DBSCAN to identify clusters This jupyter notebook contains 1 functions for dimensionality reduction: 1. DBSCAN
tsnedata_dbscan=dbscan(tsnedata,3.2,20)
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Visualization Lets take a look at our dimensionality reduction by plotting cells, but this time color each cell by the cluster assignment as determined by DBSCAN
plotTSNEClusters(tsnedata_dbscan,'V2','V3')
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Visualization Lets take a look at our dimensionality reduction by plotting cells, but this time color each cell by the cluster assignment as determined by DBSCAN. Remember that our data was reduced to 3 dimensions. So, lets plot all 3 dimensions
walkers=[] colors=['#a6cee3','#1f78b4','#b2df8a', '#33a02c','#fb9a99','#e31a1c', '#fdbf6f','#ff7f00','#cab2d6', '#6a3d9a','#ffff99','#b15928', '#000000','#bdbdbd','#ffff99'] for ii in range(0,44,1): tsne_subset=tsne[tsne['dbCluster']==ii] cellnames=tsne_subset.index a=tsne_s...
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Marker Identification Identifying genes that differentiate each of these cell populations is an important aspect of single cell RNA-seq data. There are many different methods to do this type of analysis. Given the size of the dataset ome of these are compute heavy. For the sake of brevity, we will use AUROC classificat...
aurocScoresAll=pd.DataFrame() for cluster in range(1,8,1): cells1=tsnedata_dbscan[tsnedata_dbscan['dbCluster']==cluster].index cells2=tsnedata_dbscan.index.difference(cells1) data1=cpt.loc[cpt.index,cells1].apply(expMean,1) data2=cpt.loc[cpt.index,cells2].apply(expMean,1) totaldiff=(data1-data2) ...
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Visualization Let's make a heatmap of all markergenes
markerHeatmap(cpt,aurocScoresAll.index,tsnedata_dbscan,featuredata)
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
Make .Rds file for CellView And finally, let's summarize this analysis into an .Rds file that we can share with others
mkRds(cpt,featuredata,tsnedata_dbscan)
AnalysisNotebook.ipynb
mohanbolisetty/MEDS6498-SingleCell
mit
시드 설정하기 컴퓨터 프로그램에서 무작위와 관련된 모든 알고리즘은 사실 무작위가 아니라 시작 숫자를 정해 주면 그 다음에는 정해진 알고리즘에 의해 마치 난수처럼 보이는 수열을 생성한다. 다만 출력되는 숫자들 간의 상관관계가 없어 보일 뿐이다. 또한 같은 알고리즘을 여러번 실행하더라도 다른 숫자가 나오도록 시작 숫자는 현재 시간 등을 사용해서 매번 바꿔준다. 이런 시작 숫자를 시드(seed)라고 한다. 따라서 시드를 사람이 수동으로 설정한다면 그 다음에 만들어지는 난수들은 예측할 수 있다. 파이썬에서 시드를 설정하는 명령은 seed이다. 인수로는 0과 같거나 큰 정...
np.random.seed(0)
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
이렇게 시드를 설정한 후 rand 명령으로 5개의 난수를 생성해 보자. 다른 난수 관련 명령어를 실행하지 말고 바로 다음 명령을 실행해야 한다.
np.random.rand(5)
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
몇번 더 난수를 생성한다.
np.random.rand(10) np.random.rand(10)
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
이제 시드를 0으로 재설정하고 다시 난수를 발생시켜 본다.
np.random.seed(0) np.random.rand(5) np.random.rand(10) np.random.rand(10)
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
아까와 같은 숫자가 나오는 것을 확인할 수 있다. 기존의 데이터의 순서 바꾸기 기존에 있는 데이터의 순서를 바꾸려면 shuffle 명령을 사용한다.
x = np.arange(10) np.random.shuffle(x) x
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
기존의 데이터에서 샘플링하기 이미 있는 데이터 집합에서 일부를 선택하는 것을 샘플링(sampling)이라고 한다. 샘플링에는 choice 명령을 사용한다. choice 명령은 다음과 같은 인수를 가질 수 있다. numpy.random.choice(a, size=None, replace=True, p=None) a : 배열이면 원래의 데이터, 정수이면 range(a) 명령으로 데이터 생성 size : 정수. 샘플 숫자 replace : 불리언. True이면 한번 선택한 데이터를 다시 선택 가능 p : 배열. 각 데이터가 선택될 수 있는 확률
np.random.choice(5, 5, replace=False) # shuffle 명령과 같다. np.random.choice(5, 3, replace=False) # 3개만 선택 np.random.choice(5, 10) # 반복해서 10개 선택 np.random.choice(5, 10, p=[0.1, 0, 0.3, 0.6, 0]) # 선택 확률을 다르게 해서 10개 선택
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
난수 생성 NumPy의 random 서브패키지에는 난수를 생성하는 명령이 4가지가 있다. rand: 0부터 1사이의 균일 분포 randn: 가우시안 표준 정규 분포 randint: 균일 분포의 정수 난수 rand 명령은 0부터 1사이에서 균일한 확률 분포로 실수 난수를 생성한다. 숫자 인수는 생성할 난수의 크기이다. 여러개의 인수를 넣으면 해당 크기를 가진 행렬을 생성한다.
np.random.rand(10) np.random.rand(3, 5)
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
randn 명령은 기댓값이 0이고 표준편차가 1인 가우시안 표준 정규 분포를 따르는 난수를 생성한다. 인수 사용법은 rand 명령과 같다.
np.random.randn(10) np.random.randn(3, 5)
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
randint 명령은 다음과 같은 인수를 가진다. numpy.random.randint(low, high=None, size=None) 만약 high를 입력하지 않으면 0과 low사이의 숫자를, high를 입력하면 low와 high는 사이의 숫자를 출력한다. size는 난수의 숫자이다.
np.random.randint(10, size=10) np.random.randint(10, 20, size=10) np.random.randint(10, 20, size=(3,5))
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
정수 난수 통계 이렇게 발생시킨 난수가 실수값이면 히스토그램 등을 사용하여 분석하면 된다. 만약 난수가 정수값이면 unique 명령이나 bincount 명령으로 데이터 값을 분석할 수 있다. 이 명렬들은 random 서브패키지가 아니라 NumPy 바로 아래에 포함된 명령이다. unique 명령은 데이터에서 중복된 값을 제거하고 중복되지 않는 값의 리스트를 출력한다. return_counts 인수를 True 로 설정하면 각 값을 가진 데이터 갯수도 출력한다.
np.unique([11, 11, 2, 2, 34, 34]) a = np.array(['a', 'b', 'b', 'c', 'a']) index, count = np.unique(a, return_counts=True) index count
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
그러나 unique 값은 데이터에 존재하는 값에 대해서만 갯수를 세므로 나올 수 있음에도 불구하고 데이터가 하나도 없는 값에 대한 정보를 주지 않는다. 따라서 데이터가 주사위를 던졌을 때 나오는 수처럼 특정 범위안의 수인 경우에는 bincount에 minlength 인수를 설정하여 쓰는 것이 더 편리하다. 이 때는 0 부터 minlength - 1 까지의 숫자에 대해 각각 카운트를 한다. 데이터가 없을 경우에는 카운트 값이 0이 된다.
np.bincount([1, 1, 2, 2, 2, 3], minlength=6)
09. 기초 확률론2 - 확률 변수/01. NumPy를 사용한 난수 발생.ipynb
zzsza/Datascience_School
mit
Set up different sections of data based on clusters of 3 and regressions Borders of clusters from visual estimate of previous homework cluster visuals (emily)
#edges of k-means, k = 3 clusters cluster3x1bounds = (409,1500) cluster3x2bounds = (1501,2500) cluster3x3bounds = (2501,3529) #edges of k-means, k = 4 clusters cluster4x1bounds = (409,1100) cluster4x4bounds = (2750,3529) def check_in_cluster(row, x_bounds): if row[0] < x_bounds[0] or row[0] > x_bounds[1]: #check ...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
Start regressions in cluster 1.1) Cluster of 3, check 1st cluster
print('Regression on X=(x,y,z), Y=syn/unmasked') X = data_k3_1[:, (0, 1, 2)] # x,y,z Y = data_k3_1[:, 3] # syn/unmasked for idx2, reg in enumerate(regressions): scores = cross_validation.cross_val_score(reg, X, Y, scoring='r2', cv=k_fold) print("R^2 of %s: \t %0.2f (+/- %0.2f)" % (names[idx2], scores.mean(), sc...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
1.2) 2nd cluster
print('Regression on X=(x,y,z), Y=syn/unmasked') X = data_k3_2[:, (0, 1, 2)] # x,y,z Y = data_k3_2[:, 3] # syn/unmasked for idx2, reg in enumerate(regressions): scores = cross_validation.cross_val_score(reg, X, Y, scoring='r2', cv=k_fold) print("R^2 of %s: \t %0.2f (+/- %0.2f)" % (names[idx2], scores.mean(), sc...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
1.3) 3rd cluster
print('Regression on X=(x,y,z), Y=syn/unmasked') X = data_k3_3[:, (0, 1, 2)] # x,y,z Y = data_k3_3[:, 3] # syn/unmasked for idx2, reg in enumerate(regressions): scores = cross_validation.cross_val_score(reg, X, Y, scoring='r2', cv=k_fold) print("R^2 of %s: \t %0.2f (+/- %0.2f)" % (names[idx2], scores.mean(), sc...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
2) Set up 4 clusters
#edges of k-means, k = 4 clusters, Not sure how to get full clusters cluster4x1bounds = (409,1100) cluster4x4bounds = (2750,3529) def check_in_cluster(row, x_bounds): if row[0] < x_bounds[0] or row[0] > x_bounds[1]: #check x inbounds return False return True indices_in_bound = np.where(np.apply_along...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
2.1) 4 cluster, section 1
print('Regression on X=(x,y,z), Y=syn/unmasked') X = data_k4_1[:, (0, 1, 2)] # x,y,z Y = data_k4_1[:, 3] # syn/unmasked for idx2, reg in enumerate(regressions): scores = cross_validation.cross_val_score(reg, X, Y, scoring='r2', cv=k_fold) print("R^2 of %s: \t %0.2f (+/- %0.2f)" % (names[idx2], scores.mean(), sc...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
2.2) 4 cluster, 4th section
print('Regression on X=(x,y,z), Y=syn/unmasked') X = data_k4_4[:, (0, 1, 2)] # x,y,z Y = data_k4_4[:, 3] # syn/unmasked for idx2, reg in enumerate(regressions): scores = cross_validation.cross_val_score(reg, X, Y, scoring='r2', cv=k_fold) print("R^2 of %s: \t %0.2f (+/- %0.2f)" % (names[idx2], scores.mean(), sc...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
3) Cluster Explore Focusing on the centroid, we can see that the centroid centers are not near where the centers are when calcualated with kmeans.
import sklearn.mixture as mixture n_clusters = 4 ########################################### gmm = mixture.GMM(n_components=n_clusters, n_iter=1000, covariance_type='diag', random_state=1) clusters = [[] for i in xrange(n_clusters)] centroidmatrix = [0]*4 print centroidmatrix predicted = gmm.fit_predict(data_density)...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
4) Hex plot hexbin for bottom 4 levels... doesn't seem to be anything interesting... only to realize bins may be too small and are just points (w/o density data)... >.<
from mpl_toolkits.mplot3d import Axes3D # Random Sample samples = 20000 perm = np.random.permutation(xrange(1, len(data_density[:]))) data_density_sample = data_density[perm[:samples]] data_uniques, UIndex, UCounts = np.unique(data_density_sample[:,2], return_index = True, return_counts = True) print 'uniques' prin...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
5) Stats of spike shown to Jovo ... something isnt right though....
def check_spike(row): if row[3] > 0.0013 and row[3] < 0.00135 : return True return False index_true = np.where(np.apply_along_axis(check_z, 1, data_density)) spike = data_density[index_true] print "Spike" print "length: ", len(spike) print "Mean: ", np.mean(spike) print "Median: ", np.mean(spike) pri...
code/Assignment10_Akash.ipynb
Upward-Spiral-Science/team1
apache-2.0
Non-parametric 1 sample cluster statistic on single trial power This script shows how to estimate significant clusters in time-frequency power estimates. It uses a non-parametric statistical procedure based on permutations and cluster level statistics. The procedure consists of: extracting epochs compute single trial ...
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.time_frequency import tfr_morlet from mne.stats import permutation_cluster_1samp_test from mne.datasets import sample print(__doc__)
0.20/_downloads/2e7ef25ccf0fd2af7902f12debe11fc1/plot_stats_cluster_1samp_test_time_frequency.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Set parameters
data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' tmin, tmax, event_id = -0.3, 0.6, 1 # Setup for reading the raw data raw = mne.io.read_raw_fif(raw_fname) events = mne.find_events(raw, stim_channel='STI 014') include = [] raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + ...
0.20/_downloads/2e7ef25ccf0fd2af7902f12debe11fc1/plot_stats_cluster_1samp_test_time_frequency.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Compute statistic
threshold = 2.5 n_permutations = 100 # Warning: 100 is too small for real-world analysis. T_obs, clusters, cluster_p_values, H0 = \ permutation_cluster_1samp_test(epochs_power, n_permutations=n_permutations, threshold=threshold, tail=0)
0.20/_downloads/2e7ef25ccf0fd2af7902f12debe11fc1/plot_stats_cluster_1samp_test_time_frequency.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
View time-frequency plots
evoked_data = evoked.data times = 1e3 * evoked.times plt.figure() plt.subplots_adjust(0.12, 0.08, 0.96, 0.94, 0.2, 0.43) # Create new stats image with only significant clusters T_obs_plot = np.nan * np.ones_like(T_obs) for c, p_val in zip(clusters, cluster_p_values): if p_val <= 0.05: T_obs_plot[c] = T_ob...
0.20/_downloads/2e7ef25ccf0fd2af7902f12debe11fc1/plot_stats_cluster_1samp_test_time_frequency.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Dask specifics Previously in 03_fwi.ipynb, we defined a function to calculate the individual contribution to the functional and gradient for each shot, which was then used in a loop over all shots. However, when using distributed frameworks such as Dask we instead think in terms of creating a worklist which gets mapped...
# Define a type to store the functional and gradient. class fg_pair: def __init__(self, f, g): self.f = f self.g = g def __add__(self, other): f = self.f + other.f g = self.g + other.g return fg_pair(f, g) def __radd__(self, other): if other...
examples/seismic/tutorials/04_dask_pickling.ipynb
opesci/devito
mit
Create operators for gradient based inversion To perform the inversion we are going to use scipy.optimize.minimize(method=’L-BFGS-B’). First we define the functional, f, and gradient, g, operator (i.e. the function fun) for a single shot of data. This is the work that is going to be performed by the worker on a unit of...
#NBVAL_IGNORE_OUTPUT from devito import Function # Create FWI gradient kernel for a single shot def fwi_gradient_i(param): # Load the current model and the shot data for this worker. # Note, unlike the serial example the model is not passed in # as an argument. Broadcasting large datasets is considered ...
examples/seismic/tutorials/04_dask_pickling.ipynb
opesci/devito
mit
Define the global functional-gradient operator. This does the following: * Maps the worklist (shots) to the workers so that the invidual contributions to (f, g) are computed. * Sum individual contributions to (f, g) and returns the result.
def fwi_gradient(model, param): # Dump a copy of the current model for the workers # to pick up when they are ready. param['model'] = "model_0.p" dump_model(param['model'], wrap_model(model)) # Define work list work = [dict(param) for i in range(param['nshots'])] for i in range(param['nsho...
examples/seismic/tutorials/04_dask_pickling.ipynb
opesci/devito
mit
FWI with L-BFGS-B Equipped with a function to calculate the functional and gradient, we are finally ready to define the optimization function.
from scipy import optimize # Many optimization methods in scipy.optimize.minimize accept a callback # function that can operate on the solution after every iteration. Here # we use this to monitor the true relative solution error. relative_error = [] def fwi_callbacks(x): # Calculate true relative error tr...
examples/seismic/tutorials/04_dask_pickling.ipynb
opesci/devito
mit
We now apply our FWI function and have a look at the result.
#NBVAL_IGNORE_OUTPUT model0 = get_initial_model() # Baby steps result = fwi(model0, param) # Print out results of optimizer. print(result) #NBVAL_SKIP # Plot FWI result from examples.seismic import plot_image slices = tuple(slice(param['nbl'],-param['nbl']) for _ in range(2)) vp = 1.0/np.sqrt(result['x'].reshape(...
examples/seismic/tutorials/04_dask_pickling.ipynb
opesci/devito
mit
cnv2utf8 (網址中文部分需要用URLEncode 轉換成 UTF-8)
def cnv2utf8(mstr): #print mstr #print urllib.quote(mstr.encode(u"utf8")) return urllib.quote(mstr.encode(u"utf8"))
model/ex02 data dowload 0804.ipynb
g2214370/bigdata_wilson
gpl-3.0
可以看json中文字的程式碼
class MyPrettyPrinter(pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): if isinstance(object, unicode): return (object.encode('utf8'), True, False) return pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def printJson(aObj): MyPrettyPrint...
model/ex02 data dowload 0804.ipynb
g2214370/bigdata_wilson
gpl-3.0
傳入六個變數,回傳一個Json 地點 產品 前幾名資料 跳過多少資料量 交易結束時間 交易開始時間
def getData(location, product, top, skip, EndDate, StartDate): ##變數宣告 # url是API的網址 # ahash是替代的變數值 url = u"http://m.coa.gov.tw/OpenData/FarmTransData.aspx?$top={top}&$skip={skip}&Market={Market}&Crop={Crop}&EndDate={EndDate}&StartDate={StartDate}" ahash={ u"{top}" :top, ...
model/ex02 data dowload 0804.ipynb
g2214370/bigdata_wilson
gpl-3.0
url = u"http://m.coa.gov.tw/OpenData/FarmTransData.aspx?$top={top}&amp;$skip={skip}&amp;Market={Market}&amp;Crop={Crop}" ahash={ u"{top}" :u"100", u"{skip}" :u"0", u"{Market}":cnv2utf8(u"台北二"), u"{Crop}" :cnv2utf8(u"椰子"), } ## 這裡再做的就是將ahash內的key用value換掉 for abc in ahash: url=url.replac...
#url = u"http://m.coa.gov.tw/OpenData/FarmTransData.aspx?$top={top}&$skip={skip}&filter={filter}" #ahash={u"99110001":u"August", # u"99110002":u"vicky"} # ahash[u"99110001"] # ahash={ u"{top}":u"20", u"{skip}":u"100", u"{filter}":u"Market=台北二&Crop=椰子", # } # ahash #ahash # for abc in ahash...
model/ex02 data dowload 0804.ipynb
g2214370/bigdata_wilson
gpl-3.0
Converting to xyz will not work yet, as the Vector class is not yet defined. That's what's coming.
class Vector: def __init__(self, arg): """Initialize a vector at an (x,y,z)""" self.xyz = XYZ(*map(float,arg)) def __repr__(self): return repr(self.xyz) @property def x(self): return self.xyz.x @property def y(self): return self.xyz.y @propert...
QuadraysJN.ipynb
4dsolutions/Python5
mit
At the end is a method for outputting in quadray coordinates. Some design decisions were taken, conventions followed, in how the XYZ and IVM systems were overlaid. Lets not worry about that for now and just imagine a cube with edges sqrt(2)/2, one corner in each octant. The face diagonals will have length 1 in this...
octant0 = Vector((root2/4, root2/4, root2/4)) print(octant0.xyz) q0 = octant0.quadray() print(q0) q0.length()
QuadraysJN.ipynb
4dsolutions/Python5
mit
This might seem strange already. What appears to be a unit vector, has some irrational length. The cube below is flipped over somehow, but gives the idea. Think of (1,0,0,0) as being in the all positive octant (+, +, +) of XYZ. Another issue with this cube, in the context of the surrounding computations, is all edges ...
octant1 = Vector((-root2/4, root2/4, root2/4)) # neighboring octant diff = octant0 - octant1 print("diff.quadray()", diff.quadray()) print("Length between adjacent corners: ", diff.length())
QuadraysJN.ipynb
4dsolutions/Python5
mit
This confirms the cube has the expected edge length. This is not the length between two quadray tips, which is $1.0$, but between two adjacent corners of our cube, so $\sqrt{2}/2$.
diff.quadray().length() a = Qvector((1,0,0,0)) b = Qvector((0,1,0,0)) (a-b).length()
QuadraysJN.ipynb
4dsolutions/Python5
mit
Half the cube's vertices will align with the four spokes of the caltrop (in blue). These correspond the the vertexes of an embedded tetrahedron of edges 2 (in red), or edges 1 if measuring in D units. Note that the Qvector class comes with two ways to express a Qray in canonical lowest terms. One way preserves the no...
# add up three quadrays and negate their sum, to get the other Qray a = Qvector((1,0,0,0)) c = Qvector((0,0,1,0)) d = Qvector((0,0,0,1)) v_sum = -(a + c + d) print("Canonical representation:", v_sum) print("Alternative expression: ", v_sum.norm0()) print("v_sum length: ", v_sum.length())
QuadraysJN.ipynb
4dsolutions/Python5
mit
<a id='step2'></a> 2. Define all the system variables
testfolder = str(Path().resolve().parent.parent / 'bifacial_radiance' / 'Tutorial_17') if not os.path.exists(testfolder): os.makedirs(testfolder) timestamp = 4020 # Noon, June 17th. simulationName = 'tutorial_17' # Optionally adding a simulation name when defning RadianceObj #Location lat = 40.1217 # Give...
docs/tutorials/17 - AgriPV - Jack Solar Site Modeling.ipynb
NREL/bifacial_radiance
bsd-3-clause
<a id='step3'></a> 3. Build Scene for a pretty Image
idx = 272 test_folderinner = os.path.join(testfolder, test_folder_fmt.format(f'{idx:04}')) if not os.path.exists(test_folderinner): os.makedirs(test_folderinner) rad_obj = bifacial_radiance.RadianceObj(simulationName,path = test_folderinner) # Create a RadianceObj 'object' rad_obj.setGround(albedo) epwfile = ra...
docs/tutorials/17 - AgriPV - Jack Solar Site Modeling.ipynb
NREL/bifacial_radiance
bsd-3-clause
The scene generated can be viewed by navigating on the terminal to the testfolder and typing rvu -vf views\front.vp -e .0265652 -vp 2 -21 2.5 -vd 0 1 0 tutorial_17.oct OR Comment the ! line below to run rvu from the Jupyter notebook instead of your terminal.
## Comment the ! line below to run rvu from the Jupyter notebook instead of your terminal. ## Simulation will stop until you close the rvu window #!rvu -vf views\front.vp -e .0265652 -vp 2 -21 2.5 -vd 0 1 0 tutorial_17.oct
docs/tutorials/17 - AgriPV - Jack Solar Site Modeling.ipynb
NREL/bifacial_radiance
bsd-3-clause
<a id='step4'></a> GHI Calculations From Weather File
# BOULDER # Simple method where I know the index where the month starts and collect the monthly values this way. # In 8760 TMY, this were the indexes: starts = [2881, 3626, 4346, 5090, 5835] ends = [3621, 4341, 5085, 5829, 6550] starts = [metdata.datetime.index(pd.to_datetime('2021-05-01 6:0:0 -7')), metdat...
docs/tutorials/17 - AgriPV - Jack Solar Site Modeling.ipynb
NREL/bifacial_radiance
bsd-3-clause
With raytrace
simulationName = 'EMPTYFIELD_MAY' starttime = pd.to_datetime('2021-05-01 6:0:0') endtime = pd.to_datetime('2021-05-31 18:0:0') rad_obj = bifacial_radiance.RadianceObj(simulationName) rad_obj.setGround(albedo) metdata = rad_obj.readWeatherFile(epwfile, label='center', coerce_year=2021, starttime=starttime, endtime=en...
docs/tutorials/17 - AgriPV - Jack Solar Site Modeling.ipynb
NREL/bifacial_radiance
bsd-3-clause
Test Yellowbrick Covariance Ranking
from yellowbrick.features.rankd import Rank2D from yellowbrick.features.radviz import RadViz from yellowbrick.features.pcoords import ParallelCoordinates # Specify the features of interest # Used all for testing purposes features = FEATURES # Extract the numpy arrays from the data frame X = df[features].as_matrix(...
examples/pbwitt/testing.ipynb
DistrictDataLabs/yellowbrick
apache-2.0
Data Extraction Create a bunch object to store data on disk. data: array of shape n_samples * n_features target: array of length n_samples feature_names: names of the features filenames: names of the files that were loaded DESCR: contents of the readme
from sklearn.datasets.base import Bunch DATA_DIR = os.path.abspath(os.path.join(".", "..", "pbwitt","data")) # Show the contents of the data directory for name in os.listdir(DATA_DIR): if name.startswith("."): continue print ("- {}".format(name)) def load_data(root=DATA_DIR): filenames = { ...
examples/pbwitt/testing.ipynb
DistrictDataLabs/yellowbrick
apache-2.0
Build and Score Regression Models Create function -- add parameters for Yellowbrick target visulizations Score models using Mean Absolute Error, Mean Squared Error, Median Absolute Error, R2
def fit_and_evaluate(dataset, model, label,vis, **kwargs ): """ Because of the Scikit-Learn API, we can create a function to do all of the fit and evaluate work on our behalf! """ start = time.time() # Start the clock! scores = {'Mean Absolute Error:':[], 'Mean Squared Error:':[], 'Median Abso...
examples/pbwitt/testing.ipynb
DistrictDataLabs/yellowbrick
apache-2.0
Load the entire dataset into an array and scale from the range [0,255] to [0,1].
X, y = dataset.get_data(request=range(dataset.num_examples)) X = X / 255.0
SUPPLEMENTARY - Standardisation.ipynb
Britefury/deep-learning-tutorial-pydata2016
mit
Get all the pixels in one long array.
samples_rgb = np.rollaxis(X, 1, 4).reshape((-1, 3))
SUPPLEMENTARY - Standardisation.ipynb
Britefury/deep-learning-tutorial-pydata2016
mit
Create a scatter plot to show the distribution of the pixel RGB values Select a random subset of samples for the scatter plot.
indices = np.arange(samples_rgb.shape[0]) np.random.shuffle(indices) samples_rgb_subset = samples_rgb[indices[:50000]]
SUPPLEMENTARY - Standardisation.ipynb
Britefury/deep-learning-tutorial-pydata2016
mit
Create a 3D plot.
fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('R') ax.set_ylabel('G') ax.set_zlabel('B') ax.scatter(samples_rgb_subset[:,0], samples_rgb_subset[:,1], samples_rgb_subset[:,2], marker='+', alpha=0.1, c='black') ax.view_init(elev=45., azim=-45)
SUPPLEMENTARY - Standardisation.ipynb
Britefury/deep-learning-tutorial-pydata2016
mit
Ideal distribution The ideal distribution for training a neural networks.
z_ideal = np.random.normal(size=(20000,3)) fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('R (ideal)') ax.set_ylabel('G (ideal)') ax.set_zlabel('B (ideal)') ax.scatter(z_ideal[:,0], z_ideal[:,1], z_ideal[:,2], marker='+', alpha=0.1, c='black') # Explicitly set the...
SUPPLEMENTARY - Standardisation.ipynb
Britefury/deep-learning-tutorial-pydata2016
mit
Standardisation The normal approach to standardisation will only help a little. Lets compute the mean and standard deviation and plot them over the scatter plot to show the distribution.
rgb_mean = np.mean(samples_rgb, axis=0) rgb_std = np.std(samples_rgb, axis=0) print 'Mean = {0}'.format(rgb_mean) print 'Std-dev = {0}'.format(rgb_std)
SUPPLEMENTARY - Standardisation.ipynb
Britefury/deep-learning-tutorial-pydata2016
mit