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
Network EnergeticsNetwork Energetics, which includes Network Thermodynamics partitions $S + B = P$ into _components_.1. Energy Storage Compartments: $C: S$, $C: B$ and $C: P$.2. Dissipative Processes: $R: r_{1;0}$3. Conservation Laws: $1$ (common flow).*Bond Graphs represent of energy networks.*
#from BondGraphTools.reaction_builder # import Reaction_Network reaction = Reaction_Network( "S + B = P", name="One Step Reaction" ) model = reaction.as_network_model() # Basic Visualisation. from BondGraphTools import draw figure = draw(model, size=(8,6)) # Initialise latex printing from sympy import init_prin...
_____no_output_____
CC-BY-4.0
ANZIAM-2019/ANZIAM Slides.ipynb
peter-cudmore/seminars
A peak under the hoodIn `BondGraphTools`, components have a number of power ports defined such that the power $P_i$ entering the $i$th port is $P_i = e_if_i$The power vaiables $(e,f)$ are related to the component state variables $(x, \mathrm{d}x)$ by _constitutive relations_.
from BondGraphTools import new chemical_potential = new("Ce", library="BioChem") chemical_potential.constitutive_relations figure
_____no_output_____
CC-BY-4.0
ANZIAM-2019/ANZIAM Slides.ipynb
peter-cudmore/seminars
A peak under the hood (cont.) The harpoons represent _shared power variables_.For example the harpoon from port 1 on $R: r_{1;0}$ to $C:P$ indiciates that$$f^{C:P}_0 = - f^{R:r_{1;0}}_1 \qquad e^{C:P}_0 = e^{R:r_{1;0}}_1 $$ so that power is conserved through the connection $$P^{C:P}_0 + P^{R:r_{1;0}}_1 = 0$...
figure
_____no_output_____
CC-BY-4.0
ANZIAM-2019/ANZIAM Slides.ipynb
peter-cudmore/seminars
Naive-Bayes Classifier
#Baseline SVM with PCA classifier import sklearn import numpy as np import sklearn.datasets as skd import ast from sklearn.feature_extraction import DictVectorizer from sklearn import linear_model from sklearn import naive_bayes from sklearn.metrics import precision_recall_fscore_support from sklearn.neighbors.nearest_...
_____no_output_____
MIT
nb_mlcy7.ipynb
vvb231/VinayProject
A Whale off the Port(folio) --- In this assignment, you'll get to use what you've learned this week to evaluate the performance among various algorithmic, hedge, and mutual fund portfolios and compare them against the S&P 500 Index.
# Initial imports import pandas as pd import numpy as np import datetime as dt from pathlib import Path %matplotlib inline
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Data CleaningIn this section, you will need to read the CSV files into DataFrames and perform any necessary data cleaning steps. After cleaning, combine all DataFrames into a single DataFrame.Files:* `whale_returns.csv`: Contains returns of some famous "whale" investors' portfolios.* `algo_returns.csv`: Contains retur...
# Reading whale returns # Count nulls # Drop nulls
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Algorithmic Daily ReturnsRead the algorithmic daily returns and clean the data
# Reading algorithmic returns # Count nulls # Drop nulls
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
S&P 500 ReturnsRead the S&P 500 historic closing prices and create a new daily returns DataFrame from the data.
# Reading S&P 500 Closing Prices # Check Data Types # Fix Data Types # Calculate Daily Returns # Drop nulls # Rename `Close` Column to be specific to this portfolio.
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Combine Whale, Algorithmic, and S&P 500 Returns
# Join Whale Returns, Algorithmic Returns, and the S&P 500 Returns into a single DataFrame with columns for each portfolio's returns.
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
--- Conduct Quantitative AnalysisIn this section, you will calculate and visualize performance and risk metrics for the portfolios. Performance Anlysis Calculate and Plot the daily returns.
# Plot daily returns of all portfolios
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate and Plot cumulative returns.
# Calculate cumulative returns of all portfolios # Plot cumulative returns
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
--- Risk AnalysisDetermine the _risk_ of each portfolio:1. Create a box plot for each portfolio. 2. Calculate the standard deviation for all portfolios4. Determine which portfolios are riskier than the S&P 5005. Calculate the Annualized Standard Deviation Create a box plot for each portfolio
# Box plot to visually show risk
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate Standard Deviations
# Calculate the daily standard deviations of all portfolios
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Determine which portfolios are riskier than the S&P 500
# Calculate the daily standard deviation of S&P 500 # Determine which portfolios are riskier than the S&P 500
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate the Annualized Standard Deviation
# Calculate the annualized standard deviation (252 trading days)
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
--- Rolling StatisticsRisk changes over time. Analyze the rolling statistics for Risk and Beta. 1. Calculate and plot the rolling standard deviation for all portfolios using a 21-day window2. Calculate the correlation between each stock to determine which portfolios may mimick the S&P 5003. Choose one portfolio, then ...
# Calculate the rolling standard deviation for all portfolios using a 21-day window # Plot the rolling standard deviation
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate and plot the correlation
# Calculate the correlation # Display de correlation matrix
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate and Plot Beta for a chosen portfolio and the S&P 500
# Calculate covariance of a single portfolio # Calculate variance of S&P 500 # Computing beta # Plot beta trend
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Rolling Statistics Challenge: Exponentially Weighted Average An alternative way to calculate a rolling window is to take the exponentially weighted moving average. This is like a moving window average, but it assigns greater importance to more recent observations. Try calculating the [`ewm`](https://pandas.pydata.org/...
# Use `ewm` to calculate the rolling window
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
--- Sharpe RatiosIn reality, investment managers and thier institutional investors look at the ratio of return-to-risk, and not just returns alone. After all, if you could invest in one of two portfolios, and each offered the same 10% return, yet one offered lower risk, you'd take that one, right? Using the daily retu...
# Annualized Sharpe Ratios # Visualize the sharpe ratios as a bar plot
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Determine whether the algorithmic strategies outperform both the market (S&P 500) and the whales portfolios.Write your answer here! --- Create Custom PortfolioIn this section, you will build your own portfolio of stocks, calculate the returns, and compare the results to the Whale Portfolios and the S&P 500. 1. Choose...
# Reading data from 1st stock # Reading data from 2nd stock # Reading data from 3rd stock # Combine all stocks in a single DataFrame # Reset Date index # Reorganize portfolio data by having a column per symbol # Calculate daily returns # Drop NAs # Display sample data
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate the weighted returns for the portfolio assuming an equal number of shares for each stock
# Set weights weights = [1/3, 1/3, 1/3] # Calculate portfolio return # Display sample data
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Join your portfolio returns to the DataFrame that contains all of the portfolio returns
# Join your returns DataFrame to the original returns DataFrame # Only compare dates where return data exists for all the stocks (drop NaNs)
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Re-run the risk analysis with your portfolio to see how it compares to the others Calculate the Annualized Standard Deviation
# Calculate the annualized `std`
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate and plot rolling `std` with 21-day window
# Calculate rolling standard deviation # Plot rolling standard deviation
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate and plot the correlation
# Calculate and plot the correlation
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Calculate and Plot Rolling 60-day Beta for Your Portfolio compared to the S&P 500
# Calculate and plot Beta
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Using the daily returns, calculate and visualize the Sharpe ratios using a bar plot
# Calculate Annualzied Sharpe Ratios # Visualize the sharpe ratios as a bar plot
_____no_output_____
ADSL
.ipynb_checkpoints/whale_analysis-checkpoint.ipynb
globalproweb/Unit-4-Homework
Germany: SK Mülheim a.d.Ruhr (Nordrhein-Westfalen)* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Nordrhein-Westfalen-SK-Mülheim-a.d.Ru...
import datetime import time start = datetime.datetime.now() print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}") %config InlineBackend.figure_formats = ['svg'] from oscovida import * overview(country="Germany", subregion="SK Mülheim a.d.Ruhr", weeks=5); overview(country=...
_____no_output_____
CC-BY-4.0
ipynb/Germany-Nordrhein-Westfalen-SK-Mülheim-a.d.Ruhr.ipynb
oscovida/oscovida.github.io
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Nordrhein-Westfalen-SK-Mülheim-a.d.Ruhr.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See ht...
print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and " f"deaths at {fetch_deaths_last_execution()}.") # to force a fresh download of data, run "clear_cache()" print(f"Notebook execution took: {datetime.datetime.now()-start}")
_____no_output_____
CC-BY-4.0
ipynb/Germany-Nordrhein-Westfalen-SK-Mülheim-a.d.Ruhr.ipynb
oscovida/oscovida.github.io
1. Carregar imagemNas próximas seções, iremos aprender como carregar imagens de duas fontes distintas para exibí-las através de nosso código: (a) Internet e (b) diretório de seu próprio google drive. Também, veremos qual vantagem cada uma das formas de aquisição. 1.1 URLsA vantagem de carregarmos imagens diretamente...
#Importação das bibliotecas que iremos utilizar import cv2 import numpy as np import urllib import matplotlib.pyplot as plt I = url_to_image("https://live.staticflickr.com/65535/48055207731_98367225e3_m.jpg") # se conseguiu carregar a imagem if(I is not None): # exibe a imagem plt.show() def url_to_image(url): ...
_____no_output_____
MIT
aula_utils.ipynb
thalesvalente/machinelearning
1.1.2 Pil.Image + comandos Linux
import PIL.Image def show_results(content_path, max_dim): #plt.figure(figsize=(10, 5)) content = img = PIL.Image.open(content_path) long = max(img.size) scale = max_dim/long img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), PIL.Image.ANTIALIAS) #plt.subplot(1, 2, 1) plt.imshow(img) ...
_____no_output_____
MIT
aula_utils.ipynb
thalesvalente/machinelearning
1.2 Arquivos no gdriveA vantagem de carregarmos imagens diretamente do gdrive pessoal é que não precisamos nos preocupar com o fato da página estar acessível ou não. No entanto, é necessário seguir os seguintes passos: - executar o código - clicar no *link* que aparecer- dar autorização- copiar o código gerado e- co...
from google.colab import drive drive.mount('/content/gdrive')
_____no_output_____
MIT
aula_utils.ipynb
thalesvalente/machinelearning
1.2.1 Usando OpenCV + Matplotlib
import cv2 import matplotlib.pyplot as plt # carrega a imagem bgr_img = cv2.imread('/content/gdrive/My Drive/Colab Notebooks/docencia/MLP/figuras/decisao_linear.png') plt.axis("off") # adiciona a imagem no plot e exibe plt.imshow(cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)) plt.show()
_____no_output_____
MIT
aula_utils.ipynb
thalesvalente/machinelearning
1.2.2 Usando Ipython.display
from IPython.display import Image # carrega, adiciona no display e exibe Image(filename="/content/gdrive/My Drive/Colab Notebooks/docencia/MLP/figuras/decisao_linear.png") %matplotlib notebook import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc from IPython.display import HTML ...
_____no_output_____
MIT
aula_utils.ipynb
thalesvalente/machinelearning
2. MatplotlibEssa seção fornece algumas dicas básicas para utilização da biblioteca matplotlib, principal biblioteca utilizada para exibição de imagens e gráficos no python
# Testei ams não funcionou. Não apareceu UI !jupyter nbextension install https://bitbucket.org/ipre/calico/downloads/calico-document-tools-1.0.zip !jupyter nbextension enable calico-document-tools #%matplotlib inline #from IPython.core.magics.display import Javascript #Javascript(""""load_extensions": {"calico-spell-c...
Reading package lists... Done Building dependency tree Reading state information... Done The following package was automatically installed and is no longer required: libnvidia-common-410 Use 'sudo apt autoremove' to remove it. The following additional packages will be installed: fonts-droid-fallback fonts-la...
MIT
aula_utils.ipynb
thalesvalente/machinelearning
AAAAAAAAAAAAAA (Granger, 2013) You can use Markdown to add images to Jupyter Notebook files, such as this image of the Markdown logo. Source: Full Stack Python. @article{PER-GRA:2007, Author = {P\'erez, Fernando and Granger, Brian E.}, Title = {{IP}ython: a System for Interactive Scientific Co...
# nbconvert funcionou. No entanto, os outros comandos não %%bash ls jupyter nbconvert aula_utils.ipynb --to latex #python latex aula_utils.tex #!python bibtex aula_utils.aux #!python pdflatex aula_utils.tex #!python pdflatex aula_utils.tex pdflatex aula_utils.tex %%bash # mudar para o diretório onde está o notebook que...
Installing nbextension ... Enabling the nbextension ... Enabling the server extension ... Done.
MIT
aula_utils.ipynb
thalesvalente/machinelearning
<!--bibtex@Article{PER-GRA:2007, Author = {P\'erez, Fernando and Granger, Brian E.}, Title = {{IP}ython: a System for Interactive Scientific Computing}, Journal = {Computing in Science and Engineering}, Volume = {9}, Number = {3}, Pages = {21--29}, month = may, year = 2007, url ...
# NÃO FINCIONOU - não carrega o arquivo com o comando load # - o colab abre arquivos somente como leitura. Não dá para editar # - tentei gambi para editar o conf.py, deu # - tentei gambi para jogar o notebook na pasta source do projeto sphinx e encontrei 2 problemas: # - 1: tudo copiado para a pasta Files é deletado qu...
_____no_output_____
MIT
aula_utils.ipynb
thalesvalente/machinelearning
See :cite:`1987:nelson` for an introduction to non-standard analysis... bibliography:: refs.bib :cited: Here is a link :func:`time.time`. .,,. ,;;*;;;;, .-'``;-');;. /' .-. /*;; .' \d \;; .;;;,/ o ` \; ,__. ,;*;;;*;,\__, _.__,' \_.-') __)--.;;;;;*;;;;, `"...
%cd source
_____no_output_____
MIT
aula_utils.ipynb
thalesvalente/machinelearning
%load conf.py
%load conf.py # acessar google drive from os.path import join from google.colab import drive ROOT = "/content/drive" drive.mount(ROOT) # criar um diretório para seus projetos PROJ = "My Drive/Colab Experimental/Workspace" # This is a custom path. PROJECT_PATH = join(ROOT, PROJ) !mkdir "{PROJECT_PATH}" # Iniciar o git...
_____no_output_____
MIT
aula_utils.ipynb
thalesvalente/machinelearning
Copyright 2020 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
TensorFlow Addons 画像 : 操作 TensorFlow.orgで表示 Google Colab で実行 GitHub でソースを表示{ ノートブックをダウンロード/a0} 概要このノートブックでは、TensorFlow Addons で画像操作を使用する方法をいくつか紹介します。この例では、以下の画像操作について説明します。- `tfa.image.mean_filter2d`- `tfa.image.rotate`- `tfa.image.transform`- `tfa.image.random_hsv_in_yiq`- `tfa.image.adjust_hsv_in_yiq`- `t...
!pip install -U tensorflow-addons import tensorflow as tf import numpy as np import tensorflow_addons as tfa import matplotlib.pyplot as plt
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
画像を準備して検査する 画像をダウンロードする
img_path = tf.keras.utils.get_file('tensorflow.png','https://tensorflow.org/images/tf_logo.png')
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
画像を検査する TensorFlow のアイコン
img_raw = tf.io.read_file(img_path) img = tf.io.decode_image(img_raw) img = tf.image.convert_image_dtype(img, tf.float32) img = tf.image.resize(img, [500,500]) plt.title("TensorFlow Logo with shape {}".format(img.shape)) _ = plt.imshow(img)
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
白黒バージョンを作成する
bw_img = 1.0 - tf.image.rgb_to_grayscale(img) plt.title("Mask image with shape {}".format(bw_img.shape)) _ = plt.imshow(bw_img[...,0], cmap='gray')
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
tfa.image を使って遊ぶ 平均フィルタリング平均フィルタリングはフィルタリング技術の 1 つで、画像や信号のノイズ除去によく使用されます。この考え方は、画像をピクセル単位で処理し、隣接するピクセルの平均値で置き換えるというものです。
mean = tfa.image.mean_filter2d(img, filter_shape=11) _ = plt.imshow(mean)
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
回転この操作は、特定の画像をユーザーが入力した角度(ラジアン単位)に回転させます。
rotate = tfa.image.rotate(img, tf.constant(np.pi/8)) _ = plt.imshow(rotate)
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
変換この操作は、特定の画像をユーザーが指定した変換ベクトルに基づいて変換します。
transform = tfa.image.transform(img, [1.0, 1.0, -250, 0.0, 1.0, 0.0, 0.0, 0.0]) _ = plt.imshow(transform)
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
YIQ でランダムに HSV 変換するこの操作は、特定の RGB 画像のカラースケールを YIQ に変更しますが、ここではデルタ色相と彩度の値を指定された範囲からランダムに選択します。
delta = 0.5 lower_saturation = 0.1 upper_saturation = 0.9 lower_value = 0.2 upper_value = 0.8 rand_hsvinyiq = tfa.image.random_hsv_in_yiq(img, delta, lower_saturation, upper_saturation, lower_value, upper_value) _ = plt.imshow(rand_hsvinyiq)
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
YIQ で HSV を調整するこの操作は、特定の RGB 画像のカラースケールを YIQ に変更しますが、ここではランダムに選択するのではなく、デルタ色相と彩度の値はユーザーの入力値です。
delta = 0.5 saturation = 0.3 value = 0.6 adj_hsvinyiq = tfa.image.adjust_hsv_in_yiq(img, delta, saturation, value) _ = plt.imshow(adj_hsvinyiq)
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
高密度画像ワープこの操作は、オフセットベクトルのフローフィールドで指定された任意の画像の非線形ワープを行います(例えば、ここではランダムな値を使用します)。
input_img = tf.image.convert_image_dtype(tf.expand_dims(img, 0), tf.dtypes.float32) flow_shape = [1, input_img.shape[1], input_img.shape[2], 2] init_flows = np.float32(np.random.normal(size=flow_shape) * 2.0) dense_img_warp = tfa.image.dense_image_warp(input_img, init_flows) dense_img_warp = tf.squeeze(dense_img_warp,...
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
ユークリッド距離変換この操作は、前景ピクセルから背景ピクセルまでのピクセル値をユークリッド距離で更新します。- 注意: これは二値化画像のみを受け取り、結果は変換された画像になります。異なる画像を指定した場合は、結果は単一の値の画像になります。
gray = tf.image.convert_image_dtype(bw_img,tf.uint8) # The op expects a batch of images, so add a batch dimension gray = tf.expand_dims(gray, 0) eucid = tfa.image.euclidean_dist_transform(gray) eucid = tf.squeeze(eucid, (0, -1)) _ = plt.imshow(eucid, cmap='gray')
_____no_output_____
Apache-2.0
site/ja/addons/tutorials/image_ops.ipynb
RedContritio/docs-l10n
Logistic Regression with a Neural Network mindsetWelcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning.**I...
import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage from lr_utils import load_dataset %matplotlib inline
_____no_output_____
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
2 - Overview of the Problem set **Problem Statement**: You are given a dataset ("data.h5") containing: - a training set of m_train images labeled as cat (y=1) or non-cat (y=0) - a test set of m_test images labeled as cat or non-cat - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RG...
# Loading the data (cat/non-cat) train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
_____no_output_____
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
We added "_orig" at the end of image datasets (train and test) because we are going to preprocess them. After preprocessing, we will end up with train_set_x and test_set_x (the labels train_set_y and test_set_y don't need any preprocessing).Each line of your train_set_x_orig and test_set_x_orig is an array representing...
# Example of a picture index = 25 plt.imshow(train_set_x_orig[index]) print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") + "' picture.")
y = [1], it's a 'cat' picture.
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
Many software bugs in deep learning come from having matrix/vector dimensions that don't fit. If you can keep your matrix/vector dimensions straight you will go a long way toward eliminating many bugs. **Exercise:** Find the values for: - m_train (number of training examples) - m_test (number of test examples) ...
### START CODE HERE ### (≈ 3 lines of code) m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] ### END CODE HERE ### print ("Number of training examples: m_train = " + str(m_train)) print ("Number of testing examples: m_test = " + str(m_test)) print ("Height/Width ...
Number of training examples: m_train = 209 Number of testing examples: m_test = 50 Height/Width of each image: num_px = 64 Each image is of size: (64, 64, 3) train_set_x shape: (209, 64, 64, 3) train_set_y shape: (1, 209) test_set_x shape: (50, 64, 64, 3) test_set_y shape: (1, 50)
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Expected Output for m_train, m_test and num_px**: **m_train** 209 **m_test** 50 **num_px** 64 For convenience, you should now reshape images of shape (num_px, num_px, 3) in a numpy-array of shape (num_px $*$ num_px $*$ 3, 1). After this, our training (and test) dataset is...
# Reshape the training and test examples ### START CODE HERE ### (≈ 2 lines of code) train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T ### END CODE HERE ### print ("train_set_x_flatten shape: " + str(train_set_x...
train_set_x_flatten shape: (12288, 209) train_set_y shape: (1, 209) test_set_x_flatten shape: (12288, 50) test_set_y shape: (1, 50) sanity check after reshaping: [17 31 56 22 33]
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Expected Output**: **train_set_x_flatten shape** (12288, 209) **train_set_y shape** (1, 209) **test_set_x_flatten shape** (12288, 50) **test_set_y shape** (1, 50) **sanity check after reshaping** [17 31 56 22 33] To represent color images, the red, green and blue c...
train_set_x = train_set_x_flatten/255. test_set_x = test_set_x_flatten/255.
_____no_output_____
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**What you need to remember:**Common steps for pre-processing a new dataset are:- Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...)- Reshape the datasets such that each example is now a vector of size (num_px \* num_px \* 3, 1)- "Standardize" the data 3 - General Architecture of the le...
# GRADED FUNCTION: sigmoid def sigmoid(z): """ Compute the sigmoid of z Arguments: z -- A scalar or numpy array of any size. Return: s -- sigmoid(z) """ ### START CODE HERE ### (≈ 1 line of code) s = 1 / (1 + np.exp(-z)) ### END CODE HERE ### return s print ("sigmoid...
sigmoid([0, 2]) = [ 0.5 0.88079708]
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Expected Output**: **sigmoid([0, 2])** [ 0.5 0.88079708] 4.2 - Initializing parameters**Exercise:** Implement parameter initialization in the cell below. You have to initialize w as a vector of zeros. If you don't know what numpy function to use, look up np.zeros() in the Numpy library's documen...
# GRADED FUNCTION: initialize_with_zeros def initialize_with_zeros(dim): """ This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0. Argument: dim -- size of the w vector we want (or number of parameters in this case) Returns: w -- initialized vector of...
w = [[ 0.] [ 0.]] b = 0
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Expected Output**: ** w ** [[ 0.] [ 0.]] ** b ** 0 For image inputs, w will be of shape (num_px $\times$ num_px $\times$ 3, 1). 4.3 - Forward and Backward propagationNow that your parameters are initialized, you can do the "forward" and "backward" propagation s...
# GRADED FUNCTION: propagate def propagate(w, b, X, Y): """ Implement the cost function and its gradient for the propagation explained above Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) ...
dw = [[ 0.99845601] [ 2.39507239]] db = 0.00145557813678 cost = 5.80154531939
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Expected Output**: ** dw ** [[ 0.99845601] [ 2.39507239]] ** db ** 0.00145557813678 ** cost ** 5.801545319394553 4.4 - Optimization- You have initialized your parameters.- You are also able to compute a cost function and its gradien...
# GRADED FUNCTION: optimize def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of shap...
w = [[ 0.19033591] [ 0.12259159]] b = 1.92535983008 dw = [[ 0.67752042] [ 1.41625495]] db = 0.219194504541
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Expected Output**: **w** [[ 0.19033591] [ 0.12259159]] **b** 1.92535983008 **dw** [[ 0.67752042] [ 1.41625495]] **db** 0.219194504541 **Exercise:** The previous function will output the learned w and b. We are able to ...
# GRADED FUNCTION: predict def predict(w, b, X): ''' Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of example...
predictions = [[ 1. 1. 0.]]
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Expected Output**: **predictions** [[ 1. 1. 0.]] **What to remember:**You've implemented several functions that:- Initialize (w,b)- Optimize the loss iteratively to learn parameters (w,b): - computing the cost and its gradient - updating t...
# GRADED FUNCTION: model def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): """ Builds the logistic regression model by calling the function you've implemented previously Arguments: X_train -- training set represented by a numpy array of sh...
_____no_output_____
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
Run the following cell to train your model.
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
Cost after iteration 0: 0.693147 Cost after iteration 100: 0.584508 Cost after iteration 200: 0.466949 Cost after iteration 300: 0.376007 Cost after iteration 400: 0.331463 Cost after iteration 500: 0.303273 Cost after iteration 600: 0.279880 Cost after iteration 700: 0.260042 Cost after iteration 800: 0.242941 Cost af...
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Expected Output**: **Cost after iteration 0 ** 0.693147 $\vdots$ $\vdots$ **Train Accuracy** 99.04306220095694 % **Test Accuracy** 70.0 % **Comment**: Training accuracy is close to 100%. This is a ...
# Example of a picture that was wrongly classified. index = 1 plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3))) print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0,index]].decode("utf-8") + "\" picture.")
y = 1, you predicted that it is a "cat" picture.
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
Let's also plot the cost function and the gradients.
# Plot learning curve (with costs) costs = np.squeeze(d['costs']) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(d["learning_rate"])) plt.show()
_____no_output_____
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Interpretation**:You can see the cost decreasing. It shows that the parameters are being learned. However, you see that you could train the model even more on the training set. Try to increase the number of iterations in the cell above and rerun the cells. You might see that the training set accuracy goes up, but the...
learning_rates = [0.01, 0.001, 0.0001] models = {} for i in learning_rates: print ("learning rate is: " + str(i)) models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False) print ('\n' + "--------------------------------------------...
learning rate is: 0.01 train accuracy: 99.52153110047847 % test accuracy: 68.0 % ------------------------------------------------------- learning rate is: 0.001 train accuracy: 88.99521531100478 % test accuracy: 64.0 % ------------------------------------------------------- learning rate is: 0.0001
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
**Interpretation**: - Different learning rates give different costs and thus different predictions results.- If the learning rate is too large (0.01), the cost may oscillate up and down. It may even diverge (though in this example, using 0.01 still eventually ends up at a good value for the cost). - A lower cost doesn'...
## START CODE HERE ## (PUT YOUR IMAGE NAME) my_image = "my_image.jpg" # change this to the name of your image file ## END CODE HERE ## # We preprocess the image to fit your algorithm. fname = "images/" + my_image image = np.array(ndimage.imread(fname, flatten=False)) image = image/255. my_image = scipy.misc.imresi...
_____no_output_____
MIT
Neural_Networks_and_Deep_Learning/Week_4/Logistic+Regression+with+a+Neural+Network+mindset+v5.ipynb
anoushkrit/MOOCs
Solar Generation
solar_data = pd.read_csv(dataset_path + 'Solar/data.csv', quotechar='"').fillna(0) solar_data_X = solar_data.drop(columns=['SITE_NO', 'DATE', 'TIME']) solar_data_y = solar_data['GEN_ENERGY'] X_train_full, y_train_full = n_steps_reshape(solar_data_X, solar_data_y, 10) X_train, X_test, y_train, y_test = train_test_split(...
_____no_output_____
Apache-2.0
Regression.ipynb
itouchz/TRepNet
Beijing PM 2.5
beijing_data = pd.read_csv(dataset_path + 'Beijing-PM25.csv').dropna().drop(columns=['No', 'year']).reset_index(drop=True) beijing_data_X = pd.get_dummies(beijing_data, columns=['cbwd']) beijing_data_y = beijing_data['pm2.5'] X_train_full, y_train_full = n_steps_reshape(beijing_data_X, beijing_data_y, 10) X_train, X_t...
_____no_output_____
Apache-2.0
Regression.ipynb
itouchz/TRepNet
Energy Data
energy_data = pd.read_csv(dataset_path + 'energydata_complete.csv') enery_data_X = energy_data.drop(columns=['date']) enery_data_y = energy_data['Appliances'] X_train_full, y_train_full = n_steps_reshape(enery_data_X, enery_data_y, 10, for_rnn=True) X_train_full = get_codings(X_train_full, 10, X_train_full.shape[2]) X_...
_____no_output_____
Apache-2.0
Regression.ipynb
itouchz/TRepNet
Parking Birmingham
parking_data = pd.read_csv(dataset_path + 'Parking Birmingham.csv') parking_data_X = parking_data.drop(columns=['SystemCodeNumber', 'LastUpdated']) parking_data_y = parking_data['Occupancy'] X_train_full, y_train_full = n_steps_reshape(parking_data_X, parking_data_y, 10) X_train, X_test, y_train, y_test = train_test_s...
_____no_output_____
Apache-2.0
Regression.ipynb
itouchz/TRepNet
Daily Demand
demand_data = pd.read_csv(dataset_path + 'Daily_Demand_Forecasting_Orders.csv', sep=';') demand_data_X = demand_data demand_data_y = demand_data['Target'] X_train_full, y_train_full = n_steps_reshape(demand_data_X, demand_data_y, 10) X_train, X_test, y_train, y_test = train_test_split(X_train_full, y_train_full, test_...
_____no_output_____
Apache-2.0
Regression.ipynb
itouchz/TRepNet
ACA-Py & ACC-Py Basic Template Copy this template into the root folder of your notebook workspace to get started Imports
from aries_cloudcontroller import AriesAgentController import os from termcolor import colored
_____no_output_____
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Initialise the Agent Controller
api_key = os.getenv("ACAPY_ADMIN_API_KEY") admin_url = os.getenv("ADMIN_URL") print(f"Initialising a controller with admin api at {admin_url} and an api key of {api_key}") agent_controller = AriesAgentController(admin_url,api_key)
Initialising a controller with admin api at http://issuer-agent:3021 and an api key of adminApiKey
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Start a Webhook Server
webhook_port = int(os.getenv("WEBHOOK_PORT")) webhook_host = "0.0.0.0" await agent_controller.init_webhook_server(webhook_host, webhook_port) print(f"Listening for webhooks from agent at http://{webhook_host}:{webhook_port}")
Listening for webhooks from agent at http://0.0.0.0:3010
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Register Agent Event ListenersYou can see some examples within the webhook_listeners recipe. Copy any relevant cells across and fill in additional logic as needed.
listeners = [] ## YOUR LISTENERS HERE # Receive connection messages def connections_handler(payload): state = payload['state'] connection_id = payload["connection_id"] their_role = payload["their_role"] routing_state = payload["routing_state"] print("--------------------------------------------...
_____no_output_____
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Store Issuing Schema and Cred Def IdentifiersIf you intend for this agent to issue credentials you should first initialise your agent as an issuer and author the relevant identifiers to the public ledger. The issuer_initialisation recipe notebook can be duplicated and used as a starting point.Once schema and cred def ...
schema_id='ABsZzHjqQSfKUCEquCaAkN:2:aries_playground:0.0.1' cred_def_id='ABsZzHjqQSfKUCEquCaAkN:3:CL:9916:default' # %store <schema_id> # %store <cred_def_id>
_____no_output_____
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Load any Identifiers from StoreIf you are writing your logic across multiple notebooks, which I have found can make it easier to break things up, then rather than defining the schema and cred def identifiers every time it can be easier to load them from the jupyter store. Note: this assumes they have been written to t...
# %store -r <schema_id> # %store -r <cred_def_id>
_____no_output_____
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Establish Connection with the Holder (PORT 8889)Before you can issue a credential you must first establish a connection across which the credential will be issued to a holder. (see recipes/connection)
# Alias for invited connection alias = None auto_accept = "true" # Use public DID? public = "false" # Should this invitation be usable by multiple invitees? multi_use = "false" invitation_response = await agent_controller.connections.create_invitation(alias, auto_accept, public, multi_use) # Is equivalent to above. Ar...
---------------------------------------------------------- Connection Webhook Event Received Connection ID : 77c0b816-5c82-4d8c-a8a7-bbdbfbabe5fe State : invitation Routing State : none Their Role : invitee ----------------------------------------------------------
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Copy Invitation Object to Holder Notebook
invitation = invitation_response["invitation"] ## Copy this output print(invitation)
{'@type': 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/invitation', '@id': '0e502654-0258-4aee-93c3-386f16db826e', 'label': 'Issuer', 'serviceEndpoint': 'https://0751-86-18-68-143.ngrok.io', 'recipientKeys': ['HtSkAapeZfrzQvv66HAetE8uejEb6nPuxoUzVjSewBwL']}
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
OPTIONAL: Display Invite as QR CodeThis is useful if you wish to issue a credential to a mobile wallet.
import qrcode # Link for connection invitation invitation_url = invitation_response["invitation_url"] # Creating an instance of qrcode qr = qrcode.QRCode( version=1, box_size=5, border=5) qr.add_data(invitation_url) qr.make(fit=True) img = qr.make_image(fill='black', back_color='white') img
_____no_output_____
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Populate Credential AttributesBefore you can issue a credential, you must define the values that will be issued in this credential. The attribute names **MUST** match those in the schem identified by the value.Make sure to change all code enclosed with .
comment=input("Please enter some comment: ") credential_attributes = [ {"name": "comment", "value": comment}, ] print(credential_attributes)
Please enter some comment: Some comment
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Send CredentialThis is the easiest way to issue a credential because it automates the rest of the protocol steps. Note: The `connection_id` must be in the active state before a credential can be sent.
# Do you want the ACA-Py instance to trace it's processes (for testing/timing analysis) trace = False comment = "" # Remove credential record after issued? auto_remove = True # Change <schema_id> and <cred_def_id> to correct pair. Cred_def_id must identify a definition to which your agent has corresponding private iss...
--------------------------------------------------- Handle Issue Credential Webhook Connection ID : 6bbe8551-f056-49b4-9d12-839f67b5db5e Credential exchange ID : e321550f-3e59-4c4a-8314-b3845141142e Agent Protocol Role : issuer Protocol State : offer_sent --------------------------------------------------- Offeri...
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
Now Request a Proof of this Credential Through the Verifier Notebook (Port 8891) Terminate ControllerWhenever you have finished with this notebook, be sure to terminate the controller. This is especially important if your business logic runs across multiple notebooks.
await agent_controller.terminate()
_____no_output_____
Apache-2.0
playground/issuer/notebooks/1. issuer.ipynb
wip-abramson/aries-jupyter-playground
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
MIT
S+P_Week_4_Lesson_1.ipynb
100rab-S/Tensorflow-Developer-Certificate
try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import tensorflow as tf import numpy as np import matplotlib.pyplot as plt print(tf.__version__) def plot_series(time, series, format="-", start=0, end=None): plt.plot(time[start:end], series[start:end], format) ...
_____no_output_____
MIT
S+P_Week_4_Lesson_1.ipynb
100rab-S/Tensorflow-Developer-Certificate
Program: 08_kmeans_test.R Date: September, 2019 Programmer: Hillary Mulder Purpose: Show K means doesnt work well with harmonized trials data
library(cluster) library(caret) library(purrr) library(dplyr) library(boot) #library(table1) library(Hmisc) data=read.csv("Data/analysis_ds.csv") data$allhat=ifelse(data$study.1=='ALLHAT', 1, 0) data$aimhigh=ifelse(data$study.1=='AIMHIGH', 1, 0) data$accord=ifelse(data$study.1=='ACCORD', 1, 0) train=data[which(data$tr...
_____no_output_____
Apache-2.0
DCRI/ipynb/08_kmeans_test.ipynb
Kao-PMP/Pilot_Project
作业3:设计并训练KNN算法对图片进行分类。 example1:
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data k=7 test_num=int(input('请输入需要测试的数据数量:')) #加载TFRecord训练集的数据 reader = tf.TFRecordReader() filename_queue = tf.train.string_input_producer(["/home/srhyme/ML project/DS/train.tfrecords"]) _, example = reader.read(fil...
请输入需要测试的数据数量:300 训练集已加载完毕 测试集已加载完毕 INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.CancelledError'>, Enqueue operation was cancelled [[Node: input_producer_1/input_producer_1_EnqueueMany = QueueEnqueueManyV2[Tcomponents=[DT_STRING], timeout_ms=-1, _device="/job:localhost...
MIT
FashionMNIST Challenge/knn.ipynb
m-L-0/17b-wangshuyun-2015
example2:
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data from collections import Counter #训练集数据的引入 reader = tf.TFRecordReader() filename_queue = tf.train.string_input_producer(["/home/srhyme/ML project/DS/train.tfrecords"]) _, example = reader.read(filename_queue) fe...
请输入需要测试的数据集数量:10 正确率为 INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.CancelledError'>, Enqueue operation was cancelled [[Node: input_producer_2/input_producer_2_EnqueueMany = QueueEnqueueManyV2[Tcomponents=[DT_STRING], timeout_ms=-1, _device="/job:localhost/replica:0/ta...
MIT
FashionMNIST Challenge/knn.ipynb
m-L-0/17b-wangshuyun-2015
String OperationsEstimated time needed: **15** minutes ObjectivesAfter completing this lab you will be able to:* Work with Strings* Perform operations on String* Manipulate Strings using indexing and escape sequences Table of Contents What are Strings? Indexi...
# Use quotation marks for defining string "Michael Jackson"
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
We can also use single quotation marks:
# Use single quotation marks for defining string 'Michael Jackson'
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
A string can be a combination of spaces and digits:
# Digitals and spaces in string '1 2 3 4 5 6 '
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
A string can also be a combination of special characters :
# Special characters in string '@#2_#]&*^%$'
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
We can print our string using the print statement:
# Print the string print("hello!")
hello!
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
We can bind or assign a string to another variable:
# Assign string to variable name = "Michael Jackson" print(name)
Michael Jackson
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Indexing It is helpful to think of a string as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers: The first index can be accessed as follows: [Tip]: Because indexing starts at 0, it means the first index is on the index 0.
# Print the first element in the string print(name[0])
M
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
We can access index 6:
# Print the element on index 6 in the string print(name[6])
l
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Moreover, we can access the 13th index:
# Print the element on the 13th index in the string print(name[13])
o
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS