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 |
|---|---|---|---|---|---|
Run the Processing Job using Amazon SageMakerNext, use the Amazon SageMaker Python SDK to submit a processing job using our custom python script. Review the Processing Script | !pygmentize preprocess-scikit-text-to-bert-feature-store.py | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Run this script as a processing job. You also need to specify one `ProcessingInput` with the `source` argument of the Amazon S3 bucket and `destination` is where the script reads this data from `/opt/ml/processing/input` (inside the Docker container.) All local paths inside the processing container must begin with `/... | import time
from smexperiments.experiment import Experiment
timestamp = int(time.time())
experiment = Experiment.create(
experiment_name="Amazon-Customer-Reviews-BERT-Experiment-{}".format(timestamp),
description="Amazon Customer Reviews BERT Experiment",
sagemaker_boto_client=sm,
)
experiment_name = exp... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Create the `Trial` | import time
from smexperiments.trial import Trial
timestamp = int(time.time())
trial = Trial.create(
trial_name="trial-{}".format(timestamp), experiment_name=experiment_name, sagemaker_boto_client=sm
)
trial_name = trial.trial_name
print("Trial name: {}".format(trial_name)) | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Create the `Experiment Config` | experiment_config = {
"ExperimentName": experiment_name,
"TrialName": trial_name,
"TrialComponentDisplayName": "prepare",
}
print(experiment_name)
%store experiment_name
print(trial_name)
%store trial_name | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Create Feature Store and Feature Group | featurestore_runtime = boto3.Session().client(service_name="sagemaker-featurestore-runtime", region_name=region)
timestamp = int(time.time())
feature_store_offline_prefix = "reviews-feature-store-" + str(timestamp)
print(feature_store_offline_prefix)
feature_group_name = "reviews-feature-group-" + str(timestamp)
pri... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Set the Processing Job Hyper-Parameters | processing_instance_type = "ml.c5.2xlarge"
processing_instance_count = 2
train_split_percentage = 0.90
validation_split_percentage = 0.05
test_split_percentage = 0.05
balance_dataset = True
max_seq_length = 64 | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Choosing a `max_seq_length` for BERTSince a smaller `max_seq_length` leads to faster training and lower resource utilization, we want to find the smallest review length that captures `80%` of our reviews.Remember our distribution of review lengths from a previous section?```mean 51.683405std 107.030844... | from sagemaker.sklearn.processing import SKLearnProcessor
processor = SKLearnProcessor(
framework_version="0.23-1",
role=role,
instance_type=processing_instance_type,
instance_count=processing_instance_count,
env={"AWS_DEFAULT_REGION": region},
max_runtime_in_seconds=7200,
)
from sagemaker.proc... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Monitor the Processing Job | running_processor = sagemaker.processing.ProcessingJob.from_processing_name(
processing_job_name=scikit_processing_job_name, sagemaker_session=sess
)
processing_job_description = running_processor.describe()
print(processing_job_description)
running_processor.wait(logs=False) | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
_Please Wait Until the ^^ Processing Job ^^ Completes Above._ Inspect the Processed Output DataTake a look at a few rows of the transformed dataset to make sure the processing was successful. | processing_job_description = running_processor.describe()
output_config = processing_job_description["ProcessingOutputConfig"]
for output in output_config["Outputs"]:
if output["OutputName"] == "bert-train":
processed_train_data_s3_uri = output["S3Output"]["S3Uri"]
if output["OutputName"] == "bert-vali... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Pass Variables to the Next Notebook(s) | %store raw_input_data_s3_uri
%store max_seq_length
%store train_split_percentage
%store validation_split_percentage
%store test_split_percentage
%store balance_dataset
%store feature_store_offline_prefix
%store feature_group_name
%store processed_train_data_s3_uri
%store processed_validation_data_s3_uri
%store processe... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Query The Feature Store | feature_store_query = feature_group.athena_query()
feature_store_table = feature_store_query.table_name
query_string = """
SELECT input_ids, input_mask, segment_ids, label_id, split_type FROM "{}" WHERE split_type='train' LIMIT 5
""".format(
feature_store_table
)
print("Running " + query_string)
feature_store_que... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Show the Experiment Tracking Lineage | from sagemaker.analytics import ExperimentAnalytics
import pandas as pd
pd.set_option("max_colwidth", 500)
# pd.set_option("max_rows", 100)
experiment_analytics = ExperimentAnalytics(
sagemaker_session=sess, experiment_name=experiment_name, sort_by="CreationTime", sort_order="Descending"
)
experiment_analytics_... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Show SageMaker ML Lineage Tracking Amazon SageMaker ML Lineage Tracking creates and stores information about the steps of a machine learning (ML) workflow from data preparation to model deployment. Amazon SageMaker Lineage enables events that happen within SageMaker to be traced via a graph structure. The data simplif... | from sagemaker.lineage.visualizer import LineageTableVisualizer
lineage_table_viz = LineageTableVisualizer(sess)
lineage_table_viz_df = lineage_table_viz.show(processing_job_name=scikit_processing_job_name)
lineage_table_viz_df | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Release Resources | %%html
<p><b>Shutting down your kernel for this notebook to release resources.</b></p>
<button class="sm-command-button" data-commandlinker-command="kernelmenu:shutdown" style="display:none;">Shutdown Kernel</button>
<script>
try {
els = document.getElementsByClassName("sm-command-button");
els[0].cli... | _____no_output_____ | Apache-2.0 | 06_prepare/02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb | MarcusFra/workshop |
Midterm Exam PROBLEMSTATEMENT 1 | a="John Angelo A. Dazo"
b="202012935"
c="19 years old"
d="June 09, 2002"
e="Blk 9 Lot 8 Persan Village, Sanja Mayor, Tanza, Cavite"
f="Programming Logic and Design"
g="1.33"
print("Full Name: "+a)
print("Student Number: "+b)
print("Age: "+c)
print("Birthday: "+d)
print("Address: "+e)
print("Course: "+f)
print("Last Se... | Full Name: John Angelo A. Dazo
Student Number: 202012935
Age: 19 years old
Birthday: June 09, 2002
Address: Blk 9 Lot 8 Persan Village, Sanja Mayor, Tanza, Cavite
Course: Programming Logic and Design
Last Sem GWA: 1.33
| Apache-2.0 | Midterm_Exam.ipynb | JohnAngeloDazo/CPEN-21A-ECE-2-1 |
PROBLEMSTATEMENT 2 | n=4
answ="Y"
print(bool(2<n)and(n<6)) #a
print(bool(2<n)or(n==6)) #b
print(bool(not(2<n)or(n==6)))#c
print(bool(not(n<6))) #d
print(bool(answ=="Y")or(answ=="y")) #e
print(bool(answ=="Y")and(answ=="y")) #f
print(bool(not(answ=="y"))) #g
print(bool((2<n)and(n==5+1))or(answ=="No")) #h
print(bool((n==2)and(n==7))or(answ=... | True
True
False
False
True
False
True
False
True
False
| Apache-2.0 | Midterm_Exam.ipynb | JohnAngeloDazo/CPEN-21A-ECE-2-1 |
PROBLEMSTATEMENT 3 | x=2
y=-3
w=7
z=-10
print(x/y) #a
print(w/y/x) #b
print(z/y%x) #c
print(x%-y*w) #d
print(x%y) #e
print(z%w-y/x*5+5) #f
print(9-x%(2+y)) #g
print(z//w) #h
print((2+y)**2) #i
print(w/x*2) #j | -0.6666666666666666
-1.1666666666666667
1.3333333333333335
14
-1
16.5
9
-2
1
7.0
| Apache-2.0 | Midterm_Exam.ipynb | JohnAngeloDazo/CPEN-21A-ECE-2-1 |
Train YOLOv5 on RailSem19This notebook is based on the [YOLOv5 tutorial](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb). This notebook is designed to run in Google Colab.--- SetupClone YOLOv5, install dependencies and check PyTorch and GPU: | !git clone https://github.com/ultralytics/yolov5 # clone
%cd yolov5
%pip install -qr requirements.txt # install
from yolov5 import utils
display = utils.notebook_init() # checks
%cd ../
!git clone https://github.com/Denbergvanthijs/railsem19_yolov5.git | _____no_output_____ | Apache-2.0 | train_rs19.ipynb | Denbergvanthijs/railsem19_yolov5 |
Load Tensorboard and Weights & Biases (both optional): | # Tensorboard (optional)
# %load_ext tensorboard
# %tensorboard --logdir runs/train
# Weights & Biases (optional)
%pip install -q wandb
import wandb
wandb.login() | _____no_output_____ | Apache-2.0 | train_rs19.ipynb | Denbergvanthijs/railsem19_yolov5 |
Mount personal Google Drive: | from google.colab import drive
drive.mount('/content/drive') | _____no_output_____ | Apache-2.0 | train_rs19.ipynb | Denbergvanthijs/railsem19_yolov5 |
Copy training data from Google Drive to local disk: | !mkdir data
!cp ./drive/MyDrive/rs19_person_semseg ./data/rs19_person_semseg -r | _____no_output_____ | Apache-2.0 | train_rs19.ipynb | Denbergvanthijs/railsem19_yolov5 |
TrainingTo train a model with the hyperparameters used in the research paper: | !python ./yolov5/train.py --batch-size 64 --epochs 50 --data ./railsem19_yolov5/data/rs19_person_semseg.yaml --weights yolov5s.pt --single-cls --cache --hyp ./railsem19_yolov5/data/hyp_evolve.yaml | _____no_output_____ | Apache-2.0 | train_rs19.ipynb | Denbergvanthijs/railsem19_yolov5 |
Hyperparameter optimalisationThe following will start the hyperparameter optimalisation: | !python ./yolov5/train.py --batch-size 64 --epochs 10 --data ./railsem19_yolov5/data/rs19_person_semseg.yaml --weights yolov5s.pt --single-cls --cache --evolve 40 --hyp "./railsem19_yolov5/data/hyp_evolve.yaml" | _____no_output_____ | Apache-2.0 | train_rs19.ipynb | Denbergvanthijs/railsem19_yolov5 |
Importing and Setuping Up Dataset | df = pd.read_csv('all_games.csv', low_memory=False)
df.head()
# Remove uncalibrated games
df = df[df['White Rating'] != '?']
df = df[df['Black Rating'] != '?']
df = df.astype({
'White Rating': int,
'Black Rating': int,
})
df['Rating Diff'] = abs(df['White Rating'] - df['Black Rating'])
df['Avg Rating'] = (df['W... | _____no_output_____ | MIT | jordan_analysis.ipynb | kdesai2018/DSL-final-project |
Rating Analysis | Rating_Ranges = [1200, 1400, 1600, 1800, 2000, 2200]
rating = df['White Rating'].append(df['Black Rating'], ignore_index=True)
bins = [rating.min()] + Rating_Ranges + [rating.max()]
display(rating.value_counts(bins=bins, sort=False))
rating.hist(bins=bins)
display(df['Rating Diff'].value_counts(bins=20, sort=False))
df... | _____no_output_____ | MIT | jordan_analysis.ipynb | kdesai2018/DSL-final-project |
Opening Analysis | def opening_prune(op):
split = re.split('[:#,]', op)
return split[0].rstrip()
df['Opening Short'] = df['Opening'].apply(opening_prune)
df['Opening Short'].value_counts(normalize=True)
counts = df['Opening Short'].value_counts()
percentage = df['Opening Short'].value_counts(normalize=True).mul(100)
open_stats = ... | Popular Openings in Rated Blitz game
| MIT | jordan_analysis.ipynb | kdesai2018/DSL-final-project |
Rating Breakdown | Rating_Ranges = [1500, 2200, 2200]
df_novice = df[df['Avg Rating'] < 1500]
df_n = pd.DataFrame(df_novice['Opening Short'].value_counts(normalize=True)).reset_index()
df_n[df_n['index'] == 'Scandinavian Defense']
#df_n.loc('Scandinavian Defense')
df_master = df[df['Avg Rating'] > 2200]
df_m = pd.DataFrame(df_master['Ope... | Popular Openings in Rating Range: 0 - 1200
| MIT | jordan_analysis.ipynb | kdesai2018/DSL-final-project |
Effectiveness of Top Openings in Top Level Play | df_top = df[(df['Avg Rating'] > 2500)]
counts = df_top['Opening Short'].value_counts()
percentage = df_top['Opening Short'].value_counts(normalize=True).mul(100)
top_stats = pd.DataFrame({'counts': counts, 'percentage':percentage})
display(top_stats.head(5))
openings = ['Sicilian Defense', 'French Defense', 'English Op... | _____no_output_____ | MIT | jordan_analysis.ipynb | kdesai2018/DSL-final-project |
prepared by Abuzer Yakaryilmaz This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. $ \newcommand{\bra}[1]{\langle 1|} $$ \newcommand{\ket}[1]{|1\rangle} $$ \newcomman... | # let's define both vectors
u = [-3,-2,0,-1,4]
v = [-1,-1,2,-3,5]
uv = 0; # summation is initially zero
for i in range(len(u)): # iteratively access every pair with the same indices
print("pairwise multiplication of the entries with index",i,"is",u[i]*v[i])
uv = uv + u[i]*v[i] # i-th entries are multiplied an... | _____no_output_____ | MIT | math/Math24_Dot_Product.ipynb | HasanIjaz-HB/Quantum-Computing |
The pairwise multiplications of entries are $ (-3)\cdot(-1) = 3 $, $ (-2)\cdot(-1) = 2 $, $ 0\cdot 2 = 0 $, $ (-1)\cdot(-3) = 3 $, and, $ 4 \cdot 5 = 20 $. Thus the summation of all pairwise multiplications of entries is $ 3+2+0+3+20 = 28 $.Remark that the dimensions of the given vectors must b... | #
# your solution is here
#
| _____no_output_____ | MIT | math/Math24_Dot_Product.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Task 2 Let $ u = \myrvector{ -3 \\ -4 } $ be a 2 dimensional vector.Find $ \dot{u}{u} $ in Python. | #
# your solution is here
#
| _____no_output_____ | MIT | math/Math24_Dot_Product.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Notes:As may be observed from Task 2, the length of a vector can be calculated by using its dot product with itself.$$ \norm{u} = \sqrt{\dot{u}{u}}. $$$ \dot{u}{u} $ is $25$, and so $ \norm{u} = \sqrt{25} = 5 $. $ \dot{u}{u} $ automatically accumulates the contribution of each entry to the lengt... | # let's find the dot product of v and u
v = [-4,0]
u = [0,-5]
result = 0;
for i in range(2):
result = result + v[i]*u[i]
print("the dot product of u and v is",result) | _____no_output_____ | MIT | math/Math24_Dot_Product.ipynb | HasanIjaz-HB/Quantum-Computing |
Now, let's check the dot product of the following two vectors: | # we can use the same code
v = [-4,3]
u = [-3,-4]
result = 0;
for i in range(2):
result = result + v[i]*u[i]
print("the dot product of u and v is",result) | _____no_output_____ | MIT | math/Math24_Dot_Product.ipynb | HasanIjaz-HB/Quantum-Computing |
The dot product of new $ u $ and $ v $ is also $0$. This is not surprising, because the vectors $u$ and $v$ (in both cases) are orthogonal to each other.Fact: The dot product of two orthogonal (perpendicular) vectors is zero. If the dot product of two vectors is zero, then they are orthogonal to each other. This... | # you may consider to write a function in Python for dot product
#
# your solution is here
#
| _____no_output_____ | MIT | math/Math24_Dot_Product.ipynb | HasanIjaz-HB/Quantum-Computing |
click for our solution Task 4 Find the dot product of $ v $ and $ u $ in Python.$$ v = \myrvector{-1 \\ 2 \\ -3 \\ 4} ~~~~\mbox{and}~~~~ u = \myrvector{-2 \\ -1 \\ 5 \\ 2}.$$Find the dot product of $ -2v $ and $ 3u $ in Python.Compare both results. | #
# your solution is here
#
| _____no_output_____ | MIT | math/Math24_Dot_Product.ipynb | HasanIjaz-HB/Quantum-Computing |
Multi step model (simple encoder-decoder)In this notebook, we demonstrate how to:- prepare time series data for training a RNN forecasting model- get data in the required shape for the keras API- implement a RNN model in keras to predict the next 3 steps ahead (time *t+1* to *t+3*) in the time series. This model uses ... | import os
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
from collections import UserDict
from IPython.display import Image
%matplotlib inline
from common.utils import load_data, mape, TimeSeriesTensor, create_evaluation_df
pd.options.display.float_format ... | _____no_output_____ | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
Load data into Pandas dataframe | energy = load_data('data/')
energy.head()
valid_start_dt = '2014-09-01 00:00:00'
test_start_dt = '2014-11-01 00:00:00'
T = 6
HORIZON = 3 | _____no_output_____ | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
Create training set containing only the model features | train = energy.copy()[energy.index < valid_start_dt][['load', 'temp']] | _____no_output_____ | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
Scale data to be in range (0, 1). This transformation should be calibrated on the training set only. This is to prevent information from the validation or test sets leaking into the training data. | from sklearn.preprocessing import MinMaxScaler
y_scaler = MinMaxScaler()
y_scaler.fit(train[['load']])
X_scaler = MinMaxScaler()
train[['load', 'temp']] = X_scaler.fit_transform(train) | _____no_output_____ | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
Use the TimeSeriesTensor convenience class to:1. Shift the values of the time series to create a Pandas dataframe containing all the data for a single training example2. Discard any samples with missing values3. Transform this Pandas dataframe into a numpy array of shape (samples, time steps, features) for input into K... | tensor_structure = {'X':(range(-T+1, 1), ['load', 'temp'])}
train_inputs = TimeSeriesTensor(train, 'load', HORIZON, {'X':(range(-T+1, 1), ['load', 'temp'])})
train_inputs.dataframe.head() | _____no_output_____ | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
Construct validation set (keeping T hours from the training set in order to construct initial features) | look_back_dt = dt.datetime.strptime(valid_start_dt, '%Y-%m-%d %H:%M:%S') - dt.timedelta(hours=T-1)
valid = energy.copy()[(energy.index >=look_back_dt) & (energy.index < test_start_dt)][['load', 'temp']]
valid[['load', 'temp']] = X_scaler.transform(valid)
valid_inputs = TimeSeriesTensor(valid, 'load', HORIZON, tensor_st... | _____no_output_____ | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
Implement the RNN We will implement a RNN forecasting model with the following structure: | Image('./images/simple_encoder_decoder.png')
from keras.models import Model, Sequential
from keras.layers import GRU, Dense, RepeatVector, TimeDistributed, Flatten
from keras.callbacks import EarlyStopping
LATENT_DIM = 5
BATCH_SIZE = 32
EPOCHS = 10
model = Sequential()
model.add(GRU(LATENT_DIM, input_shape=(T, 2)))
mod... | Train on 23368 samples, validate on 1461 samples
Epoch 1/50
23368/23368 [==============================] - 4s 185us/step - loss: 0.0217 - val_loss: 0.0053
Epoch 2/50
23368/23368 [==============================] - 3s 129us/step - loss: 0.0050 - val_loss: 0.0042
Epoch 3/50
23368/23368 [==============================] - 3... | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
Evaluate the model | look_back_dt = dt.datetime.strptime(test_start_dt, '%Y-%m-%d %H:%M:%S') - dt.timedelta(hours=T-1)
test = energy.copy()[test_start_dt:][['load', 'temp']]
test[['load', 'temp']] = X_scaler.transform(test)
test_inputs = TimeSeriesTensor(test, 'load', HORIZON, tensor_structure)
predictions = model.predict(test_inputs['X'])... | _____no_output_____ | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
Plot actuals vs predictions at each horizon for first week of the test period. As is to be expected, predictions for one step ahead (*t+1*) are more accurate than those for 2 or 3 steps ahead | plot_df = eval_df[(eval_df.timestamp<'2014-11-08') & (eval_df.h=='t+1')][['timestamp', 'actual']]
for t in range(1, HORIZON+1):
plot_df['t+'+str(t)] = eval_df[(eval_df.timestamp<'2014-11-08') & (eval_df.h=='t+'+str(t))]['prediction'].values
fig = plt.figure(figsize=(15, 8))
ax = plt.plot(plot_df['timestamp'], plot... | _____no_output_____ | MIT | 3_RNN_encoder_decoder.ipynb | YangLIN1997/DeepLearningForTimeSeriesForecasting |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.stats import norm
from sklearn.preprocessing import StandardScaler
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
df=pd.read_csv('/content/drive/MyDrive/DataSet_Main/Hous... | _____no_output_____ | MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML | |
Analysis Sales Price | # Descriptive statistics summary
df['SalePrice'].describe() | _____no_output_____ | MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML |
- If mean and median are same in the dataset meansthere is no outliers | # Histogram
sns.distplot(df['SalePrice']) | _____no_output_____ | MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML |
- Normarl Distribution | # Skewness an d kurtosis
print('Skewness: %f' % df['SalePrice'].skew())
print('Kurtosis: %f' % df['SalePrice'].skew()) | Skewness: 1.882876
Kurtosis: 1.882876
| MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML |
- If skewness is zero means dataset has no skewed point- It ranges from 0 to 10 Relationships | # Scatter plot grlivarea/saleprice
var='GrLivArea'
data=pd.concat([df['SalePrice'],df[var]],axis=1) #another way of making dataframe
data.plot.scatter(x=var,y='SalePrice',ylim=(0,800000)) | _____no_output_____ | MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML |
- For removing Outliers - If value is greater than 4000 then remove row | # Scatter plot totalbsmtsf/saleprice
var='TotalBsmtSF'
data=pd.concat([df['SalePrice'],df[var]],axis=1)
data.plot.scatter(x=var,y='SalePrice',ylim=(0,800000)) | _____no_output_____ | MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML |
Relationship with categorical variables | # Box plot overallqual/saleprice
var='OverallQual'
data=pd.concat([df['SalePrice'],df[var]],axis=1)
f,ax=plt.subplots(figsize=(10,6))
fig=sns.boxplot(x=var,y='SalePrice',data=data)
fig.axis(ymin=0,ymax=800000);
var='YearBuilt'
data=pd.concat([df['SalePrice'],df[var]],axis=1)
f,ax=plt.subplots(figsize=(16,8))
fig=sns.bo... | _____no_output_____ | MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML |
- The Dataset which is not able to visualize correctly alternate method is use tableau and powerBI for better and clear illustration Correlation | # Correlation Matrix
corrmat=df.corr()
f,ax=plt.subplots(figsize=(12,9))
sns.heatmap(corrmat,vmax=.8,square=True);
# SalePrice correlation matrix
k=10 # number of variables for heatmap
cols=corrmat.nlargest(k,'SalePrice')['SalePrice'].index
cm=np.corrcoef(df[cols].values.T)
sns.set(font_scale=0.6)
hm=sns.heatmap(cm,cb... | _____no_output_____ | MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML |
Missing Value | # missing data
total=df.isnull().sum().sort_values(ascending=False)
percent=(df.isnull().sum()/df.isnull().count()).sort_values(ascending=False)
missing_data=pd.concat([total,percent],axis=1,keys=['Total','Percent'])
missing_data.head(20) | _____no_output_____ | MIT | EDA_techniques.ipynb | capitallatera/Stat-and-ML |
ะะฝะดะธะฒะธะดัะฐะปัะฝะพะต ะทะฐะดะฐะฝะธะต | import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
import numpy as np
x = np.linspace(0, 5, 50)
y1 = 3*x
y2 = [i/0.10 for i in x]
fig, ax = plt.subplots(figsize=(15, 9))
ax.set_title("ะัะฐัะธะบ ะฒะตัะพััะฝะพััะธ ะฟะพะปััะตะฝะธั ะทะฐัะตัะฐ ะฟะพ ะบัะพััะฟะปะฐััะพัะผะตะฝะฝะพะผั ะฟัะพะณัะฐะผ... | _____no_output_____ | MIT | ind.ipynb | djamaludinn/cp4 |
Sentiment Analysis with an RNNIn this notebook, you'll implement a recurrent neural network that performs sentiment analysis. >Using an RNN rather than a strictly feedforward network is more accurate since we can include information about the *sequence* of words. Here we'll use a dataset of movie reviews, accompanied ... | from google.colab import files
# Upload reviews.txt and labels.txt to google colab
uploaded = files.upload()
import numpy as np
# read data from text files
with open('reviews.txt', 'r') as f:
reviews = f.read()
with open('labels.txt', 'r') as f:
labels = f.read()
print(reviews[:2000])
print()
print(labels[:20... | bromwell high is a cartoon comedy . it ran at the same time as some other programs about school life such as teachers . my years in the teaching profession lead me to believe that bromwell high s satire is much closer to reality than is teachers . the scramble to survive financially the insightful students who... | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Data pre-processingThe first step when building a neural network model is getting your data into the proper form to feed into the network. Since we're using embedding layers, we'll need to encode each word with an integer. We'll also want to clean it up a bit.You can see an example of the reviews data above. Here are ... | from string import punctuation
print(punctuation)
# get rid of punctuation
reviews = reviews.lower() # lowercase, standardize
all_text = ''.join([c for c in reviews if c not in punctuation])
# split by new lines and spaces
reviews_split = all_text.split('\n')
all_text = ' '.join(reviews_split)
# create a list of wor... | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Encoding the wordsThe embedding lookup requires that we pass in integers to our network. The easiest way to do this is to create dictionaries that map the words in the vocabulary to integers. Then we can convert each of our reviews into integers so they can be passed into the network.> **Exercise:** Now you're going t... | # feel free to use this import
from collections import Counter
## Build a dictionary that maps words to integers
words_counts = Counter(words)
vocab = sorted(words_counts, key=words_counts.get, reverse=True)
vocab_to_int = {word:ii for ii, word in enumerate(vocab, 1)}
## use the dict to tokenize each review in revie... | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
**Test your code**As a text that you've implemented the dictionary correctly, print out the number of unique words in your vocabulary and the contents of the first, tokenized review. | # stats about vocabulary
print('Unique words: ', len((vocab_to_int))) # should ~ 74000+
print()
# print tokens in first review
print('Tokenized review: \n', reviews_ints[:1]) | Unique words: 74072
Tokenized review:
[[21025, 308, 6, 3, 1050, 207, 8, 2138, 32, 1, 171, 57, 15, 49, 81, 5785, 44, 382, 110, 140, 15, 5194, 60, 154, 9, 1, 4975, 5852, 475, 71, 5, 260, 12, 21025, 308, 13, 1978, 6, 74, 2395, 5, 613, 73, 6, 5194, 1, 24103, 5, 1983, 10166, 1, 5786, 1499, 36, 51, 66, 204, 145, 67, 1199... | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Encoding the labelsOur labels are "positive" or "negative". To use these labels in our network, we need to convert them to 0 and 1.> **Exercise:** Convert labels from `positive` and `negative` to 1 and 0, respectively, and place those in a new list, `encoded_labels`. | # 1=positive, 0=negative label conversion
encoded_labels = np.array([1 if label=="positive" else 0 for label in labels.split('\n')]) | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Removing OutliersAs an additional pre-processing step, we want to make sure that our reviews are in good shape for standard processing. That is, our network will expect a standard input text size, and so, we'll want to shape our reviews into a specific length. We'll approach this task in two main steps:1. Getting rid ... | # outlier review stats
review_lens = Counter([len(x) for x in reviews_ints])
print("Zero-length reviews: {}".format(review_lens[0]))
print("Maximum review length: {}".format(max(review_lens))) | Zero-length reviews: 1
Maximum review length: 2514
| MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Okay, a couple issues here. We seem to have one review with zero length. And, the maximum review length is way too many steps for our RNN. We'll have to remove any super short reviews and truncate super long reviews. This removes outliers and should allow our model to train more efficiently.> **Exercise:** First, remov... | print('Number of reviews before removing outliers: ', len(reviews_ints))
## remove any reviews/labels with zero length from the reviews_ints list.
review_zero_lenght = [ii for ii in range(len(reviews_ints)) if len(reviews_ints[ii]) <= 1]
reviews_ints = [reviews_ints[ii] for ii in range(len(reviews_ints)) if ii not in... | Number of reviews before removing outliers: 25001
Number of reviews after removing outliers: 25000
| MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
--- Padding sequencesTo deal with both short and very long reviews, we'll pad or truncate all our reviews to a specific length. For reviews shorter than some `seq_length`, we'll pad with 0s. For reviews longer than `seq_length`, we can truncate them to the first `seq_length` words. A good `seq_length`, in this case, is... | def pad_features(reviews_ints, seq_length):
''' Return features of review_ints, where each review is padded with 0's
or truncated to the input seq_length.
'''
## implement function
features = np.zeros((len(reviews_ints), seq_length), dtype=int)
for ii, review in enumerate(reviews_... | [[ 0 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0 0]
[22382 42 46418 15 706 17139 3389 47 77 35]
[ 4505 505 15 3 3342 162 8312 1652 6 4819]
[ 0 0 0 0 0 0 0 0 0 0]
[ ... | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Training, Validation, TestWith our data in nice shape, we'll split it into training, validation, and test sets.> **Exercise:** Create the training, validation, and test sets. * You'll need to create sets for the features and the labels, `train_x` and `train_y`, for example. * Define a split fraction, `split_frac` as t... | split_frac = 0.8
encoded_labels = np.array(encoded_labels)
## split data into training, validation, and test data (features and labels, x and y)
split_idx = int(len(features)*0.8)
train_x, remaining_x = features[:split_idx], features[split_idx:]
train_y, remaining_y = encoded_labels[:split_idx], encoded_labels[split_... | Feature Shapes: Labels Shapes:
Train set: (20000, 200) (20000,)
Validation set: (2500, 200) (2500,)
Test set: (2500, 200) (2500,)
| MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
**Check your work**With train, validation, and test fractions equal to 0.8, 0.1, 0.1, respectively, the final, feature data shapes should look like:``` Feature Shapes:Train set: (20000, 200) Validation set: (2500, 200) Test set: (2500, 200)``` --- DataLoaders and BatchingAfter creating traini... | import torch
from torch.utils.data import TensorDataset, DataLoader
# create Tensor datasets
train_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))
valid_data = TensorDataset(torch.from_numpy(val_x), torch.from_numpy(val_y))
test_data = TensorDataset(torch.from_numpy(test_x), torch.from_numpy... | Sample input size: torch.Size([50, 200])
Sample input:
tensor([[ 1, 224, 2, ..., 8522, 10, 1514],
[ 32, 48, 210, ..., 174, 57, 1],
[ 0, 0, 0, ..., 11, 233, 580],
...,
[ 0, 0, 0, ..., 5, 41, 798],
[ 1, 78, 36, ..., 59, 92... | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
--- Sentiment Network with PyTorchBelow is where you'll define the network.The layers are as follows:1. An [embedding layer](https://pytorch.org/docs/stable/nn.htmlembedding) that converts our word tokens (integers) into embeddings of a specific size.2. An [LSTM layer](https://pytorch.org/docs/stable/nn.htmllstm) defin... | # First checking if GPU is available
train_on_gpu=torch.cuda.is_available()
if(train_on_gpu):
print('Training on GPU.')
else:
print('No GPU available, training on CPU.')
import torch.nn as nn
class SentimentRNN(nn.Module):
"""
The RNN model that will be used to perform Sentiment analysis.
"""
... | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Instantiate the networkHere, we'll instantiate the network. First up, defining the hyperparameters.* `vocab_size`: Size of our vocabulary or the range of values for our input, word tokens.* `output_size`: Size of our desired output; the number of class scores we want to output (pos/neg).* `embedding_dim`: Number of co... | # Instantiate the model w/ hyperparams
vocab_size = len(vocab_to_int)+1 # +1 for the 0 padding + our word tokens
output_size = 1
embedding_dim = 400
hidden_dim = 256
n_layers = 2
net = SentimentRNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers)
print(net) | SentimentRNN(
(embedding): Embedding(74073, 400)
(lstm): LSTM(400, 256, num_layers=2, batch_first=True, dropout=0.5)
(dropout): Dropout(p=0.5)
(fc): Linear(in_features=256, out_features=1, bias=True)
(sigmoid): Sigmoid()
)
| MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
--- TrainingBelow is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. You can also add code to save a model by name.>We'll also be using a new kind of cross entropy loss, which is designed to work with a single Sigmoid output. [BCELoss](https://pyt... | # loss and optimization functions
lr=0.001
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(net.parameters(), lr=lr)
# training params
epochs = 4 # 3-4 is approx where I noticed the validation loss stop decreasing
counter = 0
print_every = 100
clip=5 # gradient clipping
# move model to GPU, if available
if(tra... | Epoch: 1/4... Step: 100... Loss: 0.635234... Val Loss: 0.656715
Epoch: 1/4... Step: 200... Loss: 0.666213... Val Loss: 0.640142
Epoch: 1/4... Step: 300... Loss: 0.506314... Val Loss: 0.556882
Epoch: 1/4... Step: 400... Loss: 0.515226... Val Loss: 0.541775
Epoch: 2/4... Step: 500... Loss: 0.481418... Val Loss: 0.488891
... | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
--- TestingThere are a few ways to test your network.* **Test data performance:** First, we'll see how our trained model performs on all of our defined test_data, above. We'll calculate the average loss and accuracy over the test data.* **Inference on user-generated data:** Second, we'll see if we can input just one ex... | # Get test data loss and accuracy
test_losses = [] # track loss
num_correct = 0
# init hidden state
h = net.init_hidden(batch_size)
net.eval()
# iterate over test data
for inputs, labels in test_loader:
# Creating new variables for the hidden state, otherwise
# we'd backprop through the entire training hist... | Test loss: 0.525
Test accuracy: 0.811
| MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Inference on a test reviewYou can change this test_review to any text that you want. Read it and think: is it pos or neg? Then see if your model predicts correctly! > **Exercise:** Write a `predict` function that takes in a trained net, a plain text_review, and a sequence length, and prints out a custom statement f... | def predict(net, test_review, seq_length=200):
''' Prints out whether a give review is predicted to be
positive or negative in sentiment, using a trained model.
params:
net - A trained net
test_review - a review made of normal text and punctuation
seq_length - the ... | Prediction value, pre-rounding: 0.993000
Positive review detected!
Prediction value, pre-rounding: 0.005079
Negative review detected.
| MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge |
Try out test_reviews of your own!Now that you have a trained model and a predict function, you can pass in _any_ kind of text and this model will predict whether the text has a positive or negative sentiment. Push this model to its limits and try to find what words it associates with positive or negative.Later, you'll... | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge | |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from google.colab import files
uploaded_files = files.upload()
#reading the file
census = pd.read_excel('2county2019.xlsx')
census.head(5)
#fixing the names
census['CTYNAME']=census['CTYNAME'].str.replace('County', '')
census['CTYNAME']=census['CTYN... | _____no_output_____ | CC-BY-3.0 | Census_Data.ipynb | ertomz/h4bl-superfund-website | |
Notebook for importing twitter data for hurricane sandy.The twitter dataset is from mdredze. | %matplotlib inline
import sys
import os
sys.path.append(os.path.abspath('../'))
import pandas as pd
import pymongo
import twitterinfrastructure.twitter_sandy as ts
import importlib
importlib.reload(ts)
#os.chdir('../')
print(os.getcwd()) | C:\dev\research\socialsensing\notebooks
| BSD-2-Clause | notebooks/twitter-import.ipynb | jacob-heglund/socialsensing-jh |
Hydrate tweet IDs into tweets using Hydrator.1. Run the following cell to convert the raw mdredze sandy tweet ids file into an interim file of tweet ids in the format necessary to hydrate using Hydrator.1. Use [Hydrator](https://github.com/DocNow/hydrator) to hydrate the "data/interim/sandy-tweetids.txt" file. Hydrati... | # create interim file with only tweet ids for hydration using Hydrator
# (6,554,744 tweet ids, 124.5 MB)
# takes ~1 min (3.1 GHz Intel Core i7, 16 GB 1867 MHz DDR3)
path = "data/raw/release-mdredze.txt"
write_path = "data/interim/sandy-tweetids.txt"
num_tweets = ts.create_hydrator_tweetids(path=path, write_path=write_... | 2019-05-02 13:30:54 : Started converting tweet ids from data/raw/release-mdredze.txt to Hydrator format.
| BSD-2-Clause | notebooks/twitter-import.ipynb | jacob-heglund/socialsensing-jh |
Import hydrated tweets into mongodb database. | # import tweets (4799665 tweets out of 4799665 lines, 12.2 GB total doc size)
# takes ~ 40 mins (3.1 GHz Intel Core i7, 16 GB 1867 MHz DDR3)
# path = 'data/processed/sandy-tweets-20180314.json'
path = 'E:/Work/projects/twitterinfrastructure/data/processed/sandy-tweets-20180314.json'
collection = 'tweets'
db_name = 'san... | 2019-05-02 13:18:14 : Started inserting tweets from "E:/Work/projects/twitterinfrastructure/data/processed/sandy-tweets-20180314.json" to tweets collection in sandy database.
2019-05-02 13:18:14 : Dropped tweets collection (if exists).
| BSD-2-Clause | notebooks/twitter-import.ipynb | jacob-heglund/socialsensing-jh |
Import taxi_zones GeoJSON into mongodb database.1. Open terminal.1. Change to the twitterinfrastructure project home directory. For example, run the following (based on my directory structure): $ cd Documents/projects/twitterinfrastructure1. Use mongoimport to import the taxi_zones_crs4326_mod.geojson into the databas... | # create geosphere index in taxi_zones collection
db_instance = 'mongodb://localhost:27017/'
db_name = 'sandy'
zones_collection = 'taxi_zones'
#db_name = 'sandy_test'
#zones_collection = 'taxi_zones_test'
client = pymongo.MongoClient(db_instance)
db = client[db_name]
db[zones_collection].create_index([("geometry", pymo... | 263 taxi zones found in imported taxi_zones GeoJSON file.
| BSD-2-Clause | notebooks/twitter-import.ipynb | jacob-heglund/socialsensing-jh |
Import nyiso_zones GeoJSON into mongodb database.1. Open terminal.1. Change to the twitterinfrastructure project home directory. For example, run the following (based on my directory structure): $ cd Documents/projects/twitterinfrastructure1. Use mongoimport to import the 'nyiso-zones-crs4326-mod.geojson' file into th... | # create geosphere index in nyiso_zones collection
db_instance = 'mongodb://localhost:27017/'
db_name = 'sandy'
zones_collection = 'nyiso_zones'
client = pymongo.MongoClient(db_instance)
db = client[db_name]
db[zones_collection].create_index([("geometry", pymongo.GEOSPHERE)])
zones = db[zones_collection].find()
print('... | 11 nyiso zones found in imported nyiso_zones GeoJSON file.
| BSD-2-Clause | notebooks/twitter-import.ipynb | jacob-heglund/socialsensing-jh |
Define a Convolutional Neural NetworkCopy the neural network from the Neural Networks section before and modify it to take 3-channel images (instead of 1-channel images as it was defined). | import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self... | _____no_output_____ | Apache-2.0 | DeepLearning/pytorch/cifar10_tutorial.ipynb | MikoyChinese/learn |
Define a Loss function and optimizerLet's use a Classification Cross-Entropy loss and SGD with momentum. | import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=1e-3, momentum=0.9) | _____no_output_____ | Apache-2.0 | DeepLearning/pytorch/cifar10_tutorial.ipynb | MikoyChinese/learn |
Train the networkThis is when things start to get interesting. We simply have to loop over our data iterator, and feed the inputs to the network and optimize. | for epoch in range(2): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is list of [inputs, labels]
inputs, labels = data
# zero the parameters gradients
optimizer.zero_grad()
... | _____no_output_____ | Apache-2.0 | DeepLearning/pytorch/cifar10_tutorial.ipynb | MikoyChinese/learn |
Test the network on the test dataWe have trained the network for 2 passes over the training dataset. But we need to check if the network has learnt anything at all.We will check this by predicting the class label that the neural network outputs, and checking it against the ground-truth. If the prediction is correct, w... | dataiter = iter(testloader)
images, labels = dataiter.next()
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
# Load pre-train model
net = Net()
net.load_state_dict(torch.load(PATH))
outputs = net(images)
_, predicted = torch.ma... | Accuracy of plane : 56 %
Accuracy of car : 57 %
Accuracy of bird : 40 %
Accuracy of cat : 55 %
Accuracy of deer : 45 %
Accuracy of dog : 24 %
Accuracy of frog : 51 %
Accuracy of horse : 60 %
Accuracy of ship : 73 %
Accuracy of truck : 69 %
| Apache-2.0 | DeepLearning/pytorch/cifar10_tutorial.ipynb | MikoyChinese/learn |
Training on GPUJust like how you transfer a Tensor onto the GPU, you transfer the neural net onto the GPU.Letโs first define our device as the first visible cuda device if we have CUDA available: | device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Assuming that we are on a CUDA machine, this should print a CUDA device:
print(device)
correct = 0
total = 0
net.to(device)
with torch.no_grad():
for data in testloader:
images, labels = data[0].to(device), data[1].to(device)
... | Accuracy of the network on the 10000 test images: 53 %
| Apache-2.0 | DeepLearning/pytorch/cifar10_tutorial.ipynb | MikoyChinese/learn |
Copyright 2019 The TensorFlow Authors.Licensed under the Apache License, Version 2.0 (the "License"); | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n |
FGSM์ ์ด์ฉํ ์ ๋์ ์ํ ์์ฑ TensorFlow.org์์ ๋ณด๊ธฐ ๊ตฌ๊ธ ์ฝ๋ฉ(Colab)์์ ์คํํ๊ธฐ ๊นํ๋ธ(GitHub) ์์ค ๋ณด๊ธฐ Download notebook Note: ์ด ๋ฌธ์๋ ํ
์ํ๋ก ์ปค๋ฎค๋ํฐ์์ ๋ฒ์ญํ์ต๋๋ค. ์ปค๋ฎค๋ํฐ ๋ฒ์ญ ํ๋์ ํน์ฑ์ ์ ํํ ๋ฒ์ญ๊ณผ ์ต์ ๋ด์ฉ์ ๋ฐ์ํ๊ธฐ ์ํด ๋
ธ๋ ฅํจ์๋๋ถ๊ตฌํ๊ณ [๊ณต์ ์๋ฌธ ๋ฌธ์](https://www.tensorflow.org/?hl=en)์ ๋ด์ฉ๊ณผ ์ผ์นํ์ง ์์ ์ ์์ต๋๋ค.์ด ๋ฒ์ญ์ ๊ฐ์ ํ ๋ถ๋ถ์ด ์๋ค๋ฉด[tensorflow/docs-l10n](https://... | import tensorflow as tf
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['figure.figsize'] = (8, 8)
mpl.rcParams['axes.grid'] = False | _____no_output_____ | Apache-2.0 | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n |
์ฌ์ ํ๋ จ๋ MobileNetV2 ๋ชจ๋ธ๊ณผ ImageNet์ ํด๋์ค(class) ์ด๋ฆ๋ค์ ๋ถ๋ฌ์ต๋๋ค. | pretrained_model = tf.keras.applications.MobileNetV2(include_top=True,
weights='imagenet')
pretrained_model.trainable = False
# ImageNet ํด๋์ค ๋ ์ด๋ธ
decode_predictions = tf.keras.applications.mobilenet_v2.decode_predictions
# ์ด๋ฏธ์ง๊ฐ MobileNetV2์ ์ ๋ฌ๋ ์ ์๋๋ก ์ ์ฒ๋ฆฌํด์ฃผ๋ ํฌํผ ๋ฉ์๋(he... | _____no_output_____ | Apache-2.0 | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n |
์๋ณธ ์ด๋ฏธ์งMirko [CC-BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/)์ [๋๋ธ๋ผ๋ ๋ฆฌํธ๋ฆฌ๋ฒ](https://commons.wikimedia.org/wiki/File:YellowLabradorLooking_new.jpg) ์ํ ์ด๋ฏธ์ง๋ฅผ ์ด์ฉํด ์ ๋์ ์ํ์ ์์ฑํฉ๋๋ค. ์ฒซ ๋จ๊ณ๋ก, ์๋ณธ ์ด๋ฏธ์ง๋ฅผ ์ ์ฒ๋ฆฌํ์ฌ MobileNetV2 ๋ชจ๋ธ์ ์
๋ ฅ์ผ๋ก ์ ๊ณตํฉ๋๋ค. | image_path = tf.keras.utils.get_file('YellowLabradorLooking_new.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/YellowLabradorLooking_new.jpg')
image_raw = tf.io.read_file(image_path)
image = tf.image.decode_image(image_raw)
image = preprocess(image)
image_probs = pretrained_model.predict(... | _____no_output_____ | Apache-2.0 | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n |
์ด๋ฏธ์ง๋ฅผ ์ดํด๋ด
์๋ค. | plt.figure()
plt.imshow(image[0])
_, image_class, class_confidence = get_imagenet_label(image_probs)
plt.title('{} : {:.2f}% Confidence'.format(image_class, class_confidence*100))
plt.show() | _____no_output_____ | Apache-2.0 | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n |
์ ๋์ ์ด๋ฏธ์ง ์์ฑํ๊ธฐ FGSM ์คํํ๊ธฐ์ฒซ๋ฒ์งธ ๋จ๊ณ๋ ์ํ ์์ฑ์ ์ํด ์๋ณธ ์ด๋ฏธ์ง์ ๊ฐํ๊ฒ ๋ ์๊ณก์ ์์ฑํ๋ ๊ฒ์
๋๋ค. ์์ ์ดํด๋ณด์๋ฏ์ด, ์๊ณก์ ์์ฑํ ๋์๋ ์
๋ ฅ ์ด๋ฏธ์ง์ ๋ํ ๊ทธ๋๋์ธํธ๋ฅผ ์ฌ์ฉํฉ๋๋ค. | loss_object = tf.keras.losses.CategoricalCrossentropy()
def create_adversarial_pattern(input_image, input_label):
with tf.GradientTape() as tape:
tape.watch(input_image)
prediction = pretrained_model(input_image)
loss = loss_object(input_label, prediction)
# ์
๋ ฅ ์ด๋ฏธ์ง์ ๋ํ ์์ค ํจ์์ ๊ธฐ์ธ๊ธฐ๋ฅผ ๊ตฌํฉ๋๋ค.
gradient = t... | _____no_output_____ | Apache-2.0 | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n |
์์ฑํ ์๊ณก์ ์๊ฐํํด ๋ณผ ์ ์์ต๋๋ค. | # ์ด๋ฏธ์ง์ ๋ ์ด๋ธ์ ์-ํซ ์ธ์ฝ๋ฉ ์ฒ๋ฆฌํฉ๋๋ค.
labrador_retriever_index = 208
label = tf.one_hot(labrador_retriever_index, image_probs.shape[-1])
label = tf.reshape(label, (1, image_probs.shape[-1]))
perturbations = create_adversarial_pattern(image, label)
plt.imshow(perturbations[0]) | _____no_output_____ | Apache-2.0 | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n |
์๊ณก ์น์ ์ก์ค๋ก (epsilon)์ ๋ฐ๊ฟ๊ฐ๋ฉฐ ๋ค์ํ ๊ฐ๋ค์ ์๋ํด๋ด
์๋ค. ์์ ๊ฐ๋จํ ์คํ์ ํตํด ์ก์ค๋ก ์ ๊ฐ์ด ์ปค์ง์๋ก ๋คํธ์ํฌ๋ฅผ ํผ๋์ํค๋ ๊ฒ์ด ์ฌ์์ง์ ์ ์ ์์ต๋๋ค. ํ์ง๋ง ์ด๋ ์ด๋ฏธ์ง์ ์๊ณก์ด ์ ์ ๋ ๋๋ ทํด์ง๋ค๋ ๋จ์ ์ ๋๋ฐํฉ๋๋ค. | def display_images(image, description):
_, label, confidence = get_imagenet_label(pretrained_model.predict(image))
plt.figure()
plt.imshow(image[0])
plt.title('{} \n {} : {:.2f}% Confidence'.format(description,
label, confidence*100))
plt.show()
epsilons = [0... | _____no_output_____ | Apache-2.0 | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n |
plotting a neuron | import numpy as np
import McNeuron
import data_transforms
from keras.models import Sequential
from keras.layers.core import Dense, Reshape
from keras.layers.recurrent import LSTM
import matplotlib.pyplot as plt
from copy import deepcopy
import os
from numpy import linalg as LA
%matplotlib inline
import scipy.io
mat... | _____no_output_____ | MIT | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron |
Subsampling methods | # self is neuron!
def get_main_points(self):
"""
gets the index of branching points and end points.
"""
(branch_index,) = np.where(self.branch_order[self.n_soma:]==2)
(endpoint_index,) = np.where(self.branch_order[self.n_soma:]==0)
selected_index = np.union1d(branch_index + self.n_soma, endpoint... | _____no_output_____ | MIT | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron |
Testing subsamples | neuron_list = McNeuron.visualize.get_all_path(os.getcwd()+"/Data/Pyramidal/chen")
neuron = McNeuron.Neuron(file_format = 'swc', input_file=neuron_list[19])
# McNeuron.visualize.plot_2D(neuron,size = 4)
# McNeuron.visualize.plot_2D(random_subsample(neuron, 200) ,size = 4)
# McNeuron.visualize.plot_2D(subsample_main_node... | _____no_output_____ | MIT | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron |
Models | def reducing_data(swc_df, pruning_number=10):
"""
Parameters
----------
swc_df: dataframe
the original swc file
pruning_number: int
number of nodes remaining at the end of pruning
Returns
-------
pruned_df: dataframe
pruned dataframe
"""
L = ... | _____no_output_____ | MIT | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron |
Showing the geometrical data | tmp = reducing_data(neuron_list[0:20], pruning_number=10)
geo, morph = separate(tmp)
McNeuron.visualize.plot_2D(tmp[0])
plt.scatter(tmp[0].location[0,:],tmp[0].location[1,:])
for n in range(10):
plt.scatter(geo[n][0,:],geo[n][1,:])
plt.show()
McNeuron.visualize.plot_2D(tmp[1]) | _____no_output_____ | MIT | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron |
Testing function: separate [works] | geo, morph = separate(tmp)
print morph[0]
print morph[1]
print morph[2]
print geo[6].shape
n = 1
plt.scatter(geo[n][0,:],geo[n][1,:]) | _____no_output_____ | MIT | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron |
Testing geometry_generator( ) [works] | neuron = McNeuron.Neuron(file_format = 'swc', input_file=neuron_list[0])
McNeuron.visualize.plot_2D(neuron)
n1 = neuron.subsample(100)
McNeuron.visualize.plot_2D(n1)
McNeuron.visualize.plot_dedrite_tree(n1)
neuron.n_node
n1.n_node
plt.hist(n1.distance_from_parent)
plt.scatter(n1.location[0,:],n1.location[1,:],s = 7)
tm... | _____no_output_____ | MIT | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron |
Guided Capstone Step 6. Documentation **The Data Science Method** 1. Problem Identification 2. Data Wrangling 3. Exploratory Data Analysis 4. Pre-processing and Training Data Development5. Modeling6. **Documentation** * Review the Results * Finalize Code * Finalize Documentation * Create a Project ... | import os
import pandas as pd
import datetime
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
os.getcwd() | _____no_output_____ | MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
Fit Models with Training Dataset ** Using sklearn fit the model you chose in Guided Capstone 5 on your training dataset. This includes: creating dummy features for states if you need them, scaling the data,and creating train and test splits before fitting the chosen model.Also, remember to generate a model performance... | ##model4 is best model as accuracy is 93% and it is generalized model.
df_1=pd.read_csv(r'/Users/ajesh_mahto/Desktop/capstone_project/data/step_try.csv')
df_1.head()
df_1=df_1.drop('Unnamed: 0',axis=1)
df=pd.get_dummies(df_1, columns=['state'],drop_first=True)
from sklearn.preprocessing import StandardScaler
X=df.dro... | Mean Absolute Error: 5.162174619564856
Root Mean Squared Error: 6.874864639122517
Mean Squared Error: 47.263763806257174
| MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
Review the results ** Now, let's predict the Big Mountain Weekend price with our model in order to provide a recommendation to our managers on how to price the `AdultWeekend` lift ticket. First we need to find the row for Big Mountain resort in our data using string contains or string matching.** | #df[df['Name'].str.contains('Big Mountain')]
df3=df[df['Name'].str.contains('Big Mountain')]
df3 | _____no_output_____ | MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
** Prepare the Big Mountain resort data row as you did in the model fitting stage.** |
features=df3.drop(['Name','AdultWeekend'], axis=1)
| _____no_output_____ | MIT | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.