markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Scipy: Statistische Funktionen und mehr
Die PDF erhalten wir ebenfalls aus Scipy. Um sie plotten zu können, müssen wir sie auf eine Reihe von Werten anwenden um Datenpunkte zu erhalten. Hier zeigt sich erneut die Stärke von Numpy: wir können einfach die Funktion auf das ganze Array anwenden und erhalten ein Array von E... | import scipy.stats
pdf = scipy.stats.norm(2, 3).pdf
xs = np.linspace(-15, 15, 5000) # Erzeuge 5000 äquidistante Werte im Interval [-15, 15).
plt.hist(gauss, bins=20, normed=True, label='Werte')
plt.plot(xs, pdf(xs), label='PDF')
plt.xlabel('Wert')
plt.ylabel('Relative Häufigkeit')
plt.legend() | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit |
Das sieht doch schon mal hübsch aus. Zum Abschluss wollen wir noch Unsicherheiten auf die Bins berechnen und in das Histogramm eintragen. Um es einfach zu halten, verwenden wir nicht die normierte PDF, sondern skalieren unsere PDF auf unsere Daten. | bins, edges = np.histogram(gauss, bins=20)
bin_width = edges[1] - edges[0] # Alle Bins haben die gleiche Breite
centres = edges[:-1] + bin_width / 2
def scaled_pdf(x):
return bin_width * n_events * pdf(x)
plt.errorbar( # Typisches "Teilchenphysikerhistorgamm"
centres, # x
bins, # y
xerr=bin_width/... | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit |
ComicAnalyzer
雑誌分析用に,ComicAnalyzerクラスを定義します. | class ComicAnalyzer():
"""漫画雑誌の目次情報を読みだして,管理するクラスです."""
def __init__(self, data_path='data/wj-api.json', min_week=7, short_week=10):
"""
初期化時に,data_pathにある.jsonファイルから目次情報を抽出します.
- self.data: 全目次情報を保持するリスト型
- self.all_titles: 全作品名情報を保持するリスト型
- self.serialized_titles: ... | 1_analyze_comic_data_j.ipynb | haltaro/predicting-comic-end | mit |
かなりわかりづらい処理をしているので,初期化時(__init__())の動作を補足します.
1. self.all_titlesは文字通り全ての作品名を保持します.しかし,self.all_titlesは,明らかに読みきり作品や企画作品を含んでしまっています.
2. そこで,min_week以上連載した作品self.serialized_titlesとして抽出します.しかし,self.serialized_titlesは,データベースの最新の目次情報の時点で,連載を継続中の作品を含んでおり,連載継続期間が不正確になってしまいます.例えば,「鬼滅の刃」など現在も連載中の人気作が,21週で連載が終了した作品のように見えてしまいます.
3... | wj = ComicAnalyzer() | 1_analyze_comic_data_j.ipynb | haltaro/predicting-comic-end | mit |
10週以内で終わった最新10タイトルの最初の10話分の掲載順(worst)を表示してみます.値が大きいほど,巻頭付近に掲載されていたことになります. | for title in wj.short_end_titles[-10:]:
plt.plot(wj.extract_item(title)[:10], label=title[:6])
plt.xlabel('Week')
plt.ylabel('Worst')
plt.ylim(0,22)
plt.legend() | 1_analyze_comic_data_j.ipynb | haltaro/predicting-comic-end | mit |
あれ?「斉木楠雄」って結構連載していたんじゃ…?こういうときは,search_title()を使います. | wj.search_title('斉木', wj.all_titles)
len(wj.extract_item('超能力者 斉木楠雄のΨ難'))
wj.extract_item('超能力者 斉木楠雄のΨ難', 'year'), \
wj.extract_item('超能力者 斉木楠雄のΨ難', 'no')
len(wj.extract_item('斉木楠雄のΨ難')) | 1_analyze_comic_data_j.ipynb | haltaro/predicting-comic-end | mit |
どうやら,「超能力者 斉木楠雄のΨ難」で試験的に7回読み切り掲載したあと,「斉木楠雄のΨ難」の連載を開始したみたいですね(wikipedia).
次は,近年のヒット作(独断)の最初の10話分の掲載順を表示します. | target_titles = ['ONE PIECE', 'NARUTO-ナルト-', 'BLEACH', 'HUNTER×HUNTER']
for title in target_titles:
plt.plot(wj.extract_item(title)[:10], label=title[:6])
plt.ylim(0,22)
plt.xlabel('Week')
plt.ylabel('Worst')
plt.legend() | 1_analyze_comic_data_j.ipynb | haltaro/predicting-comic-end | mit |
個人的に気になったので,50話まで掲載順を見てみます. | target_titles = ['ONE PIECE', 'NARUTO-ナルト-', 'BLEACH', 'HUNTER×HUNTER']
for title in target_titles:
plt.plot(wj.extract_item(title)[:50], label=title[:6])
plt.ylim(0,22)
plt.xlabel('Week')
plt.ylabel('Worst')
plt.legend() | 1_analyze_comic_data_j.ipynb | haltaro/predicting-comic-end | mit |
ある程度予想はしてましたが,さすがですね.ちなみにですが,extract_item()を使ってサブタイトルを取得しながら掲載順を見ると,マンガ好きの方は楽しいと思います. | wj.extract_item('ONE PIECE', 'subtitle')[:10] | 1_analyze_comic_data_j.ipynb | haltaro/predicting-comic-end | mit |
さて,seabornで相関分析をやってみます.ここでは,ひとまず6週目までの掲載順をプロットします.同じ座標に複数の点が重なって非常に見づらいので,便宜上ランダムなノイズを加えて見栄えを整えます.なお,1週目を外したのは,ほとんどの場合巻頭に掲載されるためです. | end_data = pd.DataFrame(
[[wj.extract_item(title)[1] + np.random.randn() * .3,
wj.extract_item(title)[2] + np.random.randn() * .3,
wj.extract_item(title)[3] + np.random.randn() * .3,
wj.extract_item(title)[4] + np.random.randn() * .3,
wj.extract_item(title)[5] + np.random.randn() * .3,
... | 1_analyze_comic_data_j.ipynb | haltaro/predicting-comic-end | mit |
WikiData | endpoint = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql'
query = """
PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?president ?cause ?dob ?dod WHERE {... | 23-bnf.ipynb | loujine/musicbrainz-dataviz | mit |
Data BNF
http://data.bnf.fr/fr/opendata | endpoint = 'http://data.bnf.fr/sparql'
query = """
SELECT ?artist ?name ?bdate ?ddate ?wdurl ?mburl
WHERE {
?artist isni:identifierValid "0000000108935378" .
?artist owl:sameAs ?wdurl .
FILTER (regex (?wdurl, "wikidata.org"))
?artist owl:sameAs ?mburl .
FILTER (regex (?mburl, "musicbrainz.org")) .
... | 23-bnf.ipynb | loujine/musicbrainz-dataviz | mit |
Working with Data in DataFrames (Tranform)
| import re
import pandas as pd
LATEST_DISH_DATA_DF = pd.DataFrame.from_csv(os.path.join(DATA_DIR, 'Dish.csv'),
index_col='id')
LATEST_ITEM_DATA_DF = pd.DataFrame.from_csv(os.path.join(DATA_DIR, 'MenuItem.csv'),
index_col='dish_id'... | 4-intro-to-pandas.ipynb | digital-humanities-data-curation/hilt2015 | mit |
Dish.csv | NULL_APPEARANCES = LATEST_DISH_DATA_DF[LATEST_DISH_DATA_DF.times_appeared == 0]
print('Data set contains {0} dishes that appear 0 times …'.format(
len(NULL_APPEARANCES))
)
NON_NULL_DISH_DATA_DF = LATEST_DISH_DATA_DF[LATEST_DISH_DATA_DF.times_appeared != 0]
discarded_columns = [n for n in NON_NULL_DISH_DATA_DF.co... | 4-intro-to-pandas.ipynb | digital-humanities-data-curation/hilt2015 | mit |
MenuItem.csv | discarded_columns2 = [n for n in LATEST_ITEM_DATA_DF.columns if n not in
['id', 'menu_page_id', 'xpos', 'ypos']]
print('Discarding columns from MenuItem.csv …')
for discard2 in discarded_columns2:
print('{0} … removed'.format(discard2))
TRIMMED_ITEM_DATA_DF = LATEST_ITEM_DATA_DF[['id', 'men... | 4-intro-to-pandas.ipynb | digital-humanities-data-curation/hilt2015 | mit |
MenuPage.csv | LATEST_PAGE_DATA_DF.head()
LATEST_PAGE_DATA_DF[['full_height', 'full_width']].astype(int, raise_on_error=False) | 4-intro-to-pandas.ipynb | digital-humanities-data-curation/hilt2015 | mit |
Menu.csv | LATEST_MENU_DATA_DF.columns
discarded_columns3 = [n for n in LATEST_MENU_DATA_DF.columns if n not in
['sponsor', 'location', 'date', 'page_count', 'dish_count']]
pipeline_logger.info('Discarding columns from Menu.csv …')
for discard3 in discarded_columns3:
pipeline_logger.info('{0} … remove... | 4-intro-to-pandas.ipynb | digital-humanities-data-curation/hilt2015 | mit |
Merging DataFrames | MERGED_ITEM_PAGES_DF = pd.merge(TRIMMED_ITEM_DATA_DF, LATEST_PAGE_DATA_DF,
left_on='menu_page_id', right_index=True, )
MERGED_ITEM_PAGES_DF.columns = ['item_id', 'menu_page_id', 'xpos', 'ypos',
'menu_id', 'page_number',
... | 4-intro-to-pandas.ipynb | digital-humanities-data-curation/hilt2015 | mit |
Feature Crosses in BigQuery
We'll first explore how to create a feature cross in BigQuery. The cell below will create a dataset called babyweight in your GCP project, if it does not already exist. This dataset will will house our tables and models. | bq = bigquery.Client()
dataset = bigquery.Dataset(bq.dataset("babyweight"))
try:
bq.create_dataset(dataset)
print("Dataset created.")
except:
print("Dataset already exists.") | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Create datasets for training and evaluation | %%bigquery
CREATE OR REPLACE TABLE
babyweight.babyweight_data AS
SELECT
weight_pounds,
CAST(is_male AS STRING) AS is_male,
mother_age,
CASE
WHEN plurality = 1 THEN "Single(1)"
WHEN plurality = 2 THEN "Twins(2)"
WHEN plurality = 3 THEN "Triplets(3)"
WHEN plurality = 4 ... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Next, we'll create tables in BigQuery that we'll use for training and evaluation. | %%bigquery
CREATE OR REPLACE TABLE
babyweight.babyweight_data_train AS
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
mother_race
FROM
babyweight.babyweight_data
WHERE
ABS(MOD(hashmonth, 4)) < 3
%%bigquery
CREATE OR REPLACE TABLE
babyweight.babyweight_dat... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Create model in BigQuery | %%bigquery
CREATE OR REPLACE MODEL `babyweight.natality_model`
OPTIONS
(MODEL_TYPE="DNN_REGRESSOR",
HIDDEN_UNITS=[64, 32],
BATCH_SIZE=32,
INPUT_LABEL_COLS=["weight_pounds"],
DATA_SPLIT_METHOD="NO_SPLIT") AS
SELECT
weight_pounds,
is_male,
plurality,
gestation_weeks,
mother_age,
CAST(mother_... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
We can use ML.EVALUATE to determine the root mean square error of our model on the evaluation set. | query = """
SELECT
*, SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL `babyweight.natality_model`,
(
SELECT
weight_pounds,
is_male,
plurality,
gestation_weeks,
mother_age,
CAST(mother_race AS STRING) AS mother_race
FROM
babyweight.babyweight_data_eval ))... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Creating a Feature Cross with BQML
Next, we'll create a feature cross of the features is_male and mother_race. To create a feature cross we apply ML.FEATURE_CROSS to a STRUCT of the features is_male and mother_race cast as a string.
The STRUCT clause creates an ordered pair of the two features. The TRANSFORM clause is... | %%bigquery
CREATE OR REPLACE MODEL `babyweight.natality_model_feat_eng`
TRANSFORM(weight_pounds,
is_male,
plurality,
gestation_weeks,
mother_age,
CAST(mother_race AS string) AS mother_race,
ML.FEATURE_CROSS(
STRUCT(
is_male,
plurality)
) ... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
As before, we compute the root mean square error. | query = """
SELECT
*, SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL `babyweight.natality_model_feat_eng`,
(
SELECT
weight_pounds,
is_male,
plurality,
gestation_weeks,
mother_age,
CAST(mother_race AS STRING) AS mother_race
FROM
babyweight.babyweight_dat... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Feature Crosses in Keras
Next, we'll see how to implement a feature cross in Tensorflow using feature columns. | import os
import tensorflow as tf
import datetime
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow import feature_column as fc
# Determine CSV, label, and key columns
# Create list of string column headers, make sure order matches.
CSV_COLUMNS = ["weight_pounds",
"is_ma... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Make a dataset of features and label. | def features_and_labels(row_data):
"""Splits features and labels from feature dictionary.
Args:
row_data: Dictionary of CSV column names and tensor values.
Returns:
Dictionary of feature tensors and label tensor.
"""
label = row_data.pop(LABEL_COLUMN)
return row_data, label
de... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
We'll need to get the data read in by our input function to our model function, but just how do we go about connecting the dots? We can use Keras input layers (tf.Keras.layers.Input). | def create_input_layers():
"""Creates dictionary of input layers for each feature.
Returns:
Dictionary of `tf.Keras.layers.Input` layers for each feature.
"""
inputs = {
colname: tf.keras.layers.Input(
name=colname, shape=(), dtype="float32")
for colname in ["mother_... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Create feature columns for inputs
Next, define the feature columns. mother_age and gestation_weeks should be numeric. The others, is_male, plurality and mother_race, should be categorical. Remember, only dense feature columns can be inputs to a DNN.
The last feature column created in the create_feature_columns function... | def categorical_fc(name, values):
cat_column = fc.categorical_column_with_vocabulary_list(
key=name, vocabulary_list=values)
return fc.indicator_column(categorical_column=cat_column)
def create_feature_columns():
feature_columns = {
colname : fc.numeric_column(key=colname)
... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
We can double-check the output of create_feature_columns. | feature_columns = create_feature_columns()
print("Feature column keys: \n{}\n".format(list(feature_columns.keys())))
print("Feature column values: \n{}\n".format(list(feature_columns.values()))) | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Define a DNN model
Next we define our model. This is regression so make sure the output layer activation is correct and that the shape is right. We'll create deep neural network model, similar to what we use in BigQuery. | def get_model_outputs(inputs):
# Create two hidden layers of [64, 32] just in like the BQML DNN
h1 = layers.Dense(64, activation="relu", name="h1")(inputs)
h2 = layers.Dense(32, activation="relu", name="h2")(h1)
# Final output is a linear activation because this is regression
output = layers.Dense(... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Finally, we will build the model using tf.keras.models.Model giving our inputs and outputs and then compile our model with an optimizer, a loss function, and evaluation metrics. | def build_dnn_model():
"""Builds simple DNN using Keras Functional API.
Returns:
`tf.keras.models.Model` object.
"""
# Create input layer
inputs = create_input_layers()
# Create feature columns
feature_columns = create_feature_columns()
# The constructor for DenseFeatures take... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Train and evaluate our model
We've built our Keras model using our inputs from our CSV files and the architecture we designed. Let's now run our model by training our model parameters and periodically running an evaluation to track how well we are doing on outside data as training goes on. We'll need to load both our t... | %%time
tf.random.set_seed(33)
TRAIN_BATCH_SIZE = 32
NUM_TRAIN_EXAMPLES = 1000 * 5 # training dataset repeats, it'll wrap around
NUM_EVALS = 5 # how many times to evaluate
# Enough to get a reasonable sample, but not so much that it slows down
NUM_EVAL_EXAMPLES = 1000
trainds = load_dataset(
pattern="./data/bab... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Need for regularization
Let's use a high-cardinality feature cross to illustrate the point. In this model, we are predicting taxifare in New York city using a feature cross of lat and lon | !bq show mlpatterns || bq mk mlpatterns
%%bigquery
CREATE OR REPLACE TABLE mlpatterns.taxi_data AS
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_datetime,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_... | 02_data_representation/feature_cross.ipynb | GoogleCloudPlatform/ml-design-patterns | apache-2.0 |
Table 1 - Spitzer IRAC/MIPS IC348 catalog | tbl1 = ascii.read("http://iopscience.iop.org/1538-3881/131/3/1574/fulltext/datafile1.txt")
tbl1[0:4] | notebooks/Lada2006.ipynb | BrownDwarf/ApJdataFrames | mit |
Table 2 - SED Derived $\alpha_{IRAC}$ and $A_V$
But really... spectral types | tbl2 = ascii.read("http://iopscience.iop.org/1538-3881/131/3/1574/fulltext/datafile2.txt")
tbl2[0:4]
join_tbls = join(tbl1, tbl2, keys="Seq")
print "There are {} rows in tbl1, {} in tbl2, and {} in the joined table.".format(len(tbl1), len(tbl2), len(join_tbls))
join_tbls[0:4] | notebooks/Lada2006.ipynb | BrownDwarf/ApJdataFrames | mit |
Table 3 - Convenient passbands table | names = ["PASSBAND","DATA SYSTEM","REFERENCES","center_wavelength","F_{nu} (Jy)","References"]
tbl3 = pd.read_csv("http://iopscience.iop.org/1538-3881/131/3/1574/fulltext/204953.tb3.txt",
na_values="\ldots", names = names, sep='\t')
tbl3.head() | notebooks/Lada2006.ipynb | BrownDwarf/ApJdataFrames | mit |
Load data and show loaded variables. The data dictionary contains the full normalised read count marices for training and test file as well as a list of the respective gene names (either gene symbols or ENSEMBL - specify in the is_Ens option) and a list of cell cycle genes. In addition labels for traning and testing sh... | data = load_data(CFG, is_Ens=True, het_only=True, het_onlyCB=False, gene_set='GOCB')#gene_set can be either a list of genes,
class_labels = data['class_labels']#['G1','G2M','S']#['T-cells']#d#['Liver']#['early', 'late', 'mid']#data['class_labels']#['G1', 'S','G2M']#['Liver']#[data['class_labels']#['T-cells']##['G1', 'S... | py/demo/demo_cyclone.ipynb | PMBio/cyclone | apache-2.0 |
The data required to build the model are loaded. Next, we initialise the model. | cyclone = cyclone(data['Y'],row_namesY= data['genes'],cc_geneNames= data['cc_ens'],labels = data['labels'],
Y_tst = data['Y_test'], row_namesY_tst = data['genes_tst'], labels_tst = data['labels_tst']) | py/demo/demo_cyclone.ipynb | PMBio/cyclone | apache-2.0 |
2. Train model
By default, a 10-fold corss-validation is performed on the training data to estimate the gernealizability of the gene set used for a number of classifers (PCA based, random forest, logistic regression, lasso and SVM (with rbf kernel)); then the model is trained on the entire data-set and applied to the t... | cyclone.trainModel(rftop = 40, cv=10, out_dir = out_dir, do_pca=1, npc=1, is_SVM=0) | py/demo/demo_cyclone.ipynb | PMBio/cyclone | apache-2.0 |
3. Plot results
Results can be visualised in terms of barplots indicating the distributions of predicted cell cycle phases for the individual classes/labels in the test data (both int erms of absolute cells and as relative plot). In addition a barplot for the cross-validation results as well as cell-cycle phase specifi... | cyclone.plotHistograms(class_labels = class_labels, out_dir = out_dir, method='GNB', do_h=True)
cyclone.plotPerformance(plot_test=False, out_dir =out_dir, method='GNB') | py/demo/demo_cyclone.ipynb | PMBio/cyclone | apache-2.0 |
In addition to the barplots the confidence of the classifier can be visualised in form of a scatter plot. By default, a scatter plot for the test data is shown; a scatter plot for the training data can be shown by setting the plot_test argument to False. The scores to be shown on the x- and y-axis can be chosen using t... | cyclone.plotScatter(plot_test = True, xaxis = 0, yaxis = 2, xlab = 'G1 score', ylab = 'G2M score', class_labels = class_labels, out_dir = out_dir, method='GNB')
cyclone.plotScatter(plot_test = False, xaxis = 0, yaxis = 2, xlab = 'G1 score', ylab = 'G2M score', class_labels = ['G1', 'S', 'G2M'], out_dir = out_dir, metho... | py/demo/demo_cyclone.ipynb | PMBio/cyclone | apache-2.0 |
Getting and converting the data
数据获取与格式转换 | path = untar_data(URLs.BIWI_HEAD_POSE)
cal = np.genfromtxt(path/'01'/'rgb.cal', skip_footer=6); cal
fname = '09/frame_00667_rgb.jpg'
def img2txt_name(f): return path/f'{str(f)[:-7]}pose.txt'
img = open_image(path/fname)
img.show()
ctr = np.genfromtxt(img2txt_name(fname), skip_header=3); ctr
def convert_biwi(coord... | zh-nbs/Lesson3_head_pose.ipynb | fastai/course-v3 | apache-2.0 |
Creating a dataset
创建一个数据集 | data = (PointsItemList.from_folder(path)
.split_by_valid_func(lambda o: o.parent.name=='13')
.label_from_func(get_ctr)
.transform(get_transforms(), tfm_y=True, size=(120,160))
.databunch().normalize(imagenet_stats)
)
data.show_batch(3, figsize=(9,6)) | zh-nbs/Lesson3_head_pose.ipynb | fastai/course-v3 | apache-2.0 |
Train model
训练模型 | learn = cnn_learner(data, models.resnet34)
learn.lr_find()
learn.recorder.plot()
lr = 2e-2
learn.fit_one_cycle(5, slice(lr))
learn.save('stage-1')
learn.load('stage-1');
learn.show_results() | zh-nbs/Lesson3_head_pose.ipynb | fastai/course-v3 | apache-2.0 |
Data augmentation
数据增强 | tfms = get_transforms(max_rotate=20, max_zoom=1.5, max_lighting=0.5, max_warp=0.4, p_affine=1., p_lighting=1.)
data = (PointsItemList.from_folder(path)
.split_by_valid_func(lambda o: o.parent.name=='13')
.label_from_func(get_ctr)
.transform(tfms, tfm_y=True, size=(120,160))
.databunch()... | zh-nbs/Lesson3_head_pose.ipynb | fastai/course-v3 | apache-2.0 |
QUIZ QUESTION
Also, using this value of L1 penalty, how many nonzero weights do you have? | non_zero_weight_test = model_test["coefficients"][model_test["coefficients"]["value"] > 0]
print model_test["coefficients"]["value"].nnz()
non_zero_weight_test.print_rows(num_rows=20) | machine_learning/2_regression/assignment/week5/week-5-lasso-assignment-1-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Exercícios - Loops e Condiconais - Solução | # Exercício 1 - Crie uma estrutura que pergunte ao usuário qual o dia da semana. Se o dia for igual a Domingo ou
# igual a sábado, imprima na tela "Hoje é dia de descanso", caso contrário imprima na tela "Você precisa trabalhar!"
dia = input('Digite o dia da semana: ')
if dia == 'Domingo' or dia == 'Sábado':
print... | Cap03/Notebooks/DSA-Python-Cap03-Exercicios-Loops-Condiconais-Solucao.ipynb | dsacademybr/PythonFundamentos | gpl-3.0 |
Recommender using MLLib
Training the recommendation model | ratings = data.map(lambda l: l.split()).map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2]))).cache()
ratings.take(3)
nratings = ratings.count()
nUsers = ratings.keys().distinct().count()
nMovies = ratings.values().distinct().count()
print "We have Got %d ratings from %d users on %d movies." % (nratings, nUs... | Final/DATA643_pySpark_Final_Project.ipynb | psumank/DATA643 | mit |
Note: APT is supposed to automatically log the results to the output directory. Until then, do in manually: | if rerun_apt:
# Save fit results as json
with open(os.path.join(log_dir, "results_fit.json"), "w") as f:
json.dump(results_fit, f, indent=2)
# Also necessary information (can be migrated either to CAVE or (preferably) to autopytorch)
with open(os.path.join(log_dir, 'configspace.json'), 'w')... | examples/autopytorch/apt_notebook.ipynb | automl/SpySMAC | bsd-3-clause |
Next, spin up CAVE pass along the output directory. | from cave.cavefacade import CAVE
cave_output_dir = "cave_output"
cave = CAVE([log_dir], # List of folders holding results
cave_output_dir, # Output directory
['.'], # Target Algorithm Directory (only relevant for SMAC)
file_format="APT",
verbose="DEBU... | examples/autopytorch/apt_notebook.ipynb | automl/SpySMAC | bsd-3-clause |
Other analyzers also run on the APT-data: | cave.apt_tensorboard() | examples/autopytorch/apt_notebook.ipynb | automl/SpySMAC | bsd-3-clause |
f, L, w = Function('f'), Function('L'), Function('w') # abstract, Lagrangian and path functions, respectively
t, q, q_point = symbols(r't q \dot{q}') # symbols for the Leibniz notation
Lagrangian_eq = Eq(Derivative(Derivative(L(t, q, q_point),q_point,evaluate=False),
t, evaluate=False) - ... | fdg/intro.ipynb | massimo-nocentini/on-python | mit | |
Visualize the process using plt.plot with t on the x-axis and W(t) on the y-axis. Label your x and y axes. | # YOUR CODE HERE
plt.plot(t,W)
plt.xlabel('time')
plt.ylabel('Wiener Process')
assert True # this is for grading | assignments/assignment03/NumpyEx03.ipynb | joshnsolomon/phys202-2015-work | mit |
Use np.diff to compute the changes at each step of the motion, dW, and then compute the mean and standard deviation of those differences. | # YOUR CODE HERE
dW = np.diff(W)
mean = dW.mean()
standard_deviation = dW.std()
mean, standard_deviation
assert len(dW)==len(W)-1
assert dW.dtype==np.dtype(float) | assignments/assignment03/NumpyEx03.ipynb | joshnsolomon/phys202-2015-work | mit |
Write a function that takes $W(t)$ and converts it to geometric Brownian motion using the equation:
$$
X(t) = X_0 e^{((\mu - \sigma^2/2)t + \sigma W(t))}
$$
Use Numpy ufuncs and no loops in your function. | def geo_brownian(t, W, X0, mu, sigma):
"Return X(t) for geometric brownian motion with drift mu, volatility sigma."""
Xt = X0*np.exp((((mu-(sigma**2))/2)*t)+(sigma*W))
return Xt
assert True # leave this for grading | assignments/assignment03/NumpyEx03.ipynb | joshnsolomon/phys202-2015-work | mit |
Use your function to simulate geometric brownian motion, $X(t)$ for $X_0=1.0$, $\mu=0.5$ and $\sigma=0.3$ with the Wiener process you computed above.
Visualize the process using plt.plot with t on the x-axis and X(t) on the y-axis. Label your x and y axes. | # YOUR CODE HERE
Xt = geo_brownian(t, W, 1.0, .5, .3)
plt.plot(t,Xt)
plt.xlabel('time')
plt.ylabel('position')
assert True # leave this for grading | assignments/assignment03/NumpyEx03.ipynb | joshnsolomon/phys202-2015-work | mit |
Design of experiment
We define the experiment design. The benefits of using a crude Monte-Carlo approach is the potential use of several contrasts. | mcsp = pygosa.SensitivityDesign(dist=dist, model=model, size=5000) | doc/example_contrast.ipynb | sofianehaddad/gosa | lgpl-3.0 |
Moment of second order
Hereafter we define a new contrast class that helps evaluating sensitivities of $\mathbb{E}(Y^2)$. The contrast class should :
Inherits from ContrastSensitivityAnalysis
Define the contrast method with signature contrast(self, y,t, **kwargs). It should have kwargs as arguments even if not used
De... | class Moment2SA(pygosa.ContrastSensitivityAnalysis):
def __init__(self, design):
super(Moment2SA, self).__init__(design)
# contrast method
def contrast(self, y,t, **kwargs):
"""
Contrast for moment of second order
"""
return (y*y-t)*(y*y-t)
# Define risk functio... | doc/example_contrast.ipynb | sofianehaddad/gosa | lgpl-3.0 |
The previous class is a contrast similar to those provided by the module. We can thus easily apply it using the previous design: | sam = Moment2SA(mcsp)
factors_m = sam.compute_factors()
fig, ax = sam.boxplot()
print(factors_m) | doc/example_contrast.ipynb | sofianehaddad/gosa | lgpl-3.0 |
Nous pouvons parcourir les éléments d'un tableau : | tab = ["pommes", "tomates", "fromage", "lait", "sucre"]
i = 0
while i < len(tab):
print(tab[i])
i = i+1
# Attention, notez la différence avec :
j = 0
while j < len(tab):
print(j)
j = j+1 | 2015-11-18 - TD12 - Introduction aux tableaux.ipynb | ameliecordier/iutdoua-info_algo2015 | cc0-1.0 |
Exercice 1 : Recherchez si un élément est présent dans un tableau. | def cherche(tab, elt):
i = 0
while i < len(tab):
if tab[i] == elt:
print("J'ai trouvé !")
i = i+1
tableau = ["pommes", "tomates", "fromage", "lait", "sucre"]
cherche(tableau, "tomates") | 2015-11-18 - TD12 - Introduction aux tableaux.ipynb | ameliecordier/iutdoua-info_algo2015 | cc0-1.0 |
数据探索
上面数据是详细数据列表,一眼看不出来啥,先来看一下数据的大致情况。 | data_train.info() | src/ml/kaggle/titanic/titanic.ipynb | jacksu/machine-learning | mit |
从整体数据信息来看,总共包含891个顾客信息,总共有714个顾客有年龄信息,船舱信息缺失比较严重。 | data_train.describe() | src/ml/kaggle/titanic/titanic.ipynb | jacksu/machine-learning | mit |
从上可以看出,头等舱顾客比较少,不到25%,平均年龄不到30,看起来都比较年轻啊,家里人平均数都不到1,
看来计划生育搞得不错,数字看起来太不直观了,画图看看。 | #每个/多个 属性和最后的Survived之间有着什么样的关系
#中文乱码:http://blog.csdn.net/heloowird/article/details/46343519
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
fig = plt.figure()
fig.set(alpha=0.2) # 设定图表颜色alpha参数
plt.subplot2grid((2,3),(0,0)) ... | src/ml/kaggle/titanic/titanic.ipynb | jacksu/machine-learning | mit |
这个时候我们可能会有一些想法了:
不同舱位/乘客等级可能和财富/地位有关系,最后获救概率可能会不一样
年龄对获救概率也一定是有影响的,副船长曾说『小孩和女士先走』呢
和登船港口是不是有关系呢?也许登船港口不同,人的出身地位不同? | #看看各乘客等级的获救情况
fig = plt.figure()
fig.set(alpha=0.2) # 设定图表颜色alpha参数
Survived_0 = data_train.Pclass[data_train.Survived == 0].value_counts()
Survived_1 = data_train.Pclass[data_train.Survived == 1].value_counts()
df=pd.DataFrame({u'获救':Survived_1, u'未获救':Survived_0})
df.plot(kind='bar', stacked=True)
plt.title(u"各乘客等级... | src/ml/kaggle/titanic/titanic.ipynb | jacksu/machine-learning | mit |
头等舱明显获救的概率高 | #看看各性别的获救情况
fig = plt.figure()
fig.set(alpha=0.2) # 设定图表颜色alpha参数
Survived_m = data_train.Survived[data_train.Sex == 'male'].value_counts()
Survived_f = data_train.Survived[data_train.Sex == 'female'].value_counts()
df=pd.DataFrame({u'男性':Survived_m, u'女性':Survived_f})
df.plot(kind='bar', stacked=True)
plt.title(u"按性... | src/ml/kaggle/titanic/titanic.ipynb | jacksu/machine-learning | mit |
歪果盆友果然很尊重lady,lady first践行得不错。性别无疑也要作为重要特征加入最后的模型之中。 | #然后我们再来看看各种舱级别情况下各性别的获救情况
fig=plt.figure()
fig.set(alpha=0.65) # 设置图像透明度,无所谓
plt.title(u"根据舱等级和性别的获救情况")
ax1=fig.add_subplot(141)
data_train.Survived[data_train.Sex == 'female'][data_train.Pclass != 3].value_counts().plot(kind='bar', label="female highclass", color='#FA2479')
ax1.set_xticklabels([u"获救", u"未获救"], rotat... | src/ml/kaggle/titanic/titanic.ipynb | jacksu/machine-learning | mit |
数据预处理
处理missing value
这里学问有点深,如果各位有好的经验可以跟我交流下。以我浅薄的经验来说我一般会分情况处理
如果missing value占总体的比例非常小,那么直接填入平均值或者众数
如果missing value所占比例不算小也不算大,那么可以考虑它跟其他特征的关系,如果关系明显,那么直接根据其他特征填入;也可以建立简单的模型,比如线性回归,随机森林等。
如果missing value所占比例大,那么直接将miss value当做一种特殊的情况,另取一个值填入
用scikit-learn中的RandomForest来拟合一下缺失的年龄数据 | from sklearn.ensemble import RandomForestRegressor
### 使用 RandomForestClassifier 填补缺失的年龄属性
def set_missing_ages(df):
# 把已有的数值型特征取出来丢进Random Forest Regressor中
age_df = df[['Age','Fare', 'Parch', 'SibSp', 'Pclass']]
# 乘客分成已知年龄和未知年龄两部分
known_age = age_df[age_df.Age.notnull()].as_matrix()
unknown_age... | src/ml/kaggle/titanic/titanic.ipynb | jacksu/machine-learning | mit |
有一种临近结果的宠宠欲动感吧,莫急莫急,我们还得做一些处理,仔细看看Age和Fare两个属性,乘客的数值幅度变化,也忒大了吧!!如果大家了解逻辑回归与梯度下降的话,会知道,各属性值之间scale差距太大,将对收敛速度造成几万点伤害值!甚至不收敛!所以我们先用scikit-learn里面的preprocessing模块对这俩货做一个标准化。可以参考机器学习之特征工程-数据预处理 | import sklearn.preprocessing as preprocessing
scaler = preprocessing.StandardScaler()
age_scale_param = scaler.fit(df['Age'])
df['Age_scaled'] = age_scale_param.fit_transform(df['Age'])
fare_scale_param = scaler.fit(df['Fare'])
df['Fare_scaled'] = fare_scale_param.fit_transform(df['Fare'])
df
#选择线性回归
from sklearn impo... | src/ml/kaggle/titanic/titanic.ipynb | jacksu/machine-learning | mit |
下載 mnist 資料 | import os
import urllib
dataset = 'mnist.pkl.gz'
def reporthook(a,b,c):
print "\rdownloading: %5.1f%%"%(a*b*100.0/c),
if not os.path.isfile(dataset):
origin = "https://github.com/mnielsen/neural-networks-and-deep-learning/raw/master/data/mnist.pkl.gz"
print('Downloading data from %s' % origin)
... | mnist.ipynb | tjwei/class2016 | mit |
載入訓練資料 train_set 和測試資料 test_set | import gzip
import pickle
with gzip.open(dataset, 'rb') as f:
train_set, valid_set, test_set = pickle.load(f) | mnist.ipynb | tjwei/class2016 | mit |
查看 mnist 資料的概況,用 .shape 看 np.array 的形狀
train_set 有五萬筆資料,第一部份是五萬筆長度為 784 的向量。第二部份是五萬個數字
test_set 則有一萬筆同樣形式的資料 | print "train_set", train_set[0].shape, train_set[1].shape
print "valid_set", valid_set[0].shape, valid_set[1].shape
print "test_set", test_set[0].shape, test_set[1].shape | mnist.ipynb | tjwei/class2016 | mit |
資料的第一部份,每一筆都是一個 28x28 的圖片(28*28=784)
用 reshape 把長度784 的向量轉成 28*28 的方陣,就能當成圖片來看
下面是第一筆訓練資料的圖片 | imshow(train_set[0][0].reshape((28, 28)), cmap="gray") | mnist.ipynb | tjwei/class2016 | mit |
寫一個函數可以更方面的看圖。
我們查看前 5 筆資料,分別是 5張圖片,以及對應的 5 個數字 | def show(x, i=[0]):
plt.figure(i[0])
imshow(x.reshape((28,28)), cmap="gray")
i[0]+=1
for i in range(5):
print train_set[1][i]
show(train_set[0][i]) | mnist.ipynb | tjwei/class2016 | mit |
完整的模型如下
將圖片看成是長度 784 的向量 x
計算 Wx+b, 然後再取 exp。 最後得到的十個數值。將這些數值除以他們的總和。
我們希望出來的數字會符合這張圖片是這個數字的機率。
$softmax_i(W x + b) = \frac {e^{W_i x + b_i}} {\sum_j e^{W_j x + b_j}}$
先拿第一筆資料試試看, x 是輸入。 y 是這張圖片對應到的數字(以這個例子來說 y=5)。 | x = train_set[0][0]
y = train_set[1][0] | mnist.ipynb | tjwei/class2016 | mit |
先計算 exp(Wx+b) | Pr = exp(dot(x, W)+b)
Pr.shape | mnist.ipynb | tjwei/class2016 | mit |
然後 normalize,讓總和變成 1 (符合機率的意義) | Pr = Pr/Pr.sum()
print Pr | mnist.ipynb | tjwei/class2016 | mit |
由於 W 和 b 都是隨機設定的,所以上面我們算出的機率也是隨機的。
如果照上面的機率來看,y=2 的機率有 54.5% 為最高。 y=5 的機率只有 24% (也不低,但只是運氣好)
為了要評斷我們的預測的品質,要設計一個評斷誤差的方式,我們用的方法如下(不是常見的方差,而是用熵的方式來算,好處是容易微分,效果好)
$ error = - \log(P(Y=y^{(i)}|x^{(i)}, W,b)) $
上述的誤差評分方式,常常稱作 error 或者 loss,數學式可能有點費解。實際計算其實很簡單,就是下面的式子 | loss = -log(Pr[y])
loss | mnist.ipynb | tjwei/class2016 | mit |
目前的誤差 1.4215 不算太差,畢竟我們運氣很好,隨機的 W 和 b,居然能讓正確答案有 24% 的機率。
不過我們還是要想辦法改進。 我們用一種被稱作是 gradient descent 的方式來改善我們的誤差。
因為我們知道 gradient 是讓函數上升最快的方向。所以我們如果朝 gradient 的反方向走一點點(也就是下降最快的方向),那麼得到的函數值應該會小一點。
記得我們的變數是 W 和 b (裡面總共有 28*20+10 個變數),所以我們要把 loss 對 W 和 b 裡面的每一個參數來偏微分。
還好這個偏微分是可以用手算出他的形式,而最後偏微分的式子也不會很複雜。
對 b 的偏微分如下 | gradb = Pr.copy()
gradb[y] -= 1
print gradb | mnist.ipynb | tjwei/class2016 | mit |
對 W 的偏微分也不難 | print Pr.shape, x.shape, W.shape
gradW = dot(x.reshape(784,1), Pr.reshape(1,10), )
gradW[:, y] -= x | mnist.ipynb | tjwei/class2016 | mit |
再一次計算 Pr 以及 loss | Pr = exp(dot(x, W)+b)
Pr = Pr/Pr.sum()
loss = -log(Pr[y])
loss | mnist.ipynb | tjwei/class2016 | mit |
發現這次誤差下降到 0.0005 左右,改進不少
我們將同樣的方式輪流對五萬筆訓練資料來做,看看情形會如何 | W = np.random.uniform(low=-1, high=1, size=(28*28,10))
b = np.random.uniform(low=-1, high=1, size=10)
score = 0
N=50000*20
d = 0.001
learning_rate = 1e-2
for i in xrange(N):
if i%50000==0:
print i, "%5.3f%%"%(score*100)
x = train_set[0][i%50000]
y = train_set[1][i%50000]
Pr = exp(dot(x, W)+b)
... | mnist.ipynb | tjwei/class2016 | mit |
結果發現正確率大約是 92.42%, 但這是對訓練資料而不是對測試資料
而且,一筆一筆的訓練資也有點慢,線性代數的特點就是能夠向量運算。如果把很多筆 x 當成列向量組合成一個矩陣(然後還是叫做 x),由於矩陣乘法的原理,我們還是一樣計算 Wx+b , 就可以同時得到多筆結果。
下面的函數,可以一次輸入多筆 x, 同時一次計算多筆 x 的結果和準確率。 | def compute_Pr(x):
Pr = exp(dot(x, W)+b)
return Pr/Pr.sum(axis=1, keepdims=True)
def compute_accuracy(Pr, y):
return mean(Pr.argmax(axis=1)==y)
| mnist.ipynb | tjwei/class2016 | mit |
下面是更新過得訓練過程, 當 i%100000 時,順便計算一下 test accuracy 和 valid accuracy。 | W = np.random.uniform(low=-1, high=1, size=(28*28,10))
b = np.random.uniform(low=-1, high=1, size=10)
score = 0
N=50000*100
batch_size = 500
learning_rate = .7
for i in xrange(0, N, batch_size):
if i%100000==0:
x, y = test_set[0], test_set[1]
test_score = compute_accuracy(compute_Pr(x), y)*100
... | mnist.ipynb | tjwei/class2016 | mit |
最後得到的準確率是 92%-93%
不算完美,不過畢竟這只有一個矩陣而已。 | x, y = test_set[0], test_set[1]
Pr = compute_Pr(x)
test_score = compute_accuracy(Pr, y)*100
x, y = valid_set[0], valid_set[1]
Pr = compute_Pr(x)
valid_score = compute_accuracy(Pr, y)*100
print "test accuracy %5.2f%%"%test_score, "valid accuracy %5.2f%%"%valid_score
x, y = train_set[0], train_set[1]
Pr = compute_Pr(x)
... | mnist.ipynb | tjwei/class2016 | mit |
光看數據沒感覺,我們來看看前十筆測試資料跑起來的情形
可以看到前十筆只有錯一個 | x = test_set[0][:10]
y = test_set[1][:10]
Pr = compute_Pr(x)
print Pr.argmax(axis=1)
print y
for i in range(10):
show(x[i]) | mnist.ipynb | tjwei/class2016 | mit |
看看前一百筆資料中,是哪些情況算錯 | x = test_set[0][:100]
y = test_set[1][:100]
Pr = compute_Pr(x)
y2 = Pr.argmax(axis=1)
for i in range(100):
if y2[i] != y[i]:
print y2[i], y[i]
show(x[i]) | mnist.ipynb | tjwei/class2016 | mit |
Exercise: Now suppose that instead of observing a lifespan, k, you observe a lightbulb that has operated for 1 year and is still working. Write another version of LightBulb that takes data in this form and performs an update. | # Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here | code/survival.ipynb | NathanYee/ThinkBayes2 | gpl-2.0 |
Prepare and shape the data | from pyspark.mllib.recommendation import ALS, Rating
import re
#Remove the header from the RDD
header = retailData.first()
retailData = retailData.filter(lambda line: line != header)
#To produce the ALS model, we need to train it with each individual
#purchase. Each record in the RDD must be the customer id,
#item ... | source.ml/jupyterhub.ml/notebooks/zz_old/Spark/Intro/Lab 3 - Machine Learning/IntroToSparkMLlib.ipynb | shareactorIO/pipeline | apache-2.0 |
Build the recommendation model | #Use trainging RDD to train a model with Alternating Least Squares
#rank=5
#5 columns in the user-feature and product-feature matricies
#iterations=10
#10 factorization runs
rank = 5
numIterations = 10
model = ALS.train(trainData, rank, numIterations)
print "The model has been trained" | source.ml/jupyterhub.ml/notebooks/zz_old/Spark/Intro/Lab 3 - Machine Learning/IntroToSparkMLlib.ipynb | shareactorIO/pipeline | apache-2.0 |
Test the model | #Evaluate the model with the test rdd by using the predictAll function
predict = model.predictAll(testRDD.map(lambda l: (l[0],l[1])))
#Calculate and print the Mean Squared Error
predictions = predict.map(lambda l: ((l[0],l[1]), l[2]))
ratingsAndPredictions = testRDD.map(lambda l: ((l[0], l[1]), l[2])).join(predictions... | source.ml/jupyterhub.ml/notebooks/zz_old/Spark/Intro/Lab 3 - Machine Learning/IntroToSparkMLlib.ipynb | shareactorIO/pipeline | apache-2.0 |
This doesn't give us that good of a representation of ranking becuase the ranks are number of purchases. Something better may be to look at some actual recommendations. | recs = model.recommendProducts(15544,5)
for rec in recs:
print rec | source.ml/jupyterhub.ml/notebooks/zz_old/Spark/Intro/Lab 3 - Machine Learning/IntroToSparkMLlib.ipynb | shareactorIO/pipeline | apache-2.0 |
<img src='https://raw.githubusercontent.com/rosswlewis/RecommendationPoT/master/FullFile.png' width="80%" height="80%"></img>
This user seems to have purchased a lot of childrens gifts and some holiday items. The recomendation engine we created suggested some aitems along these lines | #Rating(user=15544, product=84568, rating=193.03195106065823)
#GIRLS ALPHABET IRON ON PATCHES
#Rating(user=15544, product=16033, rating=179.45915040198466)
#MINI HIGHLIGHTER PENS
#Rating(user=15544, product=22266, rating=161.04293255928698)
#EASTER DECORATION HANGING BUNNY
#Rating(user=15544, product=84598, rating=... | source.ml/jupyterhub.ml/notebooks/zz_old/Spark/Intro/Lab 3 - Machine Learning/IntroToSparkMLlib.ipynb | shareactorIO/pipeline | apache-2.0 |
modify the network:
L1 regularizer
SGD optimizer | from tfs.core.optimizer import GradientDecentOptimizer
from tfs.core.regularizers import L1
net.optimizer = GradientDecentOptimizer(net)
net.regularizer = L1(net,l1=0.001)
net.build()
net.fit(dataset,batch_size=200,n_epoch=1,max_step=100)
net.save('lenet_epoch_1')
!ls ./ | notebook/1.Save-and-load.ipynb | crackhopper/TFS-toolbox | mit |
load the model | from tfs.network import Network
net2 = Network()
net2.load('lenet_epoch_1')
print net2
print net2.optimizer
print net2.initializer
print net2.losser
print 'accuracy',net2.score(dataset.test) | notebook/1.Save-and-load.ipynb | crackhopper/TFS-toolbox | mit |
fine-tune the loaded model | net2.fit(dataset,batch_size=200,n_epoch=1,max_step=100)
net2.score(dataset.test) | notebook/1.Save-and-load.ipynb | crackhopper/TFS-toolbox | mit |
We have also seen another transformation in class: the polynomial transformation. In practice, you would use sklearn's nice PolynomialFeatures. To give you experience implementing your own transformer class, write a bivariate (exactly 2 input features) BiPolyTrans transformer class that, given two features, $W$ and $... | from itertools import chain, combinations_with_replacement
class BiPolyTrans(BaseEstimator, TransformerMixin):
"""
Transforms the data from a n x 2 matrix to a matrix with
polynomial features up to the specified degree.
Example Usage
data = np.array([[1, 2], [3, 4]])
d3polytrans = BiPolyTr... | sp17/hw/hw6/hw6.ipynb | DS-100/sp17-materials | gpl-3.0 |
She concludes that since this value is very small, sqft and the noise are most likely independent of each other. Is this a reasonable conclusion? Why or why not?
Write your answer here, replacing this text.
Question 2
Centering takes every data point and subtracts the overall mean from it. We can write the transforma... | _ = ok.submit() | sp17/hw/hw6/hw6.ipynb | DS-100/sp17-materials | gpl-3.0 |
Normalization and backgroud removal (= EXAFS extraction) | from larch.xafs import autobk
autobk(feo, kweight=2, rbkg=0.8, e0=7119.0) | notebooks/larch.ipynb | maurov/xraysloth | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.