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
Copyright 2018 The TensorFlow Authors.
#@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/en/2/tutorials/eager/custom_layers.ipynb
allenlavoie/docs
Custom layers View on TensorFlow.org Run in Google Colab View source on GitHub We recommend using `tf.keras` as a high-level API for building neural networks. That said, most TensorFlow APIs are usable with eager execution.
!pip install tf-nightly-2.0-preview import tensorflow as tf
_____no_output_____
Apache-2.0
site/en/2/tutorials/eager/custom_layers.ipynb
allenlavoie/docs
Layers: common sets of useful operationsMost of the time when writing code for machine learning models you want to operate at a higher level of abstraction than individual operations and manipulation of individual variables.Many machine learning models are expressible as the composition and stacking of relatively simp...
# In the tf.keras.layers package, layers are objects. To construct a layer, # simply construct the object. Most layers take as a first argument the number # of output dimensions / channels. layer = tf.keras.layers.Dense(100) # The number of input dimensions is often unnecessary, as it can be inferred # the first time t...
_____no_output_____
Apache-2.0
site/en/2/tutorials/eager/custom_layers.ipynb
allenlavoie/docs
The full list of pre-existing layers can be seen in [the documentation](https://www.tensorflow.org/api_docs/python/tf/keras/layers). It includes Dense (a fully-connected layer),Conv2D, LSTM, BatchNormalization, Dropout, and many others.
# To use a layer, simply call it. layer(tf.zeros([10, 5])) # Layers have many useful methods. For example, you can inspect all variables # in a layer by calling layer.variables. In this case a fully-connected layer # will have variables for weights and biases. layer.variables # The variables are also accessible through...
_____no_output_____
Apache-2.0
site/en/2/tutorials/eager/custom_layers.ipynb
allenlavoie/docs
Implementing custom layersThe best way to implement your own layer is extending the tf.keras.Layer class and implementing: * `__init__` , where you can do all input-independent initialization * `build`, where you know the shapes of the input tensors and can do the rest of the initialization * `call`, where you do ...
class MyDenseLayer(tf.keras.layers.Layer): def __init__(self, num_outputs): super(MyDenseLayer, self).__init__() self.num_outputs = num_outputs def build(self, input_shape): self.kernel = self.add_variable("kernel", shape=[int(input_shape[-1]), ...
_____no_output_____
Apache-2.0
site/en/2/tutorials/eager/custom_layers.ipynb
allenlavoie/docs
Note that you don't have to wait until `build` is called to create your variables, you can also create them in `__init__`.Overall code is easier to read and maintain if it uses standard layers whenever possible, as other readers will be familiar with the behavior of standard layers. If you want to use a layer which is ...
class ResnetIdentityBlock(tf.keras.Model): def __init__(self, kernel_size, filters): super(ResnetIdentityBlock, self).__init__(name='') filters1, filters2, filters3 = filters self.conv2a = tf.keras.layers.Conv2D(filters1, (1, 1)) self.bn2a = tf.keras.layers.BatchNormalization() self.conv2b = tf....
_____no_output_____
Apache-2.0
site/en/2/tutorials/eager/custom_layers.ipynb
allenlavoie/docs
Much of the time, however, models which compose many layers simply call one layer after the other. This can be done in very little code using tf.keras.Sequential
my_seq = tf.keras.Sequential([tf.keras.layers.Conv2D(1, (1, 1)), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(2, 1, padding='same'), tf.keras.layers.BatchN...
_____no_output_____
Apache-2.0
site/en/2/tutorials/eager/custom_layers.ipynb
allenlavoie/docs
Next stepsNow you can go back to the previous notebook and adapt the linear regression example to use layers and models to be better structured.
_____no_output_____
Apache-2.0
site/en/2/tutorials/eager/custom_layers.ipynb
allenlavoie/docs
check_list = [1,1,5,7,9,6,4] sub_list = [1,1,5] print("original list : " +str (check_list)) print("original sublist : " +str (sub_list)) flag=0 if (set (sub_list).issubset(set (check_list))): flag = 1 if (flag): print("Its a Match.") else : rint("Its Gone")
original list : [1, 1, 5, 7, 9, 6, 4] original sublist : [1, 1, 5] Its a Match.
Apache-2.0
Day5 Assignment1.ipynb
Tulasi-ummadipolu/LetsUpgrade-Python-B7
Planewave propagation in a Whole-space (frequency-domain) PurposeWe visualizae downward propagating planewave in the homogeneous earth medium. With the three apps: a) Plane wave app, b) Profile app, and c) Polarization ellipse app, we understand fundamental concepts of planewave propagation. Set upPlanewave EM equa...
ax = plotObj3D()
_____no_output_____
MIT
notebooks/em/FDEM_Planewave_Wholespace.ipynb
jcapriot/geosci-labs
Planewave app Parameters:- Field: Type of EM fields ("Ex": electric field, "Hy": magnetic field)- AmpDir: Type of the vectoral EM fields None: $F_x$ or $F_y$ or $F_z$ Amp: $\mathbf{F} \cdot \mathbf{F}^* = |\mathbf{F}|^2$ Dir: Real part of a vectoral EM fields, $\Re[\mathbf{F}]$ - ComplexNumber: Ty...
dwidget = PlanewaveWidget() Q = dwidget.InteractivePlaneWave() display(Q)
_____no_output_____
MIT
notebooks/em/FDEM_Planewave_Wholespace.ipynb
jcapriot/geosci-labs
Profile appWe visualize EM fields at vertical profile (marked as red dots in the above app). Parameters:- **Field**: Ex, Hy, and Impedance - ** $\sigma$ **: Conductivity (S/m)- **Scale**: Log10 or Linear scale- **Fixed**: Fix the scale or not- **$f$**: Frequency- **$t$**: Time
display(InteractivePlaneProfile())
_____no_output_____
MIT
notebooks/em/FDEM_Planewave_Wholespace.ipynb
jcapriot/geosci-labs
Polarization Ellipse app
Polarwidget = PolarEllipse(); Polarwidget.Interactive()
_____no_output_____
MIT
notebooks/em/FDEM_Planewave_Wholespace.ipynb
jcapriot/geosci-labs
The 1cycle policy
from fastai.gen_doc.nbdoc import * from fastai import * from fastai.vision import *
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
What is 1cycle? This Callback allows us to easily train a network using Leslie Smith's 1cycle policy. To learn more about the 1cycle technique for training neural networks check out [Leslie Smith's paper](https://arxiv.org/pdf/1803.09820.pdf) and for a more graphical and intuitive explanation check out [Sylvain Gugger...
path = untar_data(URLs.MNIST_SAMPLE) data = ImageDataBunch.from_folder(path) model = simple_cnn((3,16,16,2)) learn = Learner(data, model, metrics=[accuracy])
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
First lets find the optimum learning rate for our comparison by doing an LR range test.
learn.lr_find() learn.recorder.plot()
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
Here 5e-2 looks like a good value, a tenth of the minimum of the curve. That's going to be the highest learning rate in 1cycle so let's try a constant training at that value.
learn.fit(2, 5e-2)
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
We can also see what happens when we train at a lower learning rate
model = simple_cnn((3,16,16,2)) learn = Learner(data, model, metrics=[accuracy]) learn.fit(2, 5e-3)
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
Training with the 1cycle policy Now to do the same thing with 1cycle, we use [`fit_one_cycle`](/train.htmlfit_one_cycle).
model = simple_cnn((3,16,16,2)) learn = Learner(data, model, metrics=[accuracy]) learn.fit_one_cycle(2, 5e-2)
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
This gets the best of both world and we can see how we get a far better accuracy and a far lower loss in the same number of epochs. It's possible to get to the same amazing results with training at constant learning rates, that we progressively diminish, but it will take a far longer time.Here is the schedule of the lr...
learn.recorder.plot_lr(show_moms=True) show_doc(OneCycleScheduler, doc_string=False)
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
Create a [`Callback`](/callback.htmlCallback) that handles the hyperparameters settings following the 1cycle policy for `learn`. `lr_max` should be picked with the [`lr_find`](/train.htmllr_find) test. In phase 1, the learning rates goes from `lr_max/div_factor` to `lr_max` linearly while the momentum goes from `moms[0...
show_doc(OneCycleScheduler.steps, doc_string=False)
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
Build the [`Stepper`](/callback.htmlStepper) for the [`Callback`](/callback.htmlCallback) according to `steps_cfg`.
show_doc(OneCycleScheduler.on_train_begin, doc_string=False)
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
Initiate the parameters of a training for `n_epochs`.
show_doc(OneCycleScheduler.on_batch_end, doc_string=False)
_____no_output_____
Apache-2.0
docs_src/callbacks.one_cycle.ipynb
fmgonzales/fastai
Maskinlæring med Python Michael Gfeller, Computasdag 3.2.2018![Computas](img/logo_blue_small.jpg)----_(Notebook basert på https://www.kaggle.com/futurist/pima-data-visualisation-and-machine-learning, [Apache 2.0 license](http://www.apache.org/licenses/LICENSE-2.0))_ Definer og forstå oppgaven
from IPython.display import YouTubeVideo YouTubeVideo("pN4HqWRybwk")
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Innsikt og forutsigelse om en kvinne fra Pima-folkestammen får diabetes innen 5 år. Last inn biblioteker
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Last inn og utforsk data
pima = pd.read_csv("diabetes.csv") # pandas.core.frame.DataFrame pima.head(4) pima.shape pima.info() pima.describe() pima.groupby("Outcome").size()
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Visualiser data Histogram
pima.hist(figsize=(10,10))
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Boxplot
pima.plot(kind= 'box' , subplots=True, layout=(3,3), sharex=False, sharey=False, figsize=(8,8)) X_columns = pima.columns[0:len(pima.columns) - 1] pima[X_columns].plot(kind= 'box', subplots=False, figsize=(20,8))
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Korrelasjon mellom variablene
correlations = pima[pima.columns].corr() sns.heatmap(correlations, annot = True)
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Velg input-variabler (features, givens, independent)
from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 X = pima.iloc[:,0:8] Y = pima.iloc[:,8] select_top_4 = SelectKBest(score_func=chi2, k = 4) fit = select_top_4.fit(X,Y) features = fit.transform(X) feature_cols = pima.columns[fit.get_support('indices')] feature_cols features[0:...
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Forbered data med standardisering
from sklearn.preprocessing import StandardScaler # En av flere scalers. X_features_scaled = StandardScaler().fit_transform(X_features) X = pd.DataFrame(data = X_features_scaled, columns= X_features.columns) X.head(3) X.hist() X.plot(kind= 'box', subplots=False, figsize=(20,8))
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Prøv ut forskjellige modeller - binærklassifisering
from sklearn.model_selection import train_test_split random_seed = 22 X_train,X_test,Y_train,Y_test = train_test_split(X,Y, random_state = random_seed, test_size = 0.2) from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from ...
LR : 77.69% +/- 5.23% NB : 76.05% +/- 5.94% KNN : 74.59% +/- 4.68% DT : 70.36% +/- 3.79% SVM : 77.69% +/- 5.15% LSVM : 77.85% +/- 5.24%
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Visualiser resultatene
ax = sns.boxplot(data=results) ax.set_xticklabels(names)
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Tren og valider de beste modellerLogistisk regresjon og (L)SVM ga de beste resultatene.
X_train.describe() Y_train_df = pd.DataFrame(data = Y_train, columns = ['Outcome']) Y_train_df.groupby("Outcome").size() X_test.describe() Y_test_df = pd.DataFrame(data = Y_test, columns = ['Outcome']) Y_test_df.groupby("Outcome").size()
_____no_output_____
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Logistisk regresjon
lr = LogisticRegression() lr.fit(X_train,Y_train) predictions = lr.predict(X_test) from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix print("%-5s: %.2f%%" % ("LR", accuracy_score(Y_test,predictions)*100))
LR : 71.43%
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Support Vector Classifier
svm = SVC() svm.fit(X_train,Y_train) predictions = svm.predict(X_test) print("%-5s: %.2f%%" % ("SVM", accuracy_score(Y_test,predictions)*100)) print(classification_report(Y_test,predictions)) # https://en.wikipedia.org/wiki/Confusion_matrix confusion = confusion_matrix(Y_test,predictions) # print(confusion) tn, fp, fn,...
True negatives: 92 True positives: 21 False negatives: 33 False positives: 8 Accuracy: 73% Precision: 72% Recall: 39%
Apache-2.0
ml-presentation/cx-pima-diabetes.ipynb
mgfeller/tensorflow
Table of Contents1  Load Data2  Demo of Cleaning Functions2.1  Columns2.2  Outliers2.3  Transformations
import datetime as dt import sys from pathlib import Path import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns print(sys.executable) print(sys.version) print(f"Pandas {pd.__version__}") print(f"Seaborn {sns.__version__}") sys.path.append(str(Path.cwd().parent / 'src' / 'codebook...
_____no_output_____
MIT
demo/dev_clean.ipynb
rbuerki/codebook
Load Data
df = pd.read_csv("../data/realWorldTestData.csv", low_memory=False, nrows=1000, usecols=[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 18] ) df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 14 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 target_event 1000 non-null object 1 NUM_CONSEC_SERVICES ...
MIT
demo/dev_clean.ipynb
rbuerki/codebook
Demo of Cleaning Functions Columns
# Prettify the column names df = clean.prettify_column_names(df) # Check result df.columns # Delete columns df_del = clean.delete_columns(df, cols_to_delete=["target_event", "first_evt"]) assert df_del.shape[1] == (df.shape[1] - 2) # Downcast dtypes df_lean = clean.downcast_dtypes(df) # Check result df_lean.dtyp...
Original df size before downcasting: 0.46 MB New df size after downcasting:0.16 MB
MIT
demo/dev_clean.ipynb
rbuerki/codebook
A word of Warning: Downcasting the numerical dtypes this way can lead to problems with the power transforms that are demonstrated below. That's why we continue with the original frame here. Outliers
# Count Outliers using the IQR-Method, with a distance of X clean.count_outliers_IQR_method(df, iqr_dist=2) # Remove outliers in two selected columns outlier_cols=["avg_diff_mnth", "mean_mileage_per_mnth"] df_outliers, deleted_idx = clean.remove_outliers_IQR_method( df, outlier_cols=outlier_cols, iqr_dis...
[(0.0, 4889.35), (1296.0, 171053.0)]
MIT
demo/dev_clean.ipynb
rbuerki/codebook
Transformations
df_transform = df[["last_mileage", "sum_invoice_amount", "mean_mileage_per_mnth"]]. copy() EDA.plot_distr_histograms(df_transform) df_log = clean.transform_data(df_transform, method="log") EDA.plot_distr_histograms(df_log) df_log10 = clean.transform_data(df_transform, method="log10") EDA.plot_distr_histograms(df_log...
_____no_output_____
MIT
demo/dev_clean.ipynb
rbuerki/codebook
Getting DataFirst, we want to grab some graphs and subject covariates from a web-accessible url. We've given this to you on google drive rather than having you set up aws s3 credentials in the interest of saving time. The original data is hosted at m2g.ioBelow, you will be getting the following dataset:| Property | V...
!pip install networkx==1.9 #networkx broke backwards compatibility with these graph files import numpy as np import networkx as nx import scipy as sp import matplotlib.pyplot as plt import os import csv import networkx.algorithms.centrality as nac from collections import OrderedDict # Initializing dataset names datas...
_____no_output_____
Apache-2.0
projects/graphexplorer/submissions/RonanDariusHamilton/graphexplore.ipynb
wrgr/intersession2018
ASSIGNMENT: (Code above used to get data in the correct format. Below is a simple example test string with kind of silly features)
#Combine features, separate training and test data X = [] for i in range(len(g1)): featvec = [] matrix = nx.to_numpy_matrix(g1[i], nodelist=sorted(g1[i].nodes())) #this is how you go to a matrix logmatrix = np.log10(np.sum(matrix,0) + 1) logmatrix = np.ravel(logmatrix) covariate1 = n...
_____no_output_____
Apache-2.0
projects/graphexplorer/submissions/RonanDariusHamilton/graphexplore.ipynb
wrgr/intersession2018
Raumluftqualität 2.0 Zeitliche Entwicklung der CO_2-Konzentration in RäumenIn einem gut gelüfteten, leeren Raum wird sich zunächst genau so viel CO_2 befinden, wie in der Außenluft. Wenn sich dann Personen in den Raum begeben und CO_2 freisetzen, wird die CO_2-Konzentration langsam zunehmen. Auf welchen Wert sie sich...
import matplotlib.pyplot as plt %config InlineBackend.figure_format = 'retina' import pandas as pd import numpy as np lt = np.linspace(0,120,13) # 10-min Schritte df = pd.DataFrame( { 't': lt, 'k': 400 + 1600*lt/60 # 60min = 1h } ) display(df.T) ax=df.plot(x='t',y='k', label='$k = k(t)$') ax.a...
_____no_output_____
MIT
Notebooks/Notebook_2.ipynb
w-meiners/rlt-rlq
__Word Alignment Assignment__Your task is to learn word alignments for the data provided with this Python Notebook. Start by running the 'train' function below and implementing the assertions which will fail. Then consider the following improvements to the baseline model:* Is the TranslationModel parameterized efficien...
# This cell contains the generative models that you may want to use for word alignment. # Currently only the TranslationModel is at all functional. import numpy as np from collections import defaultdict class TranslationModel: "Models conditional distribution over trg words given a src word." def __init__(se...
_____no_output_____
MIT
week09_mt/homework/word_alignment_assignment.ipynb
Holemar/nlp_course
数据网站,http://quotes.money.163.com/stock下载交易历史数据:http://quotes.money.163.com/cjmx/2019/20191120/1300127.xls,获得一个SCV文件。结构如下:成交时间,成交价,价格变动,成交量(手),成交额(元),性质09:30:06,17.2,-0.05,50,86011,卖盘09:30:09,17.21,0.01,887,1525626,买盘大概每3秒一条记录。 Library
import numpy as np import matplotlib.pyplot as plt import pandas as pd import torch import torch.nn as nn from torch.autograd import Variable from sklearn.preprocessing import MinMaxScaler from datetime import datetime
_____no_output_____
MIT
lstm-ashare-live.ipynb
sillyemperor/mypynotebook
Data Plot
data = pd.read_csv('data/ashare/30012720191120.csv', usecols = [0, 1, 3], converters={ 0:lambda x:datetime.strptime(x, '%H:%M:%S') }) # print(data) training_set = data.iloc[:,1].values timeline = data.iloc[:,0].values plt.plot(timeline, training_set, ) plt.show() def local_price(file): data = pd.read_csv(fil...
_____no_output_____
MIT
lstm-ashare-live.ipynb
sillyemperor/mypynotebook
1. Area plots are stacked by default. Ans: True. 2. The following code uses the artist layer to create a stacked area plot of the data in the pandas dataframe, area_df.
ax = series_df.plot(kind='area', figsize=(20, 10)) ax.title('Plot Title') ax.ylabel('Vertical Axis Label') ax.xlabel('Horizontal Axis Label')
_____no_output_____
MIT
Coursera/Data Visualization with Python-IBM/Week-2/Quiz/Basic-Visualization-Tools.ipynb
manipiradi/Online-Courses-Learning
Ans: False. 3. The following code will create an unstacked area plot of the data in the pandas dataframe, area_df, with a transparency value of 0.35?
import matplotlib.pyplot as plt transparency = 0.35 area_df.plot(kind='area', alpha=transparency, figsize=(20, 10)) plt.title('Plot Title') plt.ylabel('Vertical Axis Label') plt.xlabel('Horizontal Axis Label') plt.show()
_____no_output_____
MIT
Coursera/Data Visualization with Python-IBM/Week-2/Quiz/Basic-Visualization-Tools.ipynb
manipiradi/Online-Courses-Learning
Ans: False 4. The following code will create a histogram of a pandas series, series_data, and align the bin edges with the horizontal tick marks.
count, bin_edges = np.histogram(series_data) series_data.plot(kind='hist', xticks = bin_edges)
_____no_output_____
MIT
Coursera/Data Visualization with Python-IBM/Week-2/Quiz/Basic-Visualization-Tools.ipynb
manipiradi/Online-Courses-Learning
Using fuzzy wuzzy
# identieke notes die meerdere keren voorkomen from collections import Counter c = Counter() num_lines = 0 for note in notes: c[note] += 1 repeated = [] ns = [] for k, v in c.most_common(): if v > 1: num_lines += v print(repr(k), v) repeated.append(k) else: ns.append(k) pr...
_____no_output_____
Apache-2.0
notebooks/dbnl_remove_notes.ipynb
KBNLresearch/ochre
Using fuzzy wuzzy on all the notes at the same time
notes_text = ''.join(notes) print(notes_text) %%time from fuzzywuzzy import fuzz result = pd.DataFrame() result['pratio'] = [fuzz.partial_ratio(l, notes_text) for l in lines] result.head() result.hist(bins=100) n = 42 print(lines[n]) print(result.loc[n]) print(notes[0]) fuzz.partial_ratio(lines[42], notes[0]) fuzz.par...
_____no_output_____
Apache-2.0
notebooks/dbnl_remove_notes.ipynb
KBNLresearch/ochre
Putting it all together
%%time from nlppln.utils import create_dirs, out_file_name in_file = '/home/jvdzwaan/data/dbnl_ocr/raw/ocr-with-title-page/_aio001jver01_01.txt' # remove selected lines with open(in_file) as f: text = f.read() for n in ns: for idx in n['selected']: #print(idx) l = lines[idx] ...
_____no_output_____
Apache-2.0
notebooks/dbnl_remove_notes.ipynb
KBNLresearch/ochre
用函數取代表格用簡單的神經網路來取代 V
import numpy as np from keras.models import Sequential from keras.layers import Dense from gridworld import GridWorld blocks={(1,1), (3,3)} gw = GridWorld(size=(5,5), start=(0,0), exit=(4,4), blocks=blocks) from ipywidgets import widgets as W from IPython.display import display gw_html = W.HTML(value=gw._repr_html_()) ...
_____no_output_____
MIT
RL/Grid World-Function.ipynb
PinmanHuang/CrashCourseML
使用 Q learningQ 用簡單的神經網路來定義
Q = Sequential() Q.add(Dense(128, input_shape=((gw.size[0]+2)*(gw.size[1]+2)+4,), activation="relu" )) # 輸入是 i, j 座標和 a Q.add(Dense(1, activation="tanh")) # 因為輸出是 +-1 Q.compile(loss='mse',optimizer='sgd', metrics=['accuracy']) avectors = [[0]* 4 for i in range(4)] for i in range(4): avectors[i][i]=1 def Qfunc(i,j...
_____no_output_____
MIT
RL/Grid World-Function.ipynb
PinmanHuang/CrashCourseML
Задача определения частей речи, Part-Of-Speech Tagger (POS) Мы будем решать задачу определения частей речи (POS-теггинга).
import nltk import pandas as pd import numpy as np from nltk.corpus import brown import matplotlib.pyplot as plt
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Вам в помощь http://www.nltk.org/book/ Загрузим brown корпус
nltk.download('brown')
[nltk_data] Downloading package brown to /root/nltk_data... [nltk_data] Unzipping corpora/brown.zip.
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Существует не одна система тегирования, поэтому будьте внимательны, когда прогнозируете тег слов в тексте и вычисляете качество прогноза. Можете получить несправедливо низкое качество вашего решения. Cейчас будем использовать универсальную систему тегирования universal_tagset
nltk.download('universal_tagset')
[nltk_data] Downloading package universal_tagset to /root/nltk_data... [nltk_data] Unzipping taggers/universal_tagset.zip.
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Мы имеем массив предложений пар (слово-тег)
brown_tagged_sents = brown.tagged_sents(tagset="universal") brown_tagged_sents
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Первое предложение
brown_tagged_sents[0]
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Все пары (слово-тег)
brown_tagged_words = brown.tagged_words(tagset='universal') brown_tagged_words
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Проанализируйте данные, с которыми Вы работаете. Используйте `nltk.FreqDist()` для подсчета частоты встречаемости тега и слова в нашем корпусе. Под частой элемента подразумевается кол-во этого элемента в корпусе.
# Приведем слова к нижнему регистру brown_tagged_words = list(map(lambda x: (x[0].lower(), x[1]), brown_tagged_words)) print('Кол-во предложений: ', len(brown_tagged_sents)) tags = [tag for (word, tag) in brown_tagged_words] # наши теги words = [word for (word, tag) in brown_tagged_words] # наши слова tag_num = pd.Ser...
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Вопрос 1:* Кол-во слова `cat` в корпусе? **(0.5 балл)**
word_num["cat"]
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Вопрос 2:* Самое популярное слово с самым популярным тегом? **(0.5 балл)**
# Выбираем сначала слова с самым популярным тегом, а затем среди них выбираем самое популярное слово. lst = [word for (word, tag) in brown_tagged_words if tag == "NOUN"] popular = pd.Series(nltk.FreqDist(lst)).sort_values(ascending=False) print(popular) # time - Самое популярное слово с самым популярным тегом "NOUN"
time 1597 man 1203 af 995 years 949 way 899 ... anti-communists 1 peace-treaty 1 malinovsky 1 eleventh-floor 1 boucle 1 Length: 30246, dtype: int64
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Cделайте разбиение выборки на обучение и контроль в отношении 9:1. **(0.5 балл)**
brown_tagged_sents = brown.tagged_sents(tagset="universal") # Приведем слова к нижнему регистру my_brown_tagged_sents = [] for sent in brown_tagged_sents: my_brown_tagged_sents.append(list(map(lambda x: (x[0].lower(), x[1]), sent))) my_brown_tagged_sents = np.array(my_brown_tagged_sents) from sklearn.model_selecti...
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
DefaultTagger Вопрос 3:* Какое качество вы бы получили, если бы предсказывали любой тег, как самый популярный тег на выборке train(округлите до одного знака после запятой)? **(0.5 балл)** Вы можете использовать DefaultTagger(метод tag для предсказания частей речи предложения).
from nltk.tag import DefaultTagger default_tagger = DefaultTagger("NOUN") true_pred = 0 num_pred = 0 for sent in test_sents: tags = np.array([tag for (word, tag) in sent]) words = np.array([word for (word, tag) in sent]) tagged_sent = default_tagger.tag(words) outputs = [tag for token, tag in tagged_s...
Accuracy: 23.47521651004238 %
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
если бы предсказывали любой тег, как самый популярный тег на выборке train: 15,86% - VERB LSTMTagger Подготовка данных Изменим структуру данных
pos_data = [list(zip(*sent)) for sent in brown_tagged_sents] print(pos_data[0])
[('The', 'Fulton', 'County', 'Grand', 'Jury', 'said', 'Friday', 'an', 'investigation', 'of', "Atlanta's", 'recent', 'primary', 'election', 'produced', '``', 'no', 'evidence', "''", 'that', 'any', 'irregularities', 'took', 'place', '.'), ('DET', 'NOUN', 'NOUN', 'ADJ', 'NOUN', 'VERB', 'NOUN', 'DET', 'NOUN', 'ADP', 'NOUN'...
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Пора эксплуатировать pytorch!
from torchtext.data import Field, BucketIterator import torchtext # наши поля WORD = Field(lower=True) TAG = Field(unk_token=None) # все токены нам извсетны # создаем примеры examples = [] for words, tags in pos_data: examples.append(torchtext.data.Example.fromlist([list(words), list(tags)], fields=[('words', WOR...
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Вот один наш пример:
print(vars(examples[0]))
{'words': ['the', 'fulton', 'county', 'grand', 'jury', 'said', 'friday', 'an', 'investigation', 'of', "atlanta's", 'recent', 'primary', 'election', 'produced', '``', 'no', 'evidence', "''", 'that', 'any', 'irregularities', 'took', 'place', '.'], 'tags': ['DET', 'NOUN', 'NOUN', 'ADJ', 'NOUN', 'VERB', 'NOUN', 'DET', 'NOU...
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Теперь формируем наш датасет
# кладем примеры в наш датасет dataset = torchtext.data.Dataset(examples, fields=[('words', WORD), ('tags', TAG)]) train_data, valid_data, test_data = dataset.split(split_ratio=[0.8, 0.1, 0.1]) print(f"Number of training examples: {len(train_data.examples)}") print(f"Number of validation examples: {len(valid_data.exa...
Number of training examples: 45872 Number of validation examples: 5734 Number of testing examples: 5734
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Построим словари. Параметр `min_freq` выберете сами. При построении словаря испольузем только **train** **(0.5 балл)**
WORD.build_vocab(train_data, min_freq=10) TAG.build_vocab(train_data) print(f"Unique tokens in source (ru) vocabulary: {len(WORD.vocab)}") print(f"Unique tokens in target (en) vocabulary: {len(TAG.vocab)}") print(WORD.vocab.itos[::200]) print(TAG.vocab.itos)
Unique tokens in source (ru) vocabulary: 7316 Unique tokens in target (en) vocabulary: 13 ['<unk>', 'number', 'available', 'miles', 'clearly', 'corps', 'quickly', 'b.', 'resolution', 'review', 'orchestra', 'occasionally', 'warfare', 'bread', "nation's", 'tested', 'visitors', 'accident', 'sovereign', 'gesture', 'sharpe'...
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Здесь вы увидете токен `unk` и `pad`. Первый служит для обозначения слов, которых у нас нет в словаре. Второй служит для того, что объекты в одном батче были одинакового размера.
print(vars(train_data.examples[9]))
{'words': ['there', 'was', 'a', 'contorted', 'ugliness', 'now', ';', ';'], 'tags': ['PRT', 'VERB', 'DET', 'VERB', 'NOUN', 'ADV', '.', '.']}
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Посмотрим с насколько большими предложениями мы имеем дело
length = map(len, [vars(x)['words'] for x in train_data.examples]) plt.figure(figsize=[8, 4]) plt.title("Length distribution in Train data") plt.hist(list(length), bins=20);
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Для обучения `LSTM` лучше использовать colab
import torch from torch import nn import torch.nn.functional as F import torch.optim as optim device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') device
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Для более быстрого и устойчивого обучения сгруппируем наши данные по батчам
# бьем нашу выборку на батч, не забывая сначала отсортировать выборку по длине def _len_sort_key(x): return len(x.words) BATCH_SIZE = 64 train_iterator, valid_iterator, test_iterator = BucketIterator.splits( (train_data, valid_data, test_data), batch_size = BATCH_SIZE, device = device, sort_key=...
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Модель и её обучение Инициализируем нашу модель. Прочитайте про dropout [тут](https://habr.com/ru/company/wunderfund/blog/330814/). **(3 балла)**
class LSTMTagger(nn.Module): def __init__(self, input_dim, emb_dim, hid_dim, output_dim, dropout): super().__init__() self.embeddings = nn.Embedding(num_embeddings=input_dim, embedding_dim=emb_dim) self.dropout = nn.Dropout(p=dropout) self.rnn = nn.LSTM(emb_dim,...
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Подсчитаем количество обучаемых параметров нашей модели. Используйте метод `numel()`. **(1 балл)**
def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print(f'The model has {count_parameters(model):,} trainable parameters')
The model has 37,403 trainable parameters
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Погнали обучать **(2 балла)**
PAD_IDX = TAG.vocab.stoi['<pad>'] optimizer = optim.Adam(model.parameters()) criterion = nn.CrossEntropyLoss(ignore_index = PAD_IDX) def train(model, iterator, optimizer, criterion, clip, train_history=None, valid_history=None): model.train() epoch_loss = 0 history = [] for i, batch in enumerate(i...
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Применение модели **(1 балл)**
def accuracy_model(model, iterator): model.eval() true_pred = 0 num_pred = 0 with torch.no_grad(): for i, batch in enumerate(iterator): words = batch.words tags = batch.tags output = model(words) #output = [sent len, batch ...
Accuracy: 92.797 %
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Вы можете улучшить качество, изменяя параметры модели. Вам неоходимо добиться качества не меньше, чем `accuracy = 92 %`.
best_model = LSTMTagger(INPUT_DIM, EMB_DIM, HID_DIM, OUTPUT_DIM, DROPOUT).to(device) best_model.load_state_dict(torch.load('/content/best-val-model.pt')) assert accuracy_model(best_model, test_iterator) >= 92
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
**Если качество сети меньше 92 процентов, то снимается половина от всех полученных баллов . То есть максимум в этом случае 5 баллов за работу.** Пример решение нашей задачи:
def print_tags(model, data): model.eval() with torch.no_grad(): words, _ = data example = torch.LongTensor([WORD.vocab.stoi[elem] for elem in words]).unsqueeze(1).to(device) output = model(example).argmax(dim=-1).cpu().numpy() tags = [TAG.vocab.itos[int(elem)] for e...
From NOUN what DET I NOUN was VERB able ADJ to PRT gauge NOUN in ADP a DET swift ADJ , . greedy NOUN glance NOUN , . the DET figure NOUN inside ...
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
Вывод: **(0.5 балл)**Правильный подбор параметров дает большую точность, также достаточное количество эпох позволяет достичь хорошей точности, однако модель может переобучится
_____no_output_____
MIT
FastStart/module_3_pos_tag.ipynb
Xrenya/RuCode2020
UI for your Machine Learning model Install Gradio
pip install gradio
Requirement already satisfied: gradio in d:\anaconda3\lib\site-packages (1.2.3) Requirement already satisfied: flask in d:\anaconda3\lib\site-packages (from gradio) (1.1.2) Requirement already satisfied: numpy in d:\anaconda3\lib\site-packages (from gradio) (1.18.5) Requirement already satisfied: analytics-python in d:...
MIT
ui-for-ml-using-gradio.ipynb
rajtilak82/how-machines-learn
Import the required libraries
import gradio as gr # for creating the UI import numpy as np # for preprocessing images import requests # for downloading human readable labels from keras.applications.vgg16 import VGG16 # VGG16 model from keras.applications.vgg16 import preprocess_input # VGG16 preprocessing function
_____no_output_____
MIT
ui-for-ml-using-gradio.ipynb
rajtilak82/how-machines-learn
Loading the model
vgg_model = VGG16()
_____no_output_____
MIT
ui-for-ml-using-gradio.ipynb
rajtilak82/how-machines-learn
Download the human readable labels
response = requests.get("https://raw.githubusercontent.com/gradio-app/mobilenet-example/master/labels.txt") labels = response.text.split("\n")
_____no_output_____
MIT
ui-for-ml-using-gradio.ipynb
rajtilak82/how-machines-learn
Creating the classification pipeline
# this pipeline returns a dictionary with key as label and # values as the predicted confidence for that label def classify_image(image): image = image.reshape((-1, 224, 224, 3)) # reshaping the image image = preprocess_input(image) # prepare the image for the VGG16 model prediction = vgg_model.predict(i...
_____no_output_____
MIT
ui-for-ml-using-gradio.ipynb
rajtilak82/how-machines-learn
Initializing the input and output components
image = gr.inputs.Image(shape = (224, 224, 3)) label = gr.outputs.Label(num_top_classes = 3) # predicts the top 3 classes
_____no_output_____
MIT
ui-for-ml-using-gradio.ipynb
rajtilak82/how-machines-learn
Launching the Gradio interface with our VGG16 model
gr.Interface(fn = classify_image, inputs = image, outputs = label, capture_session = True).launch()
Running locally at: http://127.0.0.1:7860/ To get a public link for a hosted model, set Share=True Interface loading below...
MIT
ui-for-ml-using-gradio.ipynb
rajtilak82/how-machines-learn
Activation Function
# Previous lecture we learn about neuron on action, but what actually is neuron ? # Every neuron have a weight, and they calculate the weight using activation function. # In this code, you will learn about 4 different activation function.
_____no_output_____
Apache-2.0
Day_2_Activation_Function.ipynb
LukasPurbaW/100_Days_of_Deep_Learning
Threshold Function
import numpy as np import matplotlib.pyplot as plt import numpy as np def binaryStep(x): ''' It returns '0' is the input is less then zero otherwise it returns one ''' return np.heaviside(x,1) x = np.linspace(-10, 10) plt.plot(x, binaryStep(x)) plt.axis('tight') plt.title('Activation Function (Threshold Funct...
_____no_output_____
Apache-2.0
Day_2_Activation_Function.ipynb
LukasPurbaW/100_Days_of_Deep_Learning
Sigmoid Function
def sigmoid(x): ''' It returns 1/(1+exp(-x)). where the values lies between zero and one ''' return 1/(1+np.exp(-x)) x = np.linspace(-10, 10) plt.plot(x, sigmoid(x)) plt.axis('tight') plt.title('Activation Function (Sigmoid)') plt.show() ## The output is equal to 1/(1+np.exp(-x)). Unlike threshold functions, t...
_____no_output_____
Apache-2.0
Day_2_Activation_Function.ipynb
LukasPurbaW/100_Days_of_Deep_Learning
Rectifier or Relu
def RELU(x): ''' It returns zero if the input is less than zero otherwise it returns the given input. ''' x1=[] for i in x: if i<0: x1.append(0) else: x1.append(i) return x1 x = np.linspace(-10, 10) plt.plot(x, RELU(x)) plt.axis('tight') plt.title('Activation Fun...
_____no_output_____
Apache-2.0
Day_2_Activation_Function.ipynb
LukasPurbaW/100_Days_of_Deep_Learning
Hyperpolic or Tanh Function
def tanh(x): ''' It returns the value (1-exp(-2x))/(1+exp(-2x)) and the value returned will be lies in between -1 to 1.''' return np.tanh(x) x = np.linspace(-10, 10) plt.plot(x, tanh(x)) plt.axis('tight') plt.title('Activation Function (Tanh)') plt.show() ## This return the minimum value of -1 and maximum value...
_____no_output_____
Apache-2.0
Day_2_Activation_Function.ipynb
LukasPurbaW/100_Days_of_Deep_Learning
Softmax Function
def softmax(x): ''' Compute softmax values for each sets of scores in x. ''' return np.exp(x) / np.sum(np.exp(x), axis=0) x = np.linspace(-10, 10) plt.plot(x, softmax(x)) plt.axis('tight') plt.title('Activation Function :Softmax') plt.show() ## Sigmoid is a smooth graphic like sigmoid. Often used in multiclass ...
_____no_output_____
Apache-2.0
Day_2_Activation_Function.ipynb
LukasPurbaW/100_Days_of_Deep_Learning
Model Evaluation and RefinementEstimated time needed: **30** minutes ObjectivesAfter completing this lab you will be able to:- Evaluate and refine prediction models Table of content Model Evaluation Over-fitting, Under-fitting and Model Selection Ridge Regression Grid Search This dataset was hoste...
import pandas as pd import numpy as np # Import clean data path = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/module_5_auto.csv' df = pd.read_csv(path) df.to_csv('module_5_auto.csv')
_____no_output_____
MIT
DA0101EN/.ipynb_checkpoints/model-evaluation-and-refinement-checkpoint.ipynb
alekhaya99/IBM-CLOUD-SQL-AND-PYTHON
First lets only use numeric data
df=df._get_numeric_data() df.head()
_____no_output_____
MIT
DA0101EN/.ipynb_checkpoints/model-evaluation-and-refinement-checkpoint.ipynb
alekhaya99/IBM-CLOUD-SQL-AND-PYTHON
Libraries for plotting
%%capture ! pip install ipywidgets from ipywidgets import interact, interactive, fixed, interact_manual
_____no_output_____
MIT
DA0101EN/.ipynb_checkpoints/model-evaluation-and-refinement-checkpoint.ipynb
alekhaya99/IBM-CLOUD-SQL-AND-PYTHON
Functions for plotting
def DistributionPlot(RedFunction, BlueFunction, RedName, BlueName, Title): width = 12 height = 10 plt.figure(figsize=(width, height)) ax1 = sns.distplot(RedFunction, hist=False, color="r", label=RedName) ax2 = sns.distplot(BlueFunction, hist=False, color="b", label=BlueName, ax=ax1) plt.title(...
_____no_output_____
MIT
DA0101EN/.ipynb_checkpoints/model-evaluation-and-refinement-checkpoint.ipynb
alekhaya99/IBM-CLOUD-SQL-AND-PYTHON
Part 1: Training and TestingAn important step in testing your model is to split your data into training and testing data. We will place the target data price in a separate dataframe y:
y_data = df['price']
_____no_output_____
MIT
DA0101EN/.ipynb_checkpoints/model-evaluation-and-refinement-checkpoint.ipynb
alekhaya99/IBM-CLOUD-SQL-AND-PYTHON