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 |
|---|---|---|---|---|---|
Set minimum percentage among plotted cells for a cell type to be included. This prevents the plot from becoming overcrowded with labels and including lines that are too thin to even see: | min_ct_perc = 0.02 | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Now generate the two sankey plots. | fig, ax = plt.subplots(figsize=(8, 8))
cts_ordered_left_lev1 = [
ct
for ct in color_prop_df.l1_label
if ct in adata.obs.original_ann_level_1_clean.values
]
ct_to_color_lev1 = {
ct: col for ct, col in zip(color_prop_df.l1_label, color_prop_df.l1_rgba)
}
# get level 1 anns:
y_lev1 = adata.obs.original_ann... | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
2c Sample compositions: In the paper we use ann level 2 and group by sample: | ann_level_number = "2"
grouping_covariate = "sample" # choose e.g. "dataset" or "subject_ID" or "sample" | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Use the "clean" version, i.e. without forward-propagated labels for cells not annotated at the chosen label, but leaving those cells set to "None": | if ann_level_number == "1":
ann_level = "original_ann_level_" + ann_level_number
else:
ann_level = "original_ann_level_" + ann_level_number + "_clean" | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Now plot: | FIGURES[
"2c_sample_compositions"
] = celltype_composition_plotting.plot_celltype_composition_per_sample(
adata,
ann_level_number,
color_prop_df,
return_fig=True,
title="original cell type annotations (level 2) per sample",
ann_level_name_prefix="original_ann_level_",
) | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Store figures | # for figname, fig in FIGURES.items():
# print("Saving", figname)
# fig.savefig(os.path.join(dir_figures, f"{figname}.png"), bbox_inches="tight", dpi=140) | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
**Reading**zyBooks Ch 2 Variables and Expressions**Reference**[Python Basics Cheatsheet](https://www.pythoncheatsheet.org/Python-Basics)**Practice** In class practice: zyBooks Lab 1.15 - No parking signzyBooks Ch 2 Practice (graded participation activity)**Learning Outcomes** Upon successful completion of this chapter... | print (7+5)
print(7, 5, 7+5)
print()
print(7, 5, end=" ")
print("Seven plus five is", 12)
# Assignments
x = 2 ** 3
print (x)
y = 5
print(y)
# Variable values can be changed
y = 8
print(y)
# type() function tells the type of object
print(type(4))
print(type(3.14))
print(type("Hello"))
print(type(True))
# id() functi... | Welcome
to
IT 111
12
HOW ARE YOU?
| Apache-2.0 | w2_variables_expressions.ipynb | kelseypatterson817/su21-it161 |
OOP Syntax Exercise - Part 2Now that you've had some practice instantiating objects, it's time to write your own class from scratch. This lesson has two parts. In the first part, you'll write a Pants class. This class is similar to the shirt class with a couple of changes. Then you'll practice instantiating Pants obje... | ### TODO:
# - code a Pants class with the following attributes
# - color (string) eg 'red', 'yellow', 'orange'
# - waist_size (integer) eg 8, 9, 10, 32, 33, 34
# - length (integer) eg 27, 28, 29, 30, 31
# - price (float) eg 9.28
### TODO: Declare the Pants Class
### TODO: write an __init__ function to init... | _____no_output_____ | MIT | notebooks/Object Oriented Programming/2.OOP_syntax_pants_practice/exercise.ipynb | jesussantana/AWS-Machine-Learning-Foundations |
Run the code cell below to check resultsIf you run the next code cell and get an error, then revise your code until the code cell doesn't output anything. | def check_results():
pants = Pants('red', 35, 36, 15.12)
assert pants.color == 'red'
assert pants.waist_size == 35
assert pants.length == 36
assert pants.price == 15.12
pants.change_price(10) == 10
assert pants.price == 10
assert pants.discount(.1) == 9
print('You mad... | You made it to the end of the check. Nice job!
| MIT | notebooks/Object Oriented Programming/2.OOP_syntax_pants_practice/exercise.ipynb | jesussantana/AWS-Machine-Learning-Foundations |
SalesPerson classThe Pants class and Shirt class are quite similar. Here is an exercise to give you more practice writing a class. **This exercise is trickier than the previous exercises.**Write a SalesPerson class with the following characteristics:* the class name should be SalesPerson* the class attributes should i... | ### TODO:
# Code a SalesPerson class with the following attributes
# - first_name (string), the first name of the salesperson
# - last_name (string), the last name of the salesperson
# - employee_id (int), the employee ID number like 5681923
# - salary (float), the monthly salary of the employee
# - pants_s... | _____no_output_____ | MIT | notebooks/Object Oriented Programming/2.OOP_syntax_pants_practice/exercise.ipynb | jesussantana/AWS-Machine-Learning-Foundations |
Run the code cell below to check resultsIf you run the next code cell and get an error, then revise your code until the code cell doesn't output anything. | def check_results():
pants_one = Pants('red', 35, 36, 15.12)
pants_two = Pants('blue', 40, 38, 24.12)
pants_three = Pants('tan', 28, 30, 8.12)
salesperson = SalesPerson('Amy', 'Gonzalez', 2581923, 40000)
assert salesperson.first_name == 'Amy'
assert salesperson.last_name == 'Gonzalez'
... | Great job, you made it to the end of the code checks!
| MIT | notebooks/Object Oriented Programming/2.OOP_syntax_pants_practice/exercise.ipynb | jesussantana/AWS-Machine-Learning-Foundations |
Check display_sales() methodIf you run the code cell below, you should get output similar to this:```pythoncolor: red, waist_size: 35, length: 36, price: 15.12color: blue, waist_size: 40, length: 38, price: 24.12color: tan, waist_size: 28, length: 30, price: 8.12``` | pants_one = Pants('red', 35, 36, 15.12)
pants_two = Pants('blue', 40, 38, 24.12)
pants_three = Pants('tan', 28, 30, 8.12)
salesperson = SalesPerson('Amy', 'Gonzalez', 2581923, 40000)
salesperson.sell_pants(pants_one)
salesperson.sell_pants(pants_two)
salesperson.sell_pants(pants_three)
salesperson.display_sales(... | color: red, waist_size: 35, length: 36, price: 15.12
color: blue, waist_size: 40, length: 38, price: 24.12
color: tan, waist_size: 28, length: 30, price: 8.12
| MIT | notebooks/Object Oriented Programming/2.OOP_syntax_pants_practice/exercise.ipynb | jesussantana/AWS-Machine-Learning-Foundations |
YBIGTA ML PROJECT / 염정운 Setting | import numpy as np
import pandas as pd
pd.set_option("max_columns", 999)
pd.set_option("max_rows", 999)
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
import seaborn as sns
import matplotlib.pyplot as plt
#sns.set(rc={'figure.figsize':(11.7,10)}) | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
Identity data Variables in this table are identity information – network connection information (IP, ISP, Proxy, etc) and digital signature (UA/browser/os/version, etc) associated with transactions. They're collected by Vesta’s fraud protection system and digital security partners.The field names are masked and pairwi... | #train_identity가 불편해서 나는 i_merged라는 isFraud를 merge하고 column 순서를 조금 바꾼 새로운 Dataframe을 만들었어! 이건 그 코드!
#i_merged = train_i.merge(train_t[['TransactionID', 'isFraud']], how = 'left', on = 'TransactionID')
#order_list =['TransactionID', 'isFraud', 'DeviceInfo', 'DeviceType', 'id_01', 'id_02', 'id_03', 'id_04', 'id_05', 'id... | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
NaN 비율 | nullrate = (((i_merged.isnull().sum() / len(i_merged)))*100).sort_values(ascending = False)
nullrate.plot(kind='barh', figsize=(15, 9))
i_merged.head() | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
DeviceType nan(3.1%) < desktop(6.5%) < mobile(10.1%) 순으로 isFraud 증가 추이*전체 datatset에서 isFraud = 1의 비율 7.8% | #DeviceType
i_merged.groupby(['DeviceType', 'isFraud']).size().unstack()
i_merged[i_merged.DeviceType.isnull()].groupby('isFraud').size() | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
Null count in row 결측치 정도와 isFraud의 유의미한 상관관계 찾지 못함 | i_merged = i_merged.assign(NaN_count = i_merged.isnull().sum(axis = 1))
print(i_merged.assign(NaN_count = i_merged.isnull().sum(axis = 1)).groupby('isFraud')['NaN_count'].mean(),
i_merged.assign(NaN_count = i_merged.isnull().sum(axis = 1)).groupby('isFraud')['NaN_count'].std(),
i_merged.assign(NaN_count = i_merged.isnu... | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
변수별 EDA - Continous | #Correlation Matrix
rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
corr = i_merged.corr()
corr.style.background_gradient(cmap='coolwarm')
#id_01 : 0 이하의 값들을 가지며 skewed 형태. 필요시 log 변환을 통한 처리가 가능할 듯.
i_merged.id_01.plot(kind='hist', bins=22, figsize=(12,6), title='id_01 dist.')
print(i_merged.groupby('i... | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
변수별 EDA - Categorical | sns.jointplot(x = 'id_09', y = 'id_03', data = i_merged) | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
Feature Engineering ** Categorical이지만 가짓수가 많은 경우 정보가 있을 때 1, 아닐 때 0으로 처리함. BaseModel 돌리기 위해 이렇게 설정하였지만, 전처리를 바꿔가는 작업에서는 이 변수들을 다른 방식으로 처리 할 필요가 더 생길 수도 있음.** Pair 관계가 있음. id03,04 / id05,06 / id07,08, 21~26 / id09, 10 ::함께 데이터가 존재하거나(1) NaN이거나(0). 한편 EDA-Category를 보면 id03, 09의 경우 상관관계가 있는 것으로 추정되어 추가적인 변형을 하지 않았음.** h... | #Continous Features
i_merged.id_01 = np.log(-i_merged.id_01 + 1)
i_merged.id_02 = np.log(i_merged.id_02)
medi = i_merged.id_02.median()
i_merged.id_02 = i_merged.id_02.fillna(medi)
i_merged.id_02.hist()
#id_02의 NaN값을 random하게 채워줌
#i_merged['id_02_filled'] = i_merged['id_02']
#temp = (i_merged['id_02'].dropna()
# ... | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
Identity_Device FE | i_merged['Device_info_clean'] = i_merged['DeviceInfo']
i_merged['Device_info_clean'] = i_merged['Device_info_clean'].fillna('unknown')
def name_divide(name):
if name == 'Windows':
return 'Windows'
elif name == 'iOS Device':
return 'iOS Device'
elif name == 'MacOS':
return 'MacOS'
elif name == 'Tride... | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
Identity_feature engineered_dataset | i_merged.columns
selected = []
selected.extend(['TransactionID', 'isFraud', 'id_01', 'id_02', 'DeviceType','Device_info_clean'])
id_exist = i_merged[selected].assign(Exist = 1)
id_exist.DeviceType.fillna('unknown', inplace = True)
id_exist.to_csv('identity_first.csv',index = False) | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
Test: Decision Tree / Random Forest Test | from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score, roc_auc_score
X = id_exist.drop([... | F1:0.22078820004609356
| MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
-------------------------- | param_grid = {
'max_depth': list(range(10,51,10)),
'n_estimators': [20, 20, 20]
}
rf = RandomForestClassifier()
gs = GridSearchCV(estimator = rf, param_grid = param_grid,
cv = 5, n_jobs = -1, verbose = 2)
gs.fit(X_train,y_train)
best_rf = gs.best_estimator_
print('best parameter: \n'... | Accuracy:0.9298821354287035
Precision:0.6993006993006993
Recall:0.20390329158170697
F1:0.31574199368516015
ROC_AUC:0.5981737508690471
| MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
----------------------- 거래 + ID merge | transaction_c = pd.read_csv('train_combined.csv')
id_c = pd.read_csv('identity_first.csv')
region = pd.read_csv('region.csv')
country = region[['TransactionID', 'Country_code']]
country.head()
f_draft = transaction_c.merge(id_c.drop(['isFraud'], axis = 1) ,how = 'left', on = 'TransactionID')
f_draft.drop('DeviceInfo', ... | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
Categorical: 'ProductCD', 'card4', 'card6', 'D15', 'DeviceType', 'Device_info_clean' | print(
f_draft.ProductCD.unique(),
f_draft.card4.unique(),
f_draft.card6.unique(),
f_draft.D15.unique(),
f_draft.DeviceType.unique(),
f_draft.Device_info_clean.unique(),
)
print(map_ProductCD, map_card4,map_card6,map_D15, sep = '\n') | {'W': 0, 'H': 1, 'C': 2, 'S': 3, 'R': 4}
{'discover': 0, 'mastercard': 1, 'visa': 2, 'american express': 3}
{'credit': 0, 'debit': 1, 'debit or credit': 2, 'charge card': 3}
{'credit': 0, 'debit': 1, 'debit or credit': 2, 'charge card': 3}
| MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
map_ProductCD = {'W': 0, 'H': 1, 'C': 2, 'S': 3, 'R': 4}map_card4 = {'discover': 0, 'mastercard': 1, 'visa': 2, '}american express': 3}map_card6 = {'credit': 0, 'debit': 1, 'debit or credit': 2, 'charge card': 3}map_D15 = {'credit': 0, 'debit': 1, 'debit or credit': 2, 'charge card': 3}map_DeviceType = {'mobile':2 'des... | f_draft.ProductCD = f_draft.ProductCD.map(map_ProductCD)
f_draft.card4 = f_draft.card4.map(map_card4)
f_draft.card6 = f_draft.card6.map(map_card6)
f_draft.D15 = f_draft.D15.map(map_D15)
f_draft.DeviceType = f_draft.DeviceType.map(map_DeviceType)
f_draft.Device_info_clean = f_draft.Device_info_clean.map(map_Device_info_... | _____no_output_____ | MIT | 19_ybita_fraud-detection/identity_pre-processing.ipynb | ski02049/repos |
READMEThis notebook extracts some information about fitting. For each molecule, it creates a CSV file.It calculates the Euclidean distance and topological distance (number of bonds separating an atom and the halogen). | def parsePrepAc(prep_ac):
# read file content
with open(prep_ac) as stream:
lines = stream.readlines()
# browse file content
atoms = {}
bonds = []
ref_at_name = None
for line in lines:
l_spl = line.split()
# skip short
if len(l_spl)... | _____no_output_____ | MIT | scripts/.ipynb_checkpoints/getOverviews-checkpoint.ipynb | mhkoscience/leskourova-offcenter |
Load Data | import pandas as pd
import numpy as np
isMergedDatasetAvailabel = True
if not isMergedDatasetAvailabel:
train_bodies_df = pd.read_csv('train_bodies.csv')
train_stance_df = pd.read_csv('train_stances.csv')
test_bodies_df = pd.read_csv('competition_test_bodies.csv')
test_stance_df = pd.read_csv('competition_test... | _____no_output_____ | MIT | DataCleansingAndEda.ipynb | Pager07/A-Hackers-AI-Voice-Assistant |
Data Cleaning | import re
import numpy as np
from sklearn import feature_extraction
from sklearn.feature_extraction.text import CountVectorizer
import nltk
from nltk.corpus import wordnet
from nltk.tokenize import word_tokenize
#downloads
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')
wnl= nltk.WordNetLe... | _____no_output_____ | MIT | DataCleansingAndEda.ipynb | Pager07/A-Hackers-AI-Voice-Assistant |
EDA | def get_top_trigrams(corpus, n=10):
vec = CountVectorizer(ngram_range=(3, 3)).fit(corpus) # parameter is set for 2 (bigram)
bag_of_words = vec.transform(corpus)
sum_words = bag_of_words.sum(axis=0)
words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()]
words_freq... | _____no_output_____ | MIT | DataCleansingAndEda.ipynb | Pager07/A-Hackers-AI-Voice-Assistant |
1.a tf-idf feature extraction | from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.sparse import hstack
totaldata= (train_merged['articleBody'].tolist() + train_merged['Headline'].tolist()+test_merged['articleBody'].tolist()+test_merged['Headline'].tolist())
tfidf_vect = TfidfVectorizer(analyzer='word', token_pattern=r'\w{1,}', ... | ===Starting train headline====
===Starting Train body====
===Starting Test headline====
===Starting Test articleBody====
['unrelated' 'related'] ['unrelated' 'related']
| MIT | DataCleansingAndEda.ipynb | Pager07/A-Hackers-AI-Voice-Assistant |
Train with tf-idf features - Navie Bayes | from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
from sklearn import metrics
from sklearn.metrics import confusion_matrix,accuracy_score,roc_auc_score,roc_curve,auc,f1_score
from sklearn.preprocessing import LabelEncoder
def binary_labels(label):
if label in ['discuss', 'agree'... | _____no_output_____ | MIT | DataCleansingAndEda.ipynb | Pager07/A-Hackers-AI-Voice-Assistant |
TF-idf Binary classification with logistice regression Steps: - Create k-fold starififed dataloader [x] - Use Sampler to have more control over the batch - Write a function get_dataloaders() that will return dict of shape fold_id x tuple. The tuple contains dataloader - Train the modle on all the splits [x] - H... | from torch.utils.data import DataLoader,Dataset
import torch
from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold
from torch.utils.data import ConcatDataset,SubsetRandomSampler
from collections import defaultdict
class TfidfBinaryStanceDataset(Dataset):
def __init__(self, X,Y)... | Starting training for fold:0
nfold:0,epoch:4,train loss:0.6024146110324536, eval loss:0.6200127760569255, fm1:0.41559849509023383
nfold:0,epoch:9,train loss:0.5978681485531694, eval loss:0.6050375978151957, fm1:0.4030031157333551
nfold:0,epoch:14,train loss:0.5998595609503278, eval loss:0.5948281049728393, fm1:0.407867... | MIT | DataCleansingAndEda.ipynb | Pager07/A-Hackers-AI-Voice-Assistant |
test | #net = torch.load('./net.pth')
net.eval()
x_test = torch.from_numpy(X_test_tfidf).to(device).float()
probs = net(x_test)
prediction = probs.argmax(dim=1).detach().cpu().numpy()
# #print the classification report to highlight the accuracy with f1-score, precision and recall
prediction = ['unrelated' if p else 'related' ... | _____no_output_____ | MIT | DataCleansingAndEda.ipynb | Pager07/A-Hackers-AI-Voice-Assistant |
Using Google Colab with GitHub [Google Colaboratory](http://colab.research.google.com) is designed to integrate cleanly with GitHub, allowing both loading notebooks from github and saving notebooks to github. Loading Public Notebooks Directly from GitHubColab can load public github notebooks directly, with no requir... | _____no_output_____ | MIT | colab-example-notebooks/colab_github_demo.ipynb | tuanavu/deep-learning-tutorials | |
AzMeta Resize Recommendations | import datetime
print("Report Date:", datetime.datetime.now().isoformat())
print("Total Annual Savings:", "${:,.2f}".format(local_data[('AzMeta', 'annual_savings')].sum()), "(Non-RI Pricing, SQL and Windows AHUB Licensing)")
# Present the dataset
import matplotlib as plt
import itertools
from matplotlib import colors
... | _____no_output_____ | MIT | src/rightsize/rightsizereport.ipynb | wpbrown/azmeta-rightsize-iaas |
Cowell's formulationFor cases where we only study the gravitational forces, solving the Kepler's equation is enough to propagate the orbit forward in time. However, when we want to take perturbations that deviate from Keplerian forces into account, we need a more complex method to solve our initial value problem: one ... | import numpy as np
from astropy import units as u
from matplotlib import pyplot as plt
plt.ion()
from poliastro.bodies import Earth
from poliastro.twobody import Orbit
from poliastro.examples import iss
from poliastro.twobody.propagation import cowell
from poliastro.plotting import OrbitPlotter3D
from poliastro.util... | _____no_output_____ | MIT | docs/source/examples/Propagation using Cowell's formulation.ipynb | nikita-astronaut/poliastro |
To provide an acceleration depending on an extra parameter, we can use **closures** like this one: | accel = 2e-5
def constant_accel_factory(accel):
def constant_accel(t0, u, k):
v = u[3:]
norm_v = (v[0]**2 + v[1]**2 + v[2]**2)**.5
return accel * v / norm_v
return constant_accel
def custom_propagator(orbit, tof, rtol, accel=accel):
# Workaround for https://github.com/poliastro/poli... | _____no_output_____ | MIT | docs/source/examples/Propagation using Cowell's formulation.ipynb | nikita-astronaut/poliastro |
And we plot the results: | frame = OrbitPlotter3D()
frame.set_attractor(Earth)
frame.plot_trajectory(positions, label="ISS")
frame.show() | _____no_output_____ | MIT | docs/source/examples/Propagation using Cowell's formulation.ipynb | nikita-astronaut/poliastro |
Error checking | def state_to_vector(ss):
r, v = ss.rv()
x, y, z = r.to(u.km).value
vx, vy, vz = v.to(u.km / u.s).value
return np.array([x, y, z, vx, vy, vz])
k = Earth.k.to(u.km**3 / u.s**2).value
rtol = 1e-13
full_periods = 2
u0 = state_to_vector(iss)
tf = ((2 * full_periods + 1) * iss.period / 2).to(u.s).value
u0, t... | _____no_output_____ | MIT | docs/source/examples/Propagation using Cowell's formulation.ipynb | nikita-astronaut/poliastro |
Numerical validationAccording to [Edelbaum, 1961], a coplanar, semimajor axis change with tangent thrust is defined by:$$\frac{\operatorname{d}\!a}{a_0} = 2 \frac{F}{m V_0}\operatorname{d}\!t, \qquad \frac{\Delta{V}}{V_0} = \frac{1}{2} \frac{\Delta{a}}{a_0}$$So let's create a new circular orbit and perform the necessa... | ss = Orbit.circular(Earth, 500 * u.km)
tof = 20 * ss.period
ad = constant_accel_factory(1e-7)
r, v = cowell(ss, tof.to(u.s).value, ad=ad)
ss_final = Orbit.from_vectors(Earth, r * u.km, v * u.km / u.s, ss.epoch + tof)
da_a0 = (ss_final.a - ss.a) / ss.a
da_a0
dv_v0 = abs(norm(ss_final.v) - norm(ss.v)) / norm(ss.v)
2 *... | _____no_output_____ | MIT | docs/source/examples/Propagation using Cowell's formulation.ipynb | nikita-astronaut/poliastro |
This means **we successfully validated the model against an extremely simple orbit transfer with approximate analytical solution**. Notice that the final eccentricity, as originally noticed by Edelbaum, is nonzero: | ss_final.ecc | _____no_output_____ | MIT | docs/source/examples/Propagation using Cowell's formulation.ipynb | nikita-astronaut/poliastro |
Print DependenciesDependences are fundamental to record the computational environment. | %load_ext watermark
# python, ipython, packages, and machine characteristics
%watermark -v -m -p pandas,keras,numpy,math,tensorflow,matplotlib,h5py
# date
print (" ")
%watermark -u -n -t -z | Python implementation: CPython
Python version : 3.8.8
IPython version : 7.22.0
pandas : 1.2.3
keras : 2.4.3
numpy : 1.19.5
math : unknown
tensorflow: 2.4.1
matplotlib: 3.4.0
h5py : 2.10.0
Compiler : Clang 12.0.0 (clang-1200.0.32.29)
OS : Darwin
Release : 19.6.0
Machine ... | MIT | notebooks/.ipynb_checkpoints/Comp_Scatt_NeuralNetwork_Classification_noposition-Copy1-checkpoint.ipynb | chiarabadiali/comp_scatt_ML |
Load of the data | from process import loaddata
class_data0 = loaddata("../data/{}.csv".format('low_ene'))
class_data0 = class_data0[class_data0[:,0] > 0.001]
class_data0.shape
y0 = class_data0[:,0]
A0 = class_data0
A0[:,9] = A0[:,13]
x0 = class_data0[:,1:10] | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Comp_Scatt_NeuralNetwork_Classification_noposition-Copy1-checkpoint.ipynb | chiarabadiali/comp_scatt_ML |
Check to see if the data are balanced now | from matplotlib import pyplot
y0 = np.array(y0)
bins = np.linspace(0, 0.55, 50)
n, edges, _ = pyplot.hist(y0, bins, color = 'indianred', alpha=0.5, label='Osiris')
#pyplot.hist(y_pred, bins, color = 'mediumslateblue', alpha=0.5, label='NN')
pyplot.legend(loc='upper right')
pyplot.xlabel('Probability')
pyplot.yscale('lo... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Comp_Scatt_NeuralNetwork_Classification_noposition-Copy1-checkpoint.ipynb | chiarabadiali/comp_scatt_ML |
Model Build | from keras.models import Sequential
from keras.layers.core import Dense
import keras.backend as K
from keras import optimizers
from keras import models
from keras import layers
from keras.layers.normalization import BatchNormalization
def build_model() :
model = models.Sequential()
model.add (BatchNormalization... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Comp_Scatt_NeuralNetwork_Classification_noposition-Copy1-checkpoint.ipynb | chiarabadiali/comp_scatt_ML |
Probability density distribution | y0 = class_data0[:,0]
A0 = class_data0
A0[:,9] = A0[:,13]
x0 = class_data0[:,1:10]
y_pred = model.predict(x0)
y_pred
from matplotlib import pyplot
y = np.array(y)
bins = np.linspace(0, 0.8, 100)
pyplot.hist(y0, bins, color = 'indianred', alpha=0.5, label='Osiris')
pyplot.hist(y_pred, bins, color = 'mediumslateblue', al... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Comp_Scatt_NeuralNetwork_Classification_noposition-Copy1-checkpoint.ipynb | chiarabadiali/comp_scatt_ML |
Recreation of Terry's Notebook with NgSpiceIn this experiment we are going to recreate Terry's notebook with NgSpice simulation backend. Step 1: Set up Python3 and NgSpice | %matplotlib inline
import matplotlib.pyplot as plt
# check if ngspice can be found from python
from ctypes.util import find_library
ngspice_lib_filename = find_library('libngspice')
print(ngspice_lib_filename) ## if the result is none, make sure that libngspice is installed
import PySpice.Logging.Logging as Logging
l... | /usr/local/lib/libngspice.dylib
******
** ngspice-32 : Circuit level simulation program
** The U. C. Berkeley CAD Group
** Copyright 1985-1994, Regents of the University of California.
** Copyright 2001-2020, The ngspice team.
** Please get your ngspice manual from http://ngspice.sourceforge.net/docs.html
** Please fil... | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Step 2: Define a single neuron Let's start with the subcircuit of a single neuron. We are going to use voltage amplifier leaky-integrate and fire neurons discussed in Section 3.3 of Indiveri et al.(May 2011). | neuron_model = '''
.subckt my_neuron Vmem out cvar=100p vsupply=1.8 vtau=0.4 vthr=0.2 vb=1
V1 Vdd 0 {vsupply}
V6 Vtau 0 {vtau}
V2 Vthr 0 {vthr}
V3 Vb1 0 {vb}
C1 Vmem 0 {cvar}
M5 N001 N001 Vdd Vdd pmos l=0.5 w=1.2 ad=1.2 as=1.2 pd=4.4 ps=4.4
M6 N002 N001 Vdd Vdd pmos l=0.5 w=1.2 ad=1.2 as=1.2 pd=4.4 ps=4.4
M8 N001 Vm... | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Create the neuron's netlist | def create_neuron_netlist(N):
# N is the number of neurons
netlist = ''
for i in range(N):
netlist += 'x'+str(i)+' Vmem'+str(i)+' out'+str(i)+' my_neuron vsupply={vsource} cvar=150p vthr=0.25 \n'
netlist += 'Rload'+str(i)+' out'+str(i)+ ' 0 100k\n'
return netlist
netlist_neurons = creat... | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Step 3: Generate the input Now, let's generate some input and see what it does. We are going to use the WhiteSignal that Terry used; however,we are going to shink the signal in amplitude (since this would be a current signal in the circuit) and also increase the frequency of the signal. | stim = nengo.processes.WhiteSignal(period=10, high=5, seed=1).run(1, dt=0.001)
input_signal = [[i*1e-6, J[0]*10e-6] for i, J in enumerate(stim)] #scaling | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Lets convert this signal to a current source. | def pwl_conv(signal):
# signal should be a list of lists where wach sublist has this form [time_value, current_value]
pwl_string = ''
for i in signal:
pwl_string += str(i[0]) + ' ' + str(i[1]) + ' '
return pwl_string | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Step 4: Generate remaining parts of the Spice Netlist | netlist_input = 'Iin0 Vdd Vmem0 PWL(' + pwl_conv(input_signal) +')\n' # Converting the input to a current source
## other setup parameters
args= {}
args['simulation_time'] = '1m'
args['simulation_step'] = '1u'
args['simulation_lib'] = '180nm.lib'
netlist_top= '''*Sample SPICE file
.include {simulation_lib}
.option s... | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Step 5: Simulate the netlist | def simulate(circuit):
ngspice.load_circuit(circuit)
ngspice.run()
print('Plots:', ngspice.plot_names)
plot = ngspice.plot(simulation=None, plot_name=ngspice.last_plot)
return plot
out=simulate(netlist)
plt.plot(out['time']._data,out['@rload0[i]']._data, label='output_current')
plt.plot(out['time'].... | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Great! We have a system that does some sort of nonlinearity. Now let's create a feedforward system with a bunch of neurons and see if the system can be used for approximating a function. Step 6: Function approximation with a feedforward network | N = 50 # how many neurons there are
E = np.random.normal(size=(N, 1))
B = np.random.normal(size=(N))*0.1
netlist_neurons = create_neuron_netlist(N) | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
*Now let's feed that same stimulus to all the neurons and see how they behave.* | def create_neuron_current_netlist(E,B,stim,N):
# take the A matrix and the number of neurons
# refactor
netlist_input='\n'
signal = np.zeros((len(stim), N))
for i, J in enumerate(stim):
Js = np.dot(E, J)
for k, JJ in enumerate(Js):
signal[i][k] = JJ+B[k]
for k i... | 2020-09-08 17:06:15,916 - PySpice.Spice.NgSpice.Shared.NgSpiceShared - Shared.WARNING - Warning: iin49: no DC value, transient time 0 value used
2020-09-08 17:06:15,917 - PySpice.Spice.NgSpice.Shared.NgSpiceShared - Shared.WARNING - Warning: iin48: no DC value, transient time 0 value used
2020-09-08 17:06:15,919 - PySp... | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
So it seems we have some output from the ensemble. Lets convert this output to get the A matrix | def extract_A_matrix(result, N, stim):
t = np.linspace(min(out['time']._data), max(out['time']._data), len(stim))
temp_time = out['time']._data
inpterpolated_result = np.zeros((len(stim), N))
A = np.zeros((len(stim), N))
for j in range(N):
temp_str = '@rload'+str(j)+'[i]'
temp_out = ... | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Cool! This is similar to the A matrix we got from Terry's notebook. We can also calculate the D matrix from this output and approximate the y(t)=x(t) function. | target = stim
D_from_spice, info = nengo.solvers.LstsqL2()(A_from_spice, target)
plt.plot(A_from_spice.dot(D_from_spice), label='output')
plt.plot(target, lw=3, label='target')
plt.legend()
plt.show()
print('RMSE:', info['rmses']) | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
*With spiking neuron models, it's very common to have a low-pass filter (i.e. a synapse) after the spike. Let's see what our output looks like with a low-pass filter applied.* | filt = nengo.synapses.Lowpass(0.01) #need to implement synapses in circuit
plt.plot(filt.filt(A_from_spice.dot(D_from_spice)), label='output (filtered)')
plt.plot(target, lw=3, label='target')
plt.legend()
plt.show() | _____no_output_____ | MIT | Ngspice/Recreating_Terrys_Notebook_with_spice_Part_1.ipynb | JD-14/grill-spice |
Python in Jupyter Fremont bicycle data demo Antero Kangas 3.6.2018 | %matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn')
from jupyterworkflow2.data import get_fremont_data
data = get_fremont_data()
data.head()
data.resample("W").sum().plot()
ax = data.resample("D").sum().rolling(365).sum().plot()
ax.set_ylim(0, None)
data.groupby(data.index.time).mean().plot()
pi... | _____no_output_____ | MIT | JupyterWorkflow2.ipynb | Andycappfi/JupyterWorkflow2 |
Scale everything | scaler = StandardScaler()
X_scale = scaler.fit_transform(X_res)
X_scale_torch = torch.FloatTensor(X_scale)
y_scale_torch = torch.FloatTensor(y_res)
y_scale_torch
from skorch import NeuralNetBinaryClassifier
from classes import MyModule
class toTensor(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
... | 10.4 ms ± 538 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
| MIT | NeuralNet-Classification-REST/NeuralNet.ipynb | rphillip/Case-Studies |
Embeds | df.columns
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler
lincolumns = (['LIMIT_BAL','AGE', 'BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6',
'PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6'])
ct = ColumnTran... | _____no_output_____ | MIT | NeuralNet-Classification-REST/NeuralNet.ipynb | rphillip/Case-Studies |
Py Torch | ## train data
class TrainData(Dataset):
def __init__(self, X_data, y_data):
self.X_data = X_data
self.y_data = y_data
def __getitem__(self, index):
return self.X_data[index], self.y_data[index]
def __len__ (self):
return len(self.X_data)
train_data = ... | _____no_output_____ | MIT | NeuralNet-Classification-REST/NeuralNet.ipynb | rphillip/Case-Studies |
For Loops (2) - Looping through the items in a sequence In the last lesson we introduced the concept of a For loop and learnt how we can use them to repeat a section of code. We learnt how to write a For loop that repeats a piece of code a specific number of times using the range() function, and saw that we have to c... | list1 = ['a', 'b', 'c', 'd', 'e']
for item in list1:
print(item) | a
b
c
d
e
| MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
It's not important what we call this variable: | for banana in list1:
print(banana) | a
b
c
d
e
| MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
But it's probably a good idea to call the variable something meaningful: | data = [20, 50, 10, 67]
for d in data:
print(d) | 20
50
10
67
| MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
Using these loopsWe can use these loops in conjunction with other concepts we have already learnt. For example, imagine that you had a list of proportions stored as decimals, but that you needed to create a new list to store them as whole numbers.We can use list.append() with a for loop to create this new list. First,... | proportions = [0.3, 0.45, 0.99, 0.23, 0.46]
percentages = [] | _____no_output_____ | MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
Next, we'll loop through each item in proportions, multiply it by 100 and append it to percentages: | for prop in proportions:
percentages.append(prop * 100)
print(percentages) | [30.0, 45.0, 99.0, 23.0, 46.0]
| MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
Using for loops with dictionariesWe've seen how to loop through each item in a list. We will also make great use of the ability to loop through the keys and values in a dictionary.If you remember from the dictionaries lessons, we can get the keys and values in a dictionary by using dict.items(). We can use this in con... | data = {2009 : [10,20,30,40],
2010 : [15,30,45,60],
2011 : [7,14,21,28],
2012 : [5,10,15,20]} | _____no_output_____ | MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
We can loop through the keys by using dict.keys(): | for k in data.keys():
print(k) | 2009
2010
2011
2012
| MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
And we can loop through the values (which are lists): | for v in data.values():
print(v) | [10, 20, 30, 40]
[15, 30, 45, 60]
[7, 14, 21, 28]
[5, 10, 15, 20]
| MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
We can loop through them both together: | for k, v in data.items():
print(k, v) | 2009 [10, 20, 30, 40]
2010 [15, 30, 45, 60]
2011 [7, 14, 21, 28]
2012 [5, 10, 15, 20]
| MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
Having the data available to compare each year is really handy, but it might also be helpful to store them as one long list so we can plot the data and see trends over time. First, we'll make a new list to store all of the data items: | allYears = [] | _____no_output_____ | MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
And then we'll loop through the dictionary and concatenate each year's data to the allYears list: | for v in data.values():
allYears = allYears + v
print(allYears) | [10, 20, 30, 40, 15, 30, 45, 60, 7, 14, 21, 28, 5, 10, 15, 20]
| MIT | PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/(12) For Loops (2) - Looping through the items in a sequence.ipynb | peternewman22/Python_Courses |
Import modules | import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import os
import sys
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
sys.path.append(os.path.abspath(os.path.join('lib', 'xbeach-toolbox', ... | _____no_output_____ | MIT | post-processing.ipynb | Sustainable-Science/northbay |
Image data prep | catalog_eng= pd.read_csv("/kaggle/input/textphase1/data/catalog_english_taxonomy.tsv",sep="\t")
X_train= pd.read_csv("/kaggle/input/textphase1/data/X_train.tsv",sep="\t")
Y_train= pd.read_csv("/kaggle/input/textphase1/data/Y_train.tsv",sep="\t")
X_test=pd.read_csv("/kaggle/input/textphase1/data/x_test_task1_phase1.tsv"... | Validation F1-Score: 0.9093939540881769
| MIT | multi-modal_concatenate_fusion.ipynb | depshad/Deep-Learning-Framework-for-Multi-modal-Product-Classification |
OptimizationThings to try:- change the number of samples- without and without bias- with and without regularization- changing the number of layers- changing the amount of noise- change number of degrees- look at parameter values (high) in OLS- tarin network for many epochs | from fastprogress.fastprogress import progress_bar
import torch
import matplotlib.pyplot as plt
from jupyterthemes import jtplot
jtplot.style(context="talk")
def plot_regression_data(model=None, MSE=None, poly_deg=0):
# Plot the noisy scatter points and the "true" function
plt.scatter(x_train, y_train, labe... | _____no_output_____ | CC0-1.0 | lectures/l15-optimization-part1.ipynb | davidd-55/cs152fa21 |
Create Fake Training Data | def fake_y(x, add_noise=False):
y = 10 * x ** 3 - 5 * x
return y + torch.randn_like(y) * 0.5 if add_noise else y
N = 20
min_x, max_x = -1, 1
x_true = torch.linspace(min_x, max_x, 100)
y_true = fake_y(x_true)
x_train = torch.rand(N) * (max_x - min_x) + min_x
y_train = fake_y(x_train, add_noise=True)
plot_re... | _____no_output_____ | CC0-1.0 | lectures/l15-optimization-part1.ipynb | davidd-55/cs152fa21 |
Train A Simple Linear Model Using Batch GD | # Hyperparameters
learning_rate = 0.1
num_epochs = 100
# Model parameters
m = torch.randn(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
params = (b, m)
# Torch utils
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(params, lr=learning_rate)
# Regression
for epoch in range(num_epochs):
... | _____no_output_____ | CC0-1.0 | lectures/l15-optimization-part1.ipynb | davidd-55/cs152fa21 |
Train Linear Regression Model Using Batch GD | # Hyperparameters
learning_rate = 0.1
num_epochs = 1000
# Model parameters
w2 = torch.randn(1, requires_grad=True)
w1 = torch.randn(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
params = (b, w1, w2)
# Torch utils
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(params, lr=learning_rate)
# ... | _____no_output_____ | CC0-1.0 | lectures/l15-optimization-part1.ipynb | davidd-55/cs152fa21 |
Train Complex Linear Regression Model Using Batch GD | # Hyperparameters
learning_rate = 0.1
num_epochs = 1000
# Model parameters
degrees = 50 # 3, 4, 16, 32, 64, 128
powers = torch.arange(degrees + 1)
x_poly = x_train.unsqueeze(-1).pow(powers)
params = torch.randn(degrees + 1, requires_grad=True)
# Torch utils
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(... | _____no_output_____ | CC0-1.0 | lectures/l15-optimization-part1.ipynb | davidd-55/cs152fa21 |
Compute Linear Regression Model Using Ordinary Least Squares | params = ((x_poly.T @ x_poly).inverse() @ x_poly.T) @ y_train
mse = torch.nn.functional.mse_loss(x_poly @ params, y_train)
plot_regression_data(lambda x: x @ params, poly_deg=degrees, MSE=mse)
# params
params | _____no_output_____ | CC0-1.0 | lectures/l15-optimization-part1.ipynb | davidd-55/cs152fa21 |
Train Neural Network Model Using Batch GD | # Hyperparameters
learning_rate = 0.01
num_epochs = 100000
regularization = 1e-2
# Model parameters
model = torch.nn.Sequential(
torch.nn.Linear(1, 100),
torch.nn.ReLU(),
torch.nn.Linear(100, 100),
torch.nn.ReLU(),
torch.nn.Linear(100, 100),
torch.nn.ReLU(),
torch.nn.Linear(100, 1),
)
# T... | tensor(-0.0212, grad_fn=<MeanBackward0>)
tensor(0.0280, grad_fn=<MeanBackward0>)
tensor(-0.0008, grad_fn=<MeanBackward0>)
tensor(-0.0142, grad_fn=<MeanBackward0>)
tensor(0.0008, grad_fn=<MeanBackward0>)
tensor(-0.0032, grad_fn=<MeanBackward0>)
tensor(0.0359, grad_fn=<MeanBackward0>)
tensor(-0.1043, grad_fn=<MeanBackwar... | CC0-1.0 | lectures/l15-optimization-part1.ipynb | davidd-55/cs152fa21 |
Hybrid Neural Net to solve Regression Problem We use a neural net with a quantum layer to predict the second half betting lines given the result of the first half and the opening line. The quantum layer is an 8 qubit layer and the model is from Keras. | import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import pennylane as qml
import warnings
warnings.filterwarnings('ignore')
tf.keras.backend.set_floatx('float64')
import warnings
warnings.filterwarnings('ig... | _____no_output_____ | MIT | Loo Boys/PythonNotebooks/betting.ipynb | ushnishray/Hackathon2021 |
Classical NN (Benchmarking) The MAE is twice as large for the purely classical NN. The quantum layer is helping the solution converge more quickly! (As an aside, the quantum NN takes alot longer to run) | clayer_1 = tf.keras.layers.Dense(8, activation="relu")
clayer_2 = tf.keras.layers.Dense(2, activation="relu")
model = tf.keras.models.Sequential([clayer_1, clayer_2])
opt = tf.keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss="mae", metrics=["mean_absolute_error"])
df = df[df.Open != 'pk']
df = df[df['2H... | Epoch 1/15
37/37 - 1s - loss: 10.3219 - mean_absolute_error: 10.3219 - val_loss: 9.8135 - val_mean_absolute_error: 9.8135
Epoch 2/15
37/37 - 0s - loss: 10.2575 - mean_absolute_error: 10.2575 - val_loss: 9.8118 - val_mean_absolute_error: 9.8118
Epoch 3/15
37/37 - 0s - loss: 10.2742 - mean_absolute_error: 10.2742 - val_l... | MIT | Loo Boys/PythonNotebooks/betting.ipynb | ushnishray/Hackathon2021 |
1-5.2 Python Intro conditionals, type, and mathematics extended- conditionals: `elif` - casting - **basic math operators** -----> Student will be able to- code more than two choices using `elif` - gather numeric input using type casting - **perform subtraction, multiplication and division operations in code**... | # [ ] review and run example
print("3 + 5 =",3 + 5)
print("3 + 5 - 9 =", 3 + 5 - 9)
print("48/9 =", 48/9)
print("5*5 =", 5*5)
print("(14 - 8)*(19/4) =", (14 - 8)*(19/4))
# [ ] review and run example - 'million_maker'
def million_maker():
make_big = input("enter a non-decimal number you wish were bigger: ")
retu... | enter a non-decimal number you wish were bigger: 5
Now you have 5000000
| MIT | Python Absolute Beginner/Module_3_5_Absolute_Beginner.ipynb | sdavi187/pythonteachingcode |
Task 1 use math operators to solve the set of tasks below | # [ ] print the result of subtracting 15 from 43
print (43 - 15)
# [ ] print the result of multiplying 15 and 43
print (15*43)
# [ ] print the result of dividing 156 by 12
print (156/12)
# [ ] print the result of dividing 21 by 0.5
print (21/0.5)
# [ ] print the result of adding 111 plus 84 and then subtracting 45
... | 100
| MIT | Python Absolute Beginner/Module_3_5_Absolute_Beginner.ipynb | sdavi187/pythonteachingcode |
Task 2 Program: Multiplying Calculator Function- define function **`multiply()`**, and within the function: - gets user input() of 2 *strings* made of whole numbers - cast the input to **`int()`** - multiply the integers and **return** the equation with result as a **`str()`** - **return** example ``... | # [ ] create and test multiply() function
def multiply():
num_1 = input ("Enter a whole number:")
num_2 = input ("Enter a second whole number:")
return (str(int(num_1)*int(num_2)))
print(multiply() + " is a string") | Enter a whole number:23
Enter a second whole number:34
782 is a string
| MIT | Python Absolute Beginner/Module_3_5_Absolute_Beginner.ipynb | sdavi187/pythonteachingcode |
Task 3 Project: Improved Multiplying Calculator Function putting together conditionals, input casting and math- update the multiply() function to multiply or divide - single parameter is **`operator`** with arguments of **`*`** or **`/`** operator - default operator is "*" (multiply) - **return** the resul... | # [ ] create improved multiply() function and test with /, no argument, and an invalid operator ($)
def multiply(operator = "*"):
num_1 = input ("Enter a whole number:")
num_2 = input ("Enter a second whole number:")
if operator == "*":
return (str(int(num_1)*int(num_2)))
elif operator =="/... | Would you like to multiply (m) or divide (d)?d
Enter a whole number:3
Enter a second whole number:1
3.0
| MIT | Python Absolute Beginner/Module_3_5_Absolute_Beginner.ipynb | sdavi187/pythonteachingcode |
Task 4 Fix the Errors | # Review, run, fix
student_name = input("enter name: ").capitalize()
if student_name.startswith("F"):
print(student_name,"Congratulations, names starting with 'F' get to go first today!")
elif student_name.startswith("G"):
print(student_name,"Congratulations, names starting with 'G' get to go second today!")
e... | enter name: frank
Frank Congratulations, names starting with 'F' get to go first today!
| MIT | Python Absolute Beginner/Module_3_5_Absolute_Beginner.ipynb | sdavi187/pythonteachingcode |
1. Import packages | from keras.models import Sequential, Model
from keras.layers import *
from keras.layers.advanced_activations import LeakyReLU
from keras.activations import relu
from keras.initializers import RandomNormal
from keras.applications import *
import keras.backend as K
from tensorflow.contrib.distributions import Beta
import... | _____no_output_____ | MIT | 0-newbooks/faceswap-GAN/FaceSwap_GAN_v2_test_img.ipynb | gopala-kr/ds-notebooks |
4. Configmixup paper: https://arxiv.org/abs/1710.09412Default training data directories: `./faceA/` and `./faceB/` | K.set_learning_phase(1)
channel_axis=-1
channel_first = False
IMAGE_SHAPE = (64, 64, 3)
nc_in = 3 # number of input channels of generators
nc_D_inp = 6 # number of input channels of discriminators
use_perceptual_loss = False
use_lsgan = True
use_instancenorm = False
use_mixup = True
mixup_alpha = 0.2 # 0.2
batchSize ... | _____no_output_____ | MIT | 0-newbooks/faceswap-GAN/FaceSwap_GAN_v2_test_img.ipynb | gopala-kr/ds-notebooks |
5. Define models | from model_GAN_v2 import *
encoder = Encoder()
decoder_A = Decoder_ps()
decoder_B = Decoder_ps()
x = Input(shape=IMAGE_SHAPE)
netGA = Model(x, decoder_A(encoder(x)))
netGB = Model(x, decoder_B(encoder(x)))
netDA = Discriminator(nc_D_inp)
netDB = Discriminator(nc_D_inp) | _____no_output_____ | MIT | 0-newbooks/faceswap-GAN/FaceSwap_GAN_v2_test_img.ipynb | gopala-kr/ds-notebooks |
6. Load Models | try:
encoder.load_weights("models/encoder.h5")
decoder_A.load_weights("models/decoder_A.h5")
decoder_B.load_weights("models/decoder_B.h5")
#netDA.load_weights("models/netDA.h5")
#netDB.load_weights("models/netDB.h5")
print ("model loaded.")
except:
print ("Weights file not found.")
pas... | model loaded.
| MIT | 0-newbooks/faceswap-GAN/FaceSwap_GAN_v2_test_img.ipynb | gopala-kr/ds-notebooks |
7. Define Inputs/Outputs Variables distorted_A: A (batch_size, 64, 64, 3) tensor, input of generator_A (netGA). distorted_B: A (batch_size, 64, 64, 3) tensor, input of generator_B (netGB). fake_A: (batch_size, 64, 64, 3) tensor, output of generator_A (netGA). fake_B: (batch_size, 64, 64, 3) tensor, output ... | def cycle_variables(netG):
distorted_input = netG.inputs[0]
fake_output = netG.outputs[0]
alpha = Lambda(lambda x: x[:,:,:, :1])(fake_output)
rgb = Lambda(lambda x: x[:,:,:, 1:])(fake_output)
masked_fake_output = alpha * rgb + (1-alpha) * distorted_input
fn_generate = K.function([distorte... | _____no_output_____ | MIT | 0-newbooks/faceswap-GAN/FaceSwap_GAN_v2_test_img.ipynb | gopala-kr/ds-notebooks |
11. Helper Function: face_swap()This function is provided for those who don't have enough VRAM to run dlib's CNN and GAN model at the same time. INPUTS: img: A RGB face image of any size. path_func: a function that is either path_abgr_A or path_abgr_B. OUPUTS: result_img: A RGB swapped face ... | def swap_face(img, path_func):
input_size = img.shape
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # generator expects BGR input
ae_input = cv2.resize(img, (64,64))/255. * 2 - 1
result = np.squeeze(np.array([path_func([[ae_input]])]))
result_a = result[:,:,0] * 255
result_bgr = np... | _____no_output_____ | MIT | 0-newbooks/faceswap-GAN/FaceSwap_GAN_v2_test_img.ipynb | gopala-kr/ds-notebooks |
In this notebook I'm going to generate simulated MIRI time series imaging data, to provide as test set for ESA Datalabs. To install Mirisim, see the [the public release webpage](http://miri.ster.kuleuven.be/bin/view/Public/MIRISim_Public). The target for the mock observations is WASP-103, an exoplanet host star with th... | arr = ['FULL', 'SUB64']
ngrp = [5, 60]
#nints = [200, 600]
nints = [1, 1] | _____no_output_____ | BSD-3-Clause | TSO-imaging-sims/datalabs-sim/MIRI_im_tso_datalabs.ipynb | STScI-MIRI/TSO-MIRI-simulations |
Step 1: Creating the input scene (WASP-103)Here we'll create the input scene for the simulations using the function wasp103_scene(). Arguments:* scene_file: the filename for the .ini file* write_cube: write the scene image out to a FITS file (optional; default=False)The function returns a mirisim.skysim.scenes.Composi... | scene_ini = wasp103_scene(scene_file='wasp103_scene.ini', write_cube=False)
print(scene_ini) | wasp103_scene.ini
| BSD-3-Clause | TSO-imaging-sims/datalabs-sim/MIRI_im_tso_datalabs.ipynb | STScI-MIRI/TSO-MIRI-simulations |
Step 2: Configuring the simulationNow I'll set up the simulations and prepare to run them. I'll set it up to loop through the 2 simulations. For this I wrote the function wasp103_sim_config. Check the docstring for descriptions and default values of the arguments. The function will write out another .ini file containi... | #reload(tso_img_sims_setup)
#from tso_img_sims_setup import wasp103_sim_config
for (a, g, i) in zip(arr, ngrp, nints):
sim_ini = wasp103_sim_config(mode='imaging', arr=a, ngrp=g, nint=i, nexp=1, filt='F770W',
scene_file=scene_ini, out=True)
print(sim_ini) | Found scene file wasp103_scene.ini
wasp103_FULL_5G1I1E_simconfig.ini exists, overwrite (y/[n])?y
wasp103_FULL_5G1I1E_simconfig.ini
Found scene file wasp103_scene.ini
wasp103_SUB64_60G1I1E_simconfig.ini exists, overwrite (y/[n])?y
wasp103_SUB64_60G1I1E_simconfig.ini
| BSD-3-Clause | TSO-imaging-sims/datalabs-sim/MIRI_im_tso_datalabs.ipynb | STScI-MIRI/TSO-MIRI-simulations |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.