markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
8. Calculating wastewater treatment energy requirementsWastewater treatment energy is dependent on the type of treatment required. Wastewater treatment can be subdivided into three stages: primary, secondary and tertiary. The treatment stages used, are then dependent on the final quality requirements of the treated wa... | #Here we load the WWTP inflow data
file_path = os.path.join(input_folder, 'wwtp_inflow.gz')
df_wwtp = pd.read_csv(file_path)
#We define an energy intensity for wastewater treatment and compute the energy demand
wwtp_energy_int = 0.1 # kWh/m3
df_wwtp['pa_e'] = df_wwtp.value * wwtp_energy_int | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
9. Saving the resultsFinally, we save the resulting dataframes as `.gz` files, which is a compressed version of a `csv` file: | #Define and create the output folder
results_folder = os.path.join('dashboard', 'data', scenario, climate)
os.makedirs(results_folder, exist_ok=True)
#Save the results
souss_massa.df.to_csv(os.path.join(results_folder, 'results.gz'), index=False)
sm_desal.df.to_csv(os.path.join(results_folder, 'desal_data.gz'), index=... | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
10. Visualizing some results Using some functions imported from the visualization tool, we can plot some general results for the scenario: Water delivered (Mm3) | water_delivered_plot(souss_massa.df, 'Year', {}) | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
Enery demand (GWh) | energy_demand_plot(souss_massa.df, df_wwtp, sm_desal.df, 'Year', {}) | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
Unmet demand (%) | unmet_demand_plot(souss_massa.df, 'Year', {}) | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
Water supplied (Mm3/year) | water_supply_plot(souss_massa.df, 'Year', {}) | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
Groundwater depth (m) | wtd_plot(souss_massa.df, 'Date', {}) | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
Crop production (ton/year) | crop = pd.read_csv(os.path.join(input_folder, 'production.gz'))
crop_production(crop, 'crop', {}) | _____no_output_____ | MIT | Morocco model/Energy calculations.ipynb | KTH-dESA/FAO |
시각 심화- **Instructor**: Jongwoo Lim / Jiun Bae- **Email**: [jlim@hanyang.ac.kr](mailto:jlim@hanyang.ac.kr) / [jiunbae.623@gmail.com](mailto:jiunbae.623@gmail.com) Machine Learnig BasicIn this example we will take a quick look at how machine learning works. The goals of this example are as follows:- Understand **Machine... | import numpy as np
import matplotlib.pyplot as plt
data_size = 1000
dimension = 2 | _____no_output_____ | MIT | 1-Machine-Learning-Basic/machinelearning.ipynb | hyu-cvlab/deeplearning-practice |
Random points1000 dots within the range of $x: 0..1, y: 0..1$.Points with $y>x$ will be green (label=0) and points with no blue (label=1). | points = np.random.rand(data_size, dimension)
labels = np.zeros(data_size)
labels[points[:, 0] > points[:, 1]] = 1
line = np.arange(0, 1, .001)
plt.scatter(points[labels == 0][:, 0], points[labels == 0][:, 1], c='g')
plt.scatter(points[labels == 1][:, 0], points[labels == 1][:, 1], c='b')
plt.plot(line, line, '-r') | _____no_output_____ | MIT | 1-Machine-Learning-Basic/machinelearning.ipynb | hyu-cvlab/deeplearning-practice |
Simple perceptron$w$ is weight, $b$ is bias$y = wx + b$ | weight = np.random.rand(dimension)
bias = np.random.rand(dimension)
def forward(weight, bias, X):
return np.sum(np.multiply(X, weight) + bias)
prediction = forward(weight, bias, points[0])
print(f'We expected {labels[0]}, prediction is {0 if prediction > .5 else 1}') | We expected 0.0, prediction is 0
| MIT | 1-Machine-Learning-Basic/machinelearning.ipynb | hyu-cvlab/deeplearning-practice |
Calculate `error` and update `weight`, `bias` | error = prediction - labels[0]
weight = weight - .1 * error * points[0]
bias = bias - .1 * error | _____no_output_____ | MIT | 1-Machine-Learning-Basic/machinelearning.ipynb | hyu-cvlab/deeplearning-practice |
Train & Test | train_size = int(data_size * .7)
train_points = points[:train_size]
train_labels = labels[:train_size]
test_points = points[train_size:]
test_labels = labels[train_size:]
for epoch in range(500):
# train
for x, y in zip(train_points, train_labels):
# get prediction
pred = forward(weight, bias, x... | Acc: 0.9400
| MIT | 1-Machine-Learning-Basic/machinelearning.ipynb | hyu-cvlab/deeplearning-practice |
print("Setting up colab environment")
!pip uninstall -y -q pyarrow
!pip install -q -U ray[tune]
!pip install -q ray[debug]
# A hack to force the runtime to restart, needed to include the above dependencies.
print("Done installing! Restarting via forced crash (this is not an issue).")
import os
os._exit(0)
## If you ar... | _____no_output_____ | MIT | FinRL_Raytune_with_Alpaca_Paper_Trading.ipynb | NicoleRichards1998/FinRL | |
Paper Trading | ray.shutdown()
ray.init()
state_dim = 1 + 2 + 3 * action_dim + len(TECHNICAL_INDICATORS_LIST) * action_dim
import datetime
import threading
from finrl.finrl_meta.data_processors.processor_alpaca import AlpacaProcessor
import alpaca_trade_api as tradeapi
import time
import pandas as pd
import numpy as np
import torch
im... | _____no_output_____ | MIT | FinRL_Raytune_with_Alpaca_Paper_Trading.ipynb | NicoleRichards1998/FinRL |
[Sebastian Raschka](http://sebastianraschka.com), 2015https://github.com/rasbt/python-machine-learning-book Python Machine Learning - Code Examples Chapter 13 - Parallelizing Neural Network Training with Theano Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the ... | %load_ext watermark
%watermark -a 'Sebastian Raschka' -u -d -v -p numpy,matplotlib,theano,keras
# to install watermark just uncomment the following line:
#%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Overview - [Building, compiling, and running expressions with Theano](Building,-compiling,-and-running-expressions-with-Theano) - [What is Theano?](What-is-Theano?) - [First steps with Theano](First-steps-with-Theano) - [Configuring Theano](Configuring-Theano) - [Working with array structures](Working-with-array-s... | from IPython.display import Image | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Building, compiling, and running expressions with Theano Depending on your system setup, it is typically sufficient to install Theano via pip install Theano For more help with the installation, please see: http://deeplearning.net/software/theano/install.html | Image(filename='./images/13_01.png', width=500) | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
What is Theano? ... First steps with Theano Introducing the TensorType variables. For a complete list, see http://deeplearning.net/software/theano/library/tensor/basic.htmlall-fully-typed-constructors | import theano
from theano import tensor as T
# initialize
x1 = T.scalar()
w1 = T.scalar()
w0 = T.scalar()
z1 = w1 * x1 + w0
# compile
net_input = theano.function(inputs=[w1, x1, w0], outputs=z1)
# execute
net_input(2.0, 1.0, 0.5) | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Configuring Theano Configuring Theano. For more options, see- http://deeplearning.net/software/theano/library/config.html- http://deeplearning.net/software/theano/library/floatX.html | print(theano.config.floatX)
theano.config.floatX = 'float32' | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
To change the float type globally, execute export THEANO_FLAGS=floatX=float32 in your bash shell. Or execute Python script as THEANO_FLAGS=floatX=float32 python your_script.py Running Theano on GPU(s). For prerequisites, please see: http://deeplearning.net/software/theano/tutorial/using_gpu.htmlNote that `fl... | print(theano.config.device) | cpu
| MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
You can run a Python script on CPU via: THEANO_FLAGS=device=cpu,floatX=float64 python your_script.pyor GPU via THEANO_FLAGS=device=gpu,floatX=float32 python your_script.py It may also be convenient to create a `.theanorc` file in your home directory to make those configurations permanent. For example, to always u... | import numpy as np
# initialize
# if you are running Theano on 64 bit mode,
# you need to use dmatrix instead of fmatrix
x = T.fmatrix(name='x')
x_sum = T.sum(x, axis=0)
# compile
calc_sum = theano.function(inputs=[x], outputs=x_sum)
# execute (Python list)
ary = [[1, 2, 3], [1, 2, 3]]
print('Column sum:', calc_sum... | Column sum: [ 2. 4. 6.]
Column sum: [ 2. 4. 6.]
| MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Updating shared arrays.More info about memory management in Theano can be found here: http://deeplearning.net/software/theano/tutorial/aliasing.html | # initialize
x = T.fmatrix(name='x')
w = theano.shared(np.asarray([[0.0, 0.0, 0.0]],
dtype=theano.config.floatX))
z = x.dot(w.T)
update = [[w, w + 1.0]]
# compile
net_input = theano.function(inputs=[x],
updates=update,
outputs=z)
... | z0: [[ 0.]]
z1: [[ 6.]]
z2: [[ 12.]]
z3: [[ 18.]]
z4: [[ 24.]]
| MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
We can use the `givens` variable to insert values into the graph before compiling it. Using this approach we can reduce the number of transfers from RAM (via CPUs) to GPUs to speed up learning with shared variables. If we use `inputs`, a datasets is transferred from the CPU to the GPU multiple times, for example, if we... | # initialize
data = np.array([[1, 2, 3]],
dtype=theano.config.floatX)
x = T.fmatrix(name='x')
w = theano.shared(np.asarray([[0.0, 0.0, 0.0]],
dtype=theano.config.floatX))
z = x.dot(w.T)
update = [[w, w + 1.0]]
# compile
net_input = theano.function(inputs=[],
... | z: [[ 0.]]
z: [[ 6.]]
z: [[ 12.]]
z: [[ 18.]]
z: [[ 24.]]
| MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Wrapping things up: A linear regression example Creating some training data. | import numpy as np
X_train = np.asarray([[0.0], [1.0], [2.0], [3.0], [4.0],
[5.0], [6.0], [7.0], [8.0], [9.0]],
dtype=theano.config.floatX)
y_train = np.asarray([1.0, 1.3, 3.1, 2.0, 5.0,
6.3, 6.6, 7.4, 8.0, 9.0],
dtype=theano.conf... | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Implementing the training function. | import theano
from theano import tensor as T
import numpy as np
def train_linreg(X_train, y_train, eta, epochs):
costs = []
# Initialize arrays
eta0 = T.fscalar('eta0')
y = T.fvector(name='y')
X = T.fmatrix(name='X')
w = theano.shared(np.zeros(
shape=(X_train.shape[1]... | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Plotting the sum of squared errors cost vs epochs. | %matplotlib inline
import matplotlib.pyplot as plt
costs, w = train_linreg(X_train, y_train, eta=0.001, epochs=10)
plt.plot(range(1, len(costs)+1), costs)
plt.tight_layout()
plt.xlabel('Epoch')
plt.ylabel('Cost')
plt.tight_layout()
# plt.savefig('./figures/cost_convergence.png', dpi=300)
plt.show() | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Making predictions. | def predict_linreg(X, w):
Xt = T.matrix(name='X')
net_input = T.dot(Xt, w[1:]) + w[0]
predict = theano.function(inputs=[Xt], givens={w: w}, outputs=net_input)
return predict(X)
plt.scatter(X_train, y_train, marker='s', s=50)
plt.plot(range(X_train.shape[0]),
predict_linreg(X_train, w),
... | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Choosing activation functions for feedforward neural networks ... Logistic function recap The logistic function, often just called "sigmoid function" is in fact a special case of a sigmoid function.Net input $z$:$$z = w_1x_{1} + \dots + w_mx_{m} = \sum_{j=1}^{m} x_{j}w_{j} \\ = \mathbf{w}^T\mathbf{x}$$Logistic acti... | # note that first element (X[0] = 1) to denote bias unit
X = np.array([[1, 1.4, 1.5]])
w = np.array([0.0, 0.2, 0.4])
def net_input(X, w):
z = X.dot(w)
return z
def logistic(z):
return 1.0 / (1.0 + np.exp(-z))
def logistic_activation(X, w):
z = net_input(X, w)
return logistic(z)
print('P(y=1|x) ... | P(y=1|x) = 0.707
| MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Now, imagine a MLP perceptron with 3 hidden units + 1 bias unit in the hidden unit. The output layer consists of 3 output units. | # W : array, shape = [n_output_units, n_hidden_units+1]
# Weight matrix for hidden layer -> output layer.
# note that first column (A[:][0] = 1) are the bias units
W = np.array([[1.1, 1.2, 1.3, 0.5],
[0.1, 0.2, 0.4, 0.1],
[0.2, 0.5, 2.1, 1.9]])
# A : array, shape = [n_hidden+1, n_s... | predicted class label: 2
| MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Estimating probabilities in multi-class classification via the softmax function The softmax function is a generalization of the logistic function and allows us to compute meaningful class-probalities in multi-class settings (multinomial logistic regression).$$P(y=j|z) =\phi_{softmax}(z) = \frac{e^{z_j}}{\sum_{k=1}^K ... | def softmax(z):
return np.exp(z) / np.sum(np.exp(z))
def softmax_activation(X, w):
z = net_input(X, w)
return softmax(z)
y_probas = softmax(Z)
print('Probabilities:\n', y_probas)
y_probas.sum()
y_class = np.argmax(Z, axis=0)
y_class | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Broadening the output spectrum using a hyperbolic tangent Another special case of a sigmoid function, it can be interpreted as a rescaled version of the logistic function.$$\phi_{tanh}(z) = \frac{e^{z}-e^{-z}}{e^{z}+e^{-z}}$$Output range: (-1, 1) | def tanh(z):
e_p = np.exp(z)
e_m = np.exp(-z)
return (e_p - e_m) / (e_p + e_m)
import matplotlib.pyplot as plt
%matplotlib inline
z = np.arange(-5, 5, 0.005)
log_act = logistic(z)
tanh_act = tanh(z)
# alternatives:
# from scipy.special import expit
# log_act = expit(z)
# tanh_act = np.tanh(z)
plt.ylim... | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Training neural networks efficiently using Keras Loading MNIST 1) Download the 4 MNIST datasets from http://yann.lecun.com/exdb/mnist/- train-images-idx3-ubyte.gz: training set images (9912422 bytes) - train-labels-idx1-ubyte.gz: training set labels (28881 bytes) - t10k-images-idx3-ubyte.gz: test set images (164... | import os
import struct
import numpy as np
def load_mnist(path, kind='train'):
"""Load MNIST data from `path`"""
labels_path = os.path.join(path,
'%s-labels-idx1-ubyte'
% kind)
images_path = os.path.join(path,
... | Rows: 10000, columns: 784
| MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Multi-layer Perceptron in Keras Once you have Theano installed, [Keras](https://github.com/fchollet/keras) can be installed via pip install Keras In order to run the following code via GPU, you can execute the Python script that was placed in this directory via THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float3... | import theano
theano.config.floatX = 'float32'
X_train = X_train.astype(theano.config.floatX)
X_test = X_test.astype(theano.config.floatX) | _____no_output_____ | MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
One-hot encoding of the class variable: | from keras.utils import np_utils
print('First 3 labels: ', y_train[:3])
y_train_ohe = np_utils.to_categorical(y_train)
print('\nFirst 3 labels (one-hot):\n', y_train_ohe[:3])
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import SGD
np.random.seed(1)
model = Sequenti... | Test accuracy: 94.39%
| MIT | code/ch13/ch13.ipynb | wei-Z/Python-Machine-Learning |
Confidence Intervals We have developed a method for estimating a parameter by using random sampling and the bootstrap. Our method produces an interval of estimates, to account for chance variability in the random sample. By providing an interval of estimates instead of just one estimate, we give ourselves some wiggle ... | baby = Table.read_table(path_data + 'baby.csv')
baby | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
Birth weight is an important factor in the health of a newborn infant – smaller babies tend to need more medical care in their first days than larger newborns. It is therefore helpful to have an estimate of birth weight before the baby is born. One way to do this is to examine the relationship between birth weight and ... | ratios = baby.select('Birth Weight', 'Gestational Days').with_column(
'Ratio BW/GD', baby.column('Birth Weight')/baby.column('Gestational Days')
)
ratios | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
Here is a histogram of the ratios. | ratios.select('Ratio BW/GD').hist() | /home/choldgraf/anaconda/envs/dev/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
At first glance the histogram looks quite symmetric, with the density at its maximum over the interval 4 ounces per day to 4.5 ounces per day. But a closer look reveals that some of the ratios were quite large by comparison. The maximum value of the ratios was just over 0.78 ounces per day, almost double the typical va... | ratios.sort('Ratio BW/GD', descending=True).take(0) | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
The median gives a sense of the typical ratio because it is unaffected by the very large or very small ratios. The median ratio in the sample is about 0.429 ounces per day. | np.median(ratios.column(2)) | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
But what was the median in the population? We don't know, so we will estimate it. Our method will be exactly the same as in the previous section. We will bootstrap the sample 5,000 times resulting in 5,000 estimates of the median. Our 95% confidence interval will be the "middle 95%" of all of our estimates.Recall the f... | def bootstrap_median(original_sample, label, replications):
"""Returns an array of bootstrapped sample medians:
original_sample: table containing the original sample
label: label of column containing the variable
replications: number of bootstrap samples
"""
just_one_column = original_... | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
The 95% confidence interval goes form about 0.425 ounces per day to about 0.433 ounces per day. We are estimating the the median "birth weight to gestational days" ratio in the population is somewhere in the interval 0.425 ounces per day to 0.433 ounces per day.The estimate of 0.429 based on the original sample happens... | resampled_medians = Table().with_column(
'Bootstrap Sample Median', bstrap_medians
)
resampled_medians.hist(bins=15)
plots.plot(make_array(left, right), make_array(0, 0), color='yellow', lw=8); | /home/choldgraf/anaconda/envs/dev/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
This histogram and interval resembles those we drew in the previous section, with one big difference – there is no red dot showing where the parameter is. We don't know where that dot should be, or whether it is even in the interval.We just have an interval of estimates. It is a 95% confidence interval of estimates, be... | baby.select('Maternal Age').hist()
np.mean(baby.column('Maternal Age')) | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
What was the average age of the mothers in the population? We don't know the value of this parameter.Let's estimate the unknown parameter by the bootstrap method. To do this, we will edit the code for `bootstrap_median` to instead define the function `bootstrap_mean`. The code is the same except that the statistics are... | def bootstrap_mean(original_sample, label, replications):
"""Returns an array of bootstrapped sample means:
original_sample: table containing the original sample
label: label of column containing the variable
replications: number of bootstrap samples
"""
just_one_column = original_samp... | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
The 95% confidence interval goes from about 26.9 years to about 27.6 years. That is, we are estimating that the average age of the mothers in the population is somewhere in the interval 26.9 years to 27.6 years. Notice how close the two ends are to the average of about 27.2 years in the original sample. The sample size... | resampled_means = Table().with_column(
'Bootstrap Sample Mean', bstrap_means
)
resampled_means.hist(bins=15)
plots.plot(make_array(left, right), make_array(0, 0), color='yellow', lw=8); | /home/choldgraf/anaconda/envs/dev/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
Once again, the average of the original sample (27.23 years) is close to the center of the interval. That's not very surprising, because each bootstrapped sample is drawn from that same original sample. The averages of the bootstrapped samples are about symmetrically distributed on either side of the average of the sam... | baby.select('Maternal Age').hist() | /home/choldgraf/anaconda/envs/dev/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
This is a consequence of the Central Limit Theorem of probability and statistics. In later sections, we will see what the theorem says. An 80% Confidence Interval You can use the bootstrapped sample means to construct an interval of any level of confidence. For example, to construct an 80% confidence interval for the ... | left_80 = percentile(10, bstrap_means)
right_80 = percentile(90, bstrap_means)
make_array(left_80, right_80)
resampled_means.hist(bins=15)
plots.plot(make_array(left_80, right_80), make_array(0, 0), color='yellow', lw=8); | /home/choldgraf/anaconda/envs/dev/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
This 80% confidence interval is much shorter than the 95% confidence interval. It only goes from about 27.0 years to about 27.4 years. While that's a tight set of estimates, you know that this process only produces a good interval about 80% of the time. The earlier process produced a wider interval but we had more conf... | baby.where('Maternal Smoker', are.equal_to(True)).num_rows/baby.num_rows | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
For what follows is useful to observe that this proportion can also be calculated by an array operation: | smoking = baby.column('Maternal Smoker')
np.count_nonzero(smoking)/len(smoking) | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
What percent of mothers in the population smoked during pregnancy? This is an unknown parameter which we can estimate by a bootstrap confidence interval. The steps in the process are analogous to those we took to estimate the population mean and median.We will start by defining a function `bootstrap_proportion` that re... | def bootstrap_proportion(original_sample, label, replications):
"""Returns an array of bootstrapped sample proportions:
original_sample: table containing the original sample
label: label of column containing the Boolean variable
replications: number of bootstrap samples
"""
just_one_co... | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
Let us use `bootstrap_proportion` to construct an approximate 95% confidence interval for the percent of smokers among the mothers in the population. The code is analogous to the corresponding code for the mean and median. | # Generate the proportions from 5000 bootstrap samples
bstrap_props = bootstrap_proportion(baby, 'Maternal Smoker', 5000)
# Get the endpoints of the 95% confidence interval
left = percentile(2.5, bstrap_props)
right = percentile(97.5, bstrap_props)
make_array(left, right) | _____no_output_____ | MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
The confidence interval goes from about 36% to about 42%. The original sample percent of 39% is very close to the center of the interval, as you can see below. | resampled_proportions = Table().with_column(
'Bootstrap Sample Proportion', bstrap_props
)
resampled_proportions.hist(bins=15)
plots.plot(make_array(left, right), make_array(0, 0), color='yellow', lw=8); | /home/choldgraf/anaconda/envs/dev/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | notebooks/13/3/Confidence_Intervals.ipynb | choldgraf/textbook-jekyll |
Quick and dirty compareSometimes all your need is a simple comparison of two time series. The `fmskill.compare()` method does just that. | from mikeio import Dfs0
import fmskill | _____no_output_____ | MIT | notebooks/Quick_and_dirty_compare.ipynb | caichac-dhi/fmskill |
The model
Can be either a dfs0 or a DataFrame. | fn_mod = '../tests/testdata/SW/ts_storm_4.dfs0'
df_mod = Dfs0(fn_mod).read(items=0).to_dataframe() # select 1 item | _____no_output_____ | MIT | notebooks/Quick_and_dirty_compare.ipynb | caichac-dhi/fmskill |
The observation
Can be either a dfs0, a DataFrame or a PointObservation object. | fn_obs = '../tests/testdata/SW/eur_Hm0.dfs0' | _____no_output_____ | MIT | notebooks/Quick_and_dirty_compare.ipynb | caichac-dhi/fmskill |
compare()
The compare() method will return an object that can be used for scatter plots, skill assessment, time series plots etc.
If the observation or model has more than 1 item, the `obs_item` or `mod_item` can be given to specify the relevant item. | c = fmskill.compare(fn_obs, df_mod) # both with 1 item only
#c = fmskill.compare(fn_obs, fn_mod, mod_item=0) # need to specify item in model file
c.plot_timeseries();
c.skill()
c.scatter()
c.taylor(normalize_std=True) | _____no_output_____ | MIT | notebooks/Quick_and_dirty_compare.ipynb | caichac-dhi/fmskill |
Wczytywanie danych | cd '/content/drive/My Drive/Colab Notebooks/dw_matrix/matrix_two/dw_matrix_car'
df = pd.read_hdf('data/car.h5')
df.shape | _____no_output_____ | MIT | day5.ipynb | wojla/dw_matrix_car |
Feature Engineering | SUFFIX_CAT = '__cat'
for feat in df.columns:
if isinstance(df[feat][0], list): continue
factorized_values = df[feat].factorize()[0]
if SUFFIX_CAT in feat:
df[feat] = factorized_values
else:
df[feat + SUFFIX_CAT] = factorized_values
# cat_feats = [x for x in df.columns if SUFFIX_CAT in x]
# cat_feat... | [06:43:37] WARNING: /workspace/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.
[06:43:41] WARNING: /workspace/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.
[06:43:45] WARNING: /workspace/src/objective/regression_obj.cu:152... | MIT | day5.ipynb | wojla/dw_matrix_car |
Hyperopt | def obj_func(params):
print("Training with params: ")
print(params)
mean_mae, score_std = run_model(xgb.XGBRegressor(**params), feats)
return {'loss': np.abs(mean_mae), 'status': STATUS_OK}
# space
xgb_reg_params = {
'learning_rate': hp.choice('learning_rate', np.arange(0.05, 0.31, 0.05)),
'max_dep... | _____no_output_____ | MIT | day5.ipynb | wojla/dw_matrix_car |
Bag J$X^J_U : x^j_u \sim f^j(x) = \sum_{i=1}^{K}\alpha^j \pi_i^j \Phi^+_i(x) + (1 - \alpha^j) \rho_i^j \Phi^-_i(x)$$\sum_{i=1}^{K}\pi_i^j = 1$$\sum_{i=1}^{K}\rho_i^j = 1$ $X^J_L : x^j_l \sim f^j_+(x) = \sum_{i=1}^{K}\pi_i^j \Phi_i^+(x)$ | from pgmpy.models import BayesianModel
from pgmpy.inference import VariableElimination
import daft
from daft import PGM
def convert_pgm_to_pgmpy(pgm):
"""Takes a Daft PGM object and converts it to a pgmpy BayesianModel"""
edges = [(edge.node1.name, edge.node2.name) for edge in pgm._edges]
model = BayesianMo... | _____no_output_____ | Apache-2.0 | 49_Overview.ipynb | Dzeiberg/multiinstance |
$p(x) = \sum_{b \in Bags}p(b) \sum_{y_i} p(y_i|b)\sum_{i=1}^{K}p(c_i|b,y)p(x|c_i,y)$ | model.get_independencies()
model.fit() | _____no_output_____ | Apache-2.0 | 49_Overview.ipynb | Dzeiberg/multiinstance |
$p(x|b_i) = \sum_{b\in Bags}I[b_i = b][]$ | pgm.add_node(daft.Node("bag",r"B",2,1,observed=True))
pgm.add_node(daft.Node("label",r"y",3,1))
pgm.add_node(daft.Node("cluster",r"c",3,2))
pgm.add_node(daft.Node("data",r"x",4,2,observed=True))
pgm.add_edge("bag","label")
pgm.add_edge("bag","cluster")
pgm.add_edge("label","cluster")
pgm.add_edge("label","data")
pgm.ad... | _____no_output_____ | Apache-2.0 | 49_Overview.ipynb | Dzeiberg/multiinstance |
$p(x) = \sum_{b_i \in {Bags}}I[b_i = b]$ | def convert_pgm_to_pgmpy(pgm):
"""Takes a Daft PGM object and converts it to a pgmpy BayesianModel"""
edges = [(edge.node1.name, edge.node2.name) for edge in pgm._edges]
model = BayesianModel(edges)
return model
pgm.render()
plt.show() | _____no_output_____ | Apache-2.0 | 49_Overview.ipynb | Dzeiberg/multiinstance |
model.to_daft(node_pos={"bag":(1,1), "label":(1,2), "cluster":(2,2), "data":(2,3)}).render() | model.get_independencies()
model = BayesianModel([("bag",'label'),
("bag","cluster"),
("label","cluster"),
("label","data"),
("cluster","data")])
pgm = PGM()
import daft
from daft import PGM
import matplotlib.pyplot as plt
impor... | _____no_output_____ | Apache-2.0 | 49_Overview.ipynb | Dzeiberg/multiinstance |
Interactive analysis with python--------------------------------Before starting this tutorial, ensure that you have set up _tangos_ [as described here](https://pynbody.github.io/tangos/) and the data sources [as described here](https://pynbody.github.io/tangos/data_exploration.html).We get started by importing the modu... | %matplotlib inline
import tangos
import pylab as p | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
First let's inspect what simulations are available in our database: | tangos.all_simulations() | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
For any of these simulations, we can generate a list of available timesteps as follows: | tangos.get_simulation("tutorial_changa").timesteps | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
For any timestep, we can access the halos using `.halos` and a specific halo using standard python 0-based indexing: | tangos.get_simulation("tutorial_changa").timesteps[3].halos[3] | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
One can skip straight to getting a specific halo as follows: | tangos.get_halo("tutorial_changa/%384/halo_4") | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
Note the use of the SQL wildcard % character which avoids us having to type out the entire path. Whatever way you access it, the resulting object allows you to query what properties have been calculated for that specific halo. We can then access those properties using the normal python square-bracket dictionary syntax. | halo = tangos.get_halo("tutorial_changa/%960/halo_1")
halo.keys()
halo['Mvir']
p.imshow(halo['uvi_image']) | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
One can also get meta-information about the computed property. It would be nice to knowthe physical size of the image we just plotted. We retrieve the underlying property objectand ask it: | halo.get_description("uvi_image").plot_extent() | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
This tells us that the image is 15 kpc across. The example properties that come with _tangos_use _pynbody_'s units system to convert everything to physical kpc, solar masses and km/s. Whenyou implement your own properties, you can of course store them in whichever units you like. Getting a time sequence of properties--... | halo = tangos.get_halo("tutorial_gadget/snapshot_020/halo_10")
# Calculate on major progenitor branch:
Mvir, t = halo.calculate_for_progenitors("mass","t()")
# Now perform plotting:
p.plot(t,1e10*Mvir)
p.xlabel("t/Gyr")
p.ylabel(r"$M/h^{-1} M_{\odot}$")
p.semilogy() | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
In the example above, `calculate_for_progenitors` retrieves properties on the major progenitor branch of the chosen halo. One can ask for as many properties as you like, each one being returned as a numpy array in order. In this particular example the first property is the mass (as reported by subfind) and the second i... | halo = tangos.get_halo("tutorial_changa_blackholes/%960/halo_1")
SFR = halo["SFR_histogram"]
# The above is sufficient to retrieve the histogram; however you probably also want to check
# the size of the time bins. The easiest approach is to request a suitable time array to go with
# the SF history:
SFR_property_objec... | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
The advantage of storing the histogram in chunks is that one can reconstruct itin different ways. The default is to go along the major progenitor branch, butone can also sum over all progenitors. The following code shows the fraction ofstar formation in the major progenitor: | SFR_all = halo.calculate('reassemble(SFR_histogram, "sum")')
p.plot(SFR_time_bins, SFR/SFR_all)
p.xlabel("Time/Gyr")
p.ylabel("Frac. SFR in major progenitor") | /Users/app/anaconda/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in true_divide
| BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
_Technical note_: It's worth being aware that the merger information is, of course, quantized to theoutput timesteps even though the SFR information is stored in small chunks. This is rarely an issuebut with coarse timesteps (such as those in the tutorial simulations), the quantization can causenoticable artefacts – he... | BH_accrate = halo.calculate('BH.BH_mdot_histogram')
p.plot(SFR_time_bins, BH_accrate)
p.xlabel("Time/Gyr")
p.ylabel("BH accretion rate/$M_{\odot}\,yr^{-1}$") | /Users/app/Science/tangos/tangos/live_calculation/__init__.py:585: RuntimeWarning: More than one relation for target 'BH' has been found. Picking the first.
warnings.warn("More than one relation for target %r has been found. Picking the first."%str(self.locator), RuntimeWarning)
| BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
This works fine, but you may have noticed the warning that more than one black holeis in the halo of interest. There is more information about the way that links betweenobjects work in _tangos_, and disambiguating between them, in the "using links" sectionbelow. Getting properties for multiple halos--------------------... | timestep = tangos.get_timestep("tutorial_gadget/snapshot_019")
mass, vmax = timestep.calculate_all("mass","VMax")
p.plot(mass*1e10,vmax,'k.')
p.loglog()
p.xlabel("$M/h^{-1} M_{\odot}$")
p.ylabel(r"$v_{max}/{\rm km s^{-1}}$") | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
Often when querying multiple halos we still want to know something about their history, and live calculations enable that. Suppose we want to know how much the mass has grown since the previous snapshot: | mass, fractional_delta_2 = timestep.calculate_all("mass", "(mass-earlier(2).mass)/mass")
p.hlines(0.0,1e10,1e15, colors="gray")
p.plot(mass*1e10, fractional_delta_2,"r.", alpha=0.2)
p.semilogx()
p.ylim(-0.1,0.9)
p.xlim(1e12,1e15)
p.xlabel("$M/h^{-1} M_{\odot}$")
p.ylabel("Fractional growth in mass") | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
This is a much more ambitious use of the live calculation system. Consider the last property retrieved, which is `(mass-earlier(2).mass)/mass`. This combines algebraic operations with _redirection_: `earlier(2)` finds the major progenitor two steps prior to this one, after which `.mass` retrieves the mass at that earli... | halo = tangos.get_halo("tutorial_changa_blackholes/%960/halo_1")
BH_mass = halo.calculate('BH_central.BH_mass') | /Users/app/Science/tangos/tangos/live_calculation/__init__.py:585: RuntimeWarning: More than one relation for target 'BH_central' has been found. Picking the first.
warnings.warn("More than one relation for target %r has been found. Picking the first."%str(self.locator), RuntimeWarning)
| BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
We still get the warning, so there's more than one black hole in the central galaxy.To avoid such warnings, you can specify more about which link you are referring to. For example,we can specifically ask for the black hole with the _largest mass_ and _smallest impact parameters_using the following two queries: | BH_max_mass = halo.calculate('link(BH_central, BH_mass, "max")')
BH_closest = halo.calculate('link(BH_central, BH_central_distance, "min")') | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
The `link` live-calculation function returns the halo with either the maximum or minimum value of anassociated property, here the `BH_mass` and `BH_central_distance` properties respectively. Either approach disambiguates the black holes we mean (in fact, they unsurprisingly lead tothe same disambiguation): | BH_max_mass == BH_closest | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
However one doesn't always have to name a link to make use of it. The mere existence of a linkis sometimes enough. An example is the merger tree information already used. Another usefulexample is when two simulations have the same initial conditions, as in the `tutorial_changa`and `tutorial_changa_blackholes` examples;... | SFR_in_other_sim = halo.calculate("match('tutorial_changa').SFR_histogram")
p.plot(SFR_time_bins, halo['SFR_histogram'],color='r', label="With AGN feedback")
p.plot(SFR_time_bins, SFR_in_other_sim, color='b',label="No AGN feedback")
p.legend(loc="lower right")
p.semilogy()
p.xlabel("t/Gyr")
p.ylabel("SFR/$M_{\odot}\,yr... | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
The `match` syntax simply tries to follow links until it finds a halo in the named_tangos_ context. One can use it to match halos across entire timesteps too; let'scompare the stellar masses of our objects: | timestep = tangos.get_timestep("tutorial_changa/%960")
Mstar_no_AGN, Mstar_AGN = timestep.calculate_all("star_mass_profile[-1]",
"match('tutorial_changa_blackholes').star_mass_profile[-1]")
# note that we use star_mass_profile[-1] to get the last entry of the star_mass_... | _____no_output_____ | BSD-3-Clause | docs/Data exploration with python.ipynb | trquinn/tangos |
Previews--------Previews are typically invoked before running the often time-consuming generation process triggered by:meth:`.ContainerFlowGenerationManager.generate`.A preview provides a first impression on what kind of data will be generated based on the input distributions and schedules.At this stage, some simplific... | import datetime
import matplotlib.pyplot as plt
from IPython.display import Markdown
import conflowgen
database_chooser = conflowgen.DatabaseChooser(
sqlite_databases_directory="./data/"
)
database_chooser.load_existing_sqlite_database("demo_deham_cta.sqlite") | _____no_output_____ | MIT | docs/notebooks/previews.ipynb | 1grasse/conflowgen |
Showing Previews as TextFor running all previews, a convencience function exists.It can simply print all information to the standard output. | conflowgen.run_all_previews(
as_text=True,
display_text_func=print,
) | _____no_output_____ | MIT | docs/notebooks/previews.ipynb | 1grasse/conflowgen |
Displaying Previews as GraphsPreviews can also be displayed as graphs.The depicted information contains the same information but might be easier to grasp.For emphasis, in the following the text version and graph version of the report are presented side-by-side.In addition, we also use the Markdown capabilities of the ... | conflowgen.run_all_previews(
as_text=True,
as_graph=True,
display_text_func=lambda text: display(Markdown(text)),
display_in_markup_language="markdown",
static_graphs=True
) | _____no_output_____ | MIT | docs/notebooks/previews.ipynb | 1grasse/conflowgen |
n=b | # Binary representation ---> Microsoft
# Difficulty: School Marks: 0
'''
Write a program to print Binary representation of a given number N.
Input:
The first line of input contains an integer T, denoting the number of test cases. Each test case contains an integer N.
Output:
For each test case, print the binary rep... | 2
4
5
17
35
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
***IMP*** | # ------------------------------------------IMP---------------------------------------
"https://practice.geeksforgeeks.org/problems/toggle-bits-given-range/0/?track=sp-bit-magic&batchId=152"
# Toggle bits given range
# Difficulty: Basic Marks: 1
'''
Given a non-negative number N and two values L and R. The problem ... | 2
100
70
129
24
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Check whether K-th bit is set or not](https://practice.geeksforgeeks.org/problems/check-whether-k-th-bit-is-set-or-not/0/?track=sp-bit-magic&batchId=152)- Company Tag: Cisco- Difficulty: Basic - Marks: 1***Given a number N and a bit number K, check if Kth bit of N is set or not. A bit is called set if it is 1. Positi... | for _ in range(int(input())):
a=bin(int(input()))[2:]
k=int(input())
if a[(len(a)-1)-k]=='1':
print('Yes')
else:
print('No') | 3
4
0
No
4
2
Yes
500
3
No
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Rightmost different bit](https://practice.geeksforgeeks.org/problems/rightmost-different-bit/0/?track=sp-bit-magic&batchId=152)- Difficulty: Basic- Marks: 1***Given two numbers M and N. The task is to find the position of rightmost different bit in binary representation of numbers.******Input:***\The input line conta... | for _ in range(int(input())):
a,c=input().split()
a=bin(int(a))[2:]
c=bin(int(c))[2:]
an=len(a)
cn=len(c)
if an!=cn:
if (an-cn)>0:
c='0'*(an-cn)+c
else:
a='0'*(cn-an)+a
k=len(a)
for i in range(k):
if a[k-1-i]!=c[k-1-i]:
print(i+... | 2
11 9
2
52 4
5
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Number is sparse or not](https://practice.geeksforgeeks.org/problems/number-is-sparse-or-not/0/?track=sp-bit-magic&batchId=152)- Difficulty: Basic- Marks: 1***Given a number N, check whether it is sparse or not. A number is said to be a sparse number if in the binary representation of the number no two or more consec... | for _ in range(int(input())):
a=bin(int(input()))[2:]
if a.count('11')>0:
print(0)
else:
print(1) | 1
81
0
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Gray Code](https://practice.geeksforgeeks.org/problems/gray-code/0/?track=sp-bit-magic&batchId=152)- Difficulty: Basic- Marks: 1***You are given a decimal number n. You need to find the gray code of the number n and convert it into decimal.To see how it's done, refer here.******Input:***\The first line contains an in... | for _ in range(int(input())):
a=bin(int(input()))[2:]
c=a[0]
for i in range(1,len(a)):
k=(int(a[i])+int(a[i-1]))
if k==0 or k==1:
c+=str(k)
else:
c+='0'
print(int(c,2)) | 1
4
6
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Gray to Binary equivalent](https://practice.geeksforgeeks.org/problems/gray-to-binary-equivalent/0/?track=sp-bit-magic&batchId=152)- Difficulty: Basic- Marks: 1***Given N in Gray code equivalent. Find its binary equivalent.******Input:***\The first line contains an integer T, number of test cases. For each test cases... | for _ in range(int(input())):
a=bin(int(input()))[2:]
c=a[0]
for i in range(1,len(a)):
k=(int(a[i])+int(c[i-1]))
if k==0 or k==1:
c+=str(k)
else:
c+='0'
print(int(c,2)) | 1
4
7
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Check if a Integer is power of 8 or not](https://practice.geeksforgeeks.org/problems/check-if-a-integer-is-power-of-8-or-not/0/?track=sp-bit-magic&batchId=152)- Difficulty: Easy- Marks: 2***Given a positive integer N, The task is to find if it is a power of eight or not.******Input:***\The first line of input contain... | for _ in range(int(input())):
n=int(input())
i=1
while 8**i<=n:
i+=1
if 8**(i-1)==n:
print('Yes')
else:
print('No') | 2
64
Yes
75
No
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Is Binary Number Multiple of 3](https://practice.geeksforgeeks.org/problems/is-binary-number-multiple-of-3/0/?track=sp-bit-magic&batchId=152)- Company Tags : Adobe, Amazon, Microsoft- Difficulty: Medium- Marks: 4***Given a binary number, write a program that prints 1 if given binary number is a multiple of 3. Else p... | for _ in range(int(input())):
n=int(input(),2)
if n%3==0:
print(1)
else:
print(0) | 1
011
1
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Reverse Bits](https://practice.geeksforgeeks.org/problems/reverse-bits/0/?track=sp-bit-magic&batchId=152)- Company Tags : Amazon, Cisco, HCL, Nvidia, Qualcomm- Difficulty: Easy- Marks: 2***Given a 32 bit number x, reverse its binary form and print the answer in decimal.******Input:***\The first line of input consists... | for _ in range(int(input())):
a=bin(int(input()))[2:][::-1]
a+='0'*(32-len(a))
print(int(a,2)) | 1
1
2147483648
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Swap all odd and even bits](https://practice.geeksforgeeks.org/problems/swap-all-odd-and-even-bits/0/?track=sp-bit-magic&batchId=152)- Difficulty: Easy- Marks: 2***Given an unsigned integer N. The task is to swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to... | for _ in range(int(input())):
a=bin(int(input()))[2:]
if len(a)%4!=0:
a='0'*(4-len(a)%4)+a
s=''
for i,j in zip(a[1::2],a[::2]):
s=s+i+j
print(int(s,2))
def f(a,c):
a=bin(a)[2:]
c=bin(c)[2:]
an=len(a)
cn=len(c)
if an!=cn:
if (an-cn)>0:
c='0'*(an... | 1
8
-1865008399 -524833575 -1162539990 -1003374718 -1677272376 -2046456104 -689632770 -688705725
800
| MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
[Bleak Numbers](https://practice.geeksforgeeks.org/problems/bleak-numbers/0/?track=sp-bit-magic&batchId=152)- Company Tags : SAP Labs- Difficulty: Medium- Marks: 4***Given an integer, check whether it is Bleak or not.******A number ‘n’ is called Bleak if it cannot be represented as sum of a positive number x and set b... | for _ in range(int(input())):
n=int(input())
for i in range(0,n+1,2):
if (i+bin(i).count('1'))==n:
print(0)
break
else:
print(1)
a
a[1::2]
''+'2'
a=bin(-2)
a
int('1b10',2)
a=list(map(int,input().split()))
xor=0
for i in range(len(a)):
for j in range(i+1,len(a)):
... | _____no_output_____ | MIT | GeeksForGeeks/Sudo Placement 2019/bit-magic/bit-magic.ipynb | Dhaneshgupta1027/Python |
______Copyright Pierian DataFor more information, visit us at www.pieriandata.com Introduction to ForecastingIn the previous section we fit various smoothing models to existing data. The purpose behind this is to predict what happens next.What's our best guess for next month's value? For the next six months?In this se... | import pandas as pd
import numpy as np
%matplotlib inline
df = pd.read_csv('../Data/airline_passengers.csv',index_col='Month',parse_dates=True)
df.index.freq = 'MS'
df.head()
df.tail()
df.info() | <class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 144 entries, 1949-01-01 to 1960-12-01
Freq: MS
Data columns (total 1 columns):
Thousands of Passengers 144 non-null int64
dtypes: int64(1)
memory usage: 2.2 KB
| MIT | tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb | juspreet51/ml_templates |
Train Test Split | train_data = df.iloc[:108] # Goes up to but not including 108
test_data = df.iloc[108:] | _____no_output_____ | MIT | tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb | juspreet51/ml_templates |
Fitting the Model | from statsmodels.tsa.holtwinters import ExponentialSmoothing
fitted_model = ExponentialSmoothing(train_data['Thousands of Passengers'],trend='mul',seasonal='mul',seasonal_periods=12).fit() | _____no_output_____ | MIT | tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb | juspreet51/ml_templates |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.