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
Let's convolve!
conv = np.convolve(stim_vector, hrf)[:stim_vector.size] conv = conv / conv.max() conv_ds = conv[::TR*1000] plt.figure(figsize=(15, 5)) plt.subplot(1, 2, 1) plt.plot(conv) plt.subplot(1, 2, 2) plt.plot(conv_ds) plt.tight_layout() sns.despine() plt.show()
_____no_output_____
MIT
downsampling_hrf.ipynb
lukassnoek/random_notebooks
Table of Contents 1  Linear Regression problem2  Gradient Descent3  Gradient Descent - Classification4  Gradient descent with numpy
%matplotlib inline from fastai.learner import *
_____no_output_____
Apache-2.0
courses/dl1/lesson6-sgd.ipynb
cklukas/fastai
In this part of the lecture we explain Stochastic Gradient Descent (SGD) which is an **optimization** method commonly used in neural networks. We will illustrate the concepts with concrete examples. Linear Regression problem The goal of linear regression is to fit a line to a set of points.
# Here we generate some fake data def lin(a,b,x): return a*x+b def gen_fake_data(n, a, b): x = s = np.random.uniform(0,1,n) y = lin(a,b,x) + 0.1 * np.random.normal(0,3,n) return x, y x, y = gen_fake_data(50, 3., 8.) plt.scatter(x,y, s=8); plt.xlabel("x"); plt.ylabel("y");
_____no_output_____
Apache-2.0
courses/dl1/lesson6-sgd.ipynb
cklukas/fastai
You want to find **parameters** (weights) $a$ and $b$ such that you minimize the *error* between the points and the line $a\cdot x + b$. Note that here $a$ and $b$ are unknown. For a regression problem the most common *error function* or *loss function* is the **mean squared error**.
def mse(y_hat, y): return ((y_hat - y) ** 2).mean()
_____no_output_____
Apache-2.0
courses/dl1/lesson6-sgd.ipynb
cklukas/fastai
Suppose we believe $a = 10$ and $b = 5$ then we can compute `y_hat` which is our *prediction* and then compute our error.
y_hat = lin(10,5,x) mse(y_hat, y) def mse_loss(a, b, x, y): return mse(lin(a,b,x), y) mse_loss(10, 5, x, y)
_____no_output_____
Apache-2.0
courses/dl1/lesson6-sgd.ipynb
cklukas/fastai
So far we have specified the *model* (linear regression) and the *evaluation criteria* (or *loss function*). Now we need to handle *optimization*; that is, how do we find the best values for $a$ and $b$? How do we find the best *fitting* linear regression. Gradient Descent For a fixed dataset $x$ and $y$ `mse_loss(a,b...
# generate some more data x, y = gen_fake_data(10000, 3., 8.) x.shape, y.shape x,y = V(x),V(y) # Create random weights a and b, and wrap them in Variables. a = V(np.random.randn(1), requires_grad=True) b = V(np.random.randn(1), requires_grad=True) a,b learning_rate = 1e-3 for t in range(10000): # Forward pass: comp...
81.85150909423828 0.6641168594360352 0.14232024550437927 0.1283807009458542 0.12010374665260315 0.11376982182264328 0.10891081392765045 0.10518334060907364 0.10232385247945786 0.1001303493976593
Apache-2.0
courses/dl1/lesson6-sgd.ipynb
cklukas/fastai
Nearly all of deep learning is powered by one very important algorithm: **stochastic gradient descent (SGD)**. SGD can be seeing as an approximation of **gradient descent** (GD). In GD you have to run through *all* the samples in your training set to do a single itaration. In SGD you use *only one* or *a subset* of tr...
def gen_fake_data2(n, a, b): x = np.random.uniform(0,1,n) y = lin(a,b,x) + 0.1 * np.random.normal(0,3,n) return x, np.where(y>10, 1., 0.) x,y = gen_fake_data2(10000, 3., 8.) x,y = V(x),V(y) def nll(y_hat, y): y_hat = torch.clamp(y_hat, 1e-5, 1-1e-5) return (y*y_hat.log() + (1.-y)*(1.-y_hat).log())....
0.21786124000293539 0.3435 0.002203564243036162 0.3435 0.0005242383704432571 0.3435
Apache-2.0
courses/dl1/lesson6-sgd.ipynb
cklukas/fastai
Nearly all of deep learning is powered by one very important algorithm: **stochastic gradient descent (SGD)**. SGD can be seeing as an approximation of **gradient descent** (GD). In GD you have to run through *all* the samples in your training set to do a single itaration. In SGD you use *only one* or *a subset* of tr...
from matplotlib import rcParams, animation, rc from ipywidgets import interact, interactive, fixed from ipywidgets.widgets import * rc('animation', html='html5') rcParams['figure.figsize'] = 3, 3 x, y = gen_fake_data(50, 3., 8.) a_guess,b_guess = -1., 1. mse_loss(y, a_guess, b_guess, x) lr=0.01 def upd(): global a_...
_____no_output_____
Apache-2.0
courses/dl1/lesson6-sgd.ipynb
cklukas/fastai
Identify bifurcation point using a piecewise phase-transition function Get first bifurcation pointOnce you have this, you can draw a line segment bisecting the angle between the point and two targets. This will be the line about which you symmetrise to get the second bifurcation point
def fitfunc(x, p, q, r): return r * (np.abs((x - p)) ** q) def fitfunc_vec_self(x, p, q, r): y = np.zeros(x.shape) for i in range(len(y)): y[i] = fitfunc(x[i], p, q, r) return y x_fit = [] y_fit = [] if nPosts == 2: if model == 'neural': bif_pt = 2.5 params1 = [3, 1, 1]...
The first bifurcation occurs at an angle 96.38939242028479
MIT
model_plots.ipynb
RnoB/fly-matrix
Get the second bifurcation pointFor this, you must center the trajectories about the bifurcation point, get a new heatmap and rotate this by the angle of the bisector line
# center points about the first bifurcation cxs = xs - params1[0] cys = ys cts = ts cpost0_x = post0_x - params1[0] cpost1_x = post1_x - params1[0] cpost2_x = post2_x - params1[0] @numba.njit(fastmath=True, parallel=True) def parallel_rotate(xy, rmat): out = np.zeros(xy.shape) for idx in numba.prange(xy.shape[...
_____no_output_____
MIT
model_plots.ipynb
RnoB/fly-matrix
Matrix FactorizationMatrix Factorization :cite:`Koren.Bell.Volinsky.2009` is a well-established algorithm in the recommender systems literature. The first version of matrix factorization model is proposed by Simon Funk in a famous [blogpost](https://sifter.org/~simon/journal/20061211.html) in which he described the id...
import mxnet as mx from mxnet import autograd, gluon, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np()
_____no_output_____
MIT
scripts/d21-en/mxnet/chapter_recommender-systems/mf.ipynb
lucmertins/CapDeepLearningBook
Model ImplementationFirst, we implement the matrix factorization model described above. The user and item latent factors can be created with the `nn.Embedding`. The `input_dim` is the number of items/users and the (`output_dim`) is the dimension of the latent factors ($k$). We can also use `nn.Embedding` to create th...
class MF(nn.Block): def __init__(self, num_factors, num_users, num_items, **kwargs): super(MF, self).__init__(**kwargs) self.P = nn.Embedding(input_dim=num_users, output_dim=num_factors) self.Q = nn.Embedding(input_dim=num_items, output_dim=num_factors) self.user_bias = nn.Embedding(...
_____no_output_____
MIT
scripts/d21-en/mxnet/chapter_recommender-systems/mf.ipynb
lucmertins/CapDeepLearningBook
Evaluation MeasuresWe then implement the RMSE (root-mean-square error) measure, which is commonly used to measure the differences between rating scores predicted by the model and the actually observed ratings (ground truth) :cite:`Gunawardana.Shani.2015`. RMSE is defined as:$$\mathrm{RMSE} = \sqrt{\frac{1}{|\mathcal{T...
def evaluator(net, test_iter, devices): rmse = mx.metric.RMSE() # Get the RMSE rmse_list = [] for idx, (users, items, ratings) in enumerate(test_iter): u = gluon.utils.split_and_load(users, devices, even_split=False) i = gluon.utils.split_and_load(items, devices, even_split=False) r...
_____no_output_____
MIT
scripts/d21-en/mxnet/chapter_recommender-systems/mf.ipynb
lucmertins/CapDeepLearningBook
Training and Evaluating the ModelIn the training function, we adopt the $L_2$ loss with weight decay. The weight decay mechanism has the same effect as the $L_2$ regularization.
#@save def train_recsys_rating(net, train_iter, test_iter, loss, trainer, num_epochs, devices=d2l.try_all_gpus(), evaluator=None, **kwargs): timer = d2l.Timer() animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0, 2], legend=['train loss', 't...
_____no_output_____
MIT
scripts/d21-en/mxnet/chapter_recommender-systems/mf.ipynb
lucmertins/CapDeepLearningBook
Finally, let us put all things together and train the model. Here, we set the latent factor dimension to 30.
devices = d2l.try_all_gpus() num_users, num_items, train_iter, test_iter = d2l.split_and_load_ml100k( test_ratio=0.1, batch_size=512) net = MF(30, num_users, num_items) net.initialize(ctx=devices, force_reinit=True, init=mx.init.Normal(0.01)) lr, num_epochs, wd, optimizer = 0.002, 20, 1e-5, 'adam' loss = gluon.loss...
train loss 0.063, test RMSE 1.054 21885.2 examples/sec on [gpu(0), gpu(1)]
MIT
scripts/d21-en/mxnet/chapter_recommender-systems/mf.ipynb
lucmertins/CapDeepLearningBook
Below, we use the trained model to predict the rating that a user (ID 20) might give to an item (ID 30).
scores = net(np.array([20], dtype='int', ctx=devices[0]), np.array([30], dtype='int', ctx=devices[0])) scores
_____no_output_____
MIT
scripts/d21-en/mxnet/chapter_recommender-systems/mf.ipynb
lucmertins/CapDeepLearningBook
TUGAS BESAR TF3101 - DINAMIKA SISTEM DAN SIMULASI Sistem Elektrik, Elektromekanik, dan Mekanik Nama Anggota: Erlant Muhammad Khalfani (13317025) Bernardus Rendy (13317041) 1. Pemodelan Sistem Elektrik Untuk pemodelan sistem elektrik, dipilih rangkaian RLC seri dengan sebuah sumber tegangan sepe...
#IMPORTS from ipywidgets import interact, interactive, fixed, interact_manual , HBox, VBox, Label, Layout import ipywidgets as widgets import numpy as np import matplotlib.pyplot as plt from scipy import signal #DEFINISI SLIDER-SLIDER PARAMETER #Slider R1 R1_slider = widgets.FloatSlider( value=1., min=1., m...
_____no_output_____
MIT
Final_Task_2019/Merged_Files/.ipynb_checkpoints/PR5_13317025_13317041-checkpoint.ipynb
bernardusrendy/ssicon
Analisis a. Respon Step Dari hasil simulasi, didapatkan pengaruh perubahan-perubahan nilai parameter pada *output* sistem setelah diberikan *input* berupa sinyal *step*, di antaranya:1. Kenaikan nilai $R_1$ akan menurunkan *steady-state gain* ($K$) sistem. Ini terlihat dari turunnya nilai *output* $v_{R2}$ pada keada...
# Digunakan penyelesaian numerik untuk output import numpy as np from scipy.integrate import odeint import scipy.signal as sig import matplotlib.pyplot as plt from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem from sympy import * import control as control vin = symbols ('V_{in}') #import symbol input om...
_____no_output_____
MIT
Final_Task_2019/Merged_Files/.ipynb_checkpoints/PR5_13317025_13317041-checkpoint.ipynb
bernardusrendy/ssicon
Analisis Karena model memiliki persamaan yang cukup kompleks sehingga tidak dapat diambil secara intuitive kesimpulan parameter terhadap output sistem, akan dilakukan percobaan menggunakan slider untuk mengubah parameter dan mengamati interaksi perubahan antara parameter. Akan dilakukan juga perubahan bentuk input dan...
# Digunakan penyelesaian numerik untuk output import numpy as np from scipy.integrate import odeint import scipy.signal as sig import matplotlib.pyplot as plt from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem from sympy import * import control as control def plot_mekanik(M,B,K,VinType,grid): # Para...
_____no_output_____
MIT
Final_Task_2019/Merged_Files/.ipynb_checkpoints/PR5_13317025_13317041-checkpoint.ipynb
bernardusrendy/ssicon
IO markup Train
from modules.data import bert_data train_df_path = "/home/eartemov/ae/work/factRuEval-2016/dev.csv" valid_df_path = "/home/eartemov/ae/work/factRuEval-2016/test.csv" data = bert_data.LearnData.create( train_df_path=train_df_path, valid_df_path=valid_df_path, idx2labels_path="/home/eartemov/ae/work/factRuEva...
_____no_output_____
MIT
exps/fre BERTNCRF.ipynb
learnerhouse/ner-bert
Predict
from modules.data.bert_data import get_data_loader_for_predict dl = get_data_loader_for_predict(data, df_path=data.valid_ds.config["df_path"]) preds = learner.predict(dl) from sklearn_crfsuite.metrics import flat_classification_report from modules.analyze_utils.utils import bert_labels2tokens, voting_choicer from modul...
processed 56409 tokens with 7534 phrases; found: 7442 phrases; correct: 6377. precision: 85.69%; recall: 84.64%; FB1: 85.16 LOC: precision: 87.65%; recall: 78.87%; F1: 83.03 1401 ORG: precision: 79.46%; recall: 80.78%; F1: 80.11 3929 PER: precision: 95.98%; recall: 95.98%; F1: 95.98 2112
MIT
exps/fre BERTNCRF.ipynb
learnerhouse/ner-bert
District SummaryCalculate the total number of schoolsCalculate the total number of studentsCalculate the total budgetCalculate the average math scoreCalculate the average reading scoreCalculate the overall passing rate (overall average score), i.e. (avg. math score + avg. reading score)/2Calculate the percentage of stu...
total_number_schools = len(school_data_complete["School ID"].unique()) total_number_schools #Calculate the total number of students total_number_students = len(school_data_complete["Student ID"].unique()) total_number_students #Calculate the total budget total_budget = school_data["budget"].sum() total_budget #Calcul...
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
School SummaryCreate an overview table that summarizes key metrics about each school, including:School NameSchool TypeTotal StudentsTotal School BudgetPer Student BudgetAverage Math ScoreAverage Reading Score% Passing Math% Passing ReadingOverall Passing Rate (Average of the above two)Create a dataframe to hold the abo...
#For this part, school_data_complete school_data_complete["passing_math"] = school_data_complete["math_score"] >= 70 school_data_complete["passing_reading"] = school_data_complete["reading_score"] >= 70 school_data_complete # Use groupby by school_name school_group = school_data_complete.groupby(["school_name"]).me...
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
Top Performing Schools (By Passing Rate)Sort and display the top five schools in overall passing rate
#Sort and display the top five schools in overall passing rate top_five_schools = school_summary_dataframe.sort_values(["% Overall Passing Rate"], ascending=False) top_five_schools.head()
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
Bottom Performing Schools (By Passing Rate)¶Sort and display the five worst-performing schools
#Sort and display the five worst-performing schools bottom_five_schools = school_summary_dataframe.sort_values(["% Overall Passing Rate"], ascending=True) bottom_five_schools.head()
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
Math Scores by GradeCreate a table that lists the average Reading Score for students of each grade level (9th, 10th, 11th, 12th) at each school.Create a pandas series for each grade. Hint: use a conditional statement.Group each series by schoolCombine the series into a dataframeOptional: give the displayed data cleaner...
#Create a pandas series for each grade. Group each series by school. nineth_grade= school_data_complete[school_data_complete["grade"] == "9th"].groupby("school_name").mean()["math_score"] tenth_grade = school_data_complete[school_data_complete["grade"] == "10th"].groupby("school_name").mean()["math_score"] eleventh_...
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
Reading Score by GradePerform the same operations as above for reading scores
#Perform the same operations as above for reading scores #Create a pandas series for each grade. Group each series by school. nineth_grade= school_data_complete[school_data_complete["grade"] == "9th"].groupby("school_name").mean()["reading_score"] tenth_grade = school_data_complete[school_data_complete["grade"] == "...
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
Scores by School SpendingCreate a table that breaks down school performances based on average Spending Ranges (Per Student). Use 4 reasonable bins to group school spending. Include in the table each of the following:Average Math ScoreAverage Reading Score% Passing Math% Passing ReadingOverall Passing Rate (Average of t...
# Sample bins. Feel free to create your own bins. spending_bins = [0, 585, 615, 645, 675] group_names = ["<$585", "$585-615", "$615-645", "$645-675"] # Use 4 reasonable bins to group school spending. school_data_summary["Spending Ranges (Per Student)"] = pd.cut(school_data_summary["Per Student Budget"], spending_bin...
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
Scores by School Size¶Perform the same operations as above, based on school size.
# Sample bins. Feel free to create your own bins. size_bins = [0, 1000, 2000, 5000] group_names = ["Small (<1000)", "Medium (1000-2000)", "Large (2000-5000)"] # Use 4 reasonable bins to group school size. school_data_summary["School Size"] = pd.cut(school_data_summary["size_x"], size_bins, labels=group_names) school_...
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
Scores by School TypePerform the same operations as above, based on school type.
school_type_grouped = school_data_summary.groupby("type").mean() #Remove the unwanted columns as per the sample provided del school_type_grouped['size_x'] del school_type_grouped['budget_x'] del school_type_grouped['Per Student Budget'] del school_type_grouped['School ID_y'] del school_type_grouped['passing_math'] del...
_____no_output_____
ADSL
PyCitySchools/School_Data.ipynb
Denbigh97/Panda_Challenge
Convolution_with_fastai> 2021-10-26- toc: true - badges: true- comments: false- categories: bigdata- image: images/chart-preview.png- hide: true
import torch from fastai.vision.all import *
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
data
path = untar_data(URLs.MNIST_SAMPLE) path.ls()
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` list 형태로 목록 받기
threes = (path/'train'/'3').ls() sevens = (path/'train'/'7').ls()
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` list $\to$ image
Image.open(threes[0])
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` image $\to$ tensor
tensor(Image.open(threes[0]))
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`*` 여기서 tensor는 pytorch에 있는 tensor가 아닌, fastai에 있는 tensor이다. `*` , 만약 pytorch의 tensor였다면 torch.tensor로 사용했을 것이다.torch.tensor는 이미지파일을 텐서로 변환하는 기능이 없다.
# plt.imshow(tensor(Image.open(threes[0]))) 변환한 텐서로 이미지 출력 #[tensor(Image.open(i)) for i in sevens] # tensor들이 list로 바뀌어있다. 현재 이 상태는 것이 list 안이 tensor로, 좀 더 깔끔하게 만들면 #torch.stack([tensor(Image.open(i)) for i in sevens]) # tensor안의 값들은 float여야 하므로 seven_tensor = torch.stack([tensor(Image.open(i)) for i in sevens]).float...
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 데이터인 X는 seven_tensor와 three_tensor를 합친다. (vstack 으로)
X = torch.vstack([seven_tensor, three_tensor]) X = X.reshape(12396,-1) X.shape X.shape X = X.reshape(12396,1,28,28)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
1. 지난시간까지 모형 (네트워크 직접 설계, pytorch) 선형변환 대신에 2D Convolution with Window_size = 5 - 인자를 보면 in-channels, out-channels, 그리고 kernel-size가 있다.이 세 개를 넣어야 한다.
c1 = torch.nn.Conv2d(1,16,5) # 입력채널 = 1, 출력 채널 = 16, window_size = 5
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
NonLinear를 위해서, ReLU()대신 MaxPool2d + ReLU 를 함, MaxPooling을 하나 걸침
m1 = torch.nn.MaxPool2d(2)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
ReLU()
a1 = torch.nn.ReLU() X.shape, c1(X).shape, m1(c1(X)).shape, a1(m1(c1(X))).shape
C:\Users\USER\anaconda3\envs\bda2021\lib\site-packages\torch\nn\functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at ..\c10/core/TensorImpl...
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
Flatten
class Flatten(torch.nn.Module): # Module 상속 def forward(self,x): return x.reshape(12396,-1)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- a1을 거쳐서 들어온 것을 a1(m1(c1(X))).reshape(12396,-1) 이렇게 바꿔주어야 한다.
flatten = Flatten() X.shape, c1(X).shape, m1(c1(X)).shape, a1(m1(c1(X))).shape, flatten(a1(m1(c1(X)))).shape
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
linear
l1 = torch.nn.Linear(in_features=2304, out_features=1) X.shape, c1(X).shape, \ m1(c1(X)).shape, \ a1(m1(c1(X))).shape, \ flatten(a1(m1(c1(X)))).shape, \ l1(flatten(a1(m1(c1(X))))).shape plt.plot(l1(flatten(a1(m1(c1(X))))).data)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 학습이 안된상태
net = torch.nn.Sequential( c1, # Convolution(선형) m1, # MaxPooling(비선형) a1, # RelU(비선형) flatten, l1)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 손실함수와 옵티마이저 정의
loss_fn = torch.nn.BCEWithLogitsLoss() optimizer = torch.optim.Adam(net.parameters())
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` step 1~4
for epoc in range(200): # 1 yhat = net(X) # 2 loss = loss_fn(yhat,y) # 3 loss.backward() # 4 optimizer.step() net.zero_grad() a2 = torch.nn.Sigmoid() plt.plot(y) plt.plot(a2(yhat.data),'.') # 마지막 sigmoid를 취한 버전 ypred = a2(yhat.data)>0.5 sum(ypred == y) / 12396
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
2. 드랍아웃, 배치추가 (직접네트워크 설계, pytorch + fastai) step1 : dls를 만들자
ds = torch.utils.data.TensorDataset(X,y) ds.tensors[0].shape #이미지 자체가 들어간 것, 784개 벡터로 늘려지는게 아니라
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` training, validation 분리
ds1, ds2 = torch.utils.data.random_split(ds,[10000,2396]) # training을 10000개, validation을 2396개로 ds로부터 랜덤하게 나눔 dl1 = torch.utils.data.DataLoader(ds1, batch_size=500) # DataLoader는 batch size를 정할 수 있다. -> 총 1만개 에서 500개를 나누므로, for문 한 번당 20번 돌아감 dl2 = torch.utils.data.DataLoader(ds2, batch_size=2396) # 여기선 딱히 batch를 나누지 않...
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` dataloader를 만들었으니 이제 DataLoaders를 만들어야 한다. ( 여태 pytorch로 작업한 것이였고 여기부터는 fastai로 작업한다. )
dls = DataLoaders(dl1,dl2)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 여기까지 한 것이 데이터 정리TensorDataset step2: 아키텍처, 손실함수, 옵티마이저
class Flatten(torch.nn.Module): # Module 상속 def forward(self,x): return x.reshape(x.shape[0],-1) net = torch.nn.Sequential( torch.nn.Conv2d(1,16,5), torch.nn.MaxPool2d(2), torch.nn.ReLU(), torch.nn.Dropout2d(), Flatten(), torch.nn.Linear(2304,1) ) loss_fn = torch.nn.BCEWithLogitsLoss...
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
step3: lrnr 생성 `-` Learner 클래스에서 learner instance 생성
lrnr1 = Learner(dls, net, opt_func=Adam, loss_func=loss_fn)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 이것의 역할: 1. for 문 돌리면서 step 1~4 하던 것을 자동으로 해주는 역할 2. batch를 dls가 알아서 나눠줌 3. gpu에 자동으로 올려줌 `-` 우리가 할 일은 for문을 몇 번 돌려줄지 결정하는 것
lrnr1.fit(10)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` GPU에 올린 것을 알아둬야 한다. 이는 Shape와 같이 자주 신경써야 하는 부분이다. `-` 현재 networks의 parameter가 GPU에 올라가있기 때문에, 데이터 X도 GPU에 올려서 계산을 한다(아니면 parameter를 CPU로 내려도 되는데 계산속도가 GPU보다 느릴 것으로 예상된다)
# net(X.to("cuda:0")).to("cpu").data
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 다시 그림을 그리는 plot 을 사용하려면 계산한 결과를 cpu로 내려서 그려야 한다.
plt.plot(net(X.to("cuda:0")).to("cpu").data,'.') plt.plot(a2(net(X.to("cuda:0")).to("cpu").data),'.')
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- Sigmoid 적용 `-` 빠르고 적합 결과도 좋음 3. resnet34 사용 (기존의 네트워크 사용, 순수 fastai) `-` 데이터로부터 새로운 데이터로더스를 만들고 이를 dls2라 한다.
path = untar_data(URLs.MNIST_SAMPLE) path path.ls()
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 여기서 train부분의 폴더에 접근해서 사용할 것이다.
dls2 = ImageDataLoaders.from_folder( path, train = 'train', valid_pct = 0.2 )
Due to IPython and Windows limitation, python multiprocessing isn't available now. So `number_workers` is changed to 0 to avoid getting stuck
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` Learner를 CNN전용으로 만들어 둔 것이 있다. `-` learn오브젝트를 생성하고 학습
lrnr2 = cnn_learner(dls2, resnet34, metrics = error_rate) lrnr2.fine_tune(1)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 결과 관찰
lrnr2.show_results()
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
모형을 뜯어보는 방법 (lrnr1) `-` 우선 방법 2로 돌아가자 `-` 네트워크 구조
net
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 인덱싱을 통하여 각각의 layer에 적용할 수 있다.
net[0]
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- c1 = net[0] (torch.nn.Conv2d)에 해당하는 형태이다.
net.to("cpu")
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 먼저 GPU 성능 문제로 인한 에러때문에 net을 cpu로 옮겼다. `-` 각각의 layer에서의 중간 결과를 가로챌 수 있다. `-` 층별 변환과정
print(X.shape, '-> Input Image') print(net[0](X).shape, '-> Conv2D') print(net[1](net[0](X)).shape, '-> MaxPool2D') print(net[2](net[1](net[0](X))).shape, '-> ReLU') print(net[3](net[2](net[1](net[0](X)))).shape, '-> DropOut2D') print(net[4](net[3](net[2](net[1](net[0](X))))).shape, '-> Flatten') print(net[5](net[4](ne...
torch.Size([12396, 1, 28, 28]) -> Input Image torch.Size([12396, 16, 24, 24]) -> Conv2D torch.Size([12396, 16, 12, 12]) -> MaxPool2D torch.Size([12396, 16, 12, 12]) -> ReLU torch.Size([12396, 16, 12, 12]) -> DropOut2D torch.Size([12396, 2304]) -> Flatten torch.Size([12396, 1]) -> Linear
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 중간의 각각 layer들을 연속해서 적용한 결과, 실제 network 전체에 대입한(연속적인 계산) 결과와 동일한 결과를 얻는다. `-` 두 결과가 일치하는지 확인
print(net(X)) print(net[5](net[4](net[3](net[2](net[1](net[0](X)))))))
tensor([[ -8.9509], [-10.6344], [ -5.5692], ..., [ 15.4405], [ 8.6353], [ 6.3605]], grad_fn=<AddmmBackward>) tensor([[ -8.9509], [-10.6344], [ -5.5692], ..., [ 15.4405], [ 8.6353], [ 6.3605]], grad_fn=<AddmmBackward>)
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 일치한다. `-` lrnr1 자체를 활용해도 층별변환과정을 추적함 lrnr1 = net임
lrnr1.model
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- net과 동일한 결과 `-` net과 동일한 신경망으로의 입력 및 출력, 층별 가로채기
lrnr1.model(X) lrnr1.model[0](X)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- net과 동일한 결과이다. `-` 위의 net부분에서 층별 변환과정을 lrnr1으로 하려면, net을 lrnr1.model으로 바꾸면 된다.
print(X.shape, '-> 입력') print(lrnr1.model[0](X).shape, '-> Conv2D') print(lrnr1.model[1](lrnr1.model[0](X)).shape, '-> MaxPool2D') ''' ... ''' print(lrnr1.model[5](lrnr1.model[4](lrnr1.model[3](lrnr1.model[2](lrnr1.model[1](lrnr1.model[0](X)))))).shape, '-> Linear')
torch.Size([12396, 1, 28, 28]) -> 입력 torch.Size([12396, 16, 24, 24]) -> Conv2D torch.Size([12396, 16, 12, 12]) -> MaxPool2D torch.Size([12396, 1]) -> Linear
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 정리: 모형은 항상 아래와 같이 2d-part와 1d-part로 나뉜다. ```torch.Size([12396, 1, 28, 28]) -> Input Imagetorch.Size([12396, 16, 24, 24]) -> Conv2Dtorch.Size([12396, 16, 12, 12]) -> MaxPool2Dtorch.Size([12396, 16, 12, 12]) -> ReLUtorch.Size([12396, 16, 12, 12]) -> DropOut2D===================================================torch.Si...
_net1 = torch.nn.Sequential( net[0], net[1], net[2], net[3] ) _net2 = torch.nn.Sequential( net[4], net[5] ) _net1 _net2 _net = torch.nn.Sequential(_net1, _net2) _net
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 2d part와 1d part로 나누었다
_net[0] _net[0](X)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 위의 _net$[$0$]$(X)의 결과는 2D part의 결과를 의미한다. lrnr2.model (resnet34) 분석
lrnr2.model
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 여기서 크게 (0) Sequential part와 (1) Sequential part로 나뉘었음을 알 수 있다. 이는 각각 2d 와 1d part를 의미한다. `-` 2d part
lrnr2.model[0]
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 1d part
lrnr2.model[1]
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
1d part 살펴보기 먼저 이미지를 받아서 Pooling을 하는데, AveragePooling이랑 MaxPooling이라는 것을 함 (Adaptive는 잘 모르겠음)그리고 Flatten()으로 펼쳐줌 (우리가 정의한 Flatten이 아님)펼친 layer의 차원이 1024임을 알 수 있음. 그리고 batch normalization이라는 것이 진행이 됨Linear Transform으로 1024를 512로 한 번 줄여줌그리고 ReLU하고 다시 Batch normarlization, Dropout, Linear를 반복한다는 것 `-` 주목할 만한 점은, BatchNor...
lrnr2.model[0]
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
크게 주목할만한 점: 1. Batch Normalization이 중간중간에 들어가 있다는 것.2. 2D version의 Dropout이 없다는 것3. Conv2d에 더 많은 argument (padding/ stride)들을 사용4. Conv2d의 입력채널이 3원색이라서 3차원 채널인 점 `-` 입력채널이 3이라는 점 때문에 lrnr2에서 dls를 그대로 사용하면 안되고, dls2를 따로 만든 것이다. 우리가 전에 만든 net은 입력채널이 1이였음, 그런데 resnet은 3이라서 그에 맞게 데이터를 다시 정리해줘야됨 `-` DLS, networks- 네트워크 형태에 ...
lrnr1.model net1 = torch.nn.Sequential( lrnr1.model[0], lrnr1.model[1], lrnr1.model[2], lrnr1.model[3] ) net1(X).shape
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 1단계까지의 추력결과를 시각화
fig, axs = plt.subplots(4,4) k = 0 for i in range(4): for j in range(4): axs[i,j].imshow(net1(X)[0][k].data) k = k+1 fig.set_figheight(8) fig.set_figwidth(8) fig.tight_layout()
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
net1은 유지 + net2의 구조를 변경!!
lrnr1.model
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 계획- 변경전 net2: (n,16,12,12) $\overset{flatten}{\Longrightarrow} (n,?) \overset{Linear(?,1)}{\Longrightarrow} (n,1)$- 변경후 net2: (n,16,12,12) $\overset{gap+flatten}{\Longrightarrow} (n,?) \overset{Linear(16,1)}{\Longrightarrow} (n,1)$ - gap은 (n,16,12,12)의 한 데이터에 대해서 나오는 각각의 16개 이미지들의 픽셀들의 평균을 취한 값들을 의미함. 결과적으로는 16개의 이...
ap = torch.nn.AdaptiveAvgPool2d(output_size=1)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- `*`output_size는 평균내서 나올 값의 개수를 뜻하는건가? `-` ap라는 layer를 생성했다.
ap(net1(X)).shape
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 16,1,1 부분을 보면 Flatten 작업이 필요함을 알 수 있다.- ***보충학습: ap는 그냥 평균*** `-` flatten
flatten(ap(net1(X))).shape
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- flatten을 통해서 (12396,16,1,1) 형태가 (12396,16) 로 펼쳐졌다. `-` linear
_l1 = torch.nn.Linear(16,1,bias=False) # _li.to("cuda:0") 만약 gpu에서 계속 연산을 한다면 이 코드를 실행
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 이렇게 gap을 추가한 것을 net2 로 구성, $\to$ (net1, net2)를 묶어서 새로운 net 만들자.
net2 = torch.nn.Sequential( torch.nn.AdaptiveAvgPool2d(1), Flatten(), torch.nn.Linear(16,1,bias=False) )
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`*` torch.nn.linear과 torch.nn.Linear이 무슨 차이가 있는지, ---> L부분이 대문자일 때와 소문자일 때의 차이
ds = torch.utils.data.TensorDataset(X,y) ds1,ds2 = torch.utils.data.random_split(ds, [10000,2396]) dl1 = torch.utils.data.DataLoader(ds1,batch_size=1000) dl2 = torch.utils.data.DataLoader(ds2,batch_size=2396) dls = DataLoaders(dl1,dl2) lrnr3 = Learner(dls,net,opt_func=Adam, loss_func = loss_fn , lr = 0.1) lrnr3.fit(50)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
CAM: observation을 1개로 고정하고 net2에서 layer의 순서를 바꿔서 시각화 `-` 계획- 변경전 netSequential(n,16,12,12) $\overset{flatten}{\Longrightarrow} (n,?) \overset{Linear(?,1)}{\Longrightarrow} (n,1)$- 변경후 net2: (n,16,12,12) $\overset{gap+flatten}{\Longrightarrow} (n,?) \overset{Linear(16,1)}{\Longrightarrow} (n,1)$- CAM: (1,16,12,12) $\ov...
x = X[1] X.shape, x.shape
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- x의 차원이 하나 줄었다. 네트워크에 입력할 때 문제가 발생할 수 있으므로, 입력 차원을 맞추려면 X와 같이 하나 추가를 해야한다.
x = x.reshape(1,1,28,28) #x.squeeze()
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- plt.imshow에 대입하기 위해 이를 (28,28)로 맞춰야함, 이를 위한 함수가 squeeze()
plt.imshow(x.squeeze())
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 준비과정2: 계산과 시각화를 위해서 각 네트워크를 cpu로 옮기자. (fastai로 학습한 직후라 GPU에 있음)
net1.to("cpu") net2.to("cpu")
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` forward 확인: 이 값을 기억하자.
net2(net1(x)) # 0.5 미만으로, 7에 해당한다. CNN이 7이라고 판단.
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- `-` net1, net2만 gpu에 올리고 net(x)를 실행한 결과: device가 다르다며 error가 나온다. `-` net2를 수정하고 forward값 확인
net2
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- net에서 Linear와 AdaptiveAvgPool2d의 적용순서를 바꿔줌 차원 확인
net1(x).squeeze().shape net2[2].weight.shape # net2[2]는 두 cell 위의 net2결과에서 (2): Linear부분을 뜻한다.
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 이해가 잘 안되는 부분, 1,16이면 두 번 곱할 수 있는데, 그렇게하면 1,12,12 가 나와서 차원을 하나 줄인다 하심
net2[2].weight.squeeze().shape # net2[2]는 두 cell 위의 net2결과에서 (2): Linear부분을 뜻한다.
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 차원을 하나 줄인 결과 **Linear(in_features=16, out_features=1, bias=False)** 를 먼저 적용: 16 $\times$ (16,12,12) -> (12,12)
# net2[2].weight.squeeze() @ net1(x).squeeze()
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 에러가 나는 이유: @는 matrix 연산으로 2차원 텐서에 대해서 적용하는데, 이는 3차원이라 @로 연산이 안됨- 실패 `-` 곱하는 방법: torch.einsum()
camimg = torch.einsum("i, ijk -> jk", net2[2].weight.squeeze(), net1(x).squeeze())
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 계산이 잘 됬는지 shape로 확인
camimg.shape
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
- 성공 `-` Linear를 적용하고, 이제 gap을 적용
ap(camimg)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`!!!!` 위의 0.0552와 똑같다? `-` 아래의 값이 같다.
net2(net1(x)), ap(camimg)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 왜냐하면 ap와 선형변환 모두 linear이므로 순서를 바꿔도 상관없음 `-` 아래와 같은 이치
_x = np.array([1,2,3,4]) _x np.mean(_x*2+1) 2*np.mean(_x)+1
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 이제 camimg에 관심을 가져보자.
camimg # 12 * 12 tensor
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
현재 위의 camimg를 평균 취함으로써, 즉, ap(camimg) 혹은 torch.mean(camimg)를 함으로써 0.0552와 같다는 것 `*` 교수님 픽셀의 값과 내 값이 다름, 교수님 픽셀로 일단 작성 `-` 결국 특정픽셀에서 큰 음의 값이 나오기 때문에 궁극적으로는 평균이 음수가 된다. - 평균이 음수이다. $\leftrightarrow$ 이미지가 의미하는 것이 7이다.- 특정픽셀이 큰 음수값을 가진다. $\leftrightarrow$ 이미지 값 7을 좌우하는 픽셀, 즉, 이 픽셀은 이미지가 7이라는 근거가 되는 픽셀이다.
plt.imshow(camimg.data)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 원래 이미지와 비교
plt.imshow(x.squeeze())
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
`-` 두 이미지를 겹쳐서 그리면 멋진 그림이 될 것이다. step1: 원래 이미지를 흑백으로 그리자
plt.imshow(x.squeeze(), cmap='gray',alpha=0.5)
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet
step2: camimg은 (12,12) 픽셀이고 x는 (28,28) 픽셀이라서 이를 맞춰줘야한다. $\to$ camimg를 늘린다. - interpolation을 통해서 적당히 smoothing하여 작은 픽셀을 큰 픽셀로 확대한다.
plt.imshow(camimg.data, alpha = 0.5, extent = (0,28,28,0), interpolation = 'bilinear', cmap='magma') plt.imshow(x.squeeze(), cmap='gray',alpha=0.5) plt.imshow(camimg.data, alpha = 0.5, extent = (0,27,27,0), interpolation = 'bilinear', cmap='magma')
_____no_output_____
Apache-2.0
_notebooks/2021-10-26,28-{fastai_CNN}.ipynb
chchin33/violet