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 |
|---|---|---|---|---|---|
Processing test data | # add missing dummy variables to testing set
X_test = pd.get_dummies(test_df)
y_test = X_test['loan_status_high_risk']
X_test = X_test.drop(["loan_status_low_risk","loan_status_high_risk"],axis=1)
X_test['debt_settlement_flag_Y'] = 0
X_test
set(X_train.columns) - set(X_test.columns) | _____no_output_____ | ADSL | Credit Risk Evaluator.ipynb | yuqing8/Supervised-Machine-Learning-Homework---Predicting-Credit-Risk |
Consider the models I think the random Forest would perform better than logistic regression in this case. Because test dataset includes numerical value,such as installment, annual_inc,etc. "Since Logistic Regression depends on a calculation based on ‘weights’, numerical encoding of categorical variables can lead the a... | from sklearn.linear_model import LogisticRegression
classifier_lib = LogisticRegression(solver='liblinear', max_iter=10000)
classifier_lib
# Train the Logistic Regression model on the unscaled data and print the model score
classifier_lib.fit(X_train, y_train)
print(f"Training Data Score: {classifier_lib.score(X_train,... | Training Score: 1.0
Testing Score: 0.6165461505742237
| ADSL | Credit Risk Evaluator.ipynb | yuqing8/Supervised-Machine-Learning-Homework---Predicting-Credit-Risk |
1 - Installs and imports | !pip install --upgrade pip
!pip install sentencepiece
!pip install transformers
from transformers import AutoTokenizer, AutoModel, TFAutoModel, AutoConfig
from transformers import AutoModelForSequenceClassification
from transformers import TFAutoModelForSequenceClassification
from transformers import pipeline
import nu... | _____no_output_____ | Apache-2.0 | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t |
2 - Fetch XLM-T model | MODEL = "cardiffnlp/twitter-xlm-roberta-base"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModel.from_pretrained(MODEL) | _____no_output_____ | Apache-2.0 | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t |
Use Cases 1 - Compute Tweet Similarity | def preprocess(text):
new_text = []
for t in text.split(" "):
t = '@user' if t.startswith('@') and len(t) > 1 else t
t = 'http' if t.startswith('http') else t
new_text.append(t)
return " ".join(new_text)
def get_embedding(text):
text = preprocess(text)
encoded_input = tokeni... | Most similar to: Acabo de pedir pollo frito 🐣
----------------------------------------
1 Ci siamo divertiti! 🍝
2 Nous avons passé un bon moment! 🎥
3 We had a great time! ⚽️
4 We hebben een geweldige tijd gehad! ⛩
| Apache-2.0 | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t |
2 - Simple inference example (with `pipelines`) | model_path = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
sentiment_task = pipeline("sentiment-analysis", model=model_path, tokenizer=model_path)
sentiment_task("Huggingface es lo mejor! Awesome library 🤗😎") | _____no_output_____ | Apache-2.0 | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t |
3 - Experiment on UMSAB Fetch dataset (Spanish) | language = 'spanish'
files = """test_labels.txt
test_text.txt
train_labels.txt
train_text.txt
val_labels.txt
val_text.txt""".split('\n')
def fetch_data(language, files):
dataset = defaultdict(list)
for infile in files:
thisdata = infile.split('/')[-1].replace('.txt','')
dataset_url = f"https://raw.githubuserc... | _____no_output_____ | Apache-2.0 | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t |
Run full experiment | # load multilingual sentiment classifier
CUDA = True # set to true if using GPU (Runtime -> Change runtime Type -> GPU)
BATCH_SIZE = 32
MODEL = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
config = AutoConfig.from_pretrained(MODEL)
model = AutoModelForSequenceClassifi... | _____no_output_____ | Apache-2.0 | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t |
Two-Level: Sech Pulse 4π — Pulse Breakup Define the ProblemFirst we need to define a sech pulse with the area we want. We'll fix the width of the pulse and the area to find the right amplitude.The full-width at half maximum (FWHM) $t_s$ of the sech pulse is related to the FWHM of a Gaussian by a factor of $1/2.633915... | import numpy as np
SECH_FWHM_CONV = 1./2.6339157938
t_width = 1.0*SECH_FWHM_CONV # [τ]
print('t_width', t_width)
mb_solve_json = """
{
"atom": {
"fields": [
{
"coupled_levels": [[0, 1]],
"rabi_freq_t_args": {
"n_pi": 4.0,
"centre": 0.0,
"width": %f
},
... | _____no_output_____ | MIT | docs/examples/mbs-two-sech-4pi.ipynb | amcdawes/maxwellbloch |
We'll just check that the pulse area is what we want. | print('The input pulse area is {0}'.format(
np.trapz(mbs.Omegas_zt[0,0,:].real, mbs.tlist)/np.pi))
Omegas_zt, states_zt = mbs.mbsolve(recalc=False) | _____no_output_____ | MIT | docs/examples/mbs-two-sech-4pi.ipynb | amcdawes/maxwellbloch |
Plot Output | import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set_style('darkgrid')
fig = plt.figure(1, figsize=(16, 6))
ax = fig.add_subplot(111)
cmap_range = np.linspace(0.0, 3.0, 11)
cf = ax.contourf(mbs.tlist, mbs.zlist,
np.abs(mbs.Omegas_zt[0]/(2*np.pi)),
cmap_ra... | _____no_output_____ | MIT | docs/examples/mbs-two-sech-4pi.ipynb | amcdawes/maxwellbloch |
AnalysisThe $4 \pi$ sech pulse breaks up into two $2 \pi$ pulses, which travel at a speed according to their width. Movie | # C = 0.1 # speed of light
# Y_MIN = 0.0 # Y-axis min
# Y_MAX = 4.0 # y-axis max
# ZOOM = 2 # level of linear interpolation
# FPS = 60 # frames per second
# ATOMS_ALPHA = 0.2 # Atom indicator transparency
# FNAME = "images/mb-solve-two-sech-4pi"
# FNAME_JSON = FNAME + '.json'
# with open(FNAME_JSON, "w") as f:
# f.... | _____no_output_____ | MIT | docs/examples/mbs-two-sech-4pi.ipynb | amcdawes/maxwellbloch |
This notebook presents some code to compute some basic baselines.In particular, it shows how to:1. Use the provided validation set2. Compute the top-30 metric3. Save the predictions on the test in the right format for submission | %pylab inline --no-import-all
import os
from pathlib import Path
import pandas as pd
# Change this path to adapt to where you downloaded the data
DATA_PATH = Path("data")
# Create the path to save submission files
SUBMISSION_PATH = Path("submissions")
os.makedirs(SUBMISSION_PATH, exist_ok=True) | Populating the interactive namespace from numpy and matplotlib
| MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
We also load the official metric, top-30 error rate, for which we provide efficient implementations: | from GLC.metrics import top_30_error_rate
help(top_30_error_rate)
from GLC.metrics import top_k_error_rate_from_sets
help(top_k_error_rate_from_sets) | Help on function top_k_error_rate_from_sets in module GLC.metrics:
top_k_error_rate_from_sets(y_true, s_pred)
Computes the top-k error rate from predicted sets.
Parameters
----------
y_true: 1d array, [n_samples]
True labels.
s_pred: 2d array, [n_samples, k]
Previously computed... | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
For submissions, we will also need to predict the top-30 sets for which we also provide an efficient implementation: | from GLC.metrics import predict_top_30_set
help(predict_top_30_set) | Help on function predict_top_30_set in module GLC.metrics:
predict_top_30_set(y_score)
Predicts the top-30 sets from scores.
Parameters
----------
y_score: 2d array, [n_samples, n_classes]
Scores for each sample and label.
Returns
-------
2d array, [n_samples, 30]:
... | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
We also provide an utility function to generate submission files in the right format: | from GLC.submission import generate_submission_file
help(generate_submission_file) | Help on function generate_submission_file in module GLC.submission:
generate_submission_file(filename, observation_ids, s_pred)
Generate submission file for Kaggle
Parameters
----------
filename : string
Submission filename.
observation_ids : 1d array-like
Test observations ids... | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
Observation data loading We first need to load the observation data: | df_obs_fr = pd.read_csv(DATA_PATH / "observations" / "observations_fr_train.csv", sep=";", index_col="observation_id")
df_obs_us = pd.read_csv(DATA_PATH / "observations" / "observations_us_train.csv", sep=";", index_col="observation_id")
df_obs = pd.concat((df_obs_fr, df_obs_us)) | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
Then, we retrieve the train/val split provided: | obs_id_train = df_obs.index[df_obs["subset"] == "train"].values
obs_id_val = df_obs.index[df_obs["subset"] == "val"].values
y_train = df_obs.loc[obs_id_train]["species_id"].values
y_val = df_obs.loc[obs_id_val]["species_id"].values
n_val = len(obs_id_val)
print("Validation set size: {} ({:.1%} of train observations)"... | Validation set size: 40080 (2.5% of train observations)
| MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
We also load the observation data for the test set: | df_obs_fr_test = pd.read_csv(DATA_PATH / "observations" / "observations_fr_test.csv", sep=";", index_col="observation_id")
df_obs_us_test = pd.read_csv(DATA_PATH / "observations" / "observations_us_test.csv", sep=";", index_col="observation_id")
df_obs_test = pd.concat((df_obs_fr_test, df_obs_us_test))
obs_id_test = ... | Number of observations for testing: 36421
| MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
Sample submission fileIn this section, we will demonstrate how to generate the sample submission file provided.To do so, we will use the function `generate_submission_file` from `GLC.submission`. The sample submission consists in always predicting the first 30 species for all the test observations: | first_30_species = np.arange(30)
s_pred = np.tile(first_30_species[None], (len(df_obs_test), 1)) | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
We can then generate the associated submission file using: | generate_submission_file(SUBMISSION_PATH / "sample_submission.csv", df_obs_test.index, s_pred) | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
Constant baseline: 30 most observed speciesThe first baseline consists in predicting the 30 most observed species on the train set which corresponds exactly to the "Top-30 most present species": | species_distribution = df_obs.loc[obs_id_train]["species_id"].value_counts(normalize=True)
top_30_most_observed = species_distribution.index.values[:30] | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
As expected, it does not perform very well on the validation set: | s_pred = np.tile(top_30_most_observed[None], (n_val, 1))
score = top_k_error_rate_from_sets(y_val, s_pred)
print("Top-30 error rate: {:.1%}".format(score)) | Top-30 error rate: 93.5%
| MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
We will however generate the associated submission file on the test using: | # Compute baseline on the test set
n_test = len(df_obs_test)
s_pred = np.tile(top_30_most_observed[None], (n_test, 1))
# Generate the submission file
generate_submission_file(SUBMISSION_PATH / "constant_top_30_most_present_species_baseline.csv", df_obs_test.index, s_pred) | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
Random forest on environmental vectorsA classical approach in ecology is to train Random Forests on environmental vectors.We show here how to do so using [scikit-learn](https://scikit-learn.org/).We start by loading the environmental vectors: | df_env = pd.read_csv(DATA_PATH / "pre-extracted" / "environmental_vectors.csv", sep=";", index_col="observation_id")
X_train = df_env.loc[obs_id_train].values
X_val = df_env.loc[obs_id_val].values
X_test = df_env.loc[obs_id_test].values | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
Then, we need to handle properly the missing values.For instance, using `SimpleImputer`: | from sklearn.impute import SimpleImputer
imp = SimpleImputer(
missing_values=np.nan,
strategy="constant",
fill_value=np.finfo(np.float32).min,
)
imp.fit(X_train)
X_train = imp.transform(X_train)
X_val = imp.transform(X_val)
X_test = imp.transform(X_test) | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
We can now start training our Random Forest (as there are a lot of observations, over 1.8M, this can take a while): | from sklearn.ensemble import RandomForestClassifier
est = RandomForestClassifier(n_estimators=16, max_depth=10, n_jobs=-1)
est.fit(X_train, y_train) | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
As there are a lot of classes (over 17K), we need to be cautious when predicting the scores of the model.This can easily take more than 5Go on the validation set.For this reason, we will be predict the top-30 sets by batches using the following generic function: | def batch_predict(predict_func, X, batch_size=1024):
res = predict_func(X[:1])
n_samples, n_outputs, dtype = X.shape[0], res.shape[1], res.dtype
preds = np.empty((n_samples, n_outputs), dtype=dtype)
for i in range(0, len(X), batch_size):
X_batch = X[i:i+batch_size]
preds[i:i+ba... | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
We can know compute the top-30 error rate on the validation set: | def predict_func(X):
y_score = est.predict_proba(X)
s_pred = predict_top_30_set(y_score)
return s_pred
s_val = batch_predict(predict_func, X_val, batch_size=1024)
score_val = top_k_error_rate_from_sets(y_val, s_val)
print("Top-30 error rate: {:.1%}".format(score_val)) | Top-30 error rate: 80.4%
| MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
We now predict the top-30 sets on the test data and save them in a submission file: | # Compute baseline on the test set
s_pred = batch_predict(predict_func, X_test, batch_size=1024)
# Generate the submission file
generate_submission_file(SUBMISSION_PATH / "random_forest_on_environmental_vectors.csv", df_obs_test.index, s_pred) | _____no_output_____ | MIT | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 |
Tips Dataframe - Loc:Desktop\Fundamentals_of-Data_Analysis/Fund_of_Data_Analysis/ | #import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns; sns.set()
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
sns.set(rc={'figure.figsize':(10,8)})
sns.set_style('white') | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
Description | df=pd.read_csv("tips.csv")
print (('The data has the following shape'), df.shape)
print ("\n")
df.info()
df.head()
df = df.rename(columns={'total_bill': 'Bill', 'tip':'Tip', 'sex':'Gender', 'smoker':'Smoker', 'day':'Day','time':'Time', 'size': 'Party'})
df.head()
df.describe()
df.plot(style = "o", ms=3, figsize = [10,5... | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
Linear Regression- Plot the Tips relative to the Bill amount. | df.plot(x='Bill', y='Tip', style='o')
plt.title('Bill amount and Tip given')
plt.xlabel('Bill')
plt.ylabel('Tip')
plt.show() | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
- Looking at where the dots, it would seem that the Tip amount increases relative to the Bill amount. It would seem that the Tip is approximate 20 % of the Bill amount. There are a few outliers that could skew the data.- I will try a few values for the slope and where it crosses the Y-axis. The slopes I will at will va... | # Plot w versus d with black dots.
df.plot(x='Bill', y='Tip', style='o')
# Overlay some lines on the plot.
x = np.arange(0.0, 50.0, 1.0)
plt.plot(x, 0.125 * x + 0.5, 'r-', label=r"$x/8 + 0.5$")
plt.plot(x, 0.2 * x + 0.5, 'g-', label=r"$x/5 + 0.5$")
plt.plot(x, 0.1 * x + 0.0, 'b-', label=r"$x/10 + 0.0$")
# Add a leg... | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
- The red line seems to be the best fit. But I will investigate using the least square technique. In the above table, for every x, there is two values for y, one on the line and one on the dot. The following measures this distance and squares it (to account for negative values). The lease value is the best guess for th... | B = df["Bill"]
T = df["Tip"]
cost = lambda m,c: np.sum([(T[i] - m * B[i] - c)**2 for i in range(B.size)])
print("Red line cost with m = %5.2f and c = %5.2f: is %8.2f" % (0.125, 0.50, cost(0.125, 0.5)))
print("Green line cost with m = %5.2f and c = %5.2f: is %8.2f" % (0.2, 0.5, cost(0.2, 0.5)))
print("Blue line cost... | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
Minimising the cost | # Calculate the best values for m and c.
B = df["Bill"]
T = df["Tip"]
# Calculate the best values for B and T.
B_avg = df["Bill"].mean()
T_avg = df["Tip"].mean()
B_zero = B - B_avg
T_zero = T - T_avg
m = np.sum(B_zero * T_zero) / np.sum(B_zero * B_zero)
c = T_avg - m * B_avg
print ("m is %8.6f and c is %6.6f." % (... | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
- The line the minimises the cost can now be superimposed on the data. | # Plot the best fit line.
plt.plot(B, T, 'k.', label='Original data')
plt.plot(B, m * B + c, 'b-', label='Best fit line')
# Add axis labels and a legend.
plt.xlabel('Bill')
plt.ylabel('Tips')
plt.legend()
plt.ylim(0, 10)
# Show the plot.
plt.show()
cost = lambda m,c: np.sum([(T[i] - m * B[i] - c)**2 for i in range(B.... | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
- In the case of linear regression, the cost function is the sum of the squares of the residuals (residuals being the difference between the dependent variable value and the value given by the model). The procedure finds for you the intercept and slope(s) that minimize the cost function.- This is why the linear regress... | import statsmodels.api as sm
X = df['Bill']
y = df['Tip']
X2 = sm.add_constant(X)
est = sm.OLS(y, X2)
est2 = est.fit()
print(est2.summary()) | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
- Ref: https://towardsdatascience.com/the-complete-guide-to-linear-regression-in-python-3d3f8f06bf8- Looking at both coefficients, we have a p-value that is equal to 0. This means that there is a strong correlation between these coefficients and the target (Tip).- The R² value is equal to 0.45. Therefore, about 45% of ... | plt.figure(1)
df.groupby(['Gender', 'Time'])['Tip'].mean().unstack(level=0).plot(kind='bar', figsize=(10,5))
plt.ylabel('Tip Amount')
plt.figure(2)
df.groupby(['Gender', 'Smoker'])['Tip'].mean().unstack(level=0).plot(kind='bar', figsize=(10,5))
plt.ylabel('Tip Amount')
plt.figure(3)
df.groupby(['Party', 'Time'])['Tip... | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
- From the first three plots, it would seem that males are better tippers than females and that with the exeption of lunch, that size of the tip increases with the party amount. End The following contains some code that was not needed but that I may come back to. | B = df["Bill"]
T = df["Tip"]
P = df["Party"]
G = df['Gender']
#df.Gender = df.Gender.map({'Female':0,'Male':1})
#df['Gender'] = df['Gender'].map(dict(zip(['Female','Male'],[0,1]))
df['Gender'] = (df['Gender'] == 'Female').astype(int)
df.head()
C = np.polyfit(P, T, 1)
C
from statsmodels.formula.api import ols
fit = ol... | _____no_output_____ | MIT | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis |
Preprocessing for deep learning | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] ='w'
plt.rcParams['axes.edgecolor'] = '#D6D6D6'
plt.rcParams['axes.linewidth'] = 2 | _____no_output_____ | MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
1. Background A. Variance and covariance Example 1. | A = np.array([[1, 3, 5], [5, 4, 1], [3, 8, 6]])
print(A)
print(np.cov(A, rowvar=False, bias=True)) | [[ 2.66666667 0.66666667 -2.66666667]
[ 0.66666667 4.66666667 2.33333333]
[-2.66666667 2.33333333 4.66666667]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
Finding the covariance matrix with the dot product | def calculateCovariance(X):
meanX = np.mean(X, axis = 0)
lenX = X.shape[0]
X = X - meanX
covariance = X.T.dot(X)/lenX
return covariance
print(calculateCovariance(A)) | [[ 2.66666667 0.66666667 -2.66666667]
[ 0.66666667 4.66666667 2.33333333]
[-2.66666667 2.33333333 4.66666667]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
B. Visualize data and covariance matrices | def plotDataAndCov(data):
ACov = np.cov(data, rowvar=False, bias=True)
print('Covariance matrix:\n', ACov)
fig, ax = plt.subplots(nrows=1, ncols=2)
fig.set_size_inches(10, 10)
ax0 = plt.subplot(2, 2, 1)
# Choosing the colors
cmap = sns.color_palette("GnBu", 10)
sns.heatmap(ACov, c... | _____no_output_____ | MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
C. Simulating data Uncorrelated data | np.random.seed(1234)
a1 = np.random.normal(2, 1, 300)
a2 = np.random.normal(1, 1, 300)
A = np.array([a1, a2]).T
A.shape
print(A[:10,:])
sns.distplot(A[:,0], color="#53BB04")
sns.distplot(A[:,1], color="#0A98BE")
plt.show()
plt.close()
plotDataAndCov(A)
plt.show()
plt.close() | Covariance matrix:
[[ 0.95171641 -0.0447816 ]
[-0.0447816 0.87959853]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
Correlated data | np.random.seed(1234)
b1 = np.random.normal(3, 1, 300)
b2 = b1 + np.random.normal(7, 1, 300)/2.
B = np.array([b1, b2]).T
plotDataAndCov(B)
plt.show()
plt.close() | Covariance matrix:
[[0.95171641 0.92932561]
[0.92932561 1.12683445]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
2. Preprocessing A. Mean normalization | def center(X):
newX = X - np.mean(X, axis = 0)
return newX
BCentered = center(B)
print('Before:\n\n')
plotDataAndCov(B)
plt.show()
plt.close()
print('After:\n\n')
plotDataAndCov(BCentered)
plt.show()
plt.close() | Before:
Covariance matrix:
[[0.95171641 0.92932561]
[0.92932561 1.12683445]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
B. Standardization | def standardize(X):
newX = center(X)/np.std(X, axis = 0)
return newX
np.random.seed(1234)
c1 = np.random.normal(3, 1, 300)
c2 = c1 + np.random.normal(7, 5, 300)/2.
C = np.array([c1, c2]).T
plotDataAndCov(C)
plt.xlim(0, 15)
plt.ylim(0, 15)
plt.show()
plt.close()
CStandardized = standardize(C)
plotDataAndCov(C... | Covariance matrix:
[[1. 0.34500274]
[0.34500274 1. ]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
C. Whitening 1. Zero-centering | CCentered = center(C)
plotDataAndCov(CCentered)
plt.show()
plt.close() | Covariance matrix:
[[0.95171641 0.83976242]
[0.83976242 6.22529922]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
2. Decorrelate | def decorrelate(X):
cov = X.T.dot(X)/float(X.shape[0])
# Calculate the eigenvalues and eigenvectors of the covariance matrix
eigVals, eigVecs = np.linalg.eig(cov)
# Apply the eigenvectors to X
decorrelated = X.dot(eigVecs)
return decorrelated
plotDataAndCov(C)
plt.show()
plt.close()
CDecorrelat... | Covariance matrix:
[[0.95171641 0.83976242]
[0.83976242 6.22529922]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
3. Rescale the data | def whiten(X):
cov = X.T.dot(X)/float(X.shape[0])
# Calculate the eigenvalues and eigenvectors of the covariance matrix
eigVals, eigVecs = np.linalg.eig(cov)
# Apply the eigenvectors to X
decorrelated = X.dot(eigVecs)
# Rescale the decorrelated data
whitened = decorrelated / np.sqrt(eigVals ... | Covariance matrix:
[[9.99987823e-01 2.51650552e-17]
[2.51650552e-17 9.99998427e-01]]
| MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
3. Image whitening | from keras.datasets import cifar10
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
X_train.shape
X = X_train[:1000]
print(X.shape)
X = X.reshape(X.shape[0], X.shape[1]*X.shape[2]*X.shape[3])
print(X.shape)
def plotImage(X):
plt.rcParams["axes.grid"] = False
plt.figure(figsize=(1.5, 1.5))
plt.im... | _____no_output_____ | MIT | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised |
ScalabilityThis notebook show the scalability analysis performed in the paper.We compared our LTGL model with respect to state-of-the art software for graphical inference, such as LVGLASSO and TVGL.Note: GL is not included in the comparison, since it is based on coordinate descent and it does not have the eigenvalue d... | %matplotlib inline
from __future__ import print_function
import matplotlib.pyplot as plt
import matlab
import matlab.engine
import pandas as pd
import numpy as np
import cPickle as pkl
import time
from itertools import product
from regain import datasets, utils
from regain.covariance import latent_time_graph_lasso_
d... | _____no_output_____ | BSD-3-Clause | notebooks/scalability.ipynb | veronicatozzo/regain |
Since this is computationally expensive, we divide the results in two cells ... | for i, (k, res) in enumerate(sorted(data.items())):
dim = k[0]
logging.info("Start TVGL with: dim=%d, T=%d (it %d)" % (k[0],k[1], i))
data_list = res.data
K = res.thetas
K_obs = res.thetas_observed
ells = res.ells
data_grid = np.array(data_list).transpose(1,2,0) # to use it later for grid s... | _____no_output_____ | BSD-3-Clause | notebooks/scalability.ipynb | veronicatozzo/regain |
Plotting | # load pickle
with open("scalability.pkl", 'rb') as f:
df = pkl.load(f)
df.sortlevel(inplace=True)
idx = pd.IndexSlice
scores = df.columns.levels[0]
n_dims = df.columns.levels[1]
methods = df.index.levels[0]
n_times = df.index.levels[1] | _____no_output_____ | BSD-3-Clause | notebooks/scalability.ipynb | veronicatozzo/regain |
Let's plot a horizontal figure. | style = ['-', '--', ':']
f, ax = plt.subplots(1, len(n_times), sharey=True, figsize=(12,2), dpi=600)
ax[0].set_ylabel("seconds")
# ax[0].set_ylim([.1,None])
for i, t in enumerate(n_times):
for j, m in enumerate([m for m in methods if m != 'GL']):
if m == 'GL':
continue
ax[i].plot(n_dim... | _____no_output_____ | BSD-3-Clause | notebooks/scalability.ipynb | veronicatozzo/regain |
Organização do dataset | def dicom2png(input_file, output_file):
try:
ds = pydicom.dcmread(input_file)
shape = ds.pixel_array.shape
# Convert to float to avoid overflow or underflow losses.
image_2d = ds.pixel_array.astype(float)
# Rescaling grey scale between 0-255
image_2d_scaled = (np.ma... | _____no_output_____ | MIT | src/python/EfficientNet_Fine_Tuning.ipynb | mrr00b00t/rnap |
Fine-tuning EfficientNet | import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import EfficientNetB0, EfficientNetB1, EfficientNetB2, EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6, EfficientNetB7
from tensorflow.keras import models
from tensorflow.keras i... | _____no_output_____ | MIT | src/python/EfficientNet_Fine_Tuning.ipynb | mrr00b00t/rnap |
读取test data做可视化 |
digits = pd.read_csv('test_data_30.csv')
digits = digits.fillna(method='ffill')
scaler = MinMaxScaler()
X = scaler.fit_transform(digits.iloc[:,1:])
#y = digits[:,-1]
n_samples, n_features = X.shape
n_neighbors = 5
X = np.array(X)
y = np.array([67,67,67,71,71,71,8,8,8,90,90,90,7,7,7,9,9,9,5,5,5,74,74,74,199,199,199... | [[ 0.77519589 -11.86948318]
[ 2.1333111 -11.93849311]
[ 1.75364277 -11.79042791]
[ 3.14564811 -1.69316209]
[ 2.40127958 -0.80519923]
[ 1.97806687 -2.43189793]
[ 12.81251568 7.19804738]
[ 12.97860066 2.02166839]
[ 12.80743053 6.07193998]
[ 12.7631689 2.73366925]
[ 9.0357067 3.23900074]
... | MIT | 可视化/tSNE等数据可视化.ipynb | NANBFTOP5/MOF |
[](https://pythonista.io) Entrada y salida estándar. En la actualidad existen muchas fuentes desde las que se puede obtener y desplegar la información que un sistema de cómputo consume, gestiona y genera. Sin embargo, para el intérprete de Python la salida por defecto (salida estánd... | 3 * "Hola" | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
Salida estándar con la funcion ```print()```.En Python 3, la función ```print()``` se utiliza para desplegar información en la salida estándar.La sintaxis es la siguiente:```print(, , ...)```* La función ```print()``` evalúa y despliega una o varias expresiones.* Si el resultado de la expresión es un objeto ```str```,... | a = 2 | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
* La siguiente celda evalúa la expresión ```a```, por lo que desplegará ```2```. | print(a) | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
* La siguiente celda desplegará el mensaje dentro del objeto ```"Hola"```. | print("Hola") | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
* En la siguiente celda la función ```print()``` desplegará dos expresiones que corresponde cada una a un objeto de tipo ```str```. Cada objeto será desplegado separado por un espacio.* La salida será ```Hola Mundo```. | print("Hola", "Mundo") | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
* En la siguiente celda la función ```print()``` desplegará el resultado de una expresión de concatenación entre dos objetos de tipo ```str```. El resultado es un objeto ```str```.* La salida será ```HolaMundo```. | print("Hola" + "Mundo") | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
* En la siguiente celda la función ```print()``` desplegará tres expresiones que corresponden a: * El objeto ```'Tienes'``` de tipo ```str```. * El objeto ```2``` de tipo ```int``` ligado al nombre ```a```. * El objeto ```'buenos amigos'``` de tipo ```str```.Cada expresión será desplegada separada por un espacio.* L... | print("Tienes", a, "buenos amigos.") | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
* En la siguiente celda la función ```print()``` intentará desplegar el resultado de la expresión ```"Tienes" + a + "buenos amigos."```, la cual no es correcta y generará un error de tipo ```TypeError```. | print("Tienes" + a + "buenos amigos.") | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
Despliegue con formato.Para intercalar valores dentro de un formato específico de texto se utiliza el caracter sobre-escritura definodo como el signo de porcentaje ```%``` seguido de algún caracter que definirá el modo de desplegar la expresión correspondiente.```print("...%..." % expresión 1) ``````print("...%...%...... | pi = 3.141592
radio = 2
print("El perímetro de un círculo de radio %d es %f." % (radio, 2 * radio * pi))
print("El perímetro de un círculo de radio %d es %d." % (radio, 2 * radio * pi))
print("El perímetro de un circulo de radio %s es %s." % (radio, 2 * radio * pi))
print("El valor de pi es %f." % (pi))
print("El valor... | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
Para desplegar el signo de porcentaje ```%``` se utiliza ```%%```. **Ejemplo:** | valor = 13
porciento = 15
porcentaje = (valor * porciento) / 100
print("El %d%% de %f es %f." % (porciento, valor, porcentaje)) | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
Despliegue de cifras significativas.Para desplegar un número específico de cifras significativas de un valor de punto flotante, se añade un punto ```.``` y el número de cifras a desplegarse después del signo de porcentaje ```%``` y antes del carácter ```f``` o ```e```.```%.f``` **Ejemplos:** | pi = 3.14169265
radio = 2
print("El perímetro de un círculo de radio igual a %d es %f." % (radio, 2 * pi * radio))
print("El perímetro de un círculo de radio igual a %d es %.2f." % (radio, 2 * pi * radio)) | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
Caracteres de escape.Existen algunos caracteres que por su función o por la sintaxis de Python -tales como los apóstrofes, las comillas, los retornos de línea, etc.- que deben utilizar un "caracter de escape", para que puedan ser desplegados. Los caracteres de escape pueden ser introducidos después de una diagonal inv... | print("Primera línea.\nSegunda línea\t con tabulador.")
print("Este es el signo de \"gato\" \x23.")
print("Beta: \u00DF")
print('I \u2764 YOU!') | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
Entrada estándar con la función ```input()```. La función por defecto de entrada estándar para Python 3 es ```input()```.La función ```input()``` captura los caracteres provenientes de entrada estándar (el teclado) hasta que se introduce un retorno de carro Intro y el contenido capturado es devuelto al intérprete como... | input()
texto = input()
type(texto)
texto
print(texto)
nombre = input("Escribe un nombre: ")
print(nombre) | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
Entrada y salida estándar en Python 2. La función ```raw_input()```.La sintaxis es la siguiente para Python 2:``` raw_input()```**Ejemplo:**``` python>>> raw_input()Hola'Hola'>>> texto = raw_input()Hola>>> type(texto)>>> print textoHola>>> nombre = raw_input("Escribe un nombre: ")Escribe un nombre: Juan>>> print nomb... | eval(input('Ingresa: ')) | _____no_output_____ | MIT | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 |
Hopfield Network - Longren | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf') | _____no_output_____ | MIT | MNS/.ipynb_checkpoints/MNS_CP2_Longren-checkpoint.ipynb | lcubelongren/BCCN_classwork |
Tasks: | # 1. Store the patterns in the Hopfield network
'pattern A'
SA = [1,-1,1,-1]
'pattern B'
SB = [-1,1,1,1]
'pattern C'
SC = [-1,-1,-1,1]
N = 3 #number of patterns
K = 4 #number of units
WA = np.zeros([K,K]) #empty weight matrix
WB = np.zeros([K,K])
WC = np.zeros([K,K])
def weight_int(W,S): #weight initialization
... | original pattern: [1, -1, 1, -1]
convergence of A: [ 1. -1. 1. 1.]
original pattern: [-1, 1, 1, 1]
convergence of B: [-1. 1. 1. 1.]
original pattern: [-1, -1, -1, 1]
convergence of C: [-1. -1. -1. 1.]
| MIT | MNS/.ipynb_checkpoints/MNS_CP2_Longren-checkpoint.ipynb | lcubelongren/BCCN_classwork |
Analyzing the results of my code for the convergence of the patterns, we can see that according to mine there are two stable patterns, B & C, as they stick to the same pattern that was initially given after count=50 iterations. The other pattern, A, is not stable as it does not have the same value for S4 as was initial... | # 2. Calculate the energy function for the network
#loop through iterations
W = np.zeros([K,K])
Z = np.zeros([K])
E = np.zeros([K,K])
count = 5
def energy(W,S): #energy function
for i in range(K):
for j in range(K):
E[i][j] = -1 * np.sum(W[i][j] * np.dot(Z[i],Z[j])... | _____no_output_____ | MIT | MNS/.ipynb_checkpoints/MNS_CP2_Longren-checkpoint.ipynb | lcubelongren/BCCN_classwork |
All three patterns should only have a decreasing energy, however pattern A is having troubles for me for some iterations. | # 3. Reuse the code to store and recall image patterns
# 3.1 load the given images
images = np.load(r"C:\Users\lcube\Desktop\jupyter\BCCN\MNS\given\images.npz")
im = []
for item in lst: #getting the file into a usable form (somehow)
im.append(images[item]) #i know append isn't recommended, but it took me for... | [[0. 1. 1. ... 1. 1. 1.]
[1. 0. 1. ... 1. 1. 1.]
[1. 1. 0. ... 1. 1. 1.]
...
[1. 1. 1. ... 1. 1. 1.]
[1. 1. 1. ... 1. 1. 1.]
[1. 1. 1. ... 1. 1. 1.]]
| MIT | MNS/.ipynb_checkpoints/MNS_CP2_Longren-checkpoint.ipynb | lcubelongren/BCCN_classwork |
Schooling in Xenopus tadpoles: Power analysisThis is a supplementary notebook that generates some simulated data, and estimates the power analysis for a schooling protocol. The analysis subroutines are the same, or very close to ones from the actual notebook (**schooling_analysis**). The results of power analysis are ... | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.spatial
import scipy.stats as stats
from typing import List,Tuple | _____no_output_____ | MIT | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior |
1. Generate simulated dataData is generated in the following format: Layout of Tadpole dataframe: x y tx ty 0 7.391 14.783 -0.159 -0.14 1 8.850 14.623 -0.180 -0.18 2 7.751 12.426 -0.260 -0.24where each line correponds to a "tadpole"; `x` and `y` columns give the position of the... | def simulate_data(ntads=10, schooling=0.5, alignment=0.6):
"""Simulates tadpole distribution in the dish.
n = how many tadpoles to have
schooling = the probability of being in a school (simplistic, binary approach)
r = aligment radius
alignment = alignment coefficient (1-noise_level)
"""
... | _____no_output_____ | MIT | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior |
2. Processing ToolsAn exact copy of tools from the "main notebook" (as of 2020.08.01), except that instead of extracing tadpoles from real data, here we simulate this data. (So `exctractTads` function is not actually used). | def getNFrames(data):
"""Returns the total number of frames."""
return max(data.Frame)+1
def extractTads(data,frame):
"""Splits the data into XY position of each head, and _relative_ XY position of each tail."""
xy = data.loc[data.Frame==frame,['X','Y']].to_numpy()
heads = xy[0::2,:]
tails = xy... | Layout of Tadpole dataframe:
x y tx ty
0 12.972282 9.730947 -0.111329 -0.384195
1 11.880166 10.630500 0.391904 -0.080068
2 6.528482 13.566266 0.391893 0.080126
Layout of Pairs dataframe:
i j dist
0 19 5 2.737425
1 5 7 1.183917
2 7 19 3.604447
| MIT | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior |
3. Tools to Process AnglesExactly same as in the main notebook (as of 2020.08.01) | def findAngles(tads,pairs):
'''Angles between pairs of tadpoles'''
tails = tads[['tx','ty']].values # Go from pandas to lists, to utilize list comprehension
norms = [np.linalg.norm(tails[i,]) for i in range(tails.shape[0])]
angle = [np.arccos(np.dot(tails[p[0],],tails[p[1],])/(norms[p[0]]*norms[p[1]])) ... | _____no_output_____ | MIT | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior |
4. Define full processor and dataset visualizationThis function is adjusted to look like the procesisng function from the main notebook, but actually we call the simulation several times, to generate the "frames". | def processEverything(nsets=12, show_image=False, schooling=0.3, alignment=0.5):
"""Process one full dataset."""
if show_image:
fig = plt.figure(figsize=(10,10));
fullDf = pd.DataFrame()
for iframe in range(nsets):
tads = simulate_data(ntads=20, schooling=schooling, alignment=alignment)... | _____no_output_____ | MIT | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior |
5. Compare two different simulated datasetsBelow, one dataset has high schooling coefficient (0.9), and perfect alignment (1.0), while the other has almost no schooling (0.1), and perfectly random orientation for all tadpoles (alignment=0.0). | # Prepare the data
out = processEverything(show_image=False, schooling=0.9, alignment=1.0)
out_treatment = processEverything(show_image=False, schooling=0.1, alignment=0.0)
def two_groups_plot(y1, y2, labels):
"""A basic two-groups plot"""
plt.plot(1+(np.random.uniform(size=y1.shape[0])-0.5)*0.3, y1, '.', alpha... | Was the average inter-tadpole disctance different between two sets of data?
(were their clumping?)
T-test: t = -7.081288975811951 ; p-value = 2.4422756226026123e-12
Was the distribution shape different between two sets??
Kolmogorov-Smirnov test p-value = 7.172521035283853e-31
| MIT | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior |
As we can see, non-schooling tadpoles tend to be more uniformly distributed, so we observe more mid-distances and fewer low and high distances. ("More uniformly" doesn't mean that the distribution is actually uniform; it is expected to be closer to $χ^2$). Conversely, schooling tadpoles tend to be closer to each other.... | def compare_angles(out, out2, labels):
"""Visualizes angles, reports a stat test."""
HIST_BIN = 30 # Histogram step, in degrees
a = out['angle'].values
a2 = out2['angle'].values
#plt.hist(a , bins=np.arange(0,180+10,10), density=True, alpha=0.5);
#plt.hist(a2, bins=np.arange(0,180+10,10), ... |
Was the distribution of angles different between two sets?
Kolmogorov-Smirnov test p-value = 3.767828784543536e-73
| MIT | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior |
As we can see, if tadpoles are oriented at random, the histogram of inter-tadpole angles is flat. If tadpoles school, the distribution of angles drops, as most tadpoles are co-oriented. 6. Power analysis | ntries = 50
x = np.linspace(0, 1, 21)
y = np.zeros((x.shape[0], 3))
for ival in range(len(x)):
val = x[ival]
print(f'{val:4.1f}', end=' ')
count = np.array([0,0,0])
for iattempt in range(ntries):
print('.', end='')
out1 = processEverything(show_image=False, schooling=0.5, alignment=0.5)... | _____no_output_____ | MIT | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior |
Text Generation using GPT Neo 2.7B This Code Template is for Text Generation task which is a problem associated to NLG(Natural Language Generation). In this Project GPT Neo 2.7B is utilized for Text Generation.GPT-Neo 1.3B is a transformer model designed using EleutherAI's replication of the GPT-3 architecture. Requi... | !pip install transformers
from transformers import pipeline | _____no_output_____ | Apache-2.0 | Natural Language Processing/NLP/TextGenerationGPTNEO1_3B.ipynb | shreepad-nade/ds-seed |
GPT Neo 1.3B
GPT-Neo 1.3B is a transformer model designed using EleutherAI's replication of the GPT-3 architecture. GPT-Neo refers to the class of models, while 1.3B represents the number of parameters of this particular pre-trained model.
You can use this model directly with a pipeline for text generation. This exa... | generator = pipeline('text-generation', model='EleutherAI/gpt-neo-1.3B') | _____no_output_____ | Apache-2.0 | Natural Language Processing/NLP/TextGenerationGPTNEO1_3B.ipynb | shreepad-nade/ds-seed |
Text Generation | generator("How was your", max_length=20, num_return_sequences=5) | Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
| Apache-2.0 | Natural Language Processing/NLP/TextGenerationGPTNEO1_3B.ipynb | shreepad-nade/ds-seed |
OCR (Optical Character Recognition) from Images with Transformers---[Github](https://github.com/eugenesiow/practical-ml/) | More Notebooks @ [eugenesiow/practical-ml](https://github.com/eugenesiow/practical-ml)--- Notebook to recognise text automaticaly from an input image with either handwritten or printed text.[Opti... | !pip install -q git+https://github.com/huggingface/transformers.git | Installing build dependencies ... [?25l[?25hdone
Getting requirements to build wheel ... [?25l[?25hdone
Preparing wheel metadata ... [?25l[?25hdone
[K |████████████████████████████████| 3.3 MB 5.1 MB/s
[K |████████████████████████████████| 596 kB 58.0 MB/s
[K |████████████████████████████... | MIT | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml |
Using the Model (Running Inference) Let's define a function for us to get images from the web. We execute this function to download an image with a line of handwritten text and display it. | import requests
from IPython.display import display
from PIL import Image
def show_image(url):
img = Image.open(requests.get(url, stream=True).raw).convert("RGB")
display(img)
return img
handwriting1 = show_image('https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg') | _____no_output_____ | MIT | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml |
Now we want to load the model to recognise handwritten text.Specifically we are running the following steps:* Load the processor, `TrOCRProcessor`, which processes our input image and converts it into a sequence of fixed-size patches (resolution 16x16), which are linearly embedded. The processor also adds absolute posi... | import transformers
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
processor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-handwritten')
model = VisionEncoderDecoderModel.from_pretrained('microsoft/trocr-base-handwritten')
def ocr_image(src_img):
pixel_values = processor(images=src_img,... | _____no_output_____ | MIT | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml |
We now run our `ocr_image` function on the line of handwritten text in the image we have downloaded previously (and stored in `handwriting1`). | ocr_image(handwriting1) | _____no_output_____ | MIT | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml |
Lets try on another image with handwritten text. | ocr_image(show_image('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoolxi9yWGAT5SLZShv8vVd0bz47UWRzQC19fDTeE8GmGv_Rn-PCF1pP1rrUx8kOjA4gg&usqp=CAU'))
import transformers
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
print_processor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-pri... | _____no_output_____ | MIT | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml |
We download an image with noisy printed text, a scanned receipt. | receipt = show_image('https://github.com/zzzDavid/ICDAR-2019-SROIE/raw/master/data/img/000.jpg') | _____no_output_____ | MIT | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml |
As the model processes a line of text, we crop the image to include on of the lines of text in the receipt and send it to our model. | receipt_crop = receipt.crop((0, 80, receipt.size[0], 110))
display(receipt_crop)
ocr_print_image(receipt_crop) | _____no_output_____ | MIT | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml |
Regression Plots | %matplotlib inline
from statsmodels.compat import lzip
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.formula.api import ols
plt.rc("figure", figsize=(16,8))
plt.rc("font", size=14) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Duncan's Prestige Dataset Load the Data We can use a utility function to load any R dataset available from the great Rdatasets package. | prestige = sm.datasets.get_rdataset("Duncan", "carData", cache=True).data
prestige.head()
prestige_model = ols("prestige ~ income + education", data=prestige).fit()
print(prestige_model.summary()) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Influence plots Influence plots show the (externally) studentized residuals vs. the leverage of each observation as measured by the hat matrix.Externally studentized residuals are residuals that are scaled by their standard deviation where $$var(\hat{\epsilon}_i)=\hat{\sigma}^2_i(1-h_{ii})$$with$$\hat{\sigma}^2_i=\fra... | fig = sm.graphics.influence_plot(prestige_model, criterion="cooks")
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
As you can see there are a few worrisome observations. Both contractor and reporter have low leverage but a large residual. RR.engineer has small residual and large leverage. Conductor and minister have both high leverage and large residuals, and, therefore, large influence. Partial Regression Plots (Duncan) Since we ... | fig = sm.graphics.plot_partregress("prestige", "income", ["income", "education"], data=prestige)
fig.tight_layout(pad=1.0)
fig = sm.graphics.plot_partregress("prestige", "income", ["education"], data=prestige)
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
As you can see the partial regression plot confirms the influence of conductor, minister, and RR.engineer on the partial relationship between income and prestige. The cases greatly decrease the effect of income on prestige. Dropping these cases confirms this. | subset = ~prestige.index.isin(["conductor", "RR.engineer", "minister"])
prestige_model2 = ols("prestige ~ income + education", data=prestige, subset=subset).fit()
print(prestige_model2.summary()) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.