markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Detect 1 larger region
There is about 1 peak in 200 voxels (based on simulations)
Before, we made the assumption that the activated field is so small that there
is only one local maximum. We expect there to be only one local maximum
if the activated region is smaller than 200 voxels (based on simulations),
which se... | PowerLarge = 1-(1-Power)**(1/3)
print("If we expect 3 peaks, then the power per peak should be: "+str(PowerLarge)) | Figure1_Power/.ipynb_checkpoints/RequiredEffectSizeForSufficientPower-checkpoint.ipynb | jokedurnez/RequiredEffectSize | mit |
3. How large statistic in a field be to exceed the threshold with power 0.80?
We quantify this by computing the expected local maximum in the field (which is a null field elevated by value D).
We use the distribution of local maxima of Cheng&Schwartzman to compute the power/effect size. | muRange = np.arange(1.8,5,0.01)
muLarge = []
muSingle = []
for muMax in muRange:
# what is the power to detect a maximum
power = 1-integrate.quad(lambda x:peakdistribution.peakdens3D(x,1),-20,float(FweThres)-muMax)[0]
if power>PowerLarge:
muLarge.append(muMax)
if power>Power:
muSingle.appen... | Figure1_Power/.ipynb_checkpoints/RequiredEffectSizeForSufficientPower-checkpoint.ipynb | jokedurnez/RequiredEffectSize | mit |
5. From the required voxel statistic to Cohen's D for a given sample size | # Read in data
Data = pd.read_csv("tal_data.txt",sep=" ",header=None,names=['year','n'])
Data['source']='Tal'
David = pd.read_csv("david_data.txt",sep=" ",header=None,names=['year','n'])
David['source']='David'
Data=Data.append(David)
# add detectable effect
Data['deltaUnion']=muUnion/np.sqrt(Data['n'])
Data['deltaSin... | Figure1_Power/.ipynb_checkpoints/RequiredEffectSizeForSufficientPower-checkpoint.ipynb | jokedurnez/RequiredEffectSize | mit |
The figure per List (Tal or David) | twocol = cb.qualitative.Paired_12.mpl_colors
fig,axs = plt.subplots(1,2,figsize=(12,5))
fig.subplots_adjust(hspace=.5,wspace=.3)
axs=axs.ravel()
axs[0].plot(Data.year_jitter[Data.source=="Tal"],Data.n[Data.source=="Tal"],"r.",color=twocol[0],alpha=0.5,label="")
axs[0].plot(Data.year_jitter[Data.source=="David"],Data.n... | Figure1_Power/.ipynb_checkpoints/RequiredEffectSizeForSufficientPower-checkpoint.ipynb | jokedurnez/RequiredEffectSize | mit |
The figure for different Alternatives | twocol = cb.qualitative.Paired_12.mpl_colors
fig,axs = plt.subplots(1,2,figsize=(12,5))
fig.subplots_adjust(hspace=.5,wspace=.3)
axs=axs.ravel()
axs[0].plot(Data.year_jitter,Data.n,"r.",color=twocol[0],alpha=0.5,label="")
axs[0].plot(Medians.year,Medians.MdSS,color=twocol[1],lw=3,label="Median Sample Size")
axs[0].set... | Figure1_Power/.ipynb_checkpoints/RequiredEffectSizeForSufficientPower-checkpoint.ipynb | jokedurnez/RequiredEffectSize | mit |
Figure with logscale and only 1 condition | twocol = cb.qualitative.Paired_12.mpl_colors
fig,axs = plt.subplots(1,2,figsize=(12,5))
fig.subplots_adjust(hspace=.5,wspace=.3)
axs=axs.ravel()
axs[0].plot(Data.year_jitter,Data.n,"r.",color=twocol[0],alpha=0.5,label="")
axs[0].plot(Medians.year,Medians.MdSS,color=twocol[1],lw=3,label="log(Median Sample Size)")
axs[0... | Figure1_Power/.ipynb_checkpoints/RequiredEffectSizeForSufficientPower-checkpoint.ipynb | jokedurnez/RequiredEffectSize | mit |
Plot Functions | import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({'font.size': 16})
FIG_SIZE = (12, 8)
import numpy as np
np.random.seed(12345)
from emukit.multi_fidelity.convert_lists_to_array import convert_x_list_to_array
n_plot_points = 100
x_plot = np.linspace(0, 1, 500)[:, None]
y_plot_low = forreste... | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Bayesian optimization
Define Parameter Space
The parameter space now contains two parameters: the first is a ContinuousParameter that is the $x$ input to the Forrester function. The second is an InformaionSourceParameter that tells Emukit whether a given fucntion evaluation is to be performed by the high or low fidelit... | from emukit.core import ParameterSpace, ContinuousParameter, InformationSourceParameter
n_fidelities = 2
parameter_space = ParameterSpace([ContinuousParameter('x', 0, 1), InformationSourceParameter(n_fidelities)]) | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Generate Initial Data
We shall randomly choose 12 low fidelity and then choose 6 of these points at which to evaluate the high fidelity function. | x_low = np.random.rand(12)[:, None]
x_high = x_low[:6, :]
y_low = forrester_fcn_low(x_low)
y_high = forrester_fcn_high(x_high) | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Define Model
We will use the linear multi-fidelity model defined in Emukit. In this model, the high-fidelity function is modelled as a scaled sum of the low-fidelity function plus an error term:
$$
f_{high}(x) = f_{err}(x) + \rho \,f_{low}(x)
$$ | from emukit.multi_fidelity.models.linear_model import GPyLinearMultiFidelityModel
import GPy
from emukit.multi_fidelity.kernels.linear_multi_fidelity_kernel import LinearMultiFidelityKernel
from emukit.multi_fidelity.convert_lists_to_array import convert_xy_lists_to_arrays
from emukit.model_wrappers import GPyMultiOutp... | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Define Acquisition Function
As in [1] & [2] we shall use the entropy search acquisition function, scaled by the cost of evaluating either the high or low fidelity function. | from emukit.bayesian_optimization.acquisitions.entropy_search import MultiInformationSourceEntropySearch
from emukit.core.acquisition import Acquisition
# Define cost of different fidelities as acquisition function
class Cost(Acquisition):
def __init__(self, costs):
self.costs = costs
def evaluate(sel... | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Create OuterLoop | from emukit.core.loop import FixedIntervalUpdater, OuterLoop, SequentialPointCalculator
from emukit.core.loop.loop_state import create_loop_state
from emukit.core.optimization.multi_source_acquisition_optimizer import MultiSourceAcquisitionOptimizer
from emukit.core.optimization import GradientAcquisitionOptimizer
ini... | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Add Plotting of Acquisition Function
To see how the acquisition function evolves. This is done by using the iteration_end_event on the OuterLoop. This is a list of functions where each function should have the signature: function(loop, loop_state). All functions in the list are called after each iteration of the optimi... | def plot_acquisition(loop, loop_state):
colours = ['b', 'r']
plt.plot(x_plot_low[:, 0], loop.candidate_point_calculator.acquisition.evaluate(x_plot_low), 'b')
plt.plot(x_plot_high[:, 0], loop.candidate_point_calculator.acquisition.evaluate(x_plot_high), 'r')
previous_x_collected = loop_state.X[[-1]... | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Find Esimated Minimum at Every Iteration
On each iteration of the optimization loop, find the minimum value of the high fidelity model. | x_search = np.stack([np.linspace(0, 1, 1000), np.ones(1000)], axis=1)
model_min_mean = []
model_min_loc = []
def calculate_metrics(loop, loop_state):
mean, var = loop.model_updaters[0].model.predict(x_search)
model_min_mean.append(np.min(mean))
model_min_loc.append(x_search[np.argmin(mean), 0])
# subscrib... | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Run Optimization | loop.run_loop(forrester_fcn, 10) | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Plot Final Model | is_high_fidelity = loop.loop_state.X[:, -1] == 1
plot_model(x_low=loop.loop_state.X[~is_high_fidelity, 0], y_low=loop.loop_state.Y[~is_high_fidelity],
x_high=loop.loop_state.X[is_high_fidelity, 0], y_high=loop.loop_state.Y[is_high_fidelity]) | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Comparison to High Fidelity Only Bayesian Optimization
This section compares the multi-fidelity optimization to Bayesian optimization using high fidelity observations only. | from emukit.bayesian_optimization.loops import BayesianOptimizationLoop
from emukit.bayesian_optimization.acquisitions.entropy_search import EntropySearch
from emukit.model_wrappers import GPyModelWrapper
import GPy
# Make model
gpy_model = GPy.models.GPRegression(x_high, y_high)
gpy_model.Gaussian_noise.variance.fix(... | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
Plot Estimated Minimum Location | # Plot comparison
plt.figure(figsize=FIG_SIZE)
x = np.array(range(len(model_min_mean))) + 1
# Calculate cumulative cost of evaluating high fidelity only observations
n_hf_points = hf_only_loop.loop_state.X.shape[0]
cumulative_cost_hf = high_fidelity_cost * (np.array(range(n_hf_points)) + 1)
cumulative_cost_hf = cumul... | notebooks/Emukit-tutorial-multi-fidelity-bayesian-optimization.ipynb | EmuKit/emukit | apache-2.0 |
How many tweets are about the 'wall'? | # Lowercase the hashtags and tweet body
df['hashtags'] = df['hashtags'].str.lower()
df['text'] = df['text'].str.lower()
print("Total number of tweets containing hashtag 'wall' = {}".format(len(df[df['hashtags'].str.contains('wall')])))
print("Total number of tweets whose body contains 'wall' = {}".format(len(df[df['t... | exploratory_notebooks/mexico_wall_part_1.ipynb | jss367/assemble | mit |
What is the average twitter tenure of people who tweeted about the wall? | def months_between(end, start):
return (end.year - start.year)*12 + end.month - start.month
wall_tweets['created'] = pd.to_datetime(wall_tweets['created'])
wall_tweets['user_created'] = pd.to_datetime(wall_tweets['user_created'])
wall_tweets['user_tenure'] = wall_tweets[['created', \
'... | exploratory_notebooks/mexico_wall_part_1.ipynb | jss367/assemble | mit |
There are a couple of users tweeting multiple times, but most tweets come from distinct twitter handles | tweets_per_user = wall_tweets.groupby('user_name').size().sort_values(ascending=False)
fig, ax = plt.subplots()
ax.plot(tweets_per_user.values)
plt.show() | exploratory_notebooks/mexico_wall_part_1.ipynb | jss367/assemble | mit |
Who are the 'top tweeters' + descriptions? | wall_tweets.groupby(['user_name', 'user_description']).size().sort_values(ascending=False).head(20).to_frame() | exploratory_notebooks/mexico_wall_part_1.ipynb | jss367/assemble | mit |
What is the reach of these tweets in terms of followers? | plt.boxplot(wall_tweets['friends_count'].values, vert=False)
plt.show()
wall_tweets['friends_count'].describe() | exploratory_notebooks/mexico_wall_part_1.ipynb | jss367/assemble | mit |
Location of the tweets? | wall_tweets.groupby('user_location').size().sort_values(ascending=False) | exploratory_notebooks/mexico_wall_part_1.ipynb | jss367/assemble | mit |
INTRO:
The highly modular nature of FIDDLE, exemplified by the depiction below, entails similarly modular input files.
RELEVANT JSON FILES:
There are two .json files that dictate how FIDDLE is run:
1. configurations.json
2. architecture.json
configurations.json
'configurations.json' parametrizes the sequencing f... | ! cat configurations.json | fiddle/guide.ipynb | DylanM-Marshall/FIDDLE | gpl-3.0 |
architecture.json
'architecture.json' parametrizes the hyper-parameters and other neural network specific variables that FIDDLE will employ. The Encoder and Decoder will utilize the same hyper-parameters.
! cat architecture.json | ! cat architecture.json | fiddle/guide.ipynb | DylanM-Marshall/FIDDLE | gpl-3.0 |
RELEVANT HDF5 FILES:
Using the quick start hdf5 datasets as examples, one can see that the dimensions of the tracks within the hdf5 datasets reflect the characteristics of the sequencing inputs. The train, validation, and test hdf5datasets are simply partitions of an original hdf5dataset that was compiled from scripts ... | train = h5py.File('../data/hdf5datasets/NSMSDSRSCSTSRI_500bp/train.h5', 'r')
train.items() | fiddle/guide.ipynb | DylanM-Marshall/FIDDLE | gpl-3.0 |
validation = h5py.File('../data/hdf5datasets/validation.h5', 'r')
validation.items() | validation = h5py.File('../data/hdf5datasets/NSMSDSRSCSTSRI_500bp/validation.h5', 'r')
validation.items() | fiddle/guide.ipynb | DylanM-Marshall/FIDDLE | gpl-3.0 |
test = h5py.File('../data/hdf5datasets/test.h5', 'r')
test.items() | test = h5py.File('../data/hdf5datasets/NSMSDSRSCSTSRI_500bp/test.h5', 'r')
test.items() | fiddle/guide.ipynb | DylanM-Marshall/FIDDLE | gpl-3.0 |
Examining the 'info' track:
The 'info' track is the track that holds index information relevant to the sequencing datasets. The dimensions of the 'info' correspond to the following:
1. Chromosome number (e.g. 1-16)
2. Strandedness (e.g. -1, 1)
3. Gene index (parsed from the original GFF file input)
4. Base Pair index (... | infoRef_test = test.get('info')[:]
stats.describe(infoRef_test[:, 0])
stats.describe(infoRef_test[:, 1])
stats.describe(infoRef_test[:, 2])
stats.describe(infoRef_test[:, 3])
print()
infoRef_validation = validation.get('info')[:]
stats.describe(infoRef_validation[:, 0])
stats.describe(infoRef_validation[:, 1])
stats.de... | fiddle/guide.ipynb | DylanM-Marshall/FIDDLE | gpl-3.0 |
Jupyter Notebook as a Documentation Resource:
An advantage of this medium of Python interaction is the ability to quickly examine Python scripts. Using the '?' as a prepend, FIDDLE's documentation is easily accessed. First, we will import several FIDDLE scripts and quickly checkout their internals.
import main, models... | import main, models, visualization | fiddle/guide.ipynb | DylanM-Marshall/FIDDLE | gpl-3.0 |
Note: the following applies to any Python method/class/ADT/etc. as well as all imported Python packages:
The '?' prepend allows direct access to a Python script's docstrings. The '??' prepend allows direct access to the whole Python script. Jupyter Notebook's autocomplete feature allows an easy understanding of availab... | ?main
??models.
?visualization | fiddle/guide.ipynb | DylanM-Marshall/FIDDLE | gpl-3.0 |
Creating the autoencoder
Similar to regular neural networks in Shogun, we create a deep autoencoder using an array of NeuralLayer-based classes, which can be created using the utility class NeuralLayers. However, for deep autoencoders there's a restriction that the layer sizes in the network have to be symmetric, that ... | ae = sg.create_machine("DeepAutoencoder", seed=10)
ae.add("layers", sg.create_layer("NeuralInputLayer", num_neurons=256))
ae.add("layers", sg.create_layer("NeuralRectifiedLinearLayer", num_neurons=512))
ae.add("layers", sg.create_layer("NeuralRectifiedLinearLayer", num_neurons=128))
ae.add("layers", sg.create_layer("Ne... | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
Pre-training
Now we can pre-train the network. To illustrate exactly what's going to happen, we'll give the layers some labels: L1 for the input layer, L2 for the first hidden layer, and so on up to L5 for the output layer.
In pre-training, an autoencoder will formed for each encoding layer (layers up to the middle lay... | ae.put("noise_type", "AENT_DROPOUT") # use dropout noise
ae.put("noise_parameter", 0.5) # each input has a 50% chance of being set to zero
ae.put("optimization_method", "NNOM_GRADIENT_DESCENT") # train using gradient descent
ae.put("gd_learning_rate", 0.01)
ae.put("gd_mini_batch_size", 128)
ae.put("max_num_epochs", 5... | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
Fine-tuning
After pre-training, we can train the autoencoder as a whole to fine-tune the parameters. Training the whole autoencoder is performed using the train() function. Training parameters are controlled through the public attributes, same as a regular neural network. | ae.put('noise_type', "AENT_DROPOUT") # same noise type we used for pre-training
ae.put('noise_parameter', 0.5)
ae.put('max_num_epochs', 50)
ae.put('optimization_method', "NNOM_GRADIENT_DESCENT")
ae.put('gd_mini_batch_size', 128)
ae.put('gd_learning_rate', 0.0001)
ae.put('epsilon', 0.0)
# start fine-tuning. this might... | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
Evaluation
Now we can evaluate the autoencoder that we trained. We'll start by providing it with corrupted inputs and looking at how it will reconstruct them. The function reconstruct() is used to obtain the reconstructions: | # get a 50-example subset of the test set
subset = Xtest.get("feature_matrix")[:,0:50]
# corrupt the first 25 examples with multiplicative noise
subset[:,0:25] *= (np.random.random((256,25))>0.5)
# corrupt the other 25 examples with additive noise
subset[:,25:50] += np.random.random((256,25))
# obtain the reconstru... | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
The figure shows the corrupted examples and their reconstructions. The top half of the figure shows the ones corrupted with multiplicative noise, the bottom half shows the ones corrupted with additive noise. We can see that the autoencoders can provide decent reconstructions despite the heavy noise.
Next we'll look at ... | # obtain the weights matrix of the first hidden layer
# the 512 is the number of biases in the layer (512 neurons)
# the transpose is because numpy stores matrices in row-major format, and Shogun stores
# them in column major format
w1 = ae.get("layer_parameters")[0][512:].reshape(256,512).T
# visualize the weights b... | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
Now, we can use the autoencoder to initialize a supervised neural network. The network will have all the layer of the autoencoder up to (and including) the middle layer. We'll also add a softmax output layer. So, the network will look like: L1->L2->L3->Softmax. The network is obtained by calling convert_to_neural_netwo... | nn = sg.convert_to_neural_network(ae, sg.create_layer("NeuralSoftmaxLayer", num_neurons=10), 0.01)
nn.put('max_num_epochs', 50)
nn.put('labels', Ytrain)
_ = nn.train(Xtrain) | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
Next, we'll evaluate the accuracy on the test set: | predictions = nn.apply(Xtest)
accuracy = sg.create_evaluation("MulticlassAccuracy").evaluate(predictions, Ytest) * 100
print("Classification accuracy on the test set =", accuracy, "%") | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
Convolutional Autoencoders
Convolutional autoencoders [3] are the adaptation of autoencoders to images (or other spacially-structured data). They are built with convolutional layers where each layer consists of a number of feature maps. Each feature map is produced by convolving a small filter with the layer's inputs, ... | conv_ae = sg.create_machine("DeepAutoencoder", seed=10)
# 16x16 single channel images
conv_ae.add("layers", sg.create_layer("NeuralInputLayer", width=16, height=16, num_neurons=256))
# the first encoding layer: 5 feature maps, filters with radius 2 (5x5 filters)
# and max-pooling in a 2x2 region: its output will be 1... | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
Now we'll pre-train the autoencoder: | ae.put("noise_type", "AENT_DROPOUT") # use dropout noise
ae.put("noise_parameter", 0.3) # each input has a 50% chance of being set to zero
ae.put("optimization_method", "NNOM_GRADIENT_DESCENT") # train using gradient descent
ae.put("gd_learning_rate", 0.002)
ae.put("gd_mini_batch_size", 100)
ae.put("max_num_epochs", ... | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
And then convert the autoencoder to a regular neural network for classification: | conv_nn = sg.convert_to_neural_network(ae, sg.create_layer("NeuralSoftmaxLayer", num_neurons=10), 0.01)
# train the network
conv_nn.put('epsilon', 0.0)
conv_nn.put('max_num_epochs', 50)
conv_nn.put('labels', Ytrain)
# start training. this might take some time
_ = conv_nn.train(Xtrain) | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
And evaluate it on the test set: | predictions = conv_nn.apply_multiclass(Xtest)
accuracy = sg.create_evaluation("MulticlassAccuracy").evaluate(predictions, Ytest) * 100
print("Classification accuracy on the test set =", accuracy, "%") | doc/ipython-notebooks/neuralnets/autoencoders.ipynb | geektoni/shogun | bsd-3-clause |
Not bad performance for such a simple model and featurization. More sophisticated models do slightly better on this dataset, but not enormously better.
Congratulations! Time to join the Community!
Congratulations on completing this tutorial notebook! If you enjoyed working through the tutorial, and want to continue wo... | @manual{Intro4,
title={Molecular Fingerprints},
organization={DeepChem},
author={Ramsundar, Bharath},
howpublished = {\url{https://github.com/deepchem/deepchem/blob/master/examples/tutorials/Molecular_Fingerprints.ipynb}},
year={2021},
} | examples/tutorials/Molecular_Fingerprints.ipynb | deepchem/deepchem | mit |
In the notebook we can execute cells with more than one line of code, in the style of matlab or mathematica | a = 5
b = 10
print "a + b = %d" % (a + b)
print "a * b = %d" % (a * b) | Intro_IPython.ipynb | OriolAbril/Statistics-Rocks-MasterCosmosUAB | mit |
In the menu we can find useful drop-down menus to perform simple tasks to edit our notebook. The best way to know them is to experiment
Most important, the kernel menu, where we can kill the execution if we run intro trouble.
The use of the notebook allows to develop code faster in an exploratory way, writing small pie... | %lsmagic | Intro_IPython.ipynb | OriolAbril/Statistics-Rocks-MasterCosmosUAB | mit |
Clasificamos el nombre segun el titulo de una persona | # Filter the name
def get_title(x):
y = x[x.find(',')+1:].replace('.', '').replace(',', '').strip().split(' ')
if y[0] == 'the': # Search for the countess
title = y[1]
else:
title = y[0]
return title
def filter_title(title, sex):
if title in ['Countess', 'Dona', 'Lady', 'Jonkheer... | ejercicio 3/titanic.ipynb | cristhro/Machine-Learning | gpl-3.0 |
Quitamos los titulos especiales y los agrupamos en categorias mas concretas |
for df in [train_df, test_df]:
df['Title'] = df.apply(lambda x: filter_title(x['Title'], x['Sex']), axis=1)
sns.countplot(y=train_df['Title'])
train_df.groupby('Title')['PassengerId'].count().sort_values(ascending=False)
# Borramos la columna Name
train_df = train_df.drop(['Name', 'PassengerId'], axis=1)
test_df... | ejercicio 3/titanic.ipynb | cristhro/Machine-Learning | gpl-3.0 |
Eleccion del Modelo
Hemos probado con 4 modelos diferentes a ver cual da mejor resultado, y en este caso, Random Forest ha sido el daba mas puntuacion en kaggle, de entre los 3 que empataban a score (RF, DT y SVM) | X_train = train_df.drop(["Survived"], axis=1).copy()
Y_train = train_df["Survived"]
X_test = test_df.drop("PassengerId", axis=1).copy()
X_train.shape, Y_train.shape, X_test.shape | ejercicio 3/titanic.ipynb | cristhro/Machine-Learning | gpl-3.0 |
Create network using networkx
This example uses the small and simple network found here: network-example-undirected.txt. <br> | # Step 2: Import/Create the network that PathLinker will run on
network_file = 'network-example-undirected.txt'
# create a new network by importing the data from a sample using pandas
df = pd.read_csv(network_file, sep='\t', lineterminator='\n')
# and create the networkx Graph from the pandas dataframe
G = nx.from_pa... | cytoscape-automation-example/simple_use_case.ipynb | Murali-group/PathLinker-Cytoscape | gpl-3.0 |
The network shown below will be generated in Cytoscape with the above code.
Run PathLinker using the API function
Run PathLinker
The function takes user sources, targets, and a set of parameters, and computes the k shortest paths. The function returns the paths in JSON format. Based on the user input, the function cou... | # Step 3: Construct input data to pass to PathLinker API function
# construct PathLinker input data for API request
# For a description of all of the parameters, please see below
params = {
'sources': 'a',
'targets': 'e h',
'k': 2, # the number of shortest path to compute
'treatNetworkAsUndirected': T... | cytoscape-automation-example/simple_use_case.ipynb | Murali-group/PathLinker-Cytoscape | gpl-3.0 |
Output
The app will generate the following (shown below):
- a subnetwork containing the paths (with the hierarchical layout applied)
- a path rank column in the Edge Table (shows for each edge, the rank of the first path in which it appears)
- a Result Panel within Cytoscape.
The API will return:
- the computed path... | # Step 4: Store result, parse, and print
results = json.loads(result_json.content)
print("Output:\n")
# access the suid, references, and path rank column name
subnetwork_suid = results["subnetworkSUID"]
subnetwork_view_suid = results["subnetworkViewSUID"]
# The path rank column shows for each edge, the rank of the fi... | cytoscape-automation-example/simple_use_case.ipynb | Murali-group/PathLinker-Cytoscape | gpl-3.0 |
The subnetwork with "cose" layout will look something like this:
Visualization using cytoscape.js and py2cytoscape | # *** Currently the function does not work therefore is commented out. ***
# import py2cytoscape.cytoscapejs as renderer
# # visualize the subnetwork view using CytoScape.js
# renderer.render(subnetwork_view, 'Directed', background='radial-gradient(#FFFFFF 15%, #DDDDDD 105%)') | cytoscape-automation-example/simple_use_case.ipynb | Murali-group/PathLinker-Cytoscape | gpl-3.0 |
View the subnetwork and store the image | # png
subnetwork_image_png = subnetwork.get_png()
subnetwork_image_file = 'use-case-images/subnetwork-image.png'
print("Writing PNG to %s" % (subnetwork_image_file))
with open(subnetwork_image_file, 'wb') as f:
f.write(subnetwork_image_png)
from IPython.display import Image
Image(subnetwork_image_png)
# # pdf
# s... | cytoscape-automation-example/simple_use_case.ipynb | Murali-group/PathLinker-Cytoscape | gpl-3.0 |
Четное количество лепестков у 20 ромашек, нечетное у 40. Но это малая выборка с большого ромашкового поля. Настоящая вероятность получить нечетное количество лепестков может отличаться. Рассмотрим поле из 6'000 ромашек, и нечет колчество лепестков у 4'000. И посмотрим какие выводы можно сделать, если сорвать 60 из них: | universe = np.concatenate([np.zeros(2000), np.ones(4000)])
sample = np.random.choice(universe, 60)
float(sample.sum()) / sample.size | petal.ipynb | dmittov/misc | apache-2.0 |
Хотя должно было получиться: | float(universe.sum()) / universe.size | petal.ipynb | dmittov/misc | apache-2.0 |
Точечные оценки врут (хоть немного) очень часто. Интервальные только с определенной вероятностью. Природа сложна, но не злонамерена. Исследовав часть поля, мы с большой вероятностью можем сказать интервал истиной вероятности получения нечетного количества лепестков.
Bootstrap
Сделаем быстрое оценивание с помощью бутстэ... | sample = np.concatenate([np.zeros(20), np.ones(40)])
def point_est(sample):
return float(sample.sum()) / sample.size
mean = point_est(sample)
mean
def Choose(sample):
return np.random.choice(sample, sample.size)
B_size = 10000
boot = np.vectorize(lambda it: point_est(Choose(sample)))(np.arange(B_size))
sns... | petal.ipynb | dmittov/misc | apache-2.0 |
Из имеющейся выборки я сгенерировал 10'000 выборок с возвращением такого же размера. Это похоже на следующий процесс. Пусть поле состоит из очень большого числа ромашек с тем количеством лепестков, которые есть в данных Матвея. И распределение на поле такое как в его выборке. И мы 10'000 раз моделируем процесс выбора 6... | boot.mean() | petal.ipynb | dmittov/misc | apache-2.0 |
Среднее получилось почти как нужно. Но ценность не в нем, ценность в дисперсии, которой не было у точечной оценки, а теперь есть, благодаря bootstrap методу. | boot_mean = float(sample.sum()) / sample.size
boot_std = boot.std() | petal.ipynb | dmittov/misc | apache-2.0 |
Рассмотрим любимый многими 95% доверительный интервал (вероятность, что истиное значение вероятности окажется вне интервала 5%). Немножко ЦПТ магии: | alpha = 0.05
level = 1. - alpha / 2
deviation = stats.norm.ppf(level) * boot_std
boot_mean - deviation, boot_mean + deviation | petal.ipynb | dmittov/misc | apache-2.0 |
Вот такой на самом деле широкий разброс получается. В любом случае, теперь мы на 95% уверены, что четность количества лепестков не равновероятна. Посмотрим насколько эту уверенность можно повысить. | stats.norm.cdf((boot_mean - .5) / boot_std) | petal.ipynb | dmittov/misc | apache-2.0 |
Шансы честного распределения четности менее 1%
Да, можно гораздо проще
Bootstrap хорош. Но он ничего не знает о том, что мы там оценивали. С одной стороны это плюс. Можно не заморачиваясь оценивать сложные статистики.
С другой, если вдаться в детали, можно получить лучшую оценку. Естественно, например считать, что веро... | p = float(sample.sum()) / sample.size
se = np.sqrt(p * (1. - p) / sample.size)
alpha = 0.05
level = 1. - alpha / 2
deviation = stats.norm.ppf(level) * se
p - deviation, p + deviation | petal.ipynb | dmittov/misc | apache-2.0 |
Matlab Basics
Matlab has very similar syntax to Python. The main difference in general arithmetic is that Matlab includes all the math/array creation functions by default. Let's compare some examples | #Python
import numpy as np
b = 4
x = np.linspace(0,10, 5)
y = x * b
print(y)
%%matlab
b = 4;
x = linspace(0,10,5);
y = b .* x | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
There are three main differences we can spot:
Matlab doesn't require any imports or prefixes for linspace
Matlab requires a ; at the end to suppress output. If you don't end with a ;, Matlab will tell you about that line.
In numpy, all arithmetic operations are by default element-by-element. In Matlab, arithmetic op... | x = np.array([[4,3], [-2, 1]])
y = np.array([2,6]).transpose()
print(x.dot(y))
%%matlab
x = [4, 3; -2, 1];
y = [2,6]';
x * y | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
You can see here that Matlab doesn't distinguish between lists, which can grow/shrink, and arrays, which are fixed size | x = [2,5]
x.append(3)
x
%%matlab
x = [5,2];
x = [x 3] | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Since Matlab variables are always fixed length, you must create new ones to to change size
Many of the same commands we used have the same name in matlab | import scipy.linalg as lin
example = np.random.random( (3,3) )
lin.eig(example)
%%matlab
example = rand(3,3);
eig(example) | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Slicing
Slicing is nearly the same, except Matlab starts at 1 and includes both the start and end of the slice. Matlab uses parenthesis instead of brackets | %%matlab
x = 1:10;
%this is how you make comments BTW, the % sign
x(1)
x(1:2)
x(1:2:5)
x = list(range(1,11))
print(x[0])
print(x[0:2])
print(x[0:6:2]) | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Program flow control
All the same flow statements from Python exist | for i in range(3):
print(i)
print('now with a list')
x = [2,5]
for j in x:
print(j) | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Matlab can only iterate in for loops on integers. Thus, to iterate over elements of an array, you need use this syntax: | %%matlab
for i = 0:2
i
end
'now with a list'
x = [2, 5]
n = size(x)
for j = 1:n
j
end | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
If statements are similar. and is replaced by &, or by | and not by ~ | %%matlab
a = -3;
if a < 0 & abs(a) > 2
a * 2
end
if ~(a == 3 | a ~= 3)
'foo'
end | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Creating functions in Matlab
In Matlab, you always define functions in another file and then read them in. You can use the writefile cell magic to do this | %%writefile compute_pow.m
function[result] = compute_pow(x, p)
%this function computes x^p
result = x ^ p;
%%matlab
compute_pow(4,2) | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
If you modify the file, you have to force matlab to reload your function: | %%matlab
clear compute_pow | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Plotting
The matplotlib was inspired by Matlab's plotting, so many of the functions are similar. | import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(0,10,100)
y = np.cos(x)
plt.figure(figsize=(7,5))
plt.plot(x,y)
plt.grid()
plt.xlabel('x')
plt.ylabel('y')
plt.title('cosine wave')
plt.show()
%%matlab
x = linspace(0,10,100);
y = cos(x);
plot(x,y)
grid on
xlabel('x')
ylabel('y')
title('cosine wave... | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
Example - Solving and plotting an Optimization Problem
Minimize
$$f(x) = (x - 4)^2 $$ | from scipy.optimize import *
def fxn(x):
return (x - 4)**2
x_min = newton(fxn,x0=0)
plt.figure(figsize=(7,5))
x_grid = np.linspace(2,6,100)
plt.plot(x_grid, fxn(x_grid))
plt.axvline(x_min, color='red')
plt.show()
%%writefile my_obj.m
function[y] = my_obj(x)
%be careful to use .^ here so that we can pass matrice... | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
There are a few key differences to note:
When referring to a function in matlab, you have to put an @ if you're not calling it
There is not an easy way to plot a vertical line in matlab, so you have to plot a line from the lowest y-value to highest y-value
Be careful about making sure your function can handle matrices... | import pandas as pd
data = pd.read_excel('fuel_cell.xlsx')
data.info() | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
You can access data in two ways: | data.Resistance[0:10]
data.ix[0:10, 3]
%system jupyter nbconvert unit_10_lecture_1.ipynb --to slides --post serve | unit_16/lectures/lecture_1.ipynb | whitead/numerical_stats | gpl-3.0 |
TensorFlow Lattice を使った倫理のための形状制約
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/lattice/tutorials/shape_constraints_for_ethics"><img src="https://www.tensorflow.org/images/tf_logo_32px.png"> TensorFlow.orgで表示</a></td>
<td><a target="_blank" href="https://c... | #@test {"skip": true}
!pip install tensorflow-lattice seaborn | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
必要なパッケージをインポートします。 | import tensorflow as tf
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
import sys
import tensorflow_lattice as tfl
logging.disable(sys.maxsize) | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
このチュートリアルで使用されるデフォルト値です。 | # List of learning rate hyperparameters to try.
# For a longer list of reasonable hyperparameters, try [0.001, 0.01, 0.1].
LEARNING_RATES = [0.01]
# Default number of training epochs and batch sizes.
NUM_EPOCHS = 1000
BATCH_SIZE = 1000
# Directory containing dataset files.
DATA_DIR = 'https://raw.githubusercontent.com/... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
事例 1: 法科大学院への進学適正
このチュートリアルの前半では、法科大学院入学審議会(LSAC)の Law School Admissions データセットを使った事例を考察します。学生の LSAT スコアと学部課程の GPA という 2 つの特徴量を使用して、学生が司法試験に合格するかどうかを予測するための分類器をトレーニングします。
分類器のスコアによって法科大学院への進学適正または奨学金が誘導されると仮定しましょう。メリットに基づく社会規範に従うと、GPA と LSAT スコアがより高い学生が分類器からより高いスコアを得ることが期待されますが、 モデルがたやすくこういった直感的な規範を違反し、より高い GPA と LSAT ... | # Load data file.
law_file_name = 'lsac.csv'
law_file_path = os.path.join(DATA_DIR, law_file_name)
raw_law_df = pd.read_csv(law_file_path, delimiter=',') | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
データセットを前処理します。 | # Define label column name.
LAW_LABEL = 'pass_bar'
def preprocess_law_data(input_df):
# Drop rows with where the label or features of interest are missing.
output_df = input_df[~input_df[LAW_LABEL].isna() & ~input_df['ugpa'].isna() &
(input_df['ugpa'] > 0) & ~input_df['lsat'].isna()]
retur... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
データをトレーニング/検証/テストセットに分割する | def split_dataset(input_df, random_state=888):
"""Splits an input dataset into train, val, and test sets."""
train_df, test_val_df = train_test_split(
input_df, test_size=0.3, random_state=random_state)
val_df, test_df = train_test_split(
test_val_df, test_size=0.66, random_state=random_state)
retur... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
データの分布を視覚化する
まず、データの分布を視覚化します。司法試験に合格したすべての学生と合格しなかった学生の GPA と LSAT スコアを描画します。 | def plot_dataset_contour(input_df, title):
plt.rcParams['font.family'] = ['serif']
g = sns.jointplot(
x='ugpa',
y='lsat',
data=input_df,
kind='kde',
xlim=[1.4, 4],
ylim=[0, 50])
g.plot_joint(plt.scatter, c='b', s=10, linewidth=1, marker='+')
g.ax_joint.collections[0].set_alph... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
司法試験通過を予測する較正済み線形モデルをトレーニングする
次に、学生が司法試験に合格するかどうかを予測するために、TFL の較正済み線形モデルをトレーニングします。LSAT スコアと学部課程の GPA を 2 つの特徴量として使用し、学生が司法試験に合格するかどうかをトレーニングラベルとします。
まず制約を使用せずに、較正済み線形モデルをトレーニングします。次に、単調性制約を使用して較正済み線形モデルをトレーニングし、モデルの出力と精度に生じる違いを観察します。
TFL 較正済み線形 Estimator をトレーニングするためのヘルパー関数
これらは、この法科大学院の事例と以下の債務不履行の事例に使用されます。 | def train_tfl_estimator(train_df, monotonicity, learning_rate, num_epochs,
batch_size, get_input_fn,
get_feature_columns_and_configs):
"""Trains a TFL calibrated linear estimator.
Args:
train_df: pandas dataframe containing training data.
monotonicity: if 0, ... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
法科大学院データセットの特徴量を構成するためのヘルパー関数
これらのヘルパー関数は法科大学院の事例に特化した関数です。 | def get_input_fn_law(input_df, num_epochs, batch_size=None):
"""Gets TF input_fn for law school models."""
return tf.compat.v1.estimator.inputs.pandas_input_fn(
x=input_df[['ugpa', 'lsat']],
y=input_df['pass_bar'],
num_epochs=num_epochs,
batch_size=batch_size or len(input_df),
shuffle=... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
トレーニング済みモデルの出力を視覚化するためのヘルパー関数 | def get_predicted_probabilities(estimator, input_df, get_input_fn):
predictions = estimator.predict(
input_fn=get_input_fn(input_df=input_df, num_epochs=1))
return [prediction['probabilities'][1] for prediction in predictions]
def plot_model_contour(estimator, input_df, num_keypoints=20):
x = np.linspace(... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
制約なし(非単調性)の較正済み線形モデルをトレーニングする | nomon_linear_estimator = optimize_learning_rates(
train_df=law_train_df,
val_df=law_val_df,
test_df=law_test_df,
monotonicity=0,
learning_rates=LEARNING_RATES,
batch_size=BATCH_SIZE,
num_epochs=NUM_EPOCHS,
get_input_fn=get_input_fn_law,
get_feature_columns_and_configs=get_feature_col... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
単調な較正済み線形モデルをトレーニングする | mon_linear_estimator = optimize_learning_rates(
train_df=law_train_df,
val_df=law_val_df,
test_df=law_test_df,
monotonicity=1,
learning_rates=LEARNING_RATES,
batch_size=BATCH_SIZE,
num_epochs=NUM_EPOCHS,
get_input_fn=get_input_fn_law,
get_feature_columns_and_configs=get_feature_colum... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
ほかの制約なしモデルをトレーニングする
TFL の較正済み線形モデルを、精度をそれほど大きく犠牲にすることなく LSAT スコアと GPA の両方で単調になるようにトレーニングできることを実演しました。
しかし、較正済み線形モデルは、ディープニューラルネットワーク(DNN)や勾配ブースティング木(GBT)などのほかの種類のモデルとどのように比較されるでしょうか。DNN と GBT は合理的に平等な出力を持つように見えるのでしょうか。この疑問への答えをえるために、制約なしの DNN と GBT をトレーニングすることにします。実際のところ、DNN と GBT は、LSAT スコアと学部課程の GPA の単調性を大きく侵害することが観察... | feature_names = ['ugpa', 'lsat']
dnn_estimator = tf.estimator.DNNClassifier(
feature_columns=[
tf.feature_column.numeric_column(feature) for feature in feature_names
],
hidden_units=[100, 100],
optimizer=tf.keras.optimizers.Adam(learning_rate=0.008),
activation_fn=tf.nn.relu)
dnn_estimator... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
制約なしの勾配ブースティング木(GBT)モデルをトレーニングする
木の構造は、高い検証精度を得られるように、最適化済みです。 | tree_estimator = tf.estimator.BoostedTreesClassifier(
feature_columns=[
tf.feature_column.numeric_column(feature) for feature in feature_names
],
n_batches_per_layer=2,
n_trees=20,
max_depth=4)
tree_estimator.train(
input_fn=get_input_fn_law(
law_train_df, num_epochs=NUM_EPOCHS,... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
事例 2: 債務不履行
このチュートリアルで考察する 2 つ目の事例は、個人の債務不履行確率の予測です。UCI リポジトリの Default of Credit Card Clients データセットを使用します。このデータは、台湾の 30,000 人のクレジットカード利用者から集められたもので、ある期間に利用者が債務不履行となるかどうかを示すバイナリラベルが含まれます。特徴量には、2005 年 4 月から 9 月までの毎月の婚姻状況、性別、学歴、および利用者の既存の支払いの延滞期間が含まれます。
最初の事例と同様に、不平等なペナリゼーションを回避するために単調性制約を使用して説明します。モデルが利用者の信用スコアを決定するために使... | # Load data file.
credit_file_name = 'credit_default.csv'
credit_file_path = os.path.join(DATA_DIR, credit_file_name)
credit_df = pd.read_csv(credit_file_path, delimiter=',')
# Define label column name.
CREDIT_LABEL = 'default' | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
データをトレーニング/検証/テストセットに分割する | credit_train_df, credit_val_df, credit_test_df = split_dataset(credit_df) | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
データの分布を視覚化する
まず、データの分布を視覚化します。さまざまな婚姻状況と支払い状況の利用者に確認される不履行率の平均と標準偏差を描画します。支払い状況は、利用者のローン返済の月数で表されます(2005 年 4 月時点)。 | def get_agg_data(df, x_col, y_col, bins=11):
xbins = pd.cut(df[x_col], bins=bins)
data = df[[x_col, y_col]].groupby(xbins).agg(['mean', 'sem'])
return data
def plot_2d_means_credit(input_df, x_col, y_col, x_label, y_label):
plt.rcParams['font.family'] = ['serif']
_, ax = plt.subplots(nrows=1, ncols=1)
plt... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
債務不履行率を予測する較正済み線形モデルをトレーニングする
次に、利用者がローンの債務不履行となるかどうかを予測するために、TFL の較正済み線形モデルをトレーニングします。利用者の 4 月の婚姻状況とローン返済の延滞月数(返済状況)を 2 つの特徴量として使用します。トレーニングラベルは、利用者がローンの債務不履行になったかどうかを示します。
まず制約を使用せずに、較正済み線形モデルをトレーニングします。次に、単調性制約を使用して較正済み線形モデルをトレーニングし、モデルの出力と精度に生じる違いを観察します。
債務不履行データセットの特徴量を構成するためのヘルパー関数
これらのヘルパー関数は債務不履行の事例に特化した関数です。 | def get_input_fn_credit(input_df, num_epochs, batch_size=None):
"""Gets TF input_fn for credit default models."""
return tf.compat.v1.estimator.inputs.pandas_input_fn(
x=input_df[['MARRIAGE', 'PAY_0']],
y=input_df['default'],
num_epochs=num_epochs,
batch_size=batch_size or len(input_df),
... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
トレーニング済みモデルの出力を視覚化するためのヘルパー関数 | def plot_predictions_credit(input_df,
estimator,
x_col,
x_label='Repayment Status (April)',
y_label='Predicted default probability'):
predictions = get_predicted_probabilities(
estimator=estimator, in... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
制約なし(非単調性)の較正済み線形モデルをトレーニングする | nomon_linear_estimator = optimize_learning_rates(
train_df=credit_train_df,
val_df=credit_val_df,
test_df=credit_test_df,
monotonicity=0,
learning_rates=LEARNING_RATES,
batch_size=BATCH_SIZE,
num_epochs=NUM_EPOCHS,
get_input_fn=get_input_fn_credit,
get_feature_columns_and_configs=get... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
単調な較正済み線形モデルをトレーニングする | mon_linear_estimator = optimize_learning_rates(
train_df=credit_train_df,
val_df=credit_val_df,
test_df=credit_test_df,
monotonicity=1,
learning_rates=LEARNING_RATES,
batch_size=BATCH_SIZE,
num_epochs=NUM_EPOCHS,
get_input_fn=get_input_fn_credit,
get_feature_columns_and_configs=get_f... | site/ja/lattice/tutorials/shape_constraints_for_ethics.ipynb | tensorflow/docs-l10n | apache-2.0 |
Evaluate fitness of model using cost (lost) function
Cost function for simple linear regression is the sum total of residuals, called RSS | import numpy as np
print("Residual sum of squares: %.2f" %np.mean((model.predict(X)-Y)**2)) | Chapters/Two/Simple Linear Regression.ipynb | fadeetch/Mastering-ML-Python | mit |
Solving OLS for simple regression
Goal is to calculate vector of coefficients beta that minimizes cost function. | from __future__ import division
xbar = np.mean(X)
ybar = np.mean(Y)
print("Mean of X is:", xbar)
print("Mean of Y is:", ybar)
#Make own function for variance and covariance to better understand how it works
def variance(X):
return np.sum((X - np.mean(X))**2 / (len(X)-1))
def covariance(X,Y):
return np.sum((X... | Chapters/Two/Simple Linear Regression.ipynb | fadeetch/Mastering-ML-Python | mit |
Evaluate fit using r square | #Load another set
X_test = np.array([8,9,11,16,12])
Y_test = np.array([11,8.5,15,18,11])
model.fit(X_test.reshape(-1,1),Y_test)
model.predict(X_test.reshape(-1,1))
def total_sum_squares(Y):
return np.sum((Y_test - np.mean(Y_test))**2)
#Residual sum of squares
def residual_sum_squares(Y):
return np.sum( (Y_te... | Chapters/Two/Simple Linear Regression.ipynb | fadeetch/Mastering-ML-Python | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.