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 |
|---|---|---|---|---|---|
Transforming the dataThe World Bank reports GDP in US dollars and cents. To make the data easier to read, the GDP is converted to millions of British pounds (the author's local currency) with the following auxiliary functions, using the average 2013 dollar-to-pound conversion rate provided by . | def roundToMillions (value):
return round(value / 1000000)
def usdToGBP (usd):
return usd / 1.334801
GDP = 'GDP (£m)'
gdpCountries[GDP] = gdpCountries[GDP_INDICATOR].apply(usdToGBP).apply(roundToMillions)
gdpCountries.head()
COUNTRY = 'Country Name'
headings = [COUNTRY, GDP]
gdpClean = gdpCountries[headings]
... | _____no_output_____ | MIT | Ugwu Lilian WT-21-138/2018_LE_GDP.ipynb | ruthwaiharo/Week-5-Assessment |
Calculating the correlationTo measure if the life expectancy and the GDP grow together, the Spearman rank correlation coefficient is used. It is a number from -1 (perfect inverse rank correlation: if one indicator increases, the other decreases) to 1 (perfect direct rank correlation: if one indicator increases, so doe... | from scipy.stats import spearmanr
gdpColumn = gdpVsLife[GDP]
lifeColumn = gdpVsLife[LIFE]
(correlation, pValue) = spearmanr(gdpColumn, lifeColumn)
print('The correlation is', correlation)
if pValue < 0.05:
print('It is statistically significant.')
else:
print('It is not statistically significant.') | The correlation is -0.01111757436417062
It is not statistically significant.
| MIT | Ugwu Lilian WT-21-138/2018_LE_GDP.ipynb | ruthwaiharo/Week-5-Assessment |
The value shows a direct correlation, i.e. richer countries tend to have longer life expectancy. Showing the dataMeasures of correlation can be misleading, so it is best to see the overall picture with a scatterplot. The GDP axis uses a logarithmic scale to better display the vast range of GDP values, from a few milli... | %matplotlib inline
gdpVsLife.plot(x=GDP, y=LIFE, kind='scatter', grid=True, logx=True, figsize=(10, 4)) | _____no_output_____ | MIT | Ugwu Lilian WT-21-138/2018_LE_GDP.ipynb | ruthwaiharo/Week-5-Assessment |
The plot shows there is no clear correlation: there are rich countries with low life expectancy, poor countries with high expectancy, and countries with around 10 thousand (104) million pounds GDP have almost the full range of values, from below 50 to over 80 years. Towards the lower and higher end of GDP, the variatio... | # the 10 countries with lowest GDP
gdpVsLife.sort_values(GDP).head(10)
# the 10 countries with lowest life expectancy
gdpVsLife.sort_values(LIFE).head(10) | _____no_output_____ | MIT | Ugwu Lilian WT-21-138/2018_LE_GDP.ipynb | ruthwaiharo/Week-5-Assessment |
Immune disease associations of Neanderthal-introgressed SNPsThis code investigates if Neanderthal-introgressed SNPs (present in Chen introgressed sequences) have been associated with any immune-related diseases, including infectious diseases, allergic diseases, autoimmune diseases and autoinflammatory diseases, using ... | # Import modules
import pandas as pd | _____no_output_____ | MIT | disease/neanderthal_gwas.ipynb | kshiyao/neanderthal_introgression |
Get Neanderthal SNPs present in GWAS Catalog | # Load Chen Neanderthal-introgressed SNPs
chen = pd.read_excel('../chen/Additional File 1.xlsx', 'Sheet1', usecols=['Chromosome', 'Position', 'Source', 'ID', 'Chen'])
neanderthal = chen.loc[chen.Chen == 'Yes'].copy()
neanderthal.drop('Chen', axis=1)
# Load GWAS catalog
catalog = pd.read_csv('GWAS_Catalog.tsv', sep="\t"... | _____no_output_____ | MIT | disease/neanderthal_gwas.ipynb | kshiyao/neanderthal_introgression |
Immune-related diseases associated with Neanderthal SNPs Infections | nean_catalog.loc[nean_catalog['DISEASE/TRAIT'].str.contains('influenza')]
nean_catalog.loc[nean_catalog['DISEASE/TRAIT'].str.contains('wart')]
nean_catalog.loc[nean_catalog['DISEASE/TRAIT'].str.contains('HIV')]
nean_catalog.loc[nean_catalog['DISEASE/TRAIT'].str.contains('Malaria')] | _____no_output_____ | MIT | disease/neanderthal_gwas.ipynb | kshiyao/neanderthal_introgression |
Allergic diseases | nean_catalog.loc[nean_catalog['MAPPED_TRAIT'].str.contains('allerg')]
nean_catalog.loc[nean_catalog['MAPPED_TRAIT'].str.contains('asthma')]
nean_catalog.loc[nean_catalog['MAPPED_TRAIT'].str.contains('Eczema')] | _____no_output_____ | MIT | disease/neanderthal_gwas.ipynb | kshiyao/neanderthal_introgression |
Autoimmune/autoinflammatory diseases | nean_catalog.loc[nean_catalog['MAPPED_TRAIT'].str.contains('lupus')]
nean_catalog.loc[nean_catalog['MAPPED_TRAIT'].str.contains('rheumatoid')]
nean_catalog.loc[nean_catalog['MAPPED_TRAIT'].str.contains('scleroderma')]
nean_catalog.loc[nean_catalog['MAPPED_TRAIT'].str.contains('Sjogren')]
nean_catalog.loc[nean_catalog['... | _____no_output_____ | MIT | disease/neanderthal_gwas.ipynb | kshiyao/neanderthal_introgression |
Do immune disease-associated Neanderthal SNPs show eQTL? | # Load eQTL data
fairfax_ori = pd.read_csv("../fairfax/tab2_a_cis_eSNPs.txt", sep="\t", usecols=["SNP", "Gene", "Min.dataset", "LPS2.FDR", "LPS24.FDR", "IFN.FDR", "Naive.FDR"])
fairfax_re = pd.read_csv('overlap_filtered_fairfax.csv', usecols=['rsid', 'pvalue', 'gene_id', 'Condition', 'beta'])
fairfax_re.sort_values('p... | _____no_output_____ | MIT | disease/neanderthal_gwas.ipynb | kshiyao/neanderthal_introgression |
American Gut Project exampleThis notebook was created from a question we recieved from a user of MGnify.The question was:```I am attempting to retrieve some of the MGnify results from samples that are part of the American Gut Project based on sample location. However latitude and longitude do not appear to be searchab... | from pandas import DataFrame
import requests
base_url = 'https://www.ebi.ac.uk/ena/portal/api/search'
# parameters
params = {
'result': 'sample',
'query': ' AND '.join([
'geo_box1(16.9175,-158.4687,21.6593,-152.7969)',
'description="*American Gut Project*"'
]),
'fields': ','.join(['se... | secondary_sample_accession lat lon
accession
SAMEA104163502 ERS1822520 19.6 -155.0
SAMEA104163503 ERS1822521 19.6 -155.0
SAMEA104163504 ERS1822522 19.6 -155.0
SAMEA104163505 ERS1822523 19.6 -155.0... | Apache-2.0 | mgnify/src/notebooks/American_Gut_filter_based_in_location.ipynb | ProteinsWebTeam/ebi-metagenomics-examples |
Now we can use EMG API to get the information. | #!/bin/usr/env python
import requests
import sys
def get_links(data):
return data["links"]["related"]
if __name__ == "__main__":
samples_url = "https://www.ebi.ac.uk/metagenomics/api/v1/samples/"
tsv = sys.argv[1] if len(sys.argv) == 2 else None
if not tsv:
print("The first arg is the t... | _____no_output_____ | Apache-2.0 | mgnify/src/notebooks/American_Gut_filter_based_in_location.ipynb | ProteinsWebTeam/ebi-metagenomics-examples |
Employee Attrition PredictionThere is a class of problems that predict that some event happens after N years. Examples are employee attrition, hard drive failure, life expectancy, etc. Usually these kind of problems are considered simple problems and are the models have vairous degree of performance. Usually it is tre... | #Import
import numpy as np
import pandas as pd
import numpy.random
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
import math
%matplotlib inline
numpy.random.seed(1239)
# Read the data
# Source: https://www.ibm.com/communities/analytics/watso... | _____no_output_____ | Apache-2.0 | employee_attrition/attrition-tf.ipynb | mlarionov/machine_learning_POC |
First we will work on the synthetic set of data, for this reason we will not split the dataset to train/test yet | #Now scale the entire dataset, but not the first column (YearsAtCompany). Instead scale the dataset to be similar range
#to the first column
max_year = employee_data.YearsAtCompany.max()
scaler = MinMaxScaler(feature_range=(0, max_year))
scaled_data = pd.DataFrame(scaler.fit_transform(employee_data.values.astype('float... | _____no_output_____ | Apache-2.0 | employee_attrition/attrition-tf.ipynb | mlarionov/machine_learning_POC |
Based on the chart it seems like a realistic data set.Now we need to construct our loss function. It will have an additional parameter: number of yearsWe define probability $p(x, t)$ that the person quits this very day, where t is the number of years and x is the remaining features. Then the likelihood that the person ... | #pick a p
p = 0.01
#Get the maximum years. We need it to make sure that the product of p YearsAtCompany never exceeds 1.
#In reality that is not a problem, but we will use it to correctly create synthetic labels
scaled_data.YearsAtCompany.max()
#Create the synthetic labels.
synthetic_labels = numpy.random.rand(employ... | _____no_output_____ | Apache-2.0 | employee_attrition/attrition-tf.ipynb | mlarionov/machine_learning_POC |
Indeed pretty close to the value of p we set beforehand Logistic Regression with the synthetic labelsIn this version of the POC we will use TensorFlow We need to add ones to the dataframe.But since we scaled everything to be between `0` and `40`, the convergence will be faster if we add `40.0` instead of `1` | #Add 1 to the employee data.
#But to make convergence fa
scaled_data['Ones'] = 40.0
scaled_data
def reset_graph(seed=1239):
tf.reset_default_graph()
tf.set_random_seed(seed)
np.random.seed(seed)
def create_year_column(X, w, year):
year_term = tf.reshape(X[:,0]-year, (-1,1)) * w[0]
year_column = tf.r... | Epoch 0 Cost = [0.4480857]
w: [-0.00260041]
Epoch 1000 Cost = [0.25044656]
w: [-0.04913734]
Epoch 2000 Cost = [0.24958777]
w: [-0.06650413]
Epoch 3000 Cost = [0.24919516]
w: [-0.07856989]
Epoch 4000 Cost = [0.2489799]
w: [-0.08747929]
Epoch 5000 Cost = [0.24980566]
w: [-0.09409016]
Epoch 6000 Cost = [0.24926803]
w: [-0... | Apache-2.0 | employee_attrition/attrition-tf.ipynb | mlarionov/machine_learning_POC |
The cost will never go down to zero, because of the additional term in the loss function. | #We will print the learned weights.
learned_weights = [(column_name,float(best_theta[column_num])) \
for column_num, column_name in enumerate(scaled_data.columns)]
#We print the weights sorted by the absolute value of the value
sorted(learned_weights, key=lambda x: abs(x[1]), reverse=True) | _____no_output_____ | Apache-2.0 | employee_attrition/attrition-tf.ipynb | mlarionov/machine_learning_POC |
To compare with the other result we need to multiplty the last weight by 40 | print(f'The predicted probability is: {float(1/(1+np.exp(-best_theta[-1]*40)))}') | The predicted probability is: 0.010747312568128109
| Apache-2.0 | employee_attrition/attrition-tf.ipynb | mlarionov/machine_learning_POC |
Training a Boltzmann Generator for Alanine DipeptideThis notebook introduces basic concepts behind `bgflow`. It shows how to build an train a Boltzmann generator for a small peptide. The most important aspects it will cover are- retrieval of molecular training data- defining a internal coordinate transform- defining n... | %load_ext autoreload
%autoreload 2
import torch
device = "cuda:3" if torch.cuda.is_available() else "cpu"
dtype = torch.float32
# a context tensor to send data to the right device and dtype via '.to(ctx)'
ctx = torch.zeros([], device=device, dtype=dtype) | _____no_output_____ | MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
Load the Data and the Molecular SystemMolecular trajectories and their corresponding potential energy functions are available from the `bgmol` repository. | # import os
# from bgmol.datasets import Ala2TSF300
# target_energy = Ala2TSF300().get_energy_model(n_workers=1)
import os
import mdtraj
#dataset = mdtraj.load('output.dcd', top='ala2_fromURL.pdb')
dataset = mdtraj.load('TSFtraj.dcd', top='ala2_fromURL.pdb')
#fname = "obc_xmlsystem_savedmodel"
#coordinates = dataset.... | _____no_output_____ | MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
The energy model is a `bgflow.Energy` that wraps around OpenMM. The `n_workers` argument determines the number of openmm contexts that are used for energy evaluations. In notebooks, we set `n_workers=1` to avoid hickups. In production, we can omit this argument so that `n_workers` is automatically set to the number of ... | # def compute_phi_psi(trajectory):
# phi_atoms = [4, 6, 8, 14]
# phi = md.compute_dihedrals(trajectory, indices=[phi_atoms])[:, 0]
# psi_atoms = [6, 8, 14, 16]
# psi = md.compute_dihedrals(trajectory, indices=[psi_atoms])[:, 0]
# return phi, psi
import numpy as np
import mdtraj as md
from matplotli... | torch.Size([143147, 66])
| MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
Define the Internal Coordinate TransformRather than generating all-Cartesian coordinates, we use a mixed internal coordinate transform.The five central alanine atoms will serve as a Cartesian "anchor", from which all other atoms are placed with respect to internal coordinates (IC) defined through a z-matrix. We have d... | import bgflow as bg
# throw away 6 degrees of freedom (rotation and translation)
dim_cartesian = len(rigid_block) * 3 - 6
print(dim_cartesian)
#dim_cartesian = len(system.rigid_block) * 3
dim_bonds = len(z_matrix)
print(dim_bonds)
dim_angles = dim_bonds
dim_torsions = dim_bonds
coordinate_transform = bg.MixedCoordinate... | _____no_output_____ | MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
For demonstration, we transform the first 3 samples from the training data set into internal coordinates as follows: | # bonds, angles, torsions, cartesian, dlogp = coordinate_transform.forward(training_data[:3])
# bonds.shape, angles.shape, torsions.shape, cartesian.shape, dlogp.shape
# #print(bonds) | _____no_output_____ | MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
Prior DistributionThe next step is to define a prior distribution that we can easily sample from. The normalizing flow will be trained to transform such latent samples into molecular coordinates. Here, we just take a normal distribution, which is a rather naive choice for reasons that will be discussed in other notebo... | dim_ics = dim_bonds + dim_angles + dim_torsions + dim_cartesian
mean = torch.zeros(dim_ics).to(ctx)
# passing the mean explicitly to create samples on the correct device
prior = bg.NormalDistribution(dim_ics, mean=mean) | _____no_output_____ | MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
Normalizing FlowNext, we set up the normalizing flow by stacking together different neural networks. For now, we will do this in a rather naive way, not distinguishing between bonds, angles, and torsions. Therefore, we will first define a flow that splits the output from the prior into the different IC terms. Split La... | split_into_ics_flow = bg.SplitFlow(dim_bonds, dim_angles, dim_torsions, dim_cartesian)
# test
#print(prior.sample(3))
# ics = split_into_ics_flow(prior.sample(1))
# #print(_ics)
# coordinate_transform.forward(*ics, inverse=True)[0].shape | _____no_output_____ | MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
Coupling LayersNext, we will set up so-called RealNVP coupling layers, which split the input into two channels and then learn affine transformations of channel 1 conditioned on channel 2. Here we will do the split naively between the first and second half of the degrees of freedom. | class RealNVP(bg.SequentialFlow):
def __init__(self, dim, hidden):
self.dim = dim
self.hidden = hidden
super().__init__(self._create_layers())
def _create_layers(self):
dim_channel1 = self.dim//2
dim_channel2 = self.dim - dim_channel1
split_into_2 = bg.... | _____no_output_____ | MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
Boltzmann GeneratorFinally, we define the Boltzmann generator.It will sample molecular conformations by 1. sampling in latent space from the normal prior distribution,2. transforming the samples into a more complication distribution through a number of RealNVP blocks (the parameters of these blocks will be subject to ... | n_realnvp_blocks = 5
layers = []
for i in range(n_realnvp_blocks):
layers.append(RealNVP(dim_ics, hidden=[128, 128, 128]))
layers.append(split_into_ics_flow)
layers.append(bg.InverseFlow(coordinate_transform))
flow = bg.SequentialFlow(layers).to(ctx)
# test
#flow.forward(prior.sample(3))[0].shape
flow.load_state_... | torch.Size([10000, 66])
| MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
bonds, angles, torsions, cartesian, dlogp = coordinate_transform.forward(samples)print(bonds.shape)print('1:', bonds[0])CHbond_indices = [0, 2, 3 ,7 ,8, 9 ,14 ,15 ,16]bonds_new = bonds.clone().detach()bonds_new[:,CHbond_indices] = 0.109print('2:', bonds_new[0:3])samples_corrected = coordinate_transform.forward(bonds_ne... | samplestrajectory = mdtraj.Trajectory(
xyz=samples[0].cpu().detach().numpy().reshape(-1, 22, 3),
topology=mdtraj.load('ala2_fromURL.pdb').topology
)
#samplestrajectory.save('mysamples_traj_correctedonce.dcd')
import nglview as nv
#samplestrajectory.save("Samplestraj.pdb")
#md.save... | _____no_output_____ | MIT | BGflow_examples/Alanine_dipeptide/ala2_use_saved_model.ipynb | michellab/bgflow |
LassoLars Regression with Robust Scaler This Code template is for the regression analysis using a simple LassoLars Regression. It is a lasso model implemented using the LARS algorithm and feature scaling using Robust Scaler in a Pipeline Required Packages | import warnings
import numpy as np
import pandas as pd
import seaborn as se
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import RobustScaler
from sklearn.metrics import r2_score, mean_absolute_erro... | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path= "" | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
List of features which are required for model training . | #x_values
features=[] | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Target feature for prediction. | #y_value
target='' | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path)
df.head() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | X=df[features]
Y=df[target] | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_dummies(df) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Calling preprocessing functions on the feature and target set. | x=X.columns.to_list()
for i in x:
X[i]=NullClearner(X[i])
X=EncodeX(X)
Y=NullClearner(Y)
X.head() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | f,ax = plt.subplots(figsize=(18, 18))
matrix = np.triu(X.corr())
se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
ModelLassoLars is a lasso model implemented using the LARS algorithm, and unlike the implementation based on coordinate descent, this yields the exact solution, which is piecewise linear as a function of the norm of its coefficients. Tuning parameters> **fit_intercept** -> whether to calculate the intercept for this m... | model=make_pipeline(RobustScaler(),LassoLars())
model.fit(x_train,y_train) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Model AccuracyWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.score: The score function returns the coefficient of determination R2 of the prediction. | print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) | Accuracy score 79.97 %
| Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. > **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) b... | y_pred=model.predict(x_test)
print("R2 Score: {:.2f} %".format(r2_score(y_test,y_pred)*100))
print("Mean Absolute Error {:.2f}".format(mean_absolute_error(y_test,y_pred)))
print("Mean Squared Error {:.2f}".format(mean_squared_error(y_test,y_pred))) | R2 Score: 79.97 %
Mean Absolute Error 4016.94
Mean Squared Error 30625388.66
| Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Prediction PlotFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. | plt.figure(figsize=(14,10))
plt.plot(range(20),y_test[0:20], color = "green")
plt.plot(range(20),model.predict(x_test[0:20]), color = "red")
plt.legend(["Actual","prediction"])
plt.title("Predicted vs True Value")
plt.xlabel("Record number")
plt.ylabel(target)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_RobustScaler.ipynb | shreepad-nade/ds-seed |
Wczytanie danych | df = pd.read_hdf("../data/car.h5")
df.sample()
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_valu... | _____no_output_____ | MIT | matrix_two/matrix2_day5_hyperopt.ipynb | AardJan/dw_matrix |
XGBoost | xgb_params = {
'max_depth':5,
'n_estimatords':50,
'learning_rate':0.1,
'seed':0,
'nthread': 3
}
model = xgb.XGBRegressor(**xgb_params)
run_model(model, feats)
def obj_func(params):
print("Traniang with params: ")
print(params)
mean_mae, score_std = run_model(xgb.XGBRegressor(**p... | Traniang with params:
{'colsample_bytree': 0.6000000000000001, 'learning_rate': 0.3, 'max_depth': 5, 'n_estimatords': 100, 'nthread': 4, 'objective': 'reg:squarederror', 'seed': 0, 'subsample': 0.9}
Traniang with params:
{'colsample_bytree': 0.5, 'learning_rate': 0.2, 'max_depth': 9, 'n_estimatords': 100, 'nthread': ... | MIT | matrix_two/matrix2_day5_hyperopt.ipynb | AardJan/dw_matrix |
Cross Validation | value_array = []
error_array = []
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
for train_index, test_index in skf.split(X, Y):
print("TRAIN:", train_index, "TEST:", test_index)
xTrain, xTest = X[train_index], X[test_index]
yTrain, yTest ... | _____no_output_____ | CC-BY-4.0 | FuzzyKNN/Esperimenti su FKNN.ipynb | ritafolisi/Tirocinio |
Model Selection & Cross Validation | a = np.arange (1, 21, 2)
parameters = {"k" : a}
parameters["k"]
from sklearn.model_selection import GridSearchCV
clf = GridSearchCV(model, parameters, cv = 5)
clf.fit(xTrain, yTrain)
clf.score(xTest, yTest)
best_params = clf.best_params_
best_params
model = clf.best_estimator_
def MSE_membership(self, X, y):
memb, ... | _____no_output_____ | CC-BY-4.0 | FuzzyKNN/Esperimenti su FKNN.ipynb | ritafolisi/Tirocinio |
Import libraries and define const values | import json
import folium
from geopandas import GeoDataFrame
from pysal.viz.mapclassify import Natural_Breaks
import requests
id_field = 'id'
value_field = 'score'
num_bins = 4
fill_color = 'YlOrRd'
fill_opacity = 0.9
REST_API_ADDRESS= 'http://10.90.46.32:4646/'
Alive_URL = REST_API_ADDRESS + 'alive'
BRS_URL = REST_AP... | _____no_output_____ | Apache-2.0 | executable/REST_example.ipynb | smartdatalake/best_region_search |
Identify the areas where start-ups thrive | topk = 11 #
eps = 0.1 # We measure distance in radians, where 1 radian is around 100km, and epsilon is the length of each side of the region
f = "null" #
dist = True
keywordsColumn = "flags"
keywords = "startup-registroimprese"
keywordsColumn2 = ""
keywords2 = ""
table = "BRSflags"
data = {'topk' : topk, 'eps' : eps,... | [
{
"rank":1,
"center":[9.191005,45.47981],
"score":77.0
}
,{
"rank":2,
"center":[12.50779,41.873835],
"score":35.0
}
,{
"rank":3,
"center":[7.661105,45.064135],
"score":16.0
}
,{
"rank":4,
"center":[14.238015,40.869564999999994],
"score":12.0
}
,{
"rank":5,
"center":[11.382850000000001,44.483135],
"score":9.0
}
,{
"ra... | Apache-2.0 | executable/REST_example.ipynb | smartdatalake/best_region_search |
Initialize the map and visualize the output regions | m = folium.Map(
location=[45.474989560000004,9.205786594999998],
tiles='Stamen Toner',
zoom_start=11
)
gdf = GeoDataFrame.from_features(results_geojson['features'])
gdf.crs = {'init': 'epsg:4326'}
gdf['geometry'] = gdf.buffer(data['eps']/2).envelope
threshold_scale = Natural_Breaks(gdf[value_field], k=num_b... | _____no_output_____ | Apache-2.0 | executable/REST_example.ipynb | smartdatalake/best_region_search |
Analyze A/B Test ResultsYou may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your code passes the project [RUBRIC](https://review.udacity.com/!/projects/37e27304-ad47-4eb0-a1ab-8c12f60e43d0/rubric). **Please s... | import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
%matplotlib inline
#We are setting the seed to assure you get the same answers on quizzes as we set up
random.seed(42) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
`1.` Now, read in the `ab_data.csv` data. Store it in `df`. **Use your dataframe to answer the questions in Quiz 1 of the classroom.**a. Read in the dataset and take a look at the top few rows here: | #import the dataset
df = pd.read_csv('ab_data.csv')
#show the first 5 rows
df.head() | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
b. Use the cell below to find the number of rows in the dataset. | #show the total number of rows
df.shape[0] | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
c. The number of unique users in the dataset. | #calculare the number of unique user_id
len(df['user_id'].unique()) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
d. The proportion of users converted. | #calculate the converted users
df['converted'].mean() | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
e. The number of times the `new_page` and `treatment` don't match. | #treatment in group will be called A and new_page in landing_page will be called B
df_A_not_B = df.query('group == "treatment" & landing_page != "new_page"')
df_B_not_A = df.query('group != "treatment" & landing_page == "new_page"')
#calculate thenumber of time new_page and treatment don't line up
len(df_A_not_B) + ... | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
f. Do any of the rows have missing values? | #view if there is any missing value
df.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 294478 entries, 0 to 294477
Data columns (total 5 columns):
user_id 294478 non-null int64
timestamp 294478 non-null object
group 294478 non-null object
landing_page 294478 non-null object
converted 294478 non-null int64
dtypes: int64(2),... | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
**No missing Values** `2.` For the rows where **treatment** does not match with **new_page** or **control** does not match with **old_page**, we cannot be sure if this row truly received the new or old page. Use **Quiz 2** in the classroom to figure out how we should handle these rows. a. Now use the answer to the qu... | #remove the mismatch rows
df1 = df.drop(df[(df.group == "treatment") & (df.landing_page != "new_page")].index)
df2 = df1.drop(df1[(df1.group == "control") & (df1.landing_page != "old_page")].index)
# Double Check all of the correct rows were removed - this should be 0
df2[((df2['group'] == 'treatment') == (df2['landin... | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
`3.` Use **df2** and the cells below to answer questions for **Quiz3** in the classroom. a. How many unique **user_id**s are in **df2**? | #calculare the number of unique user_id
len(df2['user_id'].unique()) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
b. There is one **user_id** repeated in **df2**. What is it? | #find out the duplicate user_id
df2.loc[df2.user_id.duplicated()] | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
c. What is the row information for the repeat **user_id**? | #find out the duplicate user_id
df2.loc[df2.user_id.duplicated()] | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
d. Remove **one** of the rows with a duplicate **user_id**, but keep your dataframe as **df2**. | # Now we remove duplicate rows
df2 = df2.drop_duplicates()
# Check agin if duplicated values are deleted or not
sum(df2.duplicated()) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
`4.` Use **df2** in the cells below to answer the quiz questions related to **Quiz 4** in the classroom.a. What is the probability of an individual converting regardless of the page they receive? | # Probability of an individual converting regardless of the page they receive
df2['converted'].mean() | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
b. Given that an individual was in the `control` group, what is the probability they converted? | # The probability of an individual converting given that an individual was in the control group
control_group = len(df2.query('group=="control" and converted==1'))/len(df2.query('group=="control"'))
control_group | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
c. Given that an individual was in the `treatment` group, what is the probability they converted? | # The probability of an individual converting given that an individual was in the treatment group
treatment_group = len(df2.query('group=="treatment" and converted==1'))/len(df2.query('group=="treatment"'))
treatment_group | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
d. What is the probability that an individual received the new page? | # The probability of individual received new page
len(df2.query('landing_page=="new_page"'))/len(df2.index) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
e. Consider your results from parts (a) through (d) above, and explain below whether you think there is sufficient evidence to conclude that the new treatment page leads to more conversions. **Your answer goes here.** Part II - A/B TestNotice that because of the time stamp associated with each event, you could technic... | p_new = len(df2.query( 'converted==1'))/len(df2.index)
p_new | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
b. What is the **conversion rate** for $p_{old}$ under the null? | p_old = len(df2.query('converted==1'))/len(df2.index)
p_old
p_new = len(df2.query( 'converted==1'))/len(df2.index)
p_new
# probablity under null
p=np.mean([p_old,p_new])
p
# difference of p_new and p_old
p_diff=p_new-p_old | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
Under null p_old is equal to p_new c. What is $n_{new}$, the number of individuals in the treatment group? | #calculate number of queries when landing_page is equal to new_page
n_new = len(df2.query('landing_page=="new_page"'))
#print n_new
n_new | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
d. What is $n_{old}$, the number of individuals in the control group? | #calculate number of queries when landing_page is equal to old_page
n_old = len(df2.query('landing_page=="old_page"'))
#print n_old
n_old | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
e. Simulate $n_{new}$ transactions with a conversion rate of $p_{new}$ under the null. Store these $n_{new}$ 1's and 0's in **new_page_converted**. | ## simulate n_old transactions with a convert rate of p_new under the null
new_page_converted = np.random.choice([0, 1], n_new, p = [p_new, 1-p_new]) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
f. Simulate $n_{old}$ transactions with a conversion rate of $p_{old}$ under the null. Store these $n_{old}$ 1's and 0's in **old_page_converted**. | # simulate n_old transactions with a convert rate of p_old under the null
old_page_converted = np.random.choice([0, 1], n_old, p = [p_old, 1-p_old]) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
g. Find $p_{new}$ - $p_{old}$ for your simulated values from part (e) and (f). | # differences computed in from p_new and p_old
obs_diff= new_page_converted.mean() - old_page_converted.mean()# differences computed in from p_new and p_old
obs_diff | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
h. Create 10,000 $p_{new}$ - $p_{old}$ values using the same simulation process you used in parts (a) through (g) above. Store all 10,000 values in a NumPy array called **p_diffs**. | # Create sampling distribution for difference in p_new-p_old simulated values
# with boostrapping
p_diffs = []
for i in range(10000):
# 1st parameter dictates the choices you want. In this case [1, 0]
p_new1 = np.random.choice([1, 0],n_new,replace = True,p = [p_new, 1-p_new])
p_old1 = np.random.choice... | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
i. Plot a histogram of the **p_diffs**. Does this plot look like what you expected? Use the matching problem in the classroom to assure you fully understand what was computed here. | p_diffs=np.array(p_diffs)
#histogram of p_diff
plt.hist(p_diffs)
plt.title('Graph of p_diffs')#title of graphs
plt.xlabel('Page difference') # x-label of graphs
plt.ylabel('Count') # y-label of graphs | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
j. What proportion of the **p_diffs** are greater than the actual difference observed in **ab_data.csv**? | #histogram of p_diff
plt.hist(p_diffs);
plt.title('Graph of p_diffs') #title of graphs
plt.xlabel('Page difference') # x-label of graphs
plt.ylabel('Count') # y-label of graphs
plt.axvline(x= obs_diff, color='r'); | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
k. Please explain using the vocabulary you've learned in this course what you just computed in part **j.** What is this value called in scientific studies? What does this value mean in terms of whether or not there is a difference between the new and old pages? 89.57% is the proportion of the p_diffs that are greater... | import statsmodels.api as sm
convert_old = len(df2.query('converted==1 and landing_page=="old_page"')) #rows converted with old_page
convert_new = len(df2.query('converted==1 and landing_page=="new_page"')) #rows converted with new_page
n_old = len(df2.query('landing_page=="old_page"')) #rows_associated with old_page
... | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
m. Now use `stats.proportions_ztest` to compute your test statistic and p-value. [Here](https://docs.w3cub.com/statsmodels/generated/statsmodels.stats.proportion.proportions_ztest/) is a helpful link on using the built in. | #Computing z_score and p_value
z_score, p_value = sm.stats.proportions_ztest([convert_old,convert_new], [n_old, n_new],alternative='smaller')
#display z_score and p_value
print(z_score,p_value) | 1.31160753391 0.905173705141
| FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
n. What do the z-score and p-value you computed in the previous question mean for the conversion rates of the old and new pages? Do they agree with the findings in parts **j.** and **k.**? | from scipy.stats import norm
norm.cdf(z_score) #how significant our z_score is
norm.ppf(1-(0.05)) #critical value of 95% confidence | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
The z-score and the p_value mean that one doesn't reject the Null. The Null being the converted rate of the old_page is the same or greater than the converted rate of the new_page. The p_value is 0.91 and is higher than 0.05 significance level. That means we can not be confident with a 95% confidence level that the con... | #adding an intercept column
df2['intercept'] = 1
#Create dummy variable column
df2['ab_page'] = pd.get_dummies(df2['group'])['treatment']
df2.head() | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
c. Use **statsmodels** to instantiate your regression model on the two columns you created in part b., then fit the model using the two columns you created in part **b.** to predict whether or not an individual converts. | import statsmodels.api as sm
model=sm.Logit(df2['converted'],df2[['intercept','ab_page']])
results=model.fit() | Optimization terminated successfully.
Current function value: 0.366118
Iterations 6
| FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
d. Provide the summary of your model below, and use it as necessary to answer the following questions. |
results.summary()
| _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
e. What is the p-value associated with **ab_page**? Why does it differ from the value you found in **Part II**? **Hint**: What are the null and alternative hypotheses associated with your regression model, and how do they compare to the null and alternative hypotheses in **Part II**? The p-value associated with ab_pag... | # Store Countries.csv data in dataframe
countries = pd.read_csv('countries.csv')
countries.head()
#Inner join two datas
new = countries.set_index('user_id').join(df2.set_index('user_id'), how = 'inner')
new.head()
#adding dummy variables with 'CA' as the baseline
new[['US', 'UK']] = pd.get_dummies(new['country'])[['US... | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
h. Though you have now looked at the individual factors of country and page on conversion, we would now like to look at an interaction between page and country to see if there significant effects on conversion. Create the necessary additional columns, and fit the new model. Provide the summary results, and your concl... | from subprocess import call
call(['python', '-m', 'nbconvert', 'Analyze_ab_test_results_notebook.ipynb']) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
Finishing Up> Congratulations! You have reached the end of the A/B Test Results project! You should be very proud of all you have accomplished!> **Tip**: Once you are satisfied with your work here, check over your report to make sure that it is satisfies all the areas of the rubric (found on the project submission p... | from subprocess import call
call(['python', '-m', 'nbconvert', 'Analyze_ab_test_results_notebook.ipynb']) | _____no_output_____ | FTL | Analyze-A-B-Results-masterAnalyze_ab_test_results_notebook.ipynb | DishaMukherjee/Analyze-A-B-Results |
2章 微分積分 2.1 関数 | # 必要ライブラリの宣言
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# PDF出力用
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')
def f(x):
return x**2 +1
f(1)
f(2) | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
図2-2 点(x, f(x))のプロットとy=f(x)のグラフ | x = np.linspace(-3, 3, 601)
y = f(x)
x1 = np.linspace(-3, 3, 7)
y1 = f(x1)
plt.figure(figsize=(6,6))
plt.ylim(-2,10)
plt.plot([-3,3],[0,0],c='k')
plt.plot([0,0],[-2,10],c='k')
plt.scatter(x1,y1,c='k',s=50)
plt.grid()
plt.xlabel('x',fontsize=14)
plt.ylabel('y',fontsize=14)
plt.show()
x2 = np.linspace(-3, 3, 31)
y2 = f(x... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
2.2 合成関数・逆関数 図2.6 逆関数のグラフ | def f(x):
return(x**2 + 1)
def g(x):
return(np.sqrt(x - 1))
xx1 = np.linspace(0.0, 4.0, 200)
xx2 = np.linspace(1.0, 4.0, 200)
yy1 = f(xx1)
yy2 = g(xx2)
plt.figure(figsize=(6,6))
plt.xlabel('$x$',fontsize=14)
plt.ylabel('$y$',fontsize=14)
plt.ylim(-2.0, 4.0)
plt.xlim(-2.0, 4.0)
plt.grid()
plt.plot(xx1,yy1, lines... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
2.3 微分と極限 図2-7 関数のグラフを拡大したときの様子 | from matplotlib import pyplot as plt
import numpy as np
def f(x):
return(x**3 - x)
delta = 2.0
x = np.linspace(0.5-delta, 0.5+delta, 200)
y = f(x)
fig = plt.figure(figsize=(6,6))
plt.ylim(-3.0/8.0-delta, -3.0/8.0+delta)
plt.xlim(0.5-delta, 0.5+delta)
plt.plot(x, y, 'b-', lw=1, c='k')
plt.scatter([0.5], [-3.0/8.0])
... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
図2-8 関数のグラフ上の2点を結んだ直線の傾き | delta = 2.0
x = np.linspace(0.5-delta, 0.5+delta, 200)
x1 = 0.6
x2 = 1.0
y = f(x)
fig = plt.figure(figsize=(6,6))
plt.ylim(-1, 0.5)
plt.xlim(0, 1.5)
plt.plot(x, y, 'b-', lw=1, c='k')
plt.scatter([x1, x2], [f(x1), f(x2)], c='k', lw=1)
plt.plot([x1, x2], [f(x1), f(x2)], c='k', lw=1)
plt.plot([x1, x2, x2], [f(x1), f(x1), ... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
図2-10 接線の方程式 | def f(x):
return(x**2 - 4*x)
def g(x):
return(-2*x -1)
x = np.linspace(-2, 6, 500)
fig = plt.figure(figsize=(6,6))
plt.scatter([1],[-3],c='k')
plt.plot(x, f(x), 'b-', lw=1, c='k')
plt.plot(x, g(x), 'b-', lw=1, c='b')
plt.plot([x.min(), x.max()], [0, 0], lw=2, c='k')
plt.plot([0, 0], [g(x).min(), f(x).max()], lw... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
2.4 極大・極小 図2-11 y= x3-3xのグラフと極大・極小 | def f1(x):
return(x**3 - 3*x)
x = np.linspace(-3, 3, 500)
y = f1(x)
fig = plt.figure(figsize=(6,6))
plt.ylim(-4, 4)
plt.xlim(-3, 3)
plt.plot(x, y, 'b-', lw=1, c='k')
plt.plot([0,0],[-4,4],c='k')
plt.plot([-3,3],[0,0],c='k')
plt.grid()
plt.show() | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
図2-12 極大でも極小でもない例 (y=x3のグラフ) | def f2(x):
return(x**3)
x = np.linspace(-3, 3, 500)
y = f2(x)
fig = plt.figure(figsize=(6,6))
plt.ylim(-4, 4)
plt.xlim(-3, 3)
plt.plot(x, y, 'b-', lw=1, c='k')
plt.plot([0,0],[-4,4],c='k')
plt.plot([-3,3],[0,0],c='k')
plt.grid()
plt.show() | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
2.7 合成関数の微分 図2-14 逆関数の微分 | #逆関数の微分
def f(x):
return(x**2 + 1)
def g(x):
return(np.sqrt(x - 1))
xx1 = np.linspace(0.0, 4.0, 200)
xx2 = np.linspace(1.0, 4.0, 200)
yy1 = f(xx1)
yy2 = g(xx2)
plt.figure(figsize=(6,6))
plt.xlabel('$x$',fontsize=14)
plt.ylabel('$y$',fontsize=14)
plt.ylim(-2.0, 4.0)
plt.xlim(-2.0, 4.0)
plt.grid()
plt.plot(xx1,yy... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
2.9 積分 図2-15 面積を表す関数S(x)とf(x)の関係 | def f(x) :
return x**2 + 1
xx = np.linspace(-4.0, 4.0, 200)
yy = f(xx)
plt.figure(figsize=(6,6))
plt.xlim(-2,2)
plt.ylim(-1,4)
plt.plot(xx, yy)
plt.plot([-2,2],[0,0],c='k',lw=1)
plt.plot([0,0],[-1,4],c='k',lw=1)
plt.plot([0,0],[0,f(0)],c='b')
plt.plot([1,1],[0,f(1)],c='b')
plt.plot([1.5,1.5],[0,f(1.5)],c='b')
plt.p... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
図2-16 グラフの面積と定積分 | plt.figure(figsize=(6,6))
plt.xlim(-2,2)
plt.ylim(-1,4)
plt.plot(xx, yy)
plt.plot([-2,2],[0,0],c='k',lw=1)
plt.plot([0,0],[-1,4],c='k',lw=1)
plt.plot([0,0],[0,f(0)],c='b')
plt.plot([1,1],[0,f(1)],c='b')
plt.plot([1.5,1.5],[0,f(1.5)],c='b')
plt.tick_params(labelbottom=False, labelleft=False, labelright=False, labeltop=F... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
図2-17 積分と面積の関係 | def f(x) :
return x**2 + 1
x = np.linspace(-1.0, 2.0, 200)
y = f(x)
N = 10
xx = np.linspace(0.5, 1.5, N+1)
yy = f(xx)
print(xx)
plt.figure(figsize=(6,6))
plt.xlim(-1,2)
plt.ylim(-1,4)
plt.plot(x, y)
plt.plot([-1,2],[0,0],c='k',lw=2)
plt.plot([0,0],[-1,4],c='k',lw=2)
plt.plot([0.5,0.5],[0,f(0.5)],c='b')
plt.plot([1.... | _____no_output_____ | Apache-2.0 | notebooks/ch02-diff.ipynb | evilboy1973/math_dl_book_info |
VacationPy---- Note* Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing.* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps... | # Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import gmaps
import os
# Import API key
from api_keys import g_key
# Configure gmaps
gmaps.configure(api_key=gkey)
print(gkey) | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | kdturner83/PythonAPI_Challenge |
Store Part I results into DataFrame* Load the csv exported in Part I to a DataFrame | # Create vacation dataframe
#clean_city_data_df.to_csv('../Resources/city_output.csv')
vacation_df = pd.read_csv('../Resources/city_output.csv')
#vacation_df = vacation_df.drop(columns="Unnamed: 0")
vacation_df.head() | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | kdturner83/PythonAPI_Challenge |
Humidity Heatmap* Configure gmaps.* Use the Lat and Lng as locations and Humidity as the weight.* Add Heatmap layer to map. | # Store latitude and longitude in locations
locations = vacation_df[["lat", "long"]]
weights = vacation_df["humidity"].astype(float)
fig = gmaps.figure()
# Create heat layer
heat_layer = gmaps.heatmap_layer(locations, weights=weights,
dissipating=False, max_intensity=10,
... | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | kdturner83/PythonAPI_Challenge |
Create new DataFrame fitting weather criteria* Narrow down the cities to fit weather conditions.* Drop any rows will null values. | #vacation_df.dropna(inplace = True) max temp, cloudiness = 0, wind speed <10, 70> <80
city_weather_df = vacation_df.copy()
city_weather_df.dropna(inplace = True)
city_weather_df | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | kdturner83/PythonAPI_Challenge |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.