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
Example for running the workflowThis will run the workflow from via several submission
sos run ~/GIT/xqtl-pipeline/pipeline/eQTL_analysis_commands.ipynb sumstat_merge \ --recipe /mnt/vast/hpc/csg/snuc_pseudo_bulk//data/recipe_8tissue_new \ --genotype_list /mnt/vast/hpc/csg/snuc_pseudo_bulk/data/genotype_qced/plink_files_list.txt \ --annotation_gtf /mnt/vast/hpc/csg/snuc_pseudo_bulk/data...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Data Preprocessing Genotype Preprocessing (Once for all tissues)
[dbSNP] parameter: dbSNP_vcf = path input: dbSNP_vcf parameter: add_chr = True output: f'{cwd}/reference_data/{_input:bnn}.add_chr.variants.gz' script: interpreter = interpreter, expand = "$[ ]", stderr = f'{_output}.stderr', stdout = f'{_output}.stdout' sos run $[exe_dir]/pipeline//VCF_QC.ipynb dbsnp_annotate ...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Molecular Phenotype Processing
[annotation] stop_if(not recipe.is_file(), msg = "Please specify a valid recipe as input") import os parameter: annotation_gtf = path input: for_each = "input_inv" output: f'{cwd:a}/data_preprocessing/{_input_inv["Theme"]}/phenotype_data/{path(_input_inv["molecular_pheno"]):bn}.bed.gz' script: interpreter = interpreter...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Genotype ProcessingSince genotype is shared among the eight tissue, the QC of whole genome file is not needed. Only pca needed to be run again.
[sample_match] input: for_each = "input_inv" output: f'{cwd:a}/data_preprocessing/{_input_inv["Theme"]}/{sample_participant_lookup:bn}.filtered.txt', geno = f'{cwd:a}/data_preprocessing/{_input_inv["Theme"]}/{sample_participant_lookup:bn}.filtered_geno.txt' script: interpreter = interpreter, expand = "$[ ]", st...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Factor Analysis
[pca] input: output_from("unrelated_QC")["unrelated_bed"],group_with = "input_inv" output: f'{cwd}/data_preprocessing/{_input_inv["Theme"]}/pca/{_input:bn}.pca.rds', f'{cwd}/data_preprocessing/{_input_inv["Theme"]}/pca/{_input:bn}.pca.scree.txt' script: interpreter = interpreter, expand = "$[ ]", stderr = f'{_o...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Association Scan
[TensorQTL] # The number of minor allele count as treshold for the analysis parameter: MAC = 0 # The minor allele frequency as treshold for the analysis, overwrite MAC parameter: maf_threshold = 0 parameter: genotype_list = path input: genotype_list, output_from("phenotype_partition_by_chrom"),output_from("merge_factor...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Trans Association Scan
[TensorQTL_Trans] parameter: MAC = 0 # The minor allele frequency as treshold for the analysis, overwrite MAC parameter: maf_threshold = 0 parameter: genotype_list = path parameter: region_list = path input: genotype_list, output_from("phenotype_partition_by_chrom"),output_from("merge_factor_covariate"),group_with = "i...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
SuSiE
[UniSuSiE] input: output_from("plink_per_gene"), output_from("annotation"),output_from("factor"), output_from("region_list_concat"), group_by = "all" output: f'{cwd:a}/Fine_mapping/UniSuSiE/UniSuSiE_recipe.tsv' script: interpreter = interpreter, expand = "$[ ]" sos run $[exe_dir]/pipeline/SuSiE.ipynb uni_susie \ ...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Sumstat Merger
[yml_generation] parameter: TARGET_list = path("./") input: output_from(Association_option), group_by = "all" output: f'{cwd:a}/data_intergration/{Association_option}/qced_sumstat_list.txt',f'{cwd:a}/data_intergration/{Association_option}/yml_list.txt' script: interpreter = interpreter, expand = "$[ ]" sos run ...
_____no_output_____
MIT
code/commands_generator/eQTL_analysis_commands.ipynb
cumc/xqtl-pipeline
Artificial Intelligence Nanodegree Convolutional Neural Networks---In this notebook, we visualize four activation maps in a CNN layer. 1. Import the Image
import cv2 import scipy.misc import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'part12/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_...
/Users/scrier/anaconda3/lib/python3.6/site-packages/scipy/misc/pilutil.py:482: FutureWarning: Conversion of the second argument of issubdtype from `int` to `np.signedinteger` is deprecated. In future, it will be treated as `np.int64 == np.dtype(int).type`. if issubdtype(ts, int): /Users/scrier/anaconda3/lib/python3.6...
MIT
Deep.Learning/3.Convulutional-Networks/2.Convolutional-Neural-Networks/conv_visualization.ipynb
Scrier/udacity
2. Specify the Filters
import numpy as np # TODO: Feel free to modify the numbers here, to try out another filter! # Please don't change the size of the array ~ :D filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) ### do not modify the code below this line ### # define four filters filter_1 = filter_...
_____no_output_____
MIT
Deep.Learning/3.Convulutional-Networks/2.Convolutional-Neural-Networks/conv_visualization.ipynb
Scrier/udacity
3. Visualize the Activation Maps for Each Filter
from keras.models import Sequential from keras.layers.convolutional import Convolution2D import matplotlib.cm as cm # plot image plt.imshow(small_img, cmap='gray') # define a neural network with a single convolutional layer with one filter model = Sequential() model.add(Convolution2D(1, (4, 4), activation='relu', inp...
/Users/scrier/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Usi...
MIT
Deep.Learning/3.Convulutional-Networks/2.Convolutional-Neural-Networks/conv_visualization.ipynb
Scrier/udacity
Part - 2: COVID-19 Time Series Analysis and Prediction using ML.Net framework COVID-19- As per [Wiki](https://en.wikipedia.org/wiki/Coronavirus_disease_2019) **Coronavirus disease 2019** (**COVID-19**) is an infectious disease caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2). The disease was fir...
#!about
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
1. Define Application wide Items Nuget Packages
// ML.NET Nuget packages installation #r "nuget:Microsoft.ML" #r "nuget:Microsoft.ML.TimeSeries" #r "nuget:Microsoft.Data.Analysis" // Install XPlot package #r "nuget:XPlot.Plotly"
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
Namespaces
using System; using System.Collections.Generic; using System.Linq; using Microsoft.ML; using Microsoft.ML.Data; using Microsoft.Data.Analysis; using Microsoft.ML.Transforms.TimeSeries; using Microsoft.AspNetCore.Html; using XPlot.Plotly;
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
Constants
const string CONFIRMED_DATASET_FILE = "time_series_covid19_confirmed_global_transposed.csv"; // Forecast API const int WINDOW_SIZE = 5; const int SERIES_LENGTH = 10; const int TRAIN_SIZE = 100; const int HORIZON = 7; // Dataset const int DEFAULT_ROW_COUNT = 10; const string TOTAL_CONFIRMED_COLUMN = "TotalConfirmed"; ...
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
2. Utility Functions - TBR FormattersBy default the output of DataFrame is not proper and in order to display it as a table, we need to have a custom formatter implemented as shown in next cell.
Formatter<DataFrame>.Register((df, writer) => { var headers = new List<IHtmlContent>(); headers.Add(th(i("index"))); headers.AddRange(df.Columns.Select(c => (IHtmlContent) th(c.Name))); var rows = new List<List<IHtmlContent>>(); var take = DEFAULT_ROW_COUNT; for (var i = 0; i < Math.Min(take, df...
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
3. Dataset and Transformations Download Dataset- Actual Dataset: [Johns Hopkins CSSE](https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series)- Transformed Dataset: [time_series_covid19_confirmed_global_transposed.csv](time_series_covid19_confirmed_global_transposed.csv)I'l...
/// <summary> /// Represent data for confirmed cases with a mapping to columns in a dataset /// </summary> public class ConfirmedData { /// <summary> /// Date of confirmed case /// </summary> [LoadColumn(0)] public DateTime Date; /// <summary> /// Total no of confirmed cases on a particular...
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
5. Data Analysis For loading data from csv, first we need to create MLContext that acts as a starting point for creating a machine learning model in ML.Net. Few things to note- Set hasHeader as true as our dataset has header- Add separatorChar to ',' as its a csv Visualize Data - DataFrame
var predictedDf = DataFrame.LoadCsv(CONFIRMED_DATASET_FILE); predictedDf.Head(DEFAULT_ROW_COUNT) predictedDf.Tail(DEFAULT_ROW_COUNT) predictedDf.Description()
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
Number of Confirmed cases over Time
// Number of confirmed cases over time var totalConfirmedDateColumn = predictedDf.Columns[DATE_COLUMN]; var totalConfirmedColumn = predictedDf.Columns[TOTAL_CONFIRMED_COLUMN]; var dates = new List<string>(); var totalConfirmedCases = new List<string>(); for (int index = 0; index < totalConfirmedDateColumn.Length; inde...
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
**Analysis**- Duration: 1/22/2020 through 5/27/2020- Total records: 127- Case on first day: 555- Case on last day: 5691790- No of confirmed cases was low in the beginning, there was first jump around 2/12/2020 and an exponential jump around 3/22/2020.- Cases have been increasing at an alarming rate in the past two mont...
var context = new MLContext(); var data = context.Data.LoadFromTextFile<ConfirmedData>(CONFIRMED_DATASET_FILE, hasHeader: true, separatorChar: ',');
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
7. ML Pipeline For creating ML Pipeline for a time-series analysis, we'll use [Single Spectrum Analysis](https://en.wikipedia.org/wiki/Singular_spectrum_analysis). ML.Net provides built in API for same, more details could be found at [TimeSeriesCatalog.ForecastBySsa](https://docs.microsoft.com/en-us/dotnet/api/microso...
var pipeline = context.Forecasting.ForecastBySsa( nameof(ConfirmedForecast.Forecast), nameof(ConfirmedData.TotalConfirmed), WINDOW_SIZE, SERIES_LENGTH, TRAIN_SIZE, HORIZON);
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
8. Train Model We are ready with our pipeline and ready to train the model
var model = pipeline.Fit(data);
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
9. Prediction/Forecasting - 7 days Our model is trained and we need to do prediction for next 7(Horizon) days.Time-series provides its own engine for making prediction which is similar to PredictionEngine present in ML.Net. Predicted values show an increasing trend which is in alignment with recent past values.
var forecastingEngine = model.CreateTimeSeriesEngine<ConfirmedData, ConfirmedForecast>(context); var forecasts = forecastingEngine.Predict(); display(forecasts.Forecast.Select(x => (int) x))
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
10. Prediction Visualization
var lastDate = DateTime.Parse(dates.LastOrDefault()); var predictionStartDate = lastDate.AddDays(1); for (int index = 0; index < HORIZON; index++) { dates.Add(lastDate.AddDays(index + 1).ToShortDateString()); totalConfirmedCases.Add(forecasts.Forecast[index].ToString()); } var title = "Number of Confirmed Case...
_____no_output_____
MIT
part-2/Part-2-COVID-19-mlnet-prediction.ipynb
praveenraghuvanshi1512/covid-19
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/jupyter/transformers/HuggingFace%20in%20Spark%20NLP%20-%20RoBertaForTokenClassification.ipynb) Import RoBertaForTokenClassification models from HuggingFace �...
!pip install -q transformers==4.10.0 tensorflow==2.4.1
 |████████████████████████████████| 2.8 MB 7.0 MB/s  |████████████████████████████████| 394.3 MB 14 kB/s  |████████████████████████████████| 895 kB 73.7 MB/s  |████████████████████████████████| 636 kB 73.2 MB/s  |████████████████████████████████| 3.3 MB 37.9 MB/s  |███████...
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
- HuggingFace comes with a native `saved_model` feature inside `save_pretrained` function for TensorFlow based models. We will use that to save it as TF `SavedModel`.- We'll use [philschmid/distilroberta-base-ner-wikiann-conll2003-3-class](https://huggingface.co/philschmid/distilroberta-base-ner-wikiann-conll2003-3-cla...
from transformers import TFRobertaForTokenClassification, RobertaTokenizer MODEL_NAME = 'philschmid/distilroberta-base-ner-wikiann-conll2003-3-class' tokenizer = RobertaTokenizer.from_pretrained(MODEL_NAME) tokenizer.save_pretrained('./{}_tokenizer/'.format(MODEL_NAME)) # just in case if there is no TF/Keras file p...
_____no_output_____
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
Let's have a look inside these two directories and see what we are dealing with:
!ls -l {MODEL_NAME} !ls -l {MODEL_NAME}/saved_model/1 !ls -l {MODEL_NAME}_tokenizer
total 1336 -rw-r--r-- 1 root root 456318 Sep 20 11:56 merges.txt -rw-r--r-- 1 root root 239 Sep 20 11:56 special_tokens_map.json -rw-r--r-- 1 root root 1352 Sep 20 11:56 tokenizer_config.json -rw-r--r-- 1 root root 898822 Sep 20 11:56 vocab.json
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
- as you can see, we need the SavedModel from `saved_model/1/` path- we also be needing `vocab.json` and `merges.txt` files from the tokenizer- all we need is to first convert `vocab.json` to `vocab.txt` and copy both `vocab.txt` and `merges.txt` into `saved_model/1/assets` which Spark NLP will look for- in addition to...
asset_path = '{}/saved_model/1/assets'.format(MODEL_NAME) # let's save the vocab as txt file with open('{}_tokenizer/vocab.txt'.format(MODEL_NAME), 'w') as f: for item in tokenizer.get_vocab().keys(): f.write("%s\n" % item) # let's copy both vocab.txt and merges.txt files to saved_model/1/assets !cp {MODE...
_____no_output_____
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
Voila! We have our `vocab.txt` and `labels.txt` inside assets directory
!ls -l {MODEL_NAME}/saved_model/1/assets
total 852 -rw-r--r-- 1 root root 37 Sep 20 11:59 labels.txt -rw-r--r-- 1 root root 456318 Sep 20 11:59 merges.txt -rw-r--r-- 1 root root 407065 Sep 20 11:59 vocab.txt
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
Import and Save RobertaForTokenClassification in Spark NLP - Let's install and setup Spark NLP in Google Colab- This part is pretty easy via our simple script
! wget http://setup.johnsnowlabs.com/colab.sh -O - | bash
_____no_output_____
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
Let's start Spark with Spark NLP included via our simple `start()` function
import sparknlp # let's start Spark with Spark NLP spark = sparknlp.start()
_____no_output_____
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
- Let's use `loadSavedModel` functon in `RoBertaForTokenClassification` which allows us to load TensorFlow model in SavedModel format- Most params can be set later when you are loading this model in `RoBertaForTokenClassification` in runtime like `setMaxSentenceLength`, so don't worry what you are setting them now- `lo...
from sparknlp.annotator import * tokenClassifier = RoBertaForTokenClassification\ .loadSavedModel('{}/saved_model/1'.format(MODEL_NAME), spark)\ .setInputCols(["sentence",'token'])\ .setOutputCol("ner")\ .setCaseSensitive(True)\ .setMaxSentenceLength(128)
_____no_output_____
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
- Let's save it on disk so it is easier to be moved around and also be used later via `.load` function
tokenClassifier.write().overwrite().save("./{}_spark_nlp".format(MODEL_NAME))
_____no_output_____
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
Let's clean up stuff we don't need anymore
!rm -rf {MODEL_NAME}_tokenizer {MODEL_NAME}
_____no_output_____
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
Awesome 😎 !This is your RoBertaForTokenClassification model from HuggingFace 🤗 loaded and saved by Spark NLP 🚀
! ls -l {MODEL_NAME}_spark_nlp
total 322504 drwxr-xr-x 6 root root 4096 Sep 20 12:01 fields drwxr-xr-x 2 root root 4096 Sep 20 12:01 metadata -rw-r--r-- 1 root root 330232386 Sep 20 12:01 roberta_classification_tensorflow
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
Now let's see how we can use it on other machines, clusters, or any place you wish to use your new and shiny RoBertaForTokenClassification model 😊
tokenClassifier_loaded = RoBertaForTokenClassification.load("./{}_spark_nlp".format(MODEL_NAME))\ .setInputCols(["sentence",'token'])\ .setOutputCol("ner") tokenClassifier_loaded.getCaseSensitive()
_____no_output_____
Apache-2.0
jupyter/transformers/HuggingFace in Spark NLP - RoBertaForTokenClassification.ipynb
hatrungduc/spark-nlp-workshop
Section 2.1 `xarray`, `az.InferenceData`, and NetCDF for Markov Chain Monte Carlo_How do we generate, store, and save Markov chain Monte Carlo results_
import numpy as np import pandas as pd import scipy.stats as stats import matplotlib.pyplot as plt import arviz as az import pystan import xarray as xr from IPython.display import Video np.random.seed(0) plt.style.use('arviz-white')
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
Learning Objectives* Understand Markov chain Monte Carlo fundamentals* Recognize the meaning of sample, draws, and chains in MCMC context* Understand relationship between Xarray, az.InferenceData, and NetCDF* Gain profiency with Xarray, NetCDF, and az.InferenceData objects Markov Chain Monte Carlo**Pop quiz**: Why do...
Video("../../img/medium_steps.mp4")
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
In MCMC Step 2 and Step 4 is where most MCMC variants differentiate themselves. Algorithms like Hamiltonian Monte Carlo and Sequential Monte Carlo are better at picking that next step for certain tasks. Richard McElreath has a great visual explainer [on his blog]([http://elevanth.org/blog/2017/11/28/build-a-better-mark...
def mh_sampler(data, samples=4, mu_init=.5): mu_current = mu_init posterior = [] prior_logpdf = stats.norm(0, 1).logpdf for i in range(samples): # suggest new position mu_proposal = stats.norm(mu_current, 0.5).rvs() # Compute likelihood by multiplying probabilities of each ...
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
SetupBefore using the sampler let's generate some data to test our Metropolis Hasting Implementation. In the code block below we are generating a bimodal distribution for the sampler.
data = stats.norm.rvs(loc=30, scale=1, size=1000).flatten()
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
We'll also plot our samples to get a sense of what the distribution of data looks like. Note how the histogram centers around 30. This should intuitively make sense as we're specified a mean of 30 when generating random values.
fig, ax = plt.subplots() ax.hist(data) fig.suptitle("Histogram of observed data");
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
As humans we can intuit *data mean* of **30** + an offset of **20** will lead to a parameter mean for *mu* of **10**. We want to see if our inference algorithm can recover our parameters. Single Variable Single Chain Inference Run The simplest MCMC run we can perform is with a single variable and a single chain. We'll...
samples = 200 chain = mh_sampler(data=data, samples=samples) chain[:100]
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
And just like that we've performed an inference run! We can generate a traceplot
fig, ax = plt.subplots(figsize=(10, 7)) x = np.arange(samples) ax.plot(x, chain);
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
In terms of data structures, for a **single** variable **single** chain inference run, an array suffices for storing samples. Single Variable Multiple Chain Inference Run As Bayesian modelers, life would be relatively easy if a single chain worked well every time, but unfortunately this is not the case. To understand ...
chain_0 = mh_sampler(data=data, samples=samples) chain_1 = mh_sampler(data=data, samples=samples, mu_init=13) data_df = pd.DataFrame({"x_0":chain_0, "x_1":chain_1}) fig, ax = plt.subplots() x = np.arange(samples) ax.plot(x, data_df["x_0"], c="g") ax.plot(x, data_df["x_1"])
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
With two chains converging to approximately a single value we can be more confident that the sampler reached the true underlying parameter. We can also store the results in a 2D data structures, such as Pandas Dataframes in python memory, and csvs or sql tables for persistent on disk storage. Multiple Variable Multipl...
posterior = xr.Dataset( {"mu": (["chain", "draw"], [[11,12,13],[22,23,24]]), "sd": (["chain", "draw"], [[33,34,35],[44,45,46]])}, coords={"draw": [1,2,3], "chain": [0,1]}, ) posterior
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
Multiple Variable Multiple Chain Inference runs and associated datasetsAs a Bayesian modelers, life would be relatively easy if we were only concerned about posterior distributions. Looking back at the full end to end workflow, recall that there are other datasets, such as prior predictive samples, posterior predictiv...
stan_code_prior = """ data { int<lower=1> N; } parameters { real mu; // Estimated parameter } model { mu ~ normal(0, 1); } generated quantities { real y_hat[N]; // prior prediction for (n in 1:N) { y_hat[n] = normal_rng(mu+20, 1); } } """ stan_prior = pystan.StanModel(model_code=stan_co...
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
NetCDFCalculating the various datasets is usually not trivial. Network Common Data Form (NetCDF) is an open standard for storing multidimensional datasets, and `xarray` is a library for doing high performance analysis on those datasets. NetCDF even comes with "group" support, making it easy to serialize az.InferenceDa...
data = az.load_arviz_data("centered_eight") data
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
The benefits of az.InferenceDataOne of the goals for the ArviZ developers is to ensure that Bayesian practioners can share and reproduce analyses regardless of PPl, regardless of language and az.InferenceData was the implementation of this idea.In summary az.InferenceData * provides a consistent format for Bayesian da...
data_dict = {"mu": [chain_0, chain_1]} home_built_data = az.from_dict(data_dict) home_built_data # Load NetCDF from disk into memory ## Replace with NetCDF that's "visible" data = az.load_arviz_data("centered_eight") # Reference posterior directly posterior = data.posterior posterior # Select specific variables posteri...
_____no_output_____
Apache-2.0
notebooks/2_DataStructures/1_Ins_DataStructures.ipynb
fabriquant/bayesian-model-evaluation
Tutorial 1: "What" models**Week 1, Day 1: Model Types****By Neuromatch Academy**__Content creators:__ Matt Laporte, Byron Galbraith, Konrad Kording__Content reviewers:__ Dalin Guo, Aishwarya Balwani, Madineh Sarvestani, Maryam Vaziri-Pashkam, Michael WaskomWe would like to acknowledge [Steinmetz _et al._ (2019)](http...
# @title Video 1: "What" Models from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
Setup Python requires you to explictly "import" libraries before their functions are available to use. We will always specify our imports at the beginning of each notebook or script.
import numpy as np import matplotlib.pyplot as plt
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
Tutorial notebooks typically begin with several set-up steps that are hidden from view by default.**Important:** Even though the code is hidden, you still need to run it so that the rest of the notebook can work properly. Step through each cell, either by pressing the play button in the upper-left-hand corner or with a...
#@title Figure Settings import ipywidgets as widgets #interactive display %matplotlib inline %config InlineBackend.figure_format = 'retina' plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle") #@title Helper functions #@markdown Most of the tutorials make use of help...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
--- Section 1: Exploring the Steinmetz datasetIn this tutorial we will explore the structure of a neuroscience dataset.We consider a subset of data from a study of [Steinmetz _et al._ (2019)](https://www.nature.com/articles/s41586-019-1787-x). In this study, Neuropixels probes were implanted in the brains of mice. Elec...
type(spike_times)
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
You should see `numpy.ndarray`, which means that it's a normal NumPy array.If you see an error message, it probably means that you did not execute the set-up cells at the top of the notebook. So go ahead and make sure to do that.Once everything is running properly, we can ask the next question about the dataset: what's...
spike_times.shape
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
There are 734 entries in one dimension, and no other dimensions. What is the Python type of the first entry, and what is *its* shape?
idx = 0 print( type(spike_times[idx]), spike_times[idx].shape, sep="\n", )
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
It's also a NumPy array with a 1D shape! Why didn't this show up as a second dimension in the shape of `spike_times`? That is, why not `spike_times.shape == (734, 826)`?To investigate, let's check another entry.
idx = 321 print( type(spike_times[idx]), spike_times[idx].shape, sep="\n", )
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
It's also a 1D NumPy array, but it has a different shape. Checking the NumPy types of the values in these arrays, and their first few elements, we see they are composed of floating point numbers (not another level of `np.ndarray`):
i_neurons = [0, 321] i_print = slice(0, 5) for i in i_neurons: print( "Neuron {}:".format(i), spike_times[i].dtype, spike_times[i][i_print], "\n", sep="\n" )
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
Note that this time we've checked the NumPy `dtype` rather than the Python variable type. These two arrays contain floating point numbers ("floats") with 32 bits of precision.The basic picture is coming together:- `spike_times` is 1D, its entries are NumPy arrays, and its length is the number of neurons (734): by index...
n_neurons = len(spike_times) total_spikes_per_neuron = [len(spike_times_i) for spike_times_i in spike_times] print(f"Number of neurons: {n_neurons}") print(f"Number of spikes for first five neurons: {total_spikes_per_neuron[:5]}") # @title Video 2: Exploring the dataset from ipywidgets import widgets out2 = widgets.O...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
Section 1.2: Getting warmer: counting and plotting total spike countsAs we've seen, the number of spikes over the entire recording is variable between neurons. More generally, some neurons tend to spike more than others in a given period. Lets explore what the distribution of spiking looks like across all the neurons ...
plt.hist(total_spikes_per_neuron, bins=50, histtype="stepfilled") plt.xlabel("Total spikes per neuron") plt.ylabel("Number of neurons");
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
Let's see what percentage of neurons have a below-average spike count:
mean_spike_count = np.mean(total_spikes_per_neuron) frac_below_mean = (total_spikes_per_neuron < mean_spike_count).mean() print(f"{frac_below_mean:2.1%} of neurons are below the mean")
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
We can also see this by adding the average spike count to the histogram plot:
plt.hist(total_spikes_per_neuron, bins=50, histtype="stepfilled") plt.xlabel("Total spikes per neuron") plt.ylabel("Number of neurons") plt.axvline(mean_spike_count, color="orange", label="Mean neuron") plt.legend();
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
This shows that the majority of neurons are relatively "quiet" compared to the mean, while a small number of neurons are exceptionally "loud": they must have spiked more often to reach a large count. Exercise 1: Comparing mean and median neuronsIf the mean neuron is more active than 68% of the population, what does tha...
# To complete the exercise, fill in the missing parts (...) and uncomment the code median_spike_count = ... # Hint: Try the function np.median # plt.hist(..., bins=50, histtype="stepfilled") # plt.axvline(..., color="limegreen", label="Median neuron") # plt.axvline(mean_spike_count, color="orange", label="Mean neuro...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D1_ModelTypes/solutions/W1D1_Tutorial1_Solution_b3411d5d.py)*Example output:* *Bonus:* The median is the 50th percentile. What about other percentiles? Can you show the interquartile range on the histogram? --- Section 2...
help(restrict_spike_times) t_interval = (5, 15) # units are seconds after start of recording interval_spike_times = restrict_spike_times(spike_times, t_interval)
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
Is this a representative interval? What fraction of the total spikes fall in this interval?
original_counts = sum([len(spikes) for spikes in spike_times]) interval_counts = sum([len(spikes) for spikes in interval_spike_times]) frac_interval_spikes = interval_counts / original_counts print(f"{frac_interval_spikes:.2%} of the total spikes are in the interval")
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
How does this compare to the ratio between the interval duration and the experiment duration? (What fraction of the total time is in this interval?)We can approximate the experiment duration by taking the minimum and maximum spike time in the whole dataset. To do that, we "concatenate" all of the neurons into one array...
spike_times_flat = np.concatenate(spike_times) experiment_duration = np.ptp(spike_times_flat) interval_duration = t_interval[1] - t_interval[0] frac_interval_time = interval_duration / experiment_duration print(f"{frac_interval_time:.2%} of the total time is in the interval")
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
These two values—the fraction of total spikes and the fraction of total time—are similar. This suggests the average spike rate of the neuronal population is not very different in this interval compared to the entire recording. Section 2.2: Plotting spike trains and rastersNow that we have a representative subset, we're...
neuron_idx = 1 plt.eventplot(interval_spike_times[neuron_idx], color=".2") plt.xlabel("Time (s)") plt.yticks([]);
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
We can also plot multiple neurons. Here are three:
neuron_idx = [1, 11, 51] plt.eventplot(interval_spike_times[neuron_idx], color=".2") plt.xlabel("Time (s)") plt.yticks([]);
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
This makes a "raster" plot, where the spikes from each neuron appear in a different row.Plotting a large number of neurons can give you a sense for the characteristics in the population. Let's show every 5th neuron that was recorded:
neuron_idx = np.arange(0, len(spike_times), 5) plt.eventplot(interval_spike_times[neuron_idx], color=".2") plt.xlabel("Time (s)") plt.yticks([]);
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
*Question*: How does the information in this plot relate to the histogram of total spike counts that you saw above?
# @title Video 3: Visualizing activity from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?b...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
--- Section 3: Inter-spike intervals and their distributions Given the ordered arrays of spike times for each neuron in `spike_times`, which we've just visualized, what can we ask next?Scientific questions are informed by existing models. So, what knowledge do we already have that can inform questions about this data?W...
def compute_single_neuron_isis(spike_times, neuron_idx): """Compute a vector of ISIs for a single neuron given spike times. Args: spike_times (list of 1D arrays): Spike time dataset, with the first dimension corresponding to different neurons. neuron_idx (int): Index of the unit to compute ISIs for. ...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D1_ModelTypes/solutions/W1D1_Tutorial1_Solution_4792dbfa.py)*Example output:* ---In general, the shorter ISIs are predominant, with counts decreasing rapidly (and smoothly, more or less) with increasing ISI. However, cou...
# @title Video 4: ISI distribution from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid=...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
The ISI histograms seem to follow continuous, monotonically decreasing functions above their maxima. The function is clearly non-linear. Could it belong to a single family of functions?To motivate the idea of using a mathematical function to explain physiological phenomena, let's define a few different function forms t...
def exponential(xs, scale, rate, x0): """A simple parametrized exponential function, applied element-wise. Args: xs (np.ndarray or float): Input(s) to the function. scale (float): Linear scaling factor. rate (float): Exponential growth (positive) or decay (negative) rate. x0 (float): Horizontal off...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
Interactive Demo: ISI functions explorerHere is an interactive demo where you can vary the parameters of these functions and see how well the resulting outputs correspond to the data. Adjust the parameters by moving the sliders and see how close you can get the lines to follow the falling curve of the histogram. This ...
#@title #@markdown Be sure to run this cell to enable the demo # Don't worry about understanding this code! It's to setup an interactive plot. single_neuron_idx = 283 single_neuron_spikes = spike_times[single_neuron_idx] single_neuron_isis = np.diff(single_neuron_spikes) counts, edges = np.histogram( single_neuron_...
_____no_output_____
CC-BY-4.0
tutorials/W1D1_ModelTypes/student/W1D1_Tutorial1.ipynb
JulioLarrea/course-content
IntroductionTry writing some **SELECT** statements of your own to explore a large dataset of air pollution measurements.Run the cell below to set up the feedback system.
# Set up feedback system from learntools.core import binder binder.bind(globals()) from learntools.sql.ex2 import * print("Setup Complete")
_____no_output_____
Apache-2.0
notebooks/sql/raw/ex2.ipynb
Mattjez914/Blackjack_Microchallenge
The code cell below fetches the `global_air_quality` table from the `openaq` dataset. We also preview the first five rows of the table.
from google.cloud import bigquery # Create a "Client" object client = bigquery.Client() # Construct a reference to the "openaq" dataset dataset_ref = client.dataset("openaq", project="bigquery-public-data") # API request - fetch the dataset dataset = client.get_dataset(dataset_ref) # Construct a reference to the "g...
_____no_output_____
Apache-2.0
notebooks/sql/raw/ex2.ipynb
Mattjez914/Blackjack_Microchallenge
Exercises 1) Units of measurementWhich countries have reported pollution levels in units of "ppm"? In the code cell below, set `first_query` to an SQL query that pulls the appropriate entries from the `country` column.In case it's useful to see an example query, here's some code from the tutorial:```query = """ ...
# Query to select countries with units of "ppm" first_query = ____ # Your code goes here # Set up the query (cancel the query if it would use too much of # your quota, with the limit set to 1 GB) safe_config = bigquery.QueryJobConfig(maximum_bytes_billed=1e9) first_query_job = client.query(first_query, job_config=saf...
_____no_output_____
Apache-2.0
notebooks/sql/raw/ex2.ipynb
Mattjez914/Blackjack_Microchallenge
For the solution, uncomment the line below.
#q_1.solution()
_____no_output_____
Apache-2.0
notebooks/sql/raw/ex2.ipynb
Mattjez914/Blackjack_Microchallenge
2) High air qualityWhich pollution levels were reported to be exactly 0? - Set `zero_pollution_query` to select **all columns** of the rows where the `value` column is 0.- Set `zero_pollution_results` to a pandas DataFrame containing the query results.
# Query to select all columns where pollution levels are exactly 0 zero_pollution_query = ____ # Your code goes here # Set up the query query_job = client.query(zero_pollution_query, job_config=safe_config) # API request - run the query and return a pandas DataFrame zero_pollution_results = ____ # Your code goes here...
_____no_output_____
Apache-2.0
notebooks/sql/raw/ex2.ipynb
Mattjez914/Blackjack_Microchallenge
For the solution, uncomment the line below.
#q_2.solution()
_____no_output_____
Apache-2.0
notebooks/sql/raw/ex2.ipynb
Mattjez914/Blackjack_Microchallenge
ETL Pipeline PreparationFollow the instructions below to help you create your ETL pipeline. 1. Import libraries and load datasets.- Import Python libraries- Load `messages.csv` into a dataframe and inspect the first few lines.- Load `categories.csv` into a dataframe and inspect the first few lines.
# import libraries import pandas as pd import numpy as np # load messages dataset messages = pd.read_csv("../data/disaster_messages.csv") messages.head() # load categories dataset categories = pd.read_csv("../data/disaster_categories.csv") categories.head()
_____no_output_____
MIT
notebooks/ETL Pipeline Preparation.ipynb
felixnext/disaster_pipeline
2. Merge datasets.- Merge the messages and categories datasets using the common id- Assign this combined dataset to `df`, which will be cleaned in the following steps
# merge datasets df = pd.merge(messages, categories, on="id") df.head() df['categories'].unique()
_____no_output_____
MIT
notebooks/ETL Pipeline Preparation.ipynb
felixnext/disaster_pipeline
3. Split `categories` into separate category columns.- Split the values in the `categories` column on the `;` character so that each value becomes a separate column. You'll find [this method](https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.Series.str.split.html) very helpful! Make sure to set `expa...
# create a dataframe of the 36 individual category columns df_tmp = df['categories'].str.split(";", expand=True) cols = [w.split("-")[0] for w in df_tmp.iloc[0, :].tolist()] df_tmp.columns = cols df_tmp = df_tmp.apply(lambda x: x.str.replace(".*?-([0-9]+)", r"\g<1>").astype(int)).clip(0, 1) df = pd.concat([df.iloc[:, :...
_____no_output_____
MIT
notebooks/ETL Pipeline Preparation.ipynb
felixnext/disaster_pipeline
4. Remove duplicates.- Check how many duplicates are in this dataset.- Drop the duplicates.- Confirm duplicates were removed.
# check number of duplicates df_dub = df[df.duplicated(subset=None)] print("Duplicates: {}".format(df_dub.shape[0])) df_dub.head() # drop duplicates df = df.drop_duplicates() # check number of duplicates df[df.duplicated(subset=None)]
_____no_output_____
MIT
notebooks/ETL Pipeline Preparation.ipynb
felixnext/disaster_pipeline
Check for items with a very low mean
desc = df.describe() desc[desc.columns[desc.loc['std', :] < 0.01]] # since child_alone holds no relevant information, remove: df = df.drop('child_alone', axis=1)
_____no_output_____
MIT
notebooks/ETL Pipeline Preparation.ipynb
felixnext/disaster_pipeline
5. Save the clean dataset into an sqlite database.You can do this with pandas [`to_sql` method](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html) combined with the SQLAlchemy library. Remember to import SQLAlchemy's `create_engine` in the first cell of this notebook to use it below.
from sqlalchemy import create_engine engine = create_engine('sqlite:///../data/disaster_data.db') df.to_sql('texts', engine, index=False)
_____no_output_____
MIT
notebooks/ETL Pipeline Preparation.ipynb
felixnext/disaster_pipeline
选择 布尔类型、数值和表达式![](../Photo/33.png)- 注意:比较运算符的相等是两个等到,一个等到代表赋值- 在Python中可以用整型0来代表False,其他数字来代表True- 后面还会讲到 is 在判断语句中的用发
b=100 aa = eval(input('请输入密码: ')) bb = 123456 if aa == bb: a = eval(input('请输入取多少钱: ')) if a <= b: c = b-a print('取钱成功') b=c print('余额',c) # send_message() else: print('失败') else: print('密码错误')
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
字符串的比较使用ASCII值 Markdown - https://github.com/younghz/Markdown EP:- - 输入一个数字,判断其实奇数还是偶数 产生随机数字- 函数random.randint(a,b) 可以用来产生一个a和b之间且包括a和b的随机整数 其他random方法- random.random 返回0.0到1.0之间前闭后开区间的随机浮点- random.randrange(a,b) 前闭后开 EP:- 产生两个随机整数number1和number2,然后显示给用户,使用户输入数字的和,并判定其是否正确- 进阶:写一个随机序号点名程序
import random a = random.randint(1,10) b = random.randint(1,6) if b < 5: print('请第',a,'行','第',b,'个同学回答问题') else: print('请第 9 行','第',b,'个同学回答问题')
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
if语句- 如果条件正确就执行一个单向if语句,亦即当条件为真的时候才执行if内部的语句- Python有很多选择语句:> - 单向if - 双向if-else - 嵌套if - 多向if-elif-else - 注意:当语句含有子语句的时候,那么一定至少要有一个缩进,也就是说如果有儿子存在,那么一定要缩进- 切记不可tab键和space混用,单用tab 或者 space- 当你输出的结果是无论if是否为真时都需要显示时,语句应该与if对齐 EP:- 用户输入一个数字,判断其实奇数还是偶数- 进阶:可以查看下4.5实例研究猜生日 双向if-else 语句- 如果条件为真,那么走if内部语句,否则走else内部语句 ...
tz = eval(input('请输入体重(KG): ')) sg = eval(input('身高(m): ')) aa = tz / sg if aa<18.5: print('超轻') if 18.5<=aa<25.0: print('标准') if 25.0<=aa<30.0: print('超重') if 30.0<=aa: print('吃肥') year = eval(input('请输入年份: ')) b = year % 12 if b == 0: print('猴') elif b== 1: print('鸡') elif b== 2: print('狗'...
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
逻辑运算符![](../Photo/38.png) ![](../Photo/39.png)![](../Photo/40.png) EP:- 判定闰年:一个年份如果能被4整除但不能被100整除,或者能被400整除,那么这个年份就是闰年- 提示用户输入一个年份,并返回是否是闰年- 提示用户输入一个数字,判断其是否为水仙花数
for i in range(100,1000): a = i % 10 b = i // 100 c = (i // 10) % 10 e = a ** 3 + b ** 3 + c ** 3 if e == i: print(e) stri = 'asdsad' stri[1] year = eval(input('nianfen: ')) if (year % 4 ==0 and year % 100 != 0) or year % 400 ==0: print('闰年') else: print('非')
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
实例研究:彩票![](../Photo/41.png)
import random a = input('请输入一个两位数: ') b = str(random.randint(10,99)) print('随机生成: ',b) if a == (b[0]+b[1]): print('恭喜获得10000$') elif a == (b[1]+b[0]): print('恭喜获得3000$') elif a[0] == b[0] or a[0] == b[1] or a[1] == b[0] or a[1] == b[1]: print('恭喜获得1000$') else: print('抱歉什么也没有!')
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
Homework- 1![](../Photo/42.png)
import math a,b,c = eval(input('Enter a,b,c')) e = b**2 -4*a*c if e > 0: r1=(-b+math.sqrt(e))/2*a r2=(-b-math.sqrt(e))/2*a print('r1=',round(r1,6),'\nr2',round(r2,6)) elif e == 0: r =-b / 2*a print('r=',int(r)) else: print('没有实根!')
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
- 2![](../Photo/43.png)
import random a = random.randint(0,100) b = random.randint(0,100) print('生成2个数为: ',a,' ',b) c = eval(input('请输入整和: ')) if b + a == c: print('真') else: print('假')
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
- 3![](../Photo/44.png)
a = eval(input('今天星期几: ')) b = eval(input('未来几天后: ')) c = (a+b)%7 if c==0: print('今天是星期日',b,'天后星期日') else: print('今天是星期',a,b,'天后星期',c)
今天星期几: 0 未来几天后: 31 今天是星期 0 31 天后星期 3
Apache-2.0
7.18.ipynb
dimong/dimongg
- 4![](../Photo/45.png)
a,b,c = eval(input('请输入3个数: ')) d=max(a,b,c) e=min(a,b,c) f=a+b+c-d-e print(e,f,d)
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
- 5![](../Photo/46.png)
a,b = eval(input('请输入1号重量和价钱: ')) c,d = eval(input('请输入2号重量和价钱: ')) e=a/b f=c/d if e>f: print('1号食品性价比更好!') else: print('2号食品性价比更好!')
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
- 6![](../Photo/47.png)
yue = eval(input('月份: ')) year = eval(input('年份: ')) if yue == 2: if ((year % 4 ==0 and year % 100 != 0) or year % 400 ==0): print(year,'年的2月有29天!') else: print(year,'年的2月有28天!') elif yue == 1 or yue ==3 or yue ==5 or yue ==7 or yue ==8 or yue ==10 or yue ==12: print(year,'年的',yue,'月有31天!')...
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
- 7![](../Photo/48.png)
import random a = random.randint(2,3) print('(测试程序是否正确2为正,3为反)',a) #2为正面,3为反面 b = input('请猜测硬币正反面: ') if b == '正面' and a == 2: print('猜对了!') elif b == '反面' and a==3: print('猜对了!') else: print('猜错了!')
(测试程序是否正确2为正,3为反) 3 请猜测硬币正反面: 正面 猜错了!
Apache-2.0
7.18.ipynb
dimong/dimongg
- 8![](../Photo/49.png)
import random a = eval(input('请输入你要出什么(0=剪刀,1=石头,2=布): ')) b = random.randint(0,2) print(b) if a == 0 and b == 2: print('玩家获胜!') elif a == 1 and b == 0: print('玩家获胜!') elif a == 2 and b == 1: print('玩家获胜!') elif a == b: print('平局!') else: print('电脑获胜!') h =(q+(26*(m+1))/10+k+k/4+j/4+5*j)%7
_____no_output_____
Apache-2.0
7.18.ipynb
dimong/dimongg
- 9![](../Photo/50.png)
year = eval(input('输入年份:')) months = eval(input('输入月份:')) days = eval(input('输入当前月份的某天:')) hdayDict = {0:'星期六',1:'星期日', 2: '星期一', 3: '星期二', 4: '星期三', 5: '星期四', 6: '星期五'} monDict = {1: '13', 2: '14', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', \ 11: '11', 12: '12'} if months == 1 or mo...
输入年份:2013 输入月份:1 输入当前月份的某天:25 Day of the week is 星期五
Apache-2.0
7.18.ipynb
dimong/dimongg
- 10![](../Photo/51.png)
import random a = random.randint(1,13) huase ={1:'梅花',2:'红桃',3:'方块',4:'黑桃'} c = random.randint(1,4) d = huase[c]+str(a) print(d)
黑桃1
Apache-2.0
7.18.ipynb
dimong/dimongg