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 |
|---|---|---|---|---|---|
Assign barcodes according to primer plateThis portion of the notebook will assign a barcode to each sample according to the primer plate number.As inputs, it requires:1. A plate map dataframe (from previous step)2. Preparation metadata for the plates, importantly we need the Primer Plate so we know what **EMP barcode... | _metadata = [
{
# top left plate
'Plate Position': '1',
'Primer Plate #': '1',
'Sample Plate': 'THDMI_UK_Plate_2',
'Project_Name': 'THDMI UK',
'Plating': 'SF',
'Extraction Kit Lot': '166032128',
'Extraction Robot': 'Carmen_HOWE_KF3',
... | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
The `Plate Position` and `Primer Plate ` allow us to figure out which wells are associated with each of the EMP barcodes. | if plate_metadata is not None:
plate_df = assign_emp_index(plate_df, plate_metadata, seq_type).reset_index()
plate_df.head()
else:
print('Error: Please fix the errors in the previous cell') | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
As you can see in the table above, the resulting table is now associated with the corresponding EMP barcodes (`Golay Barcode`, `Forward Primer Linker`, etc), and the plating metadata (`Primer Plate `, `Primer Date`, `Water Lot`, etc). | plate_df.head() | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Combine plates (optional)If you would like to combine existing plates with these samples, enter the path to their corresponding sample sheets and mapping (preparation) files below. Otherwise you can skip to the next section.- sample sheet and mapping (preparation) | files = [
# uncomment the line below and point to the correct filepaths to combine with previous plates
# ['test_output/amplicon/2021_08_17_THDMI-4-6_samplesheet.csv', 'test_output/amplicon/2021-08-01-515f806r_prep.tsv'],
]
sheets, preps = [], []
for sheet, prep in files:
sheets.append(KLSampleSheet(sheet)... | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Make Sample SheetThis workflow takes the pooled sample information and writes an Illumina sample sheet that can be given directly to the sequencing center or processing pipeline. Note that as of writing `bcl2fastq` does not support error-correction in Golay barcodes so the sample sheet is used to generate a mapping (p... | plate_df['sample sheet Sample_ID'] = plate_df['Sample'].map(bcl_scrub_name)
plate_df.head() | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Format the sample sheet dataThis step formats the data columns appropriately for the sample sheet, using the values we've calculated previously.The newly-created `bcl2fastq`-compatible names will be in the `Sample ID` and `Sample Name` columns. The original sample names will be in the Description column.Modify lanes t... | sequencer = 'HiSeq4000'
lanes = [1]
metadata = {
'Bioinformatics': [
{
'Sample_Project': 'THDMI_10317',
'QiitaID': '10317',
'BarcodesAreRC': 'False',
'ForwardAdapter': '',
'ReverseAdapter': '',
'HumanFiltering': 'True',
'library_construction_pr... | /Users/kfolelso/Documents/metagenomics_pooling_notebook_troubleshooting/metapool/sample_sheet.py:473: UserWarning: The column I5_Index_ID in the sample sheet is empty
warnings.warn('The column %s in the sample sheet is empty' %
/Users/kfolelso/Documents/metagenomics_pooling_notebook_troubleshooting/metapool/sample_sh... | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Check for any possible errors in the sample sheet | sheet = validate_and_scrub_sample_sheet(sheet) | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Add the other sample sheets | if len(sheets):
sheet.merge(sheets) | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Step 3: Write the sample sheet to file | # write sample sheet as .csv
sample_sheet_fp = './test_output/amplicon/2021_08_17_THDMI-4-6_samplesheet16S.csv'
if exists(sample_sheet_fp):
print("Warning! This file exists already.")
with open(sample_sheet_fp,'w') as f:
sheet.write(f)
!head -n 30 {sample_sheet_fp}
!echo ...
!tail -n 15 {sample_sheet_fp} | [Header],,,,,,,,,,
IEMFileVersion,4,,,,,,,,,
Date,2021-12-15,,,,,,,,,
Workflow,GenerateFASTQ,,,,,,,,,
Application,FASTQ Only,,,,,,,,,
Assay,TruSeq HT,,,,,,,,,
Description,,,,,,,,,,
Chemistry,Amplicon,,,,,,,,,
,,,,,,,,,,
[Reads],,,,,,,,,,
151,,,,,,,,,,
151,,,,,,,,,,
,,,,,,,,,,
[Settings],,,,,,,,,,
ReverseComplement,0,,,... | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Create a mapping (preparation) file for Qiita | output_filename = 'test_output/amplicon/2021-08-01-515f806r_prep.tsv'
qiita_df = generate_qiita_prep_file(plate_df, seq_type)
qiita_df.head()
qiita_df.set_index('sample_name', verify_integrity=True).to_csv(output_filename, sep='\t') | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Add the previous sample sheets | if len(preps):
prep = prep.append(preps, ignore_index=True)
!head -n 5 {output_filename} | sample_name barcode primer primer_plate well_id plating extractionkit_lot extraction_robot tm1000_8_tool primer_date mastermix_lot water_lot processing_robot tm300_8_tool tm50_8_tool sample_plate project_name orig_name well_description experiment_design_description library_construction_protocol linker platform run_cent... | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Machine Learning and Statistics Tasks 2020 Task 1: Python function sqrt2 Author: Ezekiel Onaloye Created: November 2020  Task 1Write a Python function called sqrt2 that calculates and prints to the screen the square root of 2 to 100 decimal places. IntroductionA square r... | # Python function called sqrt2
# Adapted from https://www.educative.io/edpresso/how-to-take-the-square-root-of-a-number-in-python
# Function takes input,calculates and prints to the screen the square root of 2 to 100 decimal places
n = int(input("Please input the base value: "))
def sqrt(n):
if n < 0:
return
... | Please input the base value: 2
The square root of 2 is 1.4142135623730951454746218587388284504413604736328125000000000000000000000000000000000000000000000000
| Apache-2.0 | Task_1.ipynb | ezekielonaloye-gmit/Machine-learning-and-statistics--Assessment-2020 |
Python function sqrt2 Algorithm 1. Let n be the given number2. create function sqrt2(takes a parameter)3. Given number stored as variable x4. y equate given number + 1 divided by 25. while y is less than x6. then x = y7. y store the value of x+n divided by itself and overall by 28. return y as the square root | # Python function called sqrt2
# Adapted from
# Function takes input,calculates and prints to the screen the square root of 2 to 100 decimal places
# user asked to enter a number
print("")
n = int(input("Please enter any number to find square root: "))
# function declared
def sqrt2(n):
# number entered stored ... |
Please enter any number to find square root: 2
Square root of 2 the given number is 1.4142135623730949234300169337075203657150268554687500000000000000000000000000000000000000000000000000
| Apache-2.0 | Task_1.ipynb | ezekielonaloye-gmit/Machine-learning-and-statistics--Assessment-2020 |
create dataset | hparams = HParams(
num_mel_bins = 32,
mel_lower_edge_hertz=100,
mel_upper_edge_hertz=22000,
butter_lowcut = 100,
butter_highcut = 22000,
ref_level_db = 25,
min_level_db = -50,
mask_spec = True,
win_length_ms = 5,
hop_length_ms = .5,
mask_spec_kwargs = {"spec_thresh": 0.9, "of... | _____no_output_____ | MIT | notebooks/02.0-make-syllable_df/3-create-swamp-sparrow-df.ipynb | xingjeffrey/avgn_paper |
Create dataset based upon JSON | from joblib import Parallel, delayed
n_jobs = -1; verbosity = 10
with Parallel(n_jobs=n_jobs, verbose=verbosity) as parallel:
syllable_dfs = parallel(
delayed(create_label_df)(
dataset.data_files[key].data,
hparams=dataset.hparams,
labels_to_retain=["syllable", "pos_in_sy... | _____no_output_____ | MIT | notebooks/02.0-make-syllable_df/3-create-swamp-sparrow-df.ipynb | xingjeffrey/avgn_paper |
get audio for dataset | with Parallel(n_jobs=n_jobs, verbose=verbosity) as parallel:
syllable_dfs = parallel(
delayed(get_row_audio)(
syllable_df[syllable_df.key == key],
dataset.data_files[key].data['wav_loc'],
dataset.hparams
)
for key in tqdm(syllable_df.key.unique())
)
... | _____no_output_____ | MIT | notebooks/02.0-make-syllable_df/3-create-swamp-sparrow-df.ipynb | xingjeffrey/avgn_paper |
Create spectrograms | from avgn.visualization.spectrogram import draw_spec_set
from avgn.signalprocessing.create_spectrogram_dataset import make_spec, mask_spec, log_resize_spec, pad_spectrogram
syllables_wav = syllable_df.audio.values
syllables_rate = syllable_df.rate.values
with Parallel(n_jobs=n_jobs, verbose=verbosity) as parallel:
... | _____no_output_____ | MIT | notebooks/02.0-make-syllable_df/3-create-swamp-sparrow-df.ipynb | xingjeffrey/avgn_paper |
Rescale spectrogram- using log rescaling | log_scaling_factor = 4
with Parallel(n_jobs=n_jobs, verbose=verbosity) as parallel:
syllables_spec = parallel(
delayed(log_resize_spec)(spec, scaling_factor=log_scaling_factor)
for spec in tqdm(syllables_spec, desc="scaling spectrograms", leave=False)
)
draw_spec_set(syllables_spec, zoom=1, maxr... | (25.0, 10) (320, 800) 25.0 32 800
| MIT | notebooks/02.0-make-syllable_df/3-create-swamp-sparrow-df.ipynb | xingjeffrey/avgn_paper |
Pad spectrograms | syll_lens = [np.shape(i)[1] for i in syllables_spec]
pad_length = np.max(syll_lens)
plt.hist(syll_lens)
with Parallel(n_jobs=n_jobs, verbose=verbosity) as parallel:
syllables_spec = parallel(
delayed(pad_spectrogram)(spec, pad_length)
for spec in tqdm(
syllables_spec, desc="padding spec... | (25.0, 10) (320, 800) 25.0 32 800
| MIT | notebooks/02.0-make-syllable_df/3-create-swamp-sparrow-df.ipynb | xingjeffrey/avgn_paper |
save dataset | np.shape(syllables_spec)
syllable_df[:3]
syllable_df['spectrogram'] = syllables_spec
save_loc = DATA_DIR / 'syllable_dfs' / DATASET_ID / 'swampsparrow.pickle'
ensure_dir(save_loc)
syllable_df.to_pickle(save_loc) | _____no_output_____ | MIT | notebooks/02.0-make-syllable_df/3-create-swamp-sparrow-df.ipynb | xingjeffrey/avgn_paper |
Construction of pYPK0_PDC1_HIS3_RPS19b[pYPKa_Z_PDC1](pYPKa_Z_PDC1.ipynb)[pYPKa_E_RPS19b](pYPKa_E_RPS19b.ipynb) | from pydna.all import *
p567,p577,p468,p467,p568,p578,p775,p778,p167,p166 = parse("yeast_pahtway_kit_standard_primers.txt") | _____no_output_____ | BSD-3-Clause | notebooks/pYPK0_PDC1_HIS3_RPS19b.ipynb | MetabolicEngineeringGroupCBMA/ypk-xylose-pathways |
[Yeast Pathway Kit Standard Primers](ypk_std_primers.ipynb) | from Bio.Restriction import ZraI, AjiI, EcoRV
pYPK0 =read("pYPK0.gb")
promoter_clone = pYPKa_Z_PDC1 =read("pYPKa_Z_PDC1.gb")
gene_clone =read("pYPKa_A_ScHIS3.gb")
terminator_clone = pYPKa_E_RPS19b =read("pYPKa_E_RPS19b.gb")
p =pcr( p167, p567, promoter_clone)
g =pcr( p468, p467, gene_clone)
t =pcr( p568, p166, termi... | _____no_output_____ | BSD-3-Clause | notebooks/pYPK0_PDC1_HIS3_RPS19b.ipynb | MetabolicEngineeringGroupCBMA/ypk-xylose-pathways |
The new construct should have cseguid ```m-7lOIJ60aZl4b7rN4vanlD7OWk``` and 9404 bp. | result.write("pYPK0_PDC1_HIS3_RPS19b.gb") | _____no_output_____ | BSD-3-Clause | notebooks/pYPK0_PDC1_HIS3_RPS19b.ipynb | MetabolicEngineeringGroupCBMA/ypk-xylose-pathways |
[Download](pYPK0_PDC1_HIS3_RPS19b.gb) | from pydna.all import *
reloaded =read("pYPK0_PDC1_HIS3_RPS19b.gb")
reloaded =read("pYPK0_PDC1_HIS3_RPS19b.gb") | _____no_output_____ | BSD-3-Clause | notebooks/pYPK0_PDC1_HIS3_RPS19b.ipynb | MetabolicEngineeringGroupCBMA/ypk-xylose-pathways |
Configuraciones para el Grupo de Estudio Contenidos- ¿Por qué jupyter notebooks?- Bash- ¿Que es un *kernel*?- Instalación- Deberes Python y proyecto Jupyter- Necesitamos llevar un registro del avance de cada integrante. - Lenguaje de programación interpretado de alto nivel.- Jupyter notebooks: son fáciles de usar- `N... | import matplotlib.pyplot as plt
import numpy as np
import math
# constantes
pi = math.pi; h = 6.626e-34; kB = 1.380e-23; c = 3.0e+8;
Temps = [9940.00, 8500.00, 7500.00, 6627.00, 5810.93, 4231.15, 3000.00, 2973.15, 288.15]
labels = ['Sirius', 'White star', 'Yellow-white star', 'Polaris', 'Sol', 'HfC', 'Bombilla', 'TaN'... | _____no_output_____ | MIT | Sesion1_Que_es_Linux/deberes/jupyter.ipynb | RSG-Ecuador/Grupo-De-Estudio-Linux-Bash- |
Generación de observaciones aleatorias a partir de una distribución de probabilidad La primera etapa de la simulación es la **generación de números aleatorios**. Los números aleatorios sirven como el bloque de construcción de la simulación. La segunda etapa de la simulación es la **generación de variables aleatorias b... | # Importamos las librerías principales
import numpy as np
import matplotlib.pyplot as plt
# Creamos la función que crea muestras distribuidas exponencialmente
def D_exponential(theta,N):
return -np.log(np.random.random(N))*theta
theta = 4 # Media
N = 10**6 # Número de muestras
# creamos muestras exponenciales con l... | 4.001007346372537
| MIT | TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb | duarteandres/SPF-2020-II-G1 |
Ejemplo 2Se sabe que la distribución Erlang resulta de la suma de $k$ variables distribuidas exponencialmente cada una con media $\theta$, y por lo tanto esta variable resultante tiene distribución Erlang de tamaño $k$ y media $theta$.> Enlace distribución Erlang: https://en.wikipedia.org/wiki/Erlang_distribution | N = 10**4
# Variables exponenciales
x1 = np.random.exponential(4,N)
x2 = np.random.exponential(4,N)
x3 = np.random.exponential(4,N)
x4 = np.random.exponential(4,N)
x5 = np.random.exponential(4,N)
# Variables erlang
e0 = x1
e1 = (x1+x2)
e2 = (x3+x4+x5)
e3 = (x1+x2+x3+x4)
e4 = x1+x2+x3+x4+x5
plt.hist(e0,100,density=True... | _____no_output_____ | MIT | TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb | duarteandres/SPF-2020-II-G1 |
Función de densidad variables Erlang$$p(x)=x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)}\equiv x^{k-1}\frac{e^{-x/\theta}}{\theta^k(k-1)!}$$ | #Librería que tiene la función gamma y factorial
# Para mostrar la equivalencia entre el factorial y la función gamma
import scipy.special as sps
from math import factorial as fac
k = 4
theta = 4
x = np.arange(0,60,0.01)
plt.show()
y= x**(k-1)*(np.exp(-x/theta) /(sps.gamma(k)*theta**k))
y2 = x**(k-1)*(np.exp(-x/the... | _____no_output_____ | MIT | TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb | duarteandres/SPF-2020-II-G1 |
Para mejorar la eficiencia, creemos una función que grafique la misma gráfica anterior pero este caso que le podamos variar los parámetros `k` y $\theta$ de la distribución | # Función que grafica subplots para cada señal de distribución Erlang
def histograma_erlang(signal:'señal que desea graficar',
k:'Parámetro de la función Erlang'):
plt.figure(figsize=(8,3))
count, x, _ = plt.hist(signal,100,density=True,label='k=%d'%k)
y = x**(k-1)*(np.exp(-x/theta) /... | _____no_output_____ | MIT | TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb | duarteandres/SPF-2020-II-G1 |
Con la función anterior, graficar la función de distribución de una Erlang con parámetros $\theta = 4$ y `Ks = [1,8,3,6] ` | theta = 4 # media
N = 10**5 # Número de muestras
Ks = [1,8,3,6] # Diferentes valores de k para la distribución Erlang
# Obtengo
Y = list(map(lambda k:D_erlang(theta,k,N),Ks))
list(map(histograma_erlang,Y,Ks)); | _____no_output_____ | MIT | TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb | duarteandres/SPF-2020-II-G1 |
Ejemplo 4Distribución de Rayleigh$$F(x)=1-e^{-2x(x-b)},\quad x\geq b $$ > Fuente: https://en.wikipedia.org/wiki/Rayleigh_distribution | # Función del ejemplo 4
def D_rayleigh(b,N):
return (b/2)+np.sqrt(b**2-2*np.log(np.random.rand(N)))/2
np.random.rayleigh?
# Función de Raylegh que contiene numpy
def D_rayleigh2(sigma,N):
return np.sqrt(-2*sigma**2*np.log(np.random.rand(N)))
b = 0.5; N =10**6;sigma = 2
r = D_rayleigh(b,N) # Funci... | _____no_output_____ | MIT | TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb | duarteandres/SPF-2020-II-G1 |
Distribuciones discretasPara una variable dicreta, evaluar $F^{-1}$ se reduce a buscar en una tabla. Considere por ejemplo una variable aleatoria discreta, cuyos posibles valores son $c_1<c_2<\cdots<c_n$. Tome $p_i$ la probabilidad alcanzada por $c_i$, $i=1,\cdots,n$ y tome $q_0=0$, en donde $q_i$ representa las **pro... | # Librería para crear tablas
import pandas as pd
val = [1,2,3,4,5]
p_ocur = [.1,.2,.4,.2,.1]
p_acum = np.cumsum(p_ocur)
df = pd.DataFrame(index=val,columns=['Probabilidades','Probabilidad acumulada'], dtype='float')
df.index.name = "Valores (índices)"
df.loc[val,'Probabilidades'] = p_ocur
df.loc[val,'Probabilidad a... | _____no_output_____ | MIT | TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb | duarteandres/SPF-2020-II-G1 |
Lo que no se debe de hacer, cuando queremos graficar el histograma de una distribución discreta | N = 10**4
u =np.random.rand(N)
v = Gen_distr_discreta(u,p_acum)+1
plt.hist(v,bins = 6)
plt.show()
N = 10**4
u =np.random.rand(N)
v = Gen_distr_discreta(u,p_acum)+1 #+1 porque los índices comienzan en 1
# print(u,v)
# Método 1 (Correcto)
hist,bins = np.histogram(v,bins=len(val))
# print(hist,bins)
plt.bar(val,hist)
pl... | _____no_output_____ | MIT | TEMA-2/Clase9_GenDistribucionProbabilidad.ipynb | duarteandres/SPF-2020-II-G1 |
MHKiT Quality Control ModuleThe following example runs a simple quality control analysis on wave elevation data using the [MHKiT QC module](https://mhkit-software.github.io/MHKiT/mhkit-python/api.qc.html). The data file used in this example is stored in the [\\\\MHKiT\\\\examples\\\\data](https://github.com/MHKiT-Sof... | import pandas as pd
from mhkit import qc, utils | _____no_output_____ | BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
Load Data The wave elevation data used in this example includes several issues, including timestamps that are out of order, corrupt data with values of -999, data outside the expected range, and stagnant data. The data is loaded into a pandas DataFrame using the pandas method `read_csv`. The first 5 rows of data are... | # Load data from the csv file into a DataFrame
data = pd.read_csv('data/qc/wave_elevation_data.csv', index_col='Time')
# Plot the data
data.plot(figsize=(15,5), ylim=(-60,60))
# Print the first 5 rows of data
print(data.head()) | probe1 probe2 probe3
Time
10.000 24.48 28.27 1.3
10.002 34.48 40.27 -8.7
10.004 30.48 38.27 -13.7
10.006 12.48 24.27 -32.7
10.008 13.48 22.27 -21.7
| BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
The data is indexed by time in seconds. To use the quality control functions, the data must be indexed by datetime. The index can be converted to datetime using the following utility function. | # Convert the index to datetime
data.index = utils.index_to_datetime(data.index, origin='2019-05-20')
# Print the first 5 rows of data
print(data.head()) | probe1 probe2 probe3
Time
2019-05-20 00:00:10.000 24.48 28.27 1.3
2019-05-20 00:00:10.002 34.48 40.27 -8.7
2019-05-20 00:00:10.004 30.48 38.27 -13.7
2019-05-20 00:00:10.006 12.48 24.27 -32.7
2019-05-20 00:00:10.008 13.48 ... | BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
Quality control testsThe following quality control tests are used to identify timestamp issues, corrupt data, data outside the expected range, and stagnant data.Each quality control tests results in the following information:* Cleaned data, which is a DataFrame that has *NaN* in place of data that did not pass the qua... | # Define expected frequency of the data, in seconds
frequency = 0.002
# Run the timestamp quality control test
results = qc.check_timestamp(data, frequency) | _____no_output_____ | BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
The cleaned data, boolean mask, and test results summary are shown below. The summary is transposed (using .T) so that it is easier to read. | # Plot cleaned data
results['cleaned_data'].plot(figsize=(15,5), ylim=(-60,60))
# Print the first 5 rows of the cleaned data
print(results['cleaned_data'].head())
# Print the first 5 rows of the mask
print(results['mask'].head())
# Print the test results summary
# The summary is transposed (using .T) so that it is ... | 0 1 \
Variable Name
Start Time 2019-05-20 00:00:10.230000 2019-05-20 00:00:10.340000
End Time 2019-05-20 00:00:10.230000 2019-05-20 00:00:10.340000
Timesteps ... | BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
Check for corrupt dataIn the following quality control tests, the cleaned data from the previous test is used as input to the subsequent test. For each quality control test, a plot of the cleaned data is shown along with the test results summary.Note, that if you want to run a series of quality control tests before ex... | # Define corrupt values
corrupt_values = [-999]
# Run the corrupt data quality control test
results = qc.check_corrupt(results['cleaned_data'], corrupt_values)
# Plot cleaned data
results['cleaned_data'].plot(figsize=(15,5), ylim=(-60,60))
# Print test results summary
print(results['test_results'].T) | 0 1
Variable Name probe1 probe3
Start Time 2019-05-20 00:00:10.110000 2019-05-20 00:00:10.834000
End Time 2019-05-20 00:00:10.134000 2019-05-20 00:00:10.848000
Timesteps 1... | BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
Check for data outside the expected rangeThe next quality control test checks for data that is greater than 50 or less than -50. Note that expected range tests can also be used to compare measured values to a model, or analyze the expected relationships between data columns. | # Define expected lower and upper bound ([lower bound, upper bound])
expected_bounds = [-50, 50]
# Run expected range quality control test
results = qc.check_range(results['cleaned_data'], expected_bounds)
# Plot cleaned data
results['cleaned_data'].plot(figsize=(15,5), ylim=(-60,60))
# Print test results summary... | 0 1 \
Variable Name probe3 probe3
Start Time 2019-05-20 00:00:10.240000 2019-05-20 00:00:10.468000
End Time 2019-05-20 00:00:10.240000 2019-05-20 00:00:10.468000
Timesteps ... | BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
Check for stagnant dataThe final quality control test checks for stagnant data by looking for data that changes by less than 0.001 within a 0.02 second moving window. | # Define expected lower bound (no upper bound is specified in this example)
expected_bound = [0.001, None]
# Define the moving window, in seconds
window = 0.02
# Run the delta quality control test
results = qc.check_delta(results['cleaned_data'], expected_bound, window)
# Plot cleaned data
results['cleaned_data']... | 0
Variable Name probe2
Start Time 2019-05-20 00:00:10.400000
End Time 2019-05-20 00:00:10.544000
Timesteps 73
Error Flag Delta < lower bound, 0.001
| BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
Cleaned DataThe cleaned data can be used directly in MHKiT analysis, or the missing values can be replaced using various methods before analysis is run. Data replacement strategies are generally defined on a case by case basis. Pandas includes methods to interpolate, replace, and fill missing values. | # Extract final cleaned data for MHKiT analysis
cleaned_data = results['cleaned_data'] | _____no_output_____ | BSD-3-Clause | examples/qc_example.ipynb | fleming79/MHKiT-Python |
全部的columns名稱 | df.columns.values | _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
把全部的分數相關的平均起來成新的column | col = df.loc[: , "review_scores_accuracy":"review_scores_value"]
df['review_scores_mean'] = col.mean(axis=1)
| _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
留下來的attributes | cols_to_keep = [
'latitude',
'longitude',
'property_type',
'room_type',
'accommodates',
'bathrooms',
'bedrooms',
'beds',
'price','review_scores_mean'
]
df = df[cols_to_keep] | _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
清理price的符號 只剩下數字和小數點 | df['price'] = df['price'].replace('[^(0-9).]','', regex=True).replace('[(]','-', regex=True).astype(float)
display(df.head())
| _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
要預測的欄位 price換成log price | df['log_price'] = np.log(df['price'].values)
| _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
drop price | data = df.drop('price', axis=1)
list(data.columns.values)
data.head() | _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
Missing Values 找出各欄位有多少NAN | #Replace blanks with NaNs
data = data.replace('_', np.nan)
data = data.replace(' ', np.nan)
data = data.replace([np.inf, -np.inf], np.nan)
col_analysis = []
for column in data.columns:
numNulls = len(data[column][data[column].isnull()])
totalLength = len(data[column])
dict1 = {'Name':column,'DataType':data[... | List of Predictors and their respective percentages of missing values
| MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
Impute Missing Values把空白的填補成整個欄位的平均值 | #Use Mean for Real values Columns
real_value_cols = useful_cols[useful_cols.DataType == 'float64']
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
data[real_value_cols.Name.values] = imp.fit_transform(data[real_value_cols.Name.values])
#Use Highest frequency for categorical columns
categorical_value_cols... | _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
log_price的直方圖 (可以看出試常態分佈) | data.log_price.hist() | _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
Convert Categorical Variables to dummy integer values here- We convert the categorical variables to numeric here such that we can run models that work only with numbers One-Hot Encoding把nomial的欄位換成數字 |
data_ohe = data.copy(deep= True)
#Encode categorical variables
def encode_categorical(array):
return preprocessing.LabelEncoder().fit_transform(array)
categorical_value_cols = useful_cols[useful_cols.DataType == 'object'].Name.values
#print(categorical_value_cols)
#Convert Categories to numbers here
data_oh... | Final Dataset ready for modelling after filling in missing values, and encoding categorical variables
| MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
Separate response from predictors |
x = data_ohe.values[:, :-1]
y = data_ohe.values[:, -1]
#response = df_filtered[['log_price']]
#predictors = df_filtered.drop(['log_price'], axis=1) | _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
Split into train/test |
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=42) | _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
Simple Regression Model | #OLS regression
clf = LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
clf.fit(x_train, y_train)
predicted = clf.predict(x_test)
score = sk.metrics.r2_score(y_test, predicted)
print('sklearn: R2 score for Linear Regression is: {}'.format(score))
from sklearn import cross_validation, ensembl... | sklearn: R2 score for Linear Regression is: 0.4082299522656714
| MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
把model打包 | joblib.dump(clf, 'predicted.pkl')
estimator = joblib.load('predicted.pkl')
estimator | _____no_output_____ | MIT | Final Project.ipynb | jesseddeng/Machine-learning-Final-Project |
** Problem: Fourier transforms of simple functions **Write Python programs to calculate the coefficients in the discrete Fourier transforms of the following periodic functions sampled at $N=1000$ evenly spaced points, and make plots of their amplitudes:1) A single cycle of a square-wave with amplitude 12) The sawtooth ... | # Import required modules
from numpy import arange
from numpy.fft import rfft
from math import sin,pi
# Square wave
def f(x):
if x<0.5:
return 1
else:
return -1
N=1000
x=arange(0.0,1.0,1.0/N)
y=map(f,x)
c=rfft(y) # Calculate the Fourier coefficients (complex numbers!)
plot(abs(c)) ... | _____no_output_____ | IJG | ExamPrep/Shit Comp/ShitComp/Fourier_Transforms.ipynb | FHomewood/ScientificComputing |
This notebook is used to generate data regarding the Goldbach conjecture: rows are of the form $N, a, b$ where $N$ is an even number, $a< b$ are prime and $N=a + b$.First we write a Python function `goldbach` that takes `N` and returns all pairs of numbers $a, b$. | import sympy as sym
import pandas as pd
def goldbach(N):
"""Returns all pairs of primes that sum to give N"""
primes = list(sym.primerange(1, N))
sums = []
for i, p1 in enumerate(primes):
for p2 in primes[i:]:
if p1 + p2 == N:
sums.append((p1, p2))
return sums | _____no_output_____ | MIT | A1-Appendix-creating-Goldbach-data.ipynb | cdvv7788/Python-Mathematics-Handbook |
Let us use the above function to create our data: | maxN = 500
data = [[N, *pair] for N in range(4, maxN + 1)
for pair in goldbach(N) if N % 2 == 0 ] | _____no_output_____ | MIT | A1-Appendix-creating-Goldbach-data.ipynb | cdvv7788/Python-Mathematics-Handbook |
Let us write our data to an excel file: | df = pd.DataFrame(data, columns=["N","a", "b"]) # Create a data frame
df.to_excel("data/goldbach.xlsx") # Write it to excel | _____no_output_____ | MIT | A1-Appendix-creating-Goldbach-data.ipynb | cdvv7788/Python-Mathematics-Handbook |
IntroductionThis notebook can be used to both train a discriminator on the AG news dataset and steering text generation in the direction of each of the four classes of this dataset, namely world, sports, business and sci/tech. My code uses and builds on a text generation plug-and-play model developed by the Uber AI... | # MUST BE RUN
!git clone https://github.com/eskilhamre/PPLM.git
# MUST BE RUN
import os
os.chdir('PPLM')
# MUST BE RUN
!pip install -r requirements.txt | Collecting torch==1.7.0
Downloading torch-1.7.0-cp37-cp37m-manylinux1_x86_64.whl (776.7 MB)
[K |████████████████████████████████| 776.7 MB 4.3 kB/s
[?25hCollecting nltk==3.4.5
Downloading nltk-3.4.5.zip (1.5 MB)
[K |████████████████████████████████| 1.5 MB 32.4 MB/s
[?25hCollecting colorama==0.4.4
D... | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Train a discriminator on AG news dataset First, download the general lanaguage model used to train the discriminator | from transformers.modeling_gpt2 import GPT2LMHeadModel
# This downloads GPT-2 Medium, it takes a little while
_ = GPT2LMHeadModel.from_pretrained("gpt2-medium") | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Import the datasetThe data can be found at: https://www.kaggle.com/amananandrai/ag-news-classification-dataset/version/2?select=train.csvThe PPLM interface requires the data to be a tsv file containing the entire dataset, where the first column is the labels and seconds column the text. Thus, we have to prepare the da... | import pandas as pd
from google.colab import files
import torch
torch.cuda.is_available()
uploaded = files.upload()
data_fp = "./ag-news-data.tsv" # where we want to store our prepared dataset
def prepare_dataset(text_index,
label_index,
label_names=None
):... | Preprocessing generic dataset...
| Apache-2.0 | main.ipynb | eskilhamre/PPLM |
We achieve about 90% accuracy on unseen data, which is pretty good in my opinion. I haven't studied the training accuracy (so I can't say the following for sure), but I don't think we're neither underfitting or overfitting here. This is good stuff! Also, the validation/test accuracy seems to stagnate on ~90%, so more... | classifier_name = "models/news_classifierhead.pt"
torch.save(discriminator.get_classifier().state_dict(), "models/news_classifierhead.pt")
files.download(classifier_name) | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
At this point, I put the newly generated model in the discrim_models/ folder, and updated my Github code to include this model. I went back to the beginning of the notebook and recloned the repo. Scoring the generated samplesWhen doing manual comparison between text generated from different model settings, I'm only in... | # MUST BE RUN
from transformers.modeling_gpt2 import GPT2LMHeadModel
from transformers import GPT2Tokenizer, OpenAIGPTLMHeadModel, OpenAIGPTTokenizer
from nltk import ngrams
import numpy as np | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Instantiate models used for scoring samples | # MUST BE RUN
device = "cuda" if torch.cuda.is_available() else "cpu"
# tokenizer and language model used for calculating fluency / "perplexity"
gpt1_tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
gpt1_model = OpenAIGPTLMHeadModel.from_pretrained("openai-gpt")
gpt1_model.eval()
gpt1_model.to(device)
devi... | [3.0594890117645264, 4.118381977081299, 3.2676448822021484, 9.095804214477539]
[0.8571428571428572, 0.8571428571428572, 0.8571428571428572, 0.4444444444444444]
| Apache-2.0 | main.ipynb | eskilhamre/PPLM |
We can see that the most sensible of the four sentences receives lowest language model score (thus higher probability). Also, we can see that the non-sensible sentence receives both bad language model and dist-score. Text generation | # MUST BE RUN
from run_pplm import run_pplm_example, generate_text_pplm, get_classifier, PPLM_DISCRIM
# MUST BE RUN
def text_generation(
model,
tokenizer,
discrim="news",
class_label="sports",
prefix_text="Last summer",
perturb=False,
num_samples=3,
device="cuda",
length=150,
s... | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Import the base model used to sample from | # MUST BE RUN
pretrained_model = "gpt2-medium"
model = GPT2LMHeadModel.from_pretrained(
pretrained_model,
output_hidden_states=True
)
model.to(device)
model.eval()
# Freeze GPT-2 weigths
for param in model.parameters():
param.requires_grad = False
tokenizer = GPT2Tokenizer.from_pretrained(pretraine... | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Sample from all combinations of model setting and prefix sentencesFirst, let's create some data structures to gather relevant information from the sampling process. | # MUST BE RUN
# most relevant hyper params wrt. speed
generated_len = 120
num_samples = 12
prefixes = [
"Last week",
"The potato",
"Breaking news:",
"In the last year",
"The president of the country",
]
model_settings = ["world", "sports", "business", "sci/tech"] # the classes of the discriminator
# MUST ... | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
The cell below runs the *entire* sampling process, it took ~5 hours to run on Googles Compute Engine backend using their GPUs. Here I decided that generate unperturbed text for each model setting. This might seem silly and redundant, since the unperturbed text is not affected by this choice. And while that is p... | # MUST BE RUN
# since we're sampling, set seed for reproducibility
torch.manual_seed(444)
np.random.seed(444)
n_combinations = len(prefixes) * len(model_settings)
i = 1
for prefix_sentence in prefixes:
for j, model_setting in enumerate(model_settings):
print(f"\n\nRun {i:3d}/{n_combinations:3d} : optimizing for... |
Run 1/ 15 : optimizing for class: sports, with prefix: Last week
<|endoftext|>Last week's
<|endoftext|>Last week's announcement
<|endoftext|>Last week's announcement that
| Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Generation analysisFirst, let's download the generated samples. | import json
with open("all-samples.json", "w") as fp:
json.dump(gen_samples, fp)
files.download("all-samples.json")
with open("comparisons.json", "w") as fp:
json.dump(comparisons, fp)
files.download("comparisons.json"") | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Let's extract the metrics from the generated samplesIn the code below, for each model setting, I calculate the perplexity score and dist-1, dist-2, and dist-3 scores for all samples. I then accumulate the mean and standard deviations of the scores wrt. to each model setting, to study how well each model setting actual... | # MUST BE RUN
metrics_means_dict = {}
metrics_stds_dict = {}
for model_setting, samples in gen_samples.items():
perplexities = [lm_score(sample) for sample in samples]
dist_scores = [dist_score(sample)[1:] for sample in samples] # stored as (mean_dist_score, dist-1, dist-2, dist-3), ignore mean
all_metrics = ... | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Let's see the best examples for each model setting and prefix | # MUST BE RUN
for model_setting, prefix_dict in comparisons.items():
print(f"Model setting: {model_setting}\n")
for prefix_sentence in prefix_dict.keys():
unpert_sample, unpert_loss, unpert_mean_dist = prefix_dict[prefix_sentence]["unpert"]
pert_sample, pert_loss, pert_mean_dist = prefix_dict[prefix_senten... | _____no_output_____ | Apache-2.0 | main.ipynb | eskilhamre/PPLM |
Florida updates their data daily at 11am and 6pm EDT | from selenium import webdriver
import time
import pandas as pd
import pendulum
import re
import yaml
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
#chrome_options.add_argument("--disable-extensions")
#chrome_options.add_argument("--disable-gpu")
#chrome_options.add_argument("--no-sand... | _____no_output_____ | MIT | FL by county.ipynb | kirbs-/covid-19-dataset |
_Lambda School Data Science, Unit 2_ Regression & Classification Sprint ChallengeTo demonstrate mastery on your Sprint Challenge, do all the required, numbered instructions in this notebook.To earn a score of "3", also do all the stretch goals.You are permitted and encouraged to do as much data exploration as you wan... | # If you're in Colab...
import sys
in_colab = 'google.colab' in sys.modules
if in_colab:
!pip install category_encoders==2.0.0
!pip install pandas-profiling==2.3.0
!pip install plotly==4.1.1 | Collecting category_encoders==2.0.0
[?25l Downloading https://files.pythonhosted.org/packages/6e/a1/f7a22f144f33be78afeb06bfa78478e8284a64263a3c09b1ef54e673841e/category_encoders-2.0.0-py2.py3-none-any.whl (87kB)
[K |████████████████████████████████| 92kB 5.7MB/s
[?25hRequirement already satisfied: statsmodels... | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
Part 1, Classification: Predict Blood Donations 🚑Our dataset is from a mobile blood donation vehicle in Taiwan. The Blood Transfusion Service Center drives to different universities and collects blood as part of a blood drive.The goal is to predict whether the donor made a donation in March 2007, using information ab... | import pandas as pd
donors = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/blood-transfusion/transfusion.data')
assert donors.shape == (748,5)
donors = donors.rename(columns={
'Recency (months)': 'months_since_last_donation',
'Frequency (times)': 'number_of_donations',
'Monetary... | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
1.1. Begin with baselinesWhat accuracy score would you get here with a "majority class baseline"? (You don't need to split the data into train and test sets yet. You can answer this question either with a scikit-learn function or with a pandas function.) | y_train = donors.made_donation_in_march_2007
y_train.value_counts(normalize=True)
# We can cross-check this using scikit-learn
majority_class = y_train.mode()[0]
majority_class
y_pred = [majority_class] * len(y_train)
len(y_pred)
from sklearn.metrics import accuracy_score
accuracy_score(y_train, y_pred) | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
1.2. Do train/test split. Arrange data into X features matrix and y target vectorDo these steps in either order.Split randomly. Use scikit-learn's train/test split function. Include 75% of the data in the train set, and hold out 25% for the test set. | train_features = donors[donors.columns.difference(['made_donation_in_march_2007'])]
print(train_features.shape)
train_features.head()
train_labels = donors['made_donation_in_march_2007']
print(train_labels.shape)
train_labels.head()
from sklearn.model_selection import train_test_split
X_train = train_features
y_train ... | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
1.3. Use scikit-learn to fit a logistic regression modelYou may use any number of features | # No categorical features, only numerical, no need for OHE
from sklearn.linear_model import LogisticRegression
# Right now we include all numerical features
# If we want to split into less features:
# X_train_subset = X_train[features]
# X_val_subset = X_val[features]
model = LogisticRegression(
solver='lbfgs',... | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
1.4. Report classification metric: accuracyWhat is your model's accuracy on the test set?Don't worry if your model doesn't beat the mean baseline. That's okay!_"The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data."_ —[John ... | print('Validation Accuracy', model.score(X_val, y_val)) | Validation Accuracy 0.7807486631016043
| MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
Part 2, Regression: Predict home prices in Ames, Iowa 🏠You'll use historical housing data. There's a data dictionary at the bottom of the notebook. Run this code cell to load the dataset: | import pandas as pd
URL = 'https://drive.google.com/uc?export=download&id=1522WlEW6HFss36roD_Cd9nybqSuiVcCK'
homes = pd.read_csv(URL)
assert homes.shape == (2904, 47)
homes.head() | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
2.1. Begin with baselinesWhat is the Mean Absolute Error and R^2 score for a mean baseline? | from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import numpy as np
y_train = homes['SalePrice']
y_pred_train = [y_train.mean()] * len(y_train)
print('Mean Baseline:')
print('Train Mean Absolute Error:', mean_absolute_error(y_train, y_pred_train))
print('Train R^2 Score:', r2_score(y_trai... | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
2.2. Do train/test splitTrain on houses sold in the years 2006 - 2008. (1,920 rows)Validate on house sold in 2009. (644 rows)Test on houses sold in 2010. (340 rows) | train = homes[(homes.Yr_Sold >= 2006) & (homes.Yr_Sold <= 2008)]
print(train.shape)
val = homes[homes.Yr_Sold == 2009]
print(val.shape)
test = homes[homes.Yr_Sold == 2010]
print(test.shape) | (340, 47)
| MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
2.3. Arrange data into X features matrix and y target vectorSelect at least one numeric feature and at least one categorical feature.Otherwise, you many choose whichever features and however many you want. | homes.isnull().sum()
target = 'SalePrice'
numeric_features = train[train.columns.difference(['SalePrice'])].select_dtypes(include='number').columns.tolist()
cardinality = train.select_dtypes(exclude='number').nunique()
low_cardinality_features = cardinality[cardinality <= 10].index.tolist()
features = numeric_featur... | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
2.4. Do one-hot encodingEncode your categorical feature(s). | X_train = train[features]
y_train = train[target]
X_val = val[features]
y_val = val[target]
X_test = test[features]
y_test = test[target]
import category_encoders as ce
from sklearn.preprocessing import StandardScaler
X_train_subset = X_train[features]
X_val_subset = X_val[features]
X_test_subset = X_test[features]
... | (1920, 157) (644, 157) (340, 157)
| MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
2.5. Use scikit-learn to fit a linear regression (or ridge regression) modelFit your model. | # STRETCH GOAL: Try at least 3 feature combinations. You may select features manually, or automatically
# STRETCH GOAL: Report validation MAE and R2 for each feature combination you try
from sklearn.linear_model import RidgeCV
from sklearn.feature_selection import f_regression, SelectKBest
for k in range(1, len(X_tr... | 1 features
Test MAE: $35,831
Test R2: 0.570
2 features
Test MAE: $30,063
Test R2: 0.700
3 features
Test MAE: $27,450
Test R2: 0.741
4 features
Test MAE: $27,428
Test R2: 0.744
5 features
Test MAE: $27,420
Test R2: 0.745
6 features
Test MAE: $25,676
Test R2: 0.770
7 features
Test MAE: $25,671
Test R2: 0.771 ... | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
2.6. Report validation MAE and $R^2$What is your model's Mean Absolute Error and $R^2$ score on the validation set? | # STRETCH GOAL: Report test MAE and $R^2$ for your final model
selector = SelectKBest(score_func=f_regression, k=157)
X_train_selected = selector.fit_transform(X_train_scaled, y_train)
X_val_selected = selector.transform(X_val_scaled)
model = RidgeCV()
model.fit(X_train_selected, y_train)
y_pred_val = model.predict(... | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
Stretch Goals, Regression- Make visualizations to explore relationships between features and target- Try at least 3 feature combinations. You may select features manually, or automatically- Report validation MAE and $R^2$ for each feature combination you try- Report test MAE and $R^2$ for your final model- Print or pl... | #STRETCH GOAL: Make visualizations to explore relationships between features and target
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
for col in sorted(low_cardinality_features):
sns.catplot(x=col, y='SalePrice', data=train, kind='bar', color='grey')
plt.xticks(rotation=45)
plt.s... | _____no_output_____ | MIT | DS7_Sprint_Challenge_5_Regression_Classification.ipynb | sapinspys/DS-Unit-2-Regression-Classification |
Navigation---In this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893). 1. Start the EnvironmentWe begin by importing some necessary packages. If the co... | from unityagents import UnityEnvironment
import numpy as np
from collections import deque
import torch
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | archive/Navigation-31Dec1515.ipynb | kapalko/DRL_Banana_Collector |
Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded.- **Mac**: `"path/to/Banana.app"`- **Windows** (x86): `"path/to/Banana_Windows_x86/Banana.exe"`- **Windows** (x86_64): `"path/to/Banana_Wind... | env = UnityEnvironment(file_name="Banana.app") | INFO:unityagents:
'Academy' started successfully!
Unity Academy name: Academy
Number of Brains: 1
Number of External Brains : 1
Lesson number : 0
Reset Parameters :
Unity brain name: BananaBrain
Number of Visual Observations (per agent): 0
Vector Observation space type... | MIT | archive/Navigation-31Dec1515.ipynb | kapalko/DRL_Banana_Collector |
Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python. | # get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name] | _____no_output_____ | MIT | archive/Navigation-31Dec1515.ipynb | kapalko/DRL_Banana_Collector |
2. Examine the State and Action SpacesThe simulation contains a single agent that navigates a large environment. At each time step, it has four actions at its disposal:- `0` - walk forward - `1` - walk backward- `2` - turn left- `3` - turn rightThe state space has `37` dimensions and contains the agent's velocity, al... | # reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents in the environment
print('Number of agents:', len(env_info.agents))
# number of actions
action_size = brain.vector_action_space_size
print('Number of actions:', action_size)
# examine the state space
state = env_info.vector... | Number of agents: 1
Number of actions: 4
States look like: [1. 0. 0. 0. 0.84408134 0.
0. 1. 0. 0.0748472 0. 1.
0. 0. 0.25755 1. 0. 0.
0. 0.74177343 0. 1. 0. 0.
0.25854847 0. 0.... | MIT | archive/Navigation-31Dec1515.ipynb | kapalko/DRL_Banana_Collector |
3. Take Random Actions in the EnvironmentIn the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment.Once this cell is executed, you will watch the agent's performance, if it selects an action (uniformly) at random with each time step. A window should... | env_info = env.reset(train_mode=False)[brain_name] # reset the environment
state = env_info.vector_observations[0] # get the current state
score = 0 # initialize the score
while True:
action = np.random.randint(action_size) # select an action
env_info =... | Score: 0.0
| MIT | archive/Navigation-31Dec1515.ipynb | kapalko/DRL_Banana_Collector |
When finished, you can close the environment. | #env.close() | _____no_output_____ | MIT | archive/Navigation-31Dec1515.ipynb | kapalko/DRL_Banana_Collector |
4. It's Your Turn!Now it's your turn to train your own agent to solve the environment! When training the environment, set `train_mode=True`, so that the line for resetting the environment looks like the following:```pythonenv_info = env.reset(train_mode=True)[brain_name]``` Training using DQN based off the previous ... | from dqn_agent import Agent
agent = Agent(state_size=37, action_size=4, seed=42)
def dqn(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.99):
"""Deep Q-Learning.
Params
======
n_episodes (int): maximum number of training episodes
max_t (int): maximum number of tim... | _____no_output_____ | MIT | archive/Navigation-31Dec1515.ipynb | kapalko/DRL_Banana_Collector |
Data Download - *read description before running* Term project for ESS 490/590Grad: Erik FredricksonUndergrad: Ashika Capirala *This notebook demonstrates how the open access datasets can be downloaded, but these data are provided at significantly higher temporal resolution than needed for the purposes of our study, s... | # Imports
import obspy
import obspy.clients.fdsn.client as fdsn
from obspy import UTCDateTime | _____no_output_____ | MIT | data_download.ipynb | erikfred/ptz_detector |
APG pressures and temperaturesGet bottom temperature and bottom pressure from IRIS (https://www.iris.edu/hq/; https://doi.org/10.7914/SN/XO_2018)Alaska Amphibious Community Seismic Experiment | # Pull pressure and temperature data from IRIS
network = 'XO'
staNames = ['LA21', 'LA34', 'LA33', 'LA23', 'LA25', 'LA22', 'LA28', 'LA39', 'LA32', 'LA30', 'LT07', 'LT06', \
'LT13', 'LT03', 'LT11', 'LT04', 'LT01', 'LT20', 'LT14', 'LT16', 'LT10', 'LT12']
staCodes = 'LA21,LA34,LA33,LA23,LA25,LA22,LA28,LA39,LA32,... | _____no_output_____ | MIT | data_download.ipynb | erikfred/ptz_detector |
Satellite altimetryGet altimetry data from Copernicus Marine (https://marine.copernicus.eu/; https://resources.marine.copernicus.eu/?option=com_csw&view=details&product_id=SEALEVEL_GLO_PHY_CLIMATE_L4_REP_OBSERVATIONS_008_057)Jason-2 Satellite | # installer to handle data download
!pip install motuclient --upgrade
# Get desired data (would need to change directory, user, and password fields)
!python -m motuclient --motu https://my.cmems-du.eu/motu-web/Motu --service-id \
SEALEVEL_GLO_PHY_CLIMATE_L4_REP_OBSERVATIONS_008_057-TDS --product-id \
dataset-du... | _____no_output_____ | MIT | data_download.ipynb | erikfred/ptz_detector |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/ja/tutorials/load_data/images.ipynb | gabrielrufino/docs-l10n |
tf.dataを使って画像をロードする View on TensorFlow.org Run in Google Colab View source on GitHub Note: これらのドキュメントは私たちTensorFlowコミュニティが翻訳したものです。コミュニティによる 翻訳は**ベストエフォート**であるため、この翻訳が正確であることや[英語の公式ドキュメント](https://www.tensorflow.org/?hl=en)の 最新の状態を反映したものであることを保証することはできません。 この翻訳の品質を向上させるためのご意見をお持ちの方は、GitHubリポジトリ[t... | from __future__ import absolute_import, division, print_function, unicode_literals
try:
# Colab only
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
AUTOTUNE = tf.data.experimental.AUTOTUNE | _____no_output_____ | Apache-2.0 | site/ja/tutorials/load_data/images.ipynb | gabrielrufino/docs-l10n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.