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 |
|---|---|---|---|---|---|
Multi line strings | paragraph = "I am thinking of writing something that spans"\
"multiple lines and Nobody is helping me with that. So here"\
"is me typing something random"
print(paragraph)
# \n represents Newline
paragraph = "I am thinking of writing something that spans\n\
multiple lines and Nobody is helping me with that. So here\n\... | I am thinking of writing something that spans
multiple lines and Nobody is helping me with that. So here
is me typing something random
| Apache-2.0 | Lecture-Notes/2018/Day2.ipynb | unmeshvrije/python-for-beginners |
String indices | sample_string = "Sorry Madam"
# Subscipt operator : []
sample_string[1] # sample_string of 1
sample_string[2]
'''
*******************************************
Example of a multi-line comment:
To access the first character of the string
you need to use the index 0
*******************************************
'''
sample_st... | _____no_output_____ | Apache-2.0 | Lecture-Notes/2018/Day2.ipynb | unmeshvrije/python-for-beginners |
Conditional operators```== : Compare two expressions for equality!= : compare for inequality< : compare less than> : greater than<= : less than or equal to>= : greater than or equal to``` | fruit == 'banana'
fruit != 'orange'
print("fruit =", fruit)
print("fruit2 =", fruit2)
fruit[0:4] == fruit2[5:9] | _____no_output_____ | Apache-2.0 | Lecture-Notes/2018/Day2.ipynb | unmeshvrije/python-for-beginners |
Conditional statements | it_is_raining = False
it_is_sunny = not it_is_raining
if it_is_sunny:
print("I will go swimming in Sloterplas")
else:
print("I will work on Python (coding)")
it_is_raining = True
it_is_sunny = not it_is_raining
if it_is_sunny:
print("I will go swimming in Sloterplas")
print("I will run")
else:
... | Enter a number between 0 and 2316
I am researching
| Apache-2.0 | Lecture-Notes/2018/Day2.ipynb | unmeshvrije/python-for-beginners |
Loops | # Not so smart way of printing Hello 5 times
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")
# Smart way of printing Hello 5 times
for i in range(5):
print("Hello")
for i in range(5):
print(i)
for i in range(1,6):
print(i)
for u in range(1,6):
print(u, ")", "Hello")
sample_str... | [ 0 ]: S 15
[ 1 ]: o 15
[ 2 ]: r 15
[ 3 ]: r 15
[ 4 ]: y 15
[ 5 ]: 15
[ 6 ]: M 15
[ 7 ]: a 15
[ 8 ]: d 15
[ 9 ]: a 15
[ 10 ]: m 15
| Apache-2.0 | Lecture-Notes/2018/Day2.ipynb | unmeshvrije/python-for-beginners |
``` i = 0 print("[",str(i),"]:", sample_string[0], some_number) i = 1 print("[",str(i),"]:", sample_string[1], some_number) i = 2 print("[",str(i),"]:", sample_string[2], some_number) i = 3 print("[",str(i),"]:", sample_string[3], some_number) ... ... i = 10 print("[",str(i),"]:"... | len(sample_string) | _____no_output_____ | Apache-2.0 | Lecture-Notes/2018/Day2.ipynb | unmeshvrije/python-for-beginners |
``` n = input()n= 121224364860728496108120n = 44812162024.40``` | n = int(input())
for i in range(1,11):
print(i*n) | 12
12
24
36
48
60
72
84
96
108
120
| Apache-2.0 | Lecture-Notes/2018/Day2.ipynb | unmeshvrije/python-for-beginners |
Set up working directory | cd /usr/local/notebooks
mkdir -p ./workdir
#check seqfile files to process in data directory (make sure you still remember the data directory)
!ls ./data/test/data | 1c.fa 1d.fa 2c.fa 2d.fa
| BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
README This part of pipeline search for the SSU rRNA gene fragments, classify them, and extract reads aligned specific region. It is also heavy lifting part of the whole pipeline (more cpu will help). This part works with one seqfile a time. You just need to change the "Seqfile" and maybe other parameters in the two ce... | Seqfile='./data/test/data/2d.fa' | _____no_output_____ | BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
Other parameters to set | Cpu='2' # number of maxixum threads for search and alignment
Hmm='./data/SSUsearch_db/Hmm.ssu.hmm' # hmm model for ssu
Gene='ssu'
Script_dir='./SSUsearch/scripts'
Gene_model_org='./data/SSUsearch_db/Gene_model_org.16s_ecoli_J01695.fasta'
Ali_template='./data/SSUsearch_db/Ali_template.silva_ssu.fasta'
Start='577' ... | parsing hmmdotblout done..
50 of 114 seqs are kept after hmm parser
| BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
Pass hits to mothur aligner | !echo "*** Starting mothur align"
!cat $Gene_model_org $Tag.ssu.out/$Tag.qc.$Gene > $Tag.ssu.out/$Tag.qc.$Gene.RFadded
# mothur does not allow tab between its flags, thus no indents here
!time mothur "#align.seqs(candidate=$Tag.ssu.out/$Tag.qc.$Gene.RFadded, template=$Ali_template, threshold=0.5, flip=t, processors=$... | *** Starting mothur align
[H[2J
mothur v.1.34.4
Last updated: 12/22/2014
by
Patrick D. Schloss
Department of Microbiology & Immunology
University of Michigan
pschloss@umich.edu
http://www.mothur.org
When using, please cite:
Schloss, P.D., et al., Introducing mothur: Open-source, platform-independent, communit... | BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
Get aligned seqs that have > 50% matched to references | !python $Script_dir/mothur-align-report-parser-cutoff.py \
$Tag.ssu.out/$Tag.qc.$Gene.align.report \
$Tag.ssu.out/$Tag.qc.$Gene.align \
$Tag.ssu.out/$Tag.qc.$Gene.align.filter \
0.5
!python $Script_dir/remove-gap.py $Tag.ssu.out/$Tag.qc.$Gene.align.filter $Tag.ssu.out/$Tag.qc.$Gene.align.filter.fa | _____no_output_____ | BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
Search is done here (the computational intensive part). Hooray!- \$Tag.ssu.out/\$Tag.qc.\$Gene.align.filter: aligned SSU rRNA gene fragments - \$Tag.ssu.out/\$Tag.qc.\$Gene.align.filter.fa: unaligned SSU rRNA gene fragments Extract the reads mapped 150bp region in V4 (577-727 in *E.coli*... | !python $Script_dir/region-cut.py $Tag.ssu.out/$Tag.qc.$Gene.align.filter $Start $End $Len_cutoff
!mv $Tag.ssu.out/$Tag.qc.$Gene.align.filter."$Start"to"$End".cut.lenscreen $Tag.ssu.out/$Tag.forclust | 28 sequences are matched to 577-727 region
| BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
Classify SSU rRNA gene seqs using SILVA | !rm -f $Tag.ssu.out/$Tag.qc.$Gene.align.filter.*.wang.taxonomy
!mothur "#classify.seqs(fasta=$Tag.ssu.out/$Tag.qc.$Gene.align.filter.fa, template=$Gene_db, taxonomy=$Gene_tax, cutoff=50, processors=$Cpu)"
!mv $Tag.ssu.out/$Tag.qc.$Gene.align.filter.*.wang.taxonomy \
$Tag.ssu.out/$Tag.qc.$Gene.align.filter.wang.silv... | _____no_output_____ | BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
Classify SSU rRNA gene seqs with Greengene for copy correction later | !rm -f $Tag.ssu.out/$Tag.qc.$Gene.align.filter.*.wang.taxonomy
!mothur "#classify.seqs(fasta=$Tag.ssu.out/$Tag.qc.$Gene.align.filter.fa, template=$Gene_db_cc, taxonomy=$Gene_tax_cc, cutoff=50, processors=$Cpu)"
!mv $Tag.ssu.out/$Tag.qc.$Gene.align.filter.*.wang.taxonomy \
$Tag.ssu.out/$Tag.qc.$Gene.align.filter.wan... | 1c.577to727
1c.cut
1c.forclust
1c.qc.ssu
1c.qc.ssu.align
1c.qc.ssu.align.filter
1c.qc.ssu.align.filter.577to727.cut
1c.qc.ssu.align.filter.577to727.cut.lenscreen.fa
1c.qc.ssu.align.filter.fa
1c.qc.ssu.align.filter.greengene_97_otus.wang.tax.summary
1c.qc.ssu.align.filter.silva_taxa_family.wang.tax.summary
1c... | BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
This part of pipeline (working with one sequence file) finishes here. Next we will combine samples for community analysis (see unsupervised analysis).Following are files useful for community analysis:* 1c.577to727: aligned fasta file of seqs mapped to target region for de novo clustering* 1c.qc.ssu.align.filter: align... | !echo "*** pipeline runs successsfully :)" | *** pipeline runs successsfully :)
| BSD-3-Clause | notebooks/ssu-search-Copy4.ipynb | smoe/SSUsearch |
Classification and RegressionThere are two major types of supervised machine learning problems, called *classification* and *regression*.In classification, the goal is to predict a *class label*, which is a choice from a predefined list of possibilities. In *Intro_to_Decision_Trees.ipynb* we used the example of classi... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
A First Application: Predicting Boston Housing PricesOne of the most famous datasets for regression in a supervised learning setting is the [Boston Housing data set](https://archive.ics.uci.edu/ml/datasets/Housing). It is a multivariate dataset introduced in a 1978 paper which records 13 attributes concerning housin... | from sklearn.datasets import load_boston
boston = load_boston()
print("Keys of boston: {}".format(boston.keys()))
# The value of the key DESCR is a short description of the dataset. Here we show the beinning of the description.
print(boston['DESCR'][:193] + "\n...")
# The value of feature_names is a list of strings, g... | Target:
[ 24. 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 15. 18.9
21.7 20.4 18.2 19.9 23.1 17.5 20.2 18.2 13.6 19.6 15.2 14.5
15.6 13.9 16.6 14.8 18.4 21. 12.7 14.5 13.2 13.1 13.5 18.9
20. 21. 24.7 30.8 34.9 26.6 25.3 24.7 21.2 19.3 20. 16.6
14.4 19.4 19.7 ... | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Measuring Success: Training and testing dataWe want to build a machine learning model from this data that can predict the species of iris for a new set of measurements. But before we can apply our model to new measurements, we need to know whether it actually works -- that is, whether we should trust its predictions.... | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(boston['data'], boston['target'], random_state=0)
print("X_train shape: {}".format(X_train.shape))
print("y_train shape: {}".format(y_train.shape))
print("X_test shape: {}".format(X_test.shape))
print("y_test shape:... | X_test shape: (127, 13)
y_test shape: (127,)
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
First things first: Look at your dataBefore building a machine learning model, it is often a good idea to inspect the data, to see if the task is easily solvable without machine learning, or if the desired information might not be contained in the data.Additionally, inspecting the data is a good way to find abnormalit... | # create dataframe from data in X_train
boston_df = pd.DataFrame(X_train, columns=boston.feature_names)
# Add in the target data
boston_df['MEDV'] = y_train
# Look at the first few rows
boston_df.head()
# create a scatter matrix from the dataframe
tmp = pd.scatter_matrix(boston_df, figsize=(15, 15)) | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
From the plots, we can see RM has a strong positive linear relationship with MEDV and LSTAT has a strong negative one. This makes sense - the housing price should go up as the number of rooms increases and the housing prices should go down as the percentage of lower class/income families in the neighborhood increases. | # Get a high-level overview of the data
boston_df.describe()
# Find which features are most highly correlated with the housing prices
df = boston_df
df['MEDV'] = y_train
df.corr()['MEDV'] | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Building your model: Linear RegressionNow we can start building the actual machine learning model. There are many regression algorithms in *scikit-learn* that we could use. Here we will use Ordinary Least Squares (OLS) Linear Regression because it is easy to understand and interpret.All machine learning models in *s... | from sklearn.linear_model import LinearRegression
lr = LinearRegression() | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
The *lr* object encapsulates the algorithm that will be used to build the model from the training data, as well the algorithm to make predictions on new data points. It will also hold the information that the algorithm has extracted from the training data.To build the model on the training set, we call the **fit** met... | lr.fit(X_train, y_train) | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
The “slope” parameters (w), also called weights or coefficients, are stored in the coef_ attribute, while the offset or intercept (b) is stored in the intercept_ attribute: | print("lr.coef_: {}".format(lr.coef_))
print("lr.intercept_: {}".format(lr.intercept_)) | lr.coef_: [ -1.16869578e-01 4.39939421e-02 -5.34808462e-03 2.39455391e+00
-1.56298371e+01 3.76145473e+00 -6.95007160e-03 -1.43520477e+00
2.39755946e-01 -1.12937318e-02 -9.86626289e-01 8.55687565e-03
-5.00029440e-01]
lr.intercept_: 36.980455337620576
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
The intercept_ attribute is always a single float number, while the coef_ attribute is a NumPy array with one entry per input feature. As we only have 13 input features in this dataset, lr.coef_ has 13 entries.Let’s look at the training set and test set performance: | print("Training set score: {:.2f}".format(lr.score(X_train, y_train)))
print("Test set score: {:.2f}".format(lr.score(X_test, y_test))) | Training set score: 0.77
Test set score: 0.64
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
An R^2 of around 0.64 on the test set is not very good, but we can see that the scores on the training and test sets are are a decent distance apart. This means we are likely overfitting. With higher-dimensional datasets (meaning datasets with a large number of features), linear models become more powerful, and there i... | # Scale the boston dataset
from sklearn.preprocessing import MinMaxScaler
X = MinMaxScaler().fit_transform(boston.data)
X_train, X_test, y_train, y_test = train_test_split(X, boston['target'], random_state=0)
lr = LinearRegression().fit(X_train, y_train)
print("Training set score: {:.2f}".format(lr.score(X_train, y_tra... | Training set score: 0.77
Test set score: 0.64
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Ordinary Least Squares (OLS) regression is not sensitive to feature scaling, but all of the regularized linear methods which help reduce the overfitting present in OLS are sensitive to feature scaling. Feature EngineeringFeature engineering is the process of using domain knowledge of the data to create features that m... | from sklearn.datasets import load_boston
from sklearn.preprocessing import MinMaxScaler, PolynomialFeatures, StandardScaler, RobustScaler
def load_extended_boston(scaler='minmax'):
boston = load_boston()
X = boston.data
if 'standard' == scaler:
X = StandardScaler().fit_transform(boston.data)
el... | Training set score: 0.95
Test set score: 0.61
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Now the basic OLS model is doing a dramatically better job fitting the training set (R^2 of 0.95 vs 0.77).This discrepancy between performance on the training set and the test set is a clear sign of overfitting, and therefore we should try to find a model that allows us to control complexity. One of the most commonly u... | from sklearn.linear_model import Ridge
ridge = Ridge().fit(X_train, y_train)
print("Training set score: {:.2f}".format(ridge.score(X_train, y_train)))
print("Test set score: {:.2f}".format(ridge.score(X_test, y_test))) | Training set score: 0.89
Test set score: 0.75
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
As you can see, the training set score of Ridge is *lower* than for LinearRegression, while the test set score is *higher*. This is consistent with our expectation. With linear regression, we were overfitting our data. Ridge is a more restricted model, so we are less likely to overfit. A less complex model means worse ... | ridge10 = Ridge(alpha=10).fit(X_train, y_train)
print("Training set score: {:.2f}".format(ridge10.score(X_train, y_train)))
print("Test set score: {:.2f}".format(ridge10.score(X_test, y_test)))
| Training set score: 0.79
Test set score: 0.64
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Decreasing alpha allows the coefficients to be less restricted. For very small values of alpha, coefficients are barely restricted at all, and we end up with a model that resembles LinearRegression: | ridge01 = Ridge(alpha=0.1).fit(X_train, y_train)
print("Training set score: {:.2f}".format(ridge01.score(X_train, y_train)))
print("Test set score: {:.2f}".format(ridge01.score(X_test, y_test))) | Training set score: 0.93
Test set score: 0.77
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Here, alpha=0.1 seems to be working well. We could try decreasing alpha even more to improve generalization. For now, notice how the parameter alpha corresponds to the model complexity. Very shortly we need to think about systematic methods for properly select optimal values for parameters such as **alpha**.We can also... | plt.figure(figsize=(15, 10))
plt.plot(ridge.coef_, 's', label="Ridge alpha=1")
plt.plot(ridge10.coef_, '^', label="Ridge alpha=10")
plt.plot(ridge01.coef_, 'v', label="Ridge alpha=0.1")
plt.plot(lr.coef_, 'o', label="LinearRegression")
plt.xlabel("Coefficient index")
plt.ylabel("Coefficient magnitude")
plt.hlines(0, 0... | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Clearly, the interactions and polynomial features gave us a good boost in performance when using Ridge. When using a more complex model like a random forest, the story can be a bit different, though. Adding features will benefit linear models the most. For very complex models, adding features may actually slightly de... | # Let's evaluate cross-validation on the iris dataset using logistic regression (which is actually classification)
from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
iris = load_iris()
logreg = LogisticRegression()
scores = cr... | Cross-validation scores: [ 0.96078431 0.92156863 0.95833333]
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
By default, cross_val_score performs three-fold cross-validation, returning three accuracy values. We can change the number of folds used by changing the cv parameter: | scores = cross_val_score(logreg, iris.data, iris.target, cv=5)
print("Cross-validation scores: {}".format(scores)) | Cross-validation scores: [ 1. 0.96666667 0.93333333 0.9 1. ]
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
A common way to summarize the cross-validation accuracy is to compute the mean: | print("Average cross-validation score: {:.2f}".format(scores.mean())) | Average cross-validation score: 0.96
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Using the mean cross-validation we can conclude that we expect the model to be around 96% accurate on average. Looking at all five scores produced by the five-fold cross-validation, we can also conclude that there is a relatively high variance in the accuracy between folds, ranging from 100% accuracy to 90% accuracy. T... | lr = LinearRegression()
scores = cross_val_score(lr, boston.data, boston.target)
print("Cross-validation scores: {}".format(scores)) | Cross-validation scores: [ 0.5828011 0.53193819 -5.85104986]
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
As we can see, a default 3-fold cross-validation performed ok for the first two folds, but horribly bad for the third one. The fundamental problem here is that if that data isn't organized in a random way, then just taking folds in order doesn't represent a random sampling for each fold. There are multiple possible w... | # Let's look at the boston housing dataset again using shuffle-split cross-validation to ensure random sampling
# The following code splits the dataset into 80% training set and 20% test set for 3 iterations:
from sklearn.model_selection import ShuffleSplit
shuffle_split = ShuffleSplit(test_size=.8, train_size=.2, n_sp... | Cross-validation scores:
[ 0.69514428 0.69350546 0.63047915]
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Grid SearchNow that we know how to evaluate how well a model generalizes, we can take the next step and improve the model’s generalization performance by tuning its parameters. We discussed the parameter settings of the Ridge model for ridge regression earlier. Finding the values of the important parameters of a model... | X, y = load_extended_boston(scaler='standard')
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
print("Size of training set: {} size of test set: {}".format(X_train.shape[0], X_test.shape[0]))
best_score = 0
for alpha in [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100]:
# for eac... | Size of training set: 379 size of test set: 127
Best score: 0.78
Best parameters: {'alpha': 50}
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
The Danger of Overfitting the Parameters and the Validation SetGiven this result, we might be tempted to report that we found a model that performs with 78% accuracy on our dataset. However, this claim could be overly optimistic (or just wrong), for the following reason: we tried many different parameters and selected... | X, y = load_extended_boston(scaler='standard')
# split data into train+validation set and test set
X_trainval, X_test, y_trainval, y_test = train_test_split(X, y, random_state=0)
# split train+validation set into training and validation sets
X_train, X_valid, y_train, y_valid = train_test_split(X_trainval, y_trainval, ... | Size of training set: 284 size of validation set: 95 size of test set: 127
Best score on validation set: 0.92
Best parameters: {'alpha': 50}
Test set score with best parameters: 0.78
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
The best score on the validation set is 92%. However, the score on the test set—the score that actually tells us how well we generalize—is lower, at 78%. So we can claim to classify new data 78% correctly. This happens to be the same as before, now we can make a stronger claim since the final test set wasn't used in a... | best_score = 0
for alpha in [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100]:
# for each combination of parameters, train an SVC
ridge = Ridge(alpha=alpha)
# perform cross-validation
scores = cross_val_score(ridge, X_trainval, y_trainval, cv=5)
# compute mean cross-validation accura... | Best score on validation set: 0.83
Best parameters: {'alpha': 10}
Test set score with best parameters: 0.77
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
To evaluate the accuracy of the Ridge Regression model using a particular setting of alpha using five-fold cross-validation, we need to train 11 * 5 = 55 models. As you can imagine, the main downside of the use of cross-validation is the time it takes to train all these models. However, as you can see here, it is a mo... | param_grid = {'alpha': [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100]}
print("Parameter grid:\n{}".format(param_grid)) | Parameter grid:
{'alpha': [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100]}
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
We can now instantiate the **GridSearchCV** class with the model (*Ridge*), the parameter grid to search (*param_grid*), and the cross-validation strategy we want to use (say, five-fold stratified cross-validation): | from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import Ridge
grid_search = GridSearchCV(Ridge(), param_grid, cv=5) | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
**GridSearchCV** will use cross-validation in place of the split into a training and validation set that we used before. However, we still need to split the data into a training and a test set, to avoid overfitting the parameters: | X, y = load_extended_boston(scaler='standard')
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
The *grid_search* object that we created behaves just like a classifier; we can call the standard methods **fit**, **predict**, and **score** on it. However, when we call **fit**, it will run cross-validation for each combination of parameters we specified in param_grid: | grid_search.fit(X_train, y_train) | _____no_output_____ | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Fitting the **GridSearchCV** object not only searches for the best parameters, but also automatically fits a new model on the whole training dataset with the parameters that yielded the best cross-validation performance. What happens in fit is therefore equivalent to the result of the code we saw at the beginning of th... | print("Test set score: {:.2f}".format(grid_search.score(X_test, y_test))) | Test set score: 0.77
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Choosing the parameters using cross-validation, we actually found a model that achieves 77% accuracy on the test set. The important thing here is that we *did not use the test set* to choose the parameters. The parameters that were found are scored in the **`best_params_`** attribute, and the best cross-validation accu... | print("Best parameters: {}".format(grid_search.best_params_))
print("Best cross-validation score: {:.2f}".format(grid_search.best_score_)) | Best parameters: {'alpha': 10}
Best cross-validation score: 0.83
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Sometimes it is helpful to have access to the actual model that was found—for example, to look at coefficients or feature importances. You can access the model with the best parameters trained on the whole training set using the **`best_estimator_`** attribute: | print("Best estimator:\n{}".format(grid_search.best_estimator_)) | Best estimator:
Ridge(alpha=10, copy_X=True, fit_intercept=True, max_iter=None,
normalize=False, random_state=None, solver='auto', tol=0.001)
| Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Because *grid_search* itself has **predict** and **score** methods, using **`best_estimator_`** is not needed to make predictions or evaluate the model. Putting it all togetherThe one thing we didn't do was experiment with different train/test splits. Let's run it with randomness a bunch of times and see how consiste... | from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import Ridge
param_grid = {'alpha': [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100]}
grid_search = GridSearchCV(Ridge(), param_grid, cv=5)
X, y = load_extended_boston(scaler='standard')
for i in range(10):
X_train, X_test, y_train... | Run 0 - Test set score: 0.81 Best parameters: {'alpha': 1}
Run 1 - Test set score: 0.82 Best parameters: {'alpha': 5}
Run 2 - Test set score: 0.81 Best parameters: {'alpha': 10}
Run 3 - Test set score: 0.89 Best parameters: {'alpha': 10}
Run 4 - Test set score: 0.87 Best parameters: {'alpha': 10}
Run 5 - Test set ... | Apache-2.0 | SL2_Regression_and_Classification.ipynb | tleonhardt/machine_learning |
Parameter ManagementOnce we have chosen an architectureand set our hyperparameters,we proceed to the training loop,where our goal is to find parameter valuesthat minimize our objective function. After training, we will need these parameters in order to make future predictions.Additionally, we will sometimes wish to ex... | %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/
%maven ai.djl:api:0.7.0-SNAPSHOT
%maven ai.djl:model-zoo:0.7.0-SNAPSHOT
%maven org.slf4j:slf4j-api:1.7.26
%maven org.slf4j:slf4j-simple:1.7.26
%maven net.java.dev.jna:jna:5.3.0
%maven ai.djl.mxnet:mxnet-engine:0.7.0-SNAPSHOT
%maven ai.d... | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Parameter AccessLet us start with how to access parametersfrom the models that you already know.Each layer's parameters are conveniently stored in a `Pair` consisting of a unique`String` that serves as a key for the layer and the `Parameter` itself.The `ParameterList` is an extension of `PairList` and is returned with... | ParameterList params = net.getParameters();
// Print out all the keys (unique!)
for (var pair : params) {
System.out.println(pair.getKey());
}
// Use the unique key to access the Parameter
NDArray dense0Weight = params.get("01Linear_weight").getArray();
NDArray dense0Bias = params.get("01Linear_bias").getArray();
... | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
The output tells us a few important things.First, each fully-connected layer has two parameters, e.g., `dense0Weight` and `dense0Bias`,corresponding to that layer's weights and biases, respectively.The `params` variable is a `ParameterList` which contain thekey-value pairs of the layer name and a parameter of the `Para... | dense0Weight.getGradient(); | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Collecting Parameters from Nested BlocksLet us see how the parameter naming conventions work if we nest multiple blocks inside each other. For that we first define a function that produces Blocks (a Block factory, so to speak) and then combine these inside yet larger Blocks. | public SequentialBlock block1() {
SequentialBlock net = new SequentialBlock();
net.add(Linear.builder().setUnits(32).build());
net.add(Activation.reluBlock());
net.add(Linear.builder().setUnits(16).build());
net.add(Activation.reluBlock());
return net;
}
public SequentialBlock block2() {
Se... | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Now that we have designed the network, let us see how it is organized.We can get the list of named parameters by calling `getParameters()`.However, we not only want to see the parameters, but also howour network is structured.To see our network architecture, we can simply print out the block whose architecture we want ... | /* Network Architecture for RgNet */
rgnet
/* Parameters for RgNet */
for (var param : rgnet.getParameters()) {
System.out.println(param.getValue().getArray());
} | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Since the layers are hierarchically nested,we can also access them by calling their `getChildren()` methodto get a `BlockList`(also an extension of `PairList`) of their inner blocks.It shares methods with `ParameterList` and as such we can use theirfamiliar structure to access the blocks. We can call `get(i)` to get th... | Block majorBlock1 = rgnet.getChildren().get(0).getValue();
Block subBlock2 = majorBlock1.getChildren().valueAt(1);
Block linearLayer1 = subBlock2.getChildren().valueAt(0);
NDArray bias = linearLayer1.getParameters().valueAt(1).getArray();
bias | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Parameter InitializationNow that we know how to access the parameters,let us look at how to initialize them properly.We discussed the need for initialization in :numref:`sec_numerical_stability`. By default, DJL initializes weight matricesbased on your set initializer and the bias parameters are all set to $0$.However... | net.setInitializer(new ConstantInitializer(1));
net.initialize(manager, DataType.FLOAT32, x.getShape());
Block linearLayer = net.getChildren().get(0).getValue();
NDArray weight = linearLayer.getParameters().get(0).getValue().getArray();
weight | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
We can see these initializations however if we create a new network.Let us write a function to create these network architectures for usconveniently. | public SequentialBlock getNet() {
SequentialBlock net = new SequentialBlock();
net.add(Linear.builder().setUnits(8).build());
net.add(Activation.reluBlock());
net.add(Linear.builder().setUnits(1).build());
return net;
} | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
If we run our previous initializer on this new net and check a parameter, we'llsee that everything is initialized properly! (to 7777!) | SequentialBlock net = getNet();
net.setInitializer(new ConstantInitializer(7777));
net.initialize(manager, DataType.FLOAT32, x.getShape());
Block linearLayer = net.getChildren().valueAt(0);
NDArray weight = linearLayer.getParameters().valueAt(0).getArray();
weight | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
We can also initialize all parameters as Gaussian random variables with standard deviation $.01$. | SequentialBlock net = getNet();
net.setInitializer(new NormalInitializer());
net.initialize(manager, DataType.FLOAT32, x.getShape());
Block linearLayer = net.getChildren().valueAt(0);
NDArray weight = linearLayer.getParameters().valueAt(0).getArray();
weight | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
We can also apply different initializers for certain Blocks.For example, below we initialize the first layerwith the `Xavier` initializerand initialize the second layer to a constant value of 0.We will do this without the `getNet()` function as it will be easierto have the reference to each block we want to set. | SequentialBlock net = new SequentialBlock();
Linear linear1 = Linear.builder().setUnits(8).build();
net.add(linear1);
net.add(Activation.reluBlock());
Linear linear2 = Linear.builder().setUnits(1).build();
net.add(linear2);
linear1.setInitializer(new XavierInitializer());
linear1.initialize(manager, DataType.FLOAT32, ... | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Finally, we can loop over the `ParameterList` and set their initializers individually.When setting initializers directly on the `Parameter`, you must pass in an `overwrite`boolean along with the initializer to declare whether you want your currentinitializer to overwrite the previous initializer if one has already been... | SequentialBlock net = getNet();
ParameterList params = net.getParameters();
for (int i = 0; i < params.size(); i++) {
// Here we interleave initializers.
// We initialize parameters at even indexes to 0
// and parameters at odd indexes to 2.
Parameter param = params.valueAt(i);
if (i % 2 == 0) {
... | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Custom InitializationSometimes, the initialization methods we need are not standard in DJL. In these cases, we can define a class to implement the `Initializer` interface. We only have to implement the `initialize()` function,which takes an `NDManager`, a `Shape`, and the `DataType`. We then create the `NDArray` with ... | class MyInit implements Initializer {
public MyInit() {}
@Override
public NDArray initialize(NDManager manager, Shape shape, DataType dataType) {
System.out.printf("Init %s\n", shape.toString());
// Here we generate data points
// from a uniform distribution [-10, 10]
NDAr... | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Note that we always have the option of setting parameters directly by calling `getValue().getArray()` to access the underlying `NDArray`. A note for advanced users: you cannot directly modify parameters within a `GarbageCollector` scope.You must modify them outside the `GarbageCollector` scope to avoid confusing the au... | // '__'i() is an inplace operation to modify the original NDArray
NDArray weightLayer = net.getChildren().valueAt(0)
.getParameters().valueAt(0).getArray();
weightLayer.addi(7);
weightLayer.divi(9);
weightLayer.set(new NDIndex(0, 0), 2020); // set the (0, 0) index to 2020
weightLayer; | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Tied ParametersOften, we want to share parameters across multiple layers.Later we will see that when learning word embeddings,it might be sensible to use the same parametersboth for encoding and decoding words. We discussed one such case when we introduced :numref:`sec_model_construction`. Let us see how to do this a ... | SequentialBlock net = new SequentialBlock();
// We need to give the shared layer a name
// such that we can reference its parameters
Block shared = Linear.builder().setUnits(8).build();
SequentialBlock sharedRelu = new SequentialBlock();
sharedRelu.add(shared);
sharedRelu.add(Activation.reluBlock());
net.add(Linear.... | _____no_output_____ | MIT-0 | chapter_deep-learning-computation/parameters.ipynb | dltech-xyz/d2l-java |
Pandas for Data Science | import pandas as pd
s = pd.Series([3,-5,7,4], index = ['a','b','c','d']) | _____no_output_____ | BSD-4-Clause-UC | Untitled.ipynb | subhadip2038/Python |
Calling a single dimentional Array | s | _____no_output_____ | BSD-4-Clause-UC | Untitled.ipynb | subhadip2038/Python |
Create a two dimentional array | data = {'Country': ['Belgium','India','Brazil'],'Capital':['Brussels','New Delhi','Brasilia'],
'Population': [11190846,1303171035,207847528]}
df= pd.DataFrame(data, columns = ['Country','Capital','Population'])
df | _____no_output_____ | BSD-4-Clause-UC | Untitled.ipynb | subhadip2038/Python |
Selection of values | s['b']
df[1:]
df[0:2]
df[:]
df[2:2]
df[0:2]
df.iloc[[0],[0]]
df.loc[[0],['Country']]
df.ix[2, 'Capital']
df['Country']
df.loc[[0],['Country']]
df.ix[[2],['Capital']]
df.Country
df.Capital
df.Population
df.Country
df[:2]
df[1:2]
df[2:3]
df[:3]
df[2:]
df[1:]
import pandas as pd
energy = pd.read_excel('Energy Indicators.x... | _____no_output_____ | BSD-4-Clause-UC | Untitled.ipynb | subhadip2038/Python |
***Introduction to Radar Using Python and MATLAB*** Andy Harrison - Copyright (C) 2019 Artech House Frustum Radar Cross Section*** Referring to Section 7.4.1.7, the frustum geometry is shown in Figure 7.13. An approximation for the radar cross section due to linearly polarized incident energy is given by (Equation 7.6... | import lib_path | _____no_output_____ | Apache-2.0 | jupyter/Chapter07/frustum.ipynb | mberkanbicer/software |
Set the operating frequency (Hz), the nose radius (m), the base radisu (m) and the length (m) | frequency = 1e9
nose_radius = 0.1
base_radius = 0.8
length = 3.0 | _____no_output_____ | Apache-2.0 | jupyter/Chapter07/frustum.ipynb | mberkanbicer/software |
Set the incident angles using the `linspace` routine from `scipy` | from numpy import linspace
from scipy.constants import pi
incident_angle = linspace(0, pi, 1801) | _____no_output_____ | Apache-2.0 | jupyter/Chapter07/frustum.ipynb | mberkanbicer/software |
Calculate the radar cross section (m^2) for the frustum | from Libs.rcs.frustum import radar_cross_section
from numpy import array
rcs = array([radar_cross_section(frequency, nose_radius, base_radius, length, ia) for ia in incident_angle])
from matplotlib import pyplot as plt
from numpy import log10, degrees
# Set the figure size
plt.rcParams["figure.figsize"] = (15, 1... | _____no_output_____ | Apache-2.0 | jupyter/Chapter07/frustum.ipynb | mberkanbicer/software |
Advent of Code Day 1:see [here](https://adventofcode.com/2019/day/1) for detail Part 1: | input=[56123,145192,123702,66722,148748,53337,147279,126828,118438,54030,145839,87751,58832,90085,113196,104802,61235,136935,108620,60795,107908,123023,142399,131074,123411,122653,84776,100891,78816,62762,92077,91428,56831,65122,94694,78668,112506,73406,118239,57897,59200,54437,55185,102667,86076,80655,83406,141502,671... | 3223398
| MIT | Advent_of_Code_1.ipynb | wustudent/advent-of-code-2019 |
Part 2: | def calcExtra(x):
sum = 0
t = x
while t>0:
t = calcFuel(t)
if t>0:
sum+=t
return sum
print(sum(map(calcExtra,input))) | 4832253
| MIT | Advent_of_Code_1.ipynb | wustudent/advent-of-code-2019 |
再構成モデル | callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=100)
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4), loss="mse")
model.fit(recon_train_ds, epochs=1000, validation_data=recon_test_ds, callbacks=[callback]) | Epoch 1/1000
23/23 [==============================] - 19s 758ms/step - loss: 2.6931e-04 - val_loss: 0.0014
Epoch 2/1000
23/23 [==============================] - 16s 692ms/step - loss: 3.0463e-04 - val_loss: 0.0013
Epoch 3/1000
23/23 [==============================] - 16s 684ms/step - loss: 2.7788e-04 - val_loss: 4.3864... | MIT | notebooks/annotation_poc.ipynb | ydty/concreate_inspection_app |
セグメンテーションモデル | #callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=30)
#segment_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4), loss="binary_crossentropy",metrics=["binary_crossentropy"])
segment_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3), loss="mae",metrics=["mae"])
... | INFO:tensorflow:Assets written to: reconstruct\assets
INFO:tensorflow:Assets written to: segmentation\assets
| MIT | notebooks/annotation_poc.ipynb | ydty/concreate_inspection_app |
可視化 | fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax1.set_title("pred",fontsize=20)
plt.imshow(model(tf.expand_dims(image, axis=0))[0])
ax2 = fig.add_subplot(1, 2, 2)
ax2.set_title("image",fontsize=20)
plt.imshow(image)
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax1.set_title("pred",fontsize=20)
plt.imshow(segme... | _____no_output_____ | MIT | notebooks/annotation_poc.ipynb | ydty/concreate_inspection_app |
特徴空間分離 | from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
import pandas as pd
feature_model = model.get_layer("sequential_1").get_layer("model_12")
feature_model = tf.keras.Model(inputs=feature_model.input, outputs=feature_model.get_layer("block3_pool").output)
# 特徴量抽出モデル
test = train_ds.unbatch()
#a_x ... | _____no_output_____ | MIT | notebooks/annotation_poc.ipynb | ydty/concreate_inspection_app |
import random
import os
import numpy as np
import torch
SEED = 45
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
seed_everything(SEED)
!git ... | _____no_output_____ | MIT | algo.ipynb | RenqinSS/Rec | |
Style Transfer Intensity | # Style Transfer intensity
sti_responses = gc.open_by_url('https://docs.google.com/spreadsheets/d/1_B3ayl6-p3nRl3RUtTgcu7fGT2v3n6rg3CLrR4wTafQ/edit#gid=2064143541')
sti_response_sheet = sti_responses.sheet1
sti_reponse_data = sti_response_sheet.get_all_values()
# sti_reponse_data
sti_answer_dict = {}
for idx, row in en... | _____no_output_____ | Apache-2.0 | evaluation/all_evaluation.ipynb | cs-mac/Unsupervised_Style_Transfer |

nat_iso_responses = gc.open_by_url('https://docs.google.com/spreadsheets/d/1tEOalZErOjSOD8DGKfvi-edv8sKkGczLx0eYi7N6Kjw/edit#gid=1759015116')
nat_iso_response_sheet = nat_iso_responses.sheet1
nat_iso_reponse_data = nat_iso_response_sheet.get_all_values()
# nat_iso_reponse_data
nat_iso_answer_di... | _____no_output_____ | Apache-2.0 | evaluation/all_evaluation.ipynb | cs-mac/Unsupervised_Style_Transfer |
Naturalness (Comparison) | # Naturalness (comparison)
nat_comp_responses = gc.open_by_url('https://docs.google.com/spreadsheets/d/1mFtsNNaJXDK2dT9LkLz_r8LSfIOPskDqn4jBamE-bns/edit#gid=890219669')
nat_comp_response_sheet = nat_comp_responses.sheet1
nat_comp_reponse_data = nat_comp_response_sheet.get_all_values()
# nat_comp_reponse_data
nat_comp_a... | _____no_output_____ | Apache-2.0 | evaluation/all_evaluation.ipynb | cs-mac/Unsupervised_Style_Transfer |
Which Words | # Which words
ww_responses = gc.open_by_url('https://docs.google.com/spreadsheets/d/1bRoF5l8Lt9fqeOki_YrJffd2XwEpROKi1RUsbC1umIk/edit#gid=1233025762')
ww_response_sheet = ww_responses.sheet1
ww_reponse_data = ww_response_sheet.get_all_values()
ww_answer_dict = {}
for idx, row in enumerate(ww_reponse_data[1:]):
if r... |
Classification examples where both human + cls agree style is transferred
---------------------------------------- [15] ----------------------------------------
but can not complain too much it was super cheap
but can not complain barely little it was super cheap
they are not the best in the series and anyone can cle... | Apache-2.0 | evaluation/all_evaluation.ipynb | cs-mac/Unsupervised_Style_Transfer |
说明: 删除最小数量的无效括号,以使输入字符串有效。 返回所有可能的结果。 注意: 输入字符串可能包含除括号(和)以外的其他字母。Example 1: Input: "()())()" Output: ["()()()", "(())()"]Example 2: Input: "(a)())()" Output: ["(a)()()", "(a())()"]Example 3: Input: ")(" Output: [""] | class Solution:
def removeInvalidParentheses(self, s: str):
if not s: return []
self.max_len = self.get_max_len(s)
self.ans = []
self.dfs(s, 0, "", 0)
return self.ans
def dfs(self, s, idx, cur_str, count):
if len(cur_str) > self.max_len: return
if co... | _____no_output_____ | Apache-2.0 | DFS/1010/301. Remove Invalid Parentheses.ipynb | YuHe0108/Leetcode |
Outro **Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs** Video 1 | # @markdown
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
... | _____no_output_____ | CC-BY-4.0 | tutorials/W2D1_DeepLearning/W2D1_Outro.ipynb | Beilinson/course-content |
Video 2 | # @markdown
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id... | _____no_output_____ | CC-BY-4.0 | tutorials/W2D1_DeepLearning/W2D1_Outro.ipynb | Beilinson/course-content |
Daily surveyDon't forget to complete your reflections and content check in the daily survey! Please be patient after logging in as there isa small delay before you will be redirected to the survey. Slides | # @markdown
from IPython.display import IFrame
IFrame(src=f"https://mfr.ca-1.osf.io/render?url=https://osf.io/z5g93/?direct%26mode=render%26action=download%26mode=render", width=854, height=480) | _____no_output_____ | CC-BY-4.0 | tutorials/W2D1_DeepLearning/W2D1_Outro.ipynb | Beilinson/course-content |
Suicide Analysis in IndiaIn this notebook we will try to understand what might be the different reasons due to which people committed suicide in India (using the dataset "Suicides in India"). Almost 11,89,068 people committed suicide in 2012 alone, it is quite important to understand why they commit suicide and try to... | # import lib
import numpy as np #for math operations
import pandas as pd#for data manipulation
import plotly.express as px#for better visualization
import plotly.io as pio
# read dataset
data = pd.read_csv('../input/suicides-in-india/Suicides in India 2001-2012.csv')
data.tail(10) | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Dataset Information | data.info() | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Check Missing & Null Values | data.isna().sum() | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
People committed suicide from 2001-2012 | print("Total cases from 2001-12: \n",data.groupby("Year")["Total"].sum())
data.groupby("Year")["Total"].sum().plot(kind="line",marker="o",title="People Commited Suicide From 2001-2012") | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
States Present Inside DatasetThis step is for merging states with same name and remove redundency. | data["State"].value_counts() | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Remove rows with value as Total (States), Total (All India) or Total (Uts) | data = data[(data["State"]!="Total (States)")&(data["State"]!="Total (Uts)")&(data["State"]!="Total (All India)") ] | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Which Gender with Highest number of suicide? Males are commiting more sucides in comaprision to females | filter_gender = pd.DataFrame(data.groupby("Gender")["Total"].sum()).reset_index()
px.bar(filter_gender,x="Gender", y="Total",color="Gender") | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
States with Higher Suicide cases1. Maharashtra2. West Bengal3. Tamil Nadu4. Andhra Pradesh | pio.templates.default = "plotly_dark"
filter_state = pd.DataFrame(data.groupby(["State"])["Total"].sum()).reset_index()
px.bar(filter_state,x = 'State', y = 'Total',color="State")
| _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Number of cases changing over time Changing Rate of sucides over time | grouped_year = data.groupby(["Year","Gender"])["Total"].sum()
grouped_year = pd.DataFrame(grouped_year).reset_index()
# grouped_year
px.line(grouped_year,x="Year", y="Total", color="Gender") | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Number of cases based on the reasons they committed suicide | filter_type_code = pd.DataFrame(data.groupby(["Type_code","Year"])["Total"].sum()).reset_index()
filter_type_code
px.bar(filter_type_code,x="Type_code", y="Total",color="Year") | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Which social issues causes more suicides?It is clear that **married people** are more Suicides.Which makes sense because marriage issues may cause conflict between the couple and as a result they might be prone to commit suicide. | filter_social_status = pd.DataFrame(data[data["Type_code"]=="Social_Status"].groupby(["Type","Gender"])["Total"].sum()).reset_index()
px.bar(filter_social_status,x="Type", y="Total",color="Gender") | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Education status of people who committed suicidespeople with low education are commiting more suicide.People with Diploma and Graduate tend to commit least no. of suicide | filter_social_status = pd.DataFrame(data[data["Type_code"]=="Education_Status"].groupby(["Type","Gender"])["Total"].sum()).reset_index()
fig = px.bar(filter_social_status,x="Type", y="Total",color="Gender")
fig.show(rotation=90) | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Profession of the people who committed suicides**Farmers** and **housewives** have commited more suicide compared to others.This makes sense because most of the Indian farmers have debt and their life depends on the yield of their crops, if the yield is not good then they will not be able to clear their debt and in th... | filter_social_status = pd.DataFrame(data[data["Type_code"]=="Professional_Profile"].groupby(["Type","Gender"])["Total"].sum()).reset_index()
fig2 = px.bar(filter_social_status,x="Type", y="Total",color="Gender")
fig2.show(rotation=90) | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Which age group people have commited most Suicides?From the below visualization it is clear that youngsters (15-29 age) and middle age (30-44) tend to commit the maximum number of suicides.It can be due to several reasons like:* unemployment* academic stress* bad friend circle* farmers (since they have to be young and... | # age group 0-100+ encapsulates all the remaining age groups, hence it would make sense to drop it
import matplotlib.pyplot as plt #for visualization
import seaborn as sns
%matplotlib inline
sns.set(rc={'figure.figsize':(11.7,8.27)})
sns.set_palette("BrBG")
filter_age = data[data["Age_group"]!="0-100+"]
sns.catplot(x="... | _____no_output_____ | Apache-2.0 | Suicide Analysis in India.ipynb | Ayush810/Sucide-Analysis-India-From-2001-to-2012 |
Example notebook to show Github IntegrationThis notebook in the `treebeard` master branch is here so treebeard can run against this project and show the Github App Integration. Github Integration can be added to any project in the settings of the admin page when a project is built. The CLI returns the link to the ad... | assert 1 + 1 == 2 | _____no_output_____ | Apache-2.0 | main.ipynb | pombredanne/treebeard |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.