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
Let's merge the mask and depths
merged = train_mask.merge(depth, how='left') merged.head() plt.figure(figsize=(12, 6)) plt.scatter(merged['salt_proportion'], merged['z']) plt.title('Proportion of salt vs depth') print("Correlation: ", np.corrcoef(merged['salt_proportion'], merged['z'])[0, 1])
Correlation: 0.10361580365557428
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Setup Keras and Train
from keras.models import Model, load_model from keras.layers import Input from keras.layers.core import Lambda, RepeatVector, Reshape from keras.layers.convolutional import Conv2D, Conv2DTranspose from keras.layers.pooling import MaxPooling2D from keras.layers.merge import concatenate from keras.callbacks import EarlyS...
replace test/images/8cf16aa0f5.png? [y]es, [n]o, [A]ll, [N]one, [r]ename: N
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
PredictRef: https://www.kaggle.com/jesperdramsch/intro-to-seismic-salt-and-how-to-geophysics
path_test='./test/' test_ids = next(os.walk(path_test+"images"))[2] X_test = np.zeros((len(test_ids), im_height, im_width, im_chan), dtype=np.uint8) X_test_feat = np.zeros((len(test_ids), n_features), dtype=np.float32) sizes_test = [] print('Getting and resizing test images ... ') sys.stdout.flush() for n, id_ in tq...
Successfully submitted to TGS Salt Identification Challenge
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
PredictRef: https://www.kaggle.com/shaojiaxin/u-net-with-simple-resnet-blocks
callbacks = [ EarlyStopping(patience=5, verbose=1), ReduceLROnPlateau(patience=3, verbose=1), ModelCheckpoint('model-tgs-salt-new-1.h5', verbose=1, save_best_only=True, save_weights_only=True) ] #results = model.fit({'img': [X_train, X_train], 'feat': X_feat_train}, y_train, batch_size=16, epochs=50, callba...
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Save output to drive
from google.colab import drive drive.mount('/content/gdrive') !ls /content/gdrive/My\ Drive/kaggle_competitions !cp model-tgs-salt-1.h5 /content/gdrive/My\ Drive/kaggle_competitions/tgs_salt/ !cp model-tgs-salt-2.h5 /content/gdrive/My\ Drive/kaggle_competitions/tgs_salt/ !cp submission.csv /content/gdrive/My\ Drive/kag...
_____no_output_____
MIT
kaggle_tgs_salt_identification.ipynb
JacksonIsaac/colab_notebooks
Laboratory 18: Linear Regression Full name: R: HEX: Title of the notebook Date: ![](https://i.pinimg.com/originals/5f/d5/58/5fd558f8b7a4f9e2138709cbe63c7052.gif) The human brain is amazing and mysterious in many ways. Have a look at these sequences. You, with the assistance of your brain, can guess the next ite...
# Load the necessary packages import numpy as np import pandas as pd import statistics from matplotlib import pyplot as plt # Create a dataframe: time = [0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] speed = [0, 3, 7, 12, 20, 30, 45.6, 60.3, 77.7, 97.3, 121.2] data = pd.DataFrame({'Time':time, 'Speed':speed})...
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
Now, let's explore the data:
data.describe() time_var = statistics.variance(time) speed_var = statistics.variance(speed) print("Variance of recorded times is ",time_var) print("Variance of recorded times is ",speed_var)
Variance of recorded times is 11.0 Variance of recorded times is 1697.7759999999998
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
Is there a relationship ( based on covariance, correlation) between time and speed?
# To find the covariance data.cov() # To find the correlation among the columns # using pearson method data.corr(method ='pearson')
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
Let's do linear regression with primitive Python: To estimate "y" using the OLS method, we need to calculate "xmean" and "ymean", the covariance of X and y ("xycov"), and the variance of X ("xvar") before we can determine the values for alpha and beta. In our case, X is time and y is Speed.
# Calculate the mean of X and y xmean = np.mean(time) ymean = np.mean(speed) # Calculate the terms needed for the numator and denominator of beta data['xycov'] = (data['Time'] - xmean) * (data['Speed'] - ymean) data['xvar'] = (data['Time'] - xmean)**2 # Calculate beta and alpha beta = data['xycov'].sum() / data['xvar...
alpha = -16.78636363636363 beta = 11.977272727272727
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
We now have an estimate for alpha and beta! Our model can be written as Yₑ = 11.977 X -16.786, and we can make predictions:
X = np.array(time) ypred = alpha + beta * X print(ypred)
[-16.78636364 -4.80909091 7.16818182 19.14545455 31.12272727 43.1 55.07727273 67.05454545 79.03181818 91.00909091 102.98636364]
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
Let’s plot our prediction ypred against the actual values of y, to get a better visual understanding of our model:
# Plot regression against actual data plt.figure(figsize=(12, 6)) plt.plot(X, ypred, color="red") # regression line plt.plot(time, speed, 'ro', color="blue") # scatter plot showing actual data plt.title('Actual vs Predicted') plt.xlabel('Time (s)') plt.ylabel('Speed (m/s)') plt.show()
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
The red line is our line of best fit, Yₑ = 11.977 X -16.786. We can see from this graph that there is a positive linear relationship between X and y. Using our model, we can predict y from any values of X! For example, if we had a value X = 20, we can predict that:
ypred_20 = alpha + beta * 20 print(ypred_20)
222.7590909090909
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
Linear Regression with statsmodels: First, we use statsmodels’ ols function to initialise our simple linear regression model. This takes the formula y ~ X, where X is the predictor variable (Time) and y is the output variable (Speed). Then, we fit the model by calling the OLS object’s fit() method.
import statsmodels.formula.api as smf # Initialise and fit linear regression model using `statsmodels` model = smf.ols('Speed ~ Time', data=data) model = model.fit()
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
We no longer have to calculate alpha and beta ourselves as this method does it automatically for us! Calling model.params will show us the model’s parameters:
model.params
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
In the notation that we have been using, α is the intercept and β is the slope i.e. α =-16.786364 and β = 11.977273.
# Predict values speed_pred = model.predict() # Plot regression against actual data plt.figure(figsize=(12, 6)) plt.plot(data['Time'], data['Speed'], 'o') # scatter plot showing actual data plt.plot(data['Time'], speed_pred, 'r', linewidth=2) # regression line plt.xlabel('Time (s)') plt.ylabel('Speed (m/s)...
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
How good do you feel about this predictive model? Will you trust it? Example 2: Advertising and Sells! This is a classic regression problem. we have a dataset of the spendings on TV, Radio, and Newspaper advertisements and number of sales for a specific product. We are interested in exploring the relationship betwee...
# Import and display first rows of the advertising dataset df = pd.read_csv('advertising.csv') df.head() # Describe the df df.describe() tv = np.array(df['TV']) radio = np.array(df['Radio']) newspaper = np.array(df['Newspaper']) newspaper = np.array(df['Sales']) # Get Variance and Covariance - What can we infer? df.co...
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
![](https://media2.giphy.com/media/5nj4ZZWl6QwneEaBX4/source.gif) *This notebook was inspired by a several blogposts including:* - __"Introduction to Linear Regression in Python"__ by __Lorraine Li__ available at* https://towardsdatascience.com/introduction-to-linear-regression-in-python-c12a072bedf0 - __"In Depth: Lin...
# Step1: vdf = pd.read_csv('CarsDF.csv') vdf.head() vdf.describe()
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
On Step1: [Double-Click to edit]
# Step2:. vdf.corr()
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
On Step2: [Double-Click to edit]
#Step3: # Calculate the mean of X and y xmean = np.mean(vdf['Age']) ymean = np.mean(vdf['selling_price']) # Calculate the terms needed for the numator and denominator of beta vdf['xycov'] = (vdf['Age'] - xmean) * (vdf['selling_price'] - ymean) vdf['xvar'] = (vdf['Age'] - xmean)**2 # Calculate beta and alpha beta = vd...
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
On Step3: [Double-Click to edit]
# Step4: import statsmodels.formula.api as smf # Initialise and fit linear regression model using `statsmodels` model = smf.ols('selling_price ~ FuelEconomy_kmpl', data=vdf) model = model.fit() model.params # Predict values FE_pred = model.predict() # Plot regression against actual data plt.figure(figsize=(12, 6)) pl...
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
On Step4: [Double-Click to edit]
# Step5: import statsmodels.formula.api as smf # Initialise and fit linear regression model using `statsmodels` model = smf.ols('selling_price ~ engine_v', data=vdf) model = model.fit() model.params # Predict values EV_pred = model.predict() # Plot regression against actual data plt.figure(figsize=(12, 6)) plt.plot(v...
_____no_output_____
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
On Step5: [Double-Click to edit] On Step6: [Double-Click to edit]
#Step7: # Multiple Linear Regression with scikit-learn: from sklearn.linear_model import LinearRegression # Build linear regression model using TV,Radio and Newspaper as predictors # Split data into predictors X and output Y predictors = ['Age', 'km_driven', 'FuelEconomy_kmpl','engine_p','engine_v'] X = vdf[predictors...
[900102.89014124]
CC0-1.0
1-Lessons/Lesson19/Lab19/.src/Lab19_WS.ipynb
dustykat/engr-1330-psuedo-course
Import packages
import os import sys import time from datetime import datetime import GPUtil import psutil ####################### # run after two days # time.sleep(172800) ####################### os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3" sys.path.append("../") def gpu_free(max_gb): gpu_id = GPUtil.getFirstAvailable( ...
-- total_GPU_memory: 10.761GB;init_GPU_memoryFree:10.760GB init_GPU_load:0.000% GPU_memoryUtil:0% GPU_memoryUsed:0.001GB GPU memery and main memery availale, start a job -- total_GPU_memory: 10.761GB;init_GPU_memoryFree:10.757GB init_GPU_load:0.000% GPU_memoryUtil:0% GPU_memoryUsed:0.004GB GPU memery and main memery av...
MIT
demo_control_side_sep_16.ipynb
mengzaiqiao/TVBR
Checking whether the files are scanned images or true pdfs
def is_image(file_path): with open(file_path, "rb") as f: return pdftotext.PDF(f) print(is_image(filename))
_____no_output_____
FTL
tasks/extract_text/notebooks/text_preprocessing_jordi.ipynb
jordiplanascuchi/policy-data-analyzer
Converting pdf to image files and improving quality
def get_image1(file_path): """Get image out of pdf file_path. Splits pdf file into PIL images of each of its pages. """ return convert_from_path(file_path, 500) # Performance tips according to pdf2image: # Using an output folder is significantly faster if you are using an SSD. Otherwise i/o usually becomes the ...
_____no_output_____
FTL
tasks/extract_text/notebooks/text_preprocessing_jordi.ipynb
jordiplanascuchi/policy-data-analyzer
What can we do here to improve image quality? It already seems pretty good! Evaluating extraction time from each method and saving text to disk
def export_ocr(text, file, extract, out=out_path): """ Export ocr output text using extract method to file at out """ filename = f'{os.path.splitext(os.path.basename(file))[0]}_{extract}.txt' with open(os.path.join(out, filename), 'w') as the_file: the_file.write(text) def wrap_pagenum(page_text, page_num)...
_____no_output_____
FTL
tasks/extract_text/notebooks/text_preprocessing_jordi.ipynb
jordiplanascuchi/policy-data-analyzer
It seems that the pytesseract package provides the fastest extraction and by looking at the extracted text it doesn't seem to exist any difference in the output of all the tested methods.
# comparison between text extracted by the different methods os.listdir(out_path) # TODO: perform a more programatical comparison between extracted texts
_____no_output_____
FTL
tasks/extract_text/notebooks/text_preprocessing_jordi.ipynb
jordiplanascuchi/policy-data-analyzer
Let's look at the extracted text
with open(os.path.join(out_path, 'Decreto_ejecutivo_57_pytesseract.txt')) as text: extracted_text = text.read() extracted_text # Replace \x0c (page break) by \n # Match 1 or more occurrences of \n if preceeded by one occurrence of \n OR # Match 1 or more occurrences of \s (whitespace) if preceeded by one occurrence ...
_____no_output_____
FTL
tasks/extract_text/notebooks/text_preprocessing_jordi.ipynb
jordiplanascuchi/policy-data-analyzer
CS109A Introduction to Data Science Standard Section 3: Multiple Linear Regression and Polynomial Regression **Harvard University****Fall 2019****Instructors**: Pavlos Protopapas, Kevin Rader, and Chris Tanner**Section Leaders**: Marios Mattheakis, Abhimanyu (Abhi) Vasishth, Robbert (Rob) Struyven
#RUN THIS CELL import requests from IPython.core.display import HTML styles = requests.get("http://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/cs109.css").text HTML(styles)
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
For this section, our goal is to get you familiarized with Multiple Linear Regression. We have learned how to model data with kNN Regression and Simple Linear Regression and our goal now is to dive deep into Linear Regression.Specifically, we will: - Load in the titanic dataset from seaborn- Learn a few ways to plo...
# Data and Stats packages import numpy as np import pandas as pd # Visualization packages import matplotlib.pyplot as plt import seaborn as sns sns.set()
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Extending Linear Regression Working with the Titanic Dataset from SeabornFor our dataset, we'll be using the passenger list from the Titanic, which famously sank in 1912. Let's have a look at the data. Some descriptions of the data are at https://www.kaggle.com/c/titanic/data, and here's [how seaborn preprocessed it](...
# Load the dataset from seaborn titanic = sns.load_dataset("titanic") titanic.head() # checking for null values chosen_vars = ['age', 'sex', 'class', 'embark_town', 'alone', 'fare'] titanic = titanic[chosen_vars] titanic.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 6 columns): age 714 non-null float64 sex 891 non-null object class 891 non-null category embark_town 889 non-null object alone 891 non-null bool fare 891 non-null float64 dtyp...
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
**Exercise**: check the datatypes of each column and display the statistics (min, max, mean and any others) for all the numerical columns of the dataset.
## your code here # %load 'solutions/sol1.py' print(titanic.dtypes) titanic.describe()
age float64 sex object class category embark_town object alone bool fare float64 dtype: object
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
**Exercise**: drop all the non-null *rows* in the dataset. Is this always a good idea?
## your code here # %load 'solutions/sol2.py' titanic = titanic.dropna(axis=0) titanic.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 712 entries, 0 to 890 Data columns (total 6 columns): age 712 non-null float64 sex 712 non-null object class 712 non-null category embark_town 712 non-null object alone 712 non-null bool fare 712 non-null float64 dtyp...
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Now let us visualize the response variable. A good visualization of the distribution of a variable will enable us to answer three kinds of questions:- What values are central or typical? (e.g., mean, median, modes)- What is the typical spread of values around those central values? (e.g., variance/stdev, skewness)- What...
fig, ax = plt.subplots(1, 3, figsize=(24, 6)) ax = ax.ravel() sns.distplot(titanic['fare'], ax=ax[0]) # use seaborn to draw distributions ax[0].set_title('Seaborn distplot') ax[0].set_ylabel('Normalized frequencies') sns.violinplot(x='fare', data=titanic, ax=ax[1]) ax[1].set_title('Seaborn violin plot') ax[1].set_yla...
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
How do we interpret these plots? Train-Test Split
from sklearn.model_selection import train_test_split titanic_train, titanic_test = train_test_split(titanic, train_size=0.7, random_state=99) titanic_train = titanic_train.copy() titanic_test = titanic_test.copy() print(titanic_train.shape, titanic_test.shape)
(498, 6) (214, 6)
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Simple one-variable OLS **Exercise**: You've done this before: make a simple model using the OLS package from the statsmodels library predicting **fare** using **age** using the training data. Name your model `model_1` and display the summary
from statsmodels.api import OLS import statsmodels.api as sm # Your code here # %load 'solutions/sol3.py' age_ca = sm.add_constant(titanic_train['age']) model_1 = OLS(titanic_train['fare'], age_ca).fit() model_1.summary()
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Dealing with different kinds of variables In general, you should be able to distinguish between three kinds of variables: 1. Continuous variables: such as `fare` or `age`2. Categorical variables: such as `sex` or `alone`. There is no inherent ordering between the different values that these variables can take on. Thes...
titanic_orig = titanic_train.copy()
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Let us now examine the `sex` column and see the value counts.
titanic_train['sex'].value_counts()
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
**Exercise**: Create a column `sex_male` that is 1 if the passenger is male, 0 if female. The value counts indicate that these are the two options in this particular dataset. Ensure that the datatype is `int`.
# your code here # %load 'solutions/sol4.py' # functions that help us create a dummy variable stratify titanic_train['sex_male'].value_counts()
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Do we need a `sex_female` column, or a `sex_others` column? Why or why not?Now, let us look at `class` in greater detail.
titanic_train['class_Second'] = (titanic_train['class'] == 'Second').astype(int) titanic_train['class_Third'] = 1 * (titanic_train['class'] == 'Third') # just another way to do it titanic_train.info() # This function automates the above: titanic_train_copy = pd.get_dummies(titanic_train, columns=['sex', 'class'], drop_...
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Linear Regression with More Variables **Exercise**: Fit a linear regression including the new sex and class variables. Name this model `model_2`. Don't forget the constant!
# your code here # %load 'solutions/sol5.py' model_2 = sm.OLS(titanic_train['fare'], sm.add_constant(titanic_train[['age', 'sex_male', 'class_Second', 'class_Third']])).fit() model_2.summary()
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Interpreting These Results 1. Which of the predictors do you think are important? Why?2. All else equal, what does being male do to the fare? Going back to the example from class![male_female](../fig/male_female.png)3. What is the interpretation of $\beta_0$ and $\beta_1$? Exploring Interactions
sns.lmplot(x="age", y="fare", hue="sex", data=titanic_train, size=6)
/anaconda3/envs/109a/lib/python3.7/site-packages/seaborn/regression.py:546: UserWarning: The `size` paramter has been renamed to `height`; please update your code. warnings.warn(msg, UserWarning)
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
The slopes seem to be different for male and female. What does that indicate?Let us now try to add an interaction effect into our model.
# It seemed like gender interacted with age and class. Can we put that in our model? titanic_train['sex_male_X_age'] = titanic_train['age'] * titanic_train['sex_male'] model_3 = sm.OLS( titanic_train['fare'], sm.add_constant(titanic_train[['age', 'sex_male', 'class_Second', 'class_Third', 'sex_male_X_age']]) )...
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
**What happened to the `age` and `male` terms?**
# It seemed like gender interacted with age and class. Can we put that in our model? titanic_train['sex_male_X_class_Second'] = titanic_train['age'] * titanic_train['class_Second'] titanic_train['sex_male_X_class_Third'] = titanic_train['age'] * titanic_train['class_Third'] model_4 = sm.OLS( titanic_train['fare'],...
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Polynomial Regression ![poly](../fig/poly.png) Perhaps we now believe that the fare also depends on the square of age. How would we include this term in our model?
fig, ax = plt.subplots(figsize=(12,6)) ax.plot(titanic_train['age'], titanic_train['fare'], 'o') x = np.linspace(0,80,100) ax.plot(x, x, '-', label=r'$y=x$') ax.plot(x, 0.04*x**2, '-', label=r'$y=c x^2$') ax.set_title('Plotting Age (x) vs Fare (y)') ax.set_xlabel('Age (x)') ax.set_ylabel('Fare (y)') ax.legend();
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
**Exercise**: Create a model that predicts fare from all the predictors in `model_4` + the square of age. Show the summary of this model. Call it `model_5`. Remember to use the training data, `titanic_train`.
# your code here # %load 'solutions/sol6.py' titanic_train['age^2'] = titanic_train['age'] **2 model_5 = sm.OLS( titanic_train['fare'], sm.add_constant(titanic_train[['age', 'sex_male', 'class_Second', 'class_Third', 'sex_male_X_age', 'sex_male_X_class_Second', 'sex_male_X_class_...
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Looking at All Our Models: Model Selection What has happened to the $R^2$ as we added more features? Does this mean that the model is better? (What if we kept adding more predictors and interaction terms? **In general, how should we choose a model?** We will spend a lot more time on model selection and learn about way...
models = [model_1, model_2, model_3, model_4, model_5] fig, ax = plt.subplots(figsize=(12,6)) ax.plot([model.df_model for model in models], [model.rsquared for model in models], 'x-') ax.set_xlabel("Model degrees of freedom") ax.set_title('Model degrees of freedom vs training $R^2$') ax.set_ylabel("$R^2$");
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
**What about the test data?**We added a lot of columns to our training data and must add the same to our test data in order to calculate $R^2$ scores.
# Added features for model 1 # Nothing new to be added # Added features for model 2 titanic_test = pd.get_dummies(titanic_test, columns=['sex', 'class'], drop_first=True) # Added features for model 3 titanic_test['sex_male_X_age'] = titanic_test['age'] * titanic_test['sex_male'] # Added features for model 4 titanic_...
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
**Calculating R^2 scores**
from sklearn.metrics import r2_score r2_scores = [] y_preds = [] y_true = titanic_test['fare'] # model 1 y_preds.append(model_1.predict(sm.add_constant(titanic_test['age']))) # model 2 y_preds.append(model_2.predict(sm.add_constant(titanic_test[['age', 'sex_male', 'class_Second', 'class_Third']]))) # model 3 y_pred...
/anaconda3/envs/109a/lib/python3.7/site-packages/numpy/core/fromnumeric.py:2389: FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead. return ptp(axis=axis, out=out, **kwargs)
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Regression Assumptions. Should We Even Regress Linearly? ![linear regression](../fig/linear_regression.png) **Question**: What are the assumptions of a linear regression model? We find that the answer to this question can be found on closer examimation of $\epsilon$. What is $\epsilon$? It is assumed that $\epsilon$ i...
# your code here # %load 'solutions/sol7.py' # %load 'solutions/sol7.py' predictors = sm.add_constant(titanic_train[['age', 'sex_male', 'class_Second', 'class_Third', 'sex_male_X_age', 'sex_male_X_class_Second', 'sex_male_X_class_Third', 'age^2']]) y_hat = model_5.predict(predicto...
Mean of residuals: 4.784570776163707e-13
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
**What can you say about the assumptions of the model?** ---------------- End of Standard Section--------------- Extra: Visual exploration of predictors' correlationsThe dataset for this problem contains 10 simulated predictors and a response variable.
# read in the data data = pd.read_csv('../data/dataset3.txt') data.head() # this effect can be replicated using the scatter_matrix function in pandas plotting sns.pairplot(data);
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Predictors x1, x2, x3 seem to be perfectly correlated while predictors x4, x5, x6, x7 seem correlated.
data.corr() sns.heatmap(data.corr())
_____no_output_____
MIT
content/sections/section3/notebook/cs109a_section_3.ipynb
lingcog/2019-CS109A
Count all the words
wordcounter = Counter({}) words_per_video = [] for ann_idx, ann_file in enumerate(all_annotations): file = open(ann_file, "r") words = file.read().split() file.close() current_wordcounter = Counter(words) wordcounter += current_wordcounter words_per_video.append(len(words))
_____no_output_____
MIT
Get Stats.ipynb
jrterven/lip_reading_dataset
Some stats
print("Number of words:", len(wordcounter)) print("10 most common words:") print(wordcounter.most_common(10)) print("Max words in a video:", max(words_per_video)) print("Min words in a video:", min(words_per_video)) words_per_video_counter = Counter(words_per_video) print(words_per_video_counter)
Counter({11: 762, 12: 746, 9: 662, 10: 650, 13: 643, 8: 602, 5: 601, 4: 592, 7: 570, 6: 549, 14: 524, 3: 513, 2: 438, 15: 380, 1: 329, 16: 267, 17: 179, 18: 92, 19: 35, 20: 21, 21: 15, 22: 8, 23: 2, 25: 1, 24: 1})
MIT
Get Stats.ipynb
jrterven/lip_reading_dataset
hp tuning
# LogisticRegression, L1 logreg = LogisticRegression(penalty='l1',solver='saga',random_state=0,max_iter=10000) grid = {'C': np.logspace(-5, 5, 11)} #predefined splits #gs = GridSearchCV(logreg, grid, cv=ps.split(),scoring='accuracy') gs = GridSearchCV(logreg, grid, cv=ps.split(),scoring=['roc_auc','average_precision']...
_____no_output_____
MIT
models/Linear_ensemble/hyperparameter tuning/linear model_new_classification-seq only.ipynb
jingyi7777/CasRx_guide_efficiency
Test models
def classification_analysis(model_name, split, y_pred,y_true): test_df = pd.DataFrame(list(zip(list(y_pred), list(y_true))), columns =['predicted_value', 'true_binary_label']) thres_list = [0.8, 0.9,0.95] tp_thres = [] #print('thres_stats') for thres in thres_list: df_pre...
test: ['RPL31', 'RPS3A', 'CSE1L', 'XAB2', 'PSMD7', 'SUPT6H'] test: ['EEF2', 'RPS11', 'SNRPD2', 'RPL37', 'SF3B3', 'DDX51'] test: ['RPL7', 'RPS9', 'KARS', 'SF3A1', 'RPL32', 'PSMB2'] test: ['RPS7', 'EIF4A3', 'U2AF1', 'PSMA1', 'PHB', 'POLR2D'] test: ['RPSA', 'RPL23A', 'NUP93', 'AQR', 'RPA2', 'SUPT5H'] test: ['RPL6', 'RPS13...
MIT
models/Linear_ensemble/hyperparameter tuning/linear model_new_classification-seq only.ipynb
jingyi7777/CasRx_guide_efficiency
Test functions
from utils.sparse import *
_____no_output_____
Apache-2.0
jnotebook/test utils sparse functions.ipynb
edervishaj/spotify-recsys-challenge
Function list 1. inplace_set_rows_zero_where_sum (X, op, cut) 2. inplace_set_cols_zero_where_sum (X, op, cut)3. inplace_set_rows_zero (X, target_rows)4. inplace_set_cols_zero (X, target_cols)5. inplace_row_scale (X, scale)6. inplace_col_scale (X, scale) 7. sum_cols (X)8. sum_rows (X)
m = sp.random(4,5,0.5).tocsr() m.data = np.ones(m.data.shape[0]) print(m.todense()) inplace_row_scale(m,np.array([1,2,3,4])) print (m.todense()) m = sp.random(4,5,0.5).tocsc() m.data = np.ones(m.data.shape[0]) print(m.todense()) inplace_col_scale(m,np.array([1,2,3,4,5])) print (m.todense()) m = sp.random(4,5,0.5).tocsr...
[1.96108189 1.12923879 0. 1.93997106 0.40970854] [[0. 0.69020914 0. 0. 0.40970854] [0. 0. 0. 0. 0. ] [0. 0. 0. 0. 0. ] [0. 0.43902965 0. 0. 0. ]]
Apache-2.0
jnotebook/test utils sparse functions.ipynb
edervishaj/spotify-recsys-challenge
Pivot table- excel에서 보던 것- index축은 groupby와 동일- column에 추가로 labeling값을 추가하여,- Value에 numeric type 값을 aggregation하는 형태
import dateutil df_phone = pd.read_csv("code/ch5/data/phone_data.csv") df_phone['date'] = df_phone['date'].apply(dateutil.parser.parse, dayfirst=True) df_phone.tail() df_phone.pivot_table(['duration'], index=['month','item'], columns=['network'], fill_value=0, aggfunc='sum')
_____no_output_____
MIT
inflearn_machine_learning/pandas/pandas_pivot_crosstab.ipynb
Junhojuno/TIL
Crosstab- 두 컬럼의 교차 빈도, 비율, 덧셈 등을 구할 때 사용- Pivot table의 특수한 형태- User-Item Rating Matrix 등을 만들 때 사용가능
df_movie = pd.read_csv("code/ch5/data/movie_rating.csv") df_movie.tail() # 평론가의 영화별 평점 pd.crosstab(values=df_movie.rating, index=df_movie.critic, columns=df_movie.title, aggfunc='first').fillna(0) # 이걸 groupby로 만들어보자.1 df_movie.groupby(['critic','title'])['rating'].first().unstack().fillna(0) # 이걸 groupby로 만들어보자.2 df_m...
_____no_output_____
MIT
inflearn_machine_learning/pandas/pandas_pivot_crosstab.ipynb
Junhojuno/TIL
MNIST Simple DEMO
import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms class Arguments: batch = 64 test_batch = 512 epochs = 10 lr = .01 momentum = .5 seed = 42 log_interval = 100 args = Arguments() class Ne...
Train Epoch: 1 [0/60000 (0%)] Loss: 2.309220 Train Epoch: 1 [6400/60000 (11%)] Loss: 0.545335 Train Epoch: 1 [12800/60000 (21%)] Loss: 0.417650 Train Epoch: 1 [19200/60000 (32%)] Loss: 0.353491 Train Epoch: 1 [25600/60000 (43%)] Loss: 0.306972 Train Epoch: 1 [32000/60000 (53%)] Loss: 0.133229 Train Epoch: 1 [38400/6000...
MIT
legacy/MNIST/lab.ipynb
MaybeS/mnist
Project 0: Inaugural project Labor Supply Problem Following labor supply problem is given: $$c^*,l^* = log(c) - v \frac{l^{1+\frac{1}{\epsilon}}}{1+\frac{1}{\epsilon}}\\x = m + wl - [\tau_0wl+\tau_1 \max(wl-\kappa,0)]\\c \in [0,x]\\l \in [0,1]\\$$Where: c is consumption,l is labor supply,m is cash-on-hand, w is the wa...
# All used packages are imported import numpy as np import sympy as sm from scipy import optimize t0 = sm.symbols('t_0') t1 = sm.symbols('t_1') m = 1 #cash-on-hand v = 10 #disutility of labor e = 0.3 #elasticity of labor supply t0 = 0.4 #standard labor income tax t1 = 0.1 #top bracket labor income tax k = 0.4 #c...
labour supply is:0.31961536193545265 consumption is:1.119903840483863 utility:0.09677772523865749
MIT
Project 1.ipynb
notnasobe666/BlackHatGang
Question 2
import matplotlib.pyplot as plt plt.style.use('grayscale') # Plot l_star and c_star with w going from 0.5 to 1.5 # The definitions are defined - the used packages is defined above N = 10000 w_vector = np.linspace(0.5,1.5,num=N) c_optimal = np.empty(N) l_optimal = np.empty(N) # a loop is generated to test the range ...
_____no_output_____
MIT
Project 1.ipynb
notnasobe666/BlackHatGang
Question 3
# Calculate the tax revenue tax_revenue = np.sum( t0 * w_vector * l_optimal + t1 * np.max( w_vector * l_optimal - k ,0 )) print('Total tax revenue is: ' + str(tax_revenue))
Total tax revenue is: 1775.3896759006836
MIT
Project 1.ipynb
notnasobe666/BlackHatGang
Question 4
# How does the tax revenue change when e = 0.1? # New epsilon is defined e_new = 0.1 l_optimal_e_new = np.empty(N) # Same loop is used as above but only a new labor # supply is calculated as consumption isn't included # in the tax revenue formula for i, w in enumerate(w_vector): optimization = optimizer(w,e_new,v...
New total tax revenue: 3578.900497991557 The difference in tax revenue is: 1803.5108220908735
MIT
Project 1.ipynb
notnasobe666/BlackHatGang
Question 5
# Optimize the tax # Same optimization formula as above def tax_optimize(t0,t1,k): tax_optimal = optimize.minimize_scalar(tax_revenue , method='bounded' , x=[0.1,0.1,0.1]) t0_optimal = tax_optimal.x t1_optimal = tax_optimal.x k_optimal = tax_optimal.x return t0_optimal, t1_optimal, k_optimal t0...
_____no_output_____
MIT
Project 1.ipynb
notnasobe666/BlackHatGang
Tic-Tac-Toe Agent​In this notebook, you will learn to build an RL agent (using Q-learning) that learns to play Numerical Tic-Tac-Toe with odd numbers. The environment is playing randomly with the agent, i.e. its strategy is to put an even number randomly in an empty cell. The following is the layout of the notebook: ...
# from <TC_Env> import <TicTacToe> - import your class from environment file from TCGame_Env import TicTacToe import collections import numpy as np import random import pickle import time from matplotlib import pyplot as plt from tqdm import tqdm # Function to convert state array into a string to store it as keys in th...
_____no_output_____
MIT
TicTacToe_Agent.ipynb
Chiragchhillar1/ML-TicTacToe
Epsilon-greedy strategy - Write your code here(you can build your epsilon-decay function similar to the one given at the end of the notebook)
# Defining epsilon-greedy policy. You can choose any function epsilon-decay strategy def epsilon_greedy(state, time): max_epsilon = 1.0 min_epsilon = 0.001 epsilon = min_epsilon + (max_epsilon - min_epsilon) * np.exp(-0.000001*time) z = np.random.random() if z > epsilon: action = max...
_____no_output_____
MIT
TicTacToe_Agent.ipynb
Chiragchhillar1/ML-TicTacToe
Tracking the state-action pairs for checking convergence - write your code here
# Initialise Q_dictionary as 'Q_dict' and States_tracked as 'States_track' (for convergence) Q_dict = collections.defaultdict(dict) States_track = collections.defaultdict(dict) print(len(Q_dict)) print(len(States_track)) # Initialise states to be tracked def initialise_tracking_states(): sample_q_values = [...
_____no_output_____
MIT
TicTacToe_Agent.ipynb
Chiragchhillar1/ML-TicTacToe
Define hyperparameters ---write your code here
EPISODES = 6000000 LR = 0.20 GAMMA = 0.8 threshold = 2540 checkpoint_print_episodes = 600000
_____no_output_____
MIT
TicTacToe_Agent.ipynb
Chiragchhillar1/ML-TicTacToe
Q-update loop ---write your code here
start_time = time.time() q_track={} q_track['x-3-x-x-x-6-x-x-x']=[] q_track['x-1-x-x-x-x-8-x-x']=[] q_track['x-x-x-x-6-x-x-x-5']=[] q_track['x-x-x-x-9-x-6-x-x']=[] q_track['x-5-x-2-x-x-4-7-x']=[] q_track['9-x-5-x-x-x-8-x-4']=[] q_track['2-7-x-x-6-x-x-3-x']=[] q_track['9-x-x-x-x-2-x-x-x']=[] q_track['x-x-7-x-x-x-x-x-2'...
_____no_output_____
MIT
TicTacToe_Agent.ipynb
Chiragchhillar1/ML-TicTacToe
Check the Q-dictionary
Q_dict len(Q_dict) # try checking for one of the states - that which action your agent thinks is the best -----This will not be evaluated Q_dict['x-x-5-x-x-x-x-x-4']
_____no_output_____
MIT
TicTacToe_Agent.ipynb
Chiragchhillar1/ML-TicTacToe
Check the states tracked for Q-values convergence(non-evaluative)
# Write the code for plotting the graphs for state-action pairs tracked plt.figure(0, figsize=(16,7)) plt.subplot(241) t1=States_track['x-3-x-x-x-6-x-x-x'][(0,1)] plt.title("(s,a)=('x-3-x-x-x-6-x-x-x',(0,1))") plt.plot(np.asarray(range(0, len(t1))),np.asarray(t1)) plt.subplot(242) t2=States_track['x-x-x-x-6-x-x-x-5'][...
_____no_output_____
MIT
TicTacToe_Agent.ipynb
Chiragchhillar1/ML-TicTacToe
Epsilon - decay check
max_epsilon = 1.0 min_epsilon = 0.001 time = np.arange(0,5000000) epsilon = [] for i in range(0,5000000): epsilon.append(min_epsilon + (max_epsilon - min_epsilon) * np.exp(-0.000001*i)) plt.plot(time, epsilon) plt.show()
_____no_output_____
MIT
TicTacToe_Agent.ipynb
Chiragchhillar1/ML-TicTacToe
[fnmatch](https://docs.python.org/3/library/fnmatch.html)1. What is fnmatch and why is it useful?1. Why should I use fnmatch and not regex?1. Two examplesFnmatch is part of the python standard library. Allows the use of UNIX style wildcards for string matching. Makes it easy to select a single file type out of a list ...
import fnmatch FILES = ["some_picture.png", "some_data.csv", "another_picture.png"] # select only the .png files for file in FILES: if fnmatch.fnmatch(file, '*.png'): print(file) # or using the fnmatch shorthand print(fnmatch.filter(FILES, '*.png'))
some_picture.png another_picture.png ['some_picture.png', 'another_picture.png']
MIT
2021-06-09-fnmatch.ipynb
phackstock/code-and-tell
*SIDE NOTE*: The matching is **case insensitive**, if you want to perform a case sensitive match use [`fnmatch.fnmatchcase()`](https://docs.python.org/3/library/fnmatch.htmlfnmatch.fnmatchcase) Match a list of patterns
MODELS = ["MESSAGEix-GLOBIOM 1.0", "MESSAGEix-GLOBIOM 1.1", "REMIND-MAgPIE 2.1-4.2", "REMIND-MAgPIE 1.7-3.2", "NIGEM", "POLES GECO2019", "COFFEE 1.0", "COFFEE 2.0", "TEA", "GCAM5.2", "GCAM5.3"] MATCH_MODELS = ["MESSAGEi...
MESSAGEix-GLOBIOM 1.0 MESSAGEix-GLOBIOM 1.1 REMIND-MAgPIE 2.1-4.2 REMIND-MAgPIE 1.7-3.2
MIT
2021-06-09-fnmatch.ipynb
phackstock/code-and-tell
Question 6:Write a code in python to display different functions of python module.
#module required import time print("I am Iron Man.") time.sleep(2.4)#this function delays the time print("I love you 3000.") #this statement is printed after 2.4 seconds import time # seconds passed since epoch seconds = 1545925769.9618232 local_time = time.ctime(seconds) print("Local time:", local_time)
_____no_output_____
MIT
Python/C6.ipynb
pooja-gera/TheWireUsChallenge
**3.d Formación de vectores****Responsable:**César Zamora Martínez**Infraestructura usada:** Google Colab, para pruebas 0. Importamos librerias necesarias**Fuente:** 3c_formacion_matrices.ipynb, 3c_formacion_abc.ipynb, 3c_formacion_delta.ipynb
!curl https://colab.chainer.org/install | sh - import cupy as cp def formar_vectores(mu, Sigma): ''' Calcula las cantidades u = \Sigma^{-1} \mu y v := \Sigma^{-1} \cdot 1 del problema de Markowitz Args: mu (cupy array, vector): valores medios esperados de activos (dimension n) Sigma (cupy array, matriz...
_____no_output_____
RSA-MD
notebooks/Programacion/3d_formacion_vectores.ipynb
izmfc/MNO_finalproject
1. Implementación**Consideraciones:**. Esta etapa supone que se conocen $\bar{r}$, $\mu$ y $\Sigma$ asociados a los activos, ello con el objeto de es obtener valores escalares que serán relevantes para obtener los pesos del portafolio para el inversionista. Hasta este punto se asume que ya conocemos todos los términos...
def formar_omegas(r, mu, Sigma): ''' Calcula las cantidades w_o y w_1 del problema de Markowitz (valores de multiplicadores de Lagrange) Args: r (cupy array, escalar): escalar que denota el retorno esperado por el inversionista mu (cupy array, vector): valores medios esperados de activos (dimension n) ...
_____no_output_____
RSA-MD
notebooks/Programacion/3d_formacion_vectores.ipynb
izmfc/MNO_finalproject
1.1 Valores de prueba
n= 10 # r y mu r= 10 mu=cp.random.rand(n, 1) # Sigma S=cp.random.rand(n, n) Sigma=S@S # multiplicadores de lagrande formar_omegas(r,mu,Sigma)
_____no_output_____
RSA-MD
notebooks/Programacion/3d_formacion_vectores.ipynb
izmfc/MNO_finalproject
OverviewThis notebook works on the IEEE-CIS Fraud Detection competition. Here I build a simple XGBoost model based on a balanced dataset. Lessons:. keep the categorical variables as single items. Use a high max_depth for xgboost (maybe 40) Ideas to try:. train divergence of expected value (eg. for TransactionAmt and ...
# all imports necessary for this notebook %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import random import gc import copy import missingno as msno import xgboost from xgboost import XGBClassifier, XGBRegressor from sklearn.model_selection import StratifiedKFold, cross_vali...
_____no_output_____
MIT
ieee-preprocess-v2-0-top-300.ipynb
tarekoraby/IEEE-CIS-Fraud-Detection
Load the iris data
import matplotlib.pyplot as plt %matplotlib inline from sklearn.datasets import load_iris from numpy.linalg import inv import pandas as pd import numpy as np iris = load_iris() iris['data'][:5,:] y = np.where(iris['target'] == 2, 1, 0) X = iris['data'] const = np.ones(shape=y.shape).reshape(-1,1) mat = np.concatena...
_____no_output_____
MIT
logistic-regression/gradient-descent-logistic-regression.ipynb
appliedecon/data602-lectures
Recall the algorithm we created for gradient descent for linear regressionUsing the following cost function:$$J(w)=\frac{1}{2}\sum(y^{(i)} - \hat{y}^{(i)})^2$$
import numpy as np def gradientDescent(x, y, theta, alpha, m, numIterations): thetaHistory = list() xTrans = x.transpose() costList = list() for i in range(0, numIterations): # data x feature weights = y_hat hypothesis = np.dot(x, theta) # how far we are off lo...
_____no_output_____
MIT
logistic-regression/gradient-descent-logistic-regression.ipynb
appliedecon/data602-lectures
For Logistic regression we replace with our likehihood function:$$J(w)=\sum{[-y^{(i)}log(\theta(z^{(i)}))-(1-y^{(i)})log(1-\theta(z^{(i)})]}$$ And add the sigmoid function to bound $y$ between 0 and 1
def gradientDescent(x, y, alpha, numIterations): def mle(y,yhat): ''' This replaces the mean squared error ''' return (-y.dot(np.log(yhat)) - ((1-y)).dot(np.log(1-yhat))) def sigmoid(z): ''' Transforms values to follow the sigmoid function and bound between 0...
_____no_output_____
MIT
logistic-regression/gradient-descent-logistic-regression.ipynb
appliedecon/data602-lectures
Let's try it out- Run the algorithm, which gives us the weight and cost history. - Plot the cost to see if it converges. - Make predictions with the last batch of weights. - Apply the sigmoid function to the above predictions. - Plot the actual vs. predicted values. - Plot the evolution of the weights for each ite...
iters = 500000 import datetime start_ts = datetime.datetime.now() betaHistory, costList = gradientDescent(mat, y, alpha=0.01, numIterations=iters) end_ts = datetime.datetime.now() print(f'Completed in {end_ts-start_ts}') # cost history plt.plot(costL...
Completed in 0:00:17.566409
MIT
logistic-regression/gradient-descent-logistic-regression.ipynb
appliedecon/data602-lectures
셀레니움을 이용한 네이버 블로그(검색창) 크롤러- 네이버 메인 검색 페이지에서 크롤링한다.
import platform print(platform.architecture()) !python --version pwd # 네이버에서 검색어 입력받아 검색 한 후 블로그 메뉴를 선택하고 # 오른쪽에 있는 검색옵션 버튼을 눌러서 # 정렬 방식과 기간을 입력하기 #Step 0. 필요한 모듈과 라이브러리를 로딩하고 검색어를 입력 받습니다. import sys import os import pandas as pd import numpy as np import math from bs4 import BeautifulSoup import requests import url...
_____no_output_____
MIT
naversearchCrawlerSelenium.ipynb
JeongCheck/Crawling
1 page = 7 posts72 page searchsample = https://section.blog.naver.com/Search/Post.naver?pageNo=1&rangeType=PERIOD&orderBy=sim&startDate=2019-01-01&endDate=2021-05-01&keyword=%EC%84%B1%EC%8B%AC%EB%8B%B9%EC%97%AC%ED%96%89%EB%8C%80%EC%A0%84
## 제목 눌러서 블로그 페이지 열기 driver.find_element_by_class_name('title').click() time.sleep(1) type(searched_post_num), searched_post_num import re re.sub('^[0-9]', '', searched_post_num) searched_post_num searched_post_num.replace(',', '').replace('건', '') total_page = math.ceil(int(searched_post_num.replace(',', '').strip('건'...
_____no_output_____
MIT
naversearchCrawlerSelenium.ipynb
JeongCheck/Crawling
{ 'mean': [axis1, axis2, flattened], 'variance': [axis1, axis2, flattened], 'standard deviation': [axis1, axis2, flattened], 'max': [axis1, axis2, flattened], 'min': [axis1, axis2, flattened], 'sum': [axis1, axis2, flattened]}
calculations['mean']= [a.mean(axis=0).tolist(), a.mean(axis=1).tolist(), a.mean().tolist()] calculations['mean'] calculations['variance']= [a.var(axis=0).tolist(), a.var(axis=1).tolist(), a.var().tolist()] calculations calculations['standard deviation']= [a.std(axis=0).tolist(), a.std(axis=1).tolist(), a.std().tolist()...
_____no_output_____
MIT
data_analysis/Mean-Variance-Standard Deviation Calculator.ipynb
alanpirotta/freecodecamp_certif
Torrent To Google Drive Downloader **Important Note:** To get more disk space:> Go to Runtime -> Change Runtime and give GPU as the Hardware Accelerator. You will get around 384GB to download any torrent you want. Install libtorrent and Initialize Session
!apt install python3-libtorrent import libtorrent as lt ses = lt.session() ses.listen_on(6881, 6891) downloads = []
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
abhibhaw/Torrent-To-Google-Drive-Downloader
Mount Google DriveTo stream files we need to mount Google Drive.
from google.colab import drive drive.mount("/content/drive")
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
abhibhaw/Torrent-To-Google-Drive-Downloader
Add From Torrent FileYou can run this cell to add more files as many times as you want
from google.colab import files source = files.upload() params = { "save_path": "/content/drive/My Drive/Torrent", "ti": lt.torrent_info(list(source.keys())[0]), } downloads.append(ses.add_torrent(params))
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
abhibhaw/Torrent-To-Google-Drive-Downloader
Add From Magnet LinkYou can run this cell to add more files as many times as you want
params = {"save_path": "/content/drive/My Drive/Torrent"} while True: magnet_link = input("Enter Magnet Link Or Type Exit: ") if magnet_link.lower() == "exit": break downloads.append( lt.add_magnet_uri(ses, magnet_link, params) )
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
abhibhaw/Torrent-To-Google-Drive-Downloader
Start DownloadSource: https://stackoverflow.com/a/5494823/7957705 and [3 issue](https://github.com/FKLC/Torrent-To-Google-Drive-Downloader/issues/3) which refers to this [stackoverflow question](https://stackoverflow.com/a/6053350/7957705)
import time from IPython.display import display import ipywidgets as widgets state_str = [ "queued", "checking", "downloading metadata", "downloading", "finished", "seeding", "allocating", "checking fastresume", ] layout = widgets.Layout(width="auto") style = {"description_width": "ini...
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
abhibhaw/Torrent-To-Google-Drive-Downloader
Analysis of enrichment
import glob import json import math import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from functools import reduce from collections import OrderedDict, defaultdict from sklearn.feature_extraction.text import TfidfVectorizer from scipy.stats import fisher_exact as fisher fro...
_____no_output_____
MIT
scripts/pathways_3_categorization.ipynb
iganna/evo_epigen
Collecting all pathway names
pathway_tables = glob.glob("../pathways/*/gp.csv") dfs = [pd.read_csv(table) for table in pathway_tables] for i, df in enumerate(dfs): dfs[i] = df.set_index("SYMBOL") dfs[i].sort_index(inplace=True) #print(dfs[i].shape) dfs[0] all_entries = list(pd.concat(dfs, axis=1, sort=True).columns) all_entries[0:10] s...
_____no_output_____
MIT
scripts/pathways_3_categorization.ipynb
iganna/evo_epigen
By histone tag:
my_tags = ["H3K4me3", "H3K9ac", "H3K27ac", "H3K27me3", "H3K9me3"] ENR_COUNTERS = dict() for hg_tag in my_tags: files_up_human = glob.glob(f"../extracted/Human_{hg_tag}_pathways_up*") files_down_human = glob.glob(f"../extracted/Human_{hg_tag}_pathways_down*") files_up_mouse = glob.glob(f"../extracted/Mouse_{...
_____no_output_____
MIT
scripts/pathways_3_categorization.ipynb
iganna/evo_epigen
Calculates a contingency table EASE score [x y] [z k] :param n_in_path: number of outliers in the pathway :param n_total_path: total number of genes in the pathway :param n_outliers: total number of outliers :param n_total: total number of genes analysed :return:
ksi = defaultdict(dict) signs = {"+": "positively\u00A0enriched\u00A0(+)", "-": "negatively\u00A0enriched\u00A0(-)"} for hg_tag in my_tags: enriched_counter = ENR_COUNTERS[hg_tag] for sign in ["+", "-"]: for org in ["Human", "Mouse"]: for category in enriched_counter: ...
_____no_output_____
MIT
scripts/pathways_3_categorization.ipynb
iganna/evo_epigen
Basic usage Thunder offers a variety of analyses and workflows for spatial and temporal data. When run on a cluster, most methods are efficiently and automatically parallelized, but Thunder can also be used on a single machine, especially for testing purposes. We'll walk through a very simple example here as an introd...
data = tsc.loadExample('fish-series')
_____no_output_____
Apache-2.0
python/doc/tutorials/src/basic_usage.ipynb
broxtronix/thunder
``data`` is a ``Series`` object, which is a generic collection of one-dimensional array data sharing a common index. We can inspect it to see metadata:
data
_____no_output_____
Apache-2.0
python/doc/tutorials/src/basic_usage.ipynb
broxtronix/thunder
A ``Series`` object is a collection of key-value records, each containing an identifier as a key and a one-dimensional array as a value. We can look at the first key and value by using ``first()``.
key, value = data.first()
_____no_output_____
Apache-2.0
python/doc/tutorials/src/basic_usage.ipynb
broxtronix/thunder