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 |
|---|---|---|---|---|---|
Reinforcement Learning with CALVINThe **CALVIN** simulated benchmark is perfectly suited for training agents with reinforcement learning, in this notebook we will demonstrate how to integrate your agents to these environments. InstallationThe first step is to install the CALVIN github repository such that we have acc... | # Download repo
%mkdir /content/calvin
%cd /content/calvin
!git clone https://github.com/mees/calvin_env.git
%cd /content/calvin/calvin_env
!git clone https://github.com/lukashermann/tacto.git
# Install packages
%cd /content/calvin/calvin_env/tacto/
!pip3 install -e .
%cd /content/calvin/calvin_env
!pip3 install -e .
... | _____no_output_____ | MIT | RL_with_CALVIN.ipynb | lucys0/calvin |
Loading the environmentAfter the installation has finished successfully, we can start using the environment for reinforcement Learning.To be able to use the environment we need to have the appropriate configuration that define the desired features, for this example, we will load the static and gripper camera. | %cd /content/calvin
from hydra import initialize, compose
with initialize(config_path="./calvin_env/conf/"):
cfg = compose(config_name="config_data_collection.yaml", overrides=["cameras=static_and_gripper"])
cfg.env["use_egl"] = False
cfg.env["show_gui"] = False
cfg.env["use_vr"] = False
cfg.env["use_scene_i... | _____no_output_____ | MIT | RL_with_CALVIN.ipynb | lucys0/calvin |
The environment has similar structure to traditional OpenAI Gym environments.* We can restart the simulation with the *reset* function.* We can perform an action in the environment with the *step* function.* We can visualize images taken from the cameras in the environment by using the *render* function. | import time
import hydra
import numpy as np
from google.colab.patches import cv2_imshow
env = hydra.utils.instantiate(cfg.env)
observation = env.reset()
#The observation is given as a dictionary with different values
print(observation.keys())
for i in range(5):
# The action consists in a pose displacement (position ... | _____no_output_____ | MIT | RL_with_CALVIN.ipynb | lucys0/calvin |
Custom environment for Reinforcement LearningThere are some aspects that needs to be defined to be able to use it for reinforcement learning, including:1. Observation space2. Action space3. Reward functionWe are going to create a Custom environment that extends the **PlaytableSimEnv** to add these requirements.... | from gym import spaces
from calvin_env.envs.play_table_env import PlayTableSimEnv
class SlideEnv(PlayTableSimEnv):
def __init__(self,
tasks: dict = {},
**kwargs):
super(SlideEnv, self).__init__(**kwargs)
# For this example we will modify the observation to
... | _____no_output_____ | MIT | RL_with_CALVIN.ipynb | lucys0/calvin |
Training an RL agentAfter generating the wrapper training a reinforcement learning agent is straightforward, for this example we will use stable baselines 3 agents | !pip3 install stable_baselines3 | _____no_output_____ | MIT | RL_with_CALVIN.ipynb | lucys0/calvin |
To train the agent we create an instance of our new environment and send it to the stable baselines agent to learn a policy.> Note: the example uses Soft Actor Critic (SAC) which is one of the state of the art algorithm for off-policy RL. | import gym
import numpy as np
from stable_baselines3 import SAC
new_env_cfg = {**cfg.env}
new_env_cfg["tasks"] = cfg.tasks
new_env_cfg.pop('_target_', None)
new_env_cfg.pop('_recursive_', None)
env = SlideEnv(**new_env_cfg)
model = SAC("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=10000, log_interval=4)
| _____no_output_____ | MIT | RL_with_CALVIN.ipynb | lucys0/calvin |
TEXAS ERCOT | filter_1 = df_total['Balancing Authority'] == 'ERCO'
df_texas = df_total[filter_1]
df_texas
catagories_lst = ['Demand Forecast (MW)''Net Generation (MW) (Imputed)',
'Demand (MW) (Adjusted)', 'Net Generation (MW) (Adjusted)',
'Net Generation (MW) from Coal', 'Net Generation (MW) from Natural Gas',
'... | _____no_output_____ | MIT | notebooks/weather_energy_combine.ipynb | Cpizzle1/Texas_energy_use_weather_proj |
Polish phonetic comparison> "Transcript matching for E2E ASR with phonetic post-processing"- toc: false- branch: master- hidden: true- categories: [asr, polish, phonetic, todo] | from difflib import SequenceMatcher
import icu
plipa = icu.Transliterator.createInstance('pl-pl_FONIPA') | _____no_output_____ | Apache-2.0 | _notebooks/2021-04-29-phonetic-comparison.ipynb | jimregan/notes |
The errors in E2E models are quite often phonetic confusions, so we do the opposite of traditional ASR and generate the phonetic representation from the output as a basis for comparison. | def phonetic_check(word1, word2, ignore_spaces=False):
"""Uses ICU's IPA transliteration to check if words are the same"""
tl1 = plipa.transliterate(word1) if not ignore_spaces else plipa.transliterate(word1.replace(' ', ''))
tl2 = plipa.transliterate(word2) if not ignore_spaces else plipa.transliterate(wor... | _____no_output_____ | Apache-2.0 | _notebooks/2021-04-29-phonetic-comparison.ipynb | jimregan/notes |
The Polish `y` is phonetically a raised schwa; like the schwa in English, it's often deleted in fast speech. This function returns true if the only differences between the first word and the second is are deletions of `y`, except at the end of the word (which is typically the plural ending). | def no_igrek(word1, word2):
"""Checks if a word-internal y has been deleted"""
sm = SequenceMatcher(None, word1, word2)
for oc in sm.get_opcodes():
if oc[0] == 'equal':
continue
elif oc[0] == 'delete' and word1[oc[1]:oc[2]] != 'y':
return False
elif oc[0] == '... | ('equal', 0, 2, 0, 2)
('replace', 2, 3, 2, 4)
| Apache-2.0 | _notebooks/2021-04-29-phonetic-comparison.ipynb | jimregan/notes |
Reads a `CTM`-like file, returning a list of lists containing the filename, start time, end time, and word. | def read_ctmish(filename):
output = []
with open(filename, 'r') as f:
for line in f.readlines():
pieces = line.strip().split(' ')
if len(pieces) <= 4:
continue
for piece in pieces[4:]:
output.append([pieces[0], pieces[2], pieces[3], pie... | _____no_output_____ | Apache-2.0 | _notebooks/2021-04-29-phonetic-comparison.ipynb | jimregan/notes |
Returns the contents of a plain text file as a list of lists containing the line number and the word, for use in locating mismatches | def read_text(filename):
output = []
counter = 0
with open(filename, 'r') as f:
for line in f.readlines():
counter += 1
for word in line.strip().split(' ')
output.append([counter, word])
return output
ctmish = read_ctmish("/mnt/c/Users/Jim O\'Regan/git/not... | _____no_output_____ | Apache-2.0 | _notebooks/2021-04-29-phonetic-comparison.ipynb | jimregan/notes |
HW9: Forecasting Solar CyclesBelow is the notebook associated with HW\9. You can run the notebook in two modes. If you have the `emcee` and `corner` packages installed on your machine, along with the data files, just keep the following variable set to `False`. If you are running it in a Google colab notebook, set it t... | COLAB = False
if COLAB:
# Install emcee package
!pip install emcee
# Install corner package
!pip install corner
# Grab sunspot data file
!wget -O SN_m_tot_V2.0.txt https://raw.githubusercontent.com/mtlam/ASTP-720_F2020/master/HW9/SN_m_tot_V2.0.txt
import numpy as np
from matplotlib.pyplot im... | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
Define the (log-)priorsHere, the function should take a vector of parameters, `theta`, and return `0.0` if the it is in the prior range and `-np.inf` if it is outside. This is equivalent to a uniform prior over the parameters. You can, of course, define a different set of priors if you so choose! | def lnprior(theta):
"""
Parameters
----------
theta : np.ndarray
Array of parameters.
Returns
-------
Value of log-prior.
"""
pass | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
Define the (log-)likelihood | def lnlike(theta, data):
"""
Parameters
----------
theta : np.ndarray
Array of parameters.
data : np.ndarray
Returns
-------
Value of log-likelihood
"""
residuals = None
pass | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
Define total (log-)probabilityNo need to change this if the other two functions work as described. | def lnprob(theta, data):
lp = lnprior(theta)
if not np.isfinite(lp):
return -np.inf
return lp + lnlike(theta, data) | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
Set up the MCMC sampler here | # Number of walkers to search through parameter space
nwalkers = 10
# Number of iterations to run the sampler for
niter = 50000
# Initial guess of parameters. For example, if you had a model like
# s(t) = a + bt + ct^2
# and your initial guesses for a, b, and c were 5, 3, and 8, respectively, then you would write
# pin... | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
Load the data, plot to show | # Data: decimal year, sunspot number
decyear, ssn = np.loadtxt("SN_m_tot_V2.0.txt", unpack=True, usecols=(2, 3))
plot(decyear, ssn, 'k.')
xlabel('Year')
ylabel('Sunspot Number')
show() | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
Run the sampler | # Number of CPU threads to use. Reduce if you are running on your own machine
# and don't want to use too many cores
nthreads = 4
# Set up the sampler
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(ssn,), threads=nthreads)
# Run the sampler. May take a while! You might consider changing the
# number of ... | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
Get the samples in the appropriate format, with a burn value | # Burn-in value = 1/4th the number of iterations. Feel free to change!
burn = int(0.25*niter)
# Reshape the chains for input to corner.corner()
samples = sampler.chain[:, burn:, :].reshape((-1, ndim)) | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
Make a corner plotYou should feel free to adjust the parameters to the `corner` function. You **should** also add labels, which should just be a list of the names of the parameters. So, if you had two parameters, $\phi_1$ and $\phi_2$, then you could write:```labels = [r"$\phi_1$", r"$\phi_2$"]```and that will make th... | fig = corner.corner(samples, bins=50, color='C0', smooth=0.5, plot_datapoints=False, plot_density=True, \
plot_contours=True, fill_contour=False, show_titles=True)#, labels=labels)
fig.savefig("corner.png")
show() | _____no_output_____ | BSD-3-Clause | HW9/HW9-sunspots.ipynb | mtlam/ASTP-720_F2020 |
No. 2 NELFINAVIR MESYLATE | df.loc[df['output_name'] == 'NELFINAVIR'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 3 AMOPYROQUINE | df.loc[df['output_name'] == 'C0051735'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 7 HANFANGCHIN A | df.loc[df['output_name'] == 'C0076316'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 11 FERROQUINE | df.loc[df['output_name'] == 'C1313506'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 13 ASTEMIZOLE | df.loc[df['output_name'] == 'ASTEMIZOLE'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 14 amodiaquine | df.loc[df['output_name'] == 'AMODIAQUINE'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 22 (+)-MEFLOQUINE | df.loc[df['output_name'] == 'C0208248'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
ABOVE REFERS TO: name(Mefloquine Hydrochloride) umls(C0282398) | df.loc[df['output_name'] == 'C0208248'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
ABOVE REFERS TO: name(mefloquine-sulfadoxine-pyrimethamine) umls(C0208248) No. 27 CEPHARANTHINE | df.loc[df['output_name'] == 'C0055082'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 33 ANDROGRAPHOLIDE | df.loc[df['output_name'] == 'C0051821'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 39 NAFOXIDINE | df.loc[df['output_name'] == 'C0027328'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 48 RETINALDEHYDE | df.loc[df['output_name'] == 'C0035331'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 59 CLOFAZIMINE | df.loc[df['output_name'] == 'CLOFAZIMINE'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 63 PERHEXILINE | df.loc[df['output_name'] == 'PERHEXILINE'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 65 resiniferatoxin | df.loc[df['output_name'] == 'C0073081'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 69 EBASTINE | df.loc[df['output_name'] == 'EBASTINE'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 73 5-Azacytidine | df.loc[df['output_name'] == 'AZACITIDINE'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 76 AMIODARONE | df.loc[df['output_name'] == 'AMIODARONE']
df.loc[df['output_name'] == 'C0700442'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
Above refers to Amiodarone hydrochloride No. 79 NSP 805 | df.loc[df['output_name'] == 'C0660146'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 81 CLORICROMENE | df.loc[df['output_name'] == 'C0050066'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 82 TIFLUADOM | df.loc[df['output_name'] == 'C0076670'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
No. 85 SCH-28080 | df.loc[df['output_name'] == 'C0074142'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
NO. 96 IMMUNOMYCIN | df.loc[df['output_name'] == 'C0123418'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
NO.97 ARGLABIN | df.loc[df['output_name'] == 'C0661380'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
NO.100 TRETINOIN | df.loc[df['output_name'] == 'TRETINOIN'] | _____no_output_____ | Apache-2.0 | jupyter notebooks/COV-19___ACE2.ipynb | zhoue7673/biothings_explorer |
Load Cats and Dogs Images Install Packages | !pip install --upgrade keras==2.2.4
!pip install --upgrade tensorflow==1.13.1
!pip install --upgrade 'numpy<1.15.0' | _____no_output_____ | Apache-2.0 | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials |
> **Note:** After running the pip command you should restart the Jupyter kernel.> To restart the kernel, click on the kernel-restart button in the notebook menu toolbar (the refresh icon next to the **Code** button). Import Library | # This Python 3 environment comes with many helpful analytics libraries installed.
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python.
# For example, here are several helpful packages to load:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/... | _____no_output_____ | Apache-2.0 | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials |
Download the Data | !mkdir cats_and_dogs_filtered
# Download a sample stocks file from Iguazio demo bucket in AWS S3
!curl -L "iguazio-sample-data.s3.amazonaws.com/catsndogs.zip" > ./cats_and_dogs_filtered/catsndogs.zip
zip_ref = zipfile.ZipFile(DATA_PATH + 'catsndogs.zip', 'r')
zip_ref.extractall('cats_and_dogs_filtered')
zip_ref.close() | _____no_output_____ | Apache-2.0 | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials |
Prepare the Traning Data | import json
def build_prediction_map(categories_map):
return {v:k for k ,v in categories_map.items()}
# Create a file-names list (JPG image-files only)
filenames = [file for file in os.listdir(DATA_PATH+"/cats_n_dogs") if file.endswith('jpg')]
categories = []
# Categories and prediction-classes map
categories_map ... | _____no_output_____ | Apache-2.0 | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials |
Check the Total Image CountCheck the total image count for each category.The data set has 12,000 cat images and 12,000 dog images. | df['category'].value_counts().plot.bar() | _____no_output_____ | Apache-2.0 | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials |
Display the Sample Image | sample = random.choice(filenames)
image = load_img(DATA_PATH+"/cats_n_dogs/"+sample)
plt.imshow(image) | _____no_output_____ | Apache-2.0 | demos/gpu/horovod/cpu/image-classification/01-load-data-cats-n-dogs.ipynb | omesser/tutorials |
INSTALLATION | !pip install aif360
!pip install fairlearn
!apt-get install -jre
!java -version
!pip install h2o
!pip install xlsxwriter | Collecting xlsxwriter
Downloading XlsxWriter-2.0.0-py2.py3-none-any.whl (149 kB)
[?25l
[K |██▏ | 10 kB 19.1 MB/s eta 0:00:01
[K |████▍ | 20 kB 20.9 MB/s eta 0:00:01
[K |██████▋ | 30 kB 16.7 MB/s eta 0:00:01
[K |████████... | MIT | Fairness_Survey/ALGORITHMS/BaseLine/gbm and LogReg/German.ipynb | DEHO-OSCAR-BLESSED/Evaluation-of-Fairness-Algorithms |
IMPORTS | import numpy as np
from mlxtend.feature_selection import ExhaustiveFeatureSelector
from xgboost import XGBClassifier
# import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import openpyxl
import xlsxwriter
from openpyxl import load_workbook
import shap
#suppress setwith copy wa... | Checking whether there is an H2O instance running at http://localhost:54321 ..... not found.
Attempting to start a local H2O server...
Java Version: openjdk version "11.0.11" 2021-04-20; OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.18.04); OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.18.0... | MIT | Fairness_Survey/ALGORITHMS/BaseLine/gbm and LogReg/German.ipynb | DEHO-OSCAR-BLESSED/Evaluation-of-Fairness-Algorithms |
**************************LOADING DATASET******************************* | from google.colab import drive
drive.mount('/content/gdrive')
for i in range(1,51,1):
train_url=r'/content/gdrive/MyDrive/Datasets/SurveyData/DATASET/German/Train'
train_path= os.path.join(train_url ,("Train"+ str(i)+ ".csv"))
train= pd.read_csv(train_path)
test_url=r'/content/gdrive/MyDrive/Datasets/SurveyD... | _____no_output_____ | MIT | Fairness_Survey/ALGORITHMS/BaseLine/gbm and LogReg/German.ipynb | DEHO-OSCAR-BLESSED/Evaluation-of-Fairness-Algorithms |
LOGISTIC REGRESSION | for i in range(1,51,1):
train_url=r'/content/gdrive/MyDrive/Datasets/SurveyData/DATASET/German/Train'
train_path= os.path.join(train_url ,("Train"+ str(i)+ ".csv"))
train= pd.read_csv(train_path)
test_url=r'/content/gdrive/MyDrive/Datasets/SurveyData/DATASET/German/Test'
test_path= os.path.join(test_url ,("... | _____no_output_____ | MIT | Fairness_Survey/ALGORITHMS/BaseLine/gbm and LogReg/German.ipynb | DEHO-OSCAR-BLESSED/Evaluation-of-Fairness-Algorithms |
This notebook compares the email activities and draft activites of an IETF working group. Import the BigBang modules as needed. These should be in your Python environment if you've installed BigBang correctly. | import bigbang.mailman as mailman
from bigbang.parse import get_date
#from bigbang.functions import *
from bigbang.archive import Archive
from ietfdata.datatracker import * | /home/sb/projects/bigbang-multi/bigbang/config/config.py:8: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
dictionary = yaml.load(stream)
| MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Also, let's import a number of other dependencies we'll use later. | import pandas as pd
import datetime
import matplotlib.pyplot as plt
import numpy as np
import math
import pytz
import pickle
import os | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Load the HRPC Mailing ListNow let's load the email data for analysis. | wg = "httpbisa"
urls = [wg]
archives = [Archive(url,mbox=True) for url in urls]
activities = [arx.get_activity(resolved=False) for arx in archives]
activity = activities[0] | /home/sb/projects/bigbang-multi/bigbang/bigbang/mailman.py:157: UserWarning: No mailing list name found at httpbisa
warnings.warn("No mailing list name found at %s" % url)
| MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Load IETF Draft DataNext, we will use the `ietfdata` tracker to look at the frequency of drafts for this working group. | import glob
path = '../../archives/datatracker/httpbis/draft_metadata.csv' # use your path
draft_df = pd.read_csv(path, index_col=None, header=0, parse_dates=['date']) | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
We will want to use the data of the drafts. Time resolution is too small. | draft_df['date'] = draft_df['date'].dt.date | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Gender score and tendency measuresThis notebook uses the (notably imperfect) method of using first names to guess the gender of each draft author. | from gender_detector import gender_detector as gd
detector = gd.GenderDetector('us')
def gender_score(name):
"""
Takes a full name and returns a score for the guessed
gender.
1 - male
0 - female
.5 - unknown
"""
try:
first_name = name.split(" ")[0]
guess = detector.... | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Gender guesses on mailing list activityNow to use the gender guesser to track the contributions by differently gendered participants over time. | from bigbang.parse import clean_name
gender_activity = activity.groupby(
by=lambda x: gender_score(clean_name(x)),
axis=1).sum().rename({0.0 : "women", 0.5 : "unknown", 1.0 : "men"},
axis="columns") | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Note that our gender scoring method currently is unable to get a clear guess for a large percentage of the emails! | print("%f.2 percent of emails are from an unknown gender." \
% (gender_activity["unknown"].sum() / gender_activity.sum().sum()))
plt.bar(["women","unknown","men"],gender_activity.sum())
plt.title("Total emails sent by guessed gender") | 0.394629.2 percent of emails are from an unknown gender.
| MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
PlottingSome preprocessing is necessary to get the drafts data ready for plotting. | from matplotlib import cm
viridis = cm.get_cmap('viridis')
drafts_per_day = draft_df.groupby('date').count()['title']
dpd_log = drafts_per_day.apply(lambda x: np.log1p(x)) | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
For each of the mailing lists we are looking at, plot the rolling average (over `window`) of number of emails sent per day.Then plot a vertical line with the height of the drafts count and colored by the gender tendency. | window = 100
plt.figure(figsize=(12, 6))
for i, gender in enumerate(gender_activity.columns):
colors = [viridis(0), viridis(.5), viridis(.99)]
ta = gender_activity[gender]
rmta = ta.rolling(window).mean()
rmtadna = rmta.dropna()
plt.plot_date(np.array(rmtadna.index),
np.array(rm... | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Is gender diversity correlated with draft output? | from scipy.stats import pearsonr
import pandas as pd
def calculate_pvalues(df):
df = df.dropna()._get_numeric_data()
dfcols = pd.DataFrame(columns=df.columns)
pvalues = dfcols.transpose().join(dfcols, how='outer')
for r in df.columns:
for c in df.columns:
pvalues[r][c] = round(pears... | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Some variations... | garm_dna = garm.dropna(subset=['drafts']) | _____no_output_____ | MIT | examples/experimental_notebooks/Working Group Emails and Drafts-httpbis.ipynb | Christovis/bigbang |
Visualize 3D Points (Parabolic data)This notebook uses 3D plots to visualize 3D points. Reads measurement data from a csv file. | %matplotlib notebook
##%matplotlib inline
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
import numpy as np
from filter.kalman import Kalman3D
fmt = lambda x: "%9.3f" % x
np.set_printoptions(formatter={'float_kind':fmt})
## Read from csv file
import pandas as pd
| _____no_output_____ | MIT | src_yolov5/kalman_utils/.ipynb_checkpoints/visualize_3d_points-ball3-checkpoint.ipynb | diddytpq/Tennisball-Tracking-in-Video |
Read and Prepare DataRead ball tracking position data from saved CSV file and prepare mx,my,mz. The file should have dT values along with X,Y,Z values.We use these as measurements and use Kalman3D tracker to track the ball. Once we exhaust all measurements, we use Kalman3D to predict rest of the trajectory.*Note*: The... | # File containing 3D points predicted and measured. Last column with time passage will be ignored
SYNTH = False
if SYNTH:
data_ = pd.read_csv('data/datafile_parabolic.csv') ## Synthetic data
else:
data_ = pd.read_csv('data/input_positions_3.csv') ## Real data
print(data_.keys())
data = data_/1000.
_mx = np.f... | _____no_output_____ | MIT | src_yolov5/kalman_utils/.ipynb_checkpoints/visualize_3d_points-ball3-checkpoint.ipynb | diddytpq/Tennisball-Tracking-in-Video |
Track and PredictNow we use our Kalman3D tracker to track the position of the ball based on measured data and then predict the trajectory when all measurement data is exhausted. | fps = 100.
dT = (1 / fps)
print("dT: {:f}".format(dT))
KF = Kalman3D(drg=1.0, dbg=0)
pred = KF.init(getpos(0,mx,my,mz))
print("pred: {}".format(pred))
##-#######################################################################################
## Tracking
## Since we are doing all operations in zero time, specify dT man... | _____no_output_____ | MIT | src_yolov5/kalman_utils/.ipynb_checkpoints/visualize_3d_points-ball3-checkpoint.ipynb | diddytpq/Tennisball-Tracking-in-Video |
Visualize (X,Y,Z) of Predicted and Measured in Points in 3DIn the plot below, we visualize all the predicted and measured points in 3D. This gives a more realistic view of how the predicted points are related to the measured points. | fig2 = plt.figure()
ax = plt.axes(projection='3d')
#ax.set_xlim3d(-2000,2000)
#ax.set_ylim3d(-2000,2000)
#ax.set_zlim3d(-2000,2000)
if 0: ## Plot axis or not
st = [0,0,0]
xx = [200, 0, 0]
yy = [ 0, 200, 0]
zz =[ 0, 0, 200]
for i in range(len(st)):
ax.plot([st[i], xx[i]], [st[i],y... | _____no_output_____ | MIT | src_yolov5/kalman_utils/.ipynb_checkpoints/visualize_3d_points-ball3-checkpoint.ipynb | diddytpq/Tennisball-Tracking-in-Video |
Chapter4: 実践的なアプリケーションを作ってみよう 4.1 アプリケーションランチャーを作ってみよう① 4.1.1 設定ファイルの保存・呼出し | # リスト4.1.1: 設定ファイルの生成
# configparserのインポート
import configparser
# インスタンス化
config = configparser.ConfigParser()
# 設定ファイルの内容
config["Run1"] = {
"app1": r"C:\WINDOWS\system32\notepad.exe",
"app2": r"C:\Program Files\Internet Explorer\iexplore.exe"
}
# 設定ファイルへ書込み
with open("config.ini", "w+") as file:
config.wr... | _____no_output_____ | MIT | Chapter_4/Chapter_4-1.ipynb | YutaIzumi/python-app-book |
※ Macの場合 | ##### Macの場合 #####
# リスト4.1.1: 設定ファイルの生成
# configparserのインポート
import configparser
# インスタンス化
config = configparser.ConfigParser()
# 設定ファイルの内容
config["Run1"] = {
"app1": "/Applications/TextEdit.app",
"app2": "/Applications/Safari.app"
}
# 設定ファイルへ書込み
with open("config.ini", "w+") as file:
config.write(file)
... | /Applications/Safari.app
| MIT | Chapter_4/Chapter_4-1.ipynb | YutaIzumi/python-app-book |
Fastpages Notebook Blog Post> A tutorial of fastpages for Jupyter notebooks.- toc: true - badges: true- comments: true- categories: [jupyter]- image: images/chart-preview.png AboutThis notebook is a demonstration of some of capabilities of [fastpages](https://github.com/fastai/fastpages) with notebooks.With `fastpage... | #hide_input
print('The comment #hide_input was used to hide the code that produced this.\n') | The comment #hide_input was used to hide the code that produced this.
| Apache-2.0 | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog |
put a `collapse-hide` flag at the top of any cell if you want to **hide** that cell by default, but give the reader the option to show it: | #collapse-hide
import pandas as pd
import altair as alt | _____no_output_____ | Apache-2.0 | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog |
put a `collapse-show` flag at the top of any cell if you want to **show** that cell by default, but give the reader the option to hide it: | #collapse-show
cars = 'https://vega.github.io/vega-datasets/data/cars.json'
movies = 'https://vega.github.io/vega-datasets/data/movies.json'
sp500 = 'https://vega.github.io/vega-datasets/data/sp500.csv'
stocks = 'https://vega.github.io/vega-datasets/data/stocks.csv'
flights = 'https://vega.github.io/vega-datasets/data/... | _____no_output_____ | Apache-2.0 | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog |
Interactive Charts With AltairCharts made with Altair remain interactive. Example charts taken from [this repo](https://github.com/uwdata/visualization-curriculum), specifically [this notebook](https://github.com/uwdata/visualization-curriculum/blob/master/altair_interaction.ipynb). | # hide
df = pd.read_json(movies) # load movies data
genres = df['Major_Genre'].unique() # get unique field values
genres = list(filter(lambda d: d is not None, genres)) # filter out None values
genres.sort() # sort alphabetically
#hide
mpaa = ['G', 'PG', 'PG-13', 'R', 'NC-17', 'Not Rated'] | _____no_output_____ | Apache-2.0 | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog |
Example 1: DropDown | # single-value selection over [Major_Genre, MPAA_Rating] pairs
# use specific hard-wired values as the initial selected values
selection = alt.selection_single(
name='Select',
fields=['Major_Genre', 'MPAA_Rating'],
init={'Major_Genre': 'Drama', 'MPAA_Rating': 'R'},
bind={'Major_Genre': alt.binding_selec... | _____no_output_____ | Apache-2.0 | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog |
Example 2: Tooltips | alt.Chart(movies).mark_circle().add_selection(
alt.selection_interval(bind='scales', encodings=['x'])
).encode(
x='Rotten_Tomatoes_Rating:Q',
y=alt.Y('IMDB_Rating:Q', axis=alt.Axis(minExtent=30)), # use min extent to stabilize axis title placement
tooltip=['Title:N', 'Release_Date:N', 'IMDB_Rating:Q', '... | _____no_output_____ | Apache-2.0 | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog |
Example 3: More Tooltips | # select a point for which to provide details-on-demand
label = alt.selection_single(
encodings=['x'], # limit selection to x-axis value
on='mouseover', # select on mouseover events
nearest=True, # select data point nearest the cursor
empty='none' # empty selection includes no data points
)
# d... | _____no_output_____ | Apache-2.0 | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog |
Data TablesYou can display tables per the usual way in your blog: | movies = 'https://vega.github.io/vega-datasets/data/movies.json'
df = pd.read_json(movies)
# display table with pandas
df[['Title', 'Worldwide_Gross',
'Production_Budget', 'IMDB_Rating']].head() | _____no_output_____ | Apache-2.0 | _notebooks/2020-02-20-test.ipynb | mudit1729/Blog |
Coupling to Ideal LoadsIn this notebook, we investigate the WEST ICRH antenna behaviour when the front-face is considered as the combination of ideal (and independant) loads made of impedances all equal to $Z_s=R_c+j X_s$, where $R_c$ corresponds to the coupling resistance and $X_s$ is the strap reactance. In such ca... | %matplotlib widget
import matplotlib.pyplot as plt
import numpy as np
import skrf as rf
from tqdm.notebook import tqdm
# WEST ICRH Antenna package
import sys; sys.path.append('..')
from west_ic_antenna import WestIcrhAntenna
# styling the figures
rf.stylely() | C:\Users\JH218595\Documents\scikit-rf\skrf\plotting.py:1441: UserWarning: Style includes a parameter, 'interactive', that is not related to style. Ignoring
mpl.style.use(os.path.join(pwd, style_file))
| MIT | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna |
Coupling to an ideal front-faceCoupling to an ideal front face of coupling resistance $R_c$ is easy using the the `.load()` method of the `WestIcrhAntenna` class. This method takes into account the strap reactance frequency fit (derived in [Strap Reactance Frequency Fit](./strap_reactance.ipynb)) | freq = rf.Frequency(30, 70, npoints=1001, unit='MHz')
ant_ideal = WestIcrhAntenna(frequency=freq)
ant_ideal.load(Rc=1) # 1 Ohm coupling resistance front-face
# matching left and right sides : note that the solutions are (almost) the same
f_match = 55.5e6
C_left = ant_ideal.match_one_side(f_match=f_match, side='left')
C... | True solution #1: [53.56567365 45.98820709]
True solution #1: [53.56564882 45.98822849]
| MIT | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna |
At the difference of the "real" situation (see the [Matching](./matching.ipynb) or the [Coupling to a TOPICA plasma](./coupling_to_plasma_from_TOPICA.ipynb)), here is no poloidal neither toroidal coupling of the straps in this front-face model. This leads to:* Match soluitions are the same for both sides (within $10^{-... | # dipole excitation
power = [1, 1]
phase = [0, rf.pi]
# active S-parameter for the match point:
C_match = [C_left[0], C_left[1], C_right[2], C_right[3]]
s_act = ant_ideal.s_act(power, phase, Cs=C_match)
fig, ax = plt.subplots()
ax.plot(ant_ideal.f_scaled, 20*np.log10(np.abs(s_act)), lw=2)
ax.legend(('$S_{act,1}$', '$... | _____no_output_____ | MIT | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna |
Match Points vs Coupling Resistance Let's determine the match points for a range of coupling resistance at a given frequency | f_match = 55e6
Rcs = np.r_[0.01, 0.05, np.arange(0.1, 2.5, 0.2)]
C_matchs = []
ant = WestIcrhAntenna()
for Rc in tqdm(Rcs):
ant.load(Rc)
C_match = ant.match_one_side(f_match=f_match)
C_matchs.append(C_match)
| _____no_output_____ | MIT | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna |
As the coupling resistance increases, the distance between capacitances (Top vs Bottom) increases: | fig, ax = plt.subplots()
ax.plot(Rcs, np.array(C_matchs)[:,0:2], lw=2, marker='o')
ax.axhline(C_matchs[0][0], ls='--', color='C0')
ax.axhline(C_matchs[0][1], ls='--', color='C1')
ax.set_xlabel('Rc [Ohm]')
ax.set_ylabel('C [pF]')
ax.legend(('Top', 'Bot')) | _____no_output_____ | MIT | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna |
Displayed differently, the distance between capacitances (Top - Bottom) versus coupling resistance is: | delta_C_pos = np.array(C_matchs)[:,0] - C_matchs[0][0]
delta_C_neg = C_matchs[0][1] - np.array(C_matchs)[:,1]
fig, ax = plt.subplots()
ax.plot(Rcs, delta_C_pos, label='Top: + $\Delta C$', lw=2)
ax.plot(Rcs, delta_C_neg, label='Bot: - $\Delta C$', lw=2)
ax.set_xlabel('Rc [Ohm]')
ax.set_ylabel('$\Delta C$ [pF]')
ax.se... | _____no_output_____ | MIT | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna |
Load Resilience CurvesIdeal loads is usefull to study the behaviour of the load tolerance property of the antenna and the capacitance match points. It is only necessary to work on half-antenna here, because there is no coupling between toroidal elements. Now that we have figured out the match points, let's vary the c... | # create a single frequency point antenna to speed-up calculations
ant = WestIcrhAntenna(frequency=rf.Frequency.from_f(f_match, unit='Hz'))
fig, ax = plt.subplots()
power = [1, 1]
phase = [0, np.pi]
for C_match in tqdm(C_matchs[0:8]):
SWRs = []
ant.Cs = [C_match[0], C_match[1], 150, 150]
for Rc in Rcs:
... | _____no_output_____ | MIT | doc/coupling_to_ideal_load.ipynb | jhillairet/WEST_IC_antenna |
数组基础 创建一个数组 | import numpy as np
import pdir
pdir(np)
import numpy as np
a1 = np.array([0, 1, 2, 3, 4])#将列表转换为数组,可以传递任何序列(类数组),而不仅仅是常见的列表(list)数据类型。
a2 = np.array((0, 1, 2, 3, 4))#将元组转换为数组
print 'a1:',a1,type(a1)
print 'a2:',a2,type(a2)
b = np.arange(5) #python内置函数range()的数组版,返回的是numpy ndarrays数组对象,而不是列表
print 'b:',b,type(b)
c1 = np... | g [ 0. 2.5 5. 7.5 10. ] <type 'numpy.ndarray'>
| Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
数组属性 | a = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28 ,29, 30],
[31, 32, 33, 34, 35]])
print(type(a)) #<type 'numpy.ndarray'>
print(a.dtype) #int32
print(a.size) #25 Return the number of elements along a given axis.
print(a.sh... | <type 'numpy.ndarray'>
int32
25
(5L, 5L)
4
2
| Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
使用数组数组可不必编写循环即可实现循环-数组的矢量化大小相等的数组之间的任何数学运算都会应用到元素级大小不相等的数组之间的运算-叫做广播 基本操作符-数组四则运算 +、- 、/ | a = np.arange(25)
print 'a:',a,type(a)
a = a.reshape((5, 5))#Gives a new shape to an array without changing its data
print 'a:',a,type(a)
b = np.array([10, 62, 1, 14, 2, 56, 79, 2, 1, 45,
4, 92, 5, 55, 63, 43, 35, 6, 53, 24,
56, 3, 56, 44, 78])
print b.shape
b = b.reshape((5,5))
print 'b:',... | [[ 417 380 254 446 555]
[1262 1735 604 1281 1615]
[2107 3090 954 2116 2675]
[2952 4445 1304 2951 3735]
[3797 5800 1654 3786 4795]]
| Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
数组特殊运算符 | # sum, min, max, cumsum
a = np.arange(10)
print 'a:',a
print(a.sum()) # >>>45
print(a.min()) # >>>0
print(a.max()) # >>>9
print(a.cumsum()) # >>>[ 0 1 3 6 10 15 21 28 36 45] | a: [0 1 2 3 4 5 6 7 8 9]
45
0
9
[ 0 1 3 6 10 15 21 28 36 45]
| Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
索引 基本索引-整数索引 | a = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28 ,29, 30],
[31, 32, 33, 34, 35]])
print 'a:',a,type(a)
# 访问元素:二者功能相同
print a[1][3]
print a[1,3]#逗号隔开的索引列表来选取单个元素
# 多维数组中,如果省略了后面的索引,则返回对象是一个维度低一点的数组。
print a[2] | a: [[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]] <type 'numpy.ndarray'>
19
19
[21 22 23 24 25]
| Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
数组切片数组切片与列表切片重要区别在于。数组切片是原数组的视图,这意味着数据不会被复制,视图上的任何修改都会直接反映到源数组上 | a = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28 ,29, 30],
[31, 32, 33, 34, 35]])
print 'a:',a
# 单纯切片只能得到相同维度的数组视图,
print(a[::2,::2])
# [[11 13 15]
# [21 23 25]
# [31 33 35]]
print(a[:3,:2])
#切片和整数索引混合使用,可以得到低维度的切片
print(... | a_slice_copy: [66 66 66 66 66]
a_slice_copy: [111 111 111 111 111]
a: [[66 12 13 14 15]
[66 17 18 19 20]
[66 22 23 24 25]
[66 27 28 29 30]
[66 32 33 34 35]]
| Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
布尔型索引布尔型数组可用于数组索引,通过布尔型数组获取到数组中的数据,将总是创建副本==,!=,>,< | #数组的比较运算也是矢量化的,会产生一个布尔型数组
names = np.array(['bob','joe','will','bob','will','joe','joe'])
names.shape
names == 'bob'
data = np.random.randn(7,4)
data
#布尔型数组可用于数组索引,布尔型数组的长度必须跟被索引的轴长度一致,
#例如names == 'bob'长度为7;data按行索引
#names2 == 'bob'长度为4;data按列索引
print data[names == 'bob']
names2 = names[:4].copy()
print(names2)
print... | [[ 0.29218127 200. 200. 7. ]
[ 100. 200. 200. 100. ]
[ 100. 200. 200. 100. ]
[ 0.53516408 200. 200. 0.88596045]
[ 100. 200. 200. 100. ]
[ 100. 200. ... | Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
花式索引花式索引是指利用整数数组进行索引,可以指定顺序选取、花式索引不同于切片,花式索引总是将数据复制到新数组中 | arr = np.empty((8,4))
for i in range(8):
arr[i] = i
print arr
#可以指定顺序选取行子集,只需传入一个用于指定顺序的整数列表或数组即可
print arr[[4,3,0,6]]
#使用负数索引将从末尾开始选取行
print arr[[-1,-2]]
#可以同时使用正数和负数进行花式索引
print arr[[1,2,-1,-2]]
#使用多个索引数组,返回的是一个一维数组
arr = np.arange(32).reshape(8,4)
print arr
print arr[[4,3,0,6],[1,2,3,0]]
#获取的元素是(4,1)(3,2)(0,3)(6... | [[17 18 19 16]
[13 14 15 12]
[ 1 2 3 0]
[25 26 27 24]]
[[17 18 19 16]
[13 14 15 12]
[ 1 2 3 0]
[25 26 27 24]]
| Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
数组转置和轴对换 | # 转置(transpose)返回源数据的视图(不会进行任何复制操作),
# 两种办法实现转置:
# arr.transpose()方法
# arr.T属性
arr = np.arange(15).reshape(3,5)
print arr
print arr.T
print arr.transpose()
#高维数组(>=3维)需要参数:轴编号组成的元组才能对轴进行转置
arr = np.arange(16).reshape(2,2,4)
print arr
print arr.T
print arr.transpose((1,0,2)) | [[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
[[ 0 5 10]
[ 1 6 11]
[ 2 7 12]
[ 3 8 13]
[ 4 9 14]]
[[ 0 5 10]
[ 1 6 11]
[ 2 7 12]
[ 3 8 13]
[ 4 9 14]]
[[[ 0 1 2 3]
[ 4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]]
[[[ 0 8]
[ 4 12]]
[[ 1 9]
[ 5 13]]
[[ 2 10]
[ 6 14]]
[[ 3 11]... | Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
通用函数-快速的元素级数组函数对数组中数据进行元素级运算的函数 | #一元通用函数,接收一个数组
arr = np.arange(10)
print arr
print np.sqrt(arr)#开方
print np.exp(arr)#指数
print np.square(arr)#平方
#二元通用函数,接收2个数组
x = np.random.randn(5)
print x
y = np.random.randn(5)
print y
print np.add(x,y)#加法
print np.subtract(x,y)#减法
print np.greater(x,y)#元素比较 | _____no_output_____ | Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
将条件逻辑表述为数组运算numpy.where()函数是三元表达式 x if condition else y的矢量化版本 | xarr = np.array([1.1,1.2,1.3,1.4,1.5])
yarr = np.array([2.1,2.2,2.3,2.4,2.5])
condition = np.array([True,False,True,True,False])
# 列表生成式
print [(x if c else y)for x,y,c in zip(xarr,yarr,condition)]
#存在问题
#速度不是很快,原因:纯python实现
#无法用于多维数组
#利用np.where()实现相同功能很简洁
print np.where(condition,xarr,yarr)
#np.where()函数,第2,3参数不一定为数组... | [ 1.1 2.2 1.3 1.4 2.5]
[[ 1.45968931 0.04416752 0.17823822 -0.39762311]
[ 1.1620933 0.59377557 -0.23737767 -1.43722256]
[ 1.03619541 -0.64949799 0.15402381 -0.11071381]
[ 1.29405992 -0.02742662 0.43881736 1.73837499]]
[[ 1 1 1 -1]
[ 1 1 -1 -1]
[ 1 -1 1 -1]
[ 1 -1 1 1]]
[[ 1. 1. ... | Apache-2.0 | numpy/2-numpy-middle.ipynb | GmZhang3/data-science-ipython-notebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.