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 |
|---|---|---|---|---|---|
A text file containing basic information about every NLSS episode must be organized into something usable | with open(r'data\NLSS_Dockets.txt') as f:
file = f.read()
shows = file.split('\n\n') #split into every show
shows[:5] | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
This text file was taken from a webpage and so it contains links to Nick's livestream. Let's get rid of this since it's not needed. | index = 0
for s in shows:
shows[index] = s.replace(' Nick View', '')
index+=1
shows[-10:] | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Now I need to split up each show into their meaningful parts. Let's start with the games played on each episode. | games = []
for s in shows:
g = s.split('\n') #Text files has games on second line
games.append(g[1])
games | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
I'll have to clean these up later to make sure all the games are spelled consistantly. | #Number of dockets, not individual games
len(games) | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Now lets take a look at the first lines of the text file which contain the date of the show and the people who joined the show that day. They are seperated in the file by (). | date_crew = []
for s in shows:
dc = s.split('\n')[0]
date_crew.append(dc)
print(date_crew) | ['(August 24, 2017) (NL, RLS, CS, rob)', '(August 23, 2017) (NL, RLS, rob w/ Baer, LGW, HCJ)', '(August 21, 2017) (NL, RLS, JS, rob)', '(August 17, 2017) (NL w/ Sin, RLS, LGW, HCJ, Baer)', '(August 16, 2017) (NL, RLS w/ rob, Baer, LGW, Dan)', '(August 14, 2017) (NL, JS, MALF, LGW w/ Baer, HCJ)', '(August 10, 2017) (NL,... | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
I'm going to use regex to split these up. | import re
date = []
crew = []
for entry in date_crew:
foo = re.search(r'\((.*)\)', entry).group(1)
d = foo.split(r')')[0]
date.append(d)
c = foo.split(r'(')[-1]
crew.append(c) | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Now I'll start creating a data frame of this information | date_df = pd.DataFrame(date, columns = ["Date"])
date_df.head()
games_df = pd.DataFrame(games, columns = ["Docket"])
games_df.head()
crew_df = pd.DataFrame(crew, columns = ["Crew"])
crew_df.head() | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Now combine them | nlss_df = pd.DataFrame()
nlss_df['Date'] = date_df['Date']
nlss_df['Crew'] = crew_df['Crew']
nlss_df['Docket'] = games_df['Docket']
nlss_df.head()
nlss_df.describe() | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
I noticed that some lines had a link called "(continued)" in the games list. I want to get rid of these. While I'm at it, let's make the games docket contain the games as lists. | improved = []
#For each docket
for d in nlss_df['Docket']:
#Split docket into list of games
d = d.split(r',')
#For each game
for g in d:
#If game matches string to remove
if g == r" (continued)" or g == r" (Continued)":
#Remove game
d.remove(g)
improved.append... | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
I want to split on "w/" so each crew member is individual item. I'm also going to put them into a list. | improved = []
#For each cast of crew
for e in nlss_df['Crew']:
#Split cast into list of members
e = e.split(r',')
#For each member
for m in e:
#If member contains a /w
if r'w/' in m:
both = m.split(r'w/')
e.remove(m)
e.extend(both)
improved.append(... | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Strip extra spaces | fullstripped = []
for entry in improved:
stripped = []
for member in entry:
member = member.strip(' ')
stripped.append(member)
fullstripped.append(stripped)
fullstripped[:10] | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Let's make the names consistant. Luckily I know the aliases that are used. Let's see what we're working with. | names = []
for entry in fullstripped:
for user in entry:
if user not in names:
names.append(user)
print(names) | ['NL', 'RLS', 'CS', 'rob', 'LGW', 'HCJ', 'Baer', 'JS', 'Sin', 'Dan', 'MALF', 'Kory', 'TB', 'Kate', 'Blueman', 'BaerBaer', 'Mathas', 'Crendor', 'BRex', 'GhostBill', 'alpacapatrol', 'dan', '', 'Brex', 'Fox', 'Arumba', 'baer', 'cobaltstreak', 'fox', 'Mag', 'NLS', 'JS!', 'RLS in person', 'Kate in person', 'Mike Bithell', '... | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Translated: Northernlion, RockLeeSmile, CobaltStreak, AlpacaPatrol, LastGreyWolf, HCJustin, BaerTaffy, JSmithOTI, Sinvicta, DanGheesling, MALF, FlackBlag, TotalBiscuit, LovelyMomo, Blueman, BaerTaffy, MathasGames, Crendor, BananasaurusRex, NOTREAL, AlpacaPatrol, DanGheesling, BananasaurusRex, MALF, Arumba, BaerTaffy, C... | foo = "Northernlion, RockLeeSmile, CobaltStreak, AlpacaPatrol, LastGreyWolf, HCJustin, BaerTaffy, JSmithOTI, Sinvicta, DanGheesling, MALF, FlackBlag, TotalBiscuit, LovelyMomo, Blueman, BaerTaffy, MathasGames, Crendor, BananasaurusRex, NOTREAL, AlpacaPatrol, DanGheesling, NOTREAL, BananasaurusRex, MALF, Arumba, BaerTaff... | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Looking better. Let's swap it into our DF. | nlss_df['Crew'] = guests
nlss_df.head() | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Adding more stats File from https://sullygnome.com/channel/Northernlion/365/streamsThis version can only go back 365 days. Can we create a column for date that matches nlss_df format? If so, we can combine overlapping stats. I also have a larger CSV which I'm working on in FullCSV.ipynb. I will combine these once form... | import os
import glob
print(os.getcwd())
allFiles = glob.glob(r"data\*.csv")
stream_df = pd.DataFrame()
l = []
for foo in allFiles:
stream_df = pd.read_csv(foo,index_col=None, header=0)
l.append(stream_df)
stream_df = pd.concat(l)
#stream_df = pd.read_csv(r'StreamStats365.csv')
stream_df
formatted = []
order ... | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
There was a day where an extra non-NLSS stream happened. It messes up our ordering so let's remove it. | stream_df[stream_df["Date"]=='January 4, 2017']
stream_df = stream_df[stream_df['Unnamed: 0'] != 0]
stream_df[stream_df["Date"]=='January 4, 2017']
combined = nlss_df.merge(stream_df)
#drop eronious columns
combined = combined.drop('Games', 1)
combined = combined.drop('Unnamed: 0', 1)
nlss_df.head()
combined.head()
res... | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Let's Explore Our stats have been compiled. Now let's look around. Which show had most peak viewers? | mpv = nlss_df.loc[nlss_df['Peak viewers'].idxmax()]
print("Date:", mpv["Date"])
print("Peak viewers:", mpv['Peak viewers'])
print("Peak percentage:", (mpv['Peak viewers']/mpv['Views'])*100)
print("Total viewers:", mpv['Views'])
print("Games:", mpv['Docket'])
nlss_df.loc[nlss_df['Peak viewers'].idxmax()]
nlss_df.head() | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
NLSS Dataframe | len(nlss_df)
nlss_df.head()
nlss_df.tail() | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Boltzmann MachinesNotebook ini berdasarkan kursus __Deep Learning A-Z™: Hands-On Artificial Neural Networks__ di Udemy. [Lihat Kursus](https://www.udemy.com/deeplearning/). Informasi Notebook- __notebook name__: `taruma_udemy_boltzmann`- __notebook version/date__: `1.0.0`/`20190730`- __notebook server__: Google Colab-... | #### NOTEBOOK DESCRIPTION
from datetime import datetime
NOTEBOOK_TITLE = 'taruma_udemy_boltzmann'
NOTEBOOK_VERSION = '1.0.0'
NOTEBOOK_DATE = 1 # Set 1, if you want add date classifier
NOTEBOOK_NAME = "{}_{}".format(
NOTEBOOK_TITLE,
NOTEBOOK_VERSION.replace('.','_')
)
PROJECT_NAME = "{}_{}{}".format(
NOT... | _____no_output_____ | MIT | notebook/taruma_udemy_boltzmann.ipynb | taruma/hidrokit-nb |
STEP 1-5 DATA PREPROCESSING | # Importing the libraries
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
movies = pd.read_csv(DATASET_DIRECTORY + 'ml-1m/movies.dat', sep='::', header=None, engine='python', encodi... | _____no_output_____ | MIT | notebook/taruma_udemy_boltzmann.ipynb | taruma/hidrokit-nb |
STEP 6 | # Converting the ratings into binary ratings 1 (Liked) or 0 (Not Liked)
training_set[training_set == 0] = -1
training_set[training_set == 1] = 0
training_set[training_set == 2] = 0
training_set[training_set >= 3] = 1
test_set[test_set == 0] = -1
test_set[test_set == 1] = 0
test_set[test_set == 2] = 0
test_set[test_set... | _____no_output_____ | MIT | notebook/taruma_udemy_boltzmann.ipynb | taruma/hidrokit-nb |
STEP 7 - 10 Building RBM Object | # Creating the architecture of the Neural Network
# nv = number visible nodes, nh = number hidden nodes
class RBM():
def __init__(self, nv, nh):
self.W = torch.randn(nh, nv)
self.a = torch.randn(1, nh)
self.b = torch.randn(1, nv)
def sample_h(self, x):
wx = torch.mm(x, self.W.t()... | _____no_output_____ | MIT | notebook/taruma_udemy_boltzmann.ipynb | taruma/hidrokit-nb |
STEP 11 | nv = len(training_set[0])
nh = 100
batch_size = 100
rbm = RBM(nv, nh) | _____no_output_____ | MIT | notebook/taruma_udemy_boltzmann.ipynb | taruma/hidrokit-nb |
STEP 12-13 | # Training the RBM
nb_epochs = 10
for epoch in range(1, nb_epochs + 1):
train_loss = 0
s = 0.
for id_user in range(0, nb_users - batch_size, batch_size):
vk = training_set[id_user:id_user+batch_size]
v0 = training_set[id_user:id_user+batch_size]
ph0,_ = rbm.sample_h(v0)
for k... | epoch: 1 loss: tensor(0.3424)
epoch: 2 loss: tensor(0.2527)
epoch: 3 loss: tensor(0.2509)
epoch: 4 loss: tensor(0.2483)
epoch: 5 loss: tensor(0.2474)
epoch: 6 loss: tensor(0.2478)
epoch: 7 loss: tensor(0.2467)
epoch: 8 loss: tensor(0.2461)
epoch: 9 loss: tensor(0.2482)
epoch: 10 loss: tensor(0.2491)
| MIT | notebook/taruma_udemy_boltzmann.ipynb | taruma/hidrokit-nb |
STEP 14 | # Testing the RBM
test_loss = 0
s = 0.
for id_user in range(nb_users):
v = training_set[id_user:id_user+1]
vt = test_set[id_user:id_user+1]
if len(vt[vt>=0]) > 0:
_,h = rbm.sample_h(v)
_,v = rbm.sample_v(h)
test_loss += torch.mean(torch.abs(vt[vt>=0] - v[vt>=0]))
s += 1.
prin... | test loss: tensor(0.2403)
| MIT | notebook/taruma_udemy_boltzmann.ipynb | taruma/hidrokit-nb |
Volume-Weighted Moving Average (VWMA) https://www.tradingsetupsreview.com/volume-weighted-moving-average-vwma/ | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
# fix_yahoo_finance is used to fetch data
import fix_yahoo_finance as yf
yf.pdr_override()
# input
symbol = 'AAPL'
start = '2018-12-01'
end = '2019-02-01'
# Read data
df = yf.download(symbol,sta... | _____no_output_____ | MIT | Python_Stock/Technical_Indicators/Volume_Weighted_Moving_Average.ipynb | chunsj/Stock_Analysis_For_Quant |
Candlestick with VWMA | from matplotlib import dates as mdates
import datetime as dt
dfc = df.copy()
dfc['VolumePositive'] = dfc['Open'] < dfc['Adj Close']
#dfc = dfc.dropna()
dfc = dfc.reset_index()
dfc['Date'] = mdates.date2num(dfc['Date'].astype(dt.date))
dfc.head()
from mpl_finance import candlestick_ohlc
fig = plt.figure(figsize=(14,10... | _____no_output_____ | MIT | Python_Stock/Technical_Indicators/Volume_Weighted_Moving_Average.ipynb | chunsj/Stock_Analysis_For_Quant |
As a demonstration, create an ARMA22 model drawing innovations from there different distributions, a bernoulli, normal and inverse normal. Then build a keras/tensorflow model for the 1-d scattering transform to create "features", use these features to classify which model for the innovations was used. | from blusky.blusky_models import build_model_1d
import matplotlib.pylab as plt
import numpy as np
from scipy.stats import bernoulli, norm, norminvgauss
def arma22(N, alpha, beta, rnd, eps=0.5):
inov = rnd.rvs(2*N)
x = np.zeros(2*N)
# arma22 mode
for i in range(2,N*2):
x[i] = (alpha[0] * x[i-1]... | _____no_output_____ | BSD-3-Clause | notebooks/One1DExample.ipynb | enthought/sandia-blusky |
The scattering transform reduces the timeseries to a set of features, which we use for classification. The seperation between the series is more obvious looking at the log- of the features (see below). A support vector machine has an easy time classifying these processes. | base_model = build_model_1d(N, 7,6, concatenate=True)
result = base_model.predict(hodl_series)
plt.semilogy(np.mean(result[:,0,:], axis=0), '-r')
plt.semilogy(np.mean(result[8*k:16*k,0,:], axis=0), '-b')
plt.semilogy(np.mean(result[16*k:,0,:], axis=0), '-g')
from sklearn.svm import SVC
from sklearn.metrics import clas... | precision recall f1-score support
0.0 0.95 0.91 0.93 64
1.0 0.97 0.95 0.96 64
2.0 0.94 1.00 0.97 64
accuracy 0.95 192
macro avg 0.95 0.95 0.95 ... | BSD-3-Clause | notebooks/One1DExample.ipynb | enthought/sandia-blusky |
Blusky build_model_1d creates a regular old keras model, which you can use like another, think VGG16 etc. The order (order < J) defines the depth of the network. If you want a deeper network, increase this parameter. Here we attach a set of fully connected layers to classify like we did previously with the SVM.Dropping... | from tensorflow.keras import Input, Model
import tensorflow.keras.backend as K
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import BatchNormalization, Dense, Flatten, Lambda
from tensorflow.keras.utils import to_categorical
early_stopping = EarlyStopping(monitor="val_loss", patienc... | precision recall f1-score support
0.0 0.92 0.84 0.88 64
1.0 0.94 0.95 0.95 64
2.0 0.91 0.97 0.94 64
accuracy 0.92 192
macro avg 0.92 0.92 0.92 ... | BSD-3-Clause | notebooks/One1DExample.ipynb | enthought/sandia-blusky |
Apply Signature Analysis to Cell Morphology FeaturesGregory Way, 2020Here, I apply [`singscore`](https://bioconductor.org/packages/devel/bioc/vignettes/singscore/inst/doc/singscore.html) ([Foroutan et al. 2018](https://doi.org/10.1186/s12859-018-2435-4)) to our Cell Painting profiles.This notebook largely follows the ... | suppressPackageStartupMessages(library(singscore))
suppressPackageStartupMessages(library(dplyr))
suppressPackageStartupMessages(library(ggplot2))
seed <- 1234
num_permutations <- 1000
set.seed(seed) | _____no_output_____ | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Load Clone A/E (_PSMB5_ Mutations) Signature | sig_cols <- readr::cols(
feature = readr::col_character(),
estimate = readr::col_double(),
adj.p.value = readr::col_double()
)
sig_file <- file.path("results", "cloneAE_signature_tukey.tsv")
psmb_signature_scores <- readr::read_tsv(sig_file, col_types=sig_cols)
head(psmb_signature_scores, 2)
# Extract features ... | _____no_output_____ | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Load Four Clone Dataset | col_types <- readr::cols(
.default = readr::col_double(),
Metadata_Plate = readr::col_character(),
Metadata_Well = readr::col_character(),
Metadata_plate_map_name = readr::col_character(),
Metadata_clone_number = readr::col_character(),
Metadata_clone_type = readr::col_character(),
Metadata_... | _____no_output_____ | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Apply `singscore` | # Convert the four clone dataset into a feature x sample matrix without metadata
features_only_df <- t(fourclone_data_df %>% dplyr::select(!starts_with("Metadata_")))
# Apply the `rankGenes()` method to get feature rankings per feature for each sample
rankData <- rankGenes(features_only_df)
colnames(rankData) <- fourc... | [1] 300 16
| BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Perform Permutation Testing to Determine Significance of Observation | # Generate a null distribution of scores by randomly shuffling ranks
permuteResult <- generateNull(
upSet = up_features,
downSet = down_features,
rankData = rankData,
centerScore = TRUE,
knownDirection = TRUE,
B = num_permutations,
seed = seed,
useBPPARAM = NULL
)
# Calculate p values ... | Warning message:
“`as_tibble.matrix()` requires a matrix with column names or a `.name_repair` argument. Using compatibility `.name_repair`.
[90mThis warning is displayed once per session.[39m” | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Visualize Results | min_val <- quantile(as.vector(as.matrix(permuteResult)), 0.05)
max_val <- quantile(as.vector(as.matrix(permuteResult)), 0.95)
apply_psmb_signature_gg <- ggplot(full_result_df,
aes(y = TotalScore,
x = Metadata_clone_number)) +
geom_boxplot(aes(fill = Metadata_treatment), outlier.alpha = 0) +
ge... | _____no_output_____ | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Load Four Clone Signature (Generic Resistance) | sig_file <- file.path("results", "fourclone_signature_tukey.tsv")
resistance_signature_scores <- readr::read_tsv(sig_file, col_types=sig_cols)
head(resistance_signature_scores, 2)
# Extract features that are up and down in the signature
up_resistance_features <- resistance_signature_scores %>%
dplyr::filter(estima... | _____no_output_____ | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Load Clone A/E Dataset | # Do not load the feature selected data
profile_file <- file.path(profile_dir, "combined_cloneAcloneE_dataset.csv")
cloneae_cols <- readr::cols(
.default = readr::col_double(),
Metadata_CellLine = readr::col_character(),
Metadata_Plate = readr::col_character(),
Metadata_Well = readr::col_character(),
Metadat... | _____no_output_____ | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Apply `singscore` | # Convert the four clone dataset into a feature x sample matrix without metadata
features_only_res_df <- t(cloneAE_data_df %>% dplyr::select(!starts_with("Metadata_")))
# Apply the `rankGenes()` method to get feature rankings per feature for each sample
rankData_res <- rankGenes(features_only_res_df)
colnames(rankData... | [1] 72 14
| BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Perform Permutation Testing | # Generate a null distribution of scores by randomly shuffling ranks
permuteResult_res <- generateNull(
upSet = up_resistance_features,
downSet = down_resistance_features,
rankData = rankData_res,
centerScore = TRUE,
knownDirection = TRUE,
B = num_permutations,
seed = seed,
useBPPARAM =... | Warning message:
“'tidy.numeric' is deprecated.
See help("Deprecated")” | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Visualize Signature Results | min_val <- quantile(as.vector(as.matrix(permuteResult_res)), 0.05)
max_val <- quantile(as.vector(as.matrix(permuteResult_res)), 0.95)
append_dose <- function(string) paste0("Dose: ", string, "nM")
apply_res_signature_gg <- ggplot(full_res_result_df,
aes(y = TotalScore,
x = Metadata_CellLine)) +
g... | Warning message in simpleLoess(y, x, w, span, degree = degree, parametric = parametric, :
“pseudoinverse used at 0.985”Warning message in simpleLoess(y, x, w, span, degree = degree, parametric = parametric, :
“neighborhood radius 2.015”Warning message in simpleLoess(y, x, w, span, degree = degree, parametric = parametr... | BSD-3-Clause | 3.feature-differences/1.apply-signatures.ipynb | DavidStirling/profiling-resistance-mechanisms |
Generating an ROC Curve This notebook is meant to be be an introduction to generating an ROC curve for multi-class prediction problems and the code comes directly from an [Scikit-Learn demo](http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html). Please issue a comment on my Github account if you ... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from scipy import i... | _____no_output_____ | MIT | notebooks/ROC-Example.ipynb | gditzler/UA-ECE-523-Sp2018 |
In-Class Coding Lab: StringsThe goals of this lab are to help you to understand:- String slicing for substrings- How to use Python's built-in String functions in the standard library.- Tokenizing and Parsing Data- How to create user-defined functions to parse and tokenize strings Strings Strings are immutable sequence... | x = input("Enter something: ")
print ("You typed:", x)
print ("number of characters:", len(x) )
print ("First character is:", x[0])
print ("Last character is:", x[-1])
## They're sequences, so you can loop definately:
print("Printing one character at a time: ")
for ch in x:
print(ch) # print a character at a time! | Enter something: tony
You typed: tony
number of characters: 4
First character is: t
Last character is: y
Printing one character at a time:
t
o
n
y
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
Slices as substringsPython lists and sequences use **slice notation** which is a clever way to get substring from a given string.Slice notation requires two values: A start index and the end index. The substring returned starts at the start index, and *ends at the position before the end index*. It ends at the positio... | state = "Mississippi"
print (state[0:4]) # Miss
print (state[4:len(state)]) # issippi | Miss
issippi
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
In this next example, play around with the variable `split` adjusting it to how you want the string to be split up. Re run the cell several times with different values to get a feel for what happens. | state = "Mississippi"
split = 4 # TODO: play around with this number
left = state[0:split]
right = state[split:len(state)]
print(left, right)
state = "Mississippi"
split = 2 # TODO: play around with this number
left = state[0:split]
right = state[split:len(state)]
print(left, right)
state = "Mississippi"
split = 8 ... | Missi ssippi
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
Slicing from the beginning or to the endIf you omit the begin or end slice, Python will slice from the beginnning of the string or all the way to the end. So if you say `x[:5]` its the same as `x[0:5]`For example: | state = "Ohio"
print(state[0:2], state[:2]) # same!
print(state[2:len(state)], state[2:]) # same
| Oh Oh
io io
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
Now Try It!Split the string `"New Hampshire"` into two sub-strings one containing `"New"` the other containing `"Hampshire"` (without the space). | ## TODO: Write code here
state = "NewHampshire"
split = 3
left = state[0:split]
right = state[split:len(state)]
print(left, right) | New Hampshire
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
Python's built in String FunctionsPython includes several handy built-in string functions (also known as *methods* in object-oriented parlance). To get a list of available functions, use the `dir()` function on any string variable, or on the type `str` itself. | print ( dir(str)) | ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', ... | MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
Let's suppose you want to learn how to use the `count` function. There are 2 ways you can do this.1. search the web for `python 3 str count` or1. bring up internal help `help(str.count)` Both have their advantages and disadvanges. I would start with the second one, and only fall back to a web search when you can't figu... | help(str.count) | Help on method_descriptor:
count(...)
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
You'll notice in the help output it says S.count() this indicates this function is a method function. this means you invoke it like this `variable.count()`. Now Try ItTry to use the count() function method to count the number of `'i'`'s in the string `'Mississippi`: | state = 'Mississippi'
#TODO: use state.count
state.count("i")
print(state.count('i')) | 4
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
TANGENT: The Subtle difference between function and method.You'll notice sometimes we call our function alone, other times it's attached to a variable, as was the case in the example above. when we say `state.count('i')` the period (`.`) between the variable and function indicates this function is a *method function*.... | name = "Larry"
print( len(name) ) # a function call len(name) stands on its own. Gets length of 'Larry'
print( name.__len__() ) # a method call name.__len__() does the name thing for its variable 'Larry' | 5
2
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
Now Try ItTry to figure out which built in string function to use to accomplish this task.Write some code to find the text `'is'` in some text. The program shoud output the first position of `'is'` in the text. Examples:```When: text = 'Mississippi' then position = 1When: text = "This is great" then position = 2When: ... | print(dir(str))
help(str.find)
# TODO: Write your code here
text = input("Enter some text: ")
text.find('is')
print("when text =", text,"then position =",text.find('is'))
text = input("Enter some text: ")
text.find('is')
print("when text =", text,"then position =",text.find('is'))
text = input("Enter some text: ")
text... | Enter some text: fries
when text = fries then position = -1
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
Now Try It**Is that a URL?**Try to write a rudimentary URL checker. The program should input a text string and then use the `startswith` function to check if the string begins with `"http://"` or `"https://"` If it does we can assume it is a URL. | ## TODO: write code here:
url = input("Enter a URL: ")
if url.startswith('http://'):
print("We can assume this is a URL")
elif url.startswith('https://'):
print("We can assume this is a URL")
else:
print("This is not a URL")
url = input("Enter a URL: ")
if url.startswith('http://'):
print("We can assume... | Enter a URL: jfksdlfjaldskl
This is not a URL
| MIT | content/lessons/07/Class-Coding-Lab/CCL-Strings.ipynb | jvrecca-su/ist256project |
CH. 8 - Market Basket Analysis Activities Activity 8.01: Load and Prep Full Online Retail Data | import matplotlib.pyplot as plt
import mlxtend.frequent_patterns
import mlxtend.preprocessing
import numpy
import pandas
online = pandas.read_excel(
io="./Online Retail.xlsx",
sheet_name="Online Retail",
header=0
)
online['IsCPresent'] = (
online['InvoiceNo']
.astype(str)
.apply(lambda x: 1 if... | _____no_output_____ | MIT | Chapter08/Activity8.01-Activity8.03/Activity8.01-Activity8.03.ipynb | PacktWorkshops/Applied-Unsupervised-Learning-with-Python |
Activity 8.02: Apriori on the Complete Online Retail Data Set | mod_colnames_minsupport = mlxtend.frequent_patterns.apriori(
online_encoder_df,
min_support=0.01,
use_colnames=True
)
mod_colnames_minsupport.loc[0:6]
mod_colnames_minsupport[
mod_colnames_minsupport['itemsets'] == frozenset(
{'10 COLOUR SPACEBOY PEN'}
)
]
mod_colnames_minsupport['length'] ... | _____no_output_____ | MIT | Chapter08/Activity8.01-Activity8.03/Activity8.01-Activity8.03.ipynb | PacktWorkshops/Applied-Unsupervised-Learning-with-Python |
Activity 8.03: Find the Association Rules on the Complete Online Retail Data Set | rules = mlxtend.frequent_patterns.association_rules(
mod_colnames_minsupport,
metric="confidence",
min_threshold=0.6,
support_only=False
)
rules.loc[0:6]
print("Number of Associations: {}".format(rules.shape[0]))
rules.plot.scatter("support", "confidence", alpha=0.5, marker="*")
plt.xlabel("Support")... | _____no_output_____ | MIT | Chapter08/Activity8.01-Activity8.03/Activity8.01-Activity8.03.ipynb | PacktWorkshops/Applied-Unsupervised-Learning-with-Python |
Welcome to Jupyter Notebooks! Author: Shelley Knuth Date: 23 August 2019 Purpose: This is a general purpose tutorial to designed to provide basic information about Jupyter notebooks Outline1. General information about notebooks1. Formatting text in notebooks1. Formatting mathematics in notebooks1. Importing ... | __Bold__ or **bold**
_italics_ or *italics* | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Jupyter notebooks are __really__ cool! Jupyter notebooks are _really_ cool! Two spaces after text gives you a newline! Headings | # title
## major headings
### subheadings
#### 4th level subheadings | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Jupyter notebooks are really cool! Do you know what else is cool? Turtles! And Bon Jovi! CodeThe best program to use for this is the `grep` command | The best program to use for this is the `grep` command | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Text color and sizeThe sky is blue! Sometimes the color doesn't turn out WELL | The sky is <font color = blue, size = 30>blue!</font>
Sometimes the <font color = blue>color</font> doesn't turn out <font size=30> WELL</font> | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Indent or list your text> This is how!- This is how! - This is how!1. This is how! | > This is how!
- This is how!
- This is how!
1. This is how! | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
* This is also how! * This is also how! | * This is also how!
* This is also how! | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
HyperlinksSometimes copy and paste is just fine too! https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet [I'm an inline-style link](https://www.google.com)[I'm a reference-style link][Arbitrary case-insensitive reference text][I'm a relative reference to a repository file](../blob/master/LICENSE)[You ca... | [I'm an inline-style link](https://www.google.com)
[I'm a reference-style link][Arbitrary case-insensitive reference text]
[I'm a relative reference to a repository file](../blob/master/LICENSE)
[You can use numbers for reference-style link definitions][1]
Or leave it empty and use the [link text itself].
URLs and... | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Mathematical Equations in Notebooks$F=ma$This is an equation, $x=y+z$, where $y=10$ and $z=20$ | $F = ma$
This is an equation, $x=y+z$, where $y=10$ and $z=20$ | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Superscripts and Subscripts$y = x^3 + x^2 + 3x$ $F_g = m g$ | $a^2 = b^2 + c^2$
$F_g = m g$ | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Grouping$6.022\times 10^{23}$ . | $6.022\times 10^{23}$ . | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Greek Letters$\pi = 3.1415926$ $\Omega = 10$ $\delta$ | $\pi = 3.1415926$
$\Omega = 10$
$\delta$ | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Special Symbols$\pm$, $\gg$, $\ll$, $\infty$ $i = \sqrt{-1}$ $\int_a^b$ | $\pm$, $\gg$, $\ll$, $\infty$
$i = \sqrt{-1}$
$\int_a^b$ | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Fractions and DerivativesFractions $\frac{1}{2}$Derivatives $\frac{dm}{dt}$, $\frac{\partial m}{\partial t}$ | Fractions
$\frac{1}{2}$
Derivative
$\frac{dm}{dt}$
$\frac{\partial m}{\partial t}$ | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Matrices$$\begin{matrix} a & b \\ c & d \end{matrix}$$ | $$\begin{matrix} a & b \\ c & d \end{matrix}$$ | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
ExerciseWrite out an equation where the total derivative of x over y is equal to the square root of 10 added to 7/8 pi $\frac{dx}{dy} = \sqrt{10} + \pi$ Exercise Write out an equation where x sub j is equal to a 2x2 matrix containing 10, 20, 30, and 40 $x_j = \begin{matrix} 10 & 20 \\ 30 & 40 \end{matrix}$ Importing... | from IPython.display import Image
Image("bonjovi.jpg")
| _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
HTML: | <img src="bonjovi.jpg"> | _____no_output_____ | CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Basic Programming with Python Print statements | print("Hello, World!") | Hello, World!
| CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Look at how the input changed (to the left of the cell). Look at the output! (This and several cells from https://www.dataquest.io/blog/jupyter-notebook-tutorial/) Anything run in the kernal persists in the notebookCan run code and import libraries in the cells Variables in Python* Variables are not declared* Variab... | z=10.0
print('z is: ', type(z) )
x=int(43.4)
print(x) | z is: <class 'float'>
43
| CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Arithmetic in Python respects the order of operations * Addition: +* Subtraction: -* Multiplication: * * Division: / (returns float) * Floor Division: // (returns int or float; rounds down) * Mod: % (3%2 -> 1) * Exponentiation: ** 2**4 -> 16) Can concatenate strings using "+"(fro... | x='hello '+'there'
print(x) | hello there
| CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Lists Multiple Values can be grouped into a list | - lists
- basic plotting with matplotlib
- arrays and numpy; doing calculations
- plotting using numpy
- importing data from csv files
mylist=[1, 2, 10]
print(mylist) | [1, 2, 10]
| CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
* List elements accessed with [] notation* Element numbering starts at 0 | print(mylist[1]) | 2
| CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
* Lists can contain different variable types | mylist=[1, 'two', 10.0]
print(mylist) | [1, 'two', 10.0]
| CC-BY-4.0 | lessons/jupyter/general_jupyter_notebook_tutorial.ipynb | huxiaoni/espin |
Experiment DescriptionProduce PDP for a randomly picked data from cslg.> This notebook is for experiment \ and data sample \. Initialization | %load_ext autoreload
%autoreload 2
import numpy as np, sys, os
in_colab = 'google.colab' in sys.modules
# fetching code and data(if you are using colab
if in_colab:
!rm -rf s2search
!git clone --branch pipelining https://github.com/youyinnn/s2search.git
sys.path.insert(1, './s2search')
%cd s2search/pipe... | The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
| Apache-2.0 | pipelining/pdp-exp1/pdp-exp1_cslg-rand-5000_plotting.ipynb | ZeruiW/s2search |
Loading data | sys.path.insert(1, '../../')
import numpy as np, sys, os, pandas as pd
from s2search_score_pdp import pdp_based_importance, apply_order
sample_name = 'cslg-rand-5000'
f_list = ['title', 'abstract', 'venue', 'authors', 'year', 'n_citations']
pdp_xy = {}
pdp_metric = pd.DataFrame(columns=['feature_name', 'pdp_range', ... | feature_name pdp_range pdp_importance
1 abstract 17.129012 6.155994
0 title 15.760054 3.788171
2 venue 12.542338 0.971027
4 year 2.190717 0.470416
5 n_citations 0.977882 0.193581
3 authors 0.000000 0.000000
| Apache-2.0 | pipelining/pdp-exp1/pdp-exp1_cslg-rand-5000_plotting.ipynb | ZeruiW/s2search |
PDP | import matplotlib.pyplot as plt
categorical_plot_conf = [
{
'xlabel': 'Title',
'ylabel': 'Scores',
'pdp_xy': pdp_xy['title']
},
{
'xlabel': 'Abstract',
'pdp_xy': pdp_xy['abstract']
},
{
'xlabel': 'Authors',
'pdp_xy': pdp_xy['authors']
... | _____no_output_____ | Apache-2.0 | pipelining/pdp-exp1/pdp-exp1_cslg-rand-5000_plotting.ipynb | ZeruiW/s2search |
Alzhippo Pr0gress Possible Tasks- **Visualizing fibers** passing through ERC and hippo, for both ipsi and contra cxns (4-figs) (GK)- **Dilate hippocampal parcellations**, to cover entire hippocampus by nearest neighbour (JV)- **Voxelwise ERC-to-hippocampal** projections + clustering (Both) Visulaizating fibers1. Plot... | import numpy as np
import networkx as nx
import nibabel as nib
import scipy.stats as stats
import matplotlib.pyplot as plt
from nilearn import plotting
import os
import seaborn as sns
import pandas
%matplotlib notebook
def matrixplotter(data, log=True, title="Connectivity between ERC and Hippocampus"):
plotdat = n... | _____no_output_____ | MIT | code/visualizing_tracts.ipynb | gkiar/alzhippo |
2. Find representative subject | tmp = np.reshape(avg.T, (355, 36))
tmp[0]
corrs = np.corrcoef(tmp)[-1]
corrs[corrs == 1] = 0
bestfit = int(np.where(corrs == np.max(corrs))[0])
print("Most similar graph: {}".format(bestfit))
dsets = ['../data/graphs/BNU1/combined_erc_hippo_labels/',
'../data/graphs/BNU3/',
'../data/graphs/HNU1/']
fil... | _____no_output_____ | MIT | code/visualizing_tracts.ipynb | gkiar/alzhippo |
Optimization> Marcos Duarte > Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/)) > Federal University of ABC, Brazil If there occur some changes in nature, the amount of action necessary for this change must be as small as possible. Maupertuis (sec XVIII) **Optimization is the p... | # import Python libraries
import numpy as np
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import sympy as sym
from sympy.plotting import plot
import pandas as pd
from IPython.display import display
from IPython.core.display import Math | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Example 1: Maximum volume of a cardboard boxWe want to make a box from a square cardboard with side $a$ such that its volume should be maximum. What is the optimal distance where the square cardboard should be cut and folded to make a box with maximum volume? Figure. A box to be made from a cardboard such that its vo... | a, b = sym.symbols('a b')
V = b*(a - 2*b)*(a - 2*b)
Vdiff = sym.expand(sym.diff(V, b))
roots = sym.solve(Vdiff, b)
display(Math(sym.latex('Roots:') + sym.latex(roots)))
roots | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Discarding the solution $b=\dfrac{a}{2}$ (where $V=0$, which is a minimum), $b=\dfrac{a}{6}$ results in the maximum volume. We can check that by plotting the volume of the cardboard box for $a=1$ and $b: [0,\:0.5]$: | plot(V.subs({a: 1}), (b, 0, .5), xlabel='b', ylabel='V')
display(Math(sym.latex('V_{a=1}^{max}(b=%s)=%s'
%(roots[0].evalf(n=4, subs={a: 1}), V.evalf(n=3, subs={a: 1, b: roots[0]}))))) | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
- Note that although the problem above is a case of nonlinear constrained optimization, because the objective function is univariate, well-conditioned and the constraints are linear inequalities, the optimization is simple. Unfortunately, this is seldom the case. Curve fitting as an optimization problemCurve fitting ... | from IPython.display import YouTubeVideo
YouTubeVideo('Rxp7o7_RxII', width=480, height=360, rel=0) | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Gradient descentGradient descent is a first-order iterative optimization algorithm for finding the minimum of a function ([Wikipedia](https://en.wikipedia.org/wiki/Gradient_descent)). In the gradient descent algorithm, a local minimum of a function is found starting from an initial point and taking steps proportional... | # From https://en.wikipedia.org/wiki/Gradient_descent
# The local minimum of $f(x)=x^4-3x^3+2$ is at x=9/4
cur_x = 6 # The algorithm starts at x=6
gamma = 0.01 # step size multiplier
precision = 0.00001
step_size = 1 # initial step size
max_iters = 10000 # maximum number of ite... | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Multivariate optimization When there is more than one design variable (the cost function depends on more than one variable), it's a multivariate optimization. The general idea of finding minimum and maximum values where the derivatives are zero still holds for a multivariate function. The second derivative of a multiv... | # time elbow_flexion BIClong BICshort BRA
r_ef = np.loadtxt('./../data/r_elbowflexors.mot', skiprows=7)
f_ef = np.loadtxt('./../data/f_elbowflexors.mot', skiprows=7) | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
The maximum isometric force of these muscles are defined in the arm26 model as: Biceps long head: 624.3 N, Biceps short head: 435.56 N, and Brachialis: 987.26 N. Let's compute the mamimum torques that each muscle could produce considering a static situation at the different elbow flexion angles: | m_ef = r_ef*1
m_ef[:, 2:] = r_ef[:, 2:]*f_ef[:, 2:] | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
And let's visualize these data: | labels = ['Biceps long head', 'Biceps short head', 'Brachialis']
fig, ax = plt.subplots(nrows=1, ncols=3, sharex=True, figsize=(10, 4))
ax[0].plot(r_ef[:, 1], r_ef[:, 2:])
#ax[0].set_xlabel('Elbow angle $(\,^o)$')
ax[0].set_title('Moment arm (m)')
ax[1].plot(f_ef[:, 1], f_ef[:, 2:])
ax[1].set_xlabel('Elbow angle $(\,^o... | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
These data don't have the *pcsa* value of each muscle. We will estimate the *pcsa* considering that the amount of maximum muscle force generated per area is constant and equal to 50N/cm$^2$. Consequently, the *pcsa* (in cm$^2$) for each muscle is: | a_ef = np.array([624.3, 435.56, 987.26])/50 # 50 N/cm2
print(a_ef) | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Static versus dynamic optimizationIn the context of biomechanics, we can solve the distribution problem separately for each angle (instant) of the elbow; we will refer to that as static optimization. However, there is no guarantee that when we analyze all these solutions across the range of angles, they will be the be... | from scipy.optimize import minimize
def cf_f1(x):
"""Cost function: sum of forces."""
return x[0] + x[1] + x[2]
def cf_f2(x):
"""Cost function: sum of forces squared."""
return x[0]**2 + x[1]**2 + x[2]**2
def cf_fpcsa2(x, a):
"""Cost function: sum of squared muscle stresses."""
return (x[0]/... | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Let's also define the Jacobian for each cost function (which is an optional parameter for the optimization): | def cf_f1d(x):
"""Derivative of cost function: sum of forces."""
dfdx0 = 1
dfdx1 = 1
dfdx2 = 1
return np.array([dfdx0, dfdx1, dfdx2])
def cf_f2d(x):
"""Derivative of cost function: sum of forces squared."""
dfdx0 = 2*x[0]
dfdx1 = 2*x[1]
dfdx2 = 2*x[2]
return np.array([dfdx0, dfd... | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Let's define initial values: | M = 20 # desired torque at the elbow
iang = 69 # which will give the closest value to 90 degrees
r = r_ef[iang, 2:]
f0 = f_ef[iang, 2:]
a = a_ef
m = m_ef[iang, 2:]
x0 = f_ef[iang, 2:]/10 # far from the correct answer for the sum of torques
print('M =', M)
print('x0 =', x0)
print('r * x0 =', np.sum(r*x0)) | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Inequality constraints (such as boundaries in our problem) can be entered with the parameter `bounds` to the `minimize` function: | bnds = ((0, f0[0]), (0, f0[1]), (0, f0[2])) | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Equality constraints (such as the sum of torques should equals the desired torque in our problem), as well as inequality constraints, can be entered with the parameter `constraints` to the `minimize` function (and we can also opt to enter the Jacobian of these constraints): | # use this in combination with the parameter bounds:
cons = ({'type': 'eq',
'fun' : lambda x, r, f0, M: np.array([r[0]*x[0] + r[1]*x[1] + r[2]*x[2] - M]),
'jac' : lambda x, r, f0, M: np.array([r[0], r[1], r[2]]), 'args': (r, f0, M)})
# to enter everything as constraints:
cons = ({'type': 'eq',
... | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Although more verbose, if all the Jacobians of the constraints are also informed, this alternative seems better than informing bounds for the optimization process (less error in the final result and less iterations). Given the characteristics of the problem, if we use the function `minimize` we are limited to the SLSQ... | f1r = minimize(fun=cf_f1, x0=x0, args=(), jac=cf_f1d,
constraints=cons, method='SLSQP',
options={'disp': True})
f2r = minimize(fun=cf_f2, x0=x0, args=(), jac=cf_f2d,
constraints=cons, method='SLSQP',
options={'disp': True})
fpcsa2r = minimize(fun=cf_fpcsa2, x0... | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
Let's compare the results for the different cost functions: | dat = np.vstack((np.around(r*100,1), np.around(a,1), np.around(f0,0), np.around(m,1)))
opt = np.around(np.vstack((f1r.x, f2r.x, fpcsa2r.x, fmmax3r.x)), 1)
er = ['-', '-', '-', '-',
np.sum(r*f1r.x)-M, np.sum(r*f2r.x)-M, np.sum(r*fpcsa2r.x)-M, np.sum(r*fmmax3r.x)-M]
data = np.vstack((np.vstack((dat, opt)).T, er)).T... | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_DuringLecture18/BMC-master/notebooks/Optimization.ipynb | raissabthibes/bmc |
______Copyright Pierian DataFor more information, visit us at www.pieriandata.com Pandas Data Visualization ExercisesThis is just a quick exercise to review the various plots we showed earlier. Use df3.csv to replicate the following plots.IMPORTANT NOTE! Make sure you don't run the cells directly above the example out... | # RUN THIS CELL
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
df3 = pd.read_csv('df3.csv')
print(len(df3))
print(df3.head()) | 500
weekday produced defective
0 1.Monday 73 7
1 2.Tuesday 75 10
2 3.Wednesday 86 7
3 4.Thursday 64 7
4 5.Friday 70 6
| MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.