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
Module Project: Ridge RegressionFor this project, you'll return to the Tribecca Condo dataset. But this time, you'll look at the _entire_ dataset and try to predict property sale prices.The [NYC Department of Finance](https://www1.nyc.gov/site/finance/taxes/property-rolling-sales-data.page) has a glossary of property ...
def wrangle(filepath): # Import csv file cols = ['BOROUGH', 'NEIGHBORHOOD', 'BUILDING CLASS CATEGORY', 'GROSS SQUARE FEET', 'YEAR BUILT', 'SALE PRICE', 'SALE DATE'] df = pd.read_csv(filepath, usecols=cols) return df filepath = DATA_PATH+'condos/NYC_Citywide_Rolling_Calendar_Sa...
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
**Task 1:** Use the above `wrangle` function to import the `NYC_Citywide_Rolling_Calendar_Sales.csv` file into a DataFrame named `df`.
df = ...
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
**Task 2:** Modify the above `wrangle` function so that:- The column `'SALE DATE'` becomes the `DatetimeIndex`.- The dtype for the `'BOROUGH'` column is `object`, not `int`.- The dtype for the `'SALE PRICE'` column is `int`, not `object`.- The dataset includes only one-family dwellings (`BUILDING CLASS CATEGORY == '01 ...
# Perform your exploratory data analysis here and # modify the wrangle function above
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
II. Split Data**Task 3:** Split your dataset into the feature matrix `X` and the target vector `y`. You want to predict `'SALE_PRICE'`.
X = ... y = ...
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
**Task 4:** Split `X` and `y` into a training set (`X_train`, `y_train`) and a test set (`X_test`, `y_test`).- Your training set should include data from January to March 2019. - Your test set should include data from April 2019.
X_train, y_train = ..., ... X_test, y_test = ..., ...
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
III. Establish Baseline**Task 5:** Since this is a **regression** problem, you need to calculate the baseline mean absolute error for your model.
baseline_mae = ... print('Baseline MAE:', baseline_mae)
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
IV. Build Model **Task 6:** Build and train a `OneHotEncoder` and then use it to transform `X_train` and `X_test`.
ohe = ... XT_train = ... XT_test = ...
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
**Task 7:** Build and train a `LinearRegression` model named `model_lr`. Remember to train your model using your _transformed_ feature matrix.
model_lr = ...
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
**Task 8:** Build and train a `Ridge` model named `model_r`. Remember to train your model using your _transformed_ feature matrix.
model_r = ...
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
V. Check Metrics**Task 9:** Check the training and test metrics for `model_lr`.
training_mae_lr = ... test_mae_lr = ... print('Linear Training MAE:', training_mae_lr) print('Linear Test MAE:', test_mae_lr)
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
**Task 10:** Check the training and test metrics for `model_r`.
training_mae_r = ... test_mae_r = ... print('Ridge Training MAE:', training_mae_r) print('Ridge Test MAE:', test_mae_r)
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
**Stretch Goal:** Calculate the training and test $R^2$ scores `model_r`.
# Caculate R^2 score
_____no_output_____
MIT
module3-ridge-regression/LS_DS_213_assignment.ipynb
ppmorgoun/DS-Unit-2-Linear-Models
Simple ARIMAX This code template is for Time Series Analysis and Forecasting to make scientific predictions based on historical time stamped data with the help of ARIMAX algorithm Required Packages
import warnings import numpy as np import pandas as pd import seaborn as se import matplotlib.pyplot as plt from statsmodels.tsa.stattools import adfuller from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.statespace.sarimax import SARIMAX from sklearn.metrics import mean_abs...
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
InitializationFilepath of CSV file
file_path = ""
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Variable containing the date time column name of the Time Series data
date = ""
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Target feature for prediction.
target = ""
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.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
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Data PreprocessingSince the majority of the machine learning models for Time Series Forecasting doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippets have functions, which removes the rows containing null value if any exists. And convert the string ...
def data_preprocess(df, target, date): df = df.dropna(axis=0, how = 'any') df[date] = pd.to_datetime(df[date]) df = df.set_index(date) return df df = data_preprocess(df,target,date) df.head() df.plot(figsize = (15,8)) plt.show()
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Seasonality decomposition Since Simple ARIMAX for non-seasonal data, we need to check for any seasonality in our time series and decompose it.We use the Dickey Fuller Test for testing the seasonality and if the ADF Statistic value is positive, it means that the data has seasonality. Dickey Fuller TestThe Dickey Fuller...
def dickeyFuller(df,target): # Applying Dickey Fuller Test X = df.values result = adfuller(X) print('ADF Statistic: %f' % result[0]) print('p-value: %f' % result[1]) print('Number of lags used: %d' % result[2]) print('Critical Values:') for key, value in result[4].items(): ...
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
To remove the seasonality we use the rolling mean technique for smoothing our data and decomposing any seasonality.This method provides rolling windows over the data. On the resulting windows, we can perform calculations using a statistical function (in this case the mean) in order to decompose the seasonality.For more...
df = dickeyFuller(df,target)
ADF Statistic: -2.256990 p-value: 0.186215 Number of lags used: 15 Critical Values: 1%: -3.448 5%: -2.869 10%: -2.571
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Autocorrelation PlotWe can calculate the correlation for time series observations with observations with previous time steps, called lags. Because the correlation of the time series observations is calculated with values of the same series at previous times, this is called a serial correlation, or an autocorrelation.A...
x = plot_acf(df, lags=40) x.set_size_inches(15, 10, forward=True) plt.show()
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Partial Autocorrelation PlotA partial autocorrelation is a summary of the relationship between an observation in a time series with observations at prior time steps with the relationships of intervening observations removed.The partial autocorrelation at lag k is the correlation that results after removing the effect ...
y = plot_pacf(df, lags=40) y.set_size_inches(15, 10, forward=True) plt.show()
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Data SplittingSince we are using a univariate dataset, we can directly split our data into training and testing 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 the model on new data.
size = int(len(df)*0.9) df_train, df_test = df.iloc[:size], df.iloc[size:]
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
ModelThe ARIMAX model is an extended version of the ARIMA model. It includes also other independent (predictor) variables. The model is also referred to as the vector ARIMA or the dynamic regression model.The ARIMAX model is similar to a multivariate regression model, but allows to take advantage of autocorrelation th...
model=SARIMAX(df[target],order=(1, 0, 0),seasonal_order=(0,0,0,0)) result=model.fit()
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Model SummaryAfter fitting the training data into our ARIMAX and training it, we can take a look at a brief summary of our model by using the **summary()** function. The followings aspects are included in our model summary:1. Basic Model Details: The first column of our summary table contains the basic details regardi...
result.summary()
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Simple Forecasting
df_train.tail()
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
PredictionsBy specifying the start and end time for our predictions, we can easily predict the future points in our time series with the help of our model.
d = df.drop([target], axis = 1) start_date = d.iloc[size].name end_date = d.iloc[len(df)-1].name df_pred = result.predict(start = start_date, end = end_date) df_pred.head()
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Model AccuracyWe will use the three most popular metrics for model evaluation: Mean absolute error (MAE), Mean squared error (MSE), or Root mean squared error (RMSE).
test = df_test[target] print("Mean Absolute Error {:.2f}".format(mean_absolute_error(test,df_pred))) print("Mean Squared Error {:.2f}".format(mean_squared_error(test,df_pred))) print("Root Mean Squared Error {:.2f}".format(np.sqrt(mean_squared_error(test,df_pred))))
Mean Absolute Error 8.61 Mean Squared Error 98.90 Root Mean Squared Error 9.94
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
Predictions PlotFirst we make use of plot to plot the predicted values returned by our model based on the test data.After that we plot the actual test data to compare our predictions.
plt.figure(figsize=(18,5)) plt.plot(df_pred[start_date:end_date], color = "red") plt.plot(df_test, color = "blue") plt.title("Predictions vs Actual", size = 24) plt.plot(fontsize="x-large") plt.show()
_____no_output_____
Apache-2.0
Time Series Analysis/Time Series Forecasting/ARIMAX.ipynb
shreepad-nade/ds-seed
STARmap processing exampleThis notebook demonstrates the processing of STARmap data using starfish. Thedata we present here is a subset of the data used in this[publication](https://doi.org/10.1126/science.aat5691) and was generously provided to us by the authors.
from pprint import pprint import matplotlib import matplotlib.pyplot as plt import numpy as np import starfish import starfish.data from starfish.types import Axes from starfish.util.plot import ( diagnose_registration, imshow_plane, intensity_histogram ) matplotlib.rcParams["figure.dpi"] = 150
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
Visualize raw dataIn this starmap experiment, starfish exposes a test dataset containing asingle field of view. This dataset contains 672 images spanning 6 rounds`(r)`, 4 channels `(ch)`, and 28 z-planes `(z)`. Each imageis `1024x1024 (y, x)`To examine this data, the vignette displays the max projection of channels an...
experiment = starfish.data.STARmap(use_test_data=True) stack = experiment['fov_000'].get_image('primary') ch_r_projection = stack.max_proj(Axes.CH, Axes.ROUND) f = plt.figure(dpi=150) imshow_plane(ch_r_projection, sel={Axes.ZPLANE: 15})
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
Visualize the codebook----------------------The STARmap codebook maps pixel intensities across the rounds and channels tothe corresponding barcodes and genes that those pixels code for. For thisdataset, the codebook specifies 160 gene targets.
print(experiment.codebook)
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
RegistrationStarfish exposes some simple tooling to identify registration shifts.`starfish.util.plot.diagnose_registration` takes an ImageStack and aset of selectors, each of which maps `Axes` objectsto indices that specify a particular 2d image.Below the vignette projects the channels and z-planes and examines thereg...
projection = stack.max_proj(Axes.CH, Axes.ZPLANE) reference_image = projection.sel({Axes.ROUND: 1}) ltt = starfish.image.LearnTransform.Translation( reference_stack=reference_image, axes=Axes.ROUND, upsampling=1000, ) transforms = ltt.run(projection)
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
How big are the identified translations?
pprint([t[2].translation for t in transforms.transforms])
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
Apply the translations
warp = starfish.image.ApplyTransform.Warp() stack = warp.run( stack=stack, transforms_list=transforms, )
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
Show the effect of registration.
post_projection = stack.max_proj(Axes.CH, Axes.ZPLANE) f, (ax1, ax2) = plt.subplots(ncols=2) sel_0 = {Axes.ROUND: 0, Axes.X: (500, 600), Axes.Y: (500, 600)} sel_1 = {Axes.ROUND: 1, Axes.X: (500, 600), Axes.Y: (500, 600)} diagnose_registration( projection, sel_0, sel_1, ax=ax1, title='pre-registered' ) diagnose_regi...
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
The plot shows that the slight offset has been corrected.Equalize channel intensities----------------------------The second stage of the STARmap pipeline is to align the intensitydistributions across channels and rounds. Here we calculate a referencedistribution by sorting each image's intensities in increasing order a...
mh = starfish.image.Filter.MatchHistograms({Axes.CH, Axes.ROUND}) scaled = mh.run(stack, in_place=False, verbose=True, n_processes=8) def plot_scaling_result( template: starfish.ImageStack, scaled: starfish.ImageStack ): f, (before, after) = plt.subplots(ncols=4, nrows=2) for channel, ax in enumerate(before...
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
Find spots----------Finally, a local blob detector that finds spots in each (z, y, x) volumeseparately is applied. The user selects an "anchor round" and spots found inall channels of that round are used to seed a local search across other roundsand channels. The closest spot is selected, and any spots outside the sear...
lsbd = starfish.spots.DetectSpots.LocalSearchBlobDetector( min_sigma=1, max_sigma=8, num_sigma=10, threshold=np.percentile(np.ravel(stack.xarray.values), 95), exclude_border=2, anchor_round=0, search_radius=10, ) intensities = lsbd.run(scaled, n_processes=8)
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
Decode spots------------Next, spots are decoded. There is really no good way to display 3-d spotdetection in 2-d planes, so we encourage you to grab this notebook anduncomment the below lines.
decoded = experiment.codebook.decode_per_round_max(intensities.fillna(0)) decode_mask = decoded['target'] != 'nan' # %gui qt # viewer = starfish.display( # stack, decoded[decode_mask], radius_multiplier=2, mask_intensities=0.1 # )
_____no_output_____
MIT
notebooks/STARmap.ipynb
kne42/starfish
Using the Object-Oriented Interface
import coronagraph as cg print(cg.__version__) noise = cg.CoronagraphNoise(THERMAL=True) lamhr, Ahr, fstar = cg.get_earth_reflect_spectrum() noise.run_count_rates(Ahr, lamhr, fstar) noise.make_fake_data(texp = 10) fig, ax = noise.plot_spectrum() fig, ax = noise.plot_SNR() fig, ax = noise.plot_time_to_wantsnr()
_____no_output_____
MIT
docs/notebooks/interface_example.ipynb
jlustigy/coronagraph
Plotting with matplotlib Setup
%matplotlib inline import numpy as np import pandas as pd pd.set_option('display.max_columns', 10) pd.set_option('display.max_rows', 10)
_____no_output_____
MIT
pandas/Demos/plotting.ipynb
WebucatorTraining/classfiles-actionable-python
Getting the pop2019 DataFrame
csv ='../csvs/nc-est2019-agesex-res.csv' pops = pd.read_csv(csv, usecols=['SEX', 'AGE', 'POPESTIMATE2019']) def fix_sex(sex): if sex == 0: return 'T' elif sex == 1: return 'M' else: # 2 return 'F' pops.SEX = pops.SEX.apply(fix_sex) pops = pops.pivot(index='AGE', columns='SEX',...
_____no_output_____
MIT
pandas/Demos/plotting.ipynb
WebucatorTraining/classfiles-actionable-python
Create a Line Plot
# Create the plot. plt_pop = pops.plot( title = "Population by Age: 2019", style=['b--', 'm^', 'k-'], figsize=(12, 6), lw=2 ) # Include gridlines. plt_pop.grid(True) # Set the x and y labels. plt_pop.set_xlabel('Age') plt_pop.set_ylabel('Population') # Create the legend. plt_pop.legend(['M', 'F', 'A'...
_____no_output_____
MIT
pandas/Demos/plotting.ipynb
WebucatorTraining/classfiles-actionable-python
Create a Bar Plot
csv ='../csvs/mantle.csv' mantle = pd.read_csv(csv, index_col='Year', usecols=['Year', '2B', '3B', 'HR']) mantle # Create the plot. plt_mantle = mantle.plot( kind='bar', title = 'Mickey Mantle: Doubles, Triples, and Home Runs', figsize=(12, 6), width=.8, fontsize=16 ) # Include...
_____no_output_____
MIT
pandas/Demos/plotting.ipynb
WebucatorTraining/classfiles-actionable-python
Activation function is an identity function. It is trivial. Many activation functions. Out of them, these are famous -1. Sigmoid - range: [0, 1]2. Tanh - range: [-1, 1] - zero centered, prefered in hidden layers over (1)3. ReLUDue to vanishing gradient problem, Sigmoid and Tanh functions are being avoided. But to unde...
import numpy as np def sigmoid(z): return 1 / (1 + np.exp(-z)) sigmoid(-2)
_____no_output_____
MIT
Activation_Functions.ipynb
hemanthsunny/machine_learning
Tanh
import numpy as np def tanh(z): return np.tanh(z) def tanh2(z): return (np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z)) print("Tanh :", tanh(-2)) print("Tanh2 :", tanh2(-2))
Tanh : -0.9640275800758169 Tanh2 : -0.964027580075817
MIT
Activation_Functions.ipynb
hemanthsunny/machine_learning
ReLU
import numpy as np def relu(z): return z*(z>0) relu(10)
_____no_output_____
MIT
Activation_Functions.ipynb
hemanthsunny/machine_learning
Leaky ReLU
import numpy as np def leaky_relu(z): return np.maximum(0.01 * z, z) leaky_relu(-2)
_____no_output_____
MIT
Activation_Functions.ipynb
hemanthsunny/machine_learning
import os import glob import cv2 import numpy as np from sklearn.model_selection import train_test_split from re import search from tensorflow import keras #-----------------------load images--------------------------------------------- #imageDir=os.path.abspath('/content/drive/MyDrive/Colab Notebooks/ImageClassificati...
4/4 - 21s - loss: 166.1185 - accuracy: 0.3280 - 21s/epoch - 5s/step Restored model, accuracy: 32.80%
MIT
CNNBreatCancer.ipynb
RihaChri/ImageClassificationBreastCancer
We notice that pdays is having [25, 50, 75] percentiles as -1 which indicates that missing values are denoted by -1.
data[data.duplicated()]
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Which age was targeted most and which one of them responded positively?
plt.figure(figsize=(13,5)) plt.subplot(1, 2, 1) sns.distplot(data['age']).set_title('Age distribution') plt.subplot(1, 2, 2) sns.violinplot(x = 'response', y = 'age', data=data).set_title('Relationship between age and response')
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
* We see from the above graph that most people targeted in the campaign lie in the age group of 25 to 50.* It is clear that people lying in the age group of 25 to 40 respond positively than any other age group. Does job description affect the chances of success?
grouped_job = pd.DataFrame(data.groupby(['job'])['response'].value_counts(normalize=True)) grouped_job.rename(columns={"response" : "pct"}, inplace=True) grouped_job.reset_index(inplace=True) plt.figure(figsize=(15,5)) sns.barplot(x='job', y='pct', hue='response', data=grouped_job).set_title('Response by job descriptio...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
* From the above plot it can be said that customers responding positively to the camapign are very less.* Customer with job role as management seems to interested more than any other job role. Does people with high profile job and high salary have greater chances of positive response?
job_salary = pd.DataFrame(data.groupby('job')['salary'].unique().apply(lambda x : x[0])).reset_index() job_response = pd.crosstab(data['job'], data['response']).reset_index() data1 = pd.merge(job_salary, job_response) data1.sort_values('yes', ascending=False) plt.figure(figsize=(15,5)) plt.subplot(1, 2, 1) g = sns.barp...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Yes, it is clearly visible that people with high job profile and salary tend to be more interested. Does marital status decide the response type?
np.log(pd.crosstab(data['marital'], data['response'])).plot.bar(title = 'Response based on marital status')
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Positive response is almost neutral in case of marital status. Does married people of younger age responds positively to the campaign?
data2 = data[(data['marital']=='married') & (data['age']<25)] sns.barplot(x='response', y='age', data=data2)
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Ratio of yes/no among married young customer seems to be equal. Age distribution based on marital status
m = sns.FacetGrid(data, col='marital', height = 4) m.map(plt.hist, 'age')
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
* From the 1st plot it can be seen that mostly married people lie around 25 to 56.* Single people lie in the age group of 25 to 37.* Most probably divorced people lie in the age group of 30 to 60. What is the relationship between education level and salary?
sns.boxplot(x='education', y='salary', data=data).set_title('Boxplot distribution of salary based on education level') plt.show()
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
It is clear from the above graph that people with high level of education tend to have high salary. Are customer of low job profile and married are most responsive one?
grouped_job_married = pd.DataFrame(data[data['marital']=='married'].groupby(['job'])['response'].value_counts(normalize=True)) grouped_job_married.rename(columns={"response" : "pct"}, inplace=True) grouped_job_married.reset_index(inplace=True) plt.figure(figsize=(15,5)) sns.barplot(x='job', y='pct', hue='response', dat...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Yes, people who are married and have low job profile tend to response more positvely than any other job profile. Are the targeted customers interested in such campaigns?
data.head()
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
In order to answer this questions checking of previous campaign records would be appropriate.
grouped_poutcome = pd.DataFrame(data['poutcome'].value_counts(normalize=True)) grouped_poutcome = grouped_poutcome.reset_index().rename(columns={"index" : "poutcome", "poutcome" : "pct"}) sns.barplot(x='poutcome', y='pct', data=grouped_poutcome).set_title('Results of previous campaign') plt.figure(figsize=(12, 4)) plt....
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
It seems that mostly people were contacted within few days still people dosen't seems to be interested in such campaigns. Does targeted customer with high job profile and high salary interested in such campaigns anymore?
data.groupby('job')['salary'].unique().apply(lambda x : x[0]).sort_values(ascending=False) data3 = data[(data['salary']>50000) & (data['targeted']=='yes')]['response'].value_counts(normalize=True) data3 = pd.DataFrame(data3) data3 = data3.reset_index().rename(columns={'index' : 'response', 'response' : 'pct'}) grouped_...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
There is not much significant difference in the response of high job profile customers from previous to current campaign. Distribution of diff in salary and balance.
data['expenditure'] = data['salary'] - data['balance'] plt.figure(figsize=(15,5)) sns.distplot(data['expenditure'], bins=10).set_title('Distribution of expenditure')
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
It seems there are people with varying limit in terms of expenditure. What is the response of customer with high expenditure?
data['expenditure'].plot.box() threshold = data['expenditure'].quantile(0.90) less_exp = pd.DataFrame(data[data['expenditure']<threshold]['response'].value_counts(normalize=True)) less_exp = less_exp.reset_index().rename(columns={'index' : 'response', 'response' : 'pct'}) high_exp = pd.DataFrame(data[data['expenditure...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Although, the response from customers are very few. But, those who spend less have greater chances of postive response as compared to those who spend more. Is there any relationship between education level and bank balance?
sns.boxplot(x='education', y='balance', data=data).set_title('Boxplot distribution of balance by education level')
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
There is not much difference in the statistical measure of balance by education. Rather, it depends on person-to-person. What are the chances of customer responding positively who already have home and personal loan?
data[(data['housing']=='yes') & (data['loan']=='yes')]['response'].value_counts(normalize=True).plot.bar(title='Customer response having home and personal loan')
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Not much people are interested in such campaigns who already have loans. What are the ways of contacting a customer. And which contact types are most effective?
grouped_contact = pd.DataFrame(data['contact'].value_counts(normalize=True)).reset_index().rename(columns={'index' : 'contact_type', 'contact' : 'pct'}) sns.barplot(x='contact_type', y ='pct', data=grouped_contact).set_title('Different contact types for contacting customers') grouped_contact_response = pd.DataFrame(dat...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Most of the people use cell phones as a communication device and it would be better if we target customer who use cell phones. In which month and day most customer were addressed?
grouped_month = pd.DataFrame(data['month'].value_counts(normalize=True)).reset_index().rename(columns={"index" : "month", "month" : "pct"}) grouped_day = pd.DataFrame(data['day'].value_counts(normalize=True)).reset_index().rename(columns={"index" : "day", "day" : "pct"}) plt.figure(figsize=(15, 5)) plt.subplot(1, 2, 1)...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
It seems in the month of may most customers are handled and this may be due to the fact that vacations are going on at that point of time. What is the effect of regular campaigning to a customer?
grouped_camp = pd.DataFrame(data['campaign'].value_counts(normalize=True)).reset_index().rename(columns={"index" : "campaign_freq", "campaign" : "pct"}) plt.figure(figsize=(15,5)) plt.subplot(1, 2, 1) sns.barplot(x='campaign_freq', y='pct', data=grouped_camp).set_title('No of times a customer was contacted during a cam...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
* It is clear from above graph that as people are being contacted more and more for a particular contact they seems to lose interest.* The campaign team also needs to keep track of these records as it will save their time and focus on things which will add value to them. Modelling
def get_dummies(x,df): temp = pd.get_dummies(df[x], prefix = x, prefix_sep = '_', drop_first = True) df = pd.concat([df, temp], axis = 1) df.drop([x], axis = 1, inplace = True) return df X = data.drop(['response', 'campaign_size'], axis=1) y = data.response X.loc[X['pdays']==-1, 'pdays'] = 10000 # Crea...
_____no_output_____
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
Random Forest Classifier
rfc = RandomForestClassifier() random_search = RandomizedSearchCV(rfc, param_distributions=params_grid, n_iter=10, cv=10) random_search.fit(X_train, y_train) random_search.best_estimator_.n_estimators random_search.best_estimator_.criterion random_search.best_estimator_.max_depth rfc2 = RandomForestClassifier(n_estimat...
precision recall f1-score support 0 0.92 0.97 0.95 7987 1 0.64 0.35 0.45 1056 accuracy 0.90 9043 macro avg 0.78 0.66 0.70 9043 weighted avg 0.89 0.90 0.89 ...
MIT
BI_Capstone_Project1/Solution.ipynb
amazerahul/BI_Capstone_Project
This will define a class ```FitnessMax``` which inherits the Fitness class of deep.base module. The attribute weight which is a tuple is used to specify whether fitness function is to be maximized (weights=1.0) or minimized weights=-1.0. The DEAP library allows multi-objective Fitness function. IndividualNext we creat...
# Now we create a individual class creator.create("Individual", list, fitness=creator.FitnessMax)
_____no_output_____
MIT
Chapter05/GuessTheWord.ipynb
PacktPublishing/Hands-On-Artificial-Intelligence-for-IoT
PopulationOnce the individuals are created we need to create population and define gene pool, to do this we use DEAP toolbox. All the objects that we will need now onwards- an individual, the population, the functions, the operators and the arguments are stored in the container called ```Toolbox```We can add or remove...
toolbox = base.Toolbox() # Gene Pool toolbox.register("attr_string", random.choice, string.ascii_letters + string.digits ) #Number of characters in word word = list('hello') N = len(word) # Initialize population toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_string, N ) toolbox.regi...
_____no_output_____
MIT
Chapter05/GuessTheWord.ipynb
PacktPublishing/Hands-On-Artificial-Intelligence-for-IoT
We define the other operators/functions we will need by registering them in the toolbox. This allows us to easily switch between the operators if desired. Evolving the PopulationOnce the representation and the genetic operators are chosen, we will define an algorithm combining all the individual parts and performing th...
def main(): random.seed(64) # create an initial population of 300 individuals (where # each individual is a list of integers) pop = toolbox.population(n=300) # CXPB is the probability with which two individuals # are crossed # # MUTPB is the probability for mutating an individua...
Start of evolution Evaluated 300 individuals -- Generation 1 -- Evaluated 178 individuals Min 0.0 Max 2.0 Avg 0.22 Std 0.4526956299030656 -- Generation 2 -- Evaluated 174 individuals Min 0.0 Max 2.0 Avg 0.51 Std 0.613650280425803 -- Generation 3 -- Evaluated 191 individuals Min 0.0 Max 3.0 ...
MIT
Chapter05/GuessTheWord.ipynb
PacktPublishing/Hands-On-Artificial-Intelligence-for-IoT
Variance
x = torch.randn(10) x plt.scatter(range(x.numel()),x) mean = x.mean() mean x - mean wrong_variance = (x-mean).mean() wrong_variance, wrong_variance.round()
_____no_output_____
MIT
Colab Notebooks/learning/20191012_important_maths_formulas_in_pytorch.ipynb
ankschoubey/notes
The reason that this is 0 is because positive and negatives cancel out. Therefore we need to make sure everything is positive
# mean absolute deviation mad = (x-mean).abs().mean() mad (x-mean).abs() # standard deviation sd = (x-mean).pow(2).mean().sqrt() sd sd
_____no_output_____
MIT
Colab Notebooks/learning/20191012_important_maths_formulas_in_pytorch.ipynb
ankschoubey/notes
from google.colab import drive drive.mount('/content/drive') !nvidia-smi !pip install transformers !pip install -q -U watermark %reload_ext watermark %watermark -v -p numpy,pandas,torch,transformers !pip install sklearn import sklearn
Requirement already satisfied: sklearn in /usr/local/lib/python3.6/dist-packages (0.0) Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from sklearn) (0.22.2.post1) Requirement already satisfied: scipy>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sklearn) (...
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Making the necessary imports
import transformers from transformers import XLNetTokenizer, XLNetModel, AdamW, get_linear_schedule_with_warmup import torch import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib import rc from sklearn.model_selection import train_test_split from sklearn.metrics i...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Data Preprocessing
from google.colab import files files.upload() df = pd.read_csv('sent140_preprocessed.csv') df.head() from sklearn.utils import shuffle df = shuffle(df) df.head(20) df = df[:4000] len(df) import re def clean_text(text1): text = re.sub(r"@[A-Za-z0-9]+", ' ', text) text = re.sub(r"https?://[A-Za-z0-9./]+", ' ', te...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Playing with XLNetTokenizer
from transformers import XLNetTokenizer, XLNetModel PRE_TRAINED_MODEL_NAME = 'xlnet-base-cased' tokenizer = XLNetTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME) input_txt = "India is my country. All Indians are my brothers and sisters" encodings = tokenizer.encode_plus(input_txt, add_special_tokens=True, max_length=1...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Checking the distribution of token lengths
token_lens = [] for txt in df['text']: tokens = tokenizer.encode(txt, max_length=512) token_lens.append(len(tokens)) sns.distplot(token_lens) plt.xlim([0, 1024]); plt.xlabel('Token count'); MAX_LEN = 512
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Custom Dataset class
class sent140(Dataset): def __init__(self, reviews, targets, tokenizer, max_len): self.reviews = reviews self.targets = targets self.tokenizer = tokenizer self.max_len = max_len def __len__(self): return len(self.reviews) def __getitem__(self, item): ...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Custom Dataloader
def create_data_loader(df, tokenizer, max_len, batch_size): ds = sent140( reviews=df.text.to_numpy(), targets=df.polarity.to_numpy(), tokenizer=tokenizer, max_len=max_len ) return DataLoader( ds, batch_size=batch_size, num_workers=4 ) BATCH_SIZE = 4 train_data_loader = create_data_...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Loading the Pre-trained XLNet model for sequence classification from huggingface transformers
from transformers import XLNetForSequenceClassification model = XLNetForSequenceClassification.from_pretrained('xlnet-base-cased', num_labels = 2) model = model.to(device) model
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Setting Hyperparameters
EPOCHS = 3 param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01}, ...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Sanity check with one batch
data = next(iter(val_data_loader)) data.keys() input_ids = data['input_ids'].to(device) attention_mask = data['attention_mask'].to(device) targets = data['targets'].to(device) print(input_ids.reshape(4,512).shape) # batch size x seq length print(attention_mask.shape) # batch size x seq length input_ids[0] outputs = mod...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Defining the training step function
from sklearn import metrics def train_epoch(model, data_loader, optimizer, device, scheduler, n_examples): model = model.train() losses = [] acc = 0 counter = 0 for d in data_loader: input_ids = d["input_ids"].reshape(4,512).to(device) attention_mask = d["attention_mask"].to(devic...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Defining the evaluation function
def eval_model(model, data_loader, device, n_examples): model = model.eval() losses = [] acc = 0 counter = 0 with torch.no_grad(): for d in data_loader: input_ids = d["input_ids"].reshape(4,512).to(device) attention_mask = d["attention_mask"].to(device) ...
_____no_output_____
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Fine-tuning the pre-trained model
%%time history = defaultdict(list) best_accuracy = 0 for epoch in range(EPOCHS): print(f'Epoch {epoch + 1}/{EPOCHS}') print('-' * 10) train_acc, train_loss = train_epoch( model, train_data_loader, optimizer, device, scheduler, len(df_train) ) ...
Epoch 1/3 ---------- Train loss 0.5852309298217296 Train accuracy 0.7585 Val loss 0.7540176632255315 Val accuracy 0.766 Epoch 2/3 ---------- Train loss 0.5752474646037444 Train accuracy 0.764 Val loss 0.6447369921803474 Val accuracy 0.765 Epoch 3/3 ---------- Train loss 0.5502564660999923 Train accuracy 0.812 Val los...
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Evaluation of the fine-tuned model
model.load_state_dict(torch.load('C:\\Users\\BUJJI\\Desktop\\NLP\\models\\xlnet_model1.bin')) model = model.to(device) test_acc, test_loss = eval_model( model, test_data_loader, device, len(df_test) ) print('Test Accuracy :', test_acc) print('Test Loss :', test_loss) def get_predictions(model, data_loader): ...
precision recall f1-score support negative 0.83 0.86 0.84 768 positive 0.47 0.42 0.44 232 accuracy 0.76 1000 macro avg 0.65 0.64 0.64 1000 weighted avg 0.75 0.76 0.75 ...
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
Custom prediction function on raw text
def predict_sentiment(text): review_text = text encoded_review = tokenizer.encode_plus( review_text, max_length=MAX_LEN, add_special_tokens=True, return_token_type_ids=False, pad_to_max_length=False, return_attention_mask=True, return_tensors='pt', ) input_ids = pad_sequenc...
Positive score: 0.9775038957595825 Negative score: 0.022496072575449944 Review text: This is the best movie I have ever seen!! The story is such a motivation Sentiment : positive
MIT
Sentiment_Analysis_Series_part_2(4000samplesonsent140).ipynb
kumarikumari/Keras-Deep-Learning-Cookbook
06_Business_Insights In this section, we will expend upon the features used by the model and attempt to explain its significance as well as contributions to the pricing model.Accordingly, in Section Four, we identified the following key features that that are strong predictors of housing price based upon a combination...
# model coefficients prod_model_rfe
_____no_output_____
MIT
project_2/06_Production_Model_Insights.ipynb
bearylogical/ga-test
Import Libraries
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import matplotlib.ticker as ticker %matplotlib inline rfe_columns = ['Total Bsmt SF', 'Gr Liv Area', 'age_since_built', 'house_exter_score', 'Land Contour_HLS', 'Land Contour_Low', 'Land Contour_Lvl']
_____no_output_____
MIT
project_2/06_Production_Model_Insights.ipynb
bearylogical/ga-test
Load in Training Set for Exploration
train = pd.read_csv('./datasets/imputed_train.csv') new_train = train[(train['Total Bsmt SF']<4000) & (train['Total Bsmt SF']>0)] plt.figure(figsize=(15,10)) ax = sns.scatterplot(x='Total Bsmt SF',y='SalePrice',data=new_train,hue='Total Bsmt SF') ax.set_title("Total Basement Area against Sale Prices", fontname='Helveti...
_____no_output_____
MIT
project_2/06_Production_Model_Insights.ipynb
bearylogical/ga-test
Hyperparameter Tuning and Grid Search CV Read data from pickle file
import pickle as pkl with open('../data/titanic_tansformed.pkl', 'rb') as f: df_data = pkl.load(f) df_data.head() data = df_data.drop("Survived",axis=1) label = df_data["Survived"]
_____no_output_____
MIT
classification/notebooks/06 - Hyperparameter and Grid Search CV.ipynb
pshn111/Machine-Learning-Package
Divide into train and test split
from sklearn.model_selection import train_test_split data_train, data_test, label_train, label_test = train_test_split(data, label, test_size = 0.2, random_state = 101) from sklearn.model_selection import StratifiedKFold from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_s...
Best Score 0.8045007032348804 Best Value of C 0.5 Best penalty l1
MIT
classification/notebooks/06 - Hyperparameter and Grid Search CV.ipynb
pshn111/Machine-Learning-Package
Optimal Model after a GridCV Search
optimal_model = LogisticRegression(C=log_grid.best_estimator_.C, penalty=log_grid.best_estimator_.penalty) optimal_model.fit(data_train, label_train) predictions = optimal_model.predict(data_test) print('Accuracy', optimal_model.score(data_test, label_test)) print('Coefficients', optimal_model.coef_) print('Intercept'...
Accuracy 0.8146067415730337 Coefficients [[-2.88708422e-02 -2.72763004e-01 -1.09620072e-01 2.39262062e-03 7.90405016e-01 0.00000000e+00 -1.08574363e+00 2.56316901e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 -3.09675215e-01]] Intercept [0.]
MIT
classification/notebooks/06 - Hyperparameter and Grid Search CV.ipynb
pshn111/Machine-Learning-Package
Bulk RNA-seq eQTL analysisThis notebook provide a command generator on the XQTL workflow so it can automate the work for data preprocessing and association testing on multiple data collection as proposed.
%preview ../images/eqtl_command.png
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
This master control notebook is mainly to serve the 8 tissues snuc_bulk_expression analysis, but should be functional on all analysis where expression data are are a tsv table in a bed.gz like format.Input: A recipe file,each row is a data collection and with the following column: Theme name of...
pd.DataFrame({"Theme":"MWE","molecular_pheno":"MWE.log2cpm.tsv","genotype_file":"MWE.bed","covariate_file":"MWE.covariate.cov.gz"}).to_csv("/mnt/vast/hpc/csg/snuc_pseudo_bulk/eight_tissue_analysis/MWE/command_generator",sep = "\t",index = 0)
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
| Theme | molecular_pheno | genotype_file |covariate_file|| ----------- | ----------- |-----------||| MWE | MWE.log2cpm.tsv | /data/genotype_data/GRCh38_liftedover_sorted_all.add_chr.leftnorm.filtered.bed |MWE.covariate.cov.gz| Minimal Working Example GenotypeThe MWE for the genotype session can be ra...
sos run pipeline/eQTL_analysis_commands.ipynb plink_per_chrom \ --ref_fasta reference_data/GRCh38_full_analysis_set_plus_decoy_hla.noALT_noHLA_noDecoy_ERCC.fasta \ --genoFile mwe_genotype.vcf.gz \ --dbSNP_vcf reference_data/00-All.vcf.gz \ --sample_participant_lookup reference_data/sampleSheetAft...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Per tissue analysisA MWE for the core per tissue analysis can be ran with the following commands, a complete collection of input file as well as intermediate output of the analysis can be found at [here](https://drive.google.com/drive/folders/16ZUsciZHqCeeEWwZQR46Hvh5OtS8lFtA?usp=sharing).
sos run pipeline/eQTL_analysis_commands.ipynb sumstat_merge \ --recipe MWE.recipe \ --genotype_list plink_files_list.txt \ --annotation_gtf reference_data/genes.reformatted.gene.gtf \ --sample_participant_lookup reference_data/sampleSheetAfterQC.txt \ --Association_option "TensorQTL" -n ...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline