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
Performance Analysis One of the advantages of theano is the posibility to create a full profile of the function. This has to be included in at the time of the creation of the function. At the moment it should be active (the downside is larger compilation time and I think also a bit in the computation so be careful if ...
%%timeit # Compute the block GeMpy.compute_block_model(geo_data, [0,1,2], verbose = 0) geo_data.interpolator._interpolate.profile.summary()
Function profiling ================== Message: ../GeMpy/DataManagement.py:994 Time in 3 calls to Function.__call__: 8.400567e-01s Time in Function.fn.__call__: 8.395956e-01s (99.945%) Time in thunks: 8.275988e-01s (98.517%) Total compile time: 3.540267e+00s Number of Apply nodes: 342 Theano Optimizer ...
MIT
Prototype Notebook/Example_1_Sandstone.ipynb
nre-aachen/gempy
Ungraded Lab: Activation in Custom LayersIn this lab, we extend our knowledge of building custom layers by adding an activation parameter. The implementation is pretty straightforward as you'll see below. Imports
try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import tensorflow as tf from tensorflow.keras.layers import Layer
_____no_output_____
MIT
C1W3_L3_CustomLayerWithActivation.ipynb
100rab-S/TensorFlow-Advanced-Techniques
Adding an activation layerTo use the built-in activations in Keras, we can specify an `activation` parameter in the `__init__()` method of our custom layer class. From there, we can initialize it by using the `tf.keras.activations.get()` method. This takes in a string identifier that corresponds to one of the [availab...
class SimpleDense(Layer): # add an activation parameter def __init__(self, units=32, activation=None): super(SimpleDense, self).__init__() self.units = units # define the activation to get from the built-in activation layers in Keras self.activation = tf.keras.activatio...
_____no_output_____
MIT
C1W3_L3_CustomLayerWithActivation.ipynb
100rab-S/TensorFlow-Advanced-Techniques
We can now pass in an activation parameter to our custom layer. The string identifier is mostly the same as the function name so 'relu' below will get `tf.keras.activations.relu`.
mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), SimpleDense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.laye...
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 0s 0us/step Epoch 1/5 1875/1875 [==============================] - 5s 2ms/step - loss: 0.4861 - accuracy: 0.8560 Epoch 2/5 1875/1875 [==============================] - 4s 2ms/...
MIT
C1W3_L3_CustomLayerWithActivation.ipynb
100rab-S/TensorFlow-Advanced-Techniques
Using Google Cloud Functions to support event-based triggering of Cloud AI Platform Pipelines> This post shows how you can run a Cloud AI Platform Pipeline from a Google Cloud Function, providing a way for Pipeline runs to be triggered by events.- toc: true - badges: true- comments: true- categories: [ml, pipelines, m...
%env TRIGGER_BUCKET=REPLACE_WITH_YOUR_GCS_BUCKET_NAME
_____no_output_____
Apache-2.0
_notebooks/2020-05-12-hosted_kfp_gcf.ipynb
amygdala/fastpages
Give Cloud Function's service account the necessary accessFirst, make sure the Cloud Function API [is enabled](https://console.cloud.google.com/apis/library/cloudfunctions.googleapis.com?q=functions).Cloud Functions uses the project's 'appspot' acccount for its service account. It will have the form: `PROJECT_ID@apps...
%%bash mkdir -p functions
_____no_output_____
Apache-2.0
_notebooks/2020-05-12-hosted_kfp_gcf.ipynb
amygdala/fastpages
We'll first create a `requirements.txt` file, to indicate what packages the GCF code requires to be installed. (We won't actually need `kfp` for this first 'sanity check' version of a GCF function, but we'll need it below for the second function we'll create, that deploys a pipeline).
%%writefile functions/requirements.txt kfp
_____no_output_____
Apache-2.0
_notebooks/2020-05-12-hosted_kfp_gcf.ipynb
amygdala/fastpages
Next, we'll create a simple GCF function in the `functions/main.py` file:
%%writefile functions/main.py import logging def gcs_test(data, context): """Background Cloud Function to be triggered by Cloud Storage. This generic function logs relevant data when a file is changed. Args: data (dict): The Cloud Functions event payload. context (google.cloud.functions.Context):...
_____no_output_____
Apache-2.0
_notebooks/2020-05-12-hosted_kfp_gcf.ipynb
amygdala/fastpages
Deploy the GCF function as follows. (You'll need to **wait a moment or two for output of the deployment to display in the notebook**). You can also run this command from a notebook terminal window in the `functions` subdirectory.
%%bash cd functions gcloud functions deploy gcs_test --runtime python37 --trigger-resource ${TRIGGER_BUCKET} --trigger-event google.storage.object.finalize
_____no_output_____
Apache-2.0
_notebooks/2020-05-12-hosted_kfp_gcf.ipynb
amygdala/fastpages
After you've deployed, test your deployment by adding a file to the specified `TRIGGER_BUCKET`. You can do this easily by visiting the **Storage** panel in the Cloud Console, clicking on the bucket in the list, and then clicking on **Upload files** in the bucket details view.Then, check in the logs viewer panel (https:...
%%bash cd functions mv main.py main.py.bak
_____no_output_____
Apache-2.0
_notebooks/2020-05-12-hosted_kfp_gcf.ipynb
amygdala/fastpages
Then, **before executing the next cell**, **edit the `HOST` variable** in the code below. You'll replace `` with the correct value for your installation.To find this URL, visit the [Pipelines panel](https://console.cloud.google.com/ai-platform/pipelines/) in the Cloud Console. From here, you can find the URL by click...
%%writefile functions/main.py import logging import datetime import logging import time import kfp import kfp.compiler as compiler import kfp.dsl as dsl import requests # TODO: replace with your Pipelines endpoint URL HOST = 'https://<your_endpoint>.pipelines.googleusercontent.com' @dsl.pipeline( name='Seque...
_____no_output_____
Apache-2.0
_notebooks/2020-05-12-hosted_kfp_gcf.ipynb
amygdala/fastpages
Next, deploy the new GCF function. As before, **it will take a moment or two for the results of the deployment to display in the notebook**.
%%bash cd functions gcloud functions deploy hosted_kfp_test --runtime python37 --trigger-resource ${TRIGGER_BUCKET} --trigger-event google.storage.object.finalize
_____no_output_____
Apache-2.0
_notebooks/2020-05-12-hosted_kfp_gcf.ipynb
amygdala/fastpages
Herramientas Estadisticas Contenido:1.Estadistica: - Valor medio. - Mediana. - Desviacion estandar. 2.Histogramas: - Histrogramas con python. - Histogramas con numpy. - Como normalizar un histograma. 3.Distribuciones: - Como obtener una distribucion a partir de un histograma. ...
import matplotlib.pyplot as plt import numpy as np # %pylab inline def mi_mediana(lista): x = sorted(lista) d = int(len(x)/2) if(len(x)%2==0): return (x[d-1] + x[d])*0.5 else: return x[d-1] x_input = [1,3,4,5,5,7,7,6,8,6] mi_mediana(x_input) print(mi_mediana(x_input) == np.median...
True
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Problemas de no saber estadísticaEste tipo de conceptos parecen sencillos. Pero no siempre son claros para todo el mundo.
x = np.arange(1, 12) y = np.random.random(11)*10 plt.figure(figsize=(12, 5)) fig = plt.subplot(1, 2, 1) plt.scatter(x, y, c='purple', alpha=0.8, s=60) y_mean = np.mean(y) y_median = np.median(y) plt.axhline(y_mean, c='g', lw=3, label=r"$\rm{Mean}$") plt.axhline(y_median, c='r', lw=3, label=r"$\rm{Median}$") plt.legend(...
[9.33745032 0.46206052 3.07349261 8.65709198 6.44733954 2.5552359 8.93987727 8.24695437 5.62111292 4.64621772 0.05366015]
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Desviacion estandarEs el promedio de las incertidumbres de las mediciones $x_i$$\sigma = \sqrt{\dfrac{1}{n-1} \sum(x_{i} - \bar{x})^2}$Donde $n$ es el número de la muestraAdicionalmente la ${\bf{varianza}}$ se define como:$\bar{x^2} - \bar{x}^{2}$$\sigma^2 = \dfrac{1}{N} \sum(x_{i} - \bar{x})^2$Y es una medida similar...
x = np.arange(1, 12) y = np.random.random(11)*10 plt.figure(figsize=(9, 5)) y_mean = np.mean(y) y_median = np.median(y) plt.axhline(y_mean, c='g', lw=3, label=r"$\rm{Mean}$") plt.axhline(y_median, c='r', lw=3, label=r"$\rm{Median}$") sigma_y = np.std(y) plt.axhspan(y_mean-sigma_y, y_mean + sigma_y, facecolor='g', alpha...
Variancia = 7.888849132964844 Desviacion estandar = 2.8087095138096507
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Referencias: Para mas funciones estadisticas que se pueden usar en python ver: - NumPy: http://docs.scipy.org/doc/numpy/reference/routines.statistics.html- SciPy: http://docs.scipy.org/doc/scipy/reference/stats.html Histogramas 1. histhist es una funcion de python que genera un histograma a partir de un array ...
x = np.random.random(200) plt.subplot(2,2,1) plt.title("A simple hist") h = plt.hist(x) plt.subplot(2,2,2) plt.title("bins") h = plt.hist(x, bins=20) plt.subplot(2,2,3) plt.title("alpha") h = plt.hist(x, bins=20, alpha=0.6) plt.subplot(2,2,4) plt.title("histtype") h = plt.hist(x, bins=20, alpha=0.6, histtype='stepfille...
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
2. Numpy-histogram
N, bins = np.histogram(caras, bins=15) plt.plot(bins[0:-1], N)
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Histogramas 2D
x = np.random.random(500) y = np.random.random(500) plt.subplot(4, 2, 1) plt.hexbin(x, y, gridsize=15, cmap="gray") plt.colorbar() plt.subplot(4, 2, 2) data = plt.hist2d(x, y, bins=15, cmap="binary") plt.colorbar() plt.subplot(4, 2, 3) plt.hexbin(x, y, gridsize=15) plt.colorbar() plt.subplot(4, 2, 4) data = plt.hist2d...
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Como normalizar un histograma. Normalizar un histograma significa que la integral del histograma sea 1.
x = np.random.random(10)*4 plt.title("Como no normalizar un histograma", fontsize=25) h = plt.hist(x, normed="True") print ("El numero tamaño del bin debe de ser de la unidad") plt.title("Como normalizar un histograma", fontsize=25) h = hist(x, normed="True", bins=4)
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Cual es la probabilidad de sacar 9 veces cara en 10 lanzamientos? Distribución de Probabilidad:Las distribuciones de probabilidad dan información de cual es la probabilidad de que una variable aleatoria $x$ aprezca en un intervalo dado. ¿Si tenemos un conjunto de datos como podemos conocer la distribucion de probabili...
x = np.random.random(100)*10 plt.subplot(1, 2, 1) h = plt.hist(x) plt.subplot(1, 2, 2) histo, bin_edges = np.histogram(x, density=True) plt.bar(bin_edges[:-1], histo, width=1) plt.xlim(min(bin_edges), max(bin_edges))
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Distribución Normal: Descripcion Matemática.$f(x, \mu, \sigma) = \dfrac{1}{\sigma \sqrt(2\pi)} e^{-\dfrac{(x-\mu)^2}{2\sigma^2}} $donde $\sigma$ es la desviacion estandar y $\mu$ la media de los datos $x$Es una función de distribucion de probabilidad que esta totalmente determinada por los parametros $\mu$ y $\sigma$....
import scipy.stats x = np.linspace(0, 1, 100) n_dist = scipy.stats.norm(0.5, 0.1) plt.plot(x, n_dist.pdf(x))
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Podemos generar numeros aleatorios con una distribucion normal:
x = np.random.normal(0.0, 1.0, 1000) y = np.random.normal(0.0, 2.0, 1000) w = np.random.normal(0.0, 3.0, 1000) z = np.random.normal(0.0, 4.0, 1000) histo = plt.hist(z, alpha=0.2, histtype="stepfilled", color='r') histo = plt.hist(w, alpha=0.4, histtype="stepfilled", color='b') histo = plt.hist(y, alpha=0.6, histtype="s...
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
**Intervalo de confianza**$\sigma_1$ = 68% de los datos van a estar dentro de 1$\sigma$$\sigma_2$ = 95% de los datos van a estar dentro de 2$\sigma$$\sigma_3$ = 99.7% de los datos van a estar dentro de 3$\sigma$ Ejercicio: Generen distribuciones normales con:- $\mu = 5$ y $\sigma = 2$ - $\mu = -3$ y $\sigma = -2$- $\m...
def coinflip(N): cara = 0 sello = 0 i=0 while i < N: x = np.random.randint(0, 10)/5.0 if x >= 1.0: cara+=1 elif x<1.0: sello+=1 i+=1 return cara/N, sello/N
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
Función que hace M veces N lanzamientos.
def realizaciones(M, N): caras=[] for i in range(M): x, y = coinflip(N) caras.append(x) return caras hist(caras, normed=True, bins=20) caras = realizaciones(100000, 30.)
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
PDF
N, bins = np.histogram(x, density=True) plt.plot(bins[0:-1], N)
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
CDF
h = plt.hist(x, cumulative=True, bins=20)
_____no_output_____
MIT
Notebooks/python 9 - Herramientas_Estadisticas.ipynb
diegour1/HerramientasComputacionales
01 - Sentence Classification Model Building Parse & clearn labeled training data
import xml.etree.ElementTree as ET tree = ET.parse('../data/Restaurants_Train.xml') root = tree.getroot() root # Use this dataframe for multilabel classification # Must use scikitlearn's multilabel binarizer labeled_reviews = [] for sentence in root.findall("sentence"): entry = {} aterms = [] aspects = [] ...
_____no_output_____
Apache-2.0
04-Aspect_Based_Opinion_Mining/code/01-Build_Model.ipynb
ayan1995/DS_projects
Training the model with Naive Bayes1. replace pronouns with neural coref2. train the model with naive bayes
from neuralcoref import Coref import en_core_web_lg spacy = en_core_web_lg.load() coref = Coref(nlp=spacy) # Define function for replacing pronouns using neuralcoref def replace_pronouns(text): coref.one_shot_coref(text) return coref.get_resolved_utterances()[0] # Read annotated reviews df, which is the labele...
_____no_output_____
Apache-2.0
04-Aspect_Based_Opinion_Mining/code/01-Build_Model.ipynb
ayan1995/DS_projects
At this point, we can move on to 02-Sentiment analysis notebook, which will load the fitted Naive bayes model.
#mlb.inverse_transform(predicted) pred_df = pd.DataFrame( {'text_pro': X_test, 'pred_category': mlb.inverse_transform(predicted) }) pd.set_option('display.max_colwidth', -1) pred_df.head()
_____no_output_____
Apache-2.0
04-Aspect_Based_Opinion_Mining/code/01-Build_Model.ipynb
ayan1995/DS_projects
Some scrap code below which wasn't used
# Save annotated reviews labeled_df.to_pickle("annotated_reviews_df.pkl") labeled_df.head() # This code was for parsing out terms & their relations to aspects # However, the terms were not always hyponyms of the aspects, so they were unusable aspects = {"food":[],"service":[],"anecdotes/miscellaneous":[], "ambience":[]...
_____no_output_____
Apache-2.0
04-Aspect_Based_Opinion_Mining/code/01-Build_Model.ipynb
ayan1995/DS_projects
Network inference of categorical variables: non-sequential data
import sys import numpy as np from scipy import linalg from sklearn.preprocessing import OneHotEncoder import matplotlib.pyplot as plt %matplotlib inline import inference import fem # setting parameter: np.random.seed(1) n = 20 # number of positions m = 5 # number of values at each position l = int(((n*m)**2)) # num...
_____no_output_____
MIT
old_versions/1main-v4-MCMC-symmetry.ipynb
danhtaihoang/categorical-variables
1. You are provided the titanic dataset. Load the dataset and perform splitting into training and test sets with 70:30 ratio randomly using test train split.2. Use the Logistic regression created from scratch (from the prev question) in this question as well.3. Data cleaning plays a major role in this question. Report ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, f1_score,confusion_matrix,r2_score sns.set(style="darkgrid") df = pd.read_csv('titanic.csv') df.head() print('Missing Values in th...
_____no_output_____
MIT
question3.ipynb
kanishk779/SMAI-2
Data cleaning1. **Removal** :-- Remove *Name* column as this attribute does not affect the *Survived* status of the passenger. And moreover we can see that each person has a unique name hence there is no point considering this column.- Remove *Ticket* because there are 681 unique values of ticket and moreover if there...
df = df.drop(columns=['Name', 'Ticket', 'Cabin', 'PassengerId']) s1 = sns.barplot(data = df, y='Survived' , hue='Sex' , x='Sex') s1.set_title('Male-Female Survival') plt.show()
_____no_output_____
MIT
question3.ipynb
kanishk779/SMAI-2
Females had a better survival rate than male.
sns.pairplot(df, hue='Survived')
_____no_output_____
MIT
question3.ipynb
kanishk779/SMAI-2
Categorical dataFor categorical variables where no ordinal relationship exists, the integer encoding may not be enough, at best, or misleading to the model at worst.Forcing an ordinal relationship via an ordinal encoding and allowing the model to assume a natural ordering between categories may result in poor performa...
from numpy import mean s1 = sns.barplot(data = df, y='Survived' , hue='Embarked' , x='Embarked', estimator=mean) s1.set_title('Survival vs Boarding place') plt.show() carrier_count = df['Embarked'].value_counts() sns.barplot(x=carrier_count.index, y=carrier_count.values, alpha=0.9) plt.title('Frequency Distribution of...
precision recall f1-score support 0.0 0.82 0.86 0.84 153 1.0 0.80 0.75 0.77 115 accuracy 0.81 268 macro avg 0.81 0.80 0.80 268 weighted avg 0.81 0.81 0.81 ...
MIT
question3.ipynb
kanishk779/SMAI-2
起手式,導入 numpy, matplotlib
from PIL import Image import numpy as np %matplotlib inline import matplotlib import matplotlib.pyplot as plt matplotlib.style.use('bmh') matplotlib.rcParams['figure.figsize']=(8,5)
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
使用之前下載的 mnist 資料,載入訓練資料 `train_set` 和測試資料 `test_set`
import gzip import pickle with gzip.open('../Week02/mnist.pkl.gz', 'rb') as f: train_set, validation_set, test_set = pickle.load(f, encoding='latin1') train_X, train_y = train_set validation_X, validation_y = validation_set test_X, test_y = test_set
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
之前的看圖片函數
from IPython.display import display def showX(X): int_X = (X*255).clip(0,255).astype('uint8') # N*784 -> N*28*28 -> 28*N*28 -> 28 * 28N int_X_reshape = int_X.reshape(-1,28,28).swapaxes(0,1).reshape(28,-1) display(Image.fromarray(int_X_reshape)) # 訓練資料, X 的前 20 筆 showX(train_X[:20])
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
train_set 是用來訓練我們的模型用的我們的模型是很簡單的 logistic regression 模型,用到的參數只有一個 784x10 的矩陣 W 和一個長度 10 的向量 b。我們先用均勻隨機亂數來設定 W 和 b 。
W = np.random.uniform(low=-1, high=1, size=(28*28,10)) b = np.random.uniform(low=-1, high=1, size=10)
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
完整的模型如下將圖片看成是長度 784 的向量 x計算 $Wx+b$, 然後再取 $exp$。 最後得到的十個數值。將這些數值除以他們的總和。我們希望出來的數字會符合這張圖片是這個數字的機率。 $ \Pr(Y=i|x, W, b) = \frac {e^{W_i x + b_i}} {\sum_j e^{W_j x + b_j}}$ 先拿第一筆資料試試看, x 是輸入。 y 是這張圖片對應到的數字(以這個例子來說 y=5)。
x = train_X[0] y = train_y[0] showX(x) y
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
先計算 $e^{Wx+b} $
Pr = np.exp(x @ W + b) Pr.shape
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
然後 normalize,讓總和變成 1 (符合機率的意義)
Pr = Pr/Pr.sum() Pr
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
由於 $W$ 和 $b$ 都是隨機設定的,所以上面我們算出的機率也是隨機的。正確解是 $y=5$, 運氣好有可能猜中為了要評斷我們的預測的品質,要設計一個評斷誤差的方式,我們用的方法如下(不是常見的方差,而是用熵的方式來算,好處是容易微分,效果好) $ loss = - \log(\Pr(Y=y|x, W,b)) $ 上述的誤差評分方式,常常稱作 error 或者 loss,數學式可能有點費解。實際計算其實很簡單,就是下面的式子
loss = -np.log(Pr[y]) loss
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
想辦法改進。 我們用一種被稱作是 gradient descent 的方式來改善我們的誤差。因為我們知道 gradient 是讓函數上升最快的方向。所以我們如果朝 gradient 的反方向走一點點(也就是下降最快的方向),那麼得到的函數值應該會小一點。記得我們的變數是 $W$ 和 $b$ (裡面總共有 28*20+10 個變數),所以我們要把 $loss$ 對 $W$ 和 $b$ 裡面的每一個參數來偏微分。還好這個偏微分是可以用手算出他的形式,而最後偏微分的式子也不會很複雜。 $loss$ 展開後可以寫成$loss = \log(\sum_j e^{W_j x + b_j}) - W_i x - b_i$ 對 $k \neq ...
gradb = Pr.copy() gradb[y] -= 1 print(gradb)
[ 1.11201478e-03 2.32129668e-06 3.47186834e-03 3.64416088e-03 9.89922844e-01 -9.99616538e-01 4.67890738e-09 3.02581069e-04 1.11720864e-07 1.16063080e-03]
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
對 $W$ 的偏微分也不難 對 $k \neq i$ 時, $loss$ 對 $W_{k,t}$ 的偏微分是 $$ \frac{e^{W_k x + b_k} W_{k,t} x_t}{\sum_j e^{W_j x + b_j}} = \Pr(Y=k | x, W, b) x_t$$對 $k = i$ 時, $loss$ 對 $W_{k,t}$ 的偏微分是 $$ \Pr(Y=k | x, W, b) x_t - x_t$$
print(Pr.shape, x.shape, W.shape) gradW = x.reshape(784,1) @ Pr.reshape(1,10) gradW[:, y] -= x
(10,) (784,) (784, 10)
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
算好 gradient 後,讓 W 和 b 分別往 gradient 反方向走一點點,得到新的 W 和 b
W -= 0.1 * gradW b -= 0.1 * gradb
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
再一次計算 $\Pr$ 以及 $loss$
Pr = np.exp(x @ W + b) Pr = Pr/Pr.sum() loss = -np.log(Pr[y]) loss
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
Q* 看看 Pr , 然後找出機率最大者, predict y 值* 再跑一遍上面程序,看看誤差是否變小?* 拿其他的測試資料來看看,我們的 W, b 學到了什麼? 我們將同樣的方式輪流對五萬筆訓練資料來做,看看情形會如何
W = np.random.uniform(low=-1, high=1, size=(28*28,10)) b = np.random.uniform(low=-1, high=1, size=10) score = 0 N=50000*20 d = 0.001 learning_rate = 1e-2 for i in range(N): if i%50000==0: print(i, "%5.3f%%"%(score*100)) x = train_X[i%50000] y = train_y[i%50000] Pr = np.exp( x @ W +b) Pr = Pr...
0 0.000% 50000 87.490% 100000 89.497% 150000 90.022% 200000 90.377% 250000 90.599% 300000 91.002% 350000 91.298% 400000 91.551% 450000 91.613% 500000 91.678% 550000 91.785% 600000 91.792% 650000 91.889% 700000 91.918% 750000 91.946% 800000 91.885% 850000 91.955% 900000 91.954% 950000 92.044%
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
結果發現正確率大約是 92%, 但這是對訓練資料而不是對測試資料而且,一筆一筆的訓練資也有點慢,線性代數的特點就是能夠向量運算。如果把很多筆 $x$ 當成列向量組合成一個矩陣(然後叫做 $X$),由於矩陣乘法的原理,我們還是一樣計算 $WX+b$ , 就可以同時得到多筆結果。下面的函數,可以一次輸入多筆 $x$, 同時一次計算多筆 $x$ 的結果和準確率。
def compute_Pr(X): Pr = np.exp(X @ W + b) return Pr/Pr.sum(axis=1, keepdims=True) def compute_accuracy(Pr, y): return (Pr.argmax(axis=1)==y).mean()
_____no_output_____
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
下面是更新過得訓練過程, 當 i%100000 時,順便計算一下 test accuracy 和 valid accuracy。
%%timeit -r 1 -n 1 def compute_Pr(X): Pr = np.exp(X @ W + b) return Pr/Pr.sum(axis=1, keepdims=True) def compute_accuracy(Pr, y): return (Pr.argmax(axis=1)==y).mean() W = np.random.uniform(low=-1, high=1, size=(28*28,10)) b = np.random.uniform(low=-1, high=1, size=10) score = 0 N=20000 batch_size = 128 lea...
2000 90.50% 90.47% 4000 91.17% 91.56% 6000 91.72% 92.03% 8000 91.86% 92.25% 10000 92.03% 92.52% 12000 92.14% 92.88% 14000 92.34% 92.81% 16000 92.29% 92.99% 18000 92.18% 93.13% 20000 92.06% 93.12% 1 loop, best of 1: 1min 8s per loop
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
最後得到的準確率是 92%-93%不算完美,不過畢竟這只有一個矩陣而已。 光看數據沒感覺,我們來看看前十筆測試資料跑起來的情形可以看到前十筆只有錯一個
Pr = compute_Pr(test_X[:10]) pred_y =Pr.argmax(axis=1) for i in range(10): print(pred_y[i], test_y[i]) showX(test_X[i])
7 7
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
看看前一百筆資料中,是哪些情況算錯
Pr = compute_Pr(test_X[:100]) pred_y = Pr.argmax(axis=1) for i in range(100): if pred_y[i] != test_y[i]: print(pred_y[i], test_y[i]) showX(test_X[i])
6 5
MIT
Week05/From NumPy to Logistic Regression.ipynb
HowardNTUST/HackNTU_Data_2017
Скородумов Александр БВТ1904 Лабораторная работа №2 Методы поиска №1
#Импорты from IPython.display import HTML, display from tabulate import tabulate import random import time #Рандомная генерация def random_matrix(m = 50, n = 50, min_limit = -250, max_limit = 1016): return [[random.randint(min_limit, max_limit) for _ in range(n)] for _ in range(m)] #Бинарный поиск class BinarySearc...
_____no_output_____
MIT
.ipynb_checkpoints/Skorodumov.Lab2-checkpoint.ipynb
SkorodumovAlex/SIAODLabs
№2
#Простое рехеширование class HashMap: def __init__(self): self.size = 0 self.data = [] self._resize() def _hash(self, key, i): return (hash(key) + i) % len(self.data) def _find(self, key): i = 0; index = self._hash(key, i); while self.dat...
_____no_output_____
MIT
.ipynb_checkpoints/Skorodumov.Lab2-checkpoint.ipynb
SkorodumovAlex/SIAODLabs
Сравнение алгоритмов
алгоритмы = { 'Бинарный поиск': BinarySearchMap, 'Фибоначчиева поиск': FibonacciMap, 'Интерполяционный поиск': InterpolateMap, 'Бинарное дерево': BinaryTreeMap, 'Простое рехэширование': HashMap, 'Рехэширование с помощью псевдослучайных чисел': RandomHashMap, 'Метод цепочек': ChainMap, 'С...
_____no_output_____
MIT
.ipynb_checkpoints/Skorodumov.Lab2-checkpoint.ipynb
SkorodumovAlex/SIAODLabs
№3
#Вывод результата def tag(x, color='white'): return f'<td style="width:24px;height:24px;text-align:center;" bgcolor="{color}">{x}</td>' th = ''.join(map(tag, ' abcdefgh ')) def chessboard(data): row = lambda i: ''.join([ tag('<span style="font-size:24px">*</span>' * v, color='white' if (i+j+...
_____no_output_____
MIT
.ipynb_checkpoints/Skorodumov.Lab2-checkpoint.ipynb
SkorodumovAlex/SIAODLabs
```Pythonx_train = HDF5Matrix("data.h5", "x_train")x_valid = HDF5Matrix("data.h5", "x_valid")```shapes should be:* (1355578, 432, 560, 1)* (420552, 432, 560, 1)
def gen_data(shape=0, name="input"): data = np.random.rand(512, 512, 4) label = data[:,:,-1] return tf.constant(data.reshape(1,512,512,4).astype(np.float32)), tf.constant(label.reshape(1,512,512,1).astype(np.float32)) ## NOTE: ## Tensor 4D -> Batch,X,Y,Z ## Tesnor max. float32! d, l = gen_data(0,0) p...
_____no_output_____
BSD-3-Clause
Examples/simple_U-Net.ipynb
thgnaedi/DeepRain
Anschließend:```Pythonoutput_length = 1input_length = output_length + 1input_shape=(432, 560, input_length)model_1 = unet(input_shape, output_length)model_1.fit(x_train_1, y_train_1, batch_size = 16, epochs = 25, validation_data=(x_valid_1, y_valid_1))```
d.summary() #ToDo: now learn something!
_____no_output_____
BSD-3-Clause
Examples/simple_U-Net.ipynb
thgnaedi/DeepRain
Implementing a Neural NetworkIn this exercise we will develop a neural network with fully-connected layers to perform classification, and test it out on the CIFAR-10 dataset.
# A bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.neural_net import TwoLayerNet %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloadi...
/Users/ayush/anaconda2/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment. warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
We will use the class `TwoLayerNet` in the file `cs231n/classifiers/neural_net.py` to represent instances of our network. The network parameters are stored in the instance variable `self.params` where keys are string parameter names and values are numpy arrays. Below, we initialize toy data and a toy model that we will...
# Create a small net and some toy data to check your implementations. # Note that we set the random seed for repeatable experiments. input_size = 4 hidden_size = 10 num_classes = 3 num_inputs = 5 def init_toy_model(): np.random.seed(0) return TwoLayerNet(input_size, hidden_size, num_classes, std=1e-1) def init_t...
_____no_output_____
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Forward pass: compute scoresOpen the file `cs231n/classifiers/neural_net.py` and look at the method `TwoLayerNet.loss`. This function is very similar to the loss functions you have written for the SVM and Softmax exercises: It takes the data and weights and computes the class scores, the loss, and the gradients on the...
scores = net.loss(X) print 'Your scores:' print scores print print 'correct scores:' correct_scores = np.asarray([ [-0.81233741, -1.27654624, -0.70335995], [-0.17129677, -1.18803311, -0.47310444], [-0.51590475, -1.01354314, -0.8504215 ], [-0.15419291, -0.48629638, -0.52901952], [-0.00618733, -0.12435261, -0.1...
Your scores: [[-0.81233741 -1.27654624 -0.70335995] [-0.17129677 -1.18803311 -0.47310444] [-0.51590475 -1.01354314 -0.8504215 ] [-0.15419291 -0.48629638 -0.52901952] [-0.00618733 -0.12435261 -0.15226949]] correct scores: [[-0.81233741 -1.27654624 -0.70335995] [-0.17129677 -1.18803311 -0.47310444] [-0.51590475 -1...
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Forward pass: compute lossIn the same function, implement the second part that computes the data and regularizaion loss.
loss, _ = net.loss(X, y, reg=0.1) correct_loss = 1.30378789133 # should be very small, we get < 1e-12 print 'Difference between your loss and correct loss:' print np.sum(np.abs(loss - correct_loss))
Difference between your loss and correct loss: 1.79856129989e-13
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Backward passImplement the rest of the function. This will compute the gradient of the loss with respect to the variables `W1`, `b1`, `W2`, and `b2`. Now that you (hopefully!) have a correctly implemented forward pass, you can debug your backward pass using a numeric gradient check:
from cs231n.gradient_check import eval_numerical_gradient # Use numeric gradient checking to check your implementation of the backward pass. # If your implementation is correct, the difference between the numeric and # analytic gradients should be less than 1e-8 for each of W1, W2, b1, and b2. loss, grads = net.loss(...
(4, 10) W1 max relative error: 1.000000e+00
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Train the networkTo train the network we will use stochastic gradient descent (SGD), similar to the SVM and Softmax classifiers. Look at the function `TwoLayerNet.train` and fill in the missing sections to implement the training procedure. This should be very similar to the training procedure you used for the SVM and ...
net = init_toy_model() stats = net.train(X, y, X, y, learning_rate=1e-1, reg=1e-5, num_iters=100, verbose=False) print 'Final training loss: ', stats['loss_history'][-1] # plot the loss history plt.plot(stats['loss_history']) plt.xlabel('iteration') plt.ylabel('training loss') plt.title('Train...
_____no_output_____
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Load the dataNow that you have implemented a two-layer network that passes gradient checks and works on toy data, it's time to load up our favorite CIFAR-10 data so we can use it to train a classifier on a real dataset.
from cs231n.data_utils import load_CIFAR10 def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000): """ Load the CIFAR-10 dataset from disk and perform preprocessing to prepare it for the two-layer neural net classifier. These are the same steps as we used for the SVM, but condense...
_____no_output_____
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Train a networkTo train our network we will use SGD with momentum. In addition, we will adjust the learning rate with an exponential learning rate schedule as optimization proceeds; after each epoch, we will reduce the learning rate by multiplying it by a decay rate.
input_size = 32 * 32 * 3 hidden_size = 50 num_classes = 10 net = TwoLayerNet(input_size, hidden_size, num_classes) # Train the network stats = net.train(X_train, y_train, X_val, y_val, num_iters=1000, batch_size=200, learning_rate=1e-4, learning_rate_decay=0.95, reg=0.5, verbose=Tru...
_____no_output_____
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Debug the trainingWith the default parameters we provided above, you should get a validation accuracy of about 0.29 on the validation set. This isn't very good.One strategy for getting insight into what's wrong is to plot the loss function and the accuracies on the training and validation sets during optimization.Anot...
# Plot the loss function and train / validation accuracies plt.subplot(2, 1, 1) plt.plot(stats['loss_history']) plt.title('Loss history') plt.xlabel('Iteration') plt.ylabel('Loss') plt.subplot(2, 1, 2) plt.plot(stats['train_acc_history'], label='train') plt.plot(stats['val_acc_history'], label='val') plt.title('Classi...
_____no_output_____
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Tune your hyperparameters**What's wrong?**. Looking at the visualizations above, we see that the loss is decreasing more or less linearly, which seems to suggest that the learning rate may be too low. Moreover, there is no gap between the training and validation accuracy, suggesting that the model we used has low capa...
best_net = None # store the best model into this ################################################################################# # TODO: Tune hyperparameters using the validation set. Store your best trained # # model in best_net. # # ...
_____no_output_____
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Run on the test setWhen you are done experimenting, you should evaluate your final trained network on the test set; you should get above 48%.**We will give you extra bonus point for every 1% of accuracy above 52%.**
test_acc = (best_net.predict(X_test) == y_test).mean() print 'Test accuracy: ', test_acc
_____no_output_____
MIT
assignment1/two_layer_net.ipynb
ayush29feb/cs231n
Social Media Analysis EDA
df = pd.read_csv('./meme_cleaning.csv') df_sentiment = pd.read_csv('563_df_sentiments.csv') df_sentiment = df_sentiment.drop(columns=['Unnamed: 0', 'Unnamed: 0.1', 'Unnamed: 0.1.1']) df_sentiment.head() #Extract all words that begin with # and turn the results into a dataframe temp = df_sentiment['Tweet'].str.lower()....
_____no_output_____
MIT
Final_Colab.ipynb
jared-garalde/sme_deploy_heroku
Sentiment
g = sns.catplot(x = "No_of_Likes", y = "Normalized_count", hue = "vaderSentiment", data = like_df, kind = "bar") g = sns.catplot(x = "No_of_Retweets", y = "Normalized_count", hue = "vaderSentiment", data = retweet_df, kind = "bar") plt.pie(classify_df['vaderSentiment'], labels=classify_df['index']); l = [] for i in ra...
_____no_output_____
MIT
Final_Colab.ipynb
jared-garalde/sme_deploy_heroku
Word Cloud
wordcloud = WordCloud(width = 800, height = 800, background_color ='white', min_font_size = 10).generate(str(l)) plt.figure(figsize = (8, 8), facecolor = None) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.tight_layout(pad = 0) plt.show()
_____no_output_____
MIT
Final_Colab.ipynb
jared-garalde/sme_deploy_heroku
Topic Modeling
cv = CountVectorizer(stop_words='english') data_cv = cv.fit_transform(df.Tweet) words = cv.get_feature_names() data_dtm = pd.DataFrame(data_cv.toarray(), columns=cv.get_feature_names()) pickle.dump(cv, open("cv_stop.pkl", "wb")) data_dtm_transpose = data_dtm.transpose() sparse_counts = scipy.sparse.csr_matrix(data_...
_____no_output_____
MIT
Final_Colab.ipynb
jared-garalde/sme_deploy_heroku
1. We shall use the same dataset used in previous assignment - digits. Make a 80-20 train/test split.[Hint: Explore datasets module from scikit learn] 2. Using scikit learn perform a LDA on the dataset. Find out the number of components in the projected subspace.[Hint: Refer to discriminant analysis module of scikit l...
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.datasets import load_digits digits = load_digits() digits.data digits.data.shape digits.target.shape from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(digits.d...
_____no_output_____
MIT
Cls5-Dimentionality Reduction/DimensionalityReduction-CaseStudy2-solution.ipynb
tuhinssam/MLResources
Project: Create a neural network class---Based on previous code examples, develop a neural network class that is able to classify any dataset provided. The class should create objects based on the desired network architecture:1. Number of inputs2. Number of hidden layers3. Number of neurons per layer4. Number of outpu...
import numpy as np import matplotlib.pyplot as plt # Needed for the mnist data from keras.datasets import mnist from keras.utils import to_categorical
_____no_output_____
MIT
Neural Network Assignment.ipynb
DeepLearningVision-2019/a3-neural-network-class-munozgce
Define the class
class NeuralNetwork: def __init__(self, architecture, alpha): ''' layers: List of integers which represents the architecture of the network. alpha: Learning rate. ''' # TODO: Initialize the list of weights matrices, then store # the network...
_____no_output_____
MIT
Neural Network Assignment.ipynb
DeepLearningVision-2019/a3-neural-network-class-munozgce
Test datasets XOR
# input dataset XOR_inputs = np.array([ [0,0], [0,1], [1,0], [1,1] ]) # labels dataset XOR_labels = np.array([[0,1,1,0]]).T #TODO: Test the class with the XOR data
_____no_output_____
MIT
Neural Network Assignment.ipynb
DeepLearningVision-2019/a3-neural-network-class-munozgce
Multiple classes
# Creates the data points for each class class_1 = np.random.randn(700, 2) + np.array([0, -3]) class_2 = np.random.randn(700, 2) + np.array([3, 3]) class_3 = np.random.randn(700, 2) + np.array([-3, 3]) feature_set = np.vstack([class_1, class_2, class_3]) labels = np.array([0]*700 + [1]*700 + [2]*700) one_hot_labels...
Error: 0.47806009636665425 Error: 0.007121601211763323 Error: 0.005938405234795827 Error: 0.005920131593441376 Error: 0.00585185558757003 Error: 0.0049490985751735606 Error: 0.004301948969147726 Error: 0.0038221899933325782 Error: 0.003507891190406313 Error: 0.003280260509683804
MIT
Neural Network Assignment.ipynb
DeepLearningVision-2019/a3-neural-network-class-munozgce
On the mnist data set---Train the network to classify hand drawn digits.For this data set, if the training step is taking too long, you can try to adjust the architecture of the network to have fewer layers, or you could try to train it with fewer input. The data has already been loaded and preprocesed so that it can ...
# Load the train and test data from the mnist data set (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # Plot a sample data point plt.title("Label: " + str(train_labels[0])) plt.imshow(train_images[0], cmap="gray") # Standardize the data # Flatten the images train_images = train_images.re...
Error: 0.47806009636665425 Error: 0.007121601211763323 Error: 0.005938405234795827 Error: 0.005920131593441376 Error: 0.00585185558757003 Error: 0.0049490985751735606 Error: 0.004301948969147726 Error: 0.0038221899933325782 Error: 0.003507891190406313 Error: 0.003280260509683804
MIT
Neural Network Assignment.ipynb
DeepLearningVision-2019/a3-neural-network-class-munozgce
Titanic 4 > `Pclass, Sex, Age`
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns plt.style.use('seaborn') sns.set(font_scale=2.5) import missingno as msno import warnings warnings.filterwarnings('ignore') %matplotlib inline df_train=pd.read_csv('C:/Users/ehfus/Downloads/titanic/train.csv') df_test=pd.rea...
_____no_output_____
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
- scale에도 option이 여러가지 있음, google에서 확인해볼 것 > `Embarked : 탑승한 항구`
f,ax=plt.subplots(1,1,figsize=(7,7)) df_train[['Embarked','Survived']]\ .groupby(['Embarked'], as_index=True).mean()\ .sort_values(by='Survived', ascending=False)\ .plot.bar(ax=ax)
_____no_output_____
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
- `sort_values` 또는 `sort_index`도 사용 가능
f,ax=plt.subplots(2,2,figsize=(20,15)) #2차원임/ 1,2는 1차원 sns.countplot('Embarked',data=df_train, ax=ax[0,0]) ax[0,0].set_title('(1) No. Of Passengers Boared') sns.countplot('Embarked',hue='Sex',data=df_train, ax=ax[0,1]) ax[0,1].set_title('(2) Male-Female split for embarked') sns.countplot('Embarked', hue='Survived', d...
_____no_output_____
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
> `Family - SibSp + ParCh`
df_train['FamilySize']=df_train['SibSp'] + df_train['Parch'] + 1 print('Maximum size of Family : ',df_train['FamilySize'].max()) print('Minimum size of Family : ',df_train['FamilySize'].min())
Maximum size of Family : 11 Minimum size of Family : 1
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
- Pandas series는 연산이 가능
f,ax=plt.subplots(1,3,figsize=(40,10)) sns.countplot('FamilySize', data=df_train, ax=ax[0]) ax[0].set_title('(1) No. Of Passenger Boarded', y=1.02) sns.countplot('FamilySize', hue='Survived',data=df_train, ax=ax[1]) ax[1].set_title('(2) Survived countplot depending on FamilySize', y=1.02) df_train[['FamilySize','Surv...
_____no_output_____
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
> `Fare : 요금, 연속형 변수` - distplot ?? 시리즈에 히스토그램을 그려줌,Skewness? 왜도임 + 첨도도 있음- 왜도? 첨도?- python에서 나타내는 함수는?
fig,ax=plt.subplots(1,1,figsize=(8,8)) g=sns.distplot(df_train['Fare'], color='b',label='Skewness{:.2f}'.format(df_train['Fare'].skew()),ax=ax) g=g.legend(loc='best')
_____no_output_____
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
- skewness가 5정도로 꽤 큼 -> 좌로 많이 치우쳐져 있음 -> 그대로 모델에 학습시키면 성능이 낮아질 수 있음
df_train['Fare']=df_train['Fare'].map(lambda i: np.log(i) if i>0 else 0)
_____no_output_____
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
df_train['Fare']의 값을 적절하게 변형 중
fig,ax=plt.subplots(1,1,figsize=(8,8)) g=sns.distplot(df_train['Fare'], color='b',label='Skewness{:.2f}'.format(df_train['Fare'].skew()),ax=ax) g=g.legend(loc='best')
_____no_output_____
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
이런 작업(log로 변환)을 통해 skewness가 0으로 근접하게 해주었음
df_train['Ticket'].value_counts()
_____no_output_____
Apache-2.0
_notebooks/2021-12-26-titanic.ipynb
rhkrehtjd/kaggle
Section 1.2: Dimension reduction and principal component analysis (PCA)One of the iron laws of data science is know as the "curse of dimensionality": as the number of considered features (dimensions) of a feature space increases, the number of data configurations can grow exponentially and thus the number observations...
import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
The dataset we’ll use here is the same one drawn from the [U.S. Department of Agriculture National Nutrient Database for Standard Reference](https://www.ars.usda.gov/northeast-area/beltsville-md-bhnrc/beltsville-human-nutrition-research-center/nutrient-data-laboratory/docs/usda-national-nutrient-database-for-standard-r...
df = pd.read_csv('Data/USDA-nndb-combined.csv', encoding='latin_1')
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
We can check the number of columns and rows using the `info()` method for the `DataFrame`.
df.info()
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
> **Exercise**>> Can you think of a more concise way to check the number of rows and columns in a `DataFrame`? (***Hint:*** Use one of the [attributes](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) of the `DataFrame`.) Handle `null` valuesBecause this is a real-world dataset, it is ...
df.shape
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
Dropping those rows eliminated 76 percent of our data (8989 entries to 2190). An imperfect state of affairs, but we still have enough for our purposes in this section.> **Key takeaway:** Another solution to removing `null` values is to impute values for them, but this can be tricky. Should we handle missing values as e...
desc_df = df.iloc[:, [0, 1, 2]+[i for i in range(50,54)]] desc_df.set_index('NDB_No', inplace=True) desc_df.head()
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
> **Question**>> Why was it necessary to structure the `iloc` method call the way we did in the code cell above? What did it accomplish? Why was it necessary set the `desc_df` index to `NDB_No`?
nutr_df = df.iloc[:, :-5] nutr_df.head()
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
> **Question**>> What did the `iloc` syntax do in the code cell above?
nutr_df = nutr_df.drop(['FoodGroup', 'Shrt_Desc'], axis=1)
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
> **Exercise**>> Now set the index of `nutr_df` to use `NDB_No`. > **Exercise solution**>> The correct code for students to use here is `nutr_df.set_index('NDB_No', inplace=True)`. Now let’s take a look at `nutr_df`.
nutr_df.head()
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
Check for correlation among featuresOne thing that can skew our classification results is correlation among our features. Recall that the whole reason that PCA works is that it exploits the correlation among data points to project our feature-space into a lower-dimensional space. However, if some of our features are h...
nutr_df.drop(['Folate_DFE_(µg)', 'Vit_A_RAE', 'Vit_D_IU'], inplace=True, axis=1) nutr_df.head()
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
Normalize and center the dataOur numeric data comes in a variety of mass units (grams, milligrams, and micrograms) and one energy unit (kilocalories). In order to make an apples-to-apples comparison (pun intended) of the nutritional data, we need to first *normalize* the data and make it more normally distributed (tha...
ax = nutr_df.hist(bins=50, xlabelsize=-1, ylabelsize=-1, figsize=(11,11))
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
Not a bell curve in sight. Worse, a lot of the data is clumped at or around 0. We will use the Box-Cox Transformation on the data, but it requires strictly positive input, so we will add 1 to every value in each column.
nutr_df = nutr_df + 1
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors
Now for the transformation. The [Box-Cox Transformation](https://www.statisticshowto.datasciencecentral.com/box-cox-transformation/) performs the transformation $y(\lambda) = \dfrac{y^{\lambda}-1}{\lambda}$ for $\lambda \neq 0$ and $y(\lambda) = log y$ for $\lambda = 0$ for all values $y$ in a given column. SciPy has a...
from scipy.stats import boxcox nutr_df_TF = pd.DataFrame(index=nutr_df.index) for col in nutr_df.columns.values: nutr_df_TF['{}_TF'.format(col)] = boxcox(nutr_df.loc[:, col])[0]
_____no_output_____
MIT
Machine Learning 2_Using Advanced Machine Learning Models/Reference Material/190053-Reactors-DS-Tr2-Sec1-2-PCA.ipynb
raspyweather/Reactors