markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Next, we give this configuration to Evaluator and run it. | # Use TFMA to compute a evaluation statistics over features of a model and
# validate them against a baseline.
# The model resolver is only required if performing model validation in addition
# to evaluation. In this case we validate against the latest blessed model. If
# no model has been blessed before (as in this c... | site/en-snapshot/tfx/tutorials/tfx/components.ipynb | tensorflow/docs-l10n | apache-2.0 |
Using the evaluation output we can show the default visualization of global metrics on the entire evaluation set. | context.show(evaluator.outputs['evaluation']) | site/en-snapshot/tfx/tutorials/tfx/components.ipynb | tensorflow/docs-l10n | apache-2.0 |
To see the visualization for sliced evaluation metrics, we can directly call the TensorFlow Model Analysis library. | import tensorflow_model_analysis as tfma
# Get the TFMA output result path and load the result.
PATH_TO_RESULT = evaluator.outputs['evaluation'].get()[0].uri
tfma_result = tfma.load_eval_result(PATH_TO_RESULT)
# Show data sliced along feature column trip_start_hour.
tfma.view.render_slicing_metrics(
tfma_result, ... | site/en-snapshot/tfx/tutorials/tfx/components.ipynb | tensorflow/docs-l10n | apache-2.0 |
This visualization shows the same metrics, but computed at every feature value of trip_start_hour instead of on the entire evaluation set.
TensorFlow Model Analysis supports many other visualizations, such as Fairness Indicators and plotting a time series of model performance. To learn more, see the tutorial.
Since we ... | blessing_uri = evaluator.outputs['blessing'].get()[0].uri
!ls -l {blessing_uri} | site/en-snapshot/tfx/tutorials/tfx/components.ipynb | tensorflow/docs-l10n | apache-2.0 |
Pusher
The Pusher component is usually at the end of a TFX pipeline. It checks whether a model has passed validation, and if so, exports the model to _serving_model_dir. | pusher = tfx.components.Pusher(
model=trainer.outputs['model'],
model_blessing=evaluator.outputs['blessing'],
push_destination=tfx.proto.PushDestination(
filesystem=tfx.proto.PushDestination.Filesystem(
base_directory=_serving_model_dir)))
context.run(pusher) | site/en-snapshot/tfx/tutorials/tfx/components.ipynb | tensorflow/docs-l10n | apache-2.0 |
Assume we have a FATE Flow Service in 127.0.0.1:9380(defaults in standalone), then exec | !pipeline init --ip 127.0.0.1 --port 9380 | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
upload data
Before start a modeling task, the data to be used should be uploaded.
Typically, a party is usually a cluster which include multiple nodes. Thus, when we upload these data, the data will be allocated to those nodes. | from pipeline.backend.pipeline import PipeLine | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
Make a pipeline instance:
- initiator:
* role: guest
* party: 9999
- roles:
* guest: 9999
note that only local party id is needed. | pipeline_upload = PipeLine().set_initiator(role='guest', party_id=9999).set_roles(guest=9999) | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
Define partitions for data storage | partition = 4 | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
Define table name and namespace, which will be used in FATE job configuration | dense_data_guest = {"name": "breast_hetero_guest", "namespace": f"experiment"}
dense_data_host = {"name": "breast_hetero_host", "namespace": f"experiment"}
tag_data = {"name": "breast_hetero_host", "namespace": f"experiment"} | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
Now, we add data to be uploaded. To create uuid as sid, turn on extend_sid option. Alternatively, set auto_increasing_sid to make extended sid starting at 0. | data_base = "/workspace/FATE/"
pipeline_upload.add_upload_data(file=os.path.join(data_base, "examples/data/breast_hetero_guest.csv"),
table_name=dense_data_guest["name"], # table name
namespace=dense_data_guest["namespace"], # namespace... | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
We can then upload data | pipeline_upload.upload(drop=1) | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
After uploading, we can then start modeling. Here we build a Hetero SecureBoost model the same way as in this demo, but note how specificaiton of DataTransform module needs to be adjusted to crrectly load in match id. | from pipeline.backend.pipeline import PipeLine
from pipeline.component import Reader, DataTransform, Intersection, HeteroSecureBoost, Evaluation
from pipeline.interface import Data
pipeline = PipeLine() \
.set_initiator(role='guest', party_id=9999) \
.set_roles(guest=9999, host=10000)
reader_0 = Reade... | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
Add components to pipeline, in order of execution:
- data_transform_0 comsume reader_0's output data
- intersect_0 comsume data_transform_0's output data
- hetero_secureboost_0 consume intersect_0's output data
- evaluation_0 consume hetero_secureboost_0's prediciton result on training data
Then compile our pipeline t... | pipeline.add_component(reader_0)
pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))
pipeline.add_component(intersect_0, data=Data(data=data_transform_0.output.data))
pipeline.add_component(hetero_secureboost_0, data=Data(train_data=intersect_0.output.data))
pipeline.add_component(evaluation_... | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
Now, submit(fit) our pipeline: | pipeline.fit() | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
Check data output on FATEBoard or download component output data to see now each data instance has a uuid as sid. | import json
print(json.dumps(pipeline.get_component("data_transform_0").get_output_data(limits=3), indent=4)) | doc/tutorial/pipeline/pipeline_tutorial_match_id.ipynb | FederatedAI/FATE | apache-2.0 |
First, data following a (zero-inflated) negative binomial (ZINB) distribution is created for testing purposes. Test size and distribution parameters can be specified.
For a specified number of marker genes in a cluster, distribution of these genes follows a different ZINB distribution. We use the following notation:
$z... | seed(1234)
# n_cluster needs to be smaller than n_simulated_cells, n_marker_genes needs to be smaller than n_simulated_genes
n_simulated_cells=1000
n_simulated_genes=100
n_cluster=100
n_marker_genes=10
# Specify parameter between 0 and 1 for zero_inflation and p, positive integer for r
# Differential gene expression is... | 171106_t-test_wilcoxon_comparison/Generic Comparison T-Test Wilcoxon-Rank-Sum Test.ipynb | theislab/scanpy_usage | bsd-3-clause |
Create data.
Both sample names and variable names are simply intgers starting from 0. | adata=AnnData(np.multiply(binomial(1,reference_zero_inflation,(n_simulated_cells,n_simulated_genes)),
negative_binomial(reference_n,reference_p,(n_simulated_cells,n_simulated_genes))))
# adapt marker_genes for cluster
adata.X[0:n_cluster,0:n_marker_genes]=np.multiply(binomial(1,cluster_zero_i... | 171106_t-test_wilcoxon_comparison/Generic Comparison T-Test Wilcoxon-Rank-Sum Test.ipynb | theislab/scanpy_usage | bsd-3-clause |
Cluster according to true grouping:
The following code includes the true grouping such that it can be accessed by normal function calling of
sc.tl.rank_genes_groups(adata,'true_groups')
or, respectively,
sc.tl.rank_genes_groups(adata,'true_groups', test_type='wilcoxon') | import pandas as pd
smp='true_groups'
true_groups_int=np.ones((n_simulated_cells,))
true_groups_int[0:n_cluster]=0
true_groups=list()
for i,j in enumerate(true_groups_int):
true_groups.append(str(j))
adata.smp['true_groups']=pd.Categorical(true_groups, dtype='category')
adata.uns[smp + '_order']=np.asarray(['0','1... | 171106_t-test_wilcoxon_comparison/Generic Comparison T-Test Wilcoxon-Rank-Sum Test.ipynb | theislab/scanpy_usage | bsd-3-clause |
Testing
Case 1: No mean difference, large variance difference.
Using the data created above, we get the following expectation and variance
$\mathbb{E}[Z_r]=\mathbb{E}[Z_c]=0.9$
$\mathbb{V}[Z_r]=8.19$
$\mathbb{V}[Z_c]=1.89$ | sc.tl.rank_genes_groups(adata, 'true_groups')
sc.pl.rank_genes_groups(adata, n_genes=20)
sc.tl.rank_genes_groups(adata, 'true_groups', test_type='wilcoxon')
sc.pl.rank_genes_groups(adata, n_genes=20) | 171106_t-test_wilcoxon_comparison/Generic Comparison T-Test Wilcoxon-Rank-Sum Test.ipynb | theislab/scanpy_usage | bsd-3-clause |
As can be seen above, not on only does the wilcoxon-rank-sum test detect all marker genes, but there is also a clear difference to all other genes in ranking.
Case 2: No mean difference, smaller variance difference | # n_cluster needs to be smaller than n_simulated_cells, n_marker_genes needs to be smaller than n_simulated_genes
n_simulated_cells=1000
n_simulated_genes=100
n_cluster=100
n_marker_genes=10
# Specify parameter between 0 and 1 for zero_inflation and p, positive integer for r
# Differential gene expression is simulated ... | 171106_t-test_wilcoxon_comparison/Generic Comparison T-Test Wilcoxon-Rank-Sum Test.ipynb | theislab/scanpy_usage | bsd-3-clause |
This parameter initialization leads to the following expectations/ variances:
$\mathbb{E}[Z_r]=\mathbb{E}[Z_c]=0.9$
$\mathbb{V}[Z_r]=6.39$
$\mathbb{V}[Z_c]=1.89$ | adata=AnnData(np.multiply(binomial(1,reference_zero_inflation,(n_simulated_cells,n_simulated_genes)),
negative_binomial(reference_n,reference_p,(n_simulated_cells,n_simulated_genes))))
# adapt marker_genes for cluster
adata.X[0:n_cluster,0:n_marker_genes]=np.multiply(binomial(1,cluster_zero_i... | 171106_t-test_wilcoxon_comparison/Generic Comparison T-Test Wilcoxon-Rank-Sum Test.ipynb | theislab/scanpy_usage | bsd-3-clause |
With smaller difference in variance, still all marker genes are detected, but less clearly.
Case 3: Small difference in expectation, difference in variance | # n_cluster needs to be smaller than n_simulated_cells, n_marker_genes needs to be smaller than n_simulated_genes
n_simulated_cells=1000
n_simulated_genes=100
n_cluster=100
n_marker_genes=10
# Specify parameter between 0 and 1 for zero_inflation and p, positive integer for r
# Differential gene expression is simulated ... | 171106_t-test_wilcoxon_comparison/Generic Comparison T-Test Wilcoxon-Rank-Sum Test.ipynb | theislab/scanpy_usage | bsd-3-clause |
This parameter initialization leads to the following expectations/ variances:
$\mathbb{E}[Z_r]=0.9$
$\mathbb{E}[Z_c]=1.47$
$\mathbb{V}[Z_r]=6.39$
$\mathbb{V}[Z_c]=2.92$ | adata=AnnData(np.multiply(binomial(1,reference_zero_inflation,(n_simulated_cells,n_simulated_genes)),
negative_binomial(reference_n,reference_p,(n_simulated_cells,n_simulated_genes))))
# adapt marker_genes for cluster
adata.X[0:n_cluster,0:n_marker_genes]=np.multiply(binomial(1,cluster_zero_i... | 171106_t-test_wilcoxon_comparison/Generic Comparison T-Test Wilcoxon-Rank-Sum Test.ipynb | theislab/scanpy_usage | bsd-3-clause |
In AXON it will be formatted as:
``` yaml
application: "myapp"
version: "alpha-001"
runtime: "python27"
api_version: 1
threadsafe: true
url handlers
handlers: [
{ url: "/"
script: "home.app" }
{ url: "/index.html"
script: "home.app" }
{ url: "/stylesheets"
static_dir: "stylesheets" }
{ url: "/(..(gif|png|... | # print all urls
import axon
val = axon.load("example_config1.axon")
print([entry["url"] for entry in val["handlers"]]) | examples/axon_readable_as_yaml.ipynb | intellimath/pyaxon | mit |
With AXON it can be also presented in the following form:
``` yaml
_
application: "myapp"
version: "alpha-001"
runtime: "python27"
api_version: 1
threadsafe: true
# url handlers
handlers
_
url: "/"
script: "home.app"
_
url: "/index.html"
script: "home.app"
_
url: "... | # print all urls
vals = axon.load("example_config2.axon")
print([entry.url for entry in vals[0].handlers]) | examples/axon_readable_as_yaml.ipynb | intellimath/pyaxon | mit |
As shown above, I managed to collect data for 56 exams. It seems that the minimum mean mark was of 37, and the maximum was of 83.66. On average, it looks like exams tend to end up with a mark slightly above 60 (std of 9.39), about 66% percent have been closed exams, and I collected slightly more data from 3rd years (as... | # Create a quick function to allow reusing
def scatter_plot(independent, dependent, title="", xlabel="", ylabel=""):
plt.scatter(independent,dependent)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
scatter_plot(data['likes'],data['mean'],
title="Relationsh... | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
Alright, there is very little structure here, but let's see how it looks when we use the percentage of students. | data['likes_normalised'] = (100 * data['likes'])/data['number_of_students']
scatter_plot(data['likes_normalised'],data['mean'],
title="Relationship between percentage of likes and mean mark",
xlabel="Percentage of students who liked the announcements",
... | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
Quite a bit better, but let's do it for the median as it seems like a more intuitive measurement here: half the students below the median got less than the mark indicated on the y axis. Also, the median is more resilient to outliers which may be helpful in this case. | scatter_plot(data['likes_normalised'],data['median'],
title="Relationship between percentage of likes and median mark",
xlabel="Percentage of students who liked the announcements",
ylabel="Median mark") | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
Alright, without starting to remove outliers, this seems to be the best I have. I will stay away from outlier detection, and from the graph there doesn't seem to be any really obvious one (maybe besides that one at 80+ median, but I won't go there).
The structure looks like it can be fitted with a polynomial curve, so ... | from sklearn import linear_model
# Convert series to dataframes to prepare them for fitting
X = pd.DataFrame(data['likes_normalised'])
y = pd.DataFrame(data['median'])
# Add a squared feature
X = pd.concat([X,pow(X,2)],axis=1)
# Fit data with linear regression
model_linear = linear_model.LinearRegression()
model_lin... | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
Looks about right to me. I don't think stopping here would be a bad decision, but for the sake of it, I will try to fit it with a cubic polynomial. | # Add a 3rd power and fit the new data
X_ = pd.concat([X,pow(X.iloc[:,0],3)],axis=1)
model_linear.fit(X_,y)
test_x_ = pd.concat([test_x, pow(test_x.iloc[:,0],3)],axis=1)
plt.plot(test_x_.iloc[:,0],model_linear.predict(test_x_))
# Plot points
scatter_plot(X_[[0]],y,
title="Relationship between per... | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
Looks pretty, but it likely overfits. So let's try to add L2 regularization and find the regularization parameter through 10-fold cross validation. | from sklearn.linear_model import RidgeCV
list_reg_params = np.linspace(0.00001, X_.max().max() * 100, 2000)
model_ridge = linear_model.RidgeCV(alphas=list_reg_params, cv=10)
model_ridge.fit(X_,y)
reg_param = model_ridge.alpha_
print("The regularization parameter that provided the best results was {}.".format(reg_para... | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
The regularization parameter introduced only a very subtle difference. It's also a very big number as I haven't normalised the data. Now let's see which of the 2 polynomial curves fit the data better.
Evaluating the models | model_ridge_reg = linear_model.Ridge(alpha=reg_param)
from sklearn import cross_validation
scores_quadratic = abs(cross_validation.cross_val_score(
model_linear, X, y, cv=10, scoring="mean_absolute_error"))
scores_cubic = abs(cross_validation.cross_val_score(
model_ridge_reg, X_, y, cv=10, scoring="me... | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
Not too bad. An error of less than 7 marks is better than I expected. Now for a comparison test, let's just predict that the median of a module is the mean of the medians of all the other modules (but using K-fold CV). | from sklearn.metrics import mean_absolute_error
from sklearn.cross_validation import KFold
kf = KFold(X.shape[0], n_folds=10)
scores_naive = []
for train, test in kf:
train_mean = data['median'][train].mean()
scores_naive.append(mean_absolute_error(data['median'][test], [train_mean] * len(test)))
print("A... | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
D'aww, the regression predictor is not much better than the naive one. At least it's not worse! As a last test, let's see what are the chances that the the regression results are better just by chance. For this, a paired one-tailed t-test will be performed, with the null hypothesis that the 2 algorithms perform the sam... | from scipy.stats import ttest_rel
results = ttest_rel(scores_naive, scores_cubic)
print("P-value: {:.4f}" .format(results.pvalue/2)) # Dividing by 2 because it's one-tailed | notebooks/predicting_marks_by_facebook_likes.ipynb | liviu-/notebooks | mit |
Local team
Happens to be the Carolina Panthers. So let's look at their offence. | car = df[(df.OffenseTeam=='CAR')] | nfl_viz.ipynb | fdion/infographics_research | mit |
Pandas plot does a decent job, but doesn't know about categoricals. We can't use the game date string for X axis. Here we use the datetime we calculated from quarter, mins etc. But now it thinks it's a time series. Which it looks like one. Consider it instead a form of parallel plot, ignoring the slope graph between ea... | ax = car.plot(x='datetime', y='Yards') | nfl_viz.ipynb | fdion/infographics_research | mit |
Not bad, but not completely helpful. Sure, pandas also has bar plots. But I think something else could be better visually. Let's see what Seaborn has to offer. How about a strip plot? It is a scatter plot for categorical data. We'll add jitter on the x axis to better see the data | g = sns.stripplot(x='GameDate', y='Yards', data=car, jitter=True)
for item in g.get_xticklabels(): item.set_rotation(60)
# We can also alter the look of the strip plot significantly
g = sns.stripplot(x='Yards', y='GameDate', data=car,
palette="Set2", size=6, marker="D", edgecolor="gray", alpha=.25) | nfl_viz.ipynb | fdion/infographics_research | mit |
Dare to compare
How about comparing two teams? Say, Carolina and Atlanta. Let's see how they do in yards (loss and gains) per quarters, for this season up to 9/13. | car_atl = df[(df.OffenseTeam=='CAR')|(df.OffenseTeam=='ATL')] | nfl_viz.ipynb | fdion/infographics_research | mit |
Colors can really improve readability. Atlanta Falcons primary color is red and Carolina Panthers primary color is light blue. Using those (context manager with color_palette): | with sns.color_palette([sns.color_palette("muted")[2],sns.color_palette("muted")[5]]):
g = sns.stripplot(x='Quarter', y='Yards', data=car_atl, hue='OffenseTeam', jitter=True)
g.hlines(0,-1,6, color='grey') | nfl_viz.ipynb | fdion/infographics_research | mit |
Distribution
We can also look at the distribution using plot types that are specifically designed for this. One pandas dataframe method is boxplot. Does the job, although we can make something prettier than this. | ax = car.boxplot(column='Yards', by='GameDate')
ax.set_title("Carolina offence Yardage by game") | nfl_viz.ipynb | fdion/infographics_research | mit |
Let's have a look at the same thing using Seaborn. We'll fix the x axis tick labels too, rotating them. | g = sns.boxplot(data=car, y='Yards', x='GameDate')
for item in g.get_xticklabels(): item.set_rotation(60) | nfl_viz.ipynb | fdion/infographics_research | mit |
Finally, let's look at one more way to look at the distribution of data using Seaborn's violin plot. | g = sns.violinplot(data=car, x='Yards', y='GameDate', orient='h')
g.vlines(0,-1,15, alpha=0.5) | nfl_viz.ipynb | fdion/infographics_research | mit |
La pizza
Prenons comme exemple le prix des pizzas par diametre. | Diametre = [[6], [9], [12], [15], [18], [30]]
prix = [[7], [9], [13], [17.5], [18], [24]]
plt.figure()
plt.title('Pizza v diametre')
plt.xlabel('Diametre (cm)')
plt.ylabel(u'Prix (€)')
plt.plot(Diametre, prix, 'k.')
plt.axis([0, 32, 0, 25])
plt.grid(True)
plt.show() | practicum/05_regression/regression-lineaire.ipynb | JeffAbrahamson/MLWeek | gpl-3.0 |
Et si on trouvait une pizza de 25 cm de diametre. Quel serait un prix raisonnable selon notre modèle? | from sklearn.linear_model import LinearRegression
model = LinearRegression()
X = Diametre
y = prix
model.fit(X, y)
print(u'Une pizza à 25 cm doit coûter {px:.2f} €'.format(
px=model.predict([[12]])[0][0])) | practicum/05_regression/regression-lineaire.ipynb | JeffAbrahamson/MLWeek | gpl-3.0 |
La class sklearn.linear_model.LinearRegression est un estimateur (estimator). Un estimateur prédit une valeur à partir de données observées. Brèf, ça crée un modèle.
Tous les estimateurs en scikit-learn implémentent les méthodes fit() et predict().
Example : la diabète
Scikit-learn propose des exemples d'ensemble de ... | # Code source: Jaques Grobler
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# Use only one feature
diabetes_X = diabetes.data[:, np.newaxis]
diabetes_X_temp = diabetes_X[:, :, 2]
... | practicum/05_regression/regression-lineaire.ipynb | JeffAbrahamson/MLWeek | gpl-3.0 |
Generate data | # adjacency matrix
W = np.zeros((num_feats, num_feats))
for i in range(num_feats/mod_size):
W[i*mod_size:(i+1)*mod_size, i*mod_size:(i+1)*mod_size] = np.ones((mod_size, mod_size))
if not i == (num_feats/mod_size - 1):
W[(i+1)*mod_size-1, (i+1)*mod_size] = 1
W[(i+1)*mod_size, (i+1)*mod_size-1] = ... | StructuredSparsityDataGeneration.ipynb | chagaz/sfan | mit |
Save generated data
The data used in the StructuredSparsity.ipnb notebook is saved under data/struct_spars. Here it will be generated under data/my_struct_spars. | data_rep = 'data/my_struct_spars'
X_fname = '%s/X.data' % data_rep
y_fname = '%s/y.data' % data_rep
W_fname = '%s/W.data' % data_rep
causl_fname = '%s/causl.data' % data_rep
wghts_fname = '%s/w_causl.data' % data_rep
np.savetxt(X_fname, X, fmt='%d')
np.savetxt(y_fname, y)
np.savetxt(W_fname, W, fmt='%.1f')
np.savetxt(... | StructuredSparsityDataGeneration.ipynb | chagaz/sfan | mit |
對原始資料進行 Sacle to 0~1 之間,避免 weight 太劇烈變動,導至 learning rate 難以設定 | from sklearn.preprocessing import scale,MinMaxScaler
scaler1 = MinMaxScaler()
scaler2 = MinMaxScaler()
f1 = f2.reshape([f1.shape[0],1])
f2 = f2.reshape([f2.shape[0],1])
scaler1.fit(f1)
scaler2.fit(f2)
f1 = scaler1.transform(f1)
f2 = scaler2.transform(f2)
f1 = f1.reshape(f1.shape[0])
f2 = f2.reshape(f2.shape[0])
... | LogisticRegression.ipynb | texib/deeplearning_homework | mit |
LogisticRegression 公式推導如下
推導過程請參考 : http://speech.ee.ntu.edu.tw/~tlkagk/courses/ML_2017/Lecture/Logistic%20Regression%20(v4).pdf
中的 3~13 頁,其重點步驟如下
令 $y=sigmoid(w*x+b)=f_{w,b}$
我們想要 Maxima右邊這個式之 => $ ArgMaxL_{w,b}= \prod\left( \hat yf_{w,b} + (1-\hat y)(1-f_{w,b}) \right) $
但如果我們要看成 Lose Function 反過加上個負號並取 Log 方便計算,所以式... | import math
w1 =1
w2 =1
b = 0
r = 0.001
def fx(x1,x2):
temp = w1*x1 + w2*x2 + b
y_head = 1. / (1. + math.exp(-1.*temp))
return y_head
def cross_entropy(Y, A):
m = len(A)
cost = -(1.0 / m) * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
return cost
for i in range(10000):
w1_delta=0
... | LogisticRegression.ipynb | texib/deeplearning_homework | mit |
Initiate experiment with this input file: | importlib.reload(pynoddy.history)
importlib.reload(pynoddy.experiment)
from pynoddy.experiment import monte_carlo
ue = pynoddy.experiment.Experiment(history)
ue.change_cube_size(100)
ue.plot_section('y') | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Before we start to draw random realisations of the model, we should first store the base state of the model for later reference. This is simply possibel with the freeze() method which stores the current state of the model as the "base-state": | ue.freeze() | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
We now intialise the random generator. We can directly assign a random seed to simplify reproducibility (note that this is not essential, as it would be for the definition in a script function: the random state is preserved within the model and could be retrieved at a later stage, as well!): | ue.set_random_seed(12345) | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
The next step is to define probability distributions to the relevant event parameters. Let's first look at the different events: | ue.info(events_only = True)
ev2 = ue.events[2]
ev2.properties | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Next, we define the probability distributions for the uncertain input parameters: | param_stats = [{'event' : 2,
'parameter': 'Slip',
'stdev': 300.0,
'type': 'normal'},
{'event' : 2,
'parameter': 'Dip',
'stdev': 10.0,
'type': 'normal'},]
ue.set_parameter_statistics(param_stats)
resolution = 100
ue.cha... | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
This example shows how the base module for reproducible experiments with kinematics can be used. For further specification, child classes of Experiment can be defined, and we show examples of this type of extension in the next sections.
Adjustments to generate training set
First step: generate more layers and randomly ... | ue.random_draw()
s1 = ue.get_section('y')
s1.block.shape
s1.block[np.where(s1.block == 3)] = 1
s1.plot_section('y', cmap='Greys') | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Idea: generate many layers, then randomly extract a couple of these and also assign different density/ color values: | nm = pynoddy.history.NoddyHistory()
# add stratigraphy
n_layers = 8
strati_options['num_layers'] = n_layers
strati_options['layer_names'] = []
strati_options['layer_thickness'] = []
for n in range(n_layers):
strati_options['layer_names'].append("layer %d" % n)
strati_options['layer_thickness'].append(5000./... | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
All in one function
Generate images for normal faults | # back to before: re-initialise model:
nm = pynoddy.history.NoddyHistory()
# add stratigraphy
n_layers = 18
strati_options['num_layers'] = n_layers
strati_options['layer_names'] = []
strati_options['layer_thickness'] = []
for n in range(n_layers):
strati_options['layer_names'].append("layer %d" % n)
strati_... | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Generate training set for normal faults: | n_train = 10000
F_train = np.empty((n_train, 28*28))
ue.change_cube_size(100)
for i in range(n_train):
# randomly select layers:
ue.random_draw()
s1 = ue.get_section('y')
# create "feature" model:
f1 = s1.block.copy()
# randomly select layers:
f1 = np.squeeze(f1)
# n_featuers: number o... | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Generate reverse faults
And now: the same for reverse faults: | # back to before: re-initialise model:
nm = pynoddy.history.NoddyHistory()
# add stratigraphy
n_layers = 18
strati_options['num_layers'] = n_layers
strati_options['layer_names'] = []
strati_options['layer_thickness'] = []
for n in range(n_layers):
strati_options['layer_names'].append("layer %d" % n)
strati_... | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Generate simple layer structure
No need for noddy, in this simple case - just adapt a numpy array: | l1 = np.empty_like(s1.block[:,0,:])
n_layers = 18
for i in range(l1.shape[0]):
l1[:,i] = i
l1_ori = np.floor(l1*n_layers/l1.shape[0])
F_train_line = np.empty((n_train, 28*28))
for i in range(n_train):
n_features = 4
vals = np.random.randint(0,255,size=n_features)
l1 = l1_ori.copy()
for n in ran... | docs/notebooks/Training_Set_3.ipynb | flohorovicic/pynoddy | gpl-2.0 |
Using 8 estimators (usage of one per core if 8 cores (jobs) are used)
One RandomForestClassifier (RFC) for each number of jobs (1 to 8 (inclusive)) is instantiated and trained on the training set of 200k elements. During the training the train time is measured with the magic %timeit function and stored in an array. | # Create Random Forest Classifier
estimators = 8 # For mapping one estimator per core in case of max 8 cores
jobs = 8
time_it_results = []
for _ in range(jobs):
rf_class = RandomForestClassifier(n_estimators=estimators, n_jobs=(_+1))
tr = %timeit -o rf_class.fit(X_train, Y_train)
time_it_results.append(tr)... | notebooks/henrik_ueb01/02_Classification.ipynb | hhain/sdap17 | mit |
Plot of the training time in seconds of each RFC against the number of used cores (number of jobs) | x = np.arange(1,9)
labels = ['%i. Core' % i for i in x]
fig = plt.figure()
fig.suptitle('Training Time per number of cores')
ax = fig.add_subplot(111)
ax.set_xlabel('Number of cores')
ax.set_ylabel('Training time (s)')
ax.plot(x, best_times)
plt.xticks(x, labels, rotation='vertical')
plt.show() | notebooks/henrik_ueb01/02_Classification.ipynb | hhain/sdap17 | mit |
特徴量列を使用して構造化データを分類する
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https://www.tensorflow.org/tutorials/structured_data/feature_columns"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a>
</td>
<td> <a target="_blank" href="https://colab.re... | !pip install sklearn
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import feature_column
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
Pandasを使ったデータフレーム作成
Pandasは、構造化データの読み込みや操作のための便利なユーティリティを持つPythonのライブラリです。ここでは、Pandasを使ってURLからデータをダウンロードし、データフレームに読み込みます。 | URL = 'https://storage.googleapis.com/applied-dl/heart.csv'
dataframe = pd.read_csv(URL)
dataframe.head()
dataframe.head() | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
ターゲット変数を作成する
元のデータセットでは、ペットが引き取られるまでの期間 (1 週目、1 か月目、3 か月目など) を予測することがタスクとなっていますが、このチュートリアルでは、このタスクを単純化します。ここでは、このタスクを二項分類問題にし、単にペットが引き取られるかどうかのみを予測します。
ラベルの列を変更すると、0 は引き取られなかった、1 は引き取られたことを示すようになります。 | # In the original dataset "4" indicates the pet was not adopted.
dataframe['target'] = np.where(dataframe['AdoptionSpeed']==4, 0, 1)
# Drop un-used columns.
dataframe = dataframe.drop(columns=['AdoptionSpeed', 'Description']) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
データフレームを、訓練用、検証用、テスト用に分割
ダウンロードしたデータセットは1つのCSVファイルです。これを、訓練用、検証用、テスト用のデータセットに分割します。 | train, test = train_test_split(dataframe, test_size=0.2)
train, val = train_test_split(train, test_size=0.2)
print(len(train), 'train examples')
print(len(val), 'validation examples')
print(len(test), 'test examples') | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
tf.dataを使った入力パイプラインの構築
次に、tf.data を使ってデータフレームをラップします。こうすることで、特徴量の列を Pandas データフレームの列からモデルトレーニング用の特徴量へのマッピングするための橋渡し役として使うことができます。(メモリに収まらないぐらいの) 非常に大きな CSV ファイルを扱う場合には、tf.data を使ってディスクから直接 CSV ファイルを読み込むことになります。この方法は、このチュートリアルでは取り上げません。 | # Pandasデータフレームからtf.dataデータセットを作るためのユーティリティメソッド
def df_to_dataset(dataframe, shuffle=True, batch_size=32):
dataframe = dataframe.copy()
labels = dataframe.pop('target')
ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
if shuffle:
ds = ds.shuffle(buffer_size=len(dataframe))
ds = ds.batch(... | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
入力パイプラインを理解する
入力パイプラインを構築したので、それが返すデータのフォーマットを見るために呼び出してみましょう。出力を読みやすくするためにバッチサイズを小さくしてあります。 | for feature_batch, label_batch in train_ds.take(1):
print('Every feature:', list(feature_batch.keys()))
print('A batch of ages:', feature_batch['Age'])
print('A batch of targets:', label_batch ) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
ご覧のとおり、データセットは、データフレームの行から列の値にマップしている列名の (データフレームの列名) のディクショナリを返しています。
特徴量列の様々な型のデモ
TensorFlow には様々な型の特徴量列があります。このセクションでは、いくつかの型の特徴量列を作り、データフレームの列をどのように変換するかを示します。 | # いくつかの型のfeature columnsを例示するためこのバッチを使用する
example_batch = next(iter(train_ds))[0]
# feature columnsを作りデータのバッチを変換する
# ユーティリティメソッド
def demo(feature_column):
feature_layer = layers.DenseFeatures(feature_column)
print(feature_layer(example_batch).numpy()) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
数値コラム
特徴量列の出力はモデルへの入力になります (上記で定義したデモ関数を使うと、データフレームの列がどのように変換されるかを見ることができます)。数値列は、最も単純な型の列です。数値列は実数特徴量を表現するのに使われます。この列を使う場合、モデルにはデータフレームの列の値がそのまま渡されます。 | photo_count = feature_column.numeric_column('PhotoAmt')
demo(photo_count) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
PetFinder データセットでは、データフレームのほとんどの列がカテゴリカル型です。
バケット化コラム
数値をそのままモデルに入力するのではなく、値の範囲に基づいた異なるカテゴリに分割したいことがあります。例えば、人の年齢を表す生データを考えてみましょう。バケット化列を使うと年齢を数値列として表現するのではなく、年齢をいくつかのバケットに分割できます。以下のワンホット値が、各行がどの年齢範囲にあるかを表していることに注目してください。 | age = feature_column.numeric_column('Age')
age_buckets = feature_column.bucketized_column(age, boundaries=[1, 3, 5])
demo(age_buckets) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
カテゴリー型コラム
このデータセットでは、型は (「犬」や「猫」などの) 文字列として表現されています。文字列を直接モデルに入力することはできません。まず、文字列を数値にマッピングする必要があります。カテゴリカル語彙列を使うと、(上記で示した年齢バケットのように) 文字列をワンホットベクトルとして表現することができます。語彙はcategorical_column_with_vocabulary_list を使ってリストで渡すか、categorical_column_with_vocabulary_file を使ってファイルから読み込むことができます。 | thal = feature_column.categorical_column_with_vocabulary_list(
'thal', ['fixed', 'normal', 'reversible'])
thal_one_hot = feature_column.indicator_column(thal)
demo(thal_one_hot) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
埋め込み型コラム
数種類の文字列ではなく、カテゴリごとに数千 (あるいはそれ以上) の値があるとしましょう。カテゴリの数が多くなってくると、様々な理由から、ワンホットエンコーディングを使ってニューラルネットワークをトレーニングすることが難しくなります。埋め込み列を使うと、こうした制約を克服することが可能です。埋め込み列は、データを多次元のワンホットベクトルとして表すのではなく、セルの値が 0 か 1 かだけではなく、どんな数値でもとれるような密な低次元ベクトルとして表現します。埋め込みのサイズ (下記の例では 8) は、チューニングが必要なパラメータです。
重要ポイント: カテゴリカル列が多くの選択肢を持つ場合、埋め込み列を使用する... | # この埋込み型コラムの入力は、先程作成したカテゴリ型コラムであることに注意
thal_embedding = feature_column.embedding_column(thal, dimension=8)
demo(thal_embedding) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
ハッシュ化特徴量列
値の種類が多いカテゴリカル列を表現するもう一つの方法として、categorical_column_with_hash_bucket を使うことができます。この特徴量列は入力のハッシュ値を計算し、文字列をエンコードするために hash_bucket_size バケットの 1 つを選択します。この列を使用する場合には、語彙を用意する必要はありません。また、スペースの節約のために、実際のカテゴリ数に比べて極めて少ない hash_buckets 数を選択することも可能です。
重要ポイント: この手法の重要な欠点の一つは、異なる文字列が同じバケットにマッピングされ、衝突が発生する可能性があるということです。しかしながら、デ... | thal_hashed = feature_column.categorical_column_with_hash_bucket(
'thal', hash_bucket_size=1000)
demo(feature_column.indicator_column(thal_hashed)) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
フィーチャークロス列
複数の特徴量をまとめて1つの特徴量にする、フィーチャークロスとして知られている手法は、モデルが特徴量の組み合わせの一つ一つに別々の重みを学習することを可能にします。ここでは年齢と型を交差させて新しい特徴量を作ってみます。(crossed_column) は、起こりうるすべての組み合わせ全体の表 (これは非常に大きくなる可能性があります) を作るものではないことに注意してください。フィーチャークロス列は、代わりにバックエンドとして hashed_column を使用しているため、表の大きさを選択することができます。 | crossed_feature = feature_column.crossed_column([age_buckets, animal_type], hash_bucket_size=10)
demo(feature_column.indicator_column(crossed_feature)) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
使用するコラムを選択する
これまで、いくつかの特徴量列の使い方を見てきました。これからモデルのトレーニングにそれらを使用します。このチュートリアルの目的は、特徴量列を使うのに必要な完全なコード (いわば仕組み) を示すことです。以下ではモデルをトレーニングするための列を適当に選びました。
キーポイント:正確なモデルを構築するのが目的である場合には、できるだけ大きなデータセットを使用して、どの特徴量を含めるのがもっとも意味があるのかや、それらをどう表現したらよいかを、慎重に検討してください。 | feature_columns = []
# 数値コラム
for header in ['age', 'trestbps', 'chol', 'thalach', 'oldpeak', 'slope', 'ca']:
feature_columns.append(feature_column.numeric_column(header))
# バケット化コラム
age_buckets = feature_column.bucketized_column(age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65])
feature_columns.append(age_bu... | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
特徴量層の構築
特徴量列を定義したので、次に DenseFeatures レイヤーを使って Keras モデルに入力します。 | feature_layer = tf.keras.layers.DenseFeatures(feature_columns) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
これまでは、feature columnsの働きを見るため、小さなバッチサイズを使ってきました。ここではもう少し大きなバッチサイズの新しい入力パイプラインを作ります。 | batch_size = 32
train_ds = df_to_dataset(train, batch_size=batch_size)
val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)
test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size) | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
モデルの構築、コンパイルと訓練 | model = tf.keras.Sequential([
feature_layer,
layers.Dense(128, activation='relu'),
layers.Dense(128, activation='relu'),
layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
model.fit(train_ds,
validat... | site/ja/tutorials/structured_data/feature_columns.ipynb | tensorflow/docs-l10n | apache-2.0 |
Write a function named draw_circle that draws a circle using SVG. Your function should take the parameters of the circle as function arguments and have defaults as shown. You will have to write the raw SVG code as a Python string and then use the IPython.display.SVG object and IPython.display.display function. | from IPython.display import HTML
def draw_circle(width=100, height=100, cx=25, cy=25, r=5, fill='red'):
"""Draw an SVG circle.
Parameters
----------
width : int
The width of the svg drawing area in px.
height : int
The height of the svg drawing area in px.
cx : int
... | assignments/assignment06/InteractEx05.ipynb | sthuggins/phys202-2015-work | mit |
Use interactive to build a user interface for exploing the draw_circle function:
width: a fixed value of 300px
height: a fixed value of 300px
cx/cy: a slider in the range [0,300]
r: a slider in the range [0,50]
fill: a text area in which you can type a color's name
Save the return value of interactive to a variable n... | w = interactive(draw_circle, width=fixed(300),height=fixed(300),cx=(0,300), cy=(0,300), r=(0,50), fill="red")
c = w.children
assert c[0].min==0 and c[0].max==300
assert c[1].min==0 and c[1].max==300
assert c[2].min==0 and c[2].max==50
assert c[3].value=='red' | assignments/assignment06/InteractEx05.ipynb | sthuggins/phys202-2015-work | mit |
We have 2 banners promoting a new sport club.
The first banner is aggressive: it focuses on the weight equipment we have and is very attractive to crossfitters, but completely can't convince runners. Another one makes the main focus on the cardio trainers we have and is much more attractive for runners. The neutral ban... | crossfitters_ratio = .48
aggressive = {"crossfitters": .68, "runners": .04}
neutral = {"crossfitters": .28, "runners": .4}
def test_banner(banner, shows):
runners_dist = stats.bernoulli(banner["runners"])
crossfitters_dist = stats.bernoulli(banner["crossfitters"])
crossfitters_cnt = stats.bernoulli(cross... | Thompson Sampling.ipynb | dmittov/misc | apache-2.0 |
To decide which banner is better we run experiment. We show both banners to random clients and make the conclusions out of the data we get.
Imagine we ran an experiment and computed the Convertion Rate as #Convertions / #Shows. That's a point estimation = 💩
To make some statistically significant conclusions we need to... | %%time
revenue_agressive = [test_banner(aggressive, 100) for _ in range(1000)]
revenue_neutral = [test_banner(neutral, 100) for _ in range(1000)]
sns.distplot(revenue_agressive, label="agressive")
sns.distplot(revenue_neutral, label="neutral")
plt.legend()
%%time
revenue_agressive = [test_banner(aggressive, 1000) for ... | Thompson Sampling.ipynb | dmittov/misc | apache-2.0 |
Regret - the money we lost on an experiment. If we have a magic oracle that tells you which banner is the best without any experiments you save ~ 347k - 343k = 4k €
You also may compute regret in counts of the "bad" banner shows. The loss in each show is the same. So, regret is 1M shows.
Due to we know how the real wor... | .48 * .68 + .52 * .04, .48 * .28 + .52 * .4 | Thompson Sampling.ipynb | dmittov/misc | apache-2.0 |
Usually you have too many factors and it's hard to say if two banners have real different conversion rate. The less difference the more audience you need to find the difference.
So, you want to have some early stopping method + the tool to compare more than 2 banners the same time.
There are some tools in classis stati... | xs = np.linspace(0, 1, 100)
plt.plot(xs, stats.beta(1, 1).pdf(xs), label="alpha = 1 beta = 1")
plt.plot(xs, stats.beta(.1, .1).pdf(xs), label="alpha = .1 beta = .1")
plt.plot(xs, stats.beta(7, 3).pdf(xs), label="alpha = 7 beta = 3")
plt.legend() | Thompson Sampling.ipynb | dmittov/misc | apache-2.0 |
$Pr(A|B) = \frac{Pr(B|A)Pr(A)}{Pr(B)}$
$X$ - events (click/no-click)
CTR is a distribution, obviously it's defined on [0,1] (dom of Beta distribution).
$Pr(CTR|X) = \frac{Pr(X|CTR)Pr(CTR)}{Pr(X)} = \frac{Binomial(CTR) * Beta(\alpha, \beta)}{\int{Binomial(CTR) * Beta(\alpha, \beta)}} = \frac{Bernoulli(CTR) * Beta(\alpha... | xs = np.linspace(0, 1, 100)
plt.plot(xs, stats.beta(7, 3).pdf(xs), label="alpha = 7 beta = 3")
plt.plot(xs, stats.beta(70, 30).pdf(xs), label="alpha = 21 beta = 9")
plt.plot(xs, stats.beta(700, 300).pdf(xs), label="alpha = 70 beta = 30")
plt.axvline(.7, 0, 1, color="red")
plt.legend() | Thompson Sampling.ipynb | dmittov/misc | apache-2.0 |
What banner to show
Let's create a lottery. On each show <s>sample</s> draw a dice out of Beta distribution and have a CTR point estimation. | crossfitters_ratio = .48
aggressive = {"crossfitters": .68, "runners": .04}
neutral = {"crossfitters": .28, "runners": .4}
agressive_beta = {"alpha": 1, "beta": 1}
neutral_beta = {"alpha": 1, "beta": 1}
regret = 0
revenue = 0
for _ in tqdm(range(2000000)):
aggresive_score = stats.beta(agressive_beta["alpha"], ag... | Thompson Sampling.ipynb | dmittov/misc | apache-2.0 |
Define the objective function | # Set the objective function
from pyai.optimize.functions import sphere1d
from pyai.optimize.functions import sphere2d | python_scipy_optimize_brute_force_en.ipynb | jdhp-docs/python-notebooks | mit |
Minimize using the "Brute force" algorithm
Uses the "brute force" method, i.e. computes the function's value at each point of a multidimensional grid of points, to find the global minimum of the function.
See https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.brute.html#scipy.optimize.brute
First examp... | %%time
search_ranges = (slice(-3., 3.5, 0.5),)
res = optimize.brute(sphere1d,
search_ranges,
#args=params,
full_output=True,
finish=None) # optimize.fmin)
print("x* =", res[0])
print("f(x*) =", res[1])
print(res[2].shape)
print(... | python_scipy_optimize_brute_force_en.ipynb | jdhp-docs/python-notebooks | mit |
Second example: the 2D sphere function | %%time
search_ranges = (slice(-2., 2.5, 0.5), slice(-2., 2.5, 0.5))
res = optimize.brute(sphere2d,
search_ranges,
#args=params,
full_output=True,
finish=None) # optimize.fmin)
print("x* =", res[0])
print("f(x*) =", res[1])
print... | python_scipy_optimize_brute_force_en.ipynb | jdhp-docs/python-notebooks | mit |
Retrieving training and test data
The MNIST data set already contains both training and test data. There are 55,000 data points of training data, and 10,000 points of test data.
Each MNIST data point has:
1. an image of a handwritten digit and
2. a corresponding label (a number 0-9 that identifies the image)
We'll cal... | # mnist fails to load, so got this patch from the nd101 slack
def patched_read32(bytestream):
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0]
mnist._read32 = patched_read32
# Retrieve the training and test data
trainX, trainY, testX, testY = mnist.load_data(one... | Handwritten Digit Recognition with TFLearn.ipynb | khalido/nd101 | gpl-3.0 |
Visualize the training data
Provided below is a function that will help you visualize the MNIST data. By passing in the index of a training example, the function show_digit will display that training image along with it's corresponding label in the title. | # Visualizing the data
import matplotlib.pyplot as plt
%matplotlib inline
# Function for displaying a training image by it's index in the MNIST set
def show_digit(index):
label = trainY[index].argmax(axis=0)
# Reshape 784 array into 28x28 image
image = trainX[index].reshape([28,28])
plt.title('Training... | Handwritten Digit Recognition with TFLearn.ipynb | khalido/nd101 | gpl-3.0 |
Building the network
TFLearn lets you build the network by defining the layers in that network.
For this example, you'll define:
The input layer, which tells the network the number of inputs it should expect for each piece of MNIST data.
Hidden layers, which recognize patterns in data and connect the input to the ou... | # Define the neural network
def build_model():
# This resets all parameters and variables, leave this here
tf.reset_default_graph()
#### Your code ####
# Include the input layer, hidden layer(s), and set how you want to train the model
#input layer
net = tflearn.input_data([None, 784])... | Handwritten Digit Recognition with TFLearn.ipynb | khalido/nd101 | gpl-3.0 |
هذه الدالة تعطينا توصيف كامل للبيانات و تكشف لنا في ما إذا كانت هناك قيم مفقودة | df.info() | Pima Project/Pima Project 2.0.ipynb | Faris137/MachineLearningArabic | mit |
سيبورن مكتبة جميلة للرسوميات سهلة في الكتابة لكن مفيدة جداً في المعلومات التي ممكن ان نقراءها عبر الهيستوقرام
فائدها ممكن ان تكون في
1- تلخيص توزيع البينات في رسوميات
2- فهم او الإطلاع على القيم الفريدة
3- تحمل الرسوميات معنى اعمق من الكلمات | sb.countplot(x='Outcome',data=df, palette='hls')
sb.countplot(x='Pregnancies',data=df, palette='hls')
sb.countplot(x='Glucose',data=df, palette='hls')
sb.heatmap(df.corr())
sb.pairplot(df, hue="Outcome")
from scipy.stats import kendalltau
sb.jointplot(df['Pregnancies'], df['Glucose'], kind="hex", stat_func=kendall... | Pima Project/Pima Project 2.0.ipynb | Faris137/MachineLearningArabic | mit |
تجربة استخدام تقييس و تدريج الخواص لتحسين اداء النموذج | columns = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age']
labels = df['Outcome'].values
features = df[list(columns)].values
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.30)
clf = RandomForestClassifier(n_estimators=... | Pima Project/Pima Project 2.0.ipynb | Faris137/MachineLearningArabic | mit |
تجربة تحسين اداء النموذج باستخدام طريقة
standard scaler | #scaling
scaler = StandardScaler()
# Fit only on training data
scaler.fit(X_train)
X_train = scaler.transform(X_train)
# apply same transformation to test data
X_test = scaler.transform(X_test)
clf = RandomForestClassifier(n_estimators=1)
clf = clf.fit(X_train, y_train)
accuracy = clf.score(X_train, y_train)
print '... | Pima Project/Pima Project 2.0.ipynb | Faris137/MachineLearningArabic | mit |
تجربة تحسين اداء النموذج بطريقة
min-max scaler | columns = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age']
labels = df['Outcome'].values
features = df[list(columns)].values
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.30)
scaler = preprocessing.MinMaxScaler()
sca... | Pima Project/Pima Project 2.0.ipynb | Faris137/MachineLearningArabic | mit |
유니코드 문자열
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/load_data/unicode"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" /> TensorFlow.org에서 보기</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/gi... | import tensorflow as tf | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.