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
Lecture de la vรฉritable rรฉponse
AUS_response = pd.read_csv('AUS_test_Rain_tomorrow.csv', index_col=['Date'], parse_dates=True) y_true = (AUS_response['RainTomorrow'] == 'Yes').astype(int)
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Calcul du log-loss
log_loss(y_true, y_test_pred_proba_best)
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Aire sous la courbe
print(f'AUC = {roc_auc_score(y_true, y_test_pred_proba_best)}')
AUC = 0.8737077575165082
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Courbe ROC
fpr_rf, tpr_rf, thresholds = roc_curve(y_true, y_test_pred_proba_best) fig = plt.figure(4, figsize=(6, 6)) plt.plot([0, 1], [0, 1], 'k--') plt.plot(fpr_rf, tpr_rf, label='Meilleur modรจle') plt.xlabel('False positive rate') plt.ylabel('True positive rate') plt.title('ROC curve') plt.show()
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Score F1
f1_score(y_true, y_test_pred_proba_best > selected_threshold) # Attention, utiliser le seuil trouvรฉ par validation croisรฉe !
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
Matrice de confusion
fig = plt.figure(3, figsize=(6, 6)) cnf_matrix = confusion_matrix(y_true, y_test_pred_proba_best > selected_threshold) np.set_printoptions(precision=2) plot_confusion_matrix(cnf_matrix, classes=['0','1'], title='Matrice de confusion') # Accuracy (26094+7500)/(26094+7500+7045+2018)
_____no_output_____
MIT
projet2/projet2-solution.ipynb
tiombo/Projet-Final
**Data Pre Processing**
DATA_DIR = "Beijing-Pollution-DataSet/" from pandas import read_csv from datetime import datetime from random import randint def select_month(sequences, n_samples=250): X, y = list(), list() rand_hour = randint(0, 24) rand_day = randint(0, 7) for i in range(0, n_samples): start_ix = rand_hour +...
_____no_output_____
MIT
Q1 PartD/Q1 PartD - Monthly/MiniProj_RNN_ADAgrad_MSE_Q1_PartD_Pytorch_Monthly.ipynb
parhamzm/Beijing-Weather-Prediction
Preprocessing
raw_data.describe(include='all') data = raw_data.drop(['Model'],axis=1) data.describe(include='all') # dropped the Model category because it is irrelevant to increasing the accuracy of my model. data.isnull().sum() #this shows the missing values in my dataset data_no_mv = data.dropna(axis=0) #I drop the missing values ...
_____no_output_____
Apache-2.0
Linear Regression w sklearn Case Exercise.ipynb
jovemmanuelre/Practical-Case-Example-Regression-with-sklearn
PDFs Here I check the Probability Distribution Functions (PDF) of the Independent Variables Price, Year, Mileage, and Engine Volume to identify and weed out the Outliers. They can adversely affect the accuracy of my Regression model because a Regression attempts to draw a line closest to all the data; including the Ou...
sns.distplot(data_no_mv['Price']) q = data_no_mv['Price'].quantile(0.99) data_1 = data_no_mv[data_no_mv['Price']<q] data_1.describe(include='all') # I decided to exclude the observations in the 99th percentile and above to get rid of the Outliers. sns.distplot(data_1['Price']) # Now the Price variable only includes obs...
_____no_output_____
Apache-2.0
Linear Regression w sklearn Case Exercise.ipynb
jovemmanuelre/Practical-Case-Example-Regression-with-sklearn
Checking the OLS assumptions Distribution
f, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize =(15,3)) ax1.scatter(data_cleaned['Year'],data_cleaned['Price']) ax1.set_title('Price and Year') ax2.scatter(data_cleaned['EngineV'],data_cleaned['Price']) ax2.set_title('Price and EngineV') ax3.scatter(data_cleaned['Mileage'],data_cleaned['Price']) ax3.set_t...
_____no_output_____
Apache-2.0
Linear Regression w sklearn Case Exercise.ipynb
jovemmanuelre/Practical-Case-Example-Regression-with-sklearn
Multicollinearity
data_cleaned.columns.values from statsmodels.stats.outliers_influence import variance_inflation_factor variables = data_cleaned[['Mileage','Year','EngineV']] vif = pd.DataFrame() vif["VIF"] = [variance_inflation_factor(variables.values, i) for i in range(variables.shape[1])] vif["features"] = variables.columns # Throug...
_____no_output_____
Apache-2.0
Linear Regression w sklearn Case Exercise.ipynb
jovemmanuelre/Practical-Case-Example-Regression-with-sklearn
Training my Regression Model
targets = data_preprocessed['log_price'] inputs = data_preprocessed.drop(['log_price'], axis=1) # I removed log_price in the inputs to exclude the transformed dependent variable from my inputs. from sklearn.preprocessing import StandardScaler scaler = StandardScaler () scaler.fit(inputs) inputs_scaled = scaler.transfor...
_____no_output_____
Apache-2.0
Linear Regression w sklearn Case Exercise.ipynb
jovemmanuelre/Practical-Case-Example-Regression-with-sklearn
Using Residuals to check the Model
sns.distplot(y_train-y_hat) plt.title("Residuals PDF", size=20) #to check whether the Residuals is normally distributed and the variability of the outcome reg.score(x_train, y_train) reg.intercept_ # The intercept or bias calibrates the model: without it, each feature will be off the mark. reg.coef_ reg_summary=pd.Data...
_____no_output_____
Apache-2.0
Linear Regression w sklearn Case Exercise.ipynb
jovemmanuelre/Practical-Case-Example-Regression-with-sklearn
Testing my Model
y_hat_test = reg.predict(x_test) plt.scatter(y_test, y_hat_test, alpha=0.2) plt.xlabel('Targets(y_test)', size=20) plt.ylabel('Predictions(y_hat_test)', size=20) plt.xlim(6, 13) plt.ylim(6, 13) plt.show() df_pf = pd.DataFrame(np.exp(y_hat_test), columns=['Prediction']) #this returns the exponential of Y Hat Test and re...
_____no_output_____
Apache-2.0
Linear Regression w sklearn Case Exercise.ipynb
jovemmanuelre/Practical-Case-Example-Regression-with-sklearn
Simple Sentiment Analysis PipelineHere we train simple 2 layer neural network for sentiment analysis. - Model: 2 Fully Connected layer NN (PyTorch)- Dataset: Sentiment Analysis- Embedding: spacy en_core_web_lg (mean aggregated embeddings of the text) Install Requirements from [repository](https://github.com/AnzorGoza...
!wget https://raw.githubusercontent.com/AnzorGozalishvili/active_learning_playground/main/requirements.txt !pip install -r requirements.txt !rm requirements.txt !pip install spacy-sentence-bert==0.1.2
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
Imports
# system import os import sys # data and models import numpy as np import pandas as pd import scipy # utilities import random import re import datetime # text embeddings import spacy import spacy_sentence_bert # scikit-learn stuff import sklearn from sklearn.model_selection import train_test_split from sklearn.metr...
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
Set Random SeedsFor reproducibility we set several random seeds which are recommended by PyTorch. ([See here](https://pytorch.org/docs/stable/notes/randomness.html))
random.seed(hash("setting random seeds") % 2**32 - 1) np.random.seed(hash("improves reproducibility") % 2**32 - 1) torch.manual_seed(hash("PyTorch") % 2**32 - 1) RANDOM_SEED = 42
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
DatasetLet's download dataset from given [url](https://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip), then take a look at samples. Retrieve dataset
def get_dataset(): resp = urlopen("https://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip") zipfile = ZipFile(BytesIO(resp.read())) lines = list() for line in zipfile.open('SMSSpamCollection').readlines(): lines.append(line.decode('utf-8')) data = pd....
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
Explore Samples
dataset.head() dataset.shape
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
Generate Train/Test splits and move forward We see the imbalance in target variable
dataset.label.value_counts()
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
We have duplicated records
dataset.duplicated().sum()
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
remove these duplicates
dataset.drop_duplicates(inplace=True) dataset.reset_index(drop=True, inplace=True)
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
split into train/test splits with 20/80 ratio
train, test = train_test_split(dataset, test_size=0.2, random_state=RANDOM_SEED)
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
Store these sets into dataset directory
DATASET_NAME = "SMSSpamCollection" if not os.path.exists('data'): os.mkdir('data') if not os.path.exists(f'data/{DATASET_NAME}'): os.mkdir(f'data/{DATASET_NAME}') train.to_csv(f'data/{DATASET_NAME}/train.csv') test.to_csv(f'data/{DATASET_NAME}/test.csv')
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
Load again and continue
train = pd.read_csv(f'data/{DATASET_NAME}/train.csv', index_col=0) test = pd.read_csv(f'data/{DATASET_NAME}/test.csv', index_col=0) train.shape, test.shape train.head(2)
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
Generate EmbeddingsWe use spacy embeddings to vectorize our samples
class Vectorizer: """Generates text embedding using deep learning model""" def __init__(self, *args, **kwargs): self.model = spacy_sentence_bert.load_model(kwargs.get('model', 'en_paraphrase_distilroberta_base_v1')) def __call__(self, text): if not text: text = "" ...
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
PyTorch ML Pipeline ModelExample of model is taken from [here](https://github.com/rmunro/pytorch_active_learning/blob/master/active_learning_basics.py)
class MLP(nn.Module): """Simple 2 Layer Fully Connected NN (MLP)""" def __init__(self, num_labels, emb_dim): super(MLP, self).__init__() # Define model with one hidden layer with 128 neurons self.linear1 = nn.Linear(emb_dim, 128) self.linear2 = nn.Linear(128, num_labels) ...
_____no_output_____
MIT
notebooks/regular_sentiment_analysis_pipeline.ipynb
AnzorGozalishvili/active_learning_playground
Bias Removal Climate models can have biases relative to different verification datasets. Commonly, biases are removed by postprocessing before verification of forecasting skill. `climpred` provides convenience functions to do so.
import climpred import xarray as xr import matplotlib.pyplot as plt from climpred import HindcastEnsemble hind = climpred.tutorial.load_dataset('CESM-DP-SST') # CESM-DPLE hindcast ensemble output. obs = climpred.tutorial.load_dataset('ERSST') # observations hind["lead"].attrs["units"] = "years"
_____no_output_____
MIT
docs/source/bias_removal.ipynb
andersy005/climpred
We begin by removing a mean climatology for the observations, since `CESM-DPLE` generates its anomalies over this same time period.
obs = obs - obs.sel(time=slice('1964', '2014')).mean('time') hindcast = HindcastEnsemble(hind) hindcast = hindcast.add_observations(obs) hindcast.plot()
/Users/rileybrady/Desktop/dev/climpred/climpred/utils.py:141: UserWarning: Assuming annual resolution due to numeric inits. Change init to a datetime if it is another resolution. "Assuming annual resolution due to numeric inits. "
MIT
docs/source/bias_removal.ipynb
andersy005/climpred
The warming of the `observations` is similar to `initialized`. Mean bias removal Typically, bias depends on lead-time and therefore should therefore also be removed depending on lead-time.
bias = hindcast.verify(metric='bias', comparison='e2o', dim=[], alignment='same_verifs') bias.SST.plot()
_____no_output_____
MIT
docs/source/bias_removal.ipynb
andersy005/climpred
Against `observations`, there is small cold bias in 1980 and 1990 initialization years and warm bias before and after.
# lead-time dependant mean bias over all initializations is quite small but negative mean_bias = bias.mean('init') mean_bias.SST.plot()
_____no_output_____
MIT
docs/source/bias_removal.ipynb
andersy005/climpred
Cross ValidatationTo remove the mean bias quickly, the mean bias over all initializations is subtracted. For formally correct bias removal with cross validation, the given initialization is left out when subtracting the mean bias. `climpred` wraps these functions in `HindcastEnsemble.remove_bias(how='mean', cross_vali...
hindcast.remove_bias(how='mean', cross_validate=True, alignment='same_verifs').plot() plt.title('hindcast lead timeseries removed for unconditional mean bias') plt.show()
_____no_output_____
MIT
docs/source/bias_removal.ipynb
andersy005/climpred
Skill Distance-based accuracy metrics like (`mse`,`rmse`,`nrmse`,...) are sensitive to mean bias removal. Correlations like (`pearson_r`, `spearman_r`) are insensitive to bias correction.
metric='rmse' hindcast.verify(metric=metric, comparison='e2o', dim='init', alignment='same_verifs')['SST'].plot(label='no bias correction') hindcast.remove_bias(cross_validate=False, alignment='same_verifs') \ .verify(metric=metric, ...
_____no_output_____
MIT
docs/source/bias_removal.ipynb
andersy005/climpred
ๆฉŸๆขฐๅญฆ็ฟ’ใƒฉใ‚คใƒ–ใƒฉใƒชๆฉŸๆขฐๅญฆ็ฟ’ใƒฉใ‚คใƒ–ใƒฉใƒชใ€KerasใจPyTorchใฎใ‚ณใƒผใƒ‰ใ‚’็ดนไป‹ใ—ใพใ™ใ€‚ ไปŠๅ›žใฏใ‚ณใƒผใƒ‰ใฎ่ฉณใ—ใ„่งฃ่ชฌใฏ่กŒใ„ใพใ›ใ‚“ใŒใ€ๅฎŸ่ฃ…ใฎๅคงใพใ‹ใชๆตใ‚Œใ‚’ๆŠŠๆกใ—ใพใ—ใ‚‡ใ†ใ€‚ โ— Kerasใฎใ‚ณใƒผใƒ‰ไปฅไธ‹ใฎใ‚ณใƒผใƒ‰ใฏใ€Kerasใซใ‚ˆใ‚‹ใ‚ทใƒณใƒ—ใƒซใชใƒ‹ใƒฅใƒผใƒฉใƒซใƒใƒƒใƒˆใƒฏใƒผใ‚ฏใฎๅฎŸ่ฃ…ใงใ™ใ€‚ Irisใฎๅ„่Šฑใ‚’ใ€SetosaใจVersicolorใซๅˆ†้กžใ—ใพใ™ใ€‚ ไปฅไธ‹ใฎใ‚ณใƒผใƒ‰ใงใฏใ€`Sequential`ใงใƒขใƒ‡ใƒซใ‚’ไฝœใ‚Šใ€ๅฑคใ‚„ๆดปๆ€งๅŒ–้–ขๆ•ฐใ‚’่ฟฝๅŠ ใ—ใฆใ„ใพใ™ใ€‚
import numpy as np from sklearn import datasets from sklearn import preprocessing from sklearn.model_selection import train_test_split iris = datasets.load_iris() iris_data = iris.data sl_data = iris_data[:100, 0] # SetosaใจVersicolorใ€Sepal length sw_data = iris_data[:100, 1] # SetosaใจVersicolorใ€Sepal width # ๅนณๅ‡ๅ€คใ‚’0ใซ ...
_____no_output_____
MIT
section_7/ml_libraries.ipynb
kiyoshion/minna-ai
โ— PyTorchใฎใ‚ณใƒผใƒ‰ไปฅไธ‹ใฎใ‚ณใƒผใƒ‰ใฏใ€PyTorchใ‚ˆใ‚‹ใ‚ทใƒณใƒ—ใƒซใชใƒ‹ใƒฅใƒผใƒฉใƒซใƒใƒƒใƒˆใƒฏใƒผใ‚ฏใฎๅฎŸ่ฃ…ใงใ™ใ€‚ Irisใฎๅ„่Šฑใ‚’ใ€SetosaใจVersicolorใซๅˆ†้กžใ—ใพใ™ใ€‚ ไปฅไธ‹ใฎใ‚ณใƒผใƒ‰ใงใฏใ€KerasใจๅŒๆง˜ใซ`Sequential`ใงใƒขใƒ‡ใƒซใ‚’ไฝœใ‚Šใ€ๅฑคใ‚„ๆดปๆ€งๅŒ–้–ขๆ•ฐใ‚’ไธฆในใฆใ„ใพใ™ใ€‚ PyTorchใงใฏใ€ๅ…ฅๅŠ›ใ‚„ๆญฃ่งฃใ‚’Tensorๅฝขๅผใฎใƒ‡ใƒผใ‚ฟใซๅค‰ๆ›ใ™ใ‚‹ๅฟ…่ฆใŒใ‚ใ‚Šใพใ™ใ€‚
import numpy as np from sklearn import datasets from sklearn import preprocessing from sklearn.model_selection import train_test_split iris = datasets.load_iris() iris_data = iris.data sl_data = iris_data[:100, 0] # SetosaใจVersicolorใ€Sepal length sw_data = iris_data[:100, 1] # SetosaใจVersicolorใ€Sepal width # ๅนณๅ‡ๅ€คใ‚’0ใซ ...
_____no_output_____
MIT
section_7/ml_libraries.ipynb
kiyoshion/minna-ai
Transfer Learning Template
%load_ext autoreload %autoreload 2 %matplotlib inline import os, json, sys, time, random import numpy as np import torch from torch.optim import Adam from easydict import EasyDict import matplotlib.pyplot as plt from steves_models.steves_ptn import Steves_Prototypical_Network from steves_utils.lazy_iterable_wr...
_____no_output_____
MIT
experiments/tl_2/cores_wisig-oracle.run2.framed/trials/1/trial.ipynb
stevester94/csc500-notebooks
Allowed ParametersThese are allowed parameters, not defaultsEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)Papermill uses the cell tag "parameters" to inject the real parameters below this cell.Enable tags to see what I mean
required_parameters = { "experiment_name", "lr", "device", "seed", "dataset_seed", "n_shot", "n_query", "n_way", "train_k_factor", "val_k_factor", "test_k_factor", "n_epoch", "patience", "criteria_for_best", "x_net", "datasets", "torch_default_dtype", ...
_____no_output_____
MIT
experiments/tl_2/cores_wisig-oracle.run2.framed/trials/1/trial.ipynb
stevester94/csc500-notebooks
Supplementary
def show_results_dist_1_3(frames, title, y_axe_name, dims=(18, 12), save=False, file_name='trash', legend_size=13): size = len(frames) a4_dims = dims fig, axs = plt.subplots(1, 3, figsize=a4_dims) for i in range(3): sns.lineplot(x="Error = 1 - Recall@1", y=y_axe_name,hu...
_____no_output_____
MIT
results/draw_results.ipynb
Shekhale/gbnns_theory
y = 0.14766146x + 12.10283073
lr.score(x,y) #์ •ํ™•๋„
_____no_output_____
Apache-2.0
autompg_regression-Copy1.ipynb
power3247/test_machinlearning
์‚ฌ์ดํ‚ท ๋Ÿฐ ๋ชจ๋ธ๋ง์„ ํ†ตํ•ด์„œ ๋‘ ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ์–ด์ฃผ๊ณ  ์„ ํ˜•๋ชจ๋ธ์„ ๋งŒ๋“ ๊ฒƒ
y_predicted = lr.predict([[99]]) y_predicted
_____no_output_____
Apache-2.0
autompg_regression-Copy1.ipynb
power3247/test_machinlearning
1. ์ •๋ณด๋‹จ๊ณ„: ์ˆ˜์ง‘ ๊ฐ€๊ณต- ๋ฌธ์ œ ๋ฐ์ดํ„ฐ ํ™•์ธ ๋ฐ ์ฒ˜๋ฆฌ2. ๊ต์œก ๋‹จ๊ณ„: ๋จธ์‹  ๋Œ€์ƒ- ์ปฌ๋Ÿผ์„ ํƒ- ๋ชจ๋ธ ์„ ํƒ- ๊ต์œก- ์ •ํ™•๋„ ํ™•์ธ3. ์„œ๋น„์Šค ๋‹จ๊ณ„:๊ณ ๊ฐ์‘๋Œ€ X์˜ ๊ฐ’์„ ๋Š˜๋ฆด์ˆ˜ ์žˆ๋‹ค
from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(x, y) X_train, X_test, Y_train, Y_test lr.fit(X_train, Y_train) lr.coef_, lr.intercept_ #๊ธฐ์šธ๊ธฐ, ์ ˆํŽธ lr.score(X_train, Y_train) lr.score(X_test,Y_test) lr.predict([[3504.0, 8]]) lr.predict([[2790.0, 4]]) import pickle p...
_____no_output_____
Apache-2.0
autompg_regression-Copy1.ipynb
power3247/test_machinlearning
Fig.3 - Comparisons of MDR's AUC across 12 different sets Change plot's default size and font
import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [20, 12] rc = {"font.family" : "sans-serif", "font.style" : "normal", "mathtext.fontset" : "dejavusans"} plt.rcParams.update(rc) plt.rcParams["font.sans-serif"] = ["Myriad Pro"] + plt.rcParams["font.sans-serif"] from constant import HEADER_NA...
_____no_output_____
MIT
mdr_analysis/3Fig-version0-AUC_IQR_across_therapy_and_sets-separate.ipynb
bonilab/malariaibm-generation-of-MDR-mutants
PfPR = 0.1%
fig, axes = plt.subplots(5, 3, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0}) fig.patch.set_facecolor('white') fig.suptitle('PfPR = 0.1%', y=0.93, fontweight='bold', fontsize=TITLE_FONTSIZE) # plot IQR of AUC for most-dangerous-triple and -double from plotter import fig3_da...
_____no_output_____
MIT
mdr_analysis/3Fig-version0-AUC_IQR_across_therapy_and_sets-separate.ipynb
bonilab/malariaibm-generation-of-MDR-mutants
PfPR = 1%
fig, axes = plt.subplots(5, 3, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0}) fig.patch.set_facecolor('white') fig.suptitle('PfPR = 1%', y=0.93, fontweight='bold', fontsize=TITLE_FONTSIZE) # plot IQR of AUC for most-dangerous-triple and -double from plotter import fig3_dang...
_____no_output_____
MIT
mdr_analysis/3Fig-version0-AUC_IQR_across_therapy_and_sets-separate.ipynb
bonilab/malariaibm-generation-of-MDR-mutants
PfPR = 5%
fig, axes = plt.subplots(5, 3, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0}) fig.patch.set_facecolor('white') fig.suptitle('PfPR = 5%', y=0.93, fontweight='bold', fontsize=TITLE_FONTSIZE) # plot IQR of AUC for most-dangerous-triple and -double from plotter import fig3_dang...
_____no_output_____
MIT
mdr_analysis/3Fig-version0-AUC_IQR_across_therapy_and_sets-separate.ipynb
bonilab/malariaibm-generation-of-MDR-mutants
PfPR = 20%
fig, axes = plt.subplots(5, 3, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0}) fig.patch.set_facecolor('white') fig.suptitle('PfPR = 20%', y=0.93, fontweight='bold', fontsize=TITLE_FONTSIZE) # plot IQR of AUC for most-dangerous-triple and -double from plotter import fig3_dan...
_____no_output_____
MIT
mdr_analysis/3Fig-version0-AUC_IQR_across_therapy_and_sets-separate.ipynb
bonilab/malariaibm-generation-of-MDR-mutants
Image ClassificationIn this project, you'll classify images from the [CIFAR-10 dataset](https://www.cs.toronto.edu/~kriz/cifar.html). The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be norm...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifar10...
CIFAR-10 Dataset: 171MB [01:58, 1.44MB/s]
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Explore the DataThe dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named `data_batch_1`, `data_batch_2`, etc.. Each batch contains the labels and images that are one of the following:* airplane* automobile* bird* cat* deer* dog* frog* hor...
%matplotlib inline %config InlineBackend.figure_format = 'retina' import helper import numpy as np # Explore the dataset batch_id = 1 sample_id = 5 helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)
Stats of batch 1: Samples: 10000 Label Counts: {0: 1005, 1: 974, 2: 1032, 3: 1016, 4: 999, 5: 937, 6: 1030, 7: 1001, 8: 1025, 9: 981} First 20 Labels: [6, 9, 9, 4, 1, 1, 2, 7, 8, 3, 4, 7, 7, 2, 9, 9, 9, 3, 2, 6] Example of Image 5: Image - Min Value: 0 Max Value: 252 Image - Shape: (32, 32, 3) Label - Label Id: 1 Nam...
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Implement Preprocess Functions NormalizeIn the cell below, implement the `normalize` function to take in image data, `x`, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as `x`.
def normalize(x): """ Normalize a list of sample image data in the range of 0 to 1 : x: List of image data. The image shape is (32, 32, 3) : return: Numpy array of normalize data """ min = np.amin(x) max = np.amax(x) return (x - min) / (max - min) """ DON'T MODIFY ANYTHING IN THIS CEL...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
One-hot encodeJust like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the `one_hot_encode` function. The input, `x`, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are...
x = np.array([6, 1, 5]) np.array([[1 if i == y else 0 for i in range(10)] for y in x]) def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ return np.array...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Randomize DataAs you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset. Preprocess all the data and save itRunning the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also...
""" DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)
_____no_output_____
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Check PointThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
""" DON'T MODIFY ANYTHING IN THIS CELL """ import pickle import problem_unittests as tests import helper # Load the Preprocessed Validation data valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))
_____no_output_____
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Build the networkFor the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest...
import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a batch of image input : image_shape: Shape of the images : return: Tensor for image input. """ return tf.placeholder(tf.float32, shape = [None] + list(image_shape), name = "x") def neural_net_label_input...
Image Input Tests Passed. Label Input Tests Passed. Keep Prob Tests Passed.
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Convolution and Max Pooling LayerConvolution layers have a lot of success with images. For this code cell, you should implement the function `conv2d_maxpool` to apply convolution then max pooling:* Create the weight and bias using `conv_ksize`, `conv_num_outputs` and the shape of `x_tensor`.* Apply a convolution to `x...
def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple fo...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Flatten LayerImplement the `flatten` function to change the dimension of `x_tensor` from a 4-D tensor to a 2-D tensor. The output should be the shape (*Batch Size*, *Flattened Image Size*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [Tens...
import numpy as np def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ x_size = x_tensor.get_shape().as_list() ...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Fully-Connected LayerImplement the `fully_conn` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tens...
def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_out...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Output LayerImplement the `output` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/ap...
def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Create Convolutional ModelImplement the function `conv_net` to create a convolutional neural network model. The function takes in a batch of images, `x`, and outputs logits. Use the layers you created above to create this model:* Apply 1, 2, or 3 Convolution and Max Pool layers* Apply a Flatten Layer* Apply 1, 2, or ...
def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers ...
Neural Network Built!
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Train the Neural Network Single OptimizationImplement the function `train_neural_network` to do a single optimization. The optimization should use `optimizer` to optimize in `session` with a `feed_dict` of the following:* `x` for image input* `y` for labels* `keep_prob` for keep probability for dropoutThis function w...
def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Num...
Tests Passed
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Show StatsImplement the function `print_stats` to print loss and validation accuracy. Use the global variables `valid_features` and `valid_labels` to calculate validation accuracy. Use a keep probability of `1.0` to calculate the loss and validation accuracy.
def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy...
_____no_output_____
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
HyperparametersTune the following parameters:* Set `epochs` to the number of iterations until the network stops learning or start overfitting* Set `batch_size` to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ...* Set `keep_probability` to the ...
# TODO: Tune Parameters epochs = 10 batch_size = 256 keep_probability = .5
_____no_output_____
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Train on a Single CIFAR-10 BatchInstead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section.
""" DON'T MODIFY ANYTHING IN THIS CELL """ print('Checking the Training on a Single Batch...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): batch_i = 1 for batch_features, batch_label...
Checking the Training on a Single Batch... Epoch 1, CIFAR-10 Batch 1: Training Loss= 2.303360, Training Accuracy= 0.07500 Validation Loss= 2.302445, Validation Accuracy= 0.10020 Epoch 2, CIFAR-10 Batch 1: Training Loss= 2.300095, Training Accuracy= 0.07500 Validation Loss= 2.300672, Validation Accuracy= 0.10680 Epo...
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Fully Train the ModelNow that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches.
""" DON'T MODIFY ANYTHING IN THIS CELL """ save_model_path = './image_classification' print('Training...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches n_batc...
Training... Epoch 1, CIFAR-10 Batch 1: Training Loss= 2.267260, Training Accuracy= 0.10000 Validation Loss= 2.247928, Validation Accuracy= 0.15120 Epoch 1, CIFAR-10 Batch 2: Training Loss= 1.995992, Training Accuracy= 0.17500 Validation Loss= 2.067119, Validation Accuracy= 0.22640 Epoch 1, CIFAR-10 Batch 3: Train...
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
CheckpointThe model has been saved to disk. Test ModelTest your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters.
""" DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import tensorflow as tf import pickle import helper import random # Set batch size if not already set try: if batch_size: pass except NameError: batch_size = 64 save_model_path = './image_clas...
Testing Accuracy: 0.5068359375
MIT
image-classification/dlnd_image_classification.ipynb
mdiaz236/DeepLearningFoundations
Least-squares technique References - Statistics in geography: https://archive.org/details/statisticsingeog0000ebdo/ Imports
from functools import partial import numpy as np from scipy.stats import multivariate_normal, t import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from ipywidgets import interact, IntSlider inv = np.linalg.inv df = pd.read_csv('regression_data.csv') df.head(3)
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Population 0.5 and 0.2 are NOT the population parameters. Although we used them to generate the population, the population parameters can be different from them.
def get_y(x): ys = x * 0.5 + 0.2 noises = 1 * np.random.normal(size=len(ys)) return ys + noises np.random.seed(52) xs = np.linspace(0, 10, 10000) ys = get_y(xs) np.random.seed(32) np.random.shuffle(xs) np.random.seed(32) np.random.shuffle(ys) plt.scatter(xs, ys, s=5) plt.show()
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Design matrices
PHI = xs.reshape(-1, 1) PHI = np.hstack([ PHI, np.ones(PHI.shape) ]) T = ys.reshape(-1, 1)
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Normal equation with regularization
def regularized_least_squares(PHI, T, regularizer=0): assert PHI.shape[0] == T.shape[0] pseudo_inv = inv(PHI.T @ PHI + np.eye(PHI.shape[1]) * regularizer) assert pseudo_inv.shape[0] == pseudo_inv.shape[1] W = pseudo_inv @ PHI.T @ T return {'slope' : float(W[0]), 'intercept' ...
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Sampling distributions Population parameters
pop_params = regularized_least_squares(PHI, T) pop_slope, pop_intercept = pop_params['slope'], pop_params['intercept']
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Sample statistics Verify that the sampling distribution for both regression coefficients are normal.
n = 10 # sample size num_samps = 1000 def sample(PHI, T, n): idxs = np.random.randint(PHI.shape[0], size=n) return PHI[idxs], T[idxs] samp_slopes, samp_intercepts = [], [] for i in range(num_samps): PHI_samp, T_samp = sample(PHI, T, n) learned_param = regularized_least_squares(PHI_samp, T_samp) sam...
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Note that the two normal distributions above are correlated. This means that we need to be careful when plotting the 95% CI for the regression line, because we can't just plot the regression line with the highest slope and the highest intercept and the regression line with the lowest slope and the lowest intercept.
sns.jointplot(samp_slopes, samp_intercepts, s=5) plt.show()
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Confidence interval **Caution.** The following computation of confidence intervals does not apply to regularized least squares. Sample one sample
n = 500 PHI_samp, T_samp = sample(PHI, T, n)
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Compute sample statistics
learned_param = regularized_least_squares(PHI_samp, T_samp) samp_slope, samp_intercept = learned_param['slope'], learned_param['intercept'] samp_slope, samp_intercept
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Compute standard errors of sample statisticsStandard error is the estimate of the standard deviation of the sampling distribution. $$\hat\sigma = \sqrt{\frac{\text{Sum of all squared residuals}}{\text{Degrees of freedom}}}$$ Standard error for slope:$$\text{SE}(\hat\beta_1)=\hat\sigma \sqrt{\frac{1}{(n-1)s_X^2}}$$ Sta...
preds = samp_slope * PHI_samp[:,0] + samp_intercept sum_of_squared_residuals = np.sum((T_samp.reshape(-1) - preds) ** 2) samp_sigma_y_give_x = np.sqrt(sum_of_squared_residuals / (n - 2)) samp_sigma_y_give_x samp_mean = np.mean(PHI_samp[:,0]) samp_var = np.var(PHI_samp[:,0]) SE_slope = samp_sigma_y_give_x * np.sqrt(1 / ...
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Compute confidence intervals for sample statistics
slope_lower, slope_upper = samp_slope - 1.96 * SE_slope, samp_slope + 1.96 * SE_slope slope_lower, slope_upper intercept_lower, intercept_upper = samp_intercept - 1.96 * SE_intercept, samp_intercept + 1.96 * SE_intercept intercept_lower, intercept_upper
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Compute confidence interval for regression line Boostrapped solution Use a 2-d Guassian to model the joint distribution between boostrapped sample slopes and boostrapped sample intercepts. **Fixed.** `samp_slopes` and `samp_intercepts` used in the cell below are not boostrapped; they are directly sampled from the pop...
num_resamples = 10000 resample_slopes, resample_intercepts = [], [] for i in range(num_resamples): PHI_resample, T_resample = sample(PHI_samp, T_samp, n=len(PHI_samp)) learned_params = regularized_least_squares(PHI_resample, T_resample) resample_slopes.append(learned_params['slope']); resample_intercepts.ap...
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
**Fixed.** The following steps might improve the results, but I don't think they are part of the standard practice.
# means = [np.mean(resample_slopes), np.mean(resample_intercepts)] # cov = np.cov(resample_slopes, resample_intercepts) # model = multivariate_normal(mean=means, cov=cov)
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Sample 5000 (slope, intercept) pairs from the Gaussian.
# num_pairs_sampled = 10000 # pairs = model.rvs(num_pairs_sampled)
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Scatter samples, plot regression lines and CI.
plt.figure(figsize=(20, 10)) plt.scatter(PHI_samp[:,0], T_samp.reshape(-1), s=20) # sample granularity = 1000 xs = np.linspace(0, 10, granularity) plt.plot(xs, samp_slope * xs + samp_intercept, label='Sample') # sample regression line plt.plot(xs, pop_slope * xs + pop_intercept, '--', color='black', label='Popu...
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Analytic solution **Reference.** Page 97, Statistics of Geograph: A Practical Approach, David Ebdon, 1987. For a particular value $x_0$ of the independent variable $x$, its confidence interval is given by: $$\sqrt{\frac{\sum e^{2}}{n-2}\left[\frac{1}{n}+\frac{\left(x_{0}-\bar{x}\right)^{2}}{\sum x^{2}-n \bar{x}^{2}}\r...
sum_of_squared_xs = np.sum(PHI_samp[:,0] ** 2) SEs = np.sqrt( (sum_of_squared_residuals / (n - 2)) * (1 / n + (xs - samp_mean) ** 2 / (sum_of_squared_xs - n * samp_mean ** 2)) ) t_97dot5 = t.ppf(0.975, df=n-2) t_99dot5 = t.ppf(0.995, df=n-2) yhats = samp_slope * xs + samp_intercept uppers_95 = yhats + t_97dot5...
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Regularized least squares
def plot_regression_line(PHI, T, regularizer): plt.scatter(PHI[:,0], T, s=5) params = regularized_least_squares(PHI, T, regularizer) x_min, x_max = PHI[:,0].min(), PHI[:,0].max() xs = np.linspace(x_min, x_max, 2) ys = params['slope'] * xs + params['intercept'] plt.plot(xs, ys...
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
Yes! The effect of regularization does change with the size of the dataset.
_ = interact( plot_regression_line_wrapper, regularizer=IntSlider(min=0, max=10000, value=5000, continuous_update=False), num_points=IntSlider(min=2, max=1000, value=1000, continuous_update=False) )
_____no_output_____
MIT
c3_single_layer_networks/least_square_method/least_square_method_demo.ipynb
zhihanyang2022/bishop1995_notes
1. ์ •๊ทœ ํ‘œํ˜„์‹* ์ถœ์ฒ˜ : ์„œ์  "์žก์•„๋ผ! ํ…์ŠคํŠธ ๋งˆ์ด๋‹ with ํŒŒ์ด์ฌ"* ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„ ๊ทœ์น™์— ์ผ์น˜ํ•˜๋Š” ์ง€, ์ผ์น˜ํ•˜์ง€ ์•Š๋Š”์ง€ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ๋‹ค. ์ •๊ทœ ํ‘œํ˜„์‹์„ ์ด์šฉํ•˜์—ฌ ํŠน์ • ํŒจํ„ด์„ ์ง€๋‹ˆ๋‹ˆ ๋ฌธ์ž์—ด์„ ์ฐพ์„ ์ˆ˜ ์žˆ์–ด ํ…์ŠคํŠธ ๋ฐ์ดํ„ฐ ์‚ฌ์ „ ์ฒ˜๋ฆฌ ๋ฐ ํฌ๋กค๋ง์—์„œ ์ฃผ๋กœ ์“ฐ์ž„
string = '๊ธฐ์ƒ์ฒญ์€ ์Šˆํผ์ปดํ“จํ„ฐ๋„ ์„œ์šธ์ง€์—ญ์˜ ์ง‘์ค‘ํ˜ธ์šฐ๋ฅผ ์ œ๋Œ€๋กœ ์˜ˆ์ธกํ•˜์ง€ ๋ชปํ–ˆ๋‹ค๊ณ  ์„ค๋ช…ํ–ˆ์Šต๋‹ˆ๋‹ค. ์™œ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ\ ์Šต๋‹ˆ๋‹ค. ์™œ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ๋Š”์ง€ ์ž์„ธํžˆ ๋ถ„์„ํ•ด ์˜ˆ์ธก ํ”„๋กœ๊ทธ๋žจ์„ ๋ณด์™„ํ•ด์•ผ ํ•  ๋Œ€๋ชฉ์ž…๋‹ˆ๋‹ค. ๊ด€์ธก ๋ถ„์•ผ๋Š” ๊ฐœ์„ ๋  ์—ฌ์ง€๊ฐ€\ ์žˆ์Šต๋‹ˆ๋‹ค. ์ง€๊ธˆ ๋ณด์‹œ๋Š” ์™ผ์ชฝ ์‚ฌ์ง„์ด ํ˜„์žฌ ์ฒœ๋ฆฌ์•ˆ ์œ„์„ฑ์ด ์ดฌ์˜ํ•œ ๊ฒƒ์ด๊ณ  ์˜ค๋ฅธ์ชฝ์ด ์˜ฌํ•ด ๋ง ์˜์•„ ์˜ฌ๋ฆด ์ฒœ๋ฆฌ์•ˆ 2Aํ˜ธ๊ฐ€ \ ์ดฌ์˜ํ•œ ์˜์ƒ์ž…๋‹ˆ๋‹ค. ์˜ค๋ฅธ์ชฝ์ด ์™ผ์ชฝ๋ณด๋‹ค ํƒœํ’์˜ ๋ˆˆ์ด ์ข€ ๋” ๋šœ๋ ทํ•˜๊ณ  ์ฃผ๋ณ€ ๊ตฌ๋ฆ„๋„ ๋” ์ž˜ ๋ณด์ด์ฃ . ์ƒˆ ์œ„์„ฑ์„ ํ†ตํ•ด ํƒœํ’\ ๊ตฌ๋ฆ„ ๋“ฑ์˜ ์›€์ง์ž„์„ ์ƒ์„ธํžˆ ๋ถ„์„ํ•˜๋ฉด ์ข€ ๋” ์ •ํ™•ํ•œ ์˜ˆ์ธก์„ ํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ ๊ธฐ๋Œ€ํ•ด ๋ด…๋‹ˆ๋‹ค. ์ •๊ตฌํฌ ...
_____no_output_____
MIT
[STUDY]ํ…์ŠคํŠธ๋งˆ์ด๋‹_Base.ipynb
kamzzang/ADPStudy
* \([A-Za-z0-9\._+]+ : ์ด๋ฉ”์ผ ์ฃผ์†Œ๊ฐ€ ๊ด„ํ˜ธ๋กœ ์‹œ์ž‘ํ•˜์—ฌ \(ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ์›๋ž˜ ์˜๋ฏธ๋Œ€๋กœ ์“ฐ๊ฒŒ ํ•จ)์™€ (๋กœ ์‹œ์ž‘ ๋Œ€๊ด„ํ˜ธ[ ] ์•ˆ์— ์ด๋ฉ”์ผ ์ฃผ์†Œ์˜ ํŒจํ„ด์„ ์ž…๋ ฅ(์ž…๋ ฅํ•œ ๊ฒƒ ์ค‘ ์•„๋ฌด๊ฑฐ๋‚˜) A-Z = ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž, a-z = ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž, 0-9 = ์ˆซ์ž, ._+ = .๋‚˜ _๋‚˜ + ๋งˆ์ง€๋ง‰ +๋Š” ๋ฐ”๋กœ ์•ž์— ์žˆ๋Š” ๊ฒƒ์ด ์ตœ์†Œ ํ•œ๋ฒˆ ์ด์ƒ ๋‚˜์™€์•ผ ํ•œ๋‹ค๋Š” ์˜๋ฏธ * @ : ์ด๋ฉ”์ผ ์ฃผ์†Œ ๋‹ค์Œ์— @ * [A-Za-z]+ : ๋„๋ฉ”์ธ ์ฃผ์†Œ์—...
# a๋ฌธ์ž๊ฐ€ 1๋ฒˆ ์ด์ƒ ๋‚˜์˜ค๊ณ  b ๋ฌธ์ž๊ฐ€ 0๋ฒˆ ์ด์ƒ ๋‚˜์˜ค๋Š” ๋ฌธ์ž์—ด ์ฐพ๊ธฐ r = re.compile("a+b*") r.findall("aaaa, cc, bbbb, aabbb") # ๋Œ€๊ด„ํ˜ธ๋ฅผ ์ด์šฉํ•ด ๋Œ€๋ฌธ์ž๋กœ ๊ตฌ์„ฑ๋œ ๋ฌธ์ž์—ด ์ฐพ๊ธฐ r = re.compile("[A-Z]+") r.findall("HOME, home") # ^์™€ .์„ ์ด์šฉํ•˜์—ฌ ๋งจ ์•ž์— a๊ฐ€ ์˜ค๊ณ  ๊ทธ ๋‹ค์Œ์— ์–ด๋– ํ•œ ํ˜•ํƒœ๋“  2๊ฐœ์˜ ๋ฌธ์ž๊ฐ€ ์˜ค๋Š” ๋ฌธ์ž์—ด ์ฐพ๊ธฐ r = re.compile("^a..") r.findall("abc, cba") # ์ค‘๊ด„ํ˜ธ ํ‘œํ˜„์‹ {m,n}์„ ์ด์š”ํ•˜์—ฌ ํ•ด๋‹น ๋ฌธ์ž์—ด์ด m๋ฒˆ ์ด์ƒ n๋ฒˆ ์ดํ•˜ ๋‚˜ํƒ€๋‚˜...
_____no_output_____
MIT
[STUDY]ํ…์ŠคํŠธ๋งˆ์ด๋‹_Base.ipynb
kamzzang/ADPStudy
2. ์ „์ฒ˜๋ฆฌ ๋Œ€์†Œ๋ฌธ์ž ํ†ต์ผ
s = 'Hello World' print(s.lower()) print(s.upper())
hello world HELLO WORLD
MIT
[STUDY]ํ…์ŠคํŠธ๋งˆ์ด๋‹_Base.ipynb
kamzzang/ADPStudy
์ˆซ์ž, ๋ฌธ์žฅ๋ถ€ํ˜ธ, ํŠน์ˆ˜๋ฌธ์ž ์ œ๊ฑฐ
# ์ˆซ์ž ์ œ๊ฑฐ p = re.compile("[0-9]+") p.sub("", '์„œ์šธ ๋ถ€๋™์‚ฐ ๊ฐ€๊ฒฉ์ด ์˜ฌํ•ด ๋“ค์–ด ํ‰๊ท  30% ์ƒ์Šนํ–ˆ์Šต๋‹ˆ๋‹ค.') # ๋ฌธ์žฅ๋ถ€ํ˜ธ, ํŠน์ˆ˜๋ฌธ์ž ์ œ๊ฑฐ p = re.compile("\W+") p.sub(" ", "โ˜…์„œ์šธ ๋ถ€๋™์‚ฐ ๊ฐ€๊ฒฉ์ด ์˜ฌํ•ด ๋“ค์–ด ํ‰๊ท  30% ์ƒ์Šนํ–ˆ์Šต๋‹ˆ๋‹ค.") s = p.sub(" ", "์ฃผ์ œ_1: ๊ฑด๊ฐ•ํ•œ ๋ฌผ๊ณผ ๊ฑด๊ฐ•ํ•œ ์ •์‹ !") s p = re.compile("_") p.sub(" ", s)
_____no_output_____
MIT
[STUDY]ํ…์ŠคํŠธ๋งˆ์ด๋‹_Base.ipynb
kamzzang/ADPStudy
๋ถˆ์šฉ์–ด ์ œ๊ฑฐ
words_Korean = ['์ถ”์„','์—ฐํœด','๋ฏผ์กฑ','๋Œ€์ด๋™','์‹œ์ž‘','๋Š˜์–ด','๊ตํ†ต๋Ÿ‰','๊ตํ†ต์‚ฌ๊ณ ','ํŠนํžˆ','์ž๋™์ฐจ','๊ณ ์žฅ', '์ƒ๋‹น์ˆ˜','์ฐจ์ง€','๋‚˜ํƒ€','๊ฒƒ','๊ธฐ์ž'] stopwords = ['๊ฐ€๋‹ค','๋Š˜์–ด','๋‚˜ํƒ€','๊ฒƒ','๊ธฐ์ž'] [i for i in words_Korean if i not in stopwords] from nltk.corpus import stopwords # ๊ทธ๋ƒฅํ•˜๋ฉด LookupError ๋ฐœ์ƒํ•˜๋ฏ€๋กœ ๋‹ค์šด๋กœ๋“œ๊ฐ€ ํ•„์š”ํ•จ # import nltk # nltk.download() or nltk.downlo...
_____no_output_____
MIT
[STUDY]ํ…์ŠคํŠธ๋งˆ์ด๋‹_Base.ipynb
kamzzang/ADPStudy
๊ฐ™์€ ์–ด๊ทผ ๋™์ผํ™”(stemming)
from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer ps_stemmer = PorterStemmer() new_text = 'It is important to be immersed while you are pythoning with python.\ All pythoners have pothoned poorly at least once.' words = word_tokenize(new_text) for w in words: print(ps_stemmer.stem(w), e...
It is important to be immersed while you are ing with .All ers have pothoned poorly at least once .
MIT
[STUDY]ํ…์ŠคํŠธ๋งˆ์ด๋‹_Base.ipynb
kamzzang/ADPStudy
N-gram* n๋ฒˆ ์—ฐ์ด์–ด ๋“ฑ์žฅํ•˜๋Š” ๋‹จ์–ด๋“ค์˜ ์—ฐ์‡„* ๋‘ ๋ฒˆ : ๋ฐ”์ด๊ทธ๋žจ, ์„ธ ๋ฒˆ : ํŠธ๋ผ์ด๊ทธ๋žจ(ํŠธ๋ผ์ด๊ทธ๋žจ ์ด์ƒ์€ ๋ณดํŽธ์ ์œผ๋กœ ํ™œ์šฉํ•˜์ง€ ์•Š์Œ)
from nltk import ngrams sentence = 'Chief Justice Roberts, Preskdent Carter, President Clinton, President Bush, President Obama, \ fellow Americans and people of the world, thank you. We, the citizens of America are now joined in a great \ national effort to rebuild our country and restore its promise for all of our pe...
('Chief', 'Justice') ('Justice', 'Roberts,') ('Roberts,', 'Preskdent') ('Preskdent', 'Carter,') ('Carter,', 'President') ('President', 'Clinton,') ('Clinton,', 'President') ('President', 'Bush,') ('Bush,', 'President') ('President', 'Obama,') ('Obama,', 'fellow') ('fellow', 'Americans') ('Americans', 'and') ('and', 'pe...
MIT
[STUDY]ํ…์ŠคํŠธ๋งˆ์ด๋‹_Base.ipynb
kamzzang/ADPStudy
ํ’ˆ์‚ฌ ๋ถ„์„
from konlpy.tag import Hannanum hannanum = Hannanum() print(hannanum.morphs("์นœ์ฒ™๋“ค์ด ๋ชจ์ธ ์ด๋ฒˆ ์ถ”์„ ์ฐจ๋ก€์ƒ์—์„œ๋Š” ๋‹จ์—ฐ '์ง‘๊ฐ’'์ด ํ™”์ œ์— ์˜ฌ๋ž๋‹ค.")) print(hannanum.nouns("์นœ์ฒ™๋“ค์ด ๋ชจ์ธ ์ด๋ฒˆ ์ถ”์„ ์ฐจ๋ก€์ƒ์—์„œ๋Š” ๋‹จ์—ฐ '์ง‘๊ฐ’'์ด ํ™”์ œ์— ์˜ฌ๋ž๋‹ค.")) print(hannanum.pos("์นœ์ฒ™๋“ค์ด ๋ชจ์ธ ์ด๋ฒˆ ์ถ”์„ ์ฐจ๋ก€์ƒ์—์„œ๋Š” ๋‹จ์—ฐ '์ง‘๊ฐ’'์ด ํ™”์ œ์— ์˜ฌ๋ž๋‹ค.", ntags=9)) from konlpy.tag import Kkma kkma = Kkma() print(kkma.morphs("์นœ์ฒ™...
[('The', 'DT'), ('little', 'JJ'), ('yellow', 'JJ'), ('dog', 'NN'), ('barked', 'VBD'), ('at', 'IN'), ('the', 'DT'), ('Persian', 'NNP'), ('cat.', 'NN')]
MIT
[STUDY]ํ…์ŠคํŠธ๋งˆ์ด๋‹_Base.ipynb
kamzzang/ADPStudy
Location-based algorithm
location_map = list(set(TRAINING_DATA_GRAD["LOCATION"])) location_map.sort() # print(location_map) list_location = [] list_avg_rm = [] list_avg_yield = [] for val in location_map: avg_rm = np.average(TRAINING_DATA_GRAD[EXPERIMENT_DATA["LOCATION"] == str(val)]["RM"]) avg_yield = np.average(TRAINING_DATA_GRAD[EXP...
_____no_output_____
MIT
Average_RM_YIELD_location.ipynb
hmc-cs-nsuaysom/BigDataProject
AnalysisFrom the preliminary analysis, we find that the number of different locateion in the dataset is 140. The location in the dataset is encoded as a 4-digit number. We first expected that we can group the quality of the species based on the location parameters. We then plot the average of __RM__ and __YIELD__ for ...
# Calculate the number of possible locations location_set = set(TRAINING_DATA_GRAD["LOCATION"]) print("The number of possible location is {}.".format(len(location_set))) location_histogram_list = [] for location in sorted(location_set): amount = len(TRAINING_DATA_GRAD[TRAINING_DATA_GRAD["LOCATION"] == str(location...
1.05328277023 1.0262956544 0.762338198505 0.873119807647 0.253807203837 0.503792818366 0.200542622706 0.447819855195 0.29628093697 0.544316945327 0.374676270693 0.612108054753 3.15544362088e-30 1.7763568394e-15
MIT
Average_RM_YIELD_location.ipynb
hmc-cs-nsuaysom/BigDataProject
Test with validation set
# Test with validation set TESTING_DATA_GRAD = TESTING_DATA_GRAD.reset_index(drop=True) Xtest = np.column_stack((TESTING_DATA_GRAD["LOCATION"], TESTING_DATA_GRAD["RM"], TESTING_DATA_GRAD["YIELD"])) ytest = TESTING_DATA_GRAD["BAGSOLD"].astype(np.float) log_ytest = np....
_____no_output_____
MIT
Average_RM_YIELD_location.ipynb
hmc-cs-nsuaysom/BigDataProject
Testing Ridge Reg vs. Linear RegBelow is not used. It's for testing the difference between Ridge Regression and Linear Regression.The result is that the MSE is almsot the same
bagSold = np.log(np.asarray(TRAINING_DATA_GRAD["BAGSOLD"]).reshape(-1, 1).astype(np.float)) rm = np.asarray(TRAINING_DATA_GRAD["RM"]).reshape(-1,1).astype(np.float) yield_val = np.asarray(TRAINING_DATA_GRAD["YIELD"]).reshape(-1,1).astype(np.float) x = np.column_stack((rm, yield_val)) # Liear Regression regr = lin...
Coefficients = [[ 0.0062339 0.00430852]] Intercept = [ 13.11871673] MSE = 0.3483090550422536
MIT
Average_RM_YIELD_location.ipynb
hmc-cs-nsuaysom/BigDataProject
Analyze the range of values from the audio
from scipy.io import wavfile wav_file = "../data/raw/dadosBruno/t02/" + \ "t02_S-ISCA_C1_Aedes female-20-07-2017_1_001_456.wav" wav = wavfile.read(wav_file) # OPTIONAL: Load the "autoreload" extension so that code can change %load_ext autoreload # OPTIONAL: always reload modules so that as you change code ...
_____no_output_____
FTL
notebooks_tcc/0.3-BrunoGomesCoelho-Show-Normalization-Doesnt-Work.ipynb
BrunoGomesCoelho/mosquito-networking
Found existing installation: tables 3.4.4 Unistalling tables-3.4.4: Successfully unistalled tables-3.4.4 Successfully installed tables-3.6.1 import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns cd "/content/drive/My Drive/Colab Notebooks/matrix/matrix_two/dw_matrix_car" df = pd...
_____no_output_____
Apache-2.0
day2_visualisation.ipynb
Kamila86/dw_matrix
็งปๅ‹•ใƒญใƒœใƒƒใƒˆใฎ็Šถๆ…‹้ท็งป๏ผˆใƒŽใ‚คใ‚บใ‚ใ‚Š๏ผ‰ๅƒ่‘‰ๅทฅๆฅญๅคงๅญฆ ไธŠ็”ฐ ้š†ไธ€(c) 2017 Ryuichi UedaThis software is released under the MIT License, see LICENSE. ใฏใ˜ใ‚ใซใ“ใฎใ‚ณใƒผใƒ‰ใฏใ€็งปๅ‹•ใƒญใƒœใƒƒใƒˆใฎ็งปๅ‹•ใฎ็ฐกๅ˜ใชใƒขใƒ‡ใƒซใงใ™ใ€‚
%matplotlib inline import numpy as np import math, random import matplotlib.pyplot as plt # for plotting data
_____no_output_____
MIT
state_equations/with_noise.ipynb
ryuichiueda/probrobo_practice
ใฐใ‚‰ใคใใคใŽใฎใƒซใƒผใƒซใซใ—ใŸใŒใฃใฆใƒญใƒœใƒƒใƒˆใฎ็งปๅ‹•้‡ใซ้›‘้Ÿณใ‚’ๆททๅ…ฅใ—ใฆใฟใ‚‹ใ€‚* ๆŒ‡ไปคๅ€คใ‚’ไธญๅฟƒใซใ€ใ‚ฌใ‚ฆใ‚นๅˆ†ๅธƒใซใ—ใŸใŒใฃใฆๆฌกใฎใ‚ˆใ†ใซใฐใ‚‰ใคใ * ๅ‰้€ฒใ™ใ‚‹ใจใ * ่ท้›ขใŒ่ท้›ขใซๅฏพใ—ใฆ10%ใฎๆจ™ๆบ–ๅๅทฎใงใฐใ‚‰ใคใ * ๅ‘ใใŒๆจ™ๆบ–ๅๅทฎ3[deg]ใงใฐใ‚‰ใคใ * ๅ‘ใใ‚’ๅค‰ใˆใ‚‹ใจใ * ๅค‰ใˆใ‚‹ๅ‘ใใฎ่ง’ๅบฆใซๅฏพใ—ใฆ10%ใฎๆจ™ๆบ–ๅๅทฎใงใฐใ‚‰ใคใ ็Šถๆ…‹ๆ–น็จ‹ๅผใซๅฏพๅฟœใ™ใ‚‹้–ขๆ•ฐไธ‹ใฎไพ‹ใซใคใ„ใฆใ€้–ขๆ•ฐfใ‚’ๆ›ธใใพใ—ใ‚‡ใ†ใ€‚ ```pythonold_x = np.array([0,0,0]) ไปŠๅ›žใฏไธ่ฆใ ใŒnumpyใ‚’ไฝฟ็”จu = np.array([0.1,10/180*math.pi]) ๆฏŽๅ›ž0.1ใ ใ‘้€ฒใ‚ใฆ10[deg]ๅ‘ใใ‚’ๅค‰ใˆใ‚‹def...
def f(x_old,u): # ใ‚ใ‹ใ‚Šใซใใ„ใฎใงใƒใƒฉใ™ pos_x, pos_y, pos_theta = x_old act_fw, act_rot = u act_fw = random.gauss(act_fw,act_fw/10) dir_error = random.gauss(0.0, math.pi / 180.0 * 3.0) act_rot = random.gauss(act_rot,act_rot/10) pos_x += act_fw * math.cos(pos_theta + dir_error) pos_y += a...
_____no_output_____
MIT
state_equations/with_noise.ipynb
ryuichiueda/probrobo_practice
ๅฎŸ่กŒ๏ผ10ใ‚นใƒ†ใƒƒใƒ—ๅ‹•่ฒธใ—ใฆใฟใพใ—ใ‚‡ใ†ใ€‚
x = np.array([0,0,0]) u = np.array([0.1,10/180*math.pi]) # ๆฏŽๅ›ž0.1ใ ใ‘้€ฒใ‚ใฆ10[deg]ๅ‘ใใ‚’ๅค‰ใˆใ‚‹ print(x) for i in range(10): x = f(x,u) print(x)
[0 0 0] [ 0.11101391 0.01316534 0.20062588] [ 0.21667561 0.03772248 0.36210264] [ 0.30714191 0.06797028 0.53692128] [ 0.38194774 0.11808143 0.72018441] [ 0.45733798 0.17144363 0.89551629] [ 0.5062014 0.23616994 1.07167283] [ 0.55316268 0.32808052 1.24928927] [ 0.59204397 0.42298333 1.41256331] [ 0.6106...
MIT
state_equations/with_noise.ipynb
ryuichiueda/probrobo_practice
ใ‚ใ‹ใ‚‰ใ‚“ใฎใงๆ็”ป
x = np.array([0,0,0]) u = np.array([0.1,10/180*math.pi]) # ๆฏŽๅ›ž0.1ใ ใ‘้€ฒใ‚ใฆ10[deg]ๅ‘ใใ‚’ๅค‰ใˆใ‚‹ path = [x] for i in range(10): x = f(x,u) path.append(x) fig = plt.figure(i,figsize=(8, 8)) sp = fig.add_subplot(111, aspect='equal') sp.set_xlim(-1.0,1.0) sp.set_ylim(-0.5,1.5) xs = [e[0] for e in path] ys = [e[1] for...
_____no_output_____
MIT
state_equations/with_noise.ipynb
ryuichiueda/probrobo_practice