markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Rating distribution in the dataset: | data.rating.value_counts().sort_index().plot.bar() | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Building our first recommender model
Preparing data
RecommenderData class provides a set of tools for manipulating the data and preparing it for experimentation.
Input parameters are: the data itself (pandas dataframe) and mapping of the data fields (column names) to internal representation: userid, itemid and feedback... | data_model = RecommenderData(data, userid='userid', itemid='movieid', feedback='rating') | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Verify correct mapping: | data.columns
data_model.fields | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
RecommenderData class has a number of parameters to control how the data is processed. Defaults are fine to start with: | data_model.get_configuration() | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Use prepare method to split the dataset into 2 parts: training data and test data. | data_model.prepare() | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
As the original data possibly contains gaps in users' and items' indices, the data preparation process will clean this up: items from the training data will be indexed starting from zero with no gaps and the result will be stored in: | data_model.index.itemid.head() | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Similarly, all userid's from both training and test set are reindexed and stored in: | data_model.index.userid.training.head()
data_model.index.userid.test.head() | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Internally only new inices are used. This ensures consistency of various methods used by the model.
The dataset is split according to test_fold and test_ratio attributes. By default it uses first 80% of users for training and last 20% of the users as test data. | data_model.training.head()
data_model.training.shape | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
The test data is further split into testset and evaluation set (evalset). Testset is used to generate recommendations, which are than evaluated against the evaluation set. | data_model.test.testset.head()
data_model.test.testset.shape
data_model.test.evalset.head()
data_model.test.evalset.shape | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
The users in the test and evaluation sets are the same (but this users are not in the training set!).
For every test user the evaluation set contains a fixed number of items which are held out from the original test data. The number of holdout items is controlled by holdout_size parameter. By default it's set to 3: | data_model.holdout_size
data_model.test.evalset.groupby('userid').movieid.count().head() | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Creating recommender model
You can create your own model by subclassing RecommenderModel class and defining two required methods: self.build() and self.get_recommendations(): | class TopMovies(RecommenderModel):
def build(self):
self._recommendations = None # this is required line in order to ensure consitency in experiments
itemid = self.data.fields.itemid # get the name of the column, that corresponds to movieid
# calculate popularity of the movies based... | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Note, that recommendations, generated by this model, do not take into account the fact, that some of the recommended items may be present in the test set and thus, should not be recommended (they are considered seen by a test user). In order to fix that you can use filter_seen parameter along with downvote_seen_items m... | class TopMoviesALT(RecommenderModel):
def build(self):
# should be the same as in TopMovies
def slice_recommendations(self, test_data, shape, start, stop):
# current implementation requires handovering slice data in specific format further,
# and the easiest way to get it is vi... | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Now everything is set to create an instance of the recommender model and produce recommendations.
generating recommendations: | top = TopMovies(data_model) # the model takes as input parameter the recommender data model
top.build()
recs = top.get_recommendations()
recs
recs.shape
top.topk | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
You can evaluate your model befotre submitting the results (to ensure that you have improved above baseline): | top.evaluate() | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Try to change your model to maximize the true_positive score.
submitting your model:
After you have created your perfect recsys model, firstly, save your recommendation into file. Please, use your name as the name for file (this will be used to display at leaderboard) | np.savez('your_full_name', recs=recs) | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Now you can uppload your results: | import requests
files = {'upload': open('your_full_name.npz','rb')}
url = "http://isp2017.azurewebsites.net/upload"
r = requests.post(url, files=files) | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Verify, that upload is successful: | print r.status_code, r.reason | polara_intro.ipynb | Evfro/RecSys_ISP2017 | mit |
Guia inicial de TensorFlow 2.0 para expertos
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/quickstart/advanced"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />Ver en TensorFlow.org</a>
</td>
<td>
<a target="_blank" hre... | import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model | site/es-419/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Carga y prepara el conjunto de datos MNIST | 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
# Agrega una dimension de canales
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis] | site/es-419/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Utiliza tf.data to separar por lotes y mezclar el conjunto de datos: | train_ds = tf.data.Dataset.from_tensor_slices(
(x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32) | site/es-419/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Construye el modelo tf.keras utilizando la API de Keras model subclassing API: | class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.conv1(x)
x = self.flatten(x)
... | site/es-419/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Escoge un optimizador y una funcion de perdida para el entrenamiento de tu modelo: | loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam() | site/es-419/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Escoge metricas para medir la perdida y exactitud del modelo.
Estas metricas acumulan los valores cada epoch y despues imprimen el resultado total. | train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy') | site/es-419/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Utiliza tf.GradientTape para entrenar el modelo. | @tf.function
def train_step(images, labels):
with tf.GradientTape() as tape:
predictions = model(images)
loss = loss_object(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(loss)
train_accur... | site/es-419/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Prueba el modelo: | @tf.function
def test_step(images, labels):
predictions = model(images)
t_loss = loss_object(labels, predictions)
test_loss(t_loss)
test_accuracy(labels, predictions)
EPOCHS = 5
for epoch in range(EPOCHS):
for images, labels in train_ds:
train_step(images, labels)
for test_images, test_labels in tes... | site/es-419/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Data: Preparing for the model
Importing the raw data | DIR = os.getcwd() + "/../data/"
t = pd.read_csv(DIR + 'raw/lending-club-loan-data/loan.csv', low_memory=False)
t.head() | notebooks/5-aa-second_model.ipynb | QuinnLee/cs109a-Project | mit |
Cleaning, imputing missing values, feature engineering (some NLP) | t2 = md.clean_data(t)
t3 = md.impute_missing(t2)
df = md.simple_dataset(t3)
# df = md.spelling_mistakes(t3) - skipping for now, so computationally expensive! | notebooks/5-aa-second_model.ipynb | QuinnLee/cs109a-Project | mit |
Train, test split: Splitting on 2015 | df['issue_d'].hist(bins = 50)
plt.title('Seasonality in lending')
plt.ylabel('Frequency')
plt.xlabel('Year')
plt.show() | notebooks/5-aa-second_model.ipynb | QuinnLee/cs109a-Project | mit |
We can use past years as predictors of future years. One challenge with this approach is that we confound time-sensitive trends (for example, global economic shocks to interest rates - such as the financial crisis of 2008, or the growth of Lending Club to broader and broader markets of debtors) with differences related... | old = df[df['issue_d'] < '2015']
new = df[df['issue_d'] >= '2015']
old.shape, new.shape | notebooks/5-aa-second_model.ipynb | QuinnLee/cs109a-Project | mit |
We'll use the pre-2015 data on interest rates (old) to fit a model and cross-validate it. We'll then use the post-2015 data as a 'wild' dataset to test against.
Fitting the model | X = old.drop(['int_rate', 'issue_d', 'earliest_cr_line', 'grade'], 1)
y = old['int_rate']
X.shape, y.shape
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
X_train.shape, X_test.shape, y_train.shape, y_test.shape
rfr = RandomForestRegressor(n_estimators = 10, max_features='sq... | notebooks/5-aa-second_model.ipynb | QuinnLee/cs109a-Project | mit |
Fitting the model
We fit the model on all the data, and evaluate feature importances. | rfr.fit(X_total, y_total)
fi = [{'importance': x, 'feature': y} for (x, y) in \
sorted(zip(rfr.feature_importances_, X_total.columns))]
fi = pd.DataFrame(fi)
fi.sort_values(by = 'importance', ascending = False, inplace = True)
fi.head()
top5 = fi.head()
top5.plot(kind = 'bar')
plt.xticks(range(5), top5['featur... | notebooks/5-aa-second_model.ipynb | QuinnLee/cs109a-Project | mit |
๋ณ๋ถ ์ถ๋ก ์ผ๋ก ์ผ๋ฐํ๋ ์ ํ ํผํฉ ํจ๊ณผ ๋ชจ๋ธ ๋ง์ถค ์กฐ์ ํ๊ธฐ
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https://www.tensorflow.org/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org์์ ๋ณด๊ธฐ</a> </td>
<td><a ... | #@title Install { display-mode: "form" }
TF_Installation = 'System' #@param ['TF Nightly', 'TF Stable', 'System']
if TF_Installation == 'TF Nightly':
!pip install -q --upgrade tf-nightly
print('Installation of `tf-nightly` complete.')
elif TF_Installation == 'TF Stable':
!pip install -q --upgrade tensorflow
pr... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
์์ฝ
์ด colab์์๋ TensorFlow Probability์ ๋ณ๋ถ ์ถ๋ก ์ ์ฌ์ฉํ์ฌ ์ผ๋ฐํ๋ ์ ํ ํผํฉ ํจ๊ณผ ๋ชจ๋ธ์ ๋ง์ถค ์กฐ์ ํ๋ ๋ฐฉ๋ฒ์ ๋ณด์ฌ์ค๋๋ค.
๋ชจ๋ธ ํจ๋ฐ๋ฆฌ
์ผ๋ฐํ๋ ์ ํ ํผํฉ ํจ๊ณผ ๋ชจ๋ธ(GLMM)์ ์ํ๋ณ ๋
ธ์ด์ฆ๋ฅผ ์์ธก๋ ์ ํ ์๋ต์ ํตํฉํ๋ค๋ ์ ์ ์ ์ธํ๋ฉด ์ผ๋ฐํ๋ ์ ํ ๋ชจ๋ธ(GLM)๊ณผ ์ ์ฌํฉ๋๋ค. ์ด๊ฒ์ ๊ฑฐ์ ๋ณด์ด์ง ์๋ ํน์ฑ์ด ๋ ์ผ๋ฐ์ ์ผ๋ก ๋ณด์ด๋ ํน์ฑ๊ณผ ์ ๋ณด๋ฅผ ๊ณต์ ํ ์ ์๊ธฐ ๋๋ฌธ์ ๋ถ๋ถ์ ์ผ๋ก ์ ์ฉํฉ๋๋ค.
์์ฑ ํ๋ก์ธ์ค๋ก์ ์ผ๋ฐํ๋ ์ ํ ํผํฉ ํจ๊ณผ ๋ชจ๋ธ(GLMM)์ ๋ค์๊ณผ ๊ฐ์ ํน์ง์ด ์์ต๋๋ค.
$$ \begin{align} \text{for } ... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import os
from six.moves import urllib
import matplotlib.pyplot as plt; plt.style.use('ggplot')
import numpy as np
import pandas as pd
import seaborn as sns; sns.set_context('notebook')
import tensorflow_datasets as tfds
import tensorflow.compat.v2 as... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ํ GPU์ ๊ฐ์ฉ์ฑ์ ๋น ๋ฅด๊ฒ ํ์ธํฉ๋๋ค. | if tf.test.gpu_device_name() != '/device:GPU:0':
print("We'll just use the CPU for this run.")
else:
print('Huzzah! Found GPU: {}'.format(tf.test.gpu_device_name())) | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ฐ์ดํฐ์ธํธ ์ป๊ธฐ
TensorFlow ๋ฐ์ดํฐ์ธํธ์์ ๋ฐ์ดํฐ์ธํธ๋ฅผ ๋ก๋ํ๊ณ ์ฝ๊ฐ์ ๊ฐ๋ฒผ์ด ์ ์ฒ๋ฆฌ๋ฅผ ์ํํฉ๋๋ค. | def load_and_preprocess_radon_dataset(state='MN'):
"""Load the Radon dataset from TensorFlow Datasets and preprocess it.
Following the examples in "Bayesian Data Analysis" (Gelman, 2007), we filter
to Minnesota data and preprocess to obtain the following features:
- `county`: Name of county in which the meas... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
GLMM ํจ๋ฐ๋ฆฌ ์ ๋ฌธํํ๊ธฐ
์ด ์น์
์์๋ GLMM ํจ๋ฐ๋ฆฌ๋ฅผ ๋ผ๋ ์์ค ์์ธก ์์
์ ์ ๋ฌธํํฉ๋๋ค. ์ด๋ฅผ ์ํด ๋จผ์ GLMM์ ๊ณ ์ ํจ๊ณผ ํน์ ์ผ์ด์ค๋ฅผ ๊ณ ๋ คํฉ๋๋ค. $$ \mathbb{E}[\log(\text{radon}_j)] = c + \text{floor_effect}_j $$
์ด ๋ชจ๋ธ์ ๊ด์ธก์น $j$์ ๋ก๊ทธ ๋ผ๋์ด $j$๋ฒ์งธ ํ๋
๊ฐ์ด ์ธก์ ๋ ์ธต๊ณผ ์ผ์ ํ ์ ํธ์ ์ํด ์์๋๋ก ๊ฒฐ์ ๋๋ค๊ณ ๊ฐ์ ํฉ๋๋ค. ์์ฌ ์ฝ๋์์๋ ๋ค์๊ณผ ๊ฐ์ด ์์ฑํ ์ ์์ต๋๋ค.
def estimate_log_radon(floor):
return intercept + floor_effec... | fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))
df.groupby('floor')['log_radon'].plot(kind='density', ax=ax1);
ax1.set_xlabel('Measured log(radon)')
ax1.legend(title='Floor')
df['floor'].value_counts().plot(kind='bar', ax=ax2)
ax2.set_xlabel('Floor where radon was measured')
ax2.set_ylabel('Count')
fig.suptit... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ง๋ฆฌ์ ๊ดํ ๋ด์ฉ์ ํฌํจํ์ฌ ๋ชจ๋ธ์ ์ข ๋ ์ ๊ตํ๊ฒ ๋ง๋๋ ๊ฒ์ด ์๋ง๋ ๋ ์ข์ ๊ฒ์
๋๋ค. ๋ผ๋์ ๋
์ ์กด์ฌํ ์ ์๋ ์ฐ๋ผ๋์ ๋ถ๊ดด ์ฌ์ฌ์ ์ผ๋ถ์ด๋ฏ๋ก ์ง๋ฆฌ๋ฅผ ์ค๋ช
ํ๋ ๊ฒ์ด ์ค์ํฉ๋๋ค.
$$ \mathbb{E}[\log(\text{radon}_j)] = c + \text{floor_effect}_j + \text{county_effect}_j $$
๋ค์ ํ๋ฉด, ์์ฌ ์ฝ๋์์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
def estimate_log_radon(floor, county):
return intercept + floor_effect[floor] + county_effect[c... | fig, ax = plt.subplots(figsize=(22, 5));
county_freq = df['county'].value_counts()
county_freq.plot(kind='bar', ax=ax)
ax.set_xlabel('County')
ax.set_ylabel('Number of readings'); | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ด ๋ชจ๋ธ์ ๋ง์ถค ์กฐ์ ํ๋ฉด county_effect ๋ฒกํฐ๋ ํ๋ จ ์ํ์ด ๊ฑฐ์ ์๋ ์นด์ดํฐ์ ๋ํ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ์ตํ๊ฒ ๋ ๊ฒ์
๋๋ค. ์๋ง๋ ๊ณผ๋์ ํฉ์ด ๋ฐ์ํ์ฌ ์ผ๋ฐํ๊ฐ ๋ถ๋ํ ์ ์์ต๋๋ค.
GLMM์ ์์ ๋ GLM์ ๋ํด ์ ์ ํ ํํ์ ์ ์ ๊ณตํฉ๋๋ค. ๋ค์๊ณผ ๊ฐ์ด ๋ง์ถค ์กฐ์ ํ๋ ๊ฒ์ ๊ณ ๋ คํ ์ ์์ต๋๋ค.
$$ \log(\text{radon}_j) \sim c + \text{floor_effect}_j + \mathcal{N}(\text{county_effect}_j, \text{county_scale}) $$
์ด ๋ชจ๋ธ์ ์ฒซ ๋ฒ์งธ ๋ชจ๋ธ๊ณผ ๊ฐ์ง๋ง, ๊ฐ๋ฅ์ฑ์ด ์ ๊ท ๋ถํฌ๊ฐ ๋๋๋ก ... | features = df[['county_code', 'floor']].astype(int)
labels = df[['log_radon']].astype(np.float32).values.flatten() | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ชจ๋ธ์ ์ง์ ํฉ๋๋ค. | def make_joint_distribution_coroutine(floor, county, n_counties, n_floors):
def model():
county_scale = yield tfd.HalfNormal(scale=1., name='scale_prior')
intercept = yield tfd.Normal(loc=0., scale=1., name='intercept')
floor_weight = yield tfd.Normal(loc=0., scale=1., name='floor_weight')
county_pri... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ฌํ ํ๋ฅ ๋๋ฆฌ๋ฅผ ์ง์ ํฉ๋๋ค.
๋งค๊ฐ๋ณ์ $\lambda$๊ฐ ํ๋ จ ๊ฐ๋ฅํ ๋๋ฆฌ ํจ๋ฐ๋ฆฌ $q_{\lambda}$๋ฅผ ๊ตฌ์ฑํฉ๋๋ค. ์ด ๊ฒฝ์ฐ์ ํจ๋ฐ๋ฆฌ๋ ๊ฐ ๋งค๊ฐ๋ณ์์ ๋ํด ํ๋์ ๋ถํฌ๋ฅผ ๊ฐ๋ ๋
๋ฆฝ์ ์ธ ๋ค๋ณ๋ ์ ๊ท ๋ถํฌ์ด๊ณ $\lambda = {(\mu_j, \sigma_j)}$์
๋๋ค. ์ฌ๊ธฐ์ $j$๋ 4๊ฐ์ ๋งค๊ฐ๋ณ์๋ฅผ ์ธ๋ฑ์ฑํฉ๋๋ค.
๋๋ฆฌ ํจ๋ฐ๋ฆฌ๋ฅผ ๋ง์ถค ์กฐ์ ํ๊ธฐ ์ํ ๋ฉ์๋๋ tf.Variables๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์
๋๋ค. ๋ํ tfp.util.TransformedVariable์ Softplus์ ๊ฐ์ด ์ฌ์ฉํ์ฌ scale ๋งค๊ฐ๋ณ์(ํ๋ จ ๊ฐ๋ฅํจ)๋ฅผ ์์๋ก ์ ํํฉ๋๋ค. ๋ํ ์์ ๋งค... | # Initialize locations and scales randomly with `tf.Variable`s and
# `tfp.util.TransformedVariable`s.
_init_loc = lambda shape=(): tf.Variable(
tf.random.uniform(shape, minval=-2., maxval=2.))
_init_scale = lambda shape=(): tfp.util.TransformedVariable(
initial_value=tf.random.uniform(shape, minval=0.01, maxva... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ด ์
์ ๋ค์๊ณผ ๊ฐ์ด tfp.experimental.vi.build_factored_surrogate_posterior๋ก ๋์ฒดํ ์ ์์ต๋๋ค.
python
surrogate_posterior = tfp.experimental.vi.build_factored_surrogate_posterior(
event_shape=joint.event_shape_tensor()[:-1],
constraining_bijectors=[tfb.Softplus(), None, None, None])
๊ฒฐ๊ณผ
๋ค๋ฃจ๊ธฐ ์ฌ์ด ๋งค๊ฐ๋ณ์ํ๋ ๋ถํฌ ํจ๋ฐ๋ฆฌ๋ฅผ ์ ์ํ ๋ค์, ๋ชฉํ ๋ถํฌ์ ๊ฐ๊น์ด ๋ค๋ฃจ๊ธฐ... | optimizer = tf.optimizers.Adam(learning_rate=1e-2)
losses = tfp.vi.fit_surrogate_posterior(
target_log_prob_fn,
surrogate_posterior,
optimizer=optimizer,
num_steps=3000,
seed=42,
sample_size=2)
(scale_prior_,
intercept_,
floor_weight_,
county_weights_), _ = surrogate_posterior.sample_d... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ถ์ ๋ ํ๊ท ์นด์ดํฐ(county) ํจ๊ณผ์ ํด๋น ํ๊ท ์ ๋ถํ์ค์ฑ์ ํ๋กฏํ ์ ์์ต๋๋ค. ์ด๋ฅผ ๊ด์ฐฐ ํ์๋ก ์ ๋ ฌํ์ผ๋ฉฐ ๊ฐ์ฅ ํฐ ์๋ ์ผ์ชฝ์ ์์ต๋๋ค. ๊ด์ธก์น๊ฐ ๋ง์ ์นด์ดํฐ์์๋ ๋ถํ์ค์ฑ์ด ์์ง๋ง, ๊ด์ธก์น๊ฐ ํ๋ ๊ฐ๋ง ์๋ ์นด์ดํฐ์์๋ ๋ถํ์ค์ฑ์ด ๋ ํฝ๋๋ค. | county_counts = (df.groupby(by=['county', 'county_code'], observed=True)
.agg('size')
.sort_values(ascending=False)
.reset_index(name='count'))
means = county_weights_.mean()
stds = county_weights_.stddev()
fig, ax = plt.subplots(figsize=(20, 5))
for idx, row ... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ค์ ๋ก ์ถ์ ๋ ํ์ค ํธ์ฐจ์ ๋ํ ๋ก๊ทธ ์์ ๊ด์ธก์น๋ฅผ ํ๋กฏํ์ฌ ์ด๋ฅผ ๋ ์ง์ ์ ์ผ๋ก ๋ณผ ์ ์์ผ๋ฉฐ ๊ด๊ณ๊ฐ ๊ฑฐ์ ์ ํ์์ ์ ์ ์์ต๋๋ค. | fig, ax = plt.subplots(figsize=(10, 7))
ax.plot(np.log1p(county_counts['count']), stds.numpy()[county_counts.county_code], 'o')
ax.set(
ylabel='Posterior std. deviation',
xlabel='County log-count',
title='Having more observations generally\nlowers estimation uncertainty'
); | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
R์์ lme4์ ๋น๊ตํ๊ธฐ | %%shell
exit # Trick to make this block not execute.
radon = read.csv('srrs2.dat', header = TRUE)
radon = radon[radon$state=='MN',]
radon$radon = ifelse(radon$activity==0., 0.1, radon$activity)
radon$log_radon = log(radon$radon)
# install.packages('lme4')
library(lme4)
fit <- lmer(log_radon ~ 1 + floor + (1 | county... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ค์ ํ์ ๊ฒฐ๊ณผ๊ฐ ์์ฝ๋์ด ์์ต๋๋ค. | print(pd.DataFrame(data=dict(intercept=[1.462, tf.reduce_mean(intercept_.mean()).numpy()],
floor=[-0.693, tf.reduce_mean(floor_weight_.mean()).numpy()],
scale=[0.3282, tf.reduce_mean(scale_prior_.sample(10000)).numpy()]),
index=['lme4', 'vi'])... | site/ko/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference.ipynb | tensorflow/docs-l10n | apache-2.0 |
Remove the smaller objects to retrieve the large galaxy using a boolean array, and then use skimage.exposure.histogram and plt.plot to show the light distribution from the galaxy.
<div style="height: 400px;"></div> | %reload_ext load_style
%load_style ../themes/tutorial.css | notebooks/3_morphological_operations.ipynb | jni/numpy-skimage-tutorial | bsd-3-clause |
If we call the keys of the pj.alignments dictionary, we can see the names of the alignments it contains: | pj.alignments.keys() | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
3.7.1 Configuring an alignment trimming process
Like the sequence alignment phase, alignment trimming has its own configuration class, the TrimalConf class. An object of this class will generate a command-line and the required input files for the program TrimAl, but will not execute the process (this is shown below). O... | gappyout = TrimalConf(pj, # The Project
method_name='gappyout', # Any unique string ('gappyout' is default)
program_name='trimal', # No alternatives in this ReproPhylo version
... | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
3.7.1.2 List comprehension to subset alignments
In this example, it is easy enough to copy and paste alignment names into a list and pass it to TrimalConf. But this is more difficult if we want to fish out a subset of alignments from a very large list of alignments. In such cases, Python's list comprehension is very us... | rRNA_locus_names = [locus.name for locus in pj.loci if locus.feature_type == 'rRNA']
print rRNA_locus_names | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
what we get is a list of names of our rRNA loci.
Getting alignment names that have locus names of rRNA loci
The following line says: "take the key of each alignment from the pj.alignments dictionary if the first word before the '@' symbol is in the list of rRNA locus names, and put this key in a list": | rRNA_alignment_names = [key for key in pj.alignments.keys() if key.split('@')[0] in rRNA_locus_names]
print rRNA_alignment_names | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
We get a list of keys, of the rRNA loci alignments we produced on the previous section, and which are stored in the pj.alignments dictionary. We can now pass this list to a new TrimalConf instance that will only process rRNA locus alignments: | gt50 = TrimalConf(pj,
method_name='gt50',
alns = rRNA_alignment_names,
trimal_commands={'gt': 0.5} # This will keep positions with up to
# 50% gaps.
) | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
3.7.2 Executing the alignment trimming process
As for the alignment phase, this is done with a Project method, which accepts a list of TrimalConf objects. | pj.trim([gappyout, gt50]) | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
Once used, these objects are also placed in the pj.used_methods dictionary, and they can be printed out for observation: | print pj.used_methods['gappyout'] | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
3.7.3 Accessing trimmed sequence alignments
3.7.3.1 The pj.trimmed_alignments dictionary
The trimmed alignments themselves are stored in the pj.trimmed_alignments dictionary, using keys that follow this pattern: locus_name@alignment_method_name@trimming_method_name where alignment_method_name is the name you have provi... | pj.trimmed_alignments | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
3.7.3.2 Accessing a MultipleSeqAlignment object
A trimmed alignment can be easily accessed and manipulated with any of Biopython's AlignIO tricks using the fta Project method: | print pj.fta('18s@muscleDefault@gt50')[:4,410:420].format('phylip-relaxed') | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
3.7.3.3 Writing trimmed sequence alignment files
Trimmed alignment text files can be dumped in any AlignIO format for usage in an external command line or GUI program. When writing to files, you can control the header of the sequence by, for example, adding the organism name of the gene name, or by replacing the featur... | # record_id and source_organism are feature qualifiers in the SeqRecord object
# See section 3.4
files = pj.write_trimmed_alns(id=['record_id','source_organism'],
format='fasta')
files | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
The files will always be written to the current working directory (where this notebook file is), and can immediately be moved programmatically to avoid clutter: | # make a new directory for your trimmed alignment files:
if not os.path.exists('trimmed_alignment_files'):
os.mkdir('trimmed_alignment_files')
# move the files there
for f in files:
os.rename(f, "./trimmed_alignment_files/%s"%f) | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
3.7.3.4 Viewing trimmed alignments
Trimmed alignments can be viewed in the same way as alignments, but using this command: | pj.show_aln('MT-CO1@mafftLinsi@gappyout',id=['source_organism'])
pickle_pj(pj, 'outputs/my_project.pkpj') | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
3.7.4 Quick reference | # Make a TrimalConf object
trimconf = TrimalConf(pj, **kwargs)
# Execute alignment process
pj.trim([trimconf])
# Show AlnConf description
print pj.used_methods['method_name']
# Fetch a MultipleSeqAlignment object
trim_aln_obj = pj.fta('locus_name@aln_method_name@trim_method_name')
# Write alignment text files
pj.wr... | notebooks/Tutorials/Basic/3.7 Alignment trimming.ipynb | szitenberg/ReproPhyloVagrant | mit |
$g(x)\rightarrow 1$ for $x\rightarrow\infty$
$g(x)\rightarrow 0$ for $x\rightarrow -\infty$
$g(0) = 1/2$
Finally, to go from the regression to the classification, we can simply apply the following condition:
$$
y=\left{
\begin{array}{@{}ll@{}}
1, & \text{if}\ h_w(x)>=1/2 \
0, & \text{otherwise}
\end{array}... | # Simple example:
# we have 20 students that took an exam and we want to know if we can use
# the number of hours they studied to predict if they pass or fail the
# exam
# m = 20 training samples
# n = 1 feature (number of hours)
X = np.array([0.50, 0.75, 1.00, 1.25, 1.50, 1.75, 1.75, 2.00, 2.25, 2.50,
... | 03_Introduction_To_Supervised_Machine_Learning.ipynb | SchwaZhao/networkproject1 | mit |
Likelihood of the model
How to find the parameters, also called weights, $\underline{w}$ that best fit our training data?
We want to find the weights $\underline{w}$ that maximize the likelihood of observing the target $\underline{y}$ given the observed features $\underline{\underline{X}}$.
We need a probabilistic mode... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
fx = np.linspace(-5,5)
Ly1 = np.log2(1+np.exp(-fx))
Ly0 = np.log2(1+np.exp(-fx)) - np.log2(np.exp(-fx))
p = plt.plot(fx,Ly1,label='L(1,f(x))')
p = plt.plot(fx,Ly0,label='L(0,f(x))')
plt.xlabel('f(x)')
plt.ylabel('L')
plt.legend()
# coming back to ... | 03_Introduction_To_Supervised_Machine_Learning.ipynb | SchwaZhao/networkproject1 | mit |
Here we found the minimum of the loss function simply by computing it over a large range of values. In practice, this approach is not possible when the dimensionality of the loss function (number of weights) is very large. To find the minimum of the loss function, the gradient descent algorithm (or stochastic gradient ... | # plot the solution
x = np.linspace(0,6,100)
def h_w(x, w0=w0s[ind0], w1=w1s[ind1]):
return 1/(1+np.exp(-(w0+x*w1)))
p1 = plt.plot(x, h_w(x))
p2 = plt.plot(X,y,'ro')
tx = plt.xlabel('x [h]')
ty = plt.ylabel('y ')
# probability of passing the exam if you worked 5 hours:
print(h_w(5)) | 03_Introduction_To_Supervised_Machine_Learning.ipynb | SchwaZhao/networkproject1 | mit |
We will use the package sci-kit learn (http://scikit-learn.org/) that provide access to many tools for machine learning, data mining and data analysis. | # The same thing using the sklearn module
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(C=1e10)
# to train our model we use the "fit" method
# we have to reshape X because we have only one feature here
model.fit(X.reshape(-1,1),y)
# to see the weights
print(model.coef_)
print(model.i... | 03_Introduction_To_Supervised_Machine_Learning.ipynb | SchwaZhao/networkproject1 | mit |
Note that although the loss function is not linear, the decision function is a linear function of the weights and features. This is why the Logistic regression is called a linear model.
Other linear models are defined by different loss functions. For example:
- Perceptron: $L \left(y^{(i)}, f(x^{(i)})\right) = \max(0, ... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
fx = np.linspace(-5,5, 200)
Logit = np.log2(1+np.exp(-fx))
Percep = np.maximum(0,- fx)
Hinge = np.maximum(0, 1- fx)
ZeroOne = np.ones(fx.size)
ZeroOne[fx>=0] = 0
p = plt.plot(fx,Logit,label='Logistic Regression')
p = plt.plot(fx,Percep,label='Perc... | 03_Introduction_To_Supervised_Machine_Learning.ipynb | SchwaZhao/networkproject1 | mit |
Evaluating the performance of a binary classifier
The confusion matrix allows to visualize the performance of a classifier:
| | predicted positive | predicted negative |
| --- |:---:|:---:|
| real positive | TP | FN |
| real negative | FP | TN |
For each prediction $y_p$, we put it in one... | # for example
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
# logistic regression with L2 regularization, C controls the strength of the regularization
# C = 1/lambda
model = LogisticRegression(C=1, penalty='l... | 03_Introduction_To_Supervised_Machine_Learning.ipynb | SchwaZhao/networkproject1 | mit |
Vectorizer | from helpers.tokenizer import TextWrangler
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
bow_stem = CountVectorizer(strip_accents="ascii", tokenizer=TextWrangler(kind="stem"))
X_bow_stem = bow_stem.fit_transform(corpus.data)
tfidf_stem = TfidfVectorizer(strip_accents="ascii", tokenizer=... | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Models | from sklearn.decomposition import LatentDirichletAllocation, TruncatedSVD, NMF
n_topics = 5
lda = LatentDirichletAllocation(n_components=n_topics,
learning_decay=0.5, learning_offset=1.,
random_state=23)
lsa = TruncatedSVD(n_components=n_topics, random_... | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Pipelines | from sklearn.pipeline import Pipeline
lda_pipe = Pipeline([
("bow", bow_stem),
("lda", lda)
])
lsa_pipe = Pipeline([
("tfidf", tfidf_stem),
("lsa", lsa)
])
nmf_pipe = Pipeline([
("tfidf", tfidf_stem),
("nmf", nmf)
]) | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Gridsearch | from sklearn.model_selection import GridSearchCV
lda_model = GridSearchCV(lda_pipe, param_grid=lda_params, cv=5, n_jobs=-1)
#lda_model.fit(corpus.data)
#lda_model.best_params_ | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Training | lda_pipe.fit(corpus.data)
nmf_pipe.fit(corpus.data)
lsa_pipe.fit(corpus.data) | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Evaluation | print("LDA")
print("Log Likelihood:", lda_pipe.score(corpus.data)) | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Visual Inspection | def df_topic_model(vectorizer, model, n_words=20):
keywords = np.array(vectorizer.get_feature_names())
topic_keywords = []
for topic_weights in model.components_:
top_keyword_locs = (-topic_weights).argsort()[:n_words]
topic_keywords.append(keywords.take(top_keyword_locs))
df_to... | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Conclusion:
Topic models derived from different approaches look dissimilar. Top word distribution of NMF appears most
meaningful, mostly because its topics doesn't share same words (due to NMF algorithm). LSA topic model is
better interpretable than its LDA counterpart. Nonetheless, topics from both are hard to disti... | df_topic_word_lda = df_topic_model(vectorizer=bow_stem, model=lda_pipe.named_steps.lda, n_words=10)
df_topic_word_lsa = df_topic_model(vectorizer=tfidf_stem, model=lsa_pipe.named_steps.lsa, n_words=10)
df_topic_word_nmf = df_topic_model(vectorizer=tfidf_stem, model=nmf_pipe.named_steps.nmf, n_words=10)
def jaccard_ind... | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Conclusion:
Topics derived from different topic modeling approaches are fundamentally dissimilar.
Document-topic Assignment | nmf_topic_distr = nmf_pipe.transform(corpus.data)
collections_map = {0: "His Last Bow", 1: "The Adventures of Sherlock Holmes",
2: "The Case-Book of Sherlock_Holmes", 3: "The Memoirs of Sherlock Holmes",
4: "The Return of Sherlock Holmes"}
# Titles created from dominant words in ... | HolmesTopicModels/holmes_topic_models/notebook/2_Modeling.ipynb | donK23/pyData-Projects | apache-2.0 |
Open a GeoTIFF with GDAL
Let's look at the SERC Canopy Height Model (CHM) to start. We can open and read this in Python using the gdal.Open function: | # Note that you will need to update the filepath below according to your local machine
chm_filename = '/Users/olearyd/Git/data/NEON_D02_SERC_DP3_368000_4306000_CHM.tif'
chm_dataset = gdal.Open(chm_filename) | tutorials/Python/Lidar/intro-lidar/classify_raster_with_threshold-2018-py/classify_raster_with_threshold-2018-py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
On your own, adjust the number of bins, and range of the y-axis to get a good idea of the distribution of the canopy height values. We can see that most of the values are zero. In SERC, many of the zero CHM values correspond to bodies of water as well as regions of land without trees. Let's look at a histogram and plo... | chm_nonzero_array = copy.copy(chm_array)
chm_nonzero_array[chm_array==0]=np.nan
chm_nonzero_nonan_array = chm_nonzero_array[~np.isnan(chm_nonzero_array)]
# Use weighting to plot relative frequency
plt.hist(chm_nonzero_nonan_array,bins=50);
# plt.hist(chm_nonzero_nonan_array.flatten(),50)
plt.title('Distribution of SE... | tutorials/Python/Lidar/intro-lidar/classify_raster_with_threshold-2018-py/classify_raster_with_threshold-2018-py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Note that it appears that the trees don't have a smooth or normal distribution, but instead appear blocked off in chunks. This is an artifact of the Canopy Height Model algorithm, which bins the trees into 5m increments (this is done to avoid another artifact of "pits" (Khosravipour et al., 2014).
From the histogram w... | plot_band_array(chm_array,
chm_ext,
(0,35),
title='SERC Canopy Height',
cmap_title='Canopy Height, m',
colormap='BuGn') | tutorials/Python/Lidar/intro-lidar/classify_raster_with_threshold-2018-py/classify_raster_with_threshold-2018-py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Threshold Based Raster Classification
Next, we will create a classified raster object. To do this, we will use the numpy.where function to create a new raster based off boolean classifications. Let's classify the canopy height into five groups:
- Class 1: CHM = 0 m
- Class 2: 0m < CHM <= 10m
- Class 3: 10m < CHM <= 20... | chm_reclass = copy.copy(chm_array)
chm_reclass[np.where(chm_array==0)] = 1 # CHM = 0 : Class 1
chm_reclass[np.where((chm_array>0) & (chm_array<=10))] = 2 # 0m < CHM <= 10m - Class 2
chm_reclass[np.where((chm_array>10) & (chm_array<=20))] = 3 # 10m < CHM <= 20m - Class 3
chm_reclass[np.where((chm_array>20) & (chm_array<... | tutorials/Python/Lidar/intro-lidar/classify_raster_with_threshold-2018-py/classify_raster_with_threshold-2018-py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Use an arbitary distribution
NOTE this requires Pymc3 3.1
pymc3.distributions.DensityDist | # pymc3.distributions.DensityDist?
import matplotlib.pyplot as plt
import matplotlib as mpl
from pymc3 import Model, Normal, Slice
from pymc3 import sample
from pymc3 import traceplot
from pymc3.distributions import Interpolated
from theano import as_op
import theano.tensor as tt
import numpy as np
from scipy import ... | updating_info/Arb_dist.ipynb | balarsen/pymc_learning | bsd-3-clause |
The class-labels are One-Hot encoded, which means that each label is a vector with 10 elements, all of which are zero except for one element. The index of this one element is the class-number, that is, the digit shown in the associated image. We also need the class-numbers as integers for the test-set, so we calculate ... | data.test.cls = np.argmax(data.test.labels, axis=1)
feed_dict_test = {x: data.test.images,
y_true: data.test.labels,
y_true_cls: data.test.cls} | learn_stem/machine_learning/tensorflow/02_Convolutional_Neural_Network.ipynb | wgong/open_source_learning | apache-2.0 |
Function for performing a number of optimization iterations so as to gradually improve the variables of the network layers. In each iteration, a new batch of data is selected from the training-set and then TensorFlow executes the optimizer using those training samples. The progress is printed every 100 iterations. | # Counter for total number of iterations performed so far.
total_iterations = 0
def optimize(num_iterations, ndisplay_interval=100):
# Ensure we update the global variable rather than a local copy.
global total_iterations
# Start-time used for printing time-usage below.
start_time = time.time()
f... | learn_stem/machine_learning/tensorflow/02_Convolutional_Neural_Network.ipynb | wgong/open_source_learning | apache-2.0 |
helper-function to plot sample digits | def plot_sample9():
# Use TensorFlow to get a list of boolean values
# whether each test-image has been correctly classified,
# and a list for the predicted class of each image.
prediction, cls_pred = session.run([correct_prediction, y_pred_cls],
feed_dict=feed_dict_t... | learn_stem/machine_learning/tensorflow/02_Convolutional_Neural_Network.ipynb | wgong/open_source_learning | apache-2.0 |
Performance after 1000 optimization iterations
After 1000 optimization iterations, the model has greatly increased its accuracy on the test-set to more than 90%. | optimize(num_iterations=900) # We performed 100 iterations above. | learn_stem/machine_learning/tensorflow/02_Convolutional_Neural_Network.ipynb | wgong/open_source_learning | apache-2.0 |
test-run on 6/12/2017
Optimization Iteration: 101, Training Accuracy: 70.3%
Optimization Iteration: 201, Training Accuracy: 81.2%
Optimization Iteration: 301, Training Accuracy: 84.4%
Optimization Iteration: 401, Training Accuracy: 89.1%
Optimization Iteration: 501, Training Accuracy: 93.8%
Optimiz... | plot_sample9()
print_test_accuracy(show_example_errors=True) | learn_stem/machine_learning/tensorflow/02_Convolutional_Neural_Network.ipynb | wgong/open_source_learning | apache-2.0 |
Performance after 10,000 optimization iterations
After 10,000 optimization iterations, the model has a classification accuracy on the test-set of about 99%. | optimize(num_iterations=9000, ndisplay_interval=500) # We performed 1000 iterations above. | learn_stem/machine_learning/tensorflow/02_Convolutional_Neural_Network.ipynb | wgong/open_source_learning | apache-2.0 |
Optimization Iteration: 1, Training Accuracy: 92.2%
Optimization Iteration: 501, Training Accuracy: 98.4%
Optimization Iteration: 1001, Training Accuracy: 95.3%
Optimization Iteration: 1501, Training Accuracy: 100.0%
Optimization Iteration: 2001, Training Accuracy: 96.9%
Optimization Iteration: 2501... | plot_sample9()
print_test_accuracy(show_example_errors=True,
show_confusion_matrix=True) | learn_stem/machine_learning/tensorflow/02_Convolutional_Neural_Network.ipynb | wgong/open_source_learning | apache-2.0 |
From these images, it looks like the second convolutional layer might detect lines and patterns in the input images, which are less sensitive to local variations in the original input images.
These images are then flattened and input to the fully-connected layer, but that is not shown here.
Close TensorFlow Session
We ... | # This has been commented out in case you want to modify and experiment
# with the Notebook without having to restart it.
session.close() | learn_stem/machine_learning/tensorflow/02_Convolutional_Neural_Network.ipynb | wgong/open_source_learning | apache-2.0 |
Flip the plot by assigning the data variable to the y axis: | sns.ecdfplot(data=penguins, y="flipper_length_mm") | doc/docstrings/ecdfplot.ipynb | arokem/seaborn | bsd-3-clause |
If neither x nor y is assigned, the dataset is treated as wide-form, and a histogram is drawn for each numeric column: | sns.ecdfplot(data=penguins.filter(like="bill_", axis="columns")) | doc/docstrings/ecdfplot.ipynb | arokem/seaborn | bsd-3-clause |
You can also draw multiple histograms from a long-form dataset with hue mapping: | sns.ecdfplot(data=penguins, x="bill_length_mm", hue="species") | doc/docstrings/ecdfplot.ipynb | arokem/seaborn | bsd-3-clause |
The default distribution statistic is normalized to show a proportion, but you can show absolute counts instead: | sns.ecdfplot(data=penguins, x="bill_length_mm", hue="species", stat="count") | doc/docstrings/ecdfplot.ipynb | arokem/seaborn | bsd-3-clause |
It's also possible to plot the empirical complementary CDF (1 - CDF): | sns.ecdfplot(data=penguins, x="bill_length_mm", hue="species", complementary=True) | doc/docstrings/ecdfplot.ipynb | arokem/seaborn | bsd-3-clause |
There are several features of $g$ to note,
- For larger values of $z$ $g(z)$ approaches 1
- For more negative values of $z$ $g(z)$ approaches 0
- The value of $g(0) = 0.5$
- For $z \ge 0$, $g(z)\ge 0.5$
- For $z \lt 0$, $g(z)\lt 0.5$
0.5 will be the cutoff for decisions. That is, if $g(z) \ge 0.5$ then the "answer" is ... | # Generate 2 clusters of data
S = np.eye(2)
x1, y1 = np.random.multivariate_normal([1,1], S, 40).T
x2, y2 = np.random.multivariate_normal([-1,-1], S, 40).T
fig, ax = plt.subplots()
ax.plot(x1,y1, "o", label='neg data' )
ax.plot(x2,y2, "P", label='pos data')
xb = np.linspace(-3,3,100)
a = [0.55,-1.3]
ax.plot(xb, a[0] +... | ML-Logistic-Regression-theory.ipynb | dbkinghorn/blog-jupyter-notebooks | gpl-3.0 |
The plot above shows 2 sets of training-data. The positive case is represented by green '+' and the negative case by blue 'o'. The red line is the decision boundary $b(x) = 0.55 -1.3x$. Any test cases that are above the line are negative and any below are positive. The parameters for that red line would be what we coul... | fig, ax = plt.subplots()
x3, y3 = np.random.multivariate_normal([0,0], [[.5,0],[0,.5]] , 400).T
t = np.linspace(0,2*np.pi,400)
ax.plot((3+x3)*np.sin(t), (3+y3)*np.cos(t), "o")
ax.plot(x3, y3, "P")
xb1 = np.linspace(-5.0, 5.0, 100)
xb2 = np.linspace(-5.0, 5.0, 100)
Xb1, Xb2 = np.meshgrid(xb1,xb2)
b = Xb1**2 + Xb2**2 - ... | ML-Logistic-Regression-theory.ipynb | dbkinghorn/blog-jupyter-notebooks | gpl-3.0 |
In this plot the positive outcomes are in a circular region in the center of the plot. The decision boundary the red circle.
## Cost Function for Logistic Regression
A cost function's main purpose is to penalize bad choices for the parameters to be optimized and reward good ones. It should be easy to minimize by having... | z = np.linspace(-10,10,100)
fig, ax = plt.subplots()
ax.plot(z, g(z))
ax.set_title('Sigmoid Function 1/(1 + exp(-z))', fontsize=24)
ax.annotate('Convex', (-7.5,0.2), fontsize=18 )
ax.annotate('Concave', (3,0.8), fontsize=18 )
z = np.linspace(-10,10,100)
plt.plot(z, -np.log(g(z)))
plt.title("Log Sigmoid Function -log(... | ML-Logistic-Regression-theory.ipynb | dbkinghorn/blog-jupyter-notebooks | gpl-3.0 |
Recall that in the training-set $y$ are labels with a values or 0 or 1. The cost function will be broken down into two cases for each data point $(i)$, one for $y=1$ and one for $y=0$. These two cases can then be combined into a single cost function $J$
$$ \bbox[25px,border:2px solid green]{
\begin{align} J^{(i)}{y=1}... | x = np.linspace(-10,10,50)
plt.plot(g(x), -np.log(g(x)))
plt.title("h(x) vs J(a)=-log(h(x)) for y = 1", fontsize=24)
plt.xlabel('h(x)')
plt.ylabel('J(a)') | ML-Logistic-Regression-theory.ipynb | dbkinghorn/blog-jupyter-notebooks | gpl-3.0 |
You can see from this plot that when $y=1$ the cost $J(a)$ is large if $h(x)$ goes toward 0. That is, it favors $h(x)$ going to 1 which is what we want. | x = np.linspace(-10,10,50)
plt.plot(g(x), -np.log(1-g(x)))
plt.title("h(x) vs J(a)=-log(1-h(x)) for y = 0", fontsize=24)
plt.xlabel('h(x)')
plt.ylabel('J(a)') | ML-Logistic-Regression-theory.ipynb | dbkinghorn/blog-jupyter-notebooks | gpl-3.0 |
Data Generation
A set of periodic microstructures and their volume averaged elastic stress values $\bar{\sigma}_{xx}$ can be generated by importing the make_elastic_stress_random function from pymks.datasets. This function has several arguments. n_samples is the number of samples that will be generated, size specifies ... | from pymks.datasets import make_elastic_stress_random
sample_size = 200
grain_size = [(15, 2), (2, 15), (7, 7), (8, 3), (3, 9), (2, 2)]
n_samples = [sample_size] * 6
elastic_modulus = (410, 200)
poissons_ratio = (0.28, 0.3)
macro_strain = 0.001
size = (21, 21)
X, y = make_elastic_stress_random(n_samples=n_samples, siz... | notebooks/stress_homogenization_2D.ipynb | XinyiGong/pymks | mit |
These default parameters may not be the best model for a given problem, we will now show one method that can be used to optimize them.
Optimizing the Number of Components and Polynomial Order
To start with, we can look at how the variance changes as a function of the number of components.
In general for SVD as well as ... | model.n_components = 40
model.fit(X, y, periodic_axes=[0, 1])
| notebooks/stress_homogenization_2D.ipynb | XinyiGong/pymks | mit |
Roughly 90 percent of the variance is captured with the first 5 components. This means our model may only need a few components to predict the average stress.
Next we need to optimize the number of components and the polynomial order. To do this we are going to split the data into testing and training sets. This can be... | from sklearn.cross_validation import train_test_split
flat_shape = (X.shape[0],) + (np.prod(X.shape[1:]),)
X_train, X_test, y_train, y_test = train_test_split(X.reshape(flat_shape), y,
test_size=0.2, random_state=3)
print(X_train.shape)
print(X_test.shape)
| notebooks/stress_homogenization_2D.ipynb | XinyiGong/pymks | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.